vercel/ai · 上手攻略

  • 仓库:vercel/ai
  • 链接:https://github.com/vercel/ai
  • 分类:ai(llm-infra)
  • 作者:Jay
  • 更新:2026-07-10

这是什么

Vercel AI SDK(ai)是 Vercel 官方推出的 TypeScript AI 开发工具包,旨在让开发者用最少的代码在 React、Next.js、Svelte、Vue、Angular、Node.js 等框架和运行时中构建 AI 应用和 Agent。核心定位是"AI 应用的统一 API 层"——换模型提供商只需改两行代码,无需重写业务逻辑。

当前版本为 AI SDK v7(2026 年初发布),提供三大核心模块:

  • AI SDK Core:生成文本、结构化对象、工具调用、构建 Agent 的统一 API
  • AI SDK UI:框架无关的 React Hooks,快速搭建聊天/生成式 UI
  • AI SDK Harnesses:通过 HarnessAgent 接入 Claude Code、Codex 等已建立的 Agent 框架

支持 25+ 模型提供商,包括 OpenAI、Anthropic、Google(Gemini)、xAI(Grok)、Mistral、DeepSeek 等。默认通过 Vercel AI Gateway 访问,开箱即用。


解决什么问题

在 AI SDK 出现之前,TypeScript 开发者面临几个核心痛点:

  1. 每个模型提供商的 API 都不一样:OpenAI 用 client.chat.completions.create(),Anthropic 用 client.messages.create(),Google 又是另一套。切换模型意味着大量重写。
  2. 流式响应(Streaming)实现复杂:需要手动处理 SSE、解析 data: 格式,很容易写出兼容性差的代码。
  3. 构建 AI UI 门槛高:在 React 中实现流式打字效果、工具调用渲染、消息状态管理,往往要写上百行胶水代码。
  4. 工具调用(Tool Calling)没有统一方案:各家的工具定义格式和调用机制各不相同。

AI SDK 统一了这一切。你用同一套 generateText/streamText API,支持任何提供商;工具调用、Structured Output、流式 UI 全部有原生封装。


快速安装

前置条件:Node.js 22+(v7 要求)

# 基础包
npm install ai

# 按需安装提供商包(以 OpenAI 和 Anthropic 为例)
npm install @ai-sdk/openai @ai-sdk/anthropic

# 如果用 React,还需要 UI 包
npm install @ai-sdk/react

核心用法

1. 生成文本(generateText)

最基础的调用,一行切换提供商:

import { generateText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';

// 通过 Vercel AI Gateway(默认,无需 API Key 配置)
const { text } = await generateText({
  model: 'anthropic/claude-opus-4-6',  // 换 provider 也只需改这里
  prompt: 'What is retrieval-augmented generation?',
});

// 或直连提供商
const { text } = await generateText({
  model: anthropic('claude-opus-4-6'),
  prompt: 'Explain RAG in simple terms.',
});

2. 流式文本(streamText)

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

const result = await streamText({
  model: openai('gpt-5.4'),
  prompt: 'Write a haiku about version control.',
});

for await (const chunk of result.fullStream) {
  console.log(chunk.text);
}

3. 工具调用(Tool Calling)

import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';

const { text } = await generateText({
  model: openai('gpt-5.4'),
  tools: {
    // 工具可以是本地函数
    getWeather: {
      description: 'Get current weather for a city',
      parameters: z.object({
        city: z.string(),
      }),
      execute: async ({ city }) => {
        // 实际项目中调用天气 API
        return { city, temp: '22°C', condition: 'Sunny' };
      },
    }),
  },
  prompt: "What's the weather in Tokyo right now?",
});

console.log(text);
// 如果模型判断需要调用工具,会自动执行后返回结果

4. 结构化输出(Structured Output)

结合 Zod schema 生成 JSON 结构化数据:

import { generateText, Output } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';

const { output } = await generateText({
  model: openai('gpt-5.4'),
  output: Output.object({
    schema: z.object({
      recipe: z.object({
        name: z.string(),
        ingredients: z.array(z.object({
          name: z.string(),
          amount: z.string(),
        })),
        steps: z.array(z.string()),
      }),
    }),
  }),
  prompt: 'Generate a lasagna recipe.',
});

// output.recipe.name → "Lasagna"

5. AI UI Hooks(React)

// app/page.tsx
'use client';

import { useChat } from '@ai-sdk/react';

