如何使用 AI 代理挑選有用的搜尋結果(Research,版本 3)?
一次搜尋會回傳十個結果,其中有些並不值得留下。有一頁幾乎完全沒有提到人口, 另一頁則是十年前的。這個版本加入第二個工具,它的全部工作就是作出這個判斷。
代理現在有兩個工具,而系統提示詞固定了次序:先
search_internet,然後把結果交給
generate_draft。搜尋工具的做法和之前完全一樣。
generate_draft 讀取已儲存的結果,只留下符合它
規則的那些。
一個存放搜尋結果的地方
# Keeps the latest search response so generate_draft can use it
last_search = {}
工具是各自獨立的函數。一個工具完成之後,它的區域變數就會消失。如果篩選 工具在搜尋之後才被呼叫,它怎能看見搜尋找到的東西?
答案是一個存在於兩個工具之外的變數:
last_search。搜尋工具把它的回應寫進去,而
篩選工具就從那裡讀取。
工具一:搜尋,以及一行新程式碼
@tool
def search_internet(query: str):
"""
Search the internet for up-to-date information about the query
and return the full Tavily search response.
"""
global last_search
response = tavily_client.search(query, max_results=10)
last_search = response
return response
這裡有三行值得留意。最需要解釋的是
global last_search。在函數裡面,賦值通常會
建立一個全新的區域變數:last_search = response
只會填滿那份區域副本,函數結束時就把它丟掉。把
last_search 宣告為 global,就是告訴 Python:
這就是整個程式執行期間共用的同一個變數,而不是在函數裡面新造的一個。
接著 last_search = response 把十個結果存進那個
共用變數,而 return response 也同時把它們送回
代理,因為模型仍然需要看到回傳了甚麼。
工具二:generate_draft 只保留有用的結果
@tool(return_direct=True)
def generate_draft():
"""
Go through the results from the latest search_internet call.
Keep results with a score of 0.5 or higher, but never keep Wikipedia.
Return the selected results.
"""
selected = []
for r in last_search.get("results", []):
if r["score"] >= 0.5 and "wikipedia.org" not in r["url"]:
selected.append(r)
return {"query": last_search.get("query"), "results": selected}
這段 docstring 用平白的英文把一切都說清楚,這是刻意的:模型在決定這個工具 是否合用、以及它做甚麼的時候,讀的就是 docstring。
這個篩選工具不接受任何輸入。它需要的一切都在
last_search 裡面。它建立一個空清單,逐個走過
十個結果,只有當兩個條件同時成立時,才保留一個結果。
規則寫成一個 if,兩部分由
and 連接。第一部分
r["score"] >= 0.5,保留搜尋引擎評為相關的
網頁。第二部分
"wikipedia.org" not in r["url"],則無論維基百科
得分多高都把它剔除。兩個條件同時成立,結果才算過關,然後
selected.append(r) 把它加進清單。
剔除維基百科是刻意的選擇。哈佛的 《維基百科有甚麼問題?》 這樣說:
當你做學術研究時,使用維基百科應該極之謹慎。正如它自己的免責聲明所言, 維基百科上的資訊由任何想貼文的人提供,而貼文者的專業知識並不在考慮之 列。讀者可能正在閱讀過時的資訊,又或者是由某個並非該領域專家的人所貼的 內容 — 甚至是希望提供錯誤資訊的人。雖然維基百科的編輯確實會糾正 錯誤資訊,但觀察者發現他們並非全部都捉得到 — 至少不是即時。有時 不準確的資訊是故意貼上維基百科的,作為惡作劇。在一些有詳細記錄的個案 中,這些不準確的資訊會繼續流傳,因為人們把它從維基百科拿來,用在書籍和 文章裡。
哈佛學院寫作課程,《維基百科有甚麼問題?》
AI 代理
agent = create_agent(
model=my_model,
tools=[search_internet, generate_draft],
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. "
"Then call generate_draft to select the useful results."
),
)
系統提示詞現在多了一句:「然後呼叫
generate_draft 挑選有用的結果。」模型讀取問題、
呼叫搜尋、收到十個結果,然後對它們呼叫
generate_draft。
輸出結果
螢幕會先後印出兩個工具。首先是搜尋,帶著全部十個結果:
Tool: search_internet
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...
...
然後是 generate_draft,只有它選中的結果。為了讓
這一頁保持簡短,這裡略去每個結果下面的內容行;程式本身會印出來。
Tool: generate_draft
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
2. Hong Kong Population 2026 (score: 0.94)
https://worldpopulationreview.com/countries/hong-kong
3. Hong Kong Map, History & Population | Study.com (score: 0.93)
https://study.com/academy/lesson/hong-kong-facts-population.html
4. Hong Kong Population (1950-2026) (score: 0.92)
https://www.macrotrends.net/global-metrics/countries/hkg/hong-kong/population
5. Hong Kong - Population and Demography Country Profile | Our World in Data (score: 0.91)
https://ourworldindata.org/profile/population-demography/hong-kong
6. GovHK: Hong Kong – the Facts (score: 0.85)
https://www.gov.hk/en/about/abouthk/facts.htm
7. Race Relations Unit - Information Centre - Demographics (score: 0.78)
https://www.had.gov.hk/rru/en/info/demographics.htm
七個,不是十個。消失的三個是:
- 維基百科(分數 0.92)— 被網址規則擋在外面,即使它的分數很高。
- 世界銀行(分數 0.39)— 低於 0.5 這條線。
- 人口推算(分數 0.11)— 同樣低於這條線。
generate_draft 移除了一些結果,其餘的完全沒有
改動,所以數字和連結都和搜尋服務回傳時一模一樣。
完整程式
# RESEARCH, version 3: two tools, one after the other.
# Tool 1 searches. Tool 2 filters: score 0.5 or higher, never Wikipedia.
# last_search lets the second tool see what the first one found.
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)
# Keeps the latest search response so generate_draft can use it
last_search = {}
@tool
def search_internet(query: str):
"""
Search the internet for up-to-date information about the query
and return the full Tavily search response.
"""
global last_search
response = tavily_client.search(query, max_results=10)
last_search = response
return response
@tool(return_direct=True)
def generate_draft():
"""
Go through the results from the latest search_internet call.
Keep results with a score of 0.5 or higher, but never keep Wikipedia.
Return the selected results.
"""
selected = []
for r in last_search.get("results", []):
if r["score"] >= 0.5 and "wikipedia.org" not in r["url"]:
selected.append(r)
return {"query": last_search.get("query"), "results": selected}
my_model = ChatOpenAI(
model="deepseek-flash",
api_key=DEEPSEEK_API_KEY,
base_url="https://api.deepseek.com",
temperature=0,
)
agent = create_agent(
model=my_model,
tools=[search_internet, generate_draft],
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. "
"Then call generate_draft to select the useful results."
),
)
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(f"Tool: {message.name}")
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-Research03.zip)。zip 內有三個檔案:
research03.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 research03.py - 你應該會看到兩個工具先後印出:搜尋的十個結果,然後是
generate_draft的七個。一次模型呼叫需要幾秒鐘。
如果你還未設定好 uv,請先看 如何安裝 Visual Studio Code?,然後看 uv 筆記的 Windows 或 Mac 版本。
限制
- 這條規則只是為了示範而寫得簡單。0.5 這個分數只是例子。 把它調高就會留下更少結果;調低就會留下更多。一個有用但只得 0.49 分的 網頁,仍然會被丟掉;而通過測試的網頁,也仍然可能是錯的或過時的。
-
模型仍然必須遵守次序。提示詞要求先
search_internet,後generate_draft。模型可以偏離指示,所以你要 檢查的是印出來的輸出。 -
兩個工具透過一個共用變數溝通。
last_search只保存最近一次搜尋。如果之後再 執行一次搜尋,篩選工具就會悄悄地用上新的結果。 - 保留來源仍然是人的工作。七個結果比十個少,但還未讀過 任何一個。在它們之間作選擇,是下一個版本的工作。
延伸閱讀
- 如何使用 AI 代理在網上搜尋(Research,版本 2)? — 這個版本由它發展而來的單一工具代理。
- 如何用 Python 搜尋網頁(Research,版本 1)? — 搜尋本身,沒有代理。
- LangChain — 文件 — 工具與
create_agent。 - Tavily — 文件 —
search呼叫及其回應欄位。