Module 1 · Thinking in graphs
Your first cyclic agent
7 min read
We have every ingredient to build LangGraph's central object: a cyclic agent, where the model and the tools hand over to each other until the task is done. We start with the minimal version, then turn it into Relay's agent loop, with its secured tools and its stop condition.
The minimal version
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition
tools = [search_help_center]
async def call_model(state: MessagesState) -> dict:
response = await model.bind_tools(tools).ainvoke(state["messages"])
return {"messages": [response]}
builder = StateGraph(MessagesState)
builder.add_node("agent", call_model)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", tools_condition)
builder.add_edge("tools", "agent")
graph = builder.compile()
Seven lines of assembly, and everything is there:
agentcalls the model with the list of tools. Its answer (anAIMessage) is appended to the history.tools_conditionis a router provided by LangGraph: if the last message containstool_calls, it returns"tools", otherwiseEND.ToolNoderuns all tool calls of the last message and appends oneToolMessageper result.- The
tools → agentedge closes the loop: after each tool run, the model takes over again with the results.
This is examples/02_cyclic_agent.py. Run it offline with RELAY_FAKE_LLM=1 to see the trajectory: question, tool call, result, answer.
The model and the tools
The model is a LangChain chat model:
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(model="claude-opus-5-5", max_tokens=4096, max_retries=3)
Using the LangChain integration rather than the raw SDK has two benefits in a graph: messages have a standard format that add_messages, ToolNode and tools_condition understand, and the messages streaming mode (lesson 5.1) streams tokens with no extra code.
Tools are declared with the @tool decorator. The name, docstring and type annotations become the definition sent to the model:
from langchain_core.tools import tool
@tool
async def search_help_center(query: str) -> str:
"""Searches the shop's help center (returns, shipping, warranty, account).
Use it for general questions that are not about a specific order.
Returns at most 2 articles; an empty list means no article matches.
"""
return json.dumps(await data.search_help_center(query), ensure_ascii=False)
The docstring is the tool's description for the model: it says what, when, and what is returned. It is the most decisive factor in correct tool choice.
Injecting context into a tool
Relay's lookup_order tool must know which customer is asking, to show them only their own orders. That id must not be an argument the model fills in: a clever message ("I am customer cus_sam") would be enough to bypass the check. It is injected via ToolRuntime:
from langgraph.prebuilt import ToolRuntime
@tool
async def lookup_order(order_id: str, runtime: ToolRuntime[Context]) -> str:
"""Returns the status, dates and items of one of the customer's orders. ..."""
order = await data.get_order(order_id)
if order is None or order["customer_id"] != runtime.context.customer_id:
return f"No order {order_id} for this customer. Check the number (format ORD-XXXX)."
...
The runtime parameter is invisible to the model: it doesn't appear in the tool's schema, and ToolNode fills it at runtime with the run's context, the current state and the store. Access control is in the code, where it belongs.
Tool error handling
What happens when a tool raises an exception? By default, ToolNode handles only one case: invalid arguments (the model filled the schema incorrectly). It then sends the model an error ToolMessage, and the model fixes its call. Any other exception — an unavailable API, a bug — propagates and fails the graph run.
This behavior is set with the handle_tool_errors parameter: True to catch every exception, a fixed message, a function that formats the error, or a tuple of exception types to catch. Relay chooses True:
builder.add_node("tools", ToolNode(TOOLS, handle_tool_errors=True))
A tool failure thus becomes information for the model, which can retry, switch tools or explain the situation to the customer. If you'd rather have an infrastructure failure interrupt the graph (to retry it with a retry policy, lesson 2.2), pass a tuple of "business" exceptions to catch instead.
Relay's agent loop
In Relay, the loop differs from the minimal version on three points:
async def agent(state: SupportState) -> dict:
model = chat_model().bind_tools(TOOLS)
system = SystemMessage(AGENT_PROMPT.format(language=state.get("language", "fr")))
response = await model.ainvoke([system, *state["messages"]])
return {"messages": [response], "agent_turns": state.get("agent_turns", 0) + 1}
def route_after_agent(state: SupportState) -> Literal["tools", "handoff", "finish"]:
last = state["messages"][-1]
if not getattr(last, "tool_calls", None):
return "finish"
if state.get("agent_turns", 0) >= config.MAX_AGENT_TURNS:
return "handoff"
return "tools"
- The system prompt is not stored in the state. It is added on each call. The history contains only the real conversation, and changing the prompt requires no migration of existing conversations.
- A turn counter (
agent_turns) bounds the loop. Beyond six turns, the agent is probably going in circles: we hand over to a human rather than burning tokens indefinitely. - A custom router replaces
tools_condition, to have three exits: tools, escalation, finish.
The escalation trap: no orphan tool call
When the agent is stopped mid-loop, the last AIMessage contains tool_calls that never got an answer. Leave the history as is and the next model call will fail: the API requires a result for every tool call. Relay's handoff node therefore closes pending calls cleanly:
async def handoff(state: SupportState) -> dict:
messages = []
last = state["messages"][-1] if state.get("messages") else None
for call in getattr(last, "tool_calls", None) or []:
messages.append(ToolMessage(content="Annulé : demande transmise à un conseiller.",
tool_call_id=call["id"]))
messages.append(AIMessage(content=HANDOFF[state.get("language", "fr")]))
return {"messages": messages, "status": "escalated", "audit": ["handoff → conseiller"]}
The test_agent_loop_guard_hands_off_and_keeps_history_valid test checks exactly this property: every tool call in the history has its result.
Reading a trajectory
To understand what an agent did, look at its trajectory: the sequence of executed nodes.
inputs = {"messages": [("user", "Where is my order ORD-1002?")]}
result = await graph.ainvoke(inputs, config, context=Context("cus_lea"))
for message in result["messages"]:
print(message.type, message.content or message.tool_calls)
human Where is my order ORD-1002?
ai [{'name': 'lookup_order', 'args': {'order_id': 'ORD-1002'}, ...}]
tool {"order_id": "ORD-1002", "status": "shipped", "carrier": "Colissimo", ...}
ai Your order ORD-1002 has shipped (Colissimo), expected on 2026-10-14.
Expected trajectory: load_profile → triage → agent → tools → agent → finish. A test checking the trajectory catches regressions that a test on the final answer alone would miss — for example an agent that answers correctly but without consulting the tool.
Key takeaways
- A cyclic agent = a model node + a
ToolNode+ a router + thetools → agentedge.tools_conditionroutes to the tools if there aretool_calls, otherwise to the end.- Sensitive data (customer identity) is injected with
ToolRuntime: invisible to the model and not modifiable by it.- By default,
ToolNodeonly sends argument errors back to the model;handle_tool_errors=Trueadds every exception.- Bound the loop (number of turns) and never leave a tool call without a result in the history.
Practice
- Run
examples/02_cyclic_agent.pyoffline, then with an API key, and compare the trajectories. - Add a
get_delivery_options(country)tool to Relay and check that the loop uses it with no other change. - Set
MAX_AGENT_TURNSto 1 inconfig.pyand ask a question: what happens, and does the history stay valid?