实战

Vercel AI SDK全栈开发实战

| 2025-11-21 18:44 | 2348 浏览
# Vercel AI SDK全栈开发 ## 什么是Vercel AI SDK? Vercel AI SDK是Vercel推出的AI应用开发工具包,提供了构建AI聊天应用所需的一切:流式响应、多模型支持、React组件等。 ## 快速开始 ### 创建项目 ```bash npx create-next-app@latest my-ai-app cd my-ai-app npm install ai openai ``` ### 创建 API 路由 ```typescript // app/api/chat/route.ts import { openai } from "@ai-sdk/openai" import { streamText } from "ai" export async function POST(req: Request) { const { messages } = await req.json() const result = await streamText({ model: openai("gpt-4"), messages, }) return result.toDataStreamResponse() } ``` ### 创建 Chat 组件 ```tsx // app/page.tsx "use client" import { useChat } from "ai/react" export default function Chat() { const { messages, input, handleInputChange, handleSubmit } = useChat() return (
{messages.map((m) => (
{m.role === "user" ? "你" : "AI"}: {m.content}
))}
) } ``` ## 核心特性 ### 1. 流式响应 Vercel AI SDK自动处理流式响应,实现字符级别的实时显示。 ### 2. 多模型支持 ```typescript import { openai } from "@ai-sdk/openai" import { anthropic } from "@ai-sdk/anthropic" import { google } from "@ai-sdk/google" // 切换不同的模型 const model = process.env.MODEL_PROVIDER === "anthropic" ? anthropic("claude-3-sonnet") : openai("gpt-4") ``` ### 3. 工具调用 ```typescript import { z } from "zod" import { tool } from "ai" const weatherTool = tool({ description: "获取天气信息", parameters: z.object({ city: z.string().describe("城市名称") }), execute: async ({ city }) => { // 调用天气API return { city, temp: 25, weather: "晴" } } }) const result = await streamText({ model: openai("gpt-4"), messages, tools: { weather: weatherTool } }) ``` ### 4. 生成结构化数据 ```typescript import { generateObject } from "ai" import { z } from "zod" const { object } = await generateObject({ model: openai("gpt-4"), schema: z.object({ title: z.string(), summary: z.string(), tags: z.array(z.string()) }), prompt: "生成一篇关于AI编程的文章元数据" }) ``` ## 高级功能 ### RAG集成 ```typescript async function handleChat(messages: Message[]) { // 1. 检索相关文档 const relevantDocs = await searchVectorDB(messages[messages.length - 1].content) // 2. 构建上下文 const context = relevantDocs.map(d => d.content).join(" ") // 3. 生成回答 return streamText({ model: openai("gpt-4"), system: `基于以下上下文回答问题: ${context}`, messages }) } ``` ### 错误处理 ```tsx const { error, reload } = useChat({ onError: (err) => { console.error("Chat error:", err) } }) if (error) { return } ``` ## 部署 直接部署到Vercel: ```bash vercel deploy ``` 设置环境变量:`OPENAI_API_KEY` ## 总结 Vercel AI SDK大大简化了AI聊天应用的开发,几十行代码就可以创建一个具备流式响应的ChatGPT风格应用。
VercelAI SDKNext.jsReact流式响应
167 点赞 28 评论

评论 (0)

登录后发表评论。

暂无评论。成为第一个评论的人吧!