如何將 Search API 接入 LangChain,實現即時網頁搜尋
了解如何將 Search API 接入 LangChain,讓 Agent 可以取得即時網頁結果、整理最新來源,並回答依賴時效資訊的問題。
沒有 web search 的 LangChain Agent 依然有用,但它有一個明顯盲點:它無法可靠知道模型訓練截止時間之後發生了什麼。
如果只是解釋 Python list 或改寫段落,這沒問題。
但如果使用者問的是近期產品更新、當前搜尋排名、價格頁、新聞、市場信號或競品變化,就不能只靠模型記憶。
比較實際的做法是:給 Agent 一個搜尋工具。
Search API 可以把 LangChain Agent 從「依賴模型記憶的助手」變成「可以查詢即時資訊的研究助手」。Agent 可以判斷什麼時候需要搜尋,取得最新網頁結果,讀取結構化摘要,再基於當前上下文回答。
快速回答
要把 Search API 接入 LangChain,可以先把 Search API 請求封裝成 LangChain tool,再把 tool 傳給 Agent,並在 system prompt 中說清楚什麼時候需要搜尋。
典型流程是:
使用者問題
→ LangChain Agent 判斷是否需要搜尋
→ Search API 返回最新網頁結果
→ Agent 讀取結構化搜尋資料
→ Agent 基於即時上下文和來源資訊回答
為什麼 LangChain 需要 Search API?
LLM 擅長推理、摘要和寫作,但它不是即時網頁索引。
當答案依賴當前資料時,Search API 可以讓 LangChain 應用取得最新外部資訊。
常見場景包括:
-
即時研究助手
-
SEO 和排名追蹤 Agent
-
競品監控
-
市場情報 workflow
-
新聞和趨勢摘要
-
產品與價格研究
-
需要即時網頁上下文的 RAG 系統
-
內容大綱生成
重點不只是「能搜尋網頁」。
重點是搜尋結果要以 Agent 能讀懂的方式返回。
對 Agent 來說,結構化 JSON 通常比原始 HTML 更好用。相比把整頁搜尋結果塞進模型,把 title、snippet、position、source domain 等欄位傳給 LLM 會更乾淨。
Search API vs 自建爬蟲
你可以自己寫爬蟲,但它很容易變成基礎設施工程。
|
方式 |
更適合 |
主要問題 |
|
自建爬蟲 |
一次性實驗 |
解析、封鎖、CAPTCHA、版面變化 |
|
瀏覽器自動化 |
複雜頁面操作 |
慢、成本高、難擴展 |
|
Search API / SERP API |
搜尋結果、排名、摘要、來源 |
需要選對 API 和參數 |
對 LangChain Agent 來說,Search API 通常更乾淨。
Agent 不需要一整頁渲染後的搜尋頁。它通常只需要一組簡潔搜尋結果:
[
{
"title": "Example result title",
"url": "result_page",
"snippet": "Short summary from the search result",
"position": 1
}
]
這種資料更容易摘要,更省 token,也更方便後續存儲和分析。
Step 1:安裝套件
你可以自己寫 LangChain tool,也可以使用已有套件。
以 Talordata 為例,可以安裝 LangChain 相關套件:
pip install langchain langchain-openai langchain-talordata
模型供應商可以替換成你自己在 LangChain 中使用的模型。
Step 2:設定 API keys
不要把憑證寫死在程式碼裡,建議使用環境變數。
import os
os.environ["TALOR_API_KEY"] = "your-talordata-api-key"
os.environ["OPENAI_API_KEY"] = "your-llm-provider-api-key"
正式部署時,應該把 key 放在部署平台的 secret settings 裡,而不是放在原始碼中。
API key 外洩不是小 bug,是一條拿著信用卡的小龍。
Step 3:先直接測試搜尋工具
不要一開始就接 Agent。
先確保 Search API 本身能正常返回結果。
from langchain_talordata import TalorSerpTool
search_tool = TalorSerpTool.from_env()
result = search_tool.invoke({
"query": "latest LangChain agent updates",
"engine": "google",
"params": {
"gl": "us",
"hl": "en",
"device": "desktop"
}
})
print(result)
這一步可以讓排錯變簡單。
如果搜尋請求本身失敗,Agent 不會憑空修好它。先測工具,再交給 Agent。
常見搜尋參數包括:
|
參數 |
含義 |
|
|
搜尋查詢 |
|
|
搜尋引擎,例如 Google 或 Bing |
|
|
國家或市場 |
|
|
搜尋語言 |
|
|
城市或地區 |
|
|
Desktop 或 mobile |
|
|
返回結果數量 |
|
|
視設定而定,用於請求 fresh results |
Step 4:把 Search API tool 加入 LangChain Agent
搜尋工具能返回結果後,就可以傳給 LangChain Agent。
from langchain.agents import create_agent
from langchain_talordata import TalorSerpTool
search_tool = TalorSerpTool.from_env()
agent = create_agent(
model="openai:gpt-4o-mini",
tools=[search_tool],
system_prompt="""
You are a research assistant.
Use the search tool when the question depends on recent, external,
location-specific, or source-dependent information.
When you search:
- focus on title, URL, snippet, source, and ranking position
- summarize the findings clearly
- include source names when they help verification
- do not invent facts that are not supported by the results
Do not search for stable definitions or simple programming explanations.
"""
)
response = agent.invoke({
"messages": [
{
"role": "user",
"content": "What are the latest updates in LangChain agents?"
}
]
})
print(response)
這裡的核心是:當問題依賴最新資訊時,模型不應該只靠記憶回答。
Step 5:告訴 Agent 什麼時候應該搜尋
一個支援搜尋的 Agent,不應該每次都搜尋。
這是地板上的小陷阱。
如果每個問題都搜尋,Agent 會變慢、請求變多,還可能把不必要的網頁雜訊帶進答案。
適合搜尋的問題:
What changed in this product category this month?
Which pages rank for this keyword today?
Find recent pricing pages for CRM tools.
What are the latest news results about this company?
不太需要搜尋的問題:
What is a Python dictionary?
Rewrite this paragraph.
Explain what an API is.
Summarize the text I provided.
可以寫一段搜尋策略:
SEARCH_POLICY = """
Use web search only when:
- the answer may have changed recently
- the user asks for current sources
- the question involves rankings, prices, news, competitors, products, or policies
- the result may vary by country, city, language, or device
Do not search when:
- the answer is stable general knowledge
- the user only asks to rewrite, translate, or summarize provided text
- the task can be completed from the conversation alone
"""
這會讓 Agent 更可控,不會像一個停不下來的搜尋小風車。
Step 6:不要只傳 keyword,要使用搜尋參數
即時網頁搜尋裡,query 只是其中一部分。
搜尋結果會受市場、語言、裝置和地區影響。
範例:
result = search_tool.invoke({
"query": "best project management software",
"engine": "google",
"params": {
"gl": "us",
"hl": "en",
"location": "New York, United States",
"device": "desktop",
"num": 10
}
})
如果做 SEO、本地搜尋或市場研究,請保存搜尋上下文:
|
欄位 |
為什麼重要 |
|
|
實際搜尋查詢 |
|
|
Google、Bing、DuckDuckGo 等 |
|
|
國家或市場 |
|
|
搜尋語言 |
|
|
城市或地區 |
|
|
Desktop 或 mobile |
|
|
用於歷史比較的時間戳 |
沒有這些上下文,後續很難驗證答案。
Step 7:控制搜尋上下文大小
不要把所有內容都塞進 LLM。
多數 Agent 只需要這些欄位:
title
url
snippet
position
source/domain
date, if available
可以加一個壓縮層:
def compact_results(raw_results, limit=5):
organic = (
raw_results.get("organic_results")
or raw_results.get("organic")
or raw_results.get("results")
or []
)
compact = []
for item in organic[:limit]:
compact.append({
"title": item.get("title", ""),
"url": item.get("link") or item.get("url", ""),
"snippet": item.get("snippet") or item.get("description", ""),
"position": item.get("position") or item.get("rank"),
})
return compact
這樣 Agent 不用在資料泥潭裡游泳,回答會更穩。
SDK 還是 MCP?
把搜尋接入 LangChain,常見有兩種方式。
|
方式 |
適合場景 |
|
本地原型、單 Agent 應用、快速開發 |
|
|
生產系統、多 Agent 設定、共享工具服務 |
驗證流程時先用 SDK。
當工具復用、部署隔離和團隊級使用變重要時,再考慮 MCP。
簡單判斷:
一個應用、一個團隊、快速接入 → SDK
多個 Agent、共享工具服務、生產治理 → MCP
不要一開始就搞架構表演。先把搜尋工具跑通。
範例:即時研究 Agent
下面是一個更聚焦的研究型 Agent:
from langchain.agents import create_agent
from langchain_talordata import TalorSerpTool
search_tool = TalorSerpTool.from_env()
agent = create_agent(
model="openai:gpt-4o-mini",
tools=[search_tool],
system_prompt="""
You are a real-time research assistant.
When the user asks about a recent or source-dependent topic:
1. Search the web.
2. Read the top relevant results.
3. Identify the main facts, patterns, and disagreements.
4. Mention useful source names.
5. Clearly say when the search results are incomplete.
Keep the answer concise and practical.
"""
)
response = agent.invoke({
"messages": [
{
"role": "user",
"content": "Find recent discussions about AI search agents and summarize the main trends."
}
]
})
print(response)
同一套模式也能改造成 SEO 內容簡報、市場研究、本地排名追蹤、產品監控和 RAG source discovery。
Best practices
第一版保持簡單。
一個搜尋工具,一個 Agent,一個清楚 prompt。
只在需要時搜尋。
工具有價值,是因為 Agent 能選擇它,而不是每一輪都必須使用它。
Agent workflow 優先用結構化結果。
Raw HTML 適合自訂解析,但 JSON 通常更適合 LLM 上下文。
保存查詢上下文。
Query、engine、country、language、location、device 和 timestamp 都應該保留。
使用搜尋結果時,讓 Agent 提供來源名稱。
即時回答最好可以驗證。
處理失敗情況。
Search API 可能返回空結果、timeout 或 rate limit。Agent 應該溫和失敗,而不是編答案。
FAQ
LangChain 中的 Search API 是什麼?
在 LangChain 裡,Search API 通常會被封裝成 tool。Agent 可以在需要外部網頁資訊時調用它,再把返回結果作為回答上下文。
為什麼 LangChain Agent 需要即時 web search?
模型可能不知道最近事件、當前排名、即時價格或新發布頁面。即時 web search 可以讓 Agent 在回答前取得最新外部資訊。
SERP API 和 Search API 一樣嗎?
SERP API 是 Search API 的一種,重點是搜尋引擎結果頁。它通常返回 title、snippet、ranking、ads、local results、news、images 或其他搜尋結果模組。免費測試SERP API>>
應該使用 JSON 還是 HTML 搜尋結果?
對 LangChain Agent 來說,JSON 通常更合適,因為它結構化、易摘要。HTML 適合需要原始 SERP 或自訂解析的場景。
可以用於 SEO workflow 嗎?
可以。同一套模式可以支援排名追蹤、關鍵字研究、內容大綱、競品監控、本地 SEO 檢查和 SERP feature 分析。
Agent 應該每個問題都搜尋嗎?
不應該。搜尋應該用在近期、依賴來源、依賴市場或依賴地區的問題上。穩定定義和簡單寫作任務通常不需要搜尋。