Supervisor and Worker Agents in LangGraph: One Boss, Three Workers, One Shared State and a Stop Rule in Plain Code
A supervisor sends a topic to a researcher, a writer and a reviewer, and every worker reports back to it. The reviewer says REVISE once and APPROVE the second time, so the run ends in 2 rounds; a reviewer that never approves is stopped at 3 rounds by a plain-Python rule.
What you will learn
- Build a supervisor node that picks the next worker from the shared state
- Wire every worker back to the supervisor with one loop of edges
- Keep the stop rule (approved or max rounds) in plain Python, not in the model
- Handle a reviewer that never approves and a model that returns an unknown name
Before you start
- LangGraph Nodes, Edges and State
- Multi-Agent Patterns: Hub and Spoke
Some jobs need several steps by different specialists: someone finds the facts, someone writes, someone checks. In the supervisor pattern, one agent, the supervisor, never does the work itself. It reads the shared state and decides who works next. Every worker reports back to it when done, and the supervisor also decides when the job is finished.
We'll build a small team in LangGraph: a supervisor and three workers (researcher, writer, reviewer). Everything runs on a stand-in test model with scripted replies, so you need no API key.
Think of a newsroom
A story has to be researched, written and checked before it is printed. The editor doesn't write anything. The editor only decides who gets the story folder next.
- The editor sends the folder to the reporter, who adds the facts.
- It comes back to the editor and goes to the writer, who writes a short draft.
- Back to the editor, and on to the sub-editor, who says "revise".
- The editor sends it to the writer once more, then to the sub-editor again. This time it is approved, and the editor sends it to print.
Nobody hands the folder straight to the next desk. It always goes back to the editor. In code, the editor is the supervisor, the three desks are the workers and the folder is the shared state.
The shared state: one story folder
team.py starts with the state. TeamState is a TypedDict with named slots for the topic, notes, draft and feedback, plus three slots that keep score: approved, rounds and next (the name of the next worker).
import operator
from typing import Annotated, TypedDict
from langgraph.graph import END, START, StateGraph
from models import get_model
WORKERS = ["researcher", "writer", "reviewer"]
MAX_ROUNDS = 3
class TeamState(TypedDict):
topic: str
notes: str
draft: str
feedback: str
approved: bool
rounds: int
next: str
log: Annotated[list[str], operator.add]
def new_state(topic):
return {"topic": topic, "notes": "", "draft": "", "feedback": "",
"approved": False, "rounds": 0, "next": "", "log": []}
The log slot has a small trick. It is a list with operator.add as its reducer, so each worker adds one line and nobody replaces the whole list. Every other slot is simply overwritten by whoever returns it.
One factory for every model
Every role needs a model, and all four come from one function, get_model in models.py. With USE_TEST_MODEL=1 (the default) it builds a GenericFakeChatModel that hands out the scripted replies for that role, one by one. Set it to 0 and it builds a real chat model from MODEL_NAME in your .env.
def get_model(role, scenario="normal"):
if os.getenv("USE_TEST_MODEL", "1") == "1":
replies = (AIMessage(content=text) for text in SCRIPTS[scenario][role])
return GenericFakeChatModel(messages=replies)
from langchain.chat_models import init_chat_model
return init_chat_model(os.environ["MODEL_NAME"])
In the "normal" script the reviewer's first reply is a REVISE and its second is an APPROVE. Only get_model changes when you switch to a real model. The graph, the state and the tests stay the same.
The supervisor: stop rule first, model second
def supervisor(state):
if state["approved"]:
return {"next": "FINISH", "log": ["supervisor: FINISH (approved)"]}
if state["rounds"] >= MAX_ROUNDS:
return {"next": "FINISH", "log": ["supervisor: FINISH (max rounds)"]}
brief = f"Topic: {state['topic']}. Notes: {bool(state['notes'])}."
ask = [("system", "Pick the next worker."), ("human", brief)]
pick = boss.invoke(ask).content.strip()
if pick not in WORKERS:
return {"next": "FINISH", "log": [f"supervisor: FINISH (unknown {pick})"]}
return {"next": pick, "log": [f"supervisor: send to {pick}"]}
Read it top to bottom:
- If the work is approved, finish.
- If the rounds have reached
MAX_ROUNDS, finish. This decision is plain Python, and the model never gets a say in it. - Only then ask the model, which gives back a name such as
writer. - Check that name against
WORKERS. If the model says something strange, like "banana", the run finishes safely instead of crashing or wandering off.
Workers return only what they changed
A worker is a plain Python function. It reads what it needs from the state and returns only the slots it changed. The graph merges that into the shared state.
def researcher(state):
ask = [("system", "Collect short facts."), ("human", state["topic"])]
return {"notes": reporter.invoke(ask).content,
"log": ["researcher: wrote notes"]}
def writer(state):
task = f"Notes: {state['notes']} Feedback: {state['feedback']}"
ask = [("system", "Write a two-sentence brief."), ("human", task)]
return {"draft": author.invoke(ask).content,
"log": ["writer: wrote draft"]}
def reviewer(state):
ask = [("system", "Reply APPROVE or REVISE: reason."),
("human", state["draft"])]
verdict = editor.invoke(ask).content
return {"feedback": verdict, "approved": verdict.startswith("APPROVE"),
"rounds": state["rounds"] + 1,
"log": ["reviewer: " + verdict.split(":")[0]]}
The writer reads the feedback slot, so the reviewer's reason ("Say who should be invited. The draft does not.") reaches the next draft. The reviewer is also the one that counts rounds, so a round means one review.
The code draws the graph
builder = StateGraph(TeamState)
builder.add_node("supervisor", supervisor)
builder.add_node("researcher", researcher)
builder.add_node("writer", writer)
builder.add_node("reviewer", reviewer)
builder.add_edge(START, "supervisor")
builder.add_conditional_edges("supervisor", lambda s: s["next"],
{"researcher": "researcher", "writer": "writer",
"reviewer": "reviewer", "FINISH": END})
for name in WORKERS:
builder.add_edge(name, "supervisor")
return builder.compile()
add_conditional_edges is the fork: it reads next and goes to that worker, or to END on FINISH. The for loop draws the arrows that make this a supervisor pattern: every worker goes back to the supervisor.
One team run
main.py streams the graph with stream_mode="values", so it gets the whole state after each step, and prints one line per worker step. The topic is "How can a small team spend less time in meetings?".
def run_team(scenario, topic=TOPIC):
graph = make_team(scenario)
start = new_state(topic)
for state in graph.stream(start, stream_mode="values"):
yield state
--- normal run ---
researcher: wrote notes rounds=0 approved=False
writer: wrote draft rounds=0 approved=False
reviewer: REVISE rounds=1 approved=False
writer: wrote draft rounds=1 approved=False
reviewer: APPROVE rounds=2 approved=True
supervisor: FINISH (approved) rounds=2 approved=True
Draft: Meetings eat the week. Replace status meetings with a written update, give every meeting an agenda and an end time, and invite only the people who must decide.
The first draft missed one of the three ideas from the notes. The reviewer said REVISE, the feedback went into the state, and the second draft added "invite only the people who must decide". On the next visit the supervisor's stop rule saw approved and ended the graph after 2 rounds.
A reviewer who never approves
The "stubborn" script makes the reviewer say REVISE every time.
--- stubborn run ---
researcher: wrote notes rounds=0 approved=False
writer: wrote draft rounds=0 approved=False
reviewer: REVISE rounds=1 approved=False
writer: wrote draft rounds=1 approved=False
reviewer: REVISE rounds=2 approved=False
writer: wrote draft rounds=2 approved=False
reviewer: REVISE rounds=3 approved=False
supervisor: FINISH (max rounds) rounds=3 approved=False
Draft: Meetings eat the week. Use a written update, set an end time and share an agenda.
At 3 rounds the supervisor finishes with "max rounds", even though nothing was approved. Without that rule the loop would never end, and with a real model every extra round is another bill. Always give a supervisor a way out: an approval, a round limit, or both.
pytest -q prints 4 passed.Supervisor or hub and spoke?
The hub-and-spoke pattern routes one message to the right specialist and collects the answer. The supervisor here keeps going round: it sends work out, reads what came back and picks again, so a reviewer can send the job back for another pass. Use it when the work has a check that can fail and be retried.
Common mistakes
- Letting the model decide when to stop. Keep "approved" and "max rounds" in code that runs before the model is asked.
- Trusting the model's pick. Check the name against the list of workers; anything else ends the run.
- Workers calling each other. Every edge goes back to the supervisor, otherwise you lose the single place where the route is decided.
- Returning the whole state from a worker. Return only the slots you changed, and give lists like
loga reducer so updates add up instead of overwriting.
Quick recap
| Piece | Job |
|---|---|
TeamState | The shared folder: topic, notes, draft, feedback, approved, rounds, next, log |
| supervisor | Stop rule in code, then ask the model for the next worker, then check the name |
| workers | One job each, return only what changed |
| edges | Conditional edge out of the supervisor, plain edge from every worker back to it |
| stop rule | Approved, or MAX_ROUNDS = 3 |
Try it yourself
Add a fourth worker, a fact-checker that runs after the writer and before the reviewer. Add it to WORKERS, add one node and one edge back to the supervisor, and write a test that checks the new worker order. Then set MAX_ROUNDS to 1 and see which scenario still gets approved.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
A support agent forgets the customer's name, order and contact choice after twenty turns and fails 0 of 4 checks. Measure the window, clear old tool output, compact old turns and keep a notes file, and the same chat passes 4 of 4 with 470 tokens instead of 2,945.
What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
LangChain is a box of standard parts (models, prompts, retrievers, tools, parsers) that snap together with a pipe. The same refund question through the plain Anthropic SDK (1 import, 13 lines) and a chain (3 imports, 14 lines) gives the same answer word for word. It pays off when the bot grows; for one call, the SDK is simpler, with 16 packages instead of 38.
Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
A refund assistant built three ways. The chain runs classify, retrieve, reply once: it answers an opening-hours question with the billing line, misses the 30-day window, and sends a $150 refund with approved False. Plain if/while fixes it but hides the flow; a LangGraph StateGraph puts the branch, the retry loop and the approval stop in the arrows.
LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
Two small graphs. A refund skeleton: SupportState, a classify node, a route function on a conditional edge, and an Annotated log that appends instead of overwriting. A help desk: classify and answer call a scripted test model, spam goes straight to END after one model call instead of two, and the same run read with invoke, stream values and stream updates.
