Vercel AI SDK 完整介紹 — 從串流對話到 AI Agent,一個套件打通所有 LLM

Vercel AI SDK 是 TypeScript 生態系中最完整的 AI 開發工具包,支援 OpenAI、Anthropic、Google 等數十家模型提供商。本文深入解析 AI SDK Core、UI、Agent 三大子系統,以及 v6 最新功能如 Middleware、Guardrails、Telemetry。

  • Dennis
  • 5 分鐘閱讀
Vercel AI SDK 完整介紹 — 從串流對話到 AI Agent,一個套件打通所有 LLM

Vercel AI SDK 完整介紹 — 從串流對話到 AI Agent,一個套件打通所有 LLM

如果你正在用 TypeScript/JavaScript 開發 AI 應用——不管是簡單的 Chatbot、串流生成文章、還是複雜的 AI Agent——你一定會遇到一個問題:

換模型 provider 就要 rewrite 一次 API 呼叫邏輯?

Vercel AI SDK 正是為了解決這個問題而生。由 Next.js 團隊打造的開源 TypeScript 工具包,提供一個統一的 API 介面,讓你用同一套程式碼無痛切換 OpenAI、Anthropic Claude、Google Gemini、Mistral、甚至本地模型。


一句話總結

Vercel AI SDK = TypeScript 生態系的 LLM 通用轉接器,讓你用同一套程式碼操作所有 AI 模型,從簡單的文字生成到複雜的 Agent 迴圈全部涵蓋。

專案速覽

項目內容
📦 npm 套件ai
📄 LicenseApache 2.0 / 開源
⭐ GitHub Stars10,000+
🎯 核心語言TypeScript
🏢 維護者Vercel
🔄 當前版本v6.0(2026 正式版)
🧩 Provider 支援30+ 模型提供商

AI SDK 三大核心子系統

AI SDK 分為三個層次,你可以根據需求選擇使用:

AI SDK(單一 `ai` npm 套件)
├── AI SDK Core      底層 API:串流、結構化輸出、工具呼叫
├── AI SDK UI        React/Vue/Svelte HooksuseChatuseAssistant
└── AI SDK Agent     Agent 框架:ToolLoopStopConditionsGuardrails

1. AI SDK Core — 核心引擎

這是所有功能的基礎,提供最底層的 AI 呼叫能力。

import { generateText, streamText } from 'ai';
import { openai } from '@ai-sdk/openai';
// import { anthropic } from '@ai-sdk/anthropic';   ← 換這行就行
// import { google } from '@ai-sdk/google';          ← 或這行

// 文字生成(非串流)
const { text } = await generateText({
  model: openai('gpt-4o'),
  prompt: '解釋量子糾纏給高中生聽',
});

// 串流文字(串流)
const result = streamText({
  model: openai('gpt-4o'),
  prompt: '寫一篇 500 字的台灣旅遊介紹',
});
for await (const chunk of result.textStream) {
  process.stdout.write(chunk);
}

特色:

  • 多 Provider 統一介面:換模型只需改一行 import
  • 支援 30+ Provider:OpenAI / Anthropic / Google / Mistral / Groq / Together AI / Ollama(本地) / OpenRouter 等
  • Streaming 原生支援:Server-Sent Events、即時串流、中斷控制
  • Structured Output:v6 用 generateText + Output.object() 取代舊的 generateObject

2. AI SDK UI — 前端整合層

讓你不費吹灰之力把 AI 串接到前端框架。

// app/api/chat/route.ts — Next.js API Route
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-4o'),
    messages,
  });
  return result.toAIStreamResponse();
}
// app/page.tsx — 前端元件
import { useChat } from 'ai/react';

export default function Chat() {
  const { messages, input, handleInputChange, handleSubmit } = useChat();

  return (
    <div>
      {messages.map(m => (
        <div key={m.id}>
          <strong>{m.role}:</strong> {m.content}
        </div>
      ))}
      <form onSubmit={handleSubmit}>
        <input value={input} onChange={handleInputChange} />
        <button>送出</button>
      </form>
    </div>
  );
}

前端框架支援:

  • React / Next.js ✅
  • Vue / Nuxt ✅
  • Svelte / SvelteKit ✅
  • SolidJS ✅

3. AI SDK Agent — AI Agent 框架

v6 的最大亮點是強化的 Agent 支援,讓你可以建立具有工具調用、記憶步驟、策略中斷能力的 AI Agent。

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

const result = await generateText({
  model: openai('gpt-4o'),
  tools: {
    getWeather: tool({
      description: '查詢某城市的當前天氣',
      inputSchema: z.object({ location: z.string() }),
      execute: async ({ location }) => {
        return { temperature: 28, condition: '晴' };
      },
    }),
    searchFlight: tool({
      description: '搜尋航班價格',
      inputSchema: z.object({ 
        from: z.string(), 
        to: z.string(), 
        date: z.string() 
      }),
      execute: async ({ from, to, date }) => {
        return { price: 12500, airline: '中華航空' };
      },
    }),
  },
  output: Output.object({
    schema: z.object({
      recommendation: z.string(),
      totalCost: z.number(),
    }),
  }),
  prompt: '幫我規劃下週從台北到東京的旅遊建議',
});

