flowchart LR
START(["START"]) --> agent{"agent"}
agent -.->|search| search_docs("search_docs")
agent -.->|web| web_search("web_search")
agent -.->|generate| generate("generate")
search_docs --> agent
web_search --> agent
generate --> END(["END"])
6 Looping Until Enough

Every choice in Chapter 5 pointed forward, toward END. Let one edge point backward and the graph stops being a pipeline: it can think in circles until it’s satisfied.
A graph can loop. A back-edge carries control from a tool node back to the agent, which reads the new state, decides whether it has enough, and either gathers more or stops. That one backward arrow is the essential difference between an agent graph and a plain DAG.
6.1 What we’re building
The same doc-bot, but the agent can now gather from two sources — the internal docs and the web — and decides, pass by pass, whether it has enough to answer.
The two arrows returning to agent are the back-edges: a tool runs and, instead of flowing onward, hands control back for another decision. Only generate → END leaves the loop. Everything else circles.
6.2 The state grows
The agent needs two new things: a second pile of results, and a way to see how many times it has gone around.
from typing import NotRequired, TypedDict
class State(TypedDict):
question: str # input, set by the caller
route: NotRequired[str] # written by agent each pass
docs: NotRequired[list[str]] # written by search_docs
web_results: NotRequired[list[str]] # written by web_search
1 iterations: NotRequired[int] # written by agent: passes so far
answer: NotRequired[str] # written by generate- 1
-
The loop’s own count of itself. The agent writes it on every pass and reads it on the next, so the number lives in state, where a node can act on it. Two counts will be in play before the chapter is over. This one is the graph’s, and it is what a brake reads (the Try-it below) or a budget spends (the Silver challenge). The other,
recursion_limit, is LangGraph’s: a cap on supersteps that the runtime enforces from outside the state, which no node can read and which stops a run by raising, not by routing. Section 6.5 shows both at work, and the Gotcha after it says why a loop needs the second even when it has the first.
Five of the six keys are now NotRequired, and TypedDict has a spelling for that case: flip the default. total=False makes every key optional, and Required marks the one that is not:
from typing import Required, TypedDict
class State(TypedDict, total=False):
question: Required[str] # input, set by the caller
route: str # written by agent each pass
docs: list[str] # written by search_docs
web_results: list[str] # written by web_search
iterations: int # written by agent: passes so far
answer: str # written by generateThe two classes mean the same thing to the type checker and to LangGraph, which reads only the key names and their annotations. The book keeps the first spelling, because a state is read one line at a time and NotRequired says on the line what the line means; total=False says it once, at the top, and the reader has to carry it down. When a state grows to a dozen optional keys, the second spelling starts to earn its place.
6.3 The agent decides again
The agent still reads state and writes a route, never calling a tool itself. What’s new is that it runs more than once, each time reading what has accumulated to decide what is still missing.
def agent_node(state: State) -> dict:
# Not in state on the first pass.
1 docs = state.get("docs", [])
web = state.get("web_results", [])
iterations = state.get("iterations", 0)
# Stand-in for an LLM deciding "do I have enough to answer?":
# nothing yet → search the docs
# docs but no web → search the web
# both in hand → enough; go generate
if not docs:
route = "search"
elif not web:
route = "web"
else:
route = "generate"
print(
f"[agent] pass {iterations + 1}: "
f"docs={len(docs)} web={len(web)} → {route}"
)
# Record the decision AND that we went around once more.
2 return {"route": route, "iterations": iterations + 1}- 1
-
None of these exists on the first pass, so the reads are
state.get(...)with defaults: a looping node must survive both its first visit and its later ones. - 2
-
iterationsis written by the node that reads it — each pass bumps it by one.
The if / elif / else is a stand-in for judgment: a real model would weigh the question against what it has retrieved. What carries over is that the agent inspects the current state to pick its next action. It runs again after every tool, so that inspection is fresh each pass.
The two tools are stubs, hand-wired as ordinary nodes. Each writes its own field and says nothing about where to go next; the back-edge decides that. (The retriever becomes a real vector store in Part III; Chapter 7 has more on what a real external tool looks like.)
def search_docs_node(state: State) -> dict:
print("[search_docs] retrieving from the docs…")
return {"docs": ["Config Manual §3", "FAQ entry"]}
def web_search_node(state: State) -> dict:
print("[web_search] searching the web…")
return {"web_results": ["Blog post", "Stack Overflow answer"]}generate closes things out, reading whatever the agent gathered:
def generate_node(state: State) -> dict:
docs = state.get("docs", [])
web = state.get("web_results", [])
print(f"[generate] composing from {len(docs)} docs + {len(web)} web hits")
answer = f"Answer built from {len(docs)} docs and {len(web)} web hits."
return {"answer": answer}
def route_after_agent(state: State) -> str:
return state["route"]The routing function is unchanged from Chapter 5. What changed is where that string can lead: two of the three destinations, search_docs and web_search, come back to agent.
6.4 Wiring the loop
The agent gets a three-way conditional edge — Chapter 5’ branch with one more destination. The new part is the two plain edges sending the tools back to agent instead of onward.
from langgraph.graph import StateGraph, START, END
builder = StateGraph(State)
builder.add_node("agent", agent_node)
builder.add_node("search_docs", search_docs_node)
builder.add_node("web_search", web_search_node)
builder.add_node("generate", generate_node)
builder.add_edge(START, "agent")
# The agent's conditional edge now has three destinations.
builder.add_conditional_edges(
"agent",
route_after_agent,
{
"search": "search_docs",
"web": "web_search",
"generate": "generate",
},
)
# The back-edges: a tool finishes and control returns to `agent`, which
# decides again.
builder.add_edge("search_docs", "agent")
builder.add_edge("web_search", "agent")
# Only generate reaches the exit.
builder.add_edge("generate", END)
graph = builder.compile()flowchart TD
START(["START"]) --> agent{"agent"}
agent -.->|search| search_docs("search_docs")
agent -.->|web| web_search("web_search")
agent -.->|generate| generate("generate")
search_docs --> agent
web_search --> agent
generate --> END(["END"])
add_edge("search_docs", "agent") is an ordinary edge whose destination happens to be a node that already ran. Point one at an earlier node and you have a loop.
The agent decides (routes to a tool), the tool acts (writes its result to state), and that result becomes the agent’s next observation when control loops back. Decide → act → observe is the skeleton most tool-using agents are built on. create_agent, later in the book, looks like a lot of machinery but runs exactly this cycle. Here it is in four nodes and two back-edges.
6.5 Running it
There’s a catch hiding in every loop. We run the graph twice — the fuse set too short, then with room to finish — so you see both the failure and the success.
if __name__ == "__main__":
question = "How do I configure Kafka in Spring Boot?"
# First, set the fuse too short. This healthy loop needs a handful of
# steps to finish; capping it below that makes the runtime blow the fuse.
print("===== run 1: recursion_limit=4 (too low) =====")
try:
1 graph.invoke({"question": question}, {"recursion_limit": 4})
except GraphRecursionError:
print("!! GraphRecursionError: hit the step limit before finishing")
# Now give it room. The agent reaches "enough" and routes to generate.
print("\n===== run 2: recursion_limit=10 (enough) =====")
result = graph.invoke({"question": question}, {"recursion_limit": 10})
print("\nanswer:", result["answer"])
print("passes:", result["iterations"])- 1
-
A second argument to
invoke. The first is the input, as always; the second is aconfigdict, andrecursion_limitis one key in it. It belongs to this call and not to the graph: the same compiledgraphruns with4here and10four lines down, and nothing was recompiled in between. Later chapters put other keys in the same dict, and Chapter 8’sthread_idis the one you will use most.
GraphRecursionError comes from langgraph.errors, so the top of the file adds one import next to the usual graph pieces:
from langgraph.errors import GraphRecursionErrorRunning the file produces:
===== run 1: recursion_limit=4 (too low) =====
[agent] pass 1: docs=0 web=0 → search
[search_docs] retrieving from the docs…
[agent] pass 2: docs=2 web=0 → web
[web_search] searching the web…
!! GraphRecursionError: hit the step limit before finishing
===== run 2: recursion_limit=10 (enough) =====
[agent] pass 1: docs=0 web=0 → search
[search_docs] retrieving from the docs…
[agent] pass 2: docs=2 web=0 → web
[web_search] searching the web…
[agent] pass 3: docs=2 web=2 → generate
[generate] composing from 2 docs + 2 web hits
answer: Answer built from 2 docs and 2 web hits.
passes: 3
Both runs on one axis, a superstep per column. Time flows left to right, so the back-edge shows up as agent appearing again further along:
%%{init: {"flowchart": {"nodeSpacing": 14, "rankSpacing": 18, "padding": 4, "subGraphTitleMargin": {"top": 0, "bottom": 2}}}}%%
flowchart LR
subgraph s1["superstep 1"]
a1("agent · pass 1")
b1("agent · pass 1")
end
subgraph s2["superstep 2"]
a2("search_docs")
b2("search_docs")
end
subgraph s3["superstep 3"]
a3("agent · pass 2")
b3("agent · pass 2")
end
subgraph s4["superstep 4"]
a4("web_search")
b4("web_search")
end
subgraph s5["superstep 5"]
a5("⚠ GraphRecursionError")
b5("agent · pass 3")
end
subgraph s6["superstep 6"]
b6("generate")
end
r1["limit 4"] --> a1 --> a2 --> a3 --> a4 --> a5
r2["limit 10"] --> b1 --> b2 --> b3 --> b4 --> b5 --> b6
classDef step fill:none,stroke:#999,stroke-dasharray:4 4;
class s1,s2,s3,s4,s5,s6 step;
classDef bad fill:#fde2e2,stroke:#c0392b;
class a5 bad;
classDef run fill:none,stroke:none;
class r1,r2 run;
Run 1 completes four supersteps and blows the fuse as the counter passes four, before the runtime even checks whether a fifth node is waiting; run 2 has room for the same four plus agent’s third pass and generate.
recursion_limit is a fuse
The forward-only graphs of the last three chapters always terminated. A back-edge throws that guarantee away: if the agent’s stopping condition never becomes true — a real model that keeps insisting “not enough yet,” a bug that never writes the field the agent waits on — the loop runs until something stops it.
LangGraph’s built-in stop is recursion_limit: the maximum number of supersteps one invoke may take. Supersteps are the unit Chapter 4 introduced — don’t read the limit as a node count. The check runs after a superstep completes and before the next one is scheduled, so a run that needs N supersteps needs a limit of at least N+1 (Chapter 7 counts it out). Exceed it and the run raises GraphRecursionError instead of hanging your process.
That’s why run 1 sets it to 4. This loop is healthy — it does reach generate on its own — but not within four supersteps, so the cap trips first. It stands in for the real danger, a loop that would never stop at all.
Don’t count on the default to catch that. On the langgraph==1.2.19 this book pins it is 10007, far too large to be a safety net: a runaway will make thousands of model calls before it trips. Read that number as a sentinel rather than a budget.
It is version-specific, too, and has moved more than once. The official Graph API guide still says the default is 1000, “starting in version 1.0.6”1. The default also reads an environment variable, LANGGRAPH_DEFAULT_RECURSION_LIMIT, so a platform can move it again without touching your code. Every value it has taken is far past useful. For any graph whose step count isn’t known in advance, set recursion_limit yourself, sized to the longest legitimate run plus a margin.

