Lesson 52.2 · 2 of 6 · 6 min read · Reviewed 24 Nov 2026
Conditional edges and cycles
By the end, you can
- Write a conditional edge that routes on the state.
- Add a cycle with a guard so it always ends.
A graph with only fixed edges is a pipeline. Two features turn it into something that can think again: conditional edges and cycles.
Conditional edges
A conditional edge is a router: a plain function that reads the state and returns the name of the next node.
def after_test(state):
if state["passed"]:
return "review"
if state["attempts"] >= MAX_ATTEMPTS:
return "give_up"
return "fix"
The router does no work of its own. It only looks at fields earlier nodes wrote and picks a path. That makes it easy to unit test: build three states, check three answers.
Route on facts, not prose. state["passed"] came from a real test run. A router that searches the model’s reply for the word “done” breaks the first time the model writes “not done yet”.
Cycles
A cycle is an edge that points back to an earlier node. In the coding graph, fix leads back to test, so the run goes round until the tests pass:
plan -> write -> test --passed--> review
^ \--failed--> fix
|__________________|
Cycles are what separate a graph agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. from a pipeline. They give you retry, self-correction (chapter 48) and replanning (47.3), all drawn explicitly.
Every cycle needs a guard
A cycle that depends on something succeeding can run forever if it never does. Use two layers:
- Your own guard. Keep a counter in the state, increment it in the loop, and have the router send the run to a
give_upnode at the cap. The run ends on purpose with a clear outcome: “gave up after 4 attempts, last error: …”. - The framework’s backstop. Most graph runtimes cap the total number of steps per run (LangGraph calls it a recursion limit) and raise an error when it is hit. Treat that as a safety net, not your design.
Pick the cap from data. If most fixes land in one or two rounds and almost none after four, a cap of four wastes little and catches the stuck runs.
A worked trace
| Step | Node | State after |
|---|---|---|
| 1 | write | attempts 1 |
| 2 | test | passed false, 2 failures |
| 3 | fix | attempts 2 |
| 4 | test | passed false, 1 failure |
| 5 | fix | attempts 3 |
| 6 | test | passed true |
| 7 | review | approved |
The router ran after every test step and chose fix, fix, then review.
Common mistakes
- Counter never increments. The guard exists but the loop node forgets to bump it. Test the router with a high count.
- Guard checked in the wrong place. Check it in the router that closes the cycle, so no path skips it.
- Silent give-up. The cap is hit and the run reports success. The give-up node should say clearly what failed.
Key points
- A conditional edge is a small function that reads the state and returns the name of the next node.
- Cycles (edges that point back to an earlier node) are what let a graph retry, fix and refine.
- Every cycle needs a guard: a counter in the state, checked by the router, plus the framework's own step limit as a backstop.
- Route on facts in the state (a test result, a score, a flag), not on the model's free text.
Route a cycle with a guard
Write a conditional edge that routes on state facts and bounds its cycle with an attempts counter.
You will have: A tested router function and two runs of the cycle: one that passes and one that gives up.
Steps
- Run the starter: two router tests fail and the stuck run crashes into the step limit.
- Write after_test() so it routes on passed and attempts, never on text.
- Run the four router tests until all pass.
- Check the stuck run now ends at give_up, before the safety net.
- Add a test for attempts = 3 and passed = False.
Done when
- Router tests: 4/4 passed.
- The good run reaches review after 2 attempts.
- The stuck run ends with give_up after 4 attempts, not a crash.
Open in the Playground No API key needed.
Starter code (Python)
# A router reads facts in the state and names the next node. Unit test it, then run a guarded cycle.
MAX_ATTEMPTS = 4
def after_test(s):
# TODO: "review" if passed; "give_up" if attempts has reached MAX_ATTEMPTS; otherwise "fix"
return "fix"
TESTS = [
({"passed": True, "attempts": 1}, "review"),
({"passed": False, "attempts": 1}, "fix"),
({"passed": False, "attempts": 4}, "give_up"),
({"passed": True, "attempts": 4}, "review"),
]
ok = sum(after_test(s) == want for s, want in TESTS)
print(f"router tests: {ok}/{len(TESTS)} passed")
def run(fix_works_on_round):
"""Simulated loop: the fix succeeds on the given round (None means it never does)."""
s = {"passed": False, "attempts": 0}
path = []
for _ in range(50): # safety net, like a framework's step limit
s["attempts"] += 1 # the fix node starts each round
s["passed"] = s["attempts"] == fix_works_on_round
nxt = after_test(s)
path.append(nxt)
if nxt != "fix":
return f"{nxt} after {s['attempts']} attempts"
return "crashed into the step limit"
print("good run:", run(fix_works_on_round=2))
print("stuck run:", run(fix_works_on_round=None))
Show a solution
# A router reads facts in the state and names the next node. Unit test it, then run a guarded cycle.
MAX_ATTEMPTS = 4
def after_test(s):
if s["passed"]:
return "review"
if s["attempts"] >= MAX_ATTEMPTS:
return "give_up"
return "fix"
TESTS = [
({"passed": True, "attempts": 1}, "review"),
({"passed": False, "attempts": 1}, "fix"),
({"passed": False, "attempts": 4}, "give_up"),
({"passed": True, "attempts": 4}, "review"),
]
ok = sum(after_test(s) == want for s, want in TESTS)
print(f"router tests: {ok}/{len(TESTS)} passed")
def run(fix_works_on_round):
"""Simulated loop: the fix succeeds on the given round (None means it never does)."""
s = {"passed": False, "attempts": 0}
path = []
for _ in range(50): # safety net, like a framework's step limit
s["attempts"] += 1 # the fix node starts each round
s["passed"] = s["attempts"] == fix_works_on_round
nxt = after_test(s)
path.append(nxt)
if nxt != "fix":
return f"{nxt} after {s['attempts']} attempts"
return "crashed into the step limit"
print("good run:", run(fix_works_on_round=2))
print("stuck run:", run(fix_works_on_round=None))