Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

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от 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

  1. Read package.json and node_modules/ai/package.json for 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.
  2. The ai package ships its own docs for the exact installed version in node_modules/ai/docs/ (MDX). When unsure about an option, grep there before guessing: grep -rn "toolsContext" node_modules/ai/docs/.
  3. Run the project's type check (npx tsc --noEmit) after every change. In 7.x it reports parameters, maxSteps, maxTokens, experimental_context, toolCall.args and usage.promptTokens as errors. It does not catch the two worst runtime problems: system messages inside messages, and reading result.response.messages after 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: text is the final text, but toolCalls, toolResults, content, files, sources, warnings, usage and responseMessages accumulate across every step. In v5/v6, toolCalls, toolResults and usage were final-step only.
  • Final step only: result.finalStep.* (finishReason, toolCalls, usage, response, providerMetadata, reasoningText). The top-level response, request, reasoning* and providerMetadata are deprecated aliases of the final step.
  • Per step: result.steps[i], where step.response.messages is 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 }
Полный SKILL.md на GitHub

Установить tools-and-structured-output в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

metadata.json

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), без исполняемых скриптов.

Похожие скиллы

Сравнить tools-and-structured-output с