如何使用 AI 代理搜尋網頁(Research,版本 2)?
網頁搜尋是一項服務。你把問題送給 Tavily,它交回十個結果。每個結果都帶著 標題、連結、網頁的一小段文字,以及一個分數,說明這個網頁與問題有多吻合。
在這個版本,搜尋本身是一個工具,由代理決定是否使用。我們的 程式碼不再自己呼叫 Tavily。它把工具交給模型,模型讀過問題之後選擇這個工具, 然後由 Python 執行。十個結果會原封不動地交回,跟搜尋服務產生的完全一樣。
搜尋變成一個工具
@tool(return_direct=True)
def search_internet(query: str):
"""
Search the internet for up-to-date information about the query
and return the full Tavily search response.
"""
response = tavily_client.search(query, max_results=10)
return response
@tool 把一個普通函數變成模型可以呼叫的東西。三引號裡的那句話
— 也就是 docstring — 不是裝飾:模型在決定這個
工具是否適合這個請求時,讀的就是它,而它同時也告訴模型可以期望拿回甚麼。
主體就是一次搜尋:一次呼叫,十個結果,每個都有 title、
url、content 和 score。
為甚麼工具會結束這次執行
@tool(return_direct=True)
return_direct=True 的意思是:當這個工具作答,那個答案就是代理
的最終答案。模型不會在之後再寫一段回覆。
指示:不要改寫問題
agent = create_agent(
model=model,
tools=[search_internet],
system_prompt=(
"You are a helpful assistant. "
"Always call search_internet, using the user's message exactly as the query. "
"Do not rephrase, shorten, translate, or add anything to it."
),
)
系統提示詞會在任務開始之前被讀取。這裡它做兩件事:叫模型 呼叫唯一的那個工具,並叫模型在過程中不要動那條問題。
第二條規則比表面看來更重要。搜尋引擎做的是字詞配對,所以「What is the population of Hong Kong?」和「Hong Kong population」會交回不同的清單,而一個 樂於助人的模型會很自然地改寫問題,變成它認為更清楚的樣子。既然我們想逐個 版本比較這個系列,問題就必須原樣送出。
執行代理
prompt = "What is the population of Hong Kong?"
result = agent.invoke({
"messages": [{"role": "user", "content": prompt}]
})
代理接受的不是一句句子,而是一串訊息,每個訊息帶有一個角色,這裡只有一個:
"user"。.invoke() 會執行整個迴圈 — 模型讀
問題、決定呼叫 search_internet、Python 執行那個函數,然後結果
回到對話之中。result 保留這次執行的每一則訊息,不只是答案。
把答案讀回來
for message in result["messages"]:
if message.type == "tool":
response = json.loads(message.content)
這次執行裝著三類訊息:我們的問題、模型要求呼叫工具的訊息,以及工具的結果。
畫面只應該顯示第三類,所以迴圈用
message.type == "tool" 跳過另外兩類。
我們需要 json.loads(message.content),原因只有一個。Tavily 的
字典以 JSON 形式寫在 message.content 裡面,而對 Python 來說,
那只是一條長長的字串。json.loads(message.content) 讀取這段文字,
重建出程式其餘部分可以使用的字典。
負責印出的四行與版本 1 相同,所以解釋請看版本 1。
輸出結果
Search result:
Query: What is the population of Hong Kong?
1. Hong Kong Population (2026) - Worldometer (score: 0.92)
https://www.worldometers.info/world-population/china-hong-kong-sar-population
The current population of the Hong Kong Special Administrative Region of the People's Republic of China is 7,371,564 as of Sunday, October 18, 2026, based on Worldometer's elaboration of the latest Un...
2. Hong Kong Population 2026 (score: 0.94)
https://worldpopulationreview.com/countries/hong-kong
### Request Data Please enter your email address to receive this data in your inbox. ## Hong Kong By the Numbers As of 2026, Hong Kong has a total populationof 7,378,602, ranking as the 107th most...
3. Hong Kong Map, History & Population | Study.com (score: 0.93)
https://study.com/academy/lesson/hong-kong-facts-population.html
The population of Hong Kong is 7.5 million. Two million people live in Kowloon, the southern part of the peninsula, and 1 million people live in the northern part of Hong Kong Island, called Victoria ...
...
沒有摘要,沒有「根據搜尋結果,人口大約是 740 萬」。十個結果,跟 Tavily 交回 的完全一樣。代理改變的是由誰提出請求,而不是回來的東西。
完整程式
# RESEARCH, version 2: an AI agent does the search from version 1.
# The same Tavily call becomes a TOOL, and the agent decides to call it.
# return_direct=True means the tool's answer IS the final answer: the model
# does not summarise the results afterwards.
import os
import json
from dotenv import load_dotenv
from tavily import TavilyClient
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent
load_dotenv()
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
tavily_client = TavilyClient(api_key=TAVILY_API_KEY)
@tool(return_direct=True)
def search_internet(query: str):
"""
Search the internet for up-to-date information about the query
and return the full Tavily search response.
"""
response = tavily_client.search(query, max_results=10)
return response
model = ChatOpenAI(
model="deepseek-flash",
api_key=DEEPSEEK_API_KEY,
base_url="https://api.deepseek.com",
temperature=0,
)
agent = create_agent(
model=model,
tools=[search_internet],
system_prompt=(
"You are a helpful assistant. "
"Always call search_internet, using the user's message exactly as the query. "
"Do not rephrase, shorten, translate, or add anything to it."
),
)
prompt = "What is the population of Hong Kong?"
result = agent.invoke({
"messages": [{"role": "user", "content": prompt}]
})
for message in result["messages"]:
if message.type == "tool":
response = json.loads(message.content)
print("Search result:")
print(f"Query: {response['query']}\n")
for i, r in enumerate(response["results"], start=1):
print(f"{i}. {r['title']} (score: {r['score']:.2f})")
print(f" {r['url']}")
print(f" {r['content'][:200].replace(chr(10), ' ')}...\n")
在自己的電腦上執行
下載示範程式
(Folder-AI-Research02.zip)。zip 內有三個檔案:
research02.py(完整腳本)、pyproject.toml 和
README.md。這個版本會呼叫語言模型一次,所以需要 Tavily 金鑰和
DeepSeek 金鑰各一條。
- 在 Visual Studio Code 中開啟這個資料夾。
-
在資料夾裡建立一個名為
.env的檔案,內容有兩行:
Tavily 金鑰可從 Tavily 控制台取得,DeepSeek 金鑰則可從 DeepSeek 控制台取得。使用量由各自的供應商收費,所以執行之前,請先在該處查看 目前的收費條款。TAVILY_API_KEY=your-tavily-key DEEPSEEK_API_KEY=your-deepseek-key - 在終端機逐行執行以下三行:
uv python pin 3.12.10uv syncuv run research02.py - 你應該會看到與版本 1 相同的十個結果。一次模型呼叫需要幾秒鐘。
如果你還未設定好 uv,請先看 如何安裝 Visual Studio Code?,然後看 uv 筆記的 Windows 或 Mac 版本。
限制
- 代理加了一步,不是加了答案。十個結果還是那十個結果。新的 只是:這次由模型選擇工具,而下一步我們可以加入更多工具。
-
模型仍然可能改寫。指示要求原樣使用問題,
temperature=0也令模型較為穩定,但模型始終可能不依指示。請 檢查畫面上印出的查詢,是否就是你輸入的那一條。 - 分數代表相關程度,不是真確程度。與版本 1 相同的提醒:高分 表示網頁與字詞吻合,不代表網頁正確或最新。
- 沒有任何過濾。來十個就印十個,包括那個只得 0.11、幾乎 沒有提到人口的結果。
延伸閱讀
- 如何用 Python 搜尋網頁(Research,版本 1)? — 搜尋本身,沒有代理。
- 如何在 AI 代理中使用 LangChain(ReAct,版本 7)? —
create_agent首次出現的地方。 - LangChain — 文件 — 工具、
create_agent與return_direct。 - Tavily — 文件 —
search呼叫及其回應欄位。