English 繁體中文 简体中文

如何使用 AI 代理搜索网页(Research,版本 2)?

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

网页搜索是一项服务。你把问题发给 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 密钥各一条。

  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 research02.py
  4. 你应该会看到与版本 1 相同的十个结果。一次模型调用需要几秒钟。

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

局限

延伸阅读