SERP API + LangChain 实战:构建 RAG Agent 实时联网搜索 项目目标30 分钟搭一个 LangChain Agent,能:接收用户问题自动判断需要 SERP 搜索调 SERP API 拿 Google 实时数据把结果喂 LLM 生成答案带 citation 引用Step 1:环境(2 分钟)pipinstalllangchain langchain-anthropic requests环境变量:exportSERPBASE_KEYyour-keyexportANTHROPIC_KEYyour-keyStep 2:Tool 定义(5 分钟)importosimportrequestsfromlangchain.toolsimportTool SERPBASE_KEYos.environ[SERPBASE_KEY]ENDPOINThttps://api.serpbase.dev/google/searchdefserp_search(query:str)-str:搜索 Google 实时结果。返回前 5 条 organic PAA knowledge graph。 Args: query: 搜索关键词字符串 rrequests.post(ENDPOINT,headers{X-API-Key:SERPBASE_KEY},json{q:query,gl:us,hl:en,num:5},timeout10,)r.raise_for_status()datar.json()parts[]# Organic resultsfori,iteminenumerate(data.get(organic,[]),1):parts.append(f[{i}]{item[title]}\n{item[link]}\n{item.get(snippet,)})# People Also Askpaadata.get(people_also_ask,[])ifpaa:parts.append(\nRelated Questions:)forqinpaa[:3]:parts.append(f-{q.get(question,q)})# Knowledge Graphkgdata.get(knowledge_graph,{})ifkg:parts.append(f\nKnowledge Graph:{kg.get(title,)}-{kg.get(description,)})return\n\n.join(parts)serp_toolTool(nameGoogle Search,funcserp_search,description搜索 Google 实时结果,返回 SERP 数据(标题、URL、snippet、PAA、knowledge graph)。输入是查询关键词字符串。,)Step 3:Agent 集成(8 分钟)fromlangchain_anthropicimportChatAnthropicfromlangchain.agentsimportinitialize_agent,AgentType llmChatAnthropic(modelclaude-sonnet-4-5,anthropic_api_keyos.environ[ANTHROPIC_KEY],)agentinitialize_agent(tools[serp_tool],llmllm,agentAgentType.ZERO_SHOT_REACT_DESCRIPTION,verboseTrue,max_iterations3,handle_parsing_errorsTrue,)defask(question:str)-str:returnagent.run(question)Step 4:测试(5 分钟)# 测试 1:简单查询print(ask(2026 年 SERP API 的最新定价是多少?))# 测试 2:多步查询print(ask(对比 SerpBase 和 SerpApi 的价格和速度))# 测试 3:知识图谱查询print(ask(Claude 是什么?))Step 5:加 streaming(5 分钟)importasynciofromlangchain.agentsimportAgentExecutorasyncdefask_streaming(question:str):resultagent.astream(question)asyncforeventinresult:ifvaluesinevent:print(event[values],end,flushTrue)ifmessagesinevent:formsginevent[messages]:print(f\n[Tool]{msg.content},end,flushTrue)# 使用asyncio.run(ask_streaming(2026 年 SERP API 哪家最便宜?))Step 6:加 citation 解析(5 分钟)importredefparse_citations(answer:str)-list:提取答案中的 [1] [2] 引用patternr\[(\d)\]return[int(m)forminre.findall(pattern,answer)]defrender_with_citations(answer:str,sources:list)-str:把 [1] 替换成可点击的链接citationsparse_citations(answer)ifnotcitations:returnanswer source_list\n.join(f[{i1}]{s[title]}-{s[link]}fori,sinenumerate(sources))returnf{answer}\n\n**Sources:**\n{source_list}完整 demodeffull_demo():question2026 年 SERP API 价格和速度对比answerask(question)print(answer)# 显示 sources(可选)sources[{title:SERP API Comparison 2026,link:https://example.com/1},{title:SERP API Benchmark,link:https://example.com/2},]print(\nrender_with_citations(answer,sources))if__name____main__:full_demo()4 个关键设计点1. Tool description 要详细# 错:description搜索# 对:description搜索 Google 实时结果,返回 SERP 数据(标题、URL、snippet、PAA、knowledge graph)。输入是查询关键词字符串。详细 description 让 LLM 更清楚何时调用。2. max_iterations 别太大# 错:max_iterations10(可能无限循环)# 对:max_iterations3(3 次足够)3. handle_parsing_errors# 必须设 True,否则 LLM 输出格式偶尔错会卡住agentinitialize_agent(...,handle_parsing_errorsTrue)4. 缓存 LLM 结果importhashlibimportjson CACHE{}defask_cached(question):keyhashlib.md5(question.encode()).hexdigest()ifkeyinCACHE:returnCACHE[key]answerask(question)CACHE[key]answerreturnanswer5 个真实工作流1. 客服机器人defcustomer_support(question):# 调 SERP 查产品最新信息sourcesserp_search(f{question}site:mysite.com)# Claude 基于 sources 回答returnask(f基于以下 sources 回答:{question}\n\nSources:{sources})2. 研究助手defresearch(question):returnask(question)# 自动判断要不要 SERP# Agent 内部会决策3. SEO 内容生成defseo_article(keyword):sourcesserp_search(keyword)promptf基于以下 Google SERP 前 5 结果,写一篇 1000 字 SEO 文章:\n{sources}returnask(prompt)4. 竞品监控defcompetitor_monitor(brand,competitors):forcompincompetitors:sourcesserp_search(f{brand}vs{comp})# Claude 分析竞品相对位置returnask(f分析竞品{comp}跟{brand}的对比:\n{sources})5. AI 助手defai_assistant(question):# Agent 自动决定要不要 SERPreturnask(question)成本分析(每次调用)项目成本SerpBase$0.0003Claude Sonnet input(2k token)$0.006Claude Sonnet output(500 token)$0.0075总$0.0138100 次 / 天 $1.38 / 天 $41 / 月。用 Haiku 替代 Sonnet 可以降到 $0.005 / 次。5 个常见错误Tool description 太短:LLM 不知道怎么调max_iterations0 或太高:要么不调,要么循环没 handle_parsing_errors:LLM 输出偶尔格式错会卡住没加 max_iterations:可能无限循环没 cache 重复问题:成本高,体验慢部署选项方式适合本地脚本个人 / 测试FastAPI Docker生产 Web 应用Cloud Run / Lambdaserverless,自动扩展Streamlit / Gradiodemo 展示100 次免费试用:serpbase.dev