English 繁體中文 简体中文

如何使用 AI 代理挑选有用的搜索结果(Research,版本 3)?

林邦源博士 · AI 笔记 · 2026 年 11 月 9 日 · 约 4 分钟阅读

一次搜索会返回十个结果,其中有些并不值得留。有一页几乎没有提到人口,另一页 则是十年前的。这个版本加入第二个工具,它的全部工作就是做这个判断。

代理现在有两个工具,而系统提示词固定了顺序:先 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

七个,不是十个。消失的三个是:

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 密钥。

  1. 在 Visual Studio Code 中打开这个文件夹。
  2. 在文件夹里创建一个名为 .env 的文件,内容有两行:
    TAVILY_API_KEY=your-tavily-key
    DEEPSEEK_API_KEY=your-deepseek-key
    Tavily 密钥可以从 Tavily 控制台获取,DeepSeek 密钥则从 DeepSeek 控制台获取。用量由各提供商计费,所以运行之前,请先在那里查看 当前的收费条款。
  3. 在终端里逐行运行以下三行:
    uv python pin 3.12.10
    uv sync
    uv run research03.py
  4. 你应该会看到两个工具先后打印:搜索的十个结果,然后是 generate_draft 的七个。一次模型调用需要几秒钟。

如果你还没有配置好 uv,请先看 如何安装 Visual Studio Code?,然后看 uv 笔记的 Windows 或 Mac 版本。

局限

延伸阅读