ai-sdk-6

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Vercel AI SDK v6 Development Guide

Vercel AI SDK v6 开发指南

Use this skill when developing AI-powered features using Vercel AI SDK v6 (
ai
package).
当你使用Vercel AI SDK v6(
ai
包)开发AI驱动的功能时,可以参考本技能。

Quick Reference

快速参考

Installation

安装

bash
bun add ai @ai-sdk/openai zod    # or @ai-sdk/anthropic, @ai-sdk/google, etc.
bash
bun add ai @ai-sdk/openai zod    # or @ai-sdk/anthropic, @ai-sdk/google, etc.

Core Functions

核心函数

FunctionPurpose
generateText
Non-streaming text generation (+ structured output with
Output
)
streamText
Streaming text generation (+ structured output with
Output
)
v6 Note:
generateObject
/
streamObject
are deprecated. Use
generateText
/
streamText
with
output: Output.object({ schema })
instead.
函数名称用途
generateText
非流式文本生成(+ 结合
Output
实现结构化输出)
streamText
流式文本生成(+ 结合
Output
实现结构化输出)
v6 注意事项
generateObject
/
streamObject
已被弃用。 请改用带有
output: Output.object({ schema })
generateText
/
streamText

Structured Output (v6)

结构化输出(v6)

typescript
import { generateText, Output } from "ai";
import { z } from "zod";

const { output } = await generateText({
  model: anthropic("claude-sonnet-4-6"),
  output: Output.object({
    schema: z.object({
      sentiment: z.enum(["positive", "neutral", "negative"]),
      topics: z.array(z.string()),
    }),
  }),
  prompt: "Analyze this feedback...",
});
Output types:
Output.object()
,
Output.array()
,
Output.choice()
,
Output.json()
typescript
import { generateText, Output } from "ai";
import { z } from "zod";

const { output } = await generateText({
  model: anthropic("claude-sonnet-4-6"),
  output: Output.object({
    schema: z.object({
      sentiment: z.enum(["positive", "neutral", "negative"]),
      topics: z.array(z.string()),
    }),
  }),
  prompt: "Analyze this feedback...",
});
输出类型:
Output.object()
Output.array()
Output.choice()
Output.json()

Agent Class (v6 Key Feature)

Agent类(v6核心特性)

typescript
import { ToolLoopAgent, tool, stepCountIs } from "ai";
import { anthropic } from "@ai-sdk/anthropic";
import { z } from "zod";

const myAgent = new ToolLoopAgent({
  model: anthropic("claude-sonnet-4-6"),
  instructions: "You are a helpful assistant.",
  tools: {
    getData: tool({
      description: "Fetch data from API",
      inputSchema: z.object({
        query: z.string(),
      }),
      execute: async ({ query }) => {
        return { result: "data" };
      },
    }),
  },
  stopWhen: stepCountIs(20),
});

// Usage
const { text } = await myAgent.generate({ prompt: "Hello" });
const stream = myAgent.stream({ prompt: "Hello" });
typescript
import { ToolLoopAgent, tool, stepCountIs } from "ai";
import { anthropic } from "@ai-sdk/anthropic";
import { z } from "zod";

const myAgent = new ToolLoopAgent({
  model: anthropic("claude-sonnet-4-6"),
  instructions: "You are a helpful assistant.",
  tools: {
    getData: tool({
      description: "Fetch data from API",
      inputSchema: z.object({
        query: z.string(),
      }),
      execute: async ({ query }) => {
        return { result: "data" };
      },
    }),
  },
  stopWhen: stepCountIs(20),
});

// 使用方法
const { text } = await myAgent.generate({ prompt: "Hello" });
const stream = myAgent.stream({ prompt: "Hello" });

API Route with Agent

带Agent的API路由

typescript
// app/api/chat/route.ts
import { createAgentUIStreamResponse } from "ai";
import { myAgent } from "@/agents/my-agent";