RemainingSteps
The fuse doesn’t have to be invisible until it blows. Add a field of type RemainingSteps (from langgraph.managed) to the State, and the runtime fills it in before every superstep with how many supersteps remain after this one before recursion_limit trips. The first superstep of a recursion_limit=10 run reads 9.
A node reads it like any other field. The runtime owns it, and anything a node writes to it is ignored — noisily: the runtime logs wrote to unknown channel remaining_steps, ignoring it once per superstep. That is the opposite of Chapter 3’s silently-dropped unknown key, which the runtime has never heard of and says nothing about.
from langgraph.managed import RemainingSteps
class State(TypedDict):
question: str
# ... the fields you already have ...
remaining_steps: RemainingSteps # managed by the runtime — read-only
def agent_node(state: State) -> dict:
if state["remaining_steps"] < 4:
return {"route": "generate"} # wrap up while we still can
# ... the normal decision ...That turns the crash into a choice: the agent sees the budget running out and routes to a finish. It is the Try-it below’s hand-rolled iterations guard, with the counting done by the runtime against the actual fuse.

Break the stopping condition and watch the fuse do its job. In agent_node, replace the decision with a plain route = "search" so the agent is never satisfied. Run it with {"recursion_limit": 10} and the [agent] pass lines count to five before GraphRecursionError fires. Drop the argument and the same loop grinds through 5,004 passes before the default trips.
Now give that broken agent its own brake. Keep the runaway route = "search", but put one check in front of it — if iterations >= 3: route = "generate" — so it gives up on its fourth visit no matter what state says. (The guard reads the pre-increment iterations, so it first fires when that count reaches 3.) Re-run and watch it stop itself, before the fuse is anywhere in sight.
6.6 What we learned
- A back-edge makes a loop — an ordinary
add_edgewhose destination already ran. The graph doesn’t know forward from backward; it only follows edges. - Decide → act → observe is the agent skeleton. The agent routes to a tool, the tool writes its result to state, and that result is the agent’s next observation — the same cycle
create_agentruns for you later. - A looping node must survive an empty first visit, so read with
state.get(...), notstate[...]. recursion_limitis a fuse, not a plan. It caps supersteps and raisesGraphRecursionError; the default is effectively off, so always pass one. The stopping condition lives in your agent.
The two tools here were stubs, hand-wired as ordinary nodes. What does a real tool look like as a node, and how does the agent pick among a growing kit of them? Next we give search_docs and web_search a shared shape, and the agent a cleaner way to reach for whichever one the job needs.
New pieces in this chapter
| Piece | Usage |
|---|---|
| Type | |
TypedDict(total=False) / Required |
The other spelling of an optional state: every key optional by default, Required[...] for the ones the caller must supply. class State(TypedDict, total=False) with question: Required[str]; the same schema as the NotRequired form, read top-down instead of line by line |
GraphRecursionError |
Exception from langgraph.errors raised when a run exceeds recursion_limit. except GraphRecursionError:; the run crashes instead of hanging your process |
RemainingSteps |
State-field annotation from langgraph.managed; the runtime keeps the field filled with supersteps left after the current one before the fuse trips. remaining_steps: RemainingSteps; managed by the runtime — read it, never write it |
| API | |
invoke(config={"recursion_limit": …}) |
Entry in the config dict passed to invoke that caps the supersteps one invoke may take. graph.invoke({"question": q}, {"recursion_limit": 10}); the default is effectively off (10007 on langgraph==1.2.19, and version-specific) |
Code in this chapter
| File | What it runs |
|---|---|
code/ch04_looping.py |
The back-edge: a tool returns to the agent instead of moving forward, and recursion_limit is the fuse under it. |
Challenge
🥉 Bronze — make the loop’s path visible
The chapter counts how many passes the loop took, never which route it chose each time. That trajectory is usually the first thing you wish you had when a loop misbehaves.
Record it: add a trajectory field and have the agent append its route every visit with {"trajectory": state.get("trajectory", []) + [route]}. After a run it reads ["search", "web", "generate"].
Then answer the question the field raises: why does this need no reducer, when Chapter 10 will?
Worked solution with tests: code/answers/ch04_trajectory_log.py.
Because the agent runs once per superstep, in sequence, nothing writes trajectory concurrently, so plain read-and-append is safe.
🥈 Silver — a budget, with a graceful giving-up
Give the agent a real pass budget: when it’s spent, set a gave_up flag and have generate return a clearly labeled partial answer, so the exhausted case shows up in the result rather than hiding inside it.
Two runs decide it. Send in a question the loop would chase forever and read the result for both the label on the answer and the state of gave_up; send in one the agent can actually satisfy and read the same two places again. Neither run should raise.
Hints: the Try-it’s self-brake stops a runaway silently — the caller can’t tell a satisfied answer from an exhausted one, and that gap is what you’re closing. That agent is also never satisfied, so the second run needs you to give it something to be satisfied by — one stub doc that matches the question is enough. Keep recursion_limit in view for contrast: the fuse crashes the run; a budget lets the agent stop itself and still return something.
Worked solution with tests: code/answers/ch04_budget_degrade.py.
https://docs.langchain.com/oss/python/langgraph/graph-api; the installed
langgraph._internal._configis the value that actually runs.↩︎

