[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CVMX1F63B9HM6RBPMV7CXW":3,"skill-same:01M7CVMX1F63B9HM6RBPMV7CXW":127},{"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":98,"ownerHtmlUrl":99,"ownerBlogUrl":100,"ownerDescription":101,"updatedAt":102,"install":103,"resources":116},"01M7CVMX1F63B9HM6RBPMV7CXW","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.","realsudarshan\u002FSD-skill","realsudarshan","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128029723?v=4","01M7CTP2JEKQ9KBJ51NRZ2777Z","Sudarshan Dhakal","01M7CTP2JYR2PRY3BWGA30HX7J",0,"MIT","https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Fofficial-openai\u002Fopenai-local-vercel-ai-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","92c2f40ebfad0c0aa3cc1faa89ffd6b23f9e8d1b","official-openai\u002Fopenai-local-vercel-ai-sdk","https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill","https:\u002F\u002Fsd-skill.vercel.app","https:\u002F\u002Fgithub.com\u002Frealsudarshan","sudarshandhakal.com.np","Innvotative","2026-11-12 23:03:50",{"source":8,"skillName":5,"commands":104,"prompt":114,"zipAvailable":115},[105,108,111],{"tool":106,"command":107},"npx","npx skills add realsudarshan\u002FSD-skill --skill ai-sdk",{"tool":109,"command":110},"bunx","bunx skills add realsudarshan\u002FSD-skill --skill ai-sdk",{"tool":112,"command":113},"pnpm","pnpm dlx skills add realsudarshan\u002FSD-skill --skill ai-sdk","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Fofficial-openai\u002Fopenai-local-vercel-ai-sdk\u002FSKILL.md",true,[117,123],{"path":118,"resourceType":119,"resourceTypeDesc":120,"sizeBytes":121,"sourceHtmlUrl":122},"agents\u002Fopenai.yaml","REFERENCE","参考文档",89,"https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Fofficial-openai\u002Fopenai-local-vercel-ai-sdk\u002Fagents\u002Fopenai.yaml",{"path":124,"resourceType":119,"resourceTypeDesc":120,"sizeBytes":125,"sourceHtmlUrl":126},"references\u002Fproviders.md",2386,"https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Fofficial-openai\u002Fopenai-local-vercel-ai-sdk\u002Freferences\u002Fproviders.md",[128,137,145,153,161,169],{"skillNo":129,"name":130,"nameZh":6,"description":131,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":132,"licenseFileUrl":133,"sourceHtmlUrl":134,"categories":135,"keywords":136,"publishedAt":19},"01M7CW5Y6EPMPMNDWE4EN2GXRX","winui-app","Bootstrap, develop, and design modern WinUI 3 desktop applications with C# and the Windows App SDK using official Microsoft guidance, WinUI Gallery patterns, Windows App SDK samples, and CommunityToolkit components. Use when creating a brand new app, preparing a machine for WinUI, reviewing, refactoring, planning, troubleshooting, environment-checking, or setting up WinUI 3 XAML, controls, navigation, windowing, theming, accessibility, responsiveness, performance, deployment, or related Windows app design and development work.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Freccomended\u002Fwinui-app\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Freccomended\u002Fwinui-app\u002FSKILL.md",[],[],{"skillNo":138,"name":139,"nameZh":6,"description":140,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":141,"sourceHtmlUrl":142,"categories":143,"keywords":144,"publishedAt":19},"01M7CW5RWFX7616ENEG573VFWG","vercel-deploy","Deploy applications and websites to Vercel. Use when the user requests deployment actions like \"deploy my app\", \"deploy and give me the link\", \"push this live\", or \"create a preview deployment\".","https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Freccomended\u002Fvercel-deploy\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Freccomended\u002Fvercel-deploy\u002FSKILL.md",[],[],{"skillNo":146,"name":147,"nameZh":6,"description":148,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":132,"licenseFileUrl":149,"sourceHtmlUrl":150,"categories":151,"keywords":152,"publishedAt":19},"01M7CW5M4VZHQPWG764X1W0S3B","security-best-practices","Perform language and framework specific security best-practice reviews and suggest improvements. Trigger only when the user explicitly requests security best practices guidance, a security review\u002Freport, or secure-by-default coding help. Trigger only for supported languages (python, javascript\u002Ftypescript, go). Do not trigger for general code review, debugging, or non-security tasks.","https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Freccomended\u002Fsecurity-best-practices\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Freccomended\u002Fsecurity-best-practices\u002FSKILL.md",[],[],{"skillNo":154,"name":155,"nameZh":6,"description":156,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":132,"licenseFileUrl":157,"sourceHtmlUrl":158,"categories":159,"keywords":160,"publishedAt":19},"01M7CW5EBTWA7PQ54HYFT1YW39","playwright","Use when the task requires automating a real browser from the terminal (navigation, form filling, snapshots, screenshots, data extraction, UI-flow debugging) via `playwright-cli` or the bundled wrapper script.","https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Freccomended\u002Fplaywright\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Freccomended\u002Fplaywright\u002FSKILL.md",[],[],{"skillNo":162,"name":163,"nameZh":6,"description":164,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":132,"licenseFileUrl":165,"sourceHtmlUrl":166,"categories":167,"keywords":168,"publishedAt":19},"01M7CW4DA7SZ4D9JMR3P7VJVM0","openai-docs","Use when the user asks how to build with OpenAI products or APIs and needs up-to-date official documentation with citations, help choosing the latest model for a use case, or model upgrade and prompt-upgrade guidance; prioritize OpenAI docs MCP tools, use bundled references only as helper context, and restrict any fallback browsing to official OpenAI domains.","https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Freccomended\u002Fopenai-docs\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Freccomended\u002Fopenai-docs\u002FSKILL.md",[],[],{"skillNo":170,"name":171,"nameZh":6,"description":172,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":132,"licenseFileUrl":173,"sourceHtmlUrl":174,"categories":175,"keywords":176,"publishedAt":19},"01M7CW3EHY7X60KB9SYEMRD3YR","netlify-deploy","Deploy web projects to Netlify using the Netlify CLI (`npx netlify`). Use when the user asks to deploy, host, publish, or link a site\u002Frepo on Netlify, including preview and production deploys.","https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Freccomended\u002Fnetlify-deploy\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Frealsudarshan\u002FSD-skill\u002Fblob\u002Fmain\u002Freccomended\u002Fnetlify-deploy\u002FSKILL.md",[],[]]