Vercel AI SDK教程:流式AI应用开发完整指南

日期:2026-08-14 | 分类:AI工具教程


项目简介

Vercel AI SDK是TypeScript/JavaScript生态最流行的AI应用开发框架,支持流式输出、多模型切换、工具调用、结构化输出、Embedding和RAG。兼容OpenAI/Anthropic/Google/DeepSeek/xAI等30+模型提供商。

安装

npm install ai @ai-sdk/openai @ai-sdk/anthropic

# 设置API Key
export OPENAI_API_KEY="sk-your-key"
export ANTHROPIC_API_KEY="sk-ant-your-key"

流式文本生成

import { streamText } from 'ai'
import { openai } from '@ai-sdk/openai'

const result = streamText({
  model: openai('gpt-5.6'),
  prompt: '写一首关于AI的诗'
})

for await (const chunk of result.textStream) {
  process.stdout.write(chunk)
}

Next.js API路由

// app/api/chat/route.ts
import { streamText } from 'ai'
import { openai } from '@ai-sdk/openai'

export async function POST(req: Request) {
  const { messages } = await req.json()
  const result = streamText({
    model: openai('gpt-5.6'),
    messages
  })
  return result.toDataStreamResponse()
}

前端React组件

'use client'
import { useChat } from 'ai/react'

export default function Chat() {
  const { messages, input, handleInputChange, handleSubmit } = useChat()
  return (
    <div>
      {messages.map(m => <div key={m.id}>{m.role}: {m.content}</div>)}
      <form onSubmit={handleSubmit}>
        <input value={input} onChange={handleInputChange} />
      </form>
    </div>
  )
}

多模型切换

import { openai } from '@ai-sdk/openai'
import { anthropic } from '@ai-sdk/anthropic'
import { createOpenAI } from '@ai-sdk/openai'

// DeepSeek通过OpenAI兼容接口
const deepseek = createOpenAI({
  baseURL: 'https://api.deepseek.com/v1',
  apiKey: process.env.DEEPSEEK_API_KEY
})

const models = {
  fast: openai('gpt-5.6'),
  smart: anthropic('claude-fable-5'),
  cheap: deepseek('deepseek-v4-flash')
}

// 根据任务复杂度选模型
const model = taskComplexity === 'high' ? models.smart : models.cheap

工具调用

import { generateText, tool } from 'ai'
import { z } from 'zod'

const result = await generateText({
  model: openai('gpt-5.6'),
  tools: {
    getWeather: tool({
      description: '获取城市天气',
      parameters: z.object({ city: z.string() }),
      execute: async ({ city }) => {
        const res = await fetch(`https://wttr.in/${city}?format=3`)
        return res.text()
      }
    })
  },
  prompt: '北京天气怎么样?'
})

结构化输出

import { generateObject } from 'ai'
import { z } from 'zod'

const { object } = await generateObject({
  model: openai('gpt-5.6'),
  schema: z.object({
    title: z.string(),
    summary: z.string(),
    tags: z.array(z.string())
  }),
  prompt: '总结这篇文章:...'
})

Embedding与RAG

import { embed, embedMany } from 'ai'
import { openai } from '@ai-sdk/openai'

// 生成Embedding
const { embedding } = await embed({
  model: openai.embedding('text-embedding-3-large'),
  value: '这是一段文本'
})

// 批量Embedding
const { embeddings } = await embedMany({
  model: openai.embedding('text-embedding-3-large'),
  values: ['文本1', '文本2', '文本3']
})

相关阅读

📚 常见问题

Vercel AI SDK是什么?

Vercel AI SDK是TypeScript/JavaScript生态最流行的AI应用开发框架,支持流式输出、多模型切换、工具调用、结构化输出、Embedding和RAG。兼容OpenAI/Anthropic/Google/DeepSeek/xAI等30+模型提供商。