Agent 關鍵功能:

  • Tool Loop:AI 自動決定何時呼叫工具、何時產出最終答案
  • Stop Conditions:設定最大步驟數、自訂中斷條件
  • Tool Approval:整合 OPA 策略引擎做工具使用審核
  • Timeout 控制:支援 per-step / per-tool / per-chunk 三層超時設定

v6 最新功能

Middleware(中介層)

可以 wrap 任何模型 provider,加入自訂邏輯:

const cachedModel = cached(openai('gpt-4o'));
const result = await streamText({
  model: cachedModel,
  prompt: '重複的請求不再消耗 API 額度',
});

內建範例:快取中介層(開發期節省 API 呼叫)、日誌中介層、速率限制中介層。

Guardrails(安全護欄)

v6 引入了 @ai-sdk/policy-opa 套件,讓你用 OPA(Open Policy Agent)策略引擎控制模型的行為:

import { opaPolicy, wasmPolicyClient } from '@ai-sdk/policy-opa';

const toolApproval = opaPolicy({
  client: await wasmPolicyClient({ wasm }),
  path: 'agent/call/decision',
});

const result = await generateText({
  model: anthropic('claude-sonnet-4-5'),
  tools: { git, bash, queryLogs },
  toolApproval,  // ← OPA 控制哪些工具可以呼叫
  prompt: '找到失敗的測試並推送修正',
});

Telemetry(可觀測性)

原生整合 OpenTelemetry,所有 AI SDK 呼叫自動產生 tracing:

const result = await generateText({
  model: openai('gpt-4o-mini'),
  prompt: '解釋為何雞不適合當太空人',
  telemetry: {
    metadata: {
      userId: 'user-123',
      threadId: 'thread-456',
    },
  },
});

支援串接 Langfuse、LangWatch、Maxim 等 Observability 平台。


支援的 Provider 列表(超過 30 家)

Providernpm 套件模型範例
OpenAI@ai-sdk/openaiGPT-4o, GPT-5.6
Anthropic@ai-sdk/anthropicClaude Sonnet 4, Opus
Google@ai-sdk/googleGemini 2.5 Pro
Mistral@ai-sdk/mistralMistral Large
Groq@ai-sdk/groqLlama 3, Mixtral
Together AI@ai-sdk/together開源模型
Ollama(本地)@ai-sdk/ollama本地 LLM
OpenRouter@ai-sdk/openrouter數百種模型
AWS Bedrock@ai-sdk/amazon-bedrockClaude, Llama
Azure@ai-sdk/azureOpenAI on Azure
Perplexity@ai-sdk/perplexitySonar
DeepSeek@ai-sdk/deepseekDeepSeek V3
xAI Grok@ai-sdk/xaiGrok 3

誰在用 Vercel AI SDK?

  • Perplexity AI — 搜尋引擎後端
  • Replit Agent — AI 程式碼生成
  • LangChain — 部分整合方案
  • ShadCN — AI Elements UI 元件庫
  • 以及無數 Next.js + AI 的 side project

實戰:3 行程式碼建立一個多模型 Chatbot

// 只用 3 個核心步驟就能啟動
// 1. Server: API Route 串接 streamText
// 2. Client: useChat hook 綁定 UI
// 3. 切換模型 provider 只需改一行

// 步驟 1: pages/api/chat.ts
import { streamText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';

export default async function handler(req, res) {
  const result = streamText({
    model: anthropic('claude-sonnet-4-20250514'),
    messages: req.body.messages,
  });
  return result.pipeDataStreamToResponse(res);
}

// 步驟 2: 前端 Chat.tsx
import { useChat } from 'ai/react';
// useChat 自動處理串流、狀態管理、錯誤處理

// 步驟 3: 要換成 Gemini?
// 改 import { google } from '@ai-sdk/google'
// 改 model: google('gemini-2.5-pro')
// 其他全部不用動

跟其他框架的比較

功能Vercel AI SDKLangChainLlamaIndex自幹 API
Provider 統一介面
Streaming UI Hooks
TypeScript 原生⚠️ Python 為主⚠️ Python 為主
Agent Tool Loop自己刻
Guardrails✅(OPA)⚠️⚠️自己刻
Telemetry✅ OpenTelemetry自己刻
Bundle Size輕量自訂

結論

Vercel AI SDK 最強大的地方不是單一功能,而是把所有 AI 開發需要的東西整合到一個 npm 套件裡,而且設計得非常 TypeScript 原生——型別安全、自動完成、IDE 支援都一流。

如果你正在用 TypeScript 開發 AI 應用,AI SDK 應該是你的第一選擇,而不是 LangChain。

一句話結論:Vercel AI SDK = TypeScript 開發者最絲滑的 AI 開發體驗。


參考來源:Vercel AI SDK GitHub、Vercel AI SDK 官方文件、AI SDK v6 Migration Guide