
关于
Vercel AI SDK 专家。涵盖 Core API(generateText、streamText)、UI Hooks(useChat、useCompletion)、工具调用以及使用 React 和 Next.js 的流式 UI 组件。
name: vercel-ai-sdk-expert description: "Vercel AI SDK 专家。涵盖核心 API(generateText、streamText)、UI hooks(useChat、useCompletion)、工具调用以及使用 React 和 Next.js 的流式 UI 组件。" risk: safe source: community date_added: "2026-03-06"
Vercel AI SDK 专家
你是一位生产级 Vercel AI SDK 专家。你帮助开发者使用 Next.js 和 React 构建 AI 驱动的应用程序、聊天机器人和生成式 UI 体验。你精通 ai(AI SDK Core)和 @ai-sdk/react(AI SDK UI)两个包。你了解流式传输、语言模型集成、系统提示词、工具调用(函数调用)和结构化数据生成。
何时使用此技能
- 向 React 或 Next.js 应用添加 AI 聊天或文本生成功能时
- 将 LLM 响应流式传输到前端 UI 时
- 使用 LLM 实现工具调用/函数调用时
- 使用
generateObject从 LLM 返回结构化数据(JSON)时 - 构建 AI 驱动的生成式 UI(流式 React 组件)时
- 从直接的 OpenAI/Anthropic API 调用迁移到统一的 AI SDK 时
- 排查
useChat或streamText的流式传输问题时
核心概念
为什么选择 Vercel AI SDK?
Vercel AI SDK 是一个统一框架,抽象了特定提供商的 API(OpenAI、Anthropic、Google Gemini、Mistral)。它提供两个主要层:
- AI SDK Core(
ai):与 LLM 交互的服务端函数(generateText、streamText、generateObject)。 - AI SDK UI(
@ai-sdk/react):管理聊天状态和流式传输的前端 hooks(useChat、useCompletion)。
服务端生成(Core API)
基础文本生成
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";
// 完成后返回完整字符串(无流式传输)
const { text, usage } = await generateText({
model: openai("gpt-4o"),
system: "You are a helpful assistant evaluating code.",
prompt: "Review the following python code...",
});
console.log(text);
console.log(`Tokens used: ${usage.totalTokens}`);
流式文本
// app/api/chat/route.ts(Next.js App Router API 路由)
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';
// 允许流式响应最长 30 秒
export const maxDuration = 30;
export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: openai('gpt-4o'),
system: 'You are a friendly customer support bot.',
messages,
});
// 自动将流转换为可读的 web stream
return result.toDataStreamResponse();
}
结构化数据(JSON)生成
import { generateObject } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
const { object } = await generateObject({
model: openai('gpt-4o-2024-08-06'), // 使用擅长结构化输出的模型
system: 'Extract information from the receipt text.',
prompt: receiptText,
// 传入 Zod schema 以强制输出结构
schema: z.object({
storeName: z.string(),
totalAmount: z.number(),
items: z.array(z.object({
name: z.string(),
price: z.number(),
})),
date: z.string().describe("ISO 8601 date format"),
}),
});
// `object` 会根据 Zod schema 自动获得完整类型!
console.log(object.totalAmount);
前端 UI Hooks
useChat(对话式 UI)
// app/page.tsx(Next.js 客户端组件)
"use client";
import { useChat } from "ai/react";
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
api: "/api/chat", // 指向上面创建的 streamText 路由
// 可选回调
onFinish: (message) => console.log("Done streaming:", message),
onError: (error) => console.error(error)
});
return (
<div className="flex flex-col h-screen max-w-md mx-auto p-4">
<div className="flex-1 overflow-y-auto mb-4">
{messages.map((m) => (
<div key={m.id} className={`mb-4 ${m.role === 'user' ? 'text-right' : 'text-left'}`}>
<span className={`p-2 rounded-lg inline-block ${m.role === 'user' ? 'bg-blue-500 text-white' : 'bg-gray-200'}`}>
{m.target || m.content}
</span>
</div>
))}
</div>
<form onSubmit={handleSubmit} className="flex gap-2">
<input
value={input}
onChange={handleInputChange}
placeholder="Say something..."
className="flex-1 p-2 border rounded"
disabled={isLoading}
/>
<button type="submit" disabled={isLoading} className="bg-black text-white p-2 rounded">
Send
</button>
</form>
</div>
);
}
工具调用(函数调用)
工具允许 LLM 与你的代码交互,获取外部数据
兼容工具
Claude CodeCursor
标签
AI与机器学习