多個 AI 代理如何在主管之下運作(ReAct,版本 10)?
版本 9 給了代理一雙眼睛:它能讀取網頁。版本 10 給它一個團隊。一個名為主管 的代理,手上得到三個工具 — 而其中兩個工具本身就是代理。你要求一個 網頁的廣東話版本,主管會自己推斷:應該先讀取網頁,然後翻譯,再把中文轉成 廣東話。我們的程式碼從未寫明這個次序。主管只知道每個工具做甚麼,由它自己 決定。
一個主管,三個下屬代理
-
scrap_web— 下載網頁,回傳它的句子, 並加上編號。純 Python,取自版本 9。 -
translate_en_to_zh— 一個代理,把編號的 英文句子翻譯成繁體中文。 -
zh_to_cantonese— 一個代理,把中文句子 改寫成廣東話口語,然後列出哪些句子有改動。
本身是代理的工具,有時稱為下屬代理。主管對網頁和廣東話並無特別認識;它只 知道這三個工具存在,以及每個工具用來做甚麼。
一個函數如何變成工具
@tool
def scrap_web(url: str) -> str:
"""Download a web page and return its English sentences, one per line, numbered."""
@tool 是一個標籤,把普通函數變成模型可以呼叫的東西。三引號裡
的那句話不是裝飾:主管在決定這個工具是否適合這個請求時,讀的就是它。這裡的
描述含糊,是代理團隊出問題的常見原因。
下屬代理 1:用純 Python 讀取網頁
response = requests.get(url, headers={"User-Agent": USER_AGENT}, timeout=10)
soup = BeautifulSoup(response.text, "html.parser")
sentences = []
for element in soup.find_all(["h1", "h2", "h3", "p", "li"]):
text = re.sub(r"\s+", " ", element.get_text(" ", strip=True))
if text:
sentences.extend(re.split(r"(?<=[.!?])\s+", text))
result = "\n".join(f"{number}. {sentence}"
for number, sentence in enumerate(sentences, start=1))
return result
這就是版本 9,只改了一處:它不再印出,而是把編號的句子連成一段文字回傳。 這一點很重要,因為工具的答案會交回主管,主管可以再把它交給下一個工具。
下屬代理 2:包裝成工具的翻譯員
translator_agent = create_agent(
model=my_model,
tools=[],
system_prompt="""You are a professional English to Traditional Chinese (繁體中文) translator.
Translate each numbered sentence into formal written Traditional Chinese.
Keep the same numbers, one sentence per line. Keep names, URLs and abbreviations (e.g. PhD, AI) as they are.
Reply with ONLY the numbered translations.""",
)
return ask_agent(translator_agent, sentences)
create_agent 建立一個代理,這裡 tools=[] 表示這個
下屬代理沒有自己的工具。它全部的任務都寫在指示裡:翻譯、保留編號、保留名稱。
指示越窄,下屬代理就越可靠。
把輸入交給下屬代理的輔助函數
def ask_agent(agent, message):
"""Give a worker agent its input and return its final reply."""
result = agent.invoke({"messages": [{"role": "user", "content": message}]})
return result["messages"][-1].content
代理不接受一句普通句子。它接受的是一段簡短對話:一串訊息,每個訊息帶有一個
角色,例如 "user"。這個兩行的輔助函數把我們的文字變成那段只有
一則訊息的對話,然後從 result["messages"][-1] 讀出回覆。在 Python
裡,-1 表示清單中最後一項,所以 [-1] 取到最新的
訊息 — 也就是代理的答案。把這兩件事收在同一個輔助函數裡,每個工具就能
保持簡短易讀。
下屬代理 3:廣東話,加上前後對照清單
before = dict(re.findall(r"^(\d+)\.\s*(.*)$", sentences, re.M))
after = dict(re.findall(r"^(\d+)\.\s*(.*)$", result, re.M))
changes = [f"{number}. {before[number]}\n -> {after[number]}"
for number in before
if (number in after) and (before[number] != after[number])]
廣東話編輯的工作方式和翻譯員完全相同 — 一個有指示、沒有工具的代理。
新的是之後的核對。樣式
^(\d+)\.\s*(.*)$ 把每一行編號讀進一個字典,
以編號作為鍵:它把 1. 首頁 拆開,把 1 和
首頁 留成一對。
把這個樣式拆成六小塊來看:
^ 表示一行的開始。
(\d+) 表示一個或多個數字。
\. 是編號後面的句點。
\s* 是那個句點之後的空格。
(.*) 表示這一行其餘的內容。
$ 表示一行的結束。
所以每次配對都會交回兩樣東西:一個編號和一句句子。
dict(...) 把它們存成鍵和值。一個字典裝中文,一個裝廣東話,而
清單只留下兩者不同的編號。這樣最後的輸出就可以說「30 句之中有 19 句改了」,
並逐項引用改動,不必由人手逐行對照。
建立這個清單的四行,由中間向外讀會比較容易。
for number in before 逐個走過中文版的句子編號。
if 然後只留下同時出現在廣東話版、而文字真的有
分別的編號,所以沒有改動的句子會被丟棄。兩個括號把兩個測試分開:先問
(number in after),只有結果為真時,才問
(before[number] != after[number])。對於每一個
通過的編號,第一行會建立一個兩行的小條目:編號和中文句子,然後是
-> 和廣東話句子。把這個做法套用到全部 30 句,你就得到報告:
只有改動過的句子,每句都顯示改動前和改動後。
主管
supervisor = create_agent(
model=my_model,
tools=[scrap_web, translate_en_to_zh, zh_to_cantonese],
system_prompt="""You are a supervisor managing a team of tools.
Plan which tools are needed for the user's request, and call them in a sensible order.
When you pass one tool's output to the next tool, pass ALL of it, exactly as it is: do not shorten or change it.
At the end, reply with the final numbered sentences, followed by the list of changed sentences if a tool gave one.""",
)
主管有一個模型(my_model)、三個工具和一個系統提示詞。
輸出結果
########## SUPERVISOR gets the request ##########
Give me the Cantonese version of every sentence on https://pongyuenlam.github.io/biography.html
########## TOOL: scrap_web ##########
1. Home
2. Biography
...
########## SUPERVISOR's plan (tools called, in order) ##########
- scrap_web
- translate_en_to_zh
- zh_to_cantonese
有趣的是那份計劃。我們從未按那個次序寫下這三個名稱;是主管自己選的。最後 它印出廣東話清單,然後是改動:
Changed sentences (19 of 30), before -> after:
1. 首頁
-> 主頁
10. 逾三十年來於董事會與課堂之間,將大膽構想轉化為可衡量的成果。
-> 過去三十幾年,喺董事會同課堂之間,將大膽嘅構想變成可以衡量嘅成果。
...
30 句之中有 19 句改了:選單標籤(「首頁」變成「主頁」)、書面中文(「他」、 「的」、「沒有」)變成香港讀者會用的口語(「佢」、「嘅」、「冇」),而未 改動的 11 句,大多是名稱、網址和縮寫,本來就不應該改。
完整程式
# MULTIPLE AGENTS with a SUPERVISOR (manager), built with LangChain.
# The supervisor is an agent whose tools are other workers:
# 1) scrap_web -> reads a web page and lists every sentence (plain Python, code from ReAct09.py)
# 2) translate_en_to_zh -> a translator AGENT, wrapped as a tool
# 3) zh_to_cantonese -> a Cantonese editor AGENT, wrapped as a tool
# We do NOT fix the order in our code: the supervisor (the AI) decides which tool to call, and when.
import os
import re
import requests
from bs4 import BeautifulSoup
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent
from dotenv import load_dotenv
load_dotenv()
URL = "https://pongyuenlam.github.io/biography.html"
USER_AGENT = "ReAct10-class-demo" # tells the website who is visiting
my_model = ChatOpenAI(
model="deepseek-flash",
api_key=os.environ.get('DEEPSEEK_API_KEY'),
base_url="https://api.deepseek.com")
def ask_agent(agent, message):
"""Give a worker agent its input and return its final reply."""
result = agent.invoke({"messages": [{"role": "user", "content": message}]})
return result["messages"][-1].content
# ---- Three tools for the supervisor ----
@tool
def scrap_web(url: str) -> str:
"""Download a web page and return its English sentences, one per line, numbered."""
response = requests.get(url, headers={"User-Agent": USER_AGENT}, timeout=10)
soup = BeautifulSoup(response.text, "html.parser")
sentences = []
for element in soup.find_all(["h1", "h2", "h3", "p", "li"]):
text = re.sub(r"\s+", " ", element.get_text(" ", strip=True))
if text:
sentences.extend(re.split(r"(?<=[.!?])\s+", text))
result = "\n".join(f"{number}. {sentence}"
for number, sentence in enumerate(sentences, start=1))
print(f"\n########## TOOL: scrap_web ##########\n{result}")
return result
@tool
def translate_en_to_zh(sentences: str) -> str:
"""Translate numbered English sentences into numbered Traditional Chinese sentences."""
# A worker agent: same model, its own job (system_prompt), no tools
translator_agent = create_agent(
model=my_model,
tools=[],
system_prompt="""You are a professional English to Traditional Chinese (繁體中文) translator.
Translate each numbered sentence into formal written Traditional Chinese.
Keep the same numbers, one sentence per line. Keep names, URLs and abbreviations (e.g. PhD, AI) as they are.
Reply with ONLY the numbered translations.""",
)
result = ask_agent(translator_agent, sentences)
print(f"\n########## TOOL: translate_en_to_zh ##########\n{result}")
return result
@tool
def zh_to_cantonese(sentences: str) -> str:
"""Rewrite numbered Traditional Chinese sentences into numbered spoken Cantonese sentences,
then list the sentences that changed (before -> after)."""
# A worker agent: same model, its own job (system_prompt), no tools
cantonese_agent = create_agent(
model=my_model,
tools=[],
system_prompt="""You are a Hong Kong Cantonese editor.
Rewrite each numbered Traditional Chinese sentence into natural spoken Cantonese (廣東話口語),
the way a Hong Kong person would say it, e.g. 是 -> 係, 的 -> 嘅, 他 -> 佢, 沒有 -> 冇.
Keep the same numbers, one sentence per line. Keep names, URLs and abbreviations as they are.
Reply with ONLY the numbered Cantonese sentences.""",
)
result = ask_agent(cantonese_agent, sentences)
# Another list: compare before (Chinese) and after (Cantonese), sentence by sentence, using the numbers
before = dict(re.findall(r"^(\d+)\.\s*(.*)$", sentences, re.M)) # {"1": "他是...", "2": ...}
after = dict(re.findall(r"^(\d+)\.\s*(.*)$", result, re.M))
changes = [f"{number}. {before[number]}\n -> {after[number]}"
for number in before
if (number in after) and (before[number] != after[number])]
result = (result + f"\n\nChanged sentences ({len(changes)} of {len(before)}), before -> after:\n"
+ "\n".join(changes))
print(f"\n########## TOOL: zh_to_cantonese ##########\n{result}")
return result
# ---- The supervisor: decides which tools to use, and in what order ----
supervisor = create_agent(
model=my_model,
tools=[scrap_web, translate_en_to_zh, zh_to_cantonese],
system_prompt="""You are a supervisor managing a team of tools.
Plan which tools are needed for the user's request, and call them in a sensible order.
When you pass one tool's output to the next tool, pass ALL of it, exactly as it is: do not shorten or change it.
At the end, reply with the final numbered sentences, followed by the list of changed sentences if a tool gave one.""",
)
request = f"Give me the Cantonese version of every sentence on {URL}"
print(f"########## SUPERVISOR gets the request ##########\n{request}")
result = supervisor.invoke({"messages": [{"role": "user", "content": request}]})
# Show the plan the supervisor made: which tools it called, in order
print("\n########## SUPERVISOR's plan (tools called, in order) ##########")
for message in result["messages"]:
for call in getattr(message, "tool_calls", None) or []:
print(f"- {call['name']}")
print("\n########## SUPERVISOR's final answer ##########")
print(result["messages"][-1].content)
# Try it: change the request to "Give me the Traditional Chinese version of every sentence on ..."
# Does the supervisor still call zh_to_cantonese? It should not - the AI chooses the tools.
在自己的電腦上執行
下載示範程式
(Folder-AI-ReAct10.zip)。zip 內有三個檔案:
ReAct10.py(完整腳本)、pyproject.toml 和
README.md。這個版本會呼叫語言模型三次,所以需要 DeepSeek
金鑰。
- 在 Visual Studio Code 中開啟這個資料夾。
-
在資料夾裡建立一個名為
.env的檔案,內容只有一行:
金鑰可從 DeepSeek 控制台取得。使用量由模型供應商收費,所以執行之前,請先在該處查看 目前的收費條款。DEEPSEEK_API_KEY=your-deepseek-key - 在終端機逐行執行以下三行:
uv python pin 3.12.10uv syncuv run ReAct10.py - 你應該會看到請求、每個工具一個區塊、計劃,以及最後的答案。三次模型呼叫 需要一點時間,給它一分鐘。
如果你還未設定好 uv,請先看 如何安裝 Visual Studio Code?,然後看 uv 筆記的 Windows 或 Mac 版本。
限制
-
下屬代理既花錢也花時間。每個代理都是一次模型呼叫,而一個
長網頁會被送三次:一次給
translate_en_to_zh,一次給zh_to_cantonese,一次回到主管。 - 主管可能會選錯。它可能跳過一個工具、把同一個工具呼叫兩次, 或者選錯工具。它印出的計劃就是你的稽核記錄。
-
網頁必須是純 HTML。由 JavaScript 建立的網頁,能給
scrap_web的幾乎是零,整條鏈之後就沒有東西可翻譯。
延伸閱讀
- LangChain — 文件 —
create_agent、工具與多代理模式。 - DeepSeek API — 文件 — 模型、金鑰與收費。
- AI 代理如何讀取網頁(ReAct,版本 9)? —
scrap_web裡的程式碼。 - 如何在 AI 代理中使用 LangChain?(ReAct,版本 7) —
create_agent在本系列首次出現的地方。