export async function POST(request: Request) {
  const { messages } = await request.json();

  return createAgentUIStreamResponse({
    agent: myAgent,
    uiMessages: messages,
  });
}
typescript
// app/api/chat/route.ts
import { createAgentUIStreamResponse } from "ai";
import { myAgent } from "@/agents/my-agent";

export async function POST(request: Request) {
  const { messages } = await request.json();

  return createAgentUIStreamResponse({
    agent: myAgent,
    uiMessages: messages,
  });
}

Smooth Streaming

流畅流式传输

typescript
import { createAgentUIStreamResponse, smoothStream } from "ai";

return createAgentUIStreamResponse({
  agent: myAgent,
  uiMessages: messages,
  experimental_transform: smoothStream({
    delayInMs: 15,
    chunking: "word", // "word" | "line" | "none"
  }),
});
typescript
import { createAgentUIStreamResponse, smoothStream } from "ai";

return createAgentUIStreamResponse({
  agent: myAgent,
  uiMessages: messages,
  experimental_transform: smoothStream({
    delayInMs: 15,
    chunking: "word", // "word" | "line" | "none"
  }),
});

useChat Hook (Client)

useChat钩子(客户端)

typescript
"use client";
import { useChat } from "@ai-sdk/react";
import { DefaultChatTransport } from "ai";
import { useState } from "react";

export function Chat() {
  const [input, setInput] = useState("");
  const { messages, sendMessage, status } = useChat({
    transport: new DefaultChatTransport({
      api: "/api/chat",
    }),
  });

  return (
    <>
      {messages.map((msg) => (
        <div key={msg.id}>
          {msg.parts.map((part, i) =>
            part.type === "text" ? <span key={i}>{part.text}</span> : null
          )}
        </div>
      ))}
      <form
        onSubmit={(e) => {
          e.preventDefault();
          if (input.trim()) {
            sendMessage({ text: input });
            setInput("");
          }
        }}
      >
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          disabled={status !== "ready"}
        />
        <button type="submit" disabled={status !== "ready"}>
          Send
        </button>
      </form>
    </>
  );
}
v6 Note:
useChat
no longer manages input state internally. Use
useState
for controlled inputs.
typescript
"use client";
import { useChat } from "@ai-sdk/react";
import { DefaultChatTransport } from "ai";
import { useState } from "react";

export function Chat() {
  const [input, setInput] = useState("");
  const { messages, sendMessage, status } = useChat({
    transport: new DefaultChatTransport({
      api: "/api/chat",
    }),
  });

  return (
    <>
      {messages.map((msg) => (
        <div key={msg.id}>
          {msg.parts.map((part, i) =>
            part.type === "text" ? <span key={i}>{part.text}</span> : null
          )}
        </div>
      ))}
      <form
        onSubmit={(e) => {
          e.preventDefault();
          if (input.trim()) {
            sendMessage({ text: input });
            setInput("");
          }
        }}
      >
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          disabled={status !== "ready"}
        />
        <button type="submit" disabled={status !== "ready"}>
          Send
        </button>
      </form>
    </>
  );
}
v6 注意事项
useChat
不再在内部管理输入状态,请使用
useState
来实现受控输入。

Reference Documentation

参考文档

For detailed information, see:
  • agents.md - ToolLoopAgent, loop control, workflows
  • core-functions.md - generateText, streamText, Output patterns
  • tools.md - Tool definition with Zod schemas
  • ui-hooks.md - useChat, UIMessage, streaming
  • middleware.md - Custom middleware patterns
  • mcp.md - MCP server integration
如需详细信息,请查看:
  • agents.md - ToolLoopAgent、循环控制、工作流
  • core-functions.md - generateText、streamText、Output模式
  • tools.md - 基于Zod schema的工具定义
  • ui-hooks.md - useChat、UIMessage、流式传输
  • middleware.md - 自定义中间件模式
  • mcp.md - MCP服务器集成

Official Documentation

官方文档

For the latest information, see AI SDK docs.
如需最新信息,请查看AI SDK文档