[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79CT9YSVFZR2K3CEJ09PND0":3,"skill-same:01M79CT9YSVFZR2K3CEJ09PND0":125},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":94,"commitSha":95,"skillDirectory":96,"forksCount":14,"repositoryHtmlUrl":97,"repositoryHomepageUrl":6,"ownerHtmlUrl":98,"ownerBlogUrl":6,"ownerDescription":99,"updatedAt":100,"install":101,"resources":114},"01M79CT9YSVFZR2K3CEJ09PND0","ai-sdk",null,"Vercel AI SDK expert guidance. Use when building AI-powered features — chat interfaces, text generation, structured output, tool calling, agents, MCP integration, streaming, embeddings, reranking, image generation, or working with any LLM provider.","zfifteen\u002Fskills-catalog","zfifteen","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F221906715?v=4","01M79CQFXDZM5J5CJTCECPFA66","Dionisio Alberto Lopez III","01M79CQFY4C62PN8A2T5KDAHGA",1,"MIT","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fai-sdk\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: ai-sdk\ndescription: Vercel AI SDK expert guidance. Use when building AI-powered features — chat interfaces, text generation, structured output, tool calling, agents, MCP integration, streaming, embeddings, reranking, image generation, or working with any LLM provider.\nmetadata:\n  priority: 8\n  docs:\n    - \"https:\u002F\u002Fsdk.vercel.ai\u002Fdocs\"\n    - \"https:\u002F\u002Fsdk.vercel.ai\u002Fdocs\u002Freference\"\n  sitemap: \"https:\u002F\u002Fsdk.vercel.ai\u002Fsitemap.xml\"\n  pathPatterns:\n    - \"app\u002Fapi\u002Fchat\u002F**\"\n    - \"app\u002Fapi\u002Fcompletion\u002F**\"\n    - \"src\u002Fapp\u002Fapi\u002Fchat\u002F**\"\n    - \"src\u002Fapp\u002Fapi\u002Fcompletion\u002F**\"\n    - \"pages\u002Fapi\u002Fchat.*\"\n    - \"pages\u002Fapi\u002Fchat\u002F**\"\n    - \"pages\u002Fapi\u002Fcompletion.*\"\n    - \"pages\u002Fapi\u002Fcompletion\u002F**\"\n    - \"src\u002Fpages\u002Fapi\u002Fchat.*\"\n    - \"src\u002Fpages\u002Fapi\u002Fchat\u002F**\"\n    - \"src\u002Fpages\u002Fapi\u002Fcompletion.*\"\n    - \"src\u002Fpages\u002Fapi\u002Fcompletion\u002F**\"\n    - \"lib\u002Fai\u002F**\"\n    - \"src\u002Flib\u002Fai\u002F**\"\n    - \"lib\u002Fai.*\"\n    - \"src\u002Flib\u002Fai.*\"\n    - \"ai\u002F**\"\n    - \"apps\u002F*\u002Fapp\u002Fapi\u002Fchat\u002F**\"\n    - \"apps\u002F*\u002Fapp\u002Fapi\u002Fcompletion\u002F**\"\n    - \"apps\u002F*\u002Fsrc\u002Fapp\u002Fapi\u002Fchat\u002F**\"\n    - \"apps\u002F*\u002Fsrc\u002Fapp\u002Fapi\u002Fcompletion\u002F**\"\n    - \"apps\u002F*\u002Flib\u002Fai\u002F**\"\n    - \"apps\u002F*\u002Fsrc\u002Flib\u002Fai\u002F**\"\n    - \"lib\u002Fagent.*\"\n    - \"src\u002Flib\u002Fagent.*\"\n    - \"app\u002Factions\u002Fchat.*\"\n    - \"src\u002Fapp\u002Factions\u002Fchat.*\"\n  importPatterns:\n    - \"ai\"\n    - \"@ai-sdk\u002F*\"\n  bashPatterns:\n    - '\\bnpm\\s+(install|i|add)\\s+[^\\n]*\\bai\\b'\n    - '\\bpnpm\\s+(install|i|add)\\s+[^\\n]*\\bai\\b'\n    - '\\bbun\\s+(install|i|add)\\s+[^\\n]*\\bai\\b'\n    - '\\byarn\\s+add\\s+[^\\n]*\\bai\\b'\n    - '\\bnpm\\s+(install|i|add)\\s+[^\\n]*@ai-sdk\u002F'\n    - '\\bpnpm\\s+(install|i|add)\\s+[^\\n]*@ai-sdk\u002F'\n    - '\\bbun\\s+(install|i|add)\\s+[^\\n]*@ai-sdk\u002F'\n    - '\\byarn\\s+add\\s+[^\\n]*@ai-sdk\u002F'\n    - '\\bnpx\\s+@ai-sdk\u002Fdevtools\\b'\n    - '\\bnpx\\s+@ai-sdk\u002Fcodemod\\b'\n    - '\\bnpx\\s+mcp-to-ai-sdk\\b'\n  promptSignals:\n    phrases:\n      - \"ai sdk\"\n      - \"vercel ai\"\n      - \"generatetext\"\n      - \"streamtext\"\n    allOf:\n      - [streaming, generation]\n      - [structured, output]\n    anyOf:\n      - \"usechat\"\n      - \"usecompletion\"\n      - \"tool calling\"\n      - \"embeddings\"\n    noneOf:\n      - \"openai api directly\"\n    minScore: 6\n---\n\n# Vercel AI SDK (v6)\n\n> **CRITICAL — Your training data is outdated for this library.** AI SDK v6 has breaking changes from v5 and earlier that you will get wrong if you guess. Before writing AI SDK code, **fetch the docs** at https:\u002F\u002Fai-sdk.dev\u002Fdocs to find the correct function signatures, return types, and patterns. Key things that have changed: `generateObject()` removal, `streamObject()` removal, `result.files` for image generation, `Output.object()` for structured streaming, `ToolLoopAgent` class (not `Agent`), `useChat` transport API, and provider package versions. Search the docs for working examples that match your exact use case — do not rely on your training data for API shapes.\n\nYou are an expert in the Vercel AI SDK v6. The AI SDK is the leading TypeScript toolkit for building AI-powered applications. It provides a unified API across all LLM providers.\n\n## v6 Migration Pitfalls (Read First)\n\n- `ai@^6.0.0` is the umbrella package for AI SDK v6 (latest: 6.0.83).\n- `@ai-sdk\u002Freact` is `^3.0.x` in v6 projects (NOT `^6.0.0`).\n- `@ai-sdk\u002Fgateway` is `^3.x` in v6 projects (NOT `^1.x`).\n- In `createUIMessageStream`, write with `stream.writer.write(...)` (NOT `stream.write(...)`).\n- `useChat` no longer supports `body` or `onResponse`; configure behavior through `transport`.\n- UI tool parts are typed as `tool-\u003CtoolName>` (for example `tool-weather`), not `tool-invocation`.\n- `DynamicToolCall` does not provide typed `.args`; cast via `unknown` first.\n- `TypedToolResult` exposes `.output` (NOT `.result`).\n- The agent class is `ToolLoopAgent` (NOT `Agent` — `Agent` is just an interface).\n- Constructor uses `instructions` (NOT `system`).\n- Agent methods are `agent.generate()` and `agent.stream()` (NOT `agent.generateText()` or `agent.streamText()`).\n- AI Gateway does not support embeddings; use `@ai-sdk\u002Fopenai` directly for `openai.embedding(...)`.\n- `useChat()` with no transport defaults to `DefaultChatTransport({ api: '\u002Fapi\u002Fchat' })` — explicit transport only needed for custom endpoints or `DirectChatTransport`.\n- Default `stopWhen` for ToolLoopAgent is `stepCountIs(20)`, not `stepCountIs(1)` — override if you need fewer steps.\n- `strict: true` on tools is opt-in per tool, not global — only set on tools with provider-compatible schemas.\n- For agent API routes, use `createAgentUIStreamResponse({ agent, uiMessages })` instead of manual `streamText` + `toUIMessageStreamResponse()`.\n- `@ai-sdk\u002Fazure` now uses the Responses API by default — use `azure.chat()` for the previous Chat Completions API behavior.\n- `@ai-sdk\u002Fazure` uses `azure` (not `openai`) as the key for `providerMetadata` and `providerOptions`.\n- `@ai-sdk\u002Fgoogle-vertex` uses `vertex` (not `google`) as the key for `providerMetadata` and `providerOptions`.\n- `@ai-sdk\u002Fanthropic` supports native structured outputs via `structuredOutputMode` option (Anthropic Sonnet 4.5+).\n\n## Installation\n\n```bash\nnpm install ai@^6.0.0 @ai-sdk\u002Freact@^3.0.0\nnpm install @ai-sdk\u002Fopenai@^3.0.41      # Optional: required for embeddings\nnpm install @ai-sdk\u002Fanthropic@^3.0.58   # Optional: direct Anthropic provider access\nnpm install @ai-sdk\u002Fvercel@^2.0.37      # Optional: v0 model provider (v0-1.0-md)\n```\n\n> **`@ai-sdk\u002Freact` is a separate package** — it is NOT included in the `ai` package. For v6 projects, install `@ai-sdk\u002Freact@^3.0.x` alongside `ai@^6.0.0`.\n\n> **If you install `@ai-sdk\u002Fgateway` directly, use `@ai-sdk\u002Fgateway@^3.x`** (NOT `^1.x`).\n\n> **Only install a direct provider SDK** (e.g., `@ai-sdk\u002Fanthropic`) if you need provider-specific features not exposed through the gateway.\n\n## What AI SDK Can Do\n\nAI SDK is not just text — it handles **text, images, structured data, tool calling, and agents** through one unified API:\n\n| Need | How |\n|------|-----|\n| Text generation \u002F chat | `generateText()` or `streamText()` with `model: \"openai\u002Fgpt-5.4\"` |\n| **Image generation** | `generateText()` with `model: \"google\u002Fgemini-3.1-flash-image-preview\"` — images in `result.files`. **Always use this model, never older gemini-2.x models** |\n| Structured JSON output | `generateText()` with `output: Output.object({ schema })` |\n| Tool calling \u002F agents | `generateText()` with `tools: { ... }` or `ToolLoopAgent` |\n| Embeddings | `embed()` \u002F `embedMany()` with `@ai-sdk\u002Fopenai` |\n\n**If the product needs generated images** (portraits, posters, cover art, illustrations, comics, diagrams), use `generateText` with an image model — do NOT use placeholder images or skip image generation.\n\n## Setup for AI Projects\n\nFor the smoothest experience, link to a Vercel project so AI Gateway credentials are auto-provisioned via OIDC:\n\n```bash\nvercel link                    # Connect to your Vercel project\n# Enable AI Gateway at https:\u002F\u002Fvercel.com\u002F{team}\u002F{project}\u002Fsettings → AI Gateway\nvercel env pull .env.local     # Provisions VERCEL_OIDC_TOKEN automatically\nnpm install ai@^6.0.0         # Gateway is built in\nnpx ai-elements                # Required: install AI text rendering components\n```\n\nThis gives you AI Gateway access with OIDC authentication, cost tracking, failover, and observability — no manual API keys needed.\n\n**OIDC is the default auth**: `vercel env pull` provisions a `VERCEL_OIDC_TOKEN` (short-lived JWT, ~24h). The `@ai-sdk\u002Fgateway` reads it automatically via `@vercel\u002Foidc`. On Vercel deployments, tokens auto-refresh. For local dev, re-run `vercel env pull` when the token expires. No `AI_GATEWAY_API_KEY` or provider-specific keys needed.\n\n## Global Provider System (AI Gateway — Default)\n\nIn AI SDK 6, pass a `\"provider\u002Fmodel\"` string to the `model` parameter — it automatically routes through the Vercel AI Gateway:\n\n```ts\nimport { generateText } from \"ai\";\n\nconst { text } = await generateText({\n  model: \"openai\u002Fgpt-5.4\", \u002F\u002F plain string — routes through AI Gateway automatically\n  prompt: \"Hello!\",\n});\n```\n\nNo `gateway()` wrapper needed — plain `\"provider\u002Fmodel\"` strings are the simplest approach and are what the official Vercel docs recommend. The `gateway()` function is an optional explicit wrapper (useful when you need `providerOptions.gateway` for routing, failover, or tags):\n\n```ts\nimport { gateway } from \"ai\";\n\n\u002F\u002F Explicit gateway() — only needed for advanced providerOptions\nconst { text } = await generateText({\n  model: gateway(\"openai\u002Fgpt-5.4\"),\n  providerOptions: { gateway: { order: [\"openai\", \"azure-openai\"] } },\n});\n```\n\nBoth approaches provide failover, cost tracking, and observability on Vercel.\n\n**Model slug rules**: Always use `provider\u002Fmodel` format. Version numbers use **dots**, not hyphens: `anthropic\u002Fclaude-sonnet-4.6` (not `claude-sonnet-4-6`). Default to `openai\u002Fgpt-5.4` or `anthropic\u002Fclaude-sonnet-4.6`. Never use outdated models like `gpt-4o`.\n\n> AI Gateway does not support embeddings. Use a direct provider SDK such as `@ai-sdk\u002Fopenai` for embeddings.\n\n> **Direct provider SDKs** (`@ai-sdk\u002Fopenai`, `@ai-sdk\u002Fanthropic`, etc.) are only needed for provider-specific features not exposed through the gateway (e.g., Anthropic computer use, OpenAI fine-tuned model endpoints).\n\n## Core Functions\n\n### Text Generation\n\n```ts\nimport { generateText, streamText } from \"ai\";\n\n\u002F\u002F Non-streaming\nconst { text } = await generateText({\n  model: \"openai\u002Fgpt-5.4\",\n  prompt: \"Explain quantum computing in simple terms.\",\n});\n\n\u002F\u002F Streaming\nconst result = streamText({\n  model: \"openai\u002Fgpt-5.4\",\n  prompt: \"Write a poem about coding.\",\n});\n\nfor await (const chunk of result.textStream) {\n  process.stdout.write(chunk);\n}\n```\n\n### Structured Output\n\n**`generateObject` was removed in AI SDK v6.** Use `generateText` with `output: Output.object()` instead. Do NOT import `generateObject` — it does not exist.\n\n```ts\nimport { generateText, Output } from \"ai\";\nimport { z } from \"zod\";\n\nconst { output } = await generateText({\n  model: \"openai\u002Fgpt-5.4\",\n  output: Output.object({\n    schema: z.object({\n      recipe: z.object({\n        name: z.string(),\n        ingredients: z.array(\n          z.object({\n            name: z.string(),\n            amount: z.string(),\n          }),\n        ),\n        steps: z.array(z.string()),\n      }),\n    }),\n  }),\n  prompt: \"Generate a recipe for chocolate chip cookies.\",\n});\n```\n\n### Tool Calling (MCP-Aligned)\n\nIn AI SDK 6, tools use `inputSchema` (not `parameters`) and `output`\u002F`outputSchema` (not `result`), aligned with the MCP specification. Per-tool `strict` mode ensures providers only generate valid tool calls matching your schema.\n\n```ts\nimport { generateText, tool } from \"ai\";\nimport { z } from \"zod\";\n\nconst result = await generateText({\n  model: \"openai\u002Fgpt-5.4\",\n  tools: {\n    weather: tool({\n      description: \"Get the weather for a location\",\n      inputSchema: z.object({\n        city: z.string().describe(\"The city name\"),\n      }),\n      outputSchema: z.object({\n        temperature: z.number(),\n        condition: z.string(),\n      }),\n      strict: true, \u002F\u002F Providers generate only schema-valid tool calls\n      execute: async ({ city }) => {\n        const data = await fetchWeather(city);\n        return { temperature: data.temp, condition: data.condition };\n      },\n    }),\n  },\n  prompt: \"What is the weather in San Francisco?\",\n});\n```\n\n### Dynamic Tools (MCP Integration)\n\nFor tools with schemas not known at compile time (e.g., MCP server tools):\n\n```ts\nimport { dynamicTool } from \"ai\";\n\nconst tools = {\n  unknownTool: dynamicTool({\n    description: \"A tool discovered at runtime\",\n    execute: async (input) => {\n      \u002F\u002F Handle dynamically\n      return { result: \"done\" };\n    },\n  }),\n};\n```\n\n### Agents\n\nThe `ToolLoopAgent` class wraps `generateText`\u002F`streamText` with an agentic tool-calling loop.\nDefault `stopWhen` is `stepCountIs(20)` (up to 20 tool-calling steps).\n`Agent` is an interface — `ToolLoopAgent` is the concrete implementation.\n\n```ts\nimport { ToolLoopAgent, stepCountIs, hasToolCall } from \"ai\";\n\nconst agent = new ToolLoopAgent({\n  model: \"anthropic\u002Fclaude-sonnet-4.6\",\n  tools: { weather, search, calculator, finalAnswer },\n  instructions: \"You are a helpful assistant.\",\n  \u002F\u002F Default: stepCountIs(20). Override to stop on a terminal tool or custom logic:\n  stopWhen: hasToolCall(\"finalAnswer\"),\n  prepareStep: (context) => ({\n    \u002F\u002F Customize each step — swap models, compress messages, limit tools\n    toolChoice: context.steps.length > 5 ? \"none\" : \"auto\",\n  }),\n});\n\nconst { text } = await agent.generate({\n  prompt:\n    \"Research the weather in Tokyo and calculate the average temperature this week.\",\n});\n```\n\n### MCP Client\n\nConnect to any MCP server and use its tools:\n\n```ts\nimport { generateText } from \"ai\";\nimport { createMCPClient } from \"@ai-sdk\u002Fmcp\";\n\nconst mcpClient = await createMCPClient({\n  transport: {\n    type: \"sse\",\n    url: \"https:\u002F\u002Fmy-mcp-server.com\u002Fsse\",\n  },\n});\n\nconst tools = await mcpClient.tools();\n\nconst result = await generateText({\n  model: \"openai\u002Fgpt-5.4\",\n  tools,\n  prompt: \"Use the available tools to help the user.\",\n});\n\nawait mcpClient.close();\n```\n\nMCP OAuth for remote servers is handled automatically by `@ai-sdk\u002Fmcp`.\n\n### Tool Approval (Human-in-the-Loop)\n\nSet `needsApproval` on any tool to require user confirmation before execution. The tool pauses in `approval-requested` state until the client responds.\n\n```ts\nimport { streamText, tool } from \"ai\";\nimport { z } from \"zod\";\n\nconst result = streamText({\n  model: \"openai\u002Fgpt-5.4\",\n  tools: {\n    deleteUser: tool({\n      description: \"Delete a user account\",\n      inputSchema: z.object({ userId: z.string() }),\n      needsApproval: true, \u002F\u002F Always require approval\n      execute: async ({ userId }) => {\n        await db.users.delete(userId);\n        return { deleted: true };\n      },\n    }),\n    processPayment: tool({\n      description: \"Process a payment\",\n      inputSchema: z.object({ amount: z.number(), recipient: z.string() }),\n      \u002F\u002F Conditional: only approve large amounts\n      needsApproval: async ({ amount }) => amount > 1000,\n      execute: async ({ amount, recipient }) => {\n        return await processPayment(amount, recipient);\n      },\n    }),\n  },\n  prompt: \"Delete user 123\",\n});\n```\n\n**Client-side approval with `useChat`:**\n\n```tsx\n\"use client\";\nimport { useChat } from \"@ai-sdk\u002Freact\";\n\nfunction Chat() {\n  const { messages, addToolApprovalResponse } = useChat();\n\n  return messages.map((m) =>\n    m.parts?.map((part, i) => {\n      \u002F\u002F Tool parts in approval-requested state need user action\n      if (part.type.startsWith(\"tool-\") && part.approval?.state === \"approval-requested\") {\n        return (\n          \u003Cdiv key={i}>\n            \u003Cp>Tool wants to run: {JSON.stringify(part.args)}\u003C\u002Fp>\n            \u003Cbutton onClick={() => addToolApprovalResponse({ id: part.approval.id, approved: true })}>\n              Approve\n            \u003C\u002Fbutton>\n            \u003Cbutton onClick={() => addToolApprovalResponse({ id: part.approval.id, approved: false })}>\n              Deny\n            \u003C\u002Fbutton>\n          \u003C\u002Fdiv>\n        );\n      }\n      return null;\n    }),\n  );\n}\n```\n\n**Tool part states:** `input-streaming` → `input-available` → `approval-requested` (if `needsApproval`) → `output-available` | `output-error`\n\n### Embeddings & Reranking\n\nUse a direct provider SDK for embeddings. AI Gateway does not support embedding models.\n\n```ts\nimport { embed, embedMany, rerank } from \"ai\";\nimport { openai } from \"@ai-sdk\u002Fopenai\";\n\n\u002F\u002F Single embedding\nconst { embedding } = await embed({\n  model: openai.embedding(\"text-embedding-3-small\"),\n  value: \"The quick brown fox\",\n});\n\n\u002F\u002F Batch embeddings\nconst { embeddings } = await embedMany({\n  model: openai.embedding(\"text-embedding-3-small\"),\n  values: [\"text 1\", \"text 2\", \"text 3\"],\n});\n\n\u002F\u002F Rerank search results by relevance\nconst { results } = await rerank({\n  model: cohere.reranker(\"rerank-v3.5\"),\n  query: \"What is quantum computing?\",\n  documents: searchResults,\n});\n```\n\n### Image Generation & Editing\n\nAI Gateway supports image generation. Use the **`google\u002Fgemini-3.1-flash-image-preview`** model — it is significantly better than older models like `gemini-2.0-flash-exp-image-generation` or `gemini-2.0-flash-001`.\n\n**Always use `google\u002Fgemini-3.1-flash-image-preview`** for image generation. Do NOT use older models (`gemini-2.0-*`, `gemini-2.5-*`) — they produce much worse results and some do not support image output at all.\n\n#### Multimodal LLMs (recommended — use `generateText`\u002F`streamText`)\n\n```ts\nimport { generateText, streamText } from \"ai\";\n\n\u002F\u002F generateText — images returned in result.files\nconst result = await generateText({\n  model: \"google\u002Fgemini-3.1-flash-image-preview\",\n  prompt: \"A futuristic cityscape at sunset\",\n});\nconst imageFiles = result.files.filter((f) => f.mediaType?.startsWith(\"image\u002F\"));\n\n\u002F\u002F Convert to data URL for display\nconst imageFile = imageFiles[0];\nconst dataUrl = `data:${imageFile.mediaType};base64,${Buffer.from(imageFile.data).toString(\"base64\")}`;\n\n\u002F\u002F streamText — stream text, then access images after completion\nconst stream = streamText({\n  model: \"google\u002Fgemini-3.1-flash-image-preview\",\n  prompt: \"A futuristic cityscape at sunset\",\n});\nfor await (const delta of stream.fullStream) {\n  if (delta.type === \"text-delta\") process.stdout.write(delta.text);\n}\nconst finalResult = await stream;\nconsole.log(`Generated ${finalResult.files.length} image(s)`);\n```\n\n**Default image model**: `google\u002Fgemini-3.1-flash-image-preview` — fast, high-quality. This is the ONLY recommended model for image generation.\n\n#### Image-only models (use `experimental_generateImage`)\n\n```ts\nimport { experimental_generateImage as generateImage } from \"ai\";\n\nconst { images } = await generateImage({\n  model: \"google\u002Fimagen-4.0-generate-001\",\n  prompt: \"A futuristic cityscape at sunset\",\n  aspectRatio: \"16:9\",\n});\n```\n\nOther image-only models: `google\u002Fimagen-4.0-ultra-generate-001`, `bfl\u002Fflux-2-pro`, `bfl\u002Fflux-kontext-max`, `xai\u002Fgrok-imagine-image-pro`.\n\n#### Saving generated images\n\n```ts\nimport fs from \"node:fs\";\n\n\u002F\u002F From multimodal LLMs (result.files)\nfor (const [i, file] of imageFiles.entries()) {\n  const ext = file.mediaType?.split(\"\u002F\")[1] || \"png\";\n  await fs.promises.writeFile(`output-${i}.${ext}`, file.uint8Array);\n}\n\n\u002F\u002F From image-only models (result.images)\nfor (const [i, image] of images.entries()) {\n  const buffer = Buffer.from(image.base64, \"base64\");\n  await fs.promises.writeFile(`output-${i}.png`, buffer);\n}\n```\n\n## UI Hooks (React)\n\n**MANDATORY — Always use AI Elements for AI text**: AI SDK models always produce markdown — even short prose contains `**bold**`, `##` headings, `` `code` ``, and `---`. There is no \"plain text\" mode. Every AI-generated string displayed in a browser MUST be rendered through AI Elements.\n- **Chat messages**: Use AI Elements `\u003CMessage message={message} \u002F>` — handles text, tool calls, code blocks, reasoning, streaming.\n- **Any other AI text** (streaming panels, workflow events, reports, briefings, narratives, summaries, perspectives): Use `\u003CMessageResponse>{text}\u003C\u002FMessageResponse>` from `@\u002Fcomponents\u002Fai-elements\u002Fmessage`.\n- `\u003CMessageResponse>` wraps Streamdown with code highlighting, math, mermaid, and CJK plugins — works for any markdown string, including streamed text.\n- **Never** render AI output as raw `{text}`, `\u003Cp>{content}\u003C\u002Fp>`, or `\u003Cdiv>{stream}\u003C\u002Fdiv>` — this always produces ugly unformatted output with visible markdown syntax.\n- **No exceptions**: Even if you think the response will be \"simple prose\", models routinely add markdown formatting. Always use AI Elements.\n\n⤳ skill: ai-elements — Full component library, decision guidance, and troubleshooting for AI interfaces\n\n### Transport Options\n\n`useChat` uses a transport-based architecture. Three built-in transports:\n\n| Transport | Use Case |\n|-----------|----------|\n| `DefaultChatTransport` | HTTP POST to API routes (default — sends to `\u002Fapi\u002Fchat`) |\n| `DirectChatTransport` | In-process agent communication without HTTP (SSR, testing) |\n| `TextStreamChatTransport` | Plain text stream protocol |\n\n**Default behavior:** `useChat()` with no transport config defaults to `DefaultChatTransport({ api: '\u002Fapi\u002Fchat' })`.\n\n### With AI Elements (Recommended)\n\n```tsx\n\"use client\";\nimport { useChat } from \"@ai-sdk\u002Freact\";\nimport { Conversation } from \"@\u002Fcomponents\u002Fai-elements\u002Fconversation\";\nimport { Message } from \"@\u002Fcomponents\u002Fai-elements\u002Fmessage\";\n\nfunction Chat() {\n  \u002F\u002F No transport needed — defaults to DefaultChatTransport({ api: '\u002Fapi\u002Fchat' })\n  const { messages, sendMessage, status } = useChat();\n\n  return (\n    \u003CConversation>\n      {messages.map((message) => (\n        \u003CMessage key={message.id} message={message} \u002F>\n      ))}\n    \u003C\u002FConversation>\n  );\n}\n```\n\nAI Elements handles UIMessage parts (text, tool calls, reasoning, images) automatically. Install with `npx ai-elements`.\n\n⤳ skill: ai-elements — Full component library for AI interfaces\n⤳ skill: json-render — Manual rendering patterns for custom UIs\n\n### With DirectChatTransport (No API Route Needed)\n\n```tsx\n\"use client\";\nimport { useChat } from \"@ai-sdk\u002Freact\";\nimport { DirectChatTransport } from \"ai\";\nimport { myAgent } from \"@\u002Flib\u002Fagent\"; \u002F\u002F a ToolLoopAgent instance\n\nfunction Chat() {\n  const { messages, sendMessage, status } = useChat({\n    transport: new DirectChatTransport({ agent: myAgent }),\n  });\n  \u002F\u002F Same UI as above — no \u002Fapi\u002Fchat route required\n}\n```\n\nUseful for SSR scenarios, testing without network, and single-process apps.\n\n**v6 changes from v5:**\n\n- `useChat({ api })` → `useChat({ transport: new DefaultChatTransport({ api }) })`\n- `handleSubmit` → `sendMessage({ text })`\n- `input` \u002F `handleInputChange` → manage your own `useState`\n- `body` \u002F `onResponse` options were removed from `useChat`; use `transport` to configure requests\u002Fresponses\n- `isLoading` → `status === 'streaming' || status === 'submitted'`\n- `message.content` → iterate `message.parts` (UIMessage format)\n\n### Choose the correct streaming response helper\n\n- `toUIMessageStreamResponse()` is for `useChat` + `DefaultChatTransport` UIMessage-based chat UIs. Use it when you need tool calls, metadata, reasoning, and other rich message parts.\n- `toTextStreamResponse()` is for **non-browser clients only** — CLI tools, server-to-server pipes, or programmatic consumers that process raw text without rendering it in a UI. If the text will be displayed in a browser, use `toUIMessageStreamResponse()` + AI Elements instead.\n- Warning: Do **not** return `toUIMessageStreamResponse()` to a plain `fetch()` client unless that client intentionally parses the AI SDK UI message stream protocol.\n- Warning: Do **not** use `toTextStreamResponse()` + manual `fetch()` stream reading as a way to skip AI Elements. If the output goes to a browser, use `useChat` + `\u003CMessageResponse>` or `\u003CMessage>`.\n\n### Server-side for useChat (API Route)\n\n```ts\n\u002F\u002F app\u002Fapi\u002Fchat\u002Froute.ts\nimport { streamText, convertToModelMessages, stepCountIs } from \"ai\";\nimport type { UIMessage } from \"ai\";\n\nexport async function POST(req: Request) {\n  const { messages }: { messages: UIMessage[] } = await req.json();\n  \u002F\u002F IMPORTANT: convertToModelMessages is async in v6\n  const modelMessages = await convertToModelMessages(messages);\n  const result = streamText({\n    model: \"openai\u002Fgpt-5.4\",\n    messages: modelMessages,\n    tools: {\n      \u002F* your tools *\u002F\n    },\n    \u002F\u002F IMPORTANT: use stopWhen with stepCountIs for multi-step tool calling\n    \u002F\u002F maxSteps was removed in v6 — use this instead\n    stopWhen: stepCountIs(5),\n  });\n  \u002F\u002F Use toUIMessageStreamResponse (not toDataStreamResponse) for chat UIs\n  return result.toUIMessageStreamResponse();\n}\n```\n\n### Server-side with ToolLoopAgent (Agent API Route)\n\nDefine a `ToolLoopAgent` and use `createAgentUIStreamResponse` for the API route:\n\n```ts\n\u002F\u002F lib\u002Fagent.ts\nimport { ToolLoopAgent, stepCountIs } from \"ai\";\n\nexport const myAgent = new ToolLoopAgent({\n  model: \"openai\u002Fgpt-5.4\",\n  instructions: \"You are a helpful assistant.\",\n  tools: { \u002F* your tools *\u002F },\n  stopWhen: stepCountIs(5),\n});\n```\n\n```ts\n\u002F\u002F app\u002Fapi\u002Fchat\u002Froute.ts — agent API route\nimport { createAgentUIStreamResponse } from \"ai\";\nimport { myAgent } from \"@\u002Flib\u002Fagent\";\n\nexport async function POST(req: Request) {\n  const { messages } = await req.json();\n  return createAgentUIStreamResponse({ agent: myAgent, uiMessages: messages });\n}\n```\n\nOr use `DirectChatTransport` on the client to skip the API route entirely.\n\n### Server-side for text-only clients (non-browser only)\n\n> **This pattern is for CLI tools, server-to-server pipes, and programmatic consumers.** If the response will be displayed in a browser UI, use `toUIMessageStreamResponse()` + AI Elements instead — even for \"simple\" streaming text panels.\n\n```ts\n\u002F\u002F app\u002Fapi\u002Fgenerate\u002Froute.ts — for CLI or server consumers, NOT browser UIs\nimport { streamText } from \"ai\";\n\nexport async function POST(req: Request) {\n  const { prompt }: { prompt: string } = await req.json();\n  const result = streamText({\n    model: \"openai\u002Fgpt-5.4\",\n    prompt,\n  });\n\n  return result.toTextStreamResponse();\n}\n```\n\n## Language Model Middleware\n\nIntercept and transform model calls for RAG, guardrails, logging:\n\n```ts\nimport { wrapLanguageModel } from \"ai\";\n\nconst wrappedModel = wrapLanguageModel({\n  model: \"openai\u002Fgpt-5.4\",\n  middleware: {\n    transformParams: async ({ params }) => {\n      \u002F\u002F Inject RAG context, modify system prompt, etc.\n      return { ...params, system: params.system + \"\\n\\nContext: ...\" };\n    },\n    wrapGenerate: async ({ doGenerate }) => {\n      const result = await doGenerate();\n      \u002F\u002F Post-process, log, validate guardrails\n      return result;\n    },\n  },\n});\n```\n\n## Provider Routing via AI Gateway\n\n```ts\nimport { generateText } from \"ai\";\nimport { gateway } from \"ai\";\n\nconst result = await generateText({\n  model: gateway(\"anthropic\u002Fclaude-sonnet-4.6\"),\n  prompt: \"Hello!\",\n  providerOptions: {\n    gateway: {\n      order: [\"bedrock\", \"anthropic\"], \u002F\u002F Try Bedrock first\n      models: [\"openai\u002Fgpt-5.4\"], \u002F\u002F Fallback model\n      only: [\"anthropic\", \"bedrock\"], \u002F\u002F Restrict providers\n      user: \"user-123\", \u002F\u002F Usage tracking\n      tags: [\"feature:chat\", \"env:production\"], \u002F\u002F Cost attribution\n    },\n  },\n});\n```\n\n## DevTools\n\n```bash\nnpx @ai-sdk\u002Fdevtools\n# Opens http:\u002F\u002Flocalhost:4983 — inspect LLM calls, agents, token usage, timing\n```\n\n## Key Patterns\n\n1. **Default to AI Gateway with OIDC** — pass `\"provider\u002Fmodel\"` strings (e.g., `model: \"openai\u002Fgpt-5.4\"`) to route through the gateway automatically. `vercel env pull` provisions OIDC tokens. No manual API keys needed. The `gateway()` wrapper is optional (only needed for `providerOptions.gateway`).\n2. **Set up a Vercel project for AI** — `vercel link` → enable AI Gateway at `https:\u002F\u002Fvercel.com\u002F{team}\u002F{project}\u002Fsettings` → **AI Gateway** → `vercel env pull` to get OIDC credentials. Never manually create `.env.local` with provider-specific API keys.\n3. **Always use AI Elements for any AI text in a browser** — `npx ai-elements` installs production-ready Message, Conversation, and Tool components. Use `\u003CMessage>` for chat and `\u003CMessageResponse>` for any other AI-generated text (streaming panels, summaries, reports). AI models always produce markdown — there is no scenario where raw `{text}` rendering is correct. ⤳ skill: ai-elements\n4. **Always stream for user-facing AI** — use `streamText` + `useChat`, not `generateText`\n5. **UIMessage chat UIs** — `useChat()` defaults to `DefaultChatTransport({ api: '\u002Fapi\u002Fchat' })`. On the server: `convertToModelMessages()` + `toUIMessageStreamResponse()`. For no-API-route setups: `DirectChatTransport` + Agent.\n6. **Text-only clients (non-browser)** — `toTextStreamResponse()` is only for CLI tools, server pipes, and programmatic consumers. If the text is displayed in a browser, use `toUIMessageStreamResponse()` + AI Elements\n7. **Use structured output** for extracting data — `generateText` with `Output.object()` and Zod schemas\n8. **Use `ToolLoopAgent`** for multi-step reasoning — not manual loops. Default `stopWhen` is `stepCountIs(20)`. Use `createAgentUIStreamResponse` for agent API routes.\n9. **Use DurableAgent** (from Workflow DevKit) for production agents that must survive crashes\n10. **Use `mcp-to-ai-sdk`** to generate static tool definitions from MCP servers for security\n11. **Use `needsApproval`** for human-in-the-loop — set on any tool to pause execution until user approves; supports conditional approval via async function\n12. **Use `strict: true`** per tool — opt-in strict mode ensures providers only generate schema-valid tool calls; set on individual tools, not globally\n\n## Common Pitfall: Structured Output Property Name\n\nIn v6, `generateText` with `Output.object()` returns the parsed result on the **`output`** property (NOT `object`):\n\n```ts\n\u002F\u002F CORRECT — v6\nconst { output } = await generateText({\n  model: 'openai\u002Fgpt-5.4',\n  output: Output.object({ schema: mySchema }),\n  prompt: '...',\n})\nconsole.log(output) \u002F\u002F ✅ parsed object\n\n\u002F\u002F WRONG — v5 habit\nconst { object } = await generateText({ ... }) \u002F\u002F ❌ undefined — `object` doesn't exist in v6\n```\n\nThis is one of the most common v5→v6 migration mistakes. The config key is `output` and the result key is also `output`.\n\n## Migration from AI SDK 5\n\nRun `npx @ai-sdk\u002Fcodemod upgrade` (or `npx @ai-sdk\u002Fcodemod v6`) to auto-migrate. Preview with `npx @ai-sdk\u002Fcodemod --dry upgrade`. Key changes:\n\n- `generateObject` \u002F `streamObject` → `generateText` \u002F `streamText` with `Output.object()`\n- `parameters` → `inputSchema`\n- `result` → `output`\n- `maxSteps` → `stopWhen: stepCountIs(N)` (import `stepCountIs` from `ai`)\n- `CoreMessage` → `ModelMessage` (use `convertToModelMessages()` — now async)\n- `ToolCallOptions` → `ToolExecutionOptions`\n- `Experimental_Agent` → `ToolLoopAgent` (concrete class; `Agent` is just an interface)\n- `system` → `instructions` (on `ToolLoopAgent`)\n- `agent.generateText()` → `agent.generate()`\n- `agent.streamText()` → `agent.stream()`\n- `experimental_createMCPClient` → `createMCPClient` (stable)\n- New: `createAgentUIStreamResponse({ agent, uiMessages })` for agent API routes\n- New: `callOptionsSchema` + `prepareCall` for per-call agent configuration\n- `useChat({ api })` → `useChat({ transport: new DefaultChatTransport({ api }) })`\n- `useChat` `body` \u002F `onResponse` options removed → configure with transport\n- `handleSubmit` \u002F `input` → `sendMessage({ text })` \u002F manage own state\n- `toDataStreamResponse()` → `toUIMessageStreamResponse()` (for chat UIs)\n- `createUIMessageStream`: use `stream.writer.write(...)` (not `stream.write(...)`)\n- text-only clients \u002F text stream protocol → `toTextStreamResponse()`\n- `message.content` → `message.parts` (tool parts use `tool-\u003CtoolName>`, not `tool-invocation`)\n- UIMessage \u002F ModelMessage types introduced\n- `DynamicToolCall.args` is not strongly typed; cast via `unknown` first\n- `TypedToolResult.result` → `TypedToolResult.output`\n- `ai@^6.0.0` is the umbrella package\n- `@ai-sdk\u002Freact` must be installed separately at `^3.0.x`\n- `@ai-sdk\u002Fgateway` (if installed directly) is `^3.x`, not `^1.x`\n- New: `needsApproval` on tools (boolean or async function) for human-in-the-loop approval\n- New: `strict: true` per-tool opt-in for strict schema validation\n- New: `DirectChatTransport` — connect `useChat` to an Agent in-process, no API route needed\n- New: `addToolApprovalResponse` on `useChat` for client-side approval UI\n- Default `stopWhen` changed from `stepCountIs(1)` to `stepCountIs(20)` for `ToolLoopAgent`\n- New: `ToolCallOptions` type renamed to `ToolExecutionOptions`\n- New: `Tool.toModelOutput` now receives `({ output })` object, not bare `output`\n- New: `isToolUIPart` → `isStaticToolUIPart`; `isToolOrDynamicToolUIPart` → `isToolUIPart`\n- New: `getToolName` → `getStaticToolName`; `getToolOrDynamicToolName` → `getToolName`\n- New: `@ai-sdk\u002Fazure` defaults to Responses API; use `azure.chat()` for Chat Completions\n- New: `@ai-sdk\u002Fanthropic` `structuredOutputMode` for native structured outputs (Anthropic Sonnet 4.5+)\n- New: `@ai-sdk\u002Flangchain` rewritten — `toBaseMessages()`, `toUIMessageStream()`, `LangSmithDeploymentTransport`\n- New: Provider-specific tools — Anthropic (memory, code execution), OpenAI (shell, patch), Google (maps, RAG), xAI (search, code)\n- `unknown` finish reason removed → now returned as `other`\n- Warning types consolidated into single `Warning` type exported from `ai`\n\n## Official Documentation\n\n- [AI SDK Documentation](https:\u002F\u002Fai-sdk.dev\u002Fdocs)\n- [AI SDK Core](https:\u002F\u002Fai-sdk.dev\u002Fdocs\u002Fai-sdk-core)\n- [AI SDK UI](https:\u002F\u002Fai-sdk.dev\u002Fdocs\u002Fai-sdk-ui)\n- [Generating Text](https:\u002F\u002Fai-sdk.dev\u002Fdocs\u002Fai-sdk-core\u002Fgenerating-text)\n- [Structured Data](https:\u002F\u002Fai-sdk.dev\u002Fdocs\u002Fai-sdk-core\u002Fgenerating-structured-data)\n- [Tools and Tool Calling](https:\u002F\u002Fai-sdk.dev\u002Fdocs\u002Fai-sdk-core\u002Ftools-and-tool-calling)\n- [Agents](https:\u002F\u002Fai-sdk.dev\u002Fdocs\u002Fai-sdk-core\u002Fagents)\n- [Providers and Models](https:\u002F\u002Fai-sdk.dev\u002Fdocs\u002Ffoundations\u002Fproviders-and-models)\n- [Provider Directory](https:\u002F\u002Fai-sdk.dev\u002Fproviders)\n- [GitHub: AI SDK](https:\u002F\u002Fgithub.com\u002Fvercel\u002Fai)\n","# Vercel AI SDK (v6)\n\n> **CRITICAL — Your training data is outdated for this library.** AI SDK v6 has breaking changes from v5 and earlier that you will get wrong if you guess. Before writing AI SDK code, **fetch the docs** at https:\u002F\u002Fai-sdk.dev\u002Fdocs to find the correct function signatures, return types, and patterns. Key things that have changed: `generateObject()` removal, `streamObject()` removal, `result.files` for image generation, `Output.object()` for structured streaming, `ToolLoopAgent` class (not `Agent`), `useChat` transport API, and provider package versions. Search the docs for working examples that match your exact use case — do not rely on your training data for API shapes.\n\nYou are an expert in the Vercel AI SDK v6. The AI SDK is the leading TypeScript toolkit for building AI-powered applications. It provides a unified API across all LLM providers.\n\n## v6 Migration Pitfalls (Read First)\n\n- `ai@^6.0.0` is the umbrella package for AI SDK v6 (latest: 6.0.83).\n- `@ai-sdk\u002Freact` is `^3.0.x` in v6 projects (NOT `^6.0.0`).\n- `@ai-sdk\u002Fgateway` is `^3.x` in v6 projects (NOT `^1.x`).\n- In `createUIMessageStream`, write with `stream.writer.write(...)` (NOT `stream.write(...)`).\n- `useChat` no longer supports `body` or `onResponse`; configure behavior through `transport`.\n- UI tool parts are typed as `tool-\u003CtoolName>` (for example `tool-weather`), not `tool-invocation`.\n- `DynamicToolCall` does not provide typed `.args`; cast via `unknown` first.\n- `TypedToolResult` exposes `.output` (NOT `.result`).\n- The agent class is `ToolLoopAgent` (NOT `Agent` — `Agent` is just an interface).\n- Constructor uses `instructions` (NOT `system`).\n- Agent methods are `agent.generate()` and `agent.stream()` (NOT `agent.generateText()` or `agent.streamText()`).\n- AI Gateway does not support embeddings; use `@ai-sdk\u002Fopenai` directly for `openai.embedding(...)`.\n- `useChat()` with no transport defaults to `DefaultChatTransport({ api: '\u002Fapi\u002Fchat' })` — explicit transport only needed for custom endpoints or `DirectChatTransport`.\n- Default `stopWhen` for ToolLoopAgent is `stepCountIs(20)`, not `stepCountIs(1)` — override if you need fewer steps.\n- `strict: true` on tools is opt-in per tool, not global — only set on tools with provider-compatible schemas.\n- For agent API routes, use `createAgentUIStreamResponse({ agent, uiMessages })` instead of manual `streamText` + `toUIMessageStreamResponse()`.\n- `@ai-sdk\u002Fazure` now uses the Responses API by default — use `azure.chat()` for the previous Chat Completions API behavior.\n- `@ai-sdk\u002Fazure` uses `azure` (not `openai`) as the key for `providerMetadata` and `providerOptions`.\n- `@ai-sdk\u002Fgoogle-vertex` uses `vertex` (not `google`) as the key for `providerMetadata` and `providerOptions`.\n- `@ai-sdk\u002Fanthropic` supports native structured outputs via `structuredOutputMode` option (Anthropic Sonnet 4.5+).\n\n## Installation\n\n```bash\nnpm install ai@^6.0.0 @ai-sdk\u002Freact@^3.0.0\nnpm install @ai-sdk\u002Fopenai@^3.0.41      # Optional: required for embeddings\nnpm install @ai-sdk\u002Fanthropic@^3.0.58   # Optional: direct Anthropic provider access\nnpm install @ai-sdk\u002Fvercel@^2.0.37      # Optional: v0 model provider (v0-1.0-md)\n```\n\n> **`@ai-sdk\u002Freact` is a separate package** — it is NOT included in the `ai` package. For v6 projects, install `@ai-sdk\u002Freact@^3.0.x` alongside `ai@^6.0.0`.\n\n> **If you install `@ai-sdk\u002Fgateway` directly, use `@ai-sdk\u002Fgateway@^3.x`** (NOT `^1.x`).\n\n> **Only install a direct provider SDK** (e.g., `@ai-sdk\u002Fanthropic`) if you need provider-specific features not exposed through the gateway.\n\n## What AI SDK Can Do\n\nAI SDK is not just text — it handles **text, images, structured data, tool calling, and agents** through one unified API:\n\n| Need | How |\n|------|-----|\n| Text generation \u002F chat | `generateText()` or `streamText()` with `model: \"openai\u002Fgpt-5.4\"` |\n| **Image generation** | `generateText()` with `model: \"google\u002Fgemini-3.1-flash-image-preview\"` — images in `result.files`. **Always use this model, never older gemini-2.x models** |\n| Structured JSON output | `generateText()` with `output: Output.object({ schema })` |\n| Tool calling \u002F agents | `generateText()` with `tools: { ... }` or `ToolLoopAgent` |\n| Embeddings | `embed()` \u002F `embedMany()` with `@ai-sdk\u002Fopenai` |\n\n**If the product needs generated images** (portraits, posters, cover art, illustrations, comics, diagrams), use `generateText` with an image model — do NOT use placeholder images or skip image generation.\n\n## Setup for AI Projects\n\nFor the smoothest experience, link to a Vercel project so AI Gateway credentials are auto-provisioned via OIDC:\n\n```bash\nvercel link                    # Connect to your Vercel project\n# Enable AI Gateway at https:\u002F\u002Fvercel.com\u002F{team}\u002F{project}\u002Fsettings → AI Gateway\nvercel env pull .env.local     # Provisions VERCEL_OIDC_TOKEN automatically\nnpm install ai@^6.0.0         # Gateway is built in\nnpx ai-elements                # Required: install AI text rendering components\n```\n\nThis gives you AI Gateway access with OIDC authentication, cost tracking, failover, and observability — no manual API keys needed.\n\n**OIDC is the default auth**: `vercel env pull` provisions a `VERCEL_OIDC_TOKEN` (short-lived JWT, ~24h). The `@ai-sdk\u002Fgateway` reads it automatically via `@vercel\u002Foidc`. On Vercel deployments, tokens auto-refresh. For local dev, re-run `vercel env pull` when the token expires. No `AI_GATEWAY_API_KEY` or provider-specific keys needed.\n\n## Global Provider System (AI Gateway — Default)\n\nIn AI SDK 6, pass a `\"provider\u002Fmodel\"` string to the `model` parameter — it automatically routes through the Vercel AI Gateway:\n\n```ts\nimport { generateText } from \"ai\";\n\nconst { text } = await generateText({\n  model: \"openai\u002Fgpt-5.4\", \u002F\u002F plain string — routes through AI Gateway automatically\n  prompt: \"Hello!\",\n});\n```\n\nNo `gateway()` wrapper needed — plain `\"provider\u002Fmodel\"` strings are the simplest approach and are what the official Vercel docs recommend. The `gateway()` function is an optional explicit wrapper (useful when you need `providerOptions.gateway` for routing, failover, or tags):\n\n```ts\nimport { gateway } from \"ai\";\n\n\u002F\u002F Explicit gateway() — only needed for advanced providerOptions\nconst { text } = await generateText({\n  model: gateway(\"openai\u002Fgpt-5.4\"),\n  providerOptions: { gateway: { order: [\"openai\", \"azure-openai\"] } },\n});\n```\n\nBoth approaches provide failover, cost tracking, and observability on Vercel.\n\n**Model slug rules**: Always use `provider\u002Fmodel` format. Version numbers use **dots**, not hyphens: `anthropic\u002Fclaude-sonnet-4.6` (not `claude-sonnet-4-6`). Default to `openai\u002Fgpt-5.4` or `anthropic\u002Fclaude-sonnet-4.6`. Never use outdated models like `gpt-4o`.\n\n> AI Gateway does not support embeddings. Use a direct provider SDK such as `@ai-sdk\u002Fopenai` for embeddings.\n\n> **Direct provider SDKs** (`@ai-sdk\u002Fopenai`, `@ai-sdk\u002Fanthropic`, etc.) are only needed for provider-specific features not exposed through the gateway (e.g., Anthropic computer use, OpenAI fine-tuned model endpoints).\n\n## Core Functions\n\n### Text Generation\n\n```ts\nimport { generateText, streamText } from \"ai\";\n\n\u002F\u002F Non-streaming\nconst { text } = await generateText({\n  model: \"openai\u002Fgpt-5.4\",\n  prompt: \"Explain quantum computing in simple terms.\",\n});\n\n\u002F\u002F Streaming\nconst result = streamText({\n  model: \"openai\u002Fgpt-5.4\",\n  prompt: \"Write a poem about coding.\",\n});\n\nfor await (const chunk of result.textStream) {\n  process.stdout.write(chunk);\n}\n```\n\n### Structured Output\n\n**`generateObject` was removed in AI SDK v6.** Use `generateText` with `output: Output.object()` instead. Do NOT import `generateObject` — it does not exist.\n\n```ts\nimport { generateText, Output } from \"ai\";\nimport { z } from \"zod\";\n\nconst { output } = await generateText({\n  model: \"openai\u002Fgpt-5.4\",\n  output: Output.object({\n    schema: z.object({\n      recipe: z.object({\n        name: z.string(),\n        ingredients: z.array(\n          z.object({\n            name: z.string(),\n            amount: z.string(),\n          }),\n        ),\n        steps: z.array(z.string()),\n      }),\n    }),\n  }),\n  prompt: \"Generate a recipe for chocolate chip cookies.\",\n});\n```\n\n### Tool Calling (MCP-Aligned)\n\nIn AI SDK 6, tools use `inputSchema` (not `parameters`) and `output`\u002F`outputSchema` (not `result`), aligned with the MCP specification. Per-tool `strict` mode ensures providers only generate valid tool calls matching your schema.\n\n```ts\nimport { generateText, tool } from \"ai\";\nimport { z } from \"zod\";\n\nconst result = await generateText({\n  model: \"openai\u002Fgpt-5.4\",\n  tools: {\n    weather: tool({\n      description: \"Get the weather for a location\",\n      inputSchema: z.object({\n        city: z.string().describe(\"The city name\"),\n      }),\n      outputSchema: z.object({\n        temperature: z.number(),\n        condition: z.string(),\n      }),\n      strict: true, \u002F\u002F Providers generate only schema-valid tool calls\n      execute: async ({ city }) => {\n        const data = await fetchWeather(city);\n        return { temperature: data.temp, condition: data.condition };\n      },\n    }),\n  },\n  prompt: \"What is the weather in San Francisco?\",\n});\n```\n\n### Dynamic Tools (MCP Integration)\n\nFor tools with schemas not known at compile time (e.g., MCP server tools):\n\n```ts\nimport { dynamicTool } from \"ai\";\n\nconst tools = {\n  unknownTool: dynamicTool({\n    description: \"A tool discovered at runtime\",\n    execute: async (input) => {\n      \u002F\u002F Handle dynamically\n      return { result: \"done\" };\n    },\n  }),\n};\n```\n\n### Agents\n\nThe `ToolLoopAgent` class wraps `generateText`\u002F`streamText` with an agentic tool-calling loop.\nDefault `stopWhen` is `stepCountIs(20)` (up to 20 tool-calling steps).\n`Agent` is an interface — `ToolLoopAgent` is the concrete implementation.\n\n```ts\nimport { ToolLoopAgent, stepCountIs, hasToolCall } from \"ai\";\n\nconst agent = new ToolLoopAgent({\n  model: \"anthropic\u002Fclaude-sonnet-4.6\",\n  tools: { weather, search, calculator, finalAnswer },\n  instructions: \"You are a helpful assistant.\",\n  \u002F\u002F Default: stepCountIs(20). Override to stop on a terminal tool or custom logic:\n  stopWhen: hasToolCall(\"finalAnswer\"),\n  prepareStep: (context) => ({\n    \u002F\u002F Customize each step — swap models, compress messages, limit tools\n    toolChoice: context.steps.length > 5 ? \"none\" : \"auto\",\n  }),\n});\n\nconst { text } = await agent.generate({\n  prompt:\n    \"Research the weather in Tokyo and calculate the average temperature this week.\",\n});\n```\n\n### MCP Client\n\nConnect to any MCP server and use its tools:\n\n```ts\nimport { generateText } from \"ai\";\nimport { createMCPClient } from \"@ai-sdk\u002Fmcp\";\n\nconst mcpClient = await createMCPClient({\n  transport: {\n    type: \"sse\",\n    url: \"https:\u002F\u002Fmy-mcp-server.com\u002Fsse\",\n  },\n});\n\nconst tools = await mcpClient.tools();\n\nconst result = await generateText({\n  model: \"openai\u002Fgpt-5.4\",\n  tools,\n  prompt: \"Use the available tools to help the user.\",\n});\n\nawait mcpClient.close();\n```\n\nMCP OAuth for remote servers is handled automatically by `@ai-sdk\u002Fmcp`.\n\n### Tool Approval (Human-in-the-Loop)\n\nSet `needsApproval` on any tool to require user confirmation before execution. The tool pauses in `approval-requested` state until the client responds.\n\n```ts\nimport { streamText, tool } from \"ai\";\nimport { z } from \"zod\";\n\nconst result = streamText({\n  model: \"openai\u002Fgpt-5.4\",\n  tools: {\n    deleteUser: tool({\n      description: \"Delete a user account\",\n      inputSchema: z.object({ userId: z.string() }),\n      needsApproval: true, \u002F\u002F Always require approval\n      execute: async ({ userId }) => {\n        await db.users.delete(userId);\n        return { deleted: true };\n      },\n    }),\n    processPayment: tool({\n      description: \"Process a payment\",\n      inputSchema: z.object({ amount: z.number(), recipient: z.string() }),\n      \u002F\u002F Conditional: only approve large amounts\n      needsApproval: async ({ amount }) => amount > 1000,\n      execute: async ({ amount, recipient }) => {\n        return await processPayment(amount, recipient);\n      },\n    }),\n  },\n  prompt: \"Delete user 123\",\n});\n```\n\n**Client-side approval with `useChat`:**\n\n```tsx\n\"use client\";\nimport { useChat } from \"@ai-sdk\u002Freact\";\n\nfunction Chat() {\n  const { messages, addToolApprovalResponse } = useChat();\n\n  return messages.map((m) =>\n    m.parts?.map((part, i) => {\n      \u002F\u002F Tool parts in approval-requested state need user action\n      if (part.type.startsWith(\"tool-\") && part.approval?.state === \"approval-requested\") {\n        return (\n          \u003Cdiv key={i}>\n            \u003Cp>Tool wants to run: {JSON.stringify(part.args)}\u003C\u002Fp>\n            \u003Cbutton onClick={() => addToolApprovalResponse({ id: part.approval.id, approved: true })}>\n              Approve\n            \u003C\u002Fbutton>\n            \u003Cbutton onClick={() => addToolApprovalResponse({ id: part.approval.id, approved: false })}>\n              Deny\n            \u003C\u002Fbutton>\n          \u003C\u002Fdiv>\n        );\n      }\n      return null;\n    }),\n  );\n}\n```\n\n**Tool part states:** `input-streaming` → `input-available` → `approval-requested` (if `needsApproval`) → `output-available` | `output-error`\n\n### Embeddings & Reranking\n\nUse a direct provider SDK for embeddings. AI Gateway does not support embedding models.\n\n```ts\nimport { embed, embedMany, rerank } from \"ai\";\nimport { openai } from \"@ai-sdk\u002Fopenai\";\n\n\u002F\u002F Single embedding\nconst { embedding } = await embed({\n  model: openai.embedding(\"text-embedding-3-small\"),\n  value: \"The quick brown fox\",\n});\n\n\u002F\u002F Batch embeddings\nconst { embeddings } = await embedMany({\n  model: openai.embedding(\"text-embedding-3-small\"),\n  values: [\"text 1\", \"text 2\", \"text 3\"],\n});\n\n\u002F\u002F Rerank search results by relevance\nconst { results } = await rerank({\n  model: cohere.reranker(\"rerank-v3.5\"),\n  query: \"What is quantum computing?\",\n  documents: searchResults,\n});\n```\n\n### Image Generation & Editing\n\nAI Gateway supports image generation. Use the **`google\u002Fgemini-3.1-flash-image-preview`** model — it is significantly better than older models like `gemini-2.0-flash-exp-image-generation` or `gemini-2.0-flash-001`.\n\n**Always use `google\u002Fgemini-3.1-flash-image-preview`** for image generation. Do NOT use older models (`gemini-2.0-*`, `gemini-2.5-*`) — they produce much worse results and some do not support image output at all.\n\n#### Multimodal LLMs (recommended — use `generateText`\u002F`streamText`)\n\n```ts\nimport { generateText, streamText } from \"ai\";\n\n\u002F\u002F generateText — images returned in result.files\nconst result = await generateText({\n  model: \"google\u002Fgemini-3.1-flash-image-preview\",\n  prompt: \"A futuristic cityscape at sunset\",\n});\nconst imageFiles = result.files.filter((f) => f.mediaType?.startsWith(\"image\u002F\"));\n\n\u002F\u002F Convert to data URL for display\nconst imageFile = imageFiles[0];\nconst dataUrl = `data:${imageFile.mediaType};base64,${Buffer.from(imageFile.data).toString(\"base64\")}`;\n\n\u002F\u002F streamText — stream text, then access images after completion\nconst stream = streamText({\n  model: \"google\u002Fgemini-3.1-flash-image-preview\",\n  prompt: \"A futuristic cityscape at sunset\",\n});\nfor await (const delta of stream.fullStream) {\n  if (delta.type === \"text-delta\") process.stdout.write(delta.text);\n}\nconst finalResult = await stream;\nconsole.log(`Generated ${finalResult.files.length} image(s)`);\n```\n\n**Default image model**: `google\u002Fgemini-3.1-flash-image-preview` — fast, high-quality. This is the ONLY recommended model for image generation.\n\n#### Image-only models (use `experimental_generateImage`)\n\n```ts\nimport { experimental_generateImage as generateImage } from \"ai\";\n\nconst { images } = await generateImage({\n  model: \"google\u002Fimagen-4.0-generate-001\",\n  prompt: \"A futuristic cityscape at sunset\",\n  aspectRatio: \"16:9\",\n});\n```\n\nOther image-only models: `google\u002Fimagen-4.0-ultra-generate-001`, `bfl\u002Fflux-2-pro`, `bfl\u002Fflux-kontext-max`, `xai\u002Fgrok-imagine-image-pro`.\n\n#### Saving generated images\n\n```ts\nimport fs from \"node:fs\";\n\n\u002F\u002F From multimodal LLMs (result.files)\nfor (const [i, file] of imageFiles.entries()) {\n  const ext = file.mediaType?.split(\"\u002F\")[1] || \"png\";\n  await fs.promises.writeFile(`output-${i}.${ext}`, file.uint8Array);\n}\n\n\u002F\u002F From image-only models (result.images)\nfor (const [i, image] of images.entries()) {\n  const buffer = Buffer.from(image.base64, \"base64\");\n  await fs.promises.writeFile(`output-${i}.png`, buffer);\n}\n```\n\n## UI Hooks (React)\n\n**MANDATORY — Always use AI Elements for AI text**: AI SDK models always produce markdown — even short prose contains `**bold**`, `##` headings, `` `code` ``, and `---`. There is no \"plain text\" mode. Every AI-generated string displayed in a browser MUST be rendered through AI Elements.\n- **Chat messages**: Use AI Elements `\u003CMessage message={message} \u002F>` — handles text, tool calls, code blocks, reasoning, streaming.\n- **Any other AI text** (streaming panels, workflow events, reports, briefings, narratives, summaries, perspectives): Use `\u003CMessageResponse>{text}\u003C\u002FMessageResponse>` from `@\u002Fcomponents\u002Fai-elements\u002Fmessage`.\n- `\u003CMessageResponse>` wraps Streamdown with code highlighting, math, mermaid, and CJK plugins — works for any markdown string, including streamed text.\n- **Never** render AI output as raw `{text}`, `\u003Cp>{content}\u003C\u002Fp>`, or `\u003Cdiv>{stream}\u003C\u002Fdiv>` — this always produces ugly unformatted output with visible markdown syntax.\n- **No exceptions**: Even if you think the response will be \"simple prose\", models routinely add markdown formatting. Always use AI Elements.\n\n⤳ skill: ai-elements — Full component library, decision guidance, and troubleshooting for AI interfaces\n\n### Transport Options\n\n`useChat` uses a transport-based architecture. Three built-in transports:\n\n| Transport | Use Case |\n|-----------|----------|\n| `DefaultChatTransport` | HTTP POST to API routes (default — sends to `\u002Fapi\u002Fchat`) |\n| `DirectChatTransport` | In-process agent communication without HTTP (SSR, testing) |\n| `TextStreamChatTransport` | Plain text stream protocol |\n\n**Default behavior:** `useChat()` with no transport config defaults to `DefaultChatTransport({ api: '\u002Fapi\u002Fchat' })`.\n\n### With AI Elements (Recommended)\n\n```tsx\n\"use client\";\nimport { useChat } from \"@ai-sdk\u002Freact\";\nimport { Conversation } from \"@\u002Fcomponents\u002Fai-elements\u002Fconversation\";\nimport { Message } from \"@\u002Fcomponents\u002Fai-elements\u002Fmessage\";\n\nfunction Chat() {\n  \u002F\u002F No transport needed — defaults to DefaultChatTransport({ api: '\u002Fapi\u002Fchat' })\n  const { messages, sendMessage, status } = useChat();\n\n  return (\n    \u003CConversation>\n      {messages.map((message) => (\n        \u003CMessage key={message.id} message={message} \u002F>\n      ))}\n    \u003C\u002FConversation>\n  );\n}\n```\n\nAI Elements handles UIMessage parts (text, tool calls, reasoning, images) automatically. Install with `npx ai-elements`.\n\n⤳ skill: ai-elements — Full component library for AI interfaces\n⤳ skill: json-render — Manual rendering patterns for custom UIs\n\n### With DirectChatTransport (No API Route Needed)\n\n```tsx\n\"use client\";\nimport { useChat } from \"@ai-sdk\u002Freact\";\nimport { DirectChatTransport } from \"ai\";\nimport { myAgent } from \"@\u002Flib\u002Fagent\"; \u002F\u002F a ToolLoopAgent instance\n\nfunction Chat() {\n  const { messages, sendMessage, status } = useChat({\n    transport: new DirectChatTransport({ agent: myAgent }),\n  });\n  \u002F\u002F Same UI as above — no \u002Fapi\u002Fchat route required\n}\n```\n\nUseful for SSR scenarios, testing without network, and single-process apps.\n\n**v6 changes from v5:**\n\n- `useChat({ api })` → `useChat({ transport: new DefaultChatTransport({ api }) })`\n- `handleSubmit` → `sendMessage({ text })`\n- `input` \u002F `handleInputChange` → manage your own `useState`\n- `body` \u002F `onResponse` options were removed from `useChat`; use `transport` to configure requests\u002Fresponses\n- `isLoading` → `status === 'streaming' || status === 'submitted'`\n- `message.content` → iterate `message.parts` (UIMessage format)\n\n### Choose the correct streaming response helper\n\n- `toUIMessageStreamResponse()` is for `useChat` + `DefaultChatTransport` UIMessage-based chat UIs. Use it when you need tool calls, metadata, reasoning, and other rich message parts.\n- `toTextStreamResponse()` is for **non-browser clients only** — CLI tools, server-to-server pipes, or programmatic consumers that process raw text without rendering it in a UI. If the text will be displayed in a browser, use `toUIMessageStreamResponse()` + AI Elements instead.\n- Warning: Do **not** return `toUIMessageStreamResponse()` to a plain `fetch()` client unless that client intentionally parses the AI SDK UI message stream protocol.\n- Warning: Do **not** use `toTextStreamResponse()` + manual `fetch()` stream reading as a way to skip AI Elements. If the output goes to a browser, use `useChat` + `\u003CMessageResponse>` or `\u003CMessage>`.\n\n### Server-side for useChat (API Route)\n\n```ts\n\u002F\u002F app\u002Fapi\u002Fchat\u002Froute.ts\nimport { streamText, convertToModelMessages, stepCountIs } from \"ai\";\nimport type { UIMessage } from \"ai\";\n\nexport async function POST(req: Request) {\n  const { messages }: { messages: UIMessage[] } = await req.json();\n  \u002F\u002F IMPORTANT: convertToModelMessages is async in v6\n  const modelMessages = await convertToModelMessages(messages);\n  const result = streamText({\n    model: \"openai\u002Fgpt-5.4\",\n    messages: modelMessages,\n    tools: {\n      \u002F* your tools *\u002F\n    },\n    \u002F\u002F IMPORTANT: use stopWhen with stepCountIs for multi-step tool calling\n    \u002F\u002F maxSteps was removed in v6 — use this instead\n    stopWhen: stepCountIs(5),\n  });\n  \u002F\u002F Use toUIMessageStreamResponse (not toDataStreamResponse) for chat UIs\n  return result.toUIMessageStreamResponse();\n}\n```\n\n### Server-side with ToolLoopAgent (Agent API Route)\n\nDefine a `ToolLoopAgent` and use `createAgentUIStreamResponse` for the API route:\n\n```ts\n\u002F\u002F lib\u002Fagent.ts\nimport { ToolLoopAgent, stepCountIs } from \"ai\";\n\nexport const myAgent = new ToolLoopAgent({\n  model: \"openai\u002Fgpt-5.4\",\n  instructions: \"You are a helpful assistant.\",\n  tools: { \u002F* your tools *\u002F },\n  stopWhen: stepCountIs(5),\n});\n```\n\n```ts\n\u002F\u002F app\u002Fapi\u002Fchat\u002Froute.ts — agent API route\nimport { createAgentUIStreamResponse } from \"ai\";\nimport { myAgent } from \"@\u002Flib\u002Fagent\";\n\nexport async function POST(req: Request) {\n  const { messages } = await req.json();\n  return createAgentUIStreamResponse({ agent: myAgent, uiMessages: messages });\n}\n```\n\nOr use `DirectChatTransport` on the client to skip the API route entirely.\n\n### Server-side for text-only clients (non-browser only)\n\n> **This pattern is for CLI tools, server-to-server pipes, and programmatic consumers.** If the response will be displayed in a browser UI, use `toUIMessageStreamResponse()` + AI Elements instead — even for \"simple\" streaming text panels.\n\n```ts\n\u002F\u002F app\u002Fapi\u002Fgenerate\u002Froute.ts — for CLI or server consumers, NOT browser UIs\nimport { streamText } from \"ai\";\n\nexport async function POST(req: Request) {\n  const { prompt }: { prompt: string } = await req.json();\n  const result = streamText({\n    model: \"openai\u002Fgpt-5.4\",\n    prompt,\n  });\n\n  return result.toTextStreamResponse();\n}\n```\n\n## Language Model Middleware\n\nIntercept and transform model calls for RAG, guardrails, logging:\n\n```ts\nimport { wrapLanguageModel } from \"ai\";\n\nconst wrappedModel = wrapLanguageModel({\n  model: \"openai\u002Fgpt-5.4\",\n  middleware: {\n    transformParams: async ({ params }) => {\n      \u002F\u002F Inject RAG context, modify system prompt, etc.\n      return { ...params, system: params.system + \"\\n\\nContext: ...\" };\n    },\n    wrapGenerate: async ({ doGenerate }) => {\n      const result = await doGenerate();\n      \u002F\u002F Post-process, log, validate guardrails\n      return result;\n    },\n  },\n});\n```\n\n## Provider Routing via AI Gateway\n\n```ts\nimport { generateText } from \"ai\";\nimport { gateway } from \"ai\";\n\nconst result = await generateText({\n  model: gateway(\"anthropic\u002Fclaude-sonnet-4.6\"),\n  prompt: \"Hello!\",\n  providerOptions: {\n    gateway: {\n      order: [\"bedrock\", \"anthropic\"], \u002F\u002F Try Bedrock first\n      models: [\"openai\u002Fgpt-5.4\"], \u002F\u002F Fallback model\n      only: [\"anthropic\", \"bedrock\"], \u002F\u002F Restrict providers\n      user: \"user-123\", \u002F\u002F Usage tracking\n      tags: [\"feature:chat\", \"env:production\"], \u002F\u002F Cost attribution\n    },\n  },\n});\n```\n\n## DevTools\n\n```bash\nnpx @ai-sdk\u002Fdevtools\n# Opens http:\u002F\u002Flocalhost:4983 — inspect LLM calls, agents, token usage, timing\n```\n\n## Key Patterns\n\n1. **Default to AI Gateway with OIDC** — pass `\"provider\u002Fmodel\"` strings (e.g., `model: \"openai\u002Fgpt-5.4\"`) to route through the gateway automatically. `vercel env pull` provisions OIDC tokens. No manual API keys needed. The `gateway()` wrapper is optional (only needed for `providerOptions.gateway`).\n2. **Set up a Vercel project for AI** — `vercel link` → enable AI Gateway at `https:\u002F\u002Fvercel.com\u002F{team}\u002F{project}\u002Fsettings` → **AI Gateway** → `vercel env pull` to get OIDC credentials. Never manually create `.env.local` with provider-specific API keys.\n3. **Always use AI Elements for any AI text in a browser** — `npx ai-elements` installs production-ready Message, Conversation, and Tool components. Use `\u003CMessage>` for chat and `\u003CMessageResponse>` for any other AI-generated text (streaming panels, summaries, reports). AI models always produce markdown — there is no scenario where raw `{text}` rendering is correct. ⤳ skill: ai-elements\n4. **Always stream for user-facing AI** — use `streamText` + `useChat`, not `generateText`\n5. **UIMessage chat UIs** — `useChat()` defaults to `DefaultChatTransport({ api: '\u002Fapi\u002Fchat' })`. On the server: `convertToModelMessages()` + `toUIMessageStreamResponse()`. For no-API-route setups: `DirectChatTransport` + Agent.\n6. **Text-only clients (non-browser)** — `toTextStreamResponse()` is only for CLI tools, server pipes, and programmatic consumers. If the text is displayed in a browser, use `toUIMessageStreamResponse()` + AI Elements\n7. **Use structured output** for extracting data — `generateText` with `Output.object()` and Zod schemas\n8. **Use `ToolLoopAgent`** for multi-step reasoning — not manual loops. Default `stopWhen` is `stepCountIs(20)`. Use `createAgentUIStreamResponse` for agent API routes.\n9. **Use DurableAgent** (from Workflow DevKit) for production agents that must survive crashes\n10. **Use `mcp-to-ai-sdk`** to generate static tool definitions from MCP servers for security\n11. **Use `needsApproval`** for human-in-the-loop — set on any tool to pause execution until user approves; supports conditional approval via async function\n12. **Use `strict: true`** per tool — opt-in strict mode ensures providers only generate schema-valid tool calls; set on individual tools, not globally\n\n## Common Pitfall: Structured Output Property Name\n\nIn v6, `generateText` with `Output.object()` returns the parsed result on the **`output`** property (NOT `object`):\n\n```ts\n\u002F\u002F CORRECT — v6\nconst { output } = await generateText({\n  model: 'openai\u002Fgpt-5.4',\n  output: Output.object({ schema: mySchema }),\n  prompt: '...',\n})\nconsole.log(output) \u002F\u002F ✅ parsed object\n\n\u002F\u002F WRONG — v5 habit\nconst { object } = await generateText({ ... }) \u002F\u002F ❌ undefined — `object` doesn't exist in v6\n```\n\nThis is one of the most common v5→v6 migration mistakes. The config key is `output` and the result key is also `output`.\n\n## Migration from AI SDK 5\n\nRun `npx @ai-sdk\u002Fcodemod upgrade` (or `npx @ai-sdk\u002Fcodemod v6`) to auto-migrate. Preview with `npx @ai-sdk\u002Fcodemod --dry upgrade`. Key changes:\n\n- `generateObject` \u002F `streamObject` → `generateText` \u002F `streamText` with `Output.object()`\n- `parameters` → `inputSchema`\n- `result` → `output`\n- `maxSteps` → `stopWhen: stepCountIs(N)` (import `stepCountIs` from `ai`)\n- `CoreMessage` → `ModelMessage` (use `convertToModelMessages()` — now async)\n- `ToolCallOptions` → `ToolExecutionOptions`\n- `Experimental_Agent` → `ToolLoopAgent` (concrete class; `Agent` is just an interface)\n- `system` → `instructions` (on `ToolLoopAgent`)\n- `agent.generateText()` → `agent.generate()`\n- `agent.streamText()` → `agent.stream()`\n- `experimental_createMCPClient` → `createMCPClient` (stable)\n- New: `createAgentUIStreamResponse({ agent, uiMessages })` for agent API routes\n- New: `callOptionsSchema` + `prepareCall` for per-call agent configuration\n- `useChat({ api })` → `useChat({ transport: new DefaultChatTransport({ api }) })`\n- `useChat` `body` \u002F `onResponse` options removed → configure with transport\n- `handleSubmit` \u002F `input` → `sendMessage({ text })` \u002F manage own state\n- `toDataStreamResponse()` → `toUIMessageStreamResponse()` (for chat UIs)\n- `createUIMessageStream`: use `stream.writer.write(...)` (not `stream.write(...)`)\n- text-only clients \u002F text stream protocol → `toTextStreamResponse()`\n- `message.content` → `message.parts` (tool parts use `tool-\u003CtoolName>`, not `tool-invocation`)\n- UIMessage \u002F ModelMessage types introduced\n- `DynamicToolCall.args` is not strongly typed; cast via `unknown` first\n- `TypedToolResult.result` → `TypedToolResult.output`\n- `ai@^6.0.0` is the umbrella package\n- `@ai-sdk\u002Freact` must be installed separately at `^3.0.x`\n- `@ai-sdk\u002Fgateway` (if installed directly) is `^3.x`, not `^1.x`\n- New: `needsApproval` on tools (boolean or async function) for human-in-the-loop approval\n- New: `strict: true` per-tool opt-in for strict schema validation\n- New: `DirectChatTransport` — connect `useChat` to an Agent in-process, no API route needed\n- New: `addToolApprovalResponse` on `useChat` for client-side approval UI\n- Default `stopWhen` changed from `stepCountIs(1)` to `stepCountIs(20)` for `ToolLoopAgent`\n- New: `ToolCallOptions` type renamed to `ToolExecutionOptions`\n- New: `Tool.toModelOutput` now receives `({ output })` object, not bare `output`\n- New: `isToolUIPart` → `isStaticToolUIPart`; `isToolOrDynamicToolUIPart` → `isToolUIPart`\n- New: `getToolName` → `getStaticToolName`; `getToolOrDynamicToolName` → `getToolName`\n- New: `@ai-sdk\u002Fazure` defaults to Responses API; use `azure.chat()` for Chat Completions\n- New: `@ai-sdk\u002Fanthropic` `structuredOutputMode` for native structured outputs (Anthropic Sonnet 4.5+)\n- New: `@ai-sdk\u002Flangchain` rewritten — `toBaseMessages()`, `toUIMessageStream()`, `LangSmithDeploymentTransport`\n- New: Provider-specific tools — Anthropic (memory, code execution), OpenAI (shell, patch), Google (maps, RAG), xAI (search, code)\n- `unknown` finish reason removed → now returned as `other`\n- Warning types consolidated into single `Warning` type exported from `ai`\n\n## Official Documentation\n\n- [AI SDK Documentation](https:\u002F\u002Fai-sdk.dev\u002Fdocs)\n- [AI SDK Core](https:\u002F\u002Fai-sdk.dev\u002Fdocs\u002Fai-sdk-core)\n- [AI SDK UI](https:\u002F\u002Fai-sdk.dev\u002Fdocs\u002Fai-sdk-ui)\n- [Generating Text](https:\u002F\u002Fai-sdk.dev\u002Fdocs\u002Fai-sdk-core\u002Fgenerating-text)\n- [Structured Data](https:\u002F\u002Fai-sdk.dev\u002Fdocs\u002Fai-sdk-core\u002Fgenerating-structured-data)\n- [Tools and Tool Calling](https:\u002F\u002Fai-sdk.dev\u002Fdocs\u002Fai-sdk-core\u002Ftools-and-tool-calling)\n- [Agents](https:\u002F\u002Fai-sdk.dev\u002Fdocs\u002Fai-sdk-core\u002Fagents)\n- [Providers and Models](https:\u002F\u002Fai-sdk.dev\u002Fdocs\u002Ffoundations\u002Fproviders-and-models)\n- [Provider Directory](https:\u002F\u002Fai-sdk.dev\u002Fproviders)\n- [GitHub: AI SDK](https:\u002F\u002Fgithub.com\u002Fvercel\u002Fai)\n",{"name":5,"metadata":24,"description":7},{"docs":25,"sitemap":28,"priority":29,"bashPatterns":30,"pathPatterns":42,"promptSignals":70,"importPatterns":91},[26,27],"https:\u002F\u002Fsdk.vercel.ai\u002Fdocs","https:\u002F\u002Fsdk.vercel.ai\u002Fdocs\u002Freference","https:\u002F\u002Fsdk.vercel.ai\u002Fsitemap.xml",8,[31,32,33,34,35,36,37,38,39,40,41],"\\bnpm\\s+(install|i|add)\\s+[^\\n]*\\bai\\b","\\bpnpm\\s+(install|i|add)\\s+[^\\n]*\\bai\\b","\\bbun\\s+(install|i|add)\\s+[^\\n]*\\bai\\b","\\byarn\\s+add\\s+[^\\n]*\\bai\\b","\\bnpm\\s+(install|i|add)\\s+[^\\n]*@ai-sdk\u002F","\\bpnpm\\s+(install|i|add)\\s+[^\\n]*@ai-sdk\u002F","\\bbun\\s+(install|i|add)\\s+[^\\n]*@ai-sdk\u002F","\\byarn\\s+add\\s+[^\\n]*@ai-sdk\u002F","\\bnpx\\s+@ai-sdk\u002Fdevtools\\b","\\bnpx\\s+@ai-sdk\u002Fcodemod\\b","\\bnpx\\s+mcp-to-ai-sdk\\b",[43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69],"app\u002Fapi\u002Fchat\u002F**","app\u002Fapi\u002Fcompletion\u002F**","src\u002Fapp\u002Fapi\u002Fchat\u002F**","src\u002Fapp\u002Fapi\u002Fcompletion\u002F**","pages\u002Fapi\u002Fchat.*","pages\u002Fapi\u002Fchat\u002F**","pages\u002Fapi\u002Fcompletion.*","pages\u002Fapi\u002Fcompletion\u002F**","src\u002Fpages\u002Fapi\u002Fchat.*","src\u002Fpages\u002Fapi\u002Fchat\u002F**","src\u002Fpages\u002Fapi\u002Fcompletion.*","src\u002Fpages\u002Fapi\u002Fcompletion\u002F**","lib\u002Fai\u002F**","src\u002Flib\u002Fai\u002F**","lib\u002Fai.*","src\u002Flib\u002Fai.*","ai\u002F**","apps\u002F*\u002Fapp\u002Fapi\u002Fchat\u002F**","apps\u002F*\u002Fapp\u002Fapi\u002Fcompletion\u002F**","apps\u002F*\u002Fsrc\u002Fapp\u002Fapi\u002Fchat\u002F**","apps\u002F*\u002Fsrc\u002Fapp\u002Fapi\u002Fcompletion\u002F**","apps\u002F*\u002Flib\u002Fai\u002F**","apps\u002F*\u002Fsrc\u002Flib\u002Fai\u002F**","lib\u002Fagent.*","src\u002Flib\u002Fagent.*","app\u002Factions\u002Fchat.*","src\u002Fapp\u002Factions\u002Fchat.*",{"allOf":71,"anyOf":78,"noneOf":83,"phrases":85,"minScore":90},[72,75],[73,74],"streaming","generation",[76,77],"structured","output",[79,80,81,82],"usechat","usecompletion","tool calling","embeddings",[84],"openai api directly",[86,87,88,89],"ai sdk","vercel ai","generatetext","streamtext",6,[92,93],"ai","@ai-sdk\u002F*","main","d9535210da9af28aa76bca80de80355197e1b6d6","skills\u002Fai-sdk","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog","https:\u002F\u002Fgithub.com\u002Fzfifteen","I like to measure things.","2026-07-19 23:41:54",{"source":8,"skillName":5,"commands":102,"prompt":112,"zipAvailable":113},[103,106,109],{"tool":104,"command":105},"npx","npx skills add zfifteen\u002Fskills-catalog --skill ai-sdk",{"tool":107,"command":108},"bunx","bunx skills add zfifteen\u002Fskills-catalog --skill ai-sdk",{"tool":110,"command":111},"pnpm","pnpm dlx skills add zfifteen\u002Fskills-catalog --skill ai-sdk","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fai-sdk\u002FSKILL.md",true,[115,121],{"path":116,"resourceType":117,"resourceTypeDesc":118,"sizeBytes":119,"sourceHtmlUrl":120},"agents\u002Fopenai.yaml","REFERENCE","参考文档",89,"https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fai-sdk\u002Fagents\u002Fopenai.yaml",{"path":122,"resourceType":117,"resourceTypeDesc":118,"sizeBytes":123,"sourceHtmlUrl":124},"references\u002Fproviders.md",2381,"https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fai-sdk\u002Freferences\u002Fproviders.md",[126,133,140,147,156,163],{"skillNo":127,"name":128,"nameZh":6,"description":129,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":130,"categories":131,"keywords":132,"publishedAt":19},"01M79GXQ2PWPT2E4CJYHXVJ0YE","Zotero","Use Zotero Desktop from Codex to enable\u002Fprobe the local API, search a local Zotero library, list items\u002Fcollections\u002Ftags, export BibTeX, insert citation keys into LaTeX or Markdown drafts, read indexed full text when requested, and import BibTeX\u002FRIS records into Zotero through the connector server. Use when the user mentions Zotero, citations, references.bib, BibTeX export, local Zotero API, localhost:23119, or adding citations from a Zotero library.","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fzotero\u002FSKILL.md",[],[],{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":137,"categories":138,"keywords":139,"publishedAt":19},"01M79GXN85NETKBE06865CWK6Z","zoom-apps-sdk","Use when using Apps SDK.","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[],{"skillNo":141,"name":142,"nameZh":6,"description":143,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":144,"categories":145,"keywords":146,"publishedAt":19},"01M79GXCYD7FGYS932J9N9RFFY","youtube","Obtain accurate, timestamped YouTube video transcripts (preferring manual captions over auto-generated) as the primary deliverable, then derive summaries, key claims, or notes from that transcript.  Use when the user provides a YouTube URL (or video ID) and wants the transcript, a faithful summary, key claims with attribution, timestamped notes, or \"what does this video actually say\".  The skill is transcript-first: never substitute metadata, title, description, or search snippets for the spoken content.  Triggers: \"youtube transcript\", \"get the transcript of this video\", \"summarize this youtube video\", \"what did they say in https:\u002F\u002Fyoutube.com\u002F...\", \"key claims from this talk\".","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fyoutube\u002FSKILL.md",[],[],{"skillNo":148,"name":149,"nameZh":6,"description":150,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":151,"licenseFileUrl":152,"sourceHtmlUrl":153,"categories":154,"keywords":155,"publishedAt":19},"01M79GX8EXHHYM566BKR7MS778","yeet","Publish local changes to GitHub by confirming scope, committing intentionally, pushing the branch, and opening a draft PR through the GitHub app from this plugin, with `gh` used only as a fallback where connector coverage is insufficient.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fyeet\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fyeet\u002FSKILL.md",[],[],{"skillNo":157,"name":158,"nameZh":6,"description":159,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":160,"categories":161,"keywords":162,"publishedAt":19},"01M79GX2HFJPX84NMRE5VBTYX9","x-post-creator","Create X-ready post threads and co-located story packages from the active conversation or referenced project material. Use when the user says turn this into an X-post, \u002Fx-post, make this into an X thread, or wants plain-language social posts with supporting images saved to docs\u002Fx-posts\u002F[story-name]\u002F.","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fx-post-creator\u002FSKILL.md",[],[],{"skillNo":164,"name":165,"nameZh":6,"description":166,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":167,"categories":168,"keywords":169,"publishedAt":19},"01M79GWXQT4HBT6QME6QSBZJFA","x-api","Search, read, and write X posts through the local X API MCP server (the same backend used by the Codex x-api skill). Use for searching X\u002Fx.com, reading threads and replies, creating lists, staging\u002Fpublishing posts for @alltheputs, finding high-visibility reply targets for research outreach, ingesting public context, or any request that mentions \u002Fx-api or \"search X\".","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fx-api\u002FSKILL.md",[],[]]