Cycles and Loops
Rebuild Module 1’s ReAct loop as a LangGraph cycle - agent -> tools -> agent - with llama3 deciding and a step limit that actually stops it.
What you will be able to do
- Explain what a cycle is and why agents need one
- Build the agent -> tool -> agent loop with an edge back and a conditional exit
- Map Thought, Action and Observation onto nodes, state and edges
- Give a loop a stopping condition and a step limit - and know what happens without them
- Run a real ReAct cycle with llama3 choosing the actions
- Read a loop’s run step by step to find wasted or wrong steps
The idea, in plain English
Module 1’s agent was a for loop: ask the model, run the tool it chose, add the result, repeat until there is an answer. In a graph, the same loop is just one extra edge: add_edge("tools", "agent") sends every tool result back to the agent. An edge that goes back to an earlier node is called a cycle.
A cycle alone can run forever. To make it safe you add exits: when there is an answer, go to END; after too many steps, go to a give-up node.
We build it twice: first with a fake agent to see the mechanics, then with llama3 choosing the actions. LangGraph 1.2.14 throughout.
Worked example: The ReAct loop from Module 1, rebuilt as a graph cycle.
1 - Thought and action: the weather
The agent node shows llama3 the question and the (empty) history. It returns action get_weather, input Mumbai. should_continue sees no answer and few steps: go to tools.
"Should I bring an umbrella in Mumbai, and what’s 12 * 8?" - llama3 chooses each action; the tools node runs it. Three agent steps, two tool runs, 4.2 seconds.
Words you will see in this lesson
A few words about loops.
CycleA path in the graph that leads back to a node that already ran.LoopA cycle with a way out: it repeats until a condition is met.ReActReason + Act: think, use a tool, look at the result, think again (Module 1).ObservationThe result of a tool, given back to the model.ExitThe route out of the loop - usually to END.Step limitYour own maximum number of rounds, counted in the state.recursion_limitLangGraph’s own hard stop. Default 10,007 node runs.An everyday example: finding an address
You are in a new area, looking for a friend’s house. You do not know the way, so you repeat the same three things - think, ask, look - until you find it:
- 1. Think: "I don’t know the way. I should ask someone."
- 2. Ask: a shopkeeper says, "Go straight, then turn left."
- 3. Look: you walk there and look around. Not there yet? Go back to step 1 and think again with what you now know: "I’m close - but which lane?"
- Stop when you see the house - you have your answer.
- Or stop after asking ten people: you call your friend instead of walking around forever.
- An agent works the same way. The table shows which part of the story is which part of the graph.
You think what to do nextThe agent node: the model decides.You ask a shopkeeperThe tools node: a tool runs.What the shopkeeper tells youThe observation: the tool’s result.You go back and think againThe cycle: the edge from tools back to agent.You see the house and stopThe exit: the agent has an answer, so the router goes to END.After ten people you call your friendThe step limit: the router goes to the give_up node.From a for loop to a cycle
Every part of Module 1’s loop has a place in the graph:
- Nothing about ReAct changed.
- What changed: the loop is now structure you can draw, stream and extend - not hidden inside a function.
for step in range(max_steps)The cycle agent -> tools -> agent, plus a step count in the state.response = model(...)The agent node.if final answer: returnshould_continue routes to END.observation = run_tool(action)The tools node.messages.append(observation)The tools node returns the longer history.Example 1 - the cycle, with a fake agent
No model yet, so you can see the mechanics clearly. Read it in this order:
- agent: if there is no observation yet, it asks for the calculator. If there is one, it writes the answer. It also counts the step.
- calculator: the tool. It writes the observation "30".
- should_continue: the router. Answer -> "end". Too many steps -> "end". Otherwise -> "tool".
- add_edge("calculator", "agent"): the edge back. This one line makes the cycle.
from typing import TypedDict
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
question: str
step: int
action: str
observation: str
answer: str
MAX_STEPS = 5
def agent(state: State):
step = state["step"] + 1
if state["observation"]:
return {"step": step, "answer": f"The calculation result is {state['observation']}"}
return {"step": step, "action": "calculate"}
def calculator(state: State):
return {"observation": str(10 + 20)}
def should_continue(state: State):
if state["answer"]:
return "end"
if state["step"] >= MAX_STEPS:
return "end"
return "tool"
builder = StateGraph(State)
builder.add_node("agent", agent)
builder.add_node("calculator", calculator)
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", should_continue, {"tool": "calculator", "end": END})
builder.add_edge("calculator", "agent") # the edge back - this is the cycle
graph = builder.compile()
start = {"question": "What is 10 + 20?", "step": 0, "action": "", "observation": "", "answer": ""}
for update in graph.stream(start, stream_mode="updates"):
print(update){'agent': {'step': 1, 'action': 'calculate'}}
{'calculator': {'observation': '30'}}
{'agent': {'step': 2, 'answer': 'The calculation result is 30'}}Reading Example 1
- The agent ran TWICE. The first time it asked for the tool; the second time it saw the result and answered.
- That is the whole idea of ReAct: think, act, observe, think again.
- After the second agent step there was an answer, so should_continue chose END.
Every loop needs an exit and a limit
We broke the exit on purpose - an agent that never answers:
- With MAX_STEPS = 5: it went round four times and stopped at step 5 - but with an EMPTY answer. The user gets nothing.
- Better: route to a give_up node that says so - "Stopped after 6 steps without an answer."
- With no step check at all: LangGraph’s own guard stopped it - after 10,007 node runs. With a real model that is about five thousand LLM calls.
- You can set your own hard stop: graph.invoke(start, {"recursion_limit": 6}).
An agent that never answers, MAX_STEPS = 5
agent -> calculator -> agent -> calculator -> agent -> calculator -> agent -> calculator -> agent
stopped at step 5, answer: '' <- stopped, but says nothing
The same agent, no step check at all
GraphRecursionError: Recursion limit of 10007 reached without hitting a stop condition.
10007 node runs first
graph.invoke(start, {"recursion_limit": 6})
GraphRecursionError: Recursion limit of 6 reached without hitting a stop condition.Watch out: Treat recursion_limit as a crash barrier, not your step limit. Count steps in the state, route to a give-up node, and pass a recursion_limit sized to your loop - two nodes per round plus a little: with MAX_STEPS = 6, recursion_limit=20 is enough.
Example 2 - a real ReAct loop with llama3
Now llama3 makes the decisions. The parts:
- Step: a Pydantic model. action must be calculate, get_weather or final_answer; action_input is the text for it. with_structured_output forces llama3 to answer in this shape.
- agent: shows llama3 the question and the history, gets a Step, counts the step. A final_answer becomes the answer.
- tools: YOUR code runs the tool the model chose and adds "Action ..." and "Observation ..." to the history. The model decides; the program executes.
- A repeat guard in tools: if the exact same call is already in the history, it does not run it again and tells the model to answer.
- give_up and should_continue: the honest exit when the step limit is reached.
from typing import Literal, TypedDict
from langchain_ollama import ChatOllama
from langgraph.graph import END, START, StateGraph
from pydantic import BaseModel, Field
TOOLS = {"calculate": calculate, "get_weather": get_weather} # Lesson 2.13's safe tools
MAX_STEPS = 6
class Step(BaseModel):
action: Literal["calculate", "get_weather", "final_answer"]
action_input: str = Field(description="The expression, the city name, or the final answer text")
decide = ChatOllama(model="llama3", temperature=0).with_structured_output(Step)
SYSTEM = (
"You answer questions using two tools: get_weather(city) and calculate(expression). "
"Choose ONE next action. Use a tool for each piece of information you do not have yet. "
"When the Observations contain everything needed, reply with final_answer."
)
class AgentState(TypedDict):
question: str
history: list
step: int
action: str
action_input: str
answer: str
def agent(state: AgentState):
transcript = "\n".join([f"Question: {state['question']}"] + state["history"])
step = decide.invoke([("system", SYSTEM), ("human", transcript)])
update = {"step": state["step"] + 1, "action": step.action, "action_input": step.action_input}
if step.action == "final_answer":
update["answer"] = step.action_input
return update
def tools(state: AgentState):
call = f"Action: {state['action']}({state['action_input']!r})"
if call in state["history"]: # the same call again
done = state["history"][state["history"].index(call) + 1]
note = f"Observation: you already have this result ({done[13:]}). Do not repeat it; answer now if you can."
return {"history": state["history"] + [call, note]}
result = TOOLS[state["action"]](state["action_input"]) # your code runs the tool
return {"history": state["history"] + [call, f"Observation: {result}"]}
def give_up(state: AgentState):
return {"answer": f"Stopped after {state['step']} steps without an answer."}
def should_continue(state: AgentState) -> Literal["tools", "give_up", "__end__"]:
if state["answer"]:
return END
if state["step"] >= MAX_STEPS:
return "give_up"
return "tools"
builder = StateGraph(AgentState)
builder.add_node("agent", agent)
builder.add_node("tools", tools)
builder.add_node("give_up", give_up)
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", should_continue, ["tools", "give_up", END])
builder.add_edge("tools", "agent")
builder.add_edge("give_up", END)
graph = builder.compile()
question = "Should I bring an umbrella in Mumbai, and what's 12 * 8?"
start = {"question": question, "history": [], "step": 0, "action": "", "action_input": "", "answer": ""}
print(graph.invoke(start, {"recursion_limit": 20})["answer"])Should I bring an umbrella in Mumbai, and what's 12 * 8?
agent[get_weather('Mumbai')] -> tools: Rainy, 27°C
agent[calculate('12 * 8')] -> tools: 96
agent[final] "Yes, bring an umbrella in Mumbai, and the result of 12 * 8 is 96."
What's the weather in Delhi?
without the repeat guard: get_weather('Delhi') x3, then the answer
with the guard: get_weather('Delhi') -> agent repeats it -> "you already have this result" -> answer
Is it raining in Hyderabad, and what is (250 - 37) * 4?
agent[get_weather('Hyderabad')] -> tools: Cloudy, 29°C
agent[calculate('250 - 37 * 4')] -> tools: 102 <- the model dropped the brackets
agent[final] "... the result of (250 - 37) * 4 is 102." <- wrong: it is 852
graph.get_graph() edges
__start__ --> agent; agent -.-> tools; agent -.-> give_up; agent -.-> __end__;
tools --> agent; give_up --> __end__;What went right, what went wrong
We asked five questions. Each run took about 4 seconds:
- Right: the umbrella question took the path a person would - weather, then the calculation, then the answer.
- Wasted rounds: llama3 often repeated a call it had already made. For Delhi it called get_weather three times. The repeat guard cut that to one.
- Wrong answer: for (250 - 37) * 4 llama3 sent "250 - 37 * 4" - it dropped the brackets. The calculator correctly returned 102, and the model answered 102. The right answer is 852.
- Every node did its job, and the answer was still wrong. A loop guard cannot catch that - you need to check what the model sends, and test with questions whose answers you know.
Umbrella in Mumbai, and 12 * 8?get_weather -> calculate -> answer. Correct.What is 125 * 48?calculate twice, then 6000. Correct, one wasted round.Weather in Delhi?get_weather three times, then Sunny, 34°C. Correct, two wasted rounds - one with the repeat guard.Raining in Hyderabad, and (250 - 37) * 4?Sent "250 - 37 * 4", answered 102. Wrong - the right answer is 852.What is 17 * 23 + 9?calculate twice, then 400. Correct.Debugging a loop
Stream the run and, for each step, ask four questions:
- Which node ran?
- What did it change in the state?
- Which route did should_continue choose, and why?
- Did this round move closer to an answer? The same call with the same result is the first thing to fix.
- Keep the loop in the graph. A while True inside the agent node hides exactly what streaming would show you.
The recipe - and other loops
Every loop needs the same parts:
- 1. A node that does the work (agent).
- 2. An edge back (tools -> agent).
- 3. A router with an exit to END when the work is done.
- 4. A step count in the state, and a give-up route when it is too high.
- The same shape works for retries (call -> failed -> try again), validation (generate -> check -> fix), review (draft -> review -> revise) and planning (plan -> do -> re-plan).
- Lesson 3.5 replaces the hand-written tools node with LangGraph’s ready-made ToolNode.
Loops at a glance
The edge backMakes the cycle.
builder.add_edge("tools", "agent")should_continueExit, give up, or go round again.
add_conditional_edges("agent", should_continue, [...])Step count in stateYour own limit, checked by the router.
if state["step"] >= MAX_STEPS: return "give_up"
give_up nodeAn honest answer when the limit is hit.
return {"answer": "Stopped after ..."}recursion_limitLangGraph’s hard stop - default 10,007.
graph.invoke(state, {"recursion_limit": 20})GraphRecursionErrorRaised when the hard stop is hit.
from langgraph.errors import GraphRecursionError
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Stream the hard-coded graph with stream_mode="updates" and count the agent runs.”
“Make the agent never answer. Run it with MAX_STEPS, then without, then with recursion_limit=6.”
“Add a third tool to the llama3 graph - a currency converter - and ask a question that needs all three.”
“Ask the llama3 graph about (250 - 37) * 4 several times. Add a check that compares the expression with the numbers in the question.”
What usually goes wrong
A router that can only return the loop node never ends. Every cycle needs a route to END.
✗ def should_continue(state):
return "tools"✓ def should_continue(state):
if state["answer"]:
return END
...A correct exit can still be missed by a confused model. Without a count, LangGraph runs 10,007 nodes before stopping.
Ending at the limit with an empty answer leaves the user with nothing. Route to a node that explains.
✗ if state["step"] >= MAX_STEPS:
return END✓ if state["step"] >= MAX_STEPS:
return "give_up" # writes "Stopped after N steps"A while True inside the agent node defeats the graph - nothing to stream, nothing to extend. The edge back is the loop.
Observations come from the tools node, never from the model - the lesson from Module 1 and 2.14.
llama3 turned (250 - 37) * 4 into 250 - 37 * 4. The loop worked and the answer was wrong. Validate inputs and test with known answers.
Key points
- A cycle is an edge back to an earlier node: add_edge("tools", "agent").
- ReAct maps directly: agent node (think), tools node (act), history in state (observe).
- A conditional edge after the agent decides: END, give_up, or another round.
- Count steps in state and route to a give-up node - LangGraph’s own limit is 10,007.
- With llama3 deciding, the umbrella question ran weather -> calculate -> answer.
- Real loops repeat calls; a repeat guard in the tools node cut Delhi from three weather calls to one.
- A correct loop can still give a wrong answer: the model sent 250 - 37 * 4.
Quick check before you move on
Quiz
- 1.
In the hard-coded example, why does the agent node run twice?
- 2.
An agent hits MAX_STEPS and the router returns END. What is wrong with that?
- 3.
What did the repeat guard change?
- 4.
The loop answered (250 - 37) * 4 with 102. Which part failed?
Interview questions
How does a ReAct agent map onto LangGraph?
An agent node calls the model, a tools node executes the chosen action and records the observation in state, an edge leads from tools back to the agent, and a conditional edge after the agent exits to END when there is an answer.
How do you prevent an infinite agent loop?
A logical exit in the router, a step count in state with a give-up route, and a recursion_limit sized to the loop as the hard stop - the default is 10,007.
How would you implement a retry workflow?
A node that does the work and records success and an attempt count; a conditional edge that routes success onward, failure with attempts left back to the node, and failure without attempts to an escalation node.
Why keep the loop in the graph rather than in a while loop inside a node?
The graph makes every step visible - streamable, traceable, checkpointable - and lets you add nodes such as validation or human approval inside the loop without rewriting it.
A loop finishes but gives a wrong answer. Where do you look?
At each step’s state update: which action and arguments the model chose and what the tool returned. In our run the model sent the wrong expression; the fix is input validation and a set of test questions with known answers.
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...