SERP API + Vercel AI SDK:Next.js 应用实时接入 Google 搜索
·
背景
Vercel AI SDK 是 Next.js 应用接 LLM 的标准方式。streamText + tool calling 让前端能流式接收 LLM 响应,把 SERP API 作为 tool 暴露给 LLM 是常见需求。
安装
npm install ai @ai-sdk/anthropic
Tool 定义
app/api/chat/route.ts:
import { streamText, tool } from "ai";
import { anthropic } from "@ai-sdk/anthropic";
import { z } from "zod";
export const maxDuration = 30;
export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: anthropic("claude-sonnet-4-5"),
messages,
tools: {
googleSearch: tool({
description: "搜索 Google 实时结果,返回前 5 条 organic + PAA",
parameters: z.object({
query: z.string().describe("搜索关键词"),
}),
execute: async ({ query }) => {
const r = await fetch("https://api.serpbase.dev/google/search", {
method: "POST",
headers: {
"X-API-Key": process.env.SERPBASE_API_KEY!,
"Content-Type": "application/json",
},
body: JSON.stringify({
q: query,
gl: "us",
hl: "en",
num: 5,
}),
});
if (!r.ok) throw new Error(`SERP API ${r.status}`);
const data = await r.json();
const sources = (data.organic || []).map(
(item: any, i: number) =>
`[${i + 1}] ${item.title}\n${item.link}\n${item.snippet || ""}`
);
const paa = (data.people_also_ask || [])
.slice(0, 3)
.map((q: any) => `- ${q.question || q}`)
.join("\n");
return {
sources: sources.join("\n\n"),
relatedQuestions: paa,
requestId: data.request_id,
};
},
}),
},
maxSteps: 3,
});
return result.toDataStreamResponse();
}
前端调用
app/page.tsx:
"use client";
import { useChat } from "ai/react";
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat({
api: "/api/chat",
});
return (
<div className="flex flex-col w-full max-w-2xl mx-auto p-4">
<div className="space-y-4 mb-4">
{messages.map((m) => (
<div key={m.id} className="p-3 rounded bg-gray-100">
<strong>{m.role}:</strong> {m.content}
</div>
))}
</div>
<form onSubmit={handleSubmit} className="flex gap-2">
<input
value={input}
onChange={handleInputChange}
placeholder="问点什么..."
className="flex-1 p-2 border rounded"
/>
<button type="submit" className="p-2 bg-blue-500 text-white rounded">
发送
</button>
</form>
</div>
);
}
部署注意
process.env.SERPBASE_API_KEY必须在 Vercel Dashboard 配置maxDuration = 30给 SERP API + LLM 推理足够时间maxSteps: 3防止 agent 无限循环- Vercel Edge Runtime 也能跑(把 fetch 改成 Edge 兼容)
成本
跟其他 framework 一样,大头是 LLM,SERP 部分 0.9 美元 / 月(Starter Boost,3,000 调用)。
Vercel AI SDK 相对 LangChain 的优势
- 原生 streaming:不用自己拼 SSE,SDK 处理
- React Hook 集成:
useChat5 行接前端 - Edge Runtime 兼容:全球部署延迟低
- TypeScript 一等公民:tool 定义、参数校验都 type-safe
如果你的项目是 Next.js / Vercel 部署,这套是最顺的路径。
跟 LangChain / LlamaIndex 的对比
| 维度 | Vercel AI SDK | LangChain | LlamaIndex |
|---|---|---|---|
| 适配场景 | Next.js / 前端 | 后端 agent | 数据源 RAG |
| Streaming | 原生 | 自己拼 | 自己拼 |
| 部署 | Vercel 优化 | 任意 | 任意 |
| 学习曲线 | 低 | 中 | 中 |
| Tool 调用 | tool() |
Tool |
FunctionTool |
SERP API 在三家都能接,选 framework 看主战场。
注意点
- API key 必须放 Vercel 环境变量,不要 hardcode
maxSteps: 3防止 agent 循环(每步 1 次 LLM 调用 + 1 次 tool)- SERP 响应塞 LLM context 会增加 token,生产用
num: 5别开太大
100 次免费试用:serpbase.dev 注册,不用绑卡,跑通 demo 后 deploy 到 Vercel。
更多推荐

所有评论(0)