How do multiple AI agents work under a supervisor (ReAct, version 10)?
Version 9 gave the agent eyes: it could read a web page. Version 10 gives it a team. One agent, called the supervisor, is handed three tools — and two of those tools are agents themselves. Ask for a Cantonese version of a page and the supervisor works out that it should read the page first, then translate it, then turn the Chinese into Cantonese. Our code never states that order. The supervisor is told what each tool does, and it decides.
A manager with three workers
-
scrap_web— download a page and return its sentences, numbered. Plain Python, taken from version 9. -
translate_en_to_zh— an agent that translates the numbered English sentences into Traditional Chinese. -
zh_to_cantonese— an agent that rewrites the Chinese sentences into spoken Cantonese, and then lists which sentences changed.
A tool that is itself an agent is sometimes called a worker. The supervisor has no special knowledge of web pages or Cantonese; it only knows that these three tools exist and what each one is for.
How a function becomes a tool
@tool
def scrap_web(url: str) -> str:
"""Download a web page and return its English sentences, one per line, numbered."""
@tool is a label that turns an ordinary function into something
a model can call. The sentence in triple quotes is not decoration: it is
what the supervisor reads when deciding whether this tool fits the request.
A vague description here is a common reason a team of agents misbehaves.
Worker 1: read the page, in plain 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
This is version 9 with one change: instead of printing, it joins the numbered sentences into one piece of text and returns it. That matters, because a tool's answer is handed back to the supervisor, which can then pass it to the next tool.
Worker 2: a translator wrapped as a tool
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 builds an agent, and here tools=[]
means this worker has no tools of its own. Its whole job sits in the
instructions: translate, keep the numbers, keep the names. Narrow
instructions are what make a worker reliable.
The helper function that gives a worker its input
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
An agent does not take a plain sentence. It takes a short conversation: a
list of messages, each with a role, such as "user". This
two-line helper function turns our text into that one-message conversation,
then reads the reply from result["messages"][-1]. In Python,
-1 means the last item in a list, so [-1] picks
the newest message — the agent's answer. Keeping those two jobs in one
helper function lets each tool stay short and readable.
Worker 3: Cantonese, plus a before-and-after list
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])]
The Cantonese editor works exactly like the translator — an agent with
instructions and no tools. What is new is the checking after it. The pattern
^(\d+)\.\s*(.*)$ reads each numbered line into a dictionary,
with the number as the key: it takes 1. 首頁 apart and keeps
1 and 首頁 as a pair.
Read the pattern in six small pieces:
^ means the start of a line.
(\d+) means one or more digits.
\. is the full stop after the number.
\s* is any spaces after that full stop.
(.*) means the rest of the line.
$ means the end of the line.
So every match hands back two things: a number and a sentence.
dict(...) then stores them as key and value. One dictionary
holds the Chinese, one holds the Cantonese, and the list keeps only the
numbers where the two differ. That is how the finished output can say "19 of
30 sentences changed" and quote every change, without a human comparing them
line by line.
The four lines that build that list are easier to read from the middle out.
for number in before walks through the sentence numbers of the
Chinese version, one by one. The if then keeps only the numbers
that also appear in the Cantonese version and whose text is actually
different, so an unchanged sentence is dropped. The two brackets keep the
tests apart: (number in after) is asked first, and only if that
is true is (before[number] != after[number]) asked. For each
number that survives, the first line builds a small two-line entry: the
number and the Chinese sentence, then -> and the Cantonese
sentence. Run that over all 30 sentences and you get the report: only the
sentences that changed, each shown before and after.
The supervisor
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.""",
)
The supervisor has a model (my_model), three tools, and a
system prompt.
What comes out
########## 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
The plan is the interesting part. We never wrote those three names in that order; the supervisor chose them. At the end it prints the Cantonese list and then the changes:
Changed sentences (19 of 30), before -> after:
1. 首頁
-> 主頁
10. 逾三十年來於董事會與課堂之間,將大膽構想轉化為可衡量的成果。
-> 過去三十幾年,喺董事會同課堂之間,將大膽嘅構想變成可以衡量嘅成果。
...
19 of 30 sentences changed: menu labels ("首頁" became "主頁"), formal written Chinese ("他", "的", "沒有") became the spoken forms a Hong Kong reader uses ("佢", "嘅", "冇"), and the untouched 11 were mostly names, URLs and abbreviations that should not change.
The whole program
# 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.
Running it on your own computer
Download the demo program
(Folder-AI-ReAct10.zip). The zip holds three files:
ReAct10.py (the full script), pyproject.toml and
README.md. This version calls a language model three times, so
it needs a DeepSeek key.
- Open the folder in Visual Studio Code.
-
Create a file named
.envin the folder with one line:
A key is available from the DeepSeek console. Usage is billed by the model provider, so check the current pricing terms there before you run it.DEEPSEEK_API_KEY=your-deepseek-key - In the Terminal, run these three lines, one at a time:
uv python pin 3.12.10uv syncuv run ReAct10.py - You should see the request, one block per tool, the plan, and the final answer. Three model calls take a while; give it a minute.
If you have not set up uv yet, start with How to install Visual Studio Code? and then the uv note for Windows or Mac.
Limitations
-
Workers cost money and time. Every agent is a model call,
and a long page is sent three times: once to
translate_en_to_zh, once tozh_to_cantonese, once back to the supervisor. - The supervisor can choose badly. It may skip a tool, call one twice, or pick the wrong one. The plan it prints is your audit trail.
-
The page must be plain HTML. A page built by JavaScript
gives
scrap_webalmost nothing, and the rest of the chain then has nothing to translate.
Further reading
- LangChain documentation —
create_agent, tools and multi-agent patterns. - DeepSeek API documentation — models, keys and pricing.
- How does an AI agent read a web page (ReAct, version 9)? — the code inside
scrap_web. - How to use LangChain in an AI agent (ReAct, version 7)? — where
create_agentfirst appeared in this series.