export default function ChatPage() {
  const { messages, sendMessage, status } = useChat();

  return (
    <div>
      {messages.map((msg) => (
        <div key={msg.id}>
          <strong>{msg.role}: </strong>
          {msg.content}
        </div>
      ))}
      <form onSubmit={(e) => {
        e.preventDefault();
        sendMessage({ text: (e.target as any).input.value });
      }}>
        <input name="input" disabled={status !== 'ready'} />
      </form>
    </div>
  );
}

6. 构建 Agent(ToolLoopAgent)

import { ToolLoopAgent } from 'ai';
import { openai } from '@ai-sdk/openai';

const agent = new ToolLoopAgent({
  model: openai('gpt-5.4'),
  system: 'You are a helpful assistant with access to a shell environment.',
  tools: {
    shell: openai.tools.localShell({
      execute: async ({ action }) => {
        const [cmd, ...args] = action.command;
        // 执行命令并返回结果
        return { output: 'command output here' };
      },
    }),
  },
});

7. 多提供商示例

一行切换模型:

// OpenAI
const { text: t1 } = await generateText({
  model: 'openai/gpt-5.4',
  prompt: 'Hello!',
});

// Anthropic
const { text: t2 } = await generateText({
  model: 'anthropic/claude-opus-4-6',
  prompt: 'Hello!',
});

// Google
const { text: t3 } = await generateText({
  model: 'google/gemini-3-flash',
  prompt: 'Hello!',
});

典型适用场景

场景 说明
AI Chatbot useChat Hook 在 Next.js/React 中快速构建流式聊天界面
多模型对比 一个接口换不同 provider,方便评估哪个模型效果最好
结构化数据提取 结合 Zod 输出 JSON,直接对接数据库或 API
Tool Calling 应用 构建能调用外部 API、搜索、执行代码的 Agent
生成式 UI(GenUI) 流式渲染 AI 生成的 React 组件
跨云 AI Gateway 通过 Vercel AI Gateway 聚合多个 provider,统一路由和配额管理

坑与注意

  1. Node.js 22+ 强制要求:v7 起最低支持 Node.js 22,老项目注意升级。
  2. Provider API Key 管理:虽然默认走 AI Gateway 免配置,但直连时需要各 provider 的 key,建议统一放在环境变量中。
  3. 流式兼容性:部分 provider 的流式格式有细微差异,实测 OpenAI/Anthropic 最稳定,其他 provider 如有异常建议查 provider 包文档。
  4. AI SDK v5 → v7 迁移:v7 有 breaking changes(如某些 hook API 调整),大版本升级建议先看官方迁移指南
  5. @ai-sdk/langchain 兼容性:Reddit 用户反馈 AI SDK v5 与 LangChain 的集成不完整,如有复杂 RAG 需求建议直接用 LangChain.js 而非通过 AI SDK 桥接。
  6. Provider 速率限制:各 provider 的 rate limit 不同,Vercel AI Gateway 可以统一配置重试和限流策略。
  7. HarnessAgent 封装深度:使用 HarnessAgent 时,底层 harness(如 Claude Code)的行为不完全透明,调试需要参考 harness 自身文档。

与同类对比

维度 Vercel AI SDK LangChain.js Mastra Genkit
定位 AI UI + Core + Agent 全能框架 AI 应用框架 Google 主推
包大小 小(Streaming-first) 较大(101kB gzipped) 中等 中等
Edge Runtime ✅ 支持 ❌ 不支持 部分支持 部分支持
流式 UI 复杂度 约 20 行代码 100+ 行 较低 中等
Provider 数量 25+ 更多(生态更全) 较少 较少
复杂 Agent 编排 一般(适合轻量 Agent) ✅ 强(RAG、复杂 Chain) 中等 中等
学习曲线
许可证 Apache 2.0 MIT MIT Apache 2.0

一句话结论:Vercel AI SDK 是 React/Next.js 场景下构建流式 AI UI 的最快路径;如果需要复杂 RAG pipeline、多步 Chain、深度 Agent 编排,LangChain.js 生态更完整。


推荐结论

如果你在用 Next.js / React 构建 AI 功能,Vercel AI SDK 是当下最优入口——上手极简、代码量少、Streaming 原生支持、25+ 模型一键切换,v7 的统一 API 已是生产级成熟度。唯一需要想清楚的是:你的 Agent 复杂度边界在哪,简单工具调用 AI SDK 完全 hold 住,复杂编排再考虑 LangChain.js。