Every LangGraph Swarm demo looks the same. Three agents, a question goes in, it bounces from one agent to the right specialist, and an answer comes out. It looks like the agents are talking to each other. I wanted to know what is really going on underneath: what a handoff is, what the swarm remembers between turns, and what happens when two agents disagree about who owns a question.
So I built a three-agent LangGraph Swarm and ran it without an API key. A small scripted model stands in for the LLM, so every run is repeatable and the tests cost nothing. The graph, the handoffs and the memory are all the real library. One of the things I found is a default you will want to change before you put a swarm in production.
What a LangGraph Swarm is
A swarm is a multi-agent system with no manager. In a supervisor setup, one agent reads every request and decides who works on it. In a swarm, each agent gets a set of handoff tools, one per colleague it may pass work to. When an agent decides a question is not its job, it calls a handoff tool and control moves to the other agent.
The swarm also stores which agent was active last. The next message on the same conversation goes straight to that agent, not back to the start. That one detail is what makes a swarm feel like a conversation with a specialist rather than a call centre that transfers you every time you speak.
Setting up LangGraph Swarm
I used Python 3.12 with langgraph 1.2.24, langgraph-swarm 0.1.0 and langchain 1.5.2. If you are following an older tutorial, note that agents are now built with langchain.agents.create_agent and a system_prompt, not create_react_agent with prompt=.
python3.12 -m venv .venv .venv/bin/pip install langgraph langgraph-swarm langchain-core pytest
The swarm has three agents: a general Q&A agent, a science agent with a tool that looks up chemical elements, and a translator with an English-to-Spanish tool. Here are the tools and one of the agents:
from langchain.agents import create_agent
from langgraph.checkpoint.memory import InMemorySaver
from langgraph_swarm import create_handoff_tool, create_swarm
ELEMENTS = {"iron": ("Fe", 26), "gold": ("Au", 79), "carbon": ("C", 6)}
SPANISH = {"iron": "hierro", "gold": "oro", "carbon": "carbono", "thank you": "gracias"}
def element_facts(name: str) -> str:
"""Look up the symbol and atomic number of a chemical element."""
symbol, number = ELEMENTS[name.lower()]
return f"{name.title()}: symbol {symbol}, atomic number {number}"
def translate_to_spanish(text: str) -> str:
"""Translate a short English word or phrase to Spanish."""
return SPANISH.get(text.lower(), f"[no entry for {text!r}]")
science_agent = create_agent(
models["science_agent"],
tools=[
element_facts,
create_handoff_tool(agent_name="qa_agent", description="Send non-science questions back to general Q&A"),
create_handoff_tool(agent_name="translator_agent", description="Send translation requests to the translator"),
],
system_prompt="You answer chemistry questions using element_facts. Hand off anything else.",
name="science_agent",
)
Similarly, the other two agents follow the same pattern, each with handoff tools to the other two. Then the swarm itself is two lines. The checkpointer matters, and I will come back to it:
workflow = create_swarm([qa_agent, science_agent, translator_agent], default_active_agent="qa_agent") app = workflow.compile(checkpointer=InMemorySaver())
A model you can test with
From LangGraph’s point of view, a model is anything that takes messages and returns an AIMessage, sometimes with tool calls. That means you can write one that follows rules instead of calling an API:
from itertools import count
from langchain_core.language_models import BaseChatModel
from langchain_core.messages import AIMessage
from langchain_core.outputs import ChatGeneration, ChatResult
_ids = count(1)
def call(tool, **args):
return AIMessage(content="", tool_calls=[{"name": tool, "args": args, "id": f"call_{next(_ids)}"}])
class ScriptedModel(BaseChatModel):
rules: list
fallback: str = "I can't help with that."
@property
def _llm_type(self):
return "scripted"
def bind_tools(self, tools, **kwargs): # tools are chosen by the rules
return self
def _generate(self, messages, stop=None, run_manager=None, **kwargs):
for rule in self.rules:
reply = rule(messages)
if reply is not None:
return ChatResult(generations=[ChatGeneration(message=reply)])
return ChatResult(generations=[ChatGeneration(message=AIMessage(content=self.fallback))])
Each agent gets a short list of rules. The science agent’s first rule says: if the latest question mentions translation, call transfer_to_translator_agent; if it is not about chemistry at all, call transfer_to_qa_agent. The next rule calls element_facts, and the last one turns the tool result into an answer.
This is not a replacement for a real model. It is a way to test the wiring. When you want real answers, install langchain-anthropic and pass a model name instead, such as create_agent("anthropic:claude-sonnet-5-5", ...). The graph, the handoffs and the tests around them stay the same.
Three turns on one conversation
I sent three messages on the same thread and printed who handled each step:
--- turn ends with active_agent = science_agent user : What is the atomic number of iron? qa_agent : calls transfer_to_science_agent tool : Successfully transferred to science_agent science_agent : calls element_facts(name='iron') tool : Iron: symbol Fe, atomic number 26 science_agent : Iron: symbol Fe, atomic number 26. --- turn ends with active_agent = translator_agent user : How do I say iron in Spanish? science_agent : calls transfer_to_translator_agent tool : Successfully transferred to translator_agent translator_agent: calls translate_to_spanish(text='iron') tool : hierro translator_agent: In Spanish: hierro. --- turn ends with active_agent = qa_agent user : Thanks, that's all. translator_agent: calls transfer_to_qa_agent tool : Successfully transferred to qa_agent qa_agent : Happy to help. Ask me anything else.
Now look at the start of the second turn. The question did not go to the Q&A agent, the default. It went to the science agent, because that agent answered last. The science agent saw a translation request and passed it on. The third turn started with the translator for the same reason.
By contrast, a new thread starts fresh. When I sent “How do I say gold in Spanish?” on thread 43, the first agent to see it was qa_agent again.
What a handoff actually is
The handoff tool is short enough to read in full in the library. Stripped down, it returns a LangGraph Command:
return Command(
goto=agent_name,
graph=Command.PARENT,
update={
"messages": [*state["messages"], tool_message],
"active_agent": agent_name,
},
)
Three things follow from this. First, graph=Command.PARENT means the jump happens in the swarm graph, outside the agent that made the call. Second, active_agent is just a field in the state, which is how the next turn knows where to start. Third, the new agent gets the whole message list. There is no summary and no filtering.
However, that third point is easy to miss. After the three short turns above, the thread held 16 messages, including every tool call and every “Successfully transferred” note. With a real model, every agent pays for that whole history on every call. If your agents do long tool work, decide what each one really needs to see. I cover ways to do that in the shared state tutorial.
The compiled graph shows the same picture. Every agent can reach every other agent, and the start node can route to any of them:
nodes: ['__start__', 'qa_agent', 'science_agent', 'translator_agent']
edges: ['__start__->qa_agent', '__start__->science_agent', '__start__->translator_agent',
'qa_agent->science_agent', 'qa_agent->translator_agent',
'science_agent->qa_agent', 'science_agent->translator_agent',
'translator_agent->qa_agent', 'translator_agent->science_agent']
The handoff loop, and the default you should change
Now the failure that matters. Suppose the Q&A agent thinks a translation question belongs to science, and the science agent thinks it belongs to Q&A. With real models this happens more often than you would like, usually after someone edits a prompt. I made both scripted agents always hand off to each other and ran the same question with different step limits:
| recursion_limit | Model calls before it stopped | Time | Messages saved |
|---|---|---|---|
| 25 | 25 | 0.08 s | 51 |
| 100 | 100 | 0.47 s | 201 |
| 400 | 400 | 5.43 s | 801 |
In other words, each step is one model call, and each handoff adds two messages to the history. Notice the time: four times the steps took more than ten times as long, because every step carries a longer history than the one before.
Next, I checked what limit you get if you do not set one. In LangGraph 1.x it lives in langgraph/_internal/_config.py:
DEFAULT_RECURSION_LIMIT = _DefaultRecursionLimit(
getenv("LANGGRAPH_DEFAULT_RECURSION_LIMIT", "10007")
)
In LangGraph 0.6 the same line defaulted to 25. The current default is 10,007. A swarm caught in a handoff loop with no limit of its own would make thousands of model calls on one user message, each with a longer history than the last, before LangGraph gives up.
A handoff loop is free with a scripted model. With a real one, every bounce sends the whole conversation again.
Fortunately, the fix is small. Set a limit on every call, and turn the error into a reply the user can live with:
from langgraph.errors import GraphRecursionError
MAX_STEPS = 12 # agent turns per user message, handoffs included
def ask(app, thread_id: str, text: str) -> str:
config = {"configurable": {"thread_id": thread_id}, "recursion_limit": MAX_STEPS}
try:
state = app.invoke({"messages": [{"role": "user", "content": text}]}, config)
except GraphRecursionError:
return "Sorry, I couldn't route that request. A person will follow up."
return state["messages"][-1].content
With the same looping agents, ask() stopped after 12 model calls, in 0.03 seconds, and returned the fallback message. Pick the number from your own traces: count the steps your longest normal request takes and add some room. You can also set LANGGRAPH_DEFAULT_RECURSION_LIMIT for the whole process, but a limit in the code is easier to see in review.
Two mistakes, one caught and one silent
On the plus side, LangGraph catches a typo in a handoff target early. I gave one agent create_handoff_tool(agent_name="sciense_agent"), and compiling the swarm failed straight away:
ValueError: Found edge ending at unknown node `sciense_agent`
However, nothing catches a missing checkpointer. I compiled the same swarm with no checkpointer and sent two messages. The first ended with the science agent active. The second went back to the Q&A agent, and its state held only 6 messages, the second turn alone. Nothing failed; the swarm simply forgot. In production, use a persistent checkpointer such as Postgres instead of InMemorySaver, which I walk through in the LangGraph persistence tutorial.
Testing LangGraph Swarm routing
Because the model is scripted, I can test the routing like any other code. My test file has nine tests, and they run in under half a second:
- a science question goes from
qa_agenttoscience_agentand returns the right element - the next turn on the same thread starts with the last active agent
- a new thread starts with the default agent
- each domain gives the expected answer (three cases)
- every handoff tool points at an agent that exists, and every agent has a way out
- a typo in a handoff target fails at compile time
- a handoff loop is stopped within
MAX_STEPSmodel calls and returns the fallback
Two of them, to show the style:
def handlers(messages):
"""Names of the agents that produced AI messages, in order, without repeats."""
out = []
for m in messages:
if isinstance(m, AIMessage) and (not out or out[-1] != m.name):
out.append(m.name)
return out
def test_next_turn_starts_with_last_active_agent(app):
turn(app, "t1", "What is the atomic number of iron?")
_, new = turn(app, "t1", "How do I say iron in Spanish?")
assert handlers(new) == ["science_agent", "translator_agent"]
assert new[-1].content == "In Spanish: hierro."
def test_handoff_loop_is_stopped_quickly():
calls = []
def bounce(target):
def rule(m):
calls.append(target)
return call(target)
return rule
models = swarm_app.scripted_models()
models["qa_agent"] = ScriptedModel(rules=[bounce("transfer_to_science_agent")])
models["science_agent"] = ScriptedModel(rules=[bounce("transfer_to_qa_agent")])
app = swarm_app.build_app(models)
reply = swarm_app.ask(app, "loop", "Translate iron to Spanish")
assert reply.startswith("Sorry, I couldn't route that")
assert len(calls) <= swarm_app.MAX_STEPS
$ pytest -q test_swarm.py ......... [100%] 9 passed in 0.39s
Still, these tests check the plumbing, not the judgement. Whether a real model hands off at the right moment is a separate question, and it needs recorded conversations and checks on the path each one took. That is what trajectory evaluation is for, and the LangGraph evaluation tutorial shows how to run it.
LangGraph Swarm or supervisor?
| Swarm | Supervisor | |
|---|---|---|
| Who decides the route | The agent that has the question | One manager agent |
| Next message goes to | The last active agent | The supervisor, every time |
| Model calls for a follow-up | Often one, if the same agent keeps it | At least two |
| Main risk | Handoff loops between agents | The supervisor becomes a bottleneck |
I reach for a swarm when users tend to stay with one specialist for a while, like support or tutoring, because the follow-up goes straight to the right agent. I reach for a supervisor when every request needs a central decision, or when I want one place to log and control routing. My framework comparison covers where LangGraph fits against the alternatives.
What I would do before shipping one
Set a recursion_limit on every call and catch the error. Use a persistent checkpointer. Give each agent a clear way back to a general agent, so there is always somewhere for an odd question to land. And keep a scripted model around: it turns routing changes into fast, free tests that run on every commit.
Further reading
- langgraph-swarm-py on GitHub: the library source, including the handoff tool shown above
- LangGraph on GitHub
- LangGraph Multi-Agent Systems: Practical Tutorial Series
- LangGraph Supervisor Tutorial: Build a Multi-Agent System
