AI Hints
Home›LangGraph Tutorial›Safe Loops and Practice
LangGraph · Lesson 16 of 120

Stopping Loops

Exit conditions.

⏱ 2 min read▶ Video at 16:24🎓 Free
Watch this lesson in the LangGraph courseWatch on YouTube ↗Full LangGraph course

A loop that waits for success might wait forever, if success never comes. So good loops have two exits. One when the job is done, and one when we've tried enough times.

Stopping Loops
From the video: Stopping Loops
  • Success may never come
  • Two exits
  • Done, or tried enough

Retry with a limit

Call service pretends to call a flaky stock service. It takes the next result from a list, and counts the attempts. The router has three outcomes. Done if it worked, give up after three attempts, otherwise try again. Run it. The first run succeeds on the third try. The second never succeeds, so it gives up after three.

retry_loop.pypython
from typing import TypedDict
from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    results: list[str]
    attempts: int
    status: str

def call_service(s):
    status, rest = s["results"][0], s["results"][1:]
    return {"status": status, "results": rest, "attempts": s["attempts"] + 1}
def route(s):
    if s["status"] == "ok" or s["attempts"] >= 3: return END
    return "call_service"
b = StateGraph(State); b.add_node(call_service); b.add_edge(START, "call_service")
b.add_conditional_edges("call_service", route)
for results in [["timeout", "timeout", "ok"], ["timeout"] * 5]:
    out = b.compile().invoke({"results": results, "attempts": 0})
    print(out["status"], "after", out["attempts"], "attempts")
Output
ok after 3 attempts
timeout after 3 attempts

Exit conditions

Every loop needs an exit you can prove. A success check. A counter, with a maximum. Or a list that gets shorter each time, like our packing loop. Store the counter in the state, so the router can see it.

keyvalue
Successstop when done
Counterstop at a maximum
Shrinking liststop when empty
In stateso the router sees it

Summary

Good loops stop on success, or after a maximum number of tries. Keep the counter in the state. Next, LangGraph's own safety net for loops.

Key takeaways
  • Success exit
  • Max attempts
  • Counter in state
Next up: Recursion Limit — a safety net