LLM 的知识被冻结在训练截止时间,并会对近期事实产生幻觉。给 agent 一个 Google 搜索工具 可以同时解决这两个问题 —— 而像 serp.cheap 这样廉价的同步 SERP API 是理想的后端,因为延迟可预测,而且单次调用成本低到足以在 agent 规模下运行。
搜索工具(普通函数)
import requests
def google_search(query: str, country: str = "us") -> str:
"""Search Google and return the top results as text."""
data = requests.post(
"https://api.serp.cheap/v1/search",
headers={"X-API-Key": "YOUR_KEY"},
json={"q": query, "gl": country},
timeout=30,
).json()
return "\n".join(
f'{r["position"]}. {r["title"]} — {r["link"]}\n {r.get("snippet","")}'
for r in data["organic"]
)
配合 OpenAI 工具调用 API
tools = [{
"type": "function",
"function": {
"name": "google_search",
"description": "Search Google for up-to-date information.",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"},
"country": {"type": "string", "default": "us"},
},
"required": ["query"],
},
},
}]
# When the model calls google_search, run the function above and return its
# output as the tool result, then let the model answer with citations.
配合 LangChain
from langchain.tools import Tool
search_tool = Tool(
name="google_search",
description="Search Google for current information.",
func=lambda q: google_search(q),
)
# Add search_tool to your agent's tool list.
为什么 serp.cheap 适合 agent
- 同步 约 2 秒响应 —— 无需在一次工具调用内编排异步队列。
- 大规模下依然便宜 —— agent 会扇出大量搜索;$0.0006/次(缓存命中减半)让运行成本可控。
- 真实的 google.com + 可引用来源 —— 返回模型可以引用的链接,而不是黑盒索引。