Vercel Ai Sdk — Vercel AI Sdk
v1.0.1Vercel AI SDK for building chat interfaces with 流ing. Use when implementing useChat hook, handling 工具 calls, 流ing 响应s, or building chat UI. Triggers on useChat, @AI-sdk/react, UIMessage, Chat状态, 流Text, toUIMessage流响应, 添加工具输出, on工具Call, 发送Message.
运行时依赖
安装命令
点击复制技能文档
Vercel AI SDK
The Vercel AI SDK provides React hooks and server utilities for building 流ing chat interfaces with support for 工具 calls, file attachments, and multi-step reasoning.
Quick Reference Basic useChat 设置up 导入 { useChat } from '@AI-sdk/react';
const { messages, 状态, 发送Message, 停止, re生成 } = useChat({ id: 'chat-id', messages: initialMessages, onFinish: ({ message, messages, isAbort, isError }) => { console.记录('Chat finished'); }, onError: (error) => { console.error('Chat error:', error); } });
// 发送 a message 发送Message({ text: 'Hello', metadata: { 创建dAt: Date.now() } });
// 发送 with files 发送Message({ text: 'Analyze this', files: file列出 // File列出 or FileUIPart[] });
Chat状态 状态s
The 状态 field indicates the current 状态 of the chat:
ready: Chat is idle and ready to accept new messages submitted: Message sent to API, awAIting 响应 流 启动 流ing: 响应 actively 流ing from the API error: An error occurred during the 请求 Message Structure
Messages use the UIMessage type with a parts-based structure:
interface UIMessage { id: string; 角色: '系统' | 'user' | '助手'; metadata?: unknown; parts: Array; // text, file, 工具-*, reasoning, etc. }
Part types include:
text: Text content with optional 流ing 状态 file: File attachments (images, documents) 工具-{工具Name}: 工具 invocations with 状态 machine reasoning: AI reasoning 追踪s data-{typeName}: Custom data parts Server-Side 流ing 导入 { 流Text } from 'AI'; 导入 { convertTo模型Messages } from 'AI';
const 结果 = 流Text({ 模型: openAI('gpt-4'), messages: convertTo模型Messages(uiMessages), 工具s: { 获取Weather: 工具({ description: '获取 weather', 输入模式: z.object({ city: z.string() }), 执行: a同步 ({ city }) => { return { temperature: 72, weather: 'sunny' }; } }) } });
return 结果.toUIMessage流响应({ originalMessages: uiMessages, onFinish: ({ messages }) => { // Save to database } });
工具 Handling Patterns
命令行工具ent-Side 工具 Execution:
const { 添加工具输出 } = useChat({ on工具Call: a同步 ({ 工具Call }) => { if (工具Call.工具Name === '获取Location') { 添加工具输出({ 工具: '获取Location', 工具CallId: 工具Call.工具CallId, 输出: 'San Francisco' }); } } });
Rendering 工具 状态s:
{message.parts.map(part => { if (part.type === '工具-获取Weather') { switch (part.状态) { case '输入-流ing': return
{JSON.stringify(part.输入, null, 2)};
case '输入-avAIlable':
return Reference Files
DetAIled documentation on specific aspects:
use-chat.md: Complete useChat API reference messages.md: UIMessage structure and part types 流ing.md: Server-side 流ing implementation 工具s.md: 工具 definition and execution patterns Common Patterns Error Handling const { error, clearError } = useChat({ onError: (error) => { toast.error(error.message); } });
// Clear error and re设置 to ready 状态 if (error) { clearError(); }
Message Regeneration const { re生成 } = useChat();
// Re生成 last 助手 message awAIt re生成();
// Re生成 specific message awAIt re生成({ messageId: 'msg-123' });
Custom Transport 导入 { DefaultChatTransport } from 'AI';
const { messages } = useChat({ transport: new DefaultChatTransport({ API: '/API/chat', prepare发送Messages请求: ({ id, messages, trigger, messageId }) => ({ body: { chatId: id, lastMessage: messages[messages.length - 1], trigger, messageId } }) }) });
Performance Optimization // Throttle UI 更新s to reduce re-renders const chat = useChat({ experimental_throttle: 100 // 更新 max once per 100ms });
Automatic Message 发送ing 导入 { last助手MessageIsCompleteWith工具Calls } from 'AI';
const chat = useChat({ 发送AutomaticallyWhen: last助手MessageIsCompleteWith工具Calls // Automatically re发送 when all 工具 calls have 输出s });
Type Safety
The SDK provides full type inference for 工具s and messages:
导入 { InferUI工具s, UIMessage } from 'AI';
const 工具s = { 获取Weather: 工具({ 输入模式: z.object({ city: z.string() }), 执行: a同步 ({ city }) => ({ weather: 'sunny' }) }) };
type MyMessage = UIMessage< { 创建dAt: number }, // Metadata type UIDataTypes, InferUI工具s // 工具 types >;
const { messages } = useChat();
Key Concepts Parts-Based Architecture
Messages use a parts array instead of a single content field. This allows:
流ing text while mAIntAIning other parts 工具 calls with independent 状态