如何使用 AI 代理撰寫附有尾註的草稿(Research,版本 4)?
上一個版本用了兩個工具: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 金鑰。
- 在 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 research04.py - 你應該會看到三個工具先後印出:搜尋的十個結果、
generate_draft的七個,然後是write_draft的草稿。整個執行需要幾秒鐘。
如果你還未設定好 uv,請先看 如何安裝 Visual Studio Code?,然後看 uv 筆記的 Windows 或 Mac 版本。
限制
- 這是草稿,不是報告。結果是一串按結果次序排列的引文句子。 句子之間沒有任何連接,也沒有說明該相信哪個數字。
- 數字仍然互相矛盾。七句之中有六句給出人口數字,由 737.1 萬 到 750 萬不等。草稿對此很誠實,但它無法解決這個問題。
- 照抄不等於核實。逐字照抄的句子仍然可以是過時的,而模型 也可能選中一句對問題很貼題、但內容有誤導性的句子。
- 位置決定配對。句子是按次序與結果配對的。如果模型跳過一個 結果,七個結果只送來六句,那麼由那一點開始,之後每個尾註都會掛錯網頁。
- 空字串可以藏起一個結果。一個有有用數字但沒有完整句子的 網頁,完全不會貢獻任何東西,而草稿也不會說它被丟棄了。
延伸閱讀
- 如何使用 AI 代理挑選有用的搜尋結果(Research,版本 3)? — 七個結果的來源。
- 如何使用 AI 代理在網上搜尋(Research,版本 2)? — 這個版本所建基的工具。
- LangChain — 文件 — 工具、
return_direct與create_agent。 - Tavily — 文件 —
search呼叫及其回應欄位。