English 繁體中文 简体中文

如何使用 AI 代理撰写附有尾注的草稿(Research,版本 4)?

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

上一个版本用了两个工具:search_internet 带回 十个结果,generate_draft 留下其中七个。这个版本 加入第三个工具,把这七个结果变成一份简短草稿,每一句都配一个编号尾注。

关键的字眼是照抄。这份草稿不是由模型撰写的摘要。里面每一句都是从 某个网页逐字取出,而尾注会说明它来自哪一页。这是一个你可以核实的承诺。

第二个存放结果的地方

之前两个版本只用了一个共用变量。这个版本需要第二个,因为新工具处理的是筛选后 留下的结果,而不是搜索返回的那十个。

# Keeps the latest search response so generate_draft can use it
last_search = {}
# Keeps the results selected by generate_draft so write_draft can use them
selected_results = []

原因和之前一样。每个工具都是独立的函数,在一个函数里面建立的变量,会在该函数 结束时消失。两个变量都放在函数之外,所以一个工具可以把东西留在那里,下一个 工具再把它拿走。

工具三:write_draft

return_direct=True 放在“结果就是最终答案”的 那个工具上。这里就是草稿,所以 write_draft 一完成,整个运行就结束。

@tool(return_direct=True)
def write_draft(sentences: list[str]):
    """
    Write a draft with endnotes from the results of generate_draft.
    sentences: one sentence per result from generate_draft, in the same order.
    Each sentence must be copied exactly from that result's content, and be
    the sentence closest in meaning to the user's query.
    Use an empty string "" for a result that has no complete sentence.
    """

看看这个工具收到什么:sentences: list[str], 一个文本列表。这个工具从不打开网页,也从不读取搜索结果。那部分是模型做的, 它只把选好的句子交过来。

这样分工是故意的。挑选最接近问题意思的句子是一个判断,而模型擅长判断。连接 文字、编号尾注、跳过空白条目,是没有判断成分的精确工作,Python 从不会做错。 各自做好自己擅长的事。

模型是从 docstring 得知规则的:每个保留的结果一句、顺序相同、逐字照抄、 选最接近问题意思的一句,而当某页没有完整句子可提供时,就用 ""。

工具内部

    s = ""
    endnotes = ""
    endnote_num = 1
    for sentence, r in zip(sentences, selected_results):
        if sentence.strip() == "":
            continue  # skip results with no complete sentence
        s = s + sentence + "[" + str(endnote_num) + "] "
        endnotes = endnotes + f"[{endnote_num}] {r['url']}\n"
        endnote_num = endnote_num + 1

    s = s + "\n\nEndnotes:\n" + endnotes

    return s

首先建立三样空东西:草稿 s、尾注列表,以及 一个从 1 开始的计数器。

zip 把两个列表并排走过。第一次交出第一句和 第一个保留的结果,第二次交出各自第二项,如此类推。这就是为什么要告诉模型 保持相同顺序:配对是按位置做的,不是靠比对任何东西。

if 负责抓住空字符串。 strip() 会先去掉空格,所以只有空格的句子也 算作空白。配对成功时,continue 会跳到下一对, 而循环体其余部分就跳过,所以不会浪费任何尾注编号。这就是为什么七个保留的 结果,可以产生少于七个尾注。

下一行建立草稿中的一句:先是文字,然后是方括号里的编号,然后是一个空格。 str() 把计数器变成文字,因为数字不能直接粘在 字符串上。结尾只加一个空格,所以输出时所有句子都出现在同一长行里。

尾注那一行用 f-string,{r['url']} 填入对应结果 的链接。结尾加上换行,所以每个尾注各自占一行。

最后一步在句子之后加上一个空行、标题 Endnotes: 和整份尾注列表,然后返回完成的草稿。

AI 代理

agent = create_agent(
    model=my_model,
    tools=[search_internet, generate_draft, write_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. "
        "Then go through each sentence in each selected result, pick the one sentence "
        "closest in meaning to the user's query, and copy it exactly. "
        "A complete sentence has a subject and a verb and ends with a full stop; "
        "table rows, headings, menus and fragments are not complete sentences. "
        "If a result has no complete sentence, use an empty string \"\" for it. "
        "Call write_draft with these sentences in the same order as the results."
    ),
)

工具列表现在有 search_internet、 generate_draft 和 write_draft,而提示词指示模型去做这些工作。

新增的句子中有两句值得注意。“逐字照抄”堵住了改写:改写过的句子看起来更顺, 但更难追溯回原来的网页。而完整句子的定义之所以重要,是因为网页充满了不是 句子的东西 —— 标题、菜单项、表格行、说到一半就中断的片段。

输出结果

屏幕会打印三个工具区块:search_internet、 generate_draft 和 write_draft,按这个顺序。

Tool: write_draft

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 United Nations data 1.[1] As of 2026, Hong Kong has a total population of 7,378,602, ranking as the 107th most populous nation inthe world.[2] The population of Hong Kong is 7.5 million.[3] Total current population for Hong Kong in 2026 is 7,500,962, a 0.02% increase from 2025.[4] In 2023, the estimated population of Hong Kong was 7.443 million.[5] Hong Kong's population was approximately 7.50 million in mid-2025.[6] The 2021 Population Census found (by way of self-identification) that there were about 619,568 non-Chinese people in Hong Kong, or about 8.4% of the population.[7] 

Endnotes:
[1] https://www.worldometers.info/world-population/china-hong-kong-sar-population
[2] https://worldpopulationreview.com/countries/hong-kong
[3] https://study.com/academy/lesson/hong-kong-facts-population.html
[4] https://www.macrotrends.net/global-metrics/countries/hkg/hong-kong/population
[5] https://ourworldindata.org/profile/population-demography/hong-kong
[6] https://www.gov.hk/en/about/abouthk/facts.htm
[7] https://www.had.gov.hk/rru/en/info/demographics.htm

七句、七个尾注,每一句都可以追溯回某个网页。句中的数字并不一致:7,371,564、 7,378,602、750 万、7,500,962、744.3 万和 750 万。这不是程序错误。这正是那 七个网页实际说的,而草稿拒绝用平均数把这些分歧藏起来。第七句是例外:它讲的 是非华裔人口所占的比例,所以本身没有总数。

有一句值得再看一眼。尾注 [5] 标的是 2023 年,但上一段打印的那个结果预览, 完全没有提到 2023。原因是程序只打印每个结果的头 200 个字符,而模型读的是 整页文字。你在屏幕上看到的是预览;模型用来挑选的内容要长得多。

完整程序

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 = {}
# Keeps the results selected by generate_draft so write_draft can use them
selected_results = []

@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
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.
    """
    global 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)

    selected_results = selected
    return {"query": last_search.get("query"), "results": selected}


@tool(return_direct=True)
def write_draft(sentences: list[str]):
    """
    Write a draft with endnotes from the results of generate_draft.
    sentences: one sentence per result from generate_draft, in the same order.
    Each sentence must be copied exactly from that result's content, and be
    the sentence closest in meaning to the user's query.
    Use an empty string "" for a result that has no complete sentence.
    """
    s = ""
    endnotes = ""
    endnote_num = 1
    for sentence, r in zip(sentences, selected_results):
        if sentence.strip() == "":
            continue  # skip results with no complete sentence
        s = s + sentence + "[" + str(endnote_num) + "] "
        endnotes = endnotes + f"[{endnote_num}] {r['url']}\n"
        endnote_num = endnote_num + 1

    s = s + "\n\nEndnotes:\n" + endnotes

    return s


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, write_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. "
        "Then go through each sentence in each selected result, pick the one sentence "
        "closest in meaning to the user's query, and copy it exactly. "
        "A complete sentence has a subject and a verb and ends with a full stop; "
        "table rows, headings, menus and fragments are not complete sentences. "
        "If a result has no complete sentence, use an empty string \"\" for it. "
        "Call write_draft with these sentences in the same order as the 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" and message.name == "write_draft":
        print(f"Tool: {message.name}\n")
        print(message.content)
    elif 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-Research04.zip)。zip 里有三个文件: research04.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 research04.py
  4. 你应该会看到三个工具先后打印:搜索的十个结果、 generate_draft 的七个,然后是 write_draft 的草稿。整个运行需要几秒钟。

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

局限

延伸阅读