tools-and-structured-output
БесплатноБез исполняемых скриптовНе проверенWrites and fixes Vercel AI SDK (npm package `ai`, version 7) code for tool calling, multi-step tool loops, agents and structured output, and tests it with the…
от majiayu000★ 31 звезда на GitHubОб этом скилле
AI SDK 7: tools, loops and structured output
Checked against [email protected] (October 2026) with [email protected]. AI SDK 7 is ESM-only and needs Node 22+.
Most AI SDK mistakes do not throw. Old option names from v4-v6 are silently ignored, so the code "works" with a real model and quietly does less: the loop stops after one step, the model never sees the tool's schema, the token cap is not applied, persisted history loses the tool calls. Treat everything below as rules, and prove the behaviour with a mock-model test before calling it done.
First, find out what is installed
- Read
package.jsonandnode_modules/ai/package.jsonfor the real version. Everything here is for 7.x. If the project is on 5 or 6, see the migration table for what differs, and do not "upgrade" APIs the installed version does not have. - The
aipackage ships its own docs for the exact installed version innode_modules/ai/docs/(MDX). When unsure about an option, grep there before guessing:grep -rn "toolsContext" node_modules/ai/docs/. - Run the project's type check (
npx tsc --noEmit) after every change. In 7.x it reportsparameters,maxSteps,maxTokens,experimental_context,toolCall.argsandusage.promptTokensas errors. It does not catch the two worst runtime problems: system messages insidemessages, and readingresult.response.messagesafter a multi-step run.
The rules that silently break
| Write this (7.x) | Not this | What the old form does in 7.0.159 |
|---|---|---|
tool({ inputSchema: z.object(...) }) |
parameters: |
Ignored. The model receives an empty { properties: {} } schema and input is not validated. |
stopWhen: isStepCount(n) on generateText/streamText |
maxSteps: n, or nothing |
Ignored. Default is one step: the tool runs, then the call returns with text === ''. |
maxOutputTokens: n |
maxTokens: n |
Ignored. No cap is sent to the provider. |
instructions: '...' |
{ role: 'system' } inside messages/prompt |
Throws InvalidPromptError ("System messages are not allowed..."). system: still works as a deprecated alias. |
result.responseMessages to persist a turn |
result.response.messages |
Holds only the final step's messages; earlier tool calls and results are dropped. |
per-request closure, or contextSchema + toolsContext |
experimental_context |
Not passed. The tool's context is undefined, so experimental_context.accountId throws inside the tool. |
output: Output.object({ schema }), read result.output |
experimental_output |
Removed: ignored, no JSON response format is requested, result.experimental_output is undefined. |
toolCall.input, toolResult.output |
.args, .result |
undefined. |
usage.inputTokens, usage.outputTokens |
promptTokens, completionTokens |
undefined. |
Deprecated in 7.x but still working (fine to leave, prefer the new name in new code):
stepCountIs (alias of isStepCount), system (use instructions), generateObject/streamObject
(use generateText/streamText with output), totalUsage (use usage), fullStream (use
stream), onFinish/onStepFinish (use onEnd/onStepEnd), needsApproval on a tool (use
toolApproval on the call), Experimental_Agent (alias of ToolLoopAgent).
Result shapes changed in 7.0: whole run vs final step
On a generateText result (and awaited streamText promises):
- Whole run, all steps:
textis the final text, buttoolCalls,toolResults,content,files,sources,warnings,usageandresponseMessagesaccumulate across every step. In v5/v6,toolCalls,toolResultsandusagewere final-step only. - Final step only:
result.finalStep.*(finishReason,toolCalls,usage,response,providerMetadata,reasoningText). The top-levelresponse,request,reasoning*andproviderMetadataare deprecated aliases of the final step. - Per step:
result.steps[i], wherestep.response.messagesis that step's messages only.
Did the loop end without an answer? The step limit was hit while the model still wanted tools when
result.finalStep.finishReason === 'tool-calls' (and result.text is empty). Handle that case
explicitly; never return an empty string to a user.
Tools
import { generateText, isStepCount, tool, type LanguageModel } from 'ai'
import { z } from 'zod'
export function flightTools(board: DepartureBoard, accountId: string) {
return {
getFlightStatus: tool({
description: 'Gate and departure time of a flight on one of the traveller\'s bookings.',
inputSchema: z.object({
flightNumber: z.string().regex(/^[A-Z0-9]{2}\d{1,4}$/).describe('IATA flight number, e.g. TP1351'),
}),
execute: async ({ flightNumber }) => {
const flight = await board.lookup(accountId, flightNumber)
if (!flight) return { known: false, flightNumber }
Установить tools-and-structured-output в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл tools-and-structured-output?
Writes and fixes Vercel AI SDK (npm package `ai`, version 7) code for tool calling, multi-step tool loops, agents and structured output, and tests it with the SDK's mock models. Use when code imports from 'ai' or 'ai/test' and calls generateText, streamText, tool(), ToolLoopAgent, Output.object, generateObject, stopWhen/isStepCount, or MockLanguageModelV4; when adding tools or an agent loop to a chatbot; when extracting typed JSON from an LLM; when persisting chat history with tool calls; or when upgrading from AI SDK 4, 5 or 6 (parameters, maxSteps, maxTokens, experimental_context, response.messages, system messages).
Как установить скилл tools-and-structured-output?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл tools-and-structured-output запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic