Loops
Going round again.
A conditional edge can point back to an earlier node. That makes a loop. It's how a graph repeats work until a job is done, like packing books into boxes, three at a time.

- Point back
- Make a loop
- Repeat until done
Packing in a loop
Pack takes up to three books from the list, and adds them as a box. The routing function checks if any books are left. If so, it goes back to pack. If not, it ends. Run it. Seven books are packed into three boxes, and the loop stops on its own.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
books: list[str]
boxes: list[list[str]]
def pack(s):
box, rest = s["books"][:3], s["books"][3:]
print("packed", box)
return {"books": rest, "boxes": s["boxes"] + [box]}
def more(s):
return "pack" if s["books"] else END
b = StateGraph(State)
b.add_node(pack); b.add_edge(START, "pack"); b.add_conditional_edges("pack", more)
books = ["Dune", "Emma", "Circe", "Ulysses", "Beloved", "Matilda", "Persuasion"]
print(len(b.compile().invoke({"books": books, "boxes": []})["boxes"]), "boxes")packed ['Dune', 'Emma', 'Circe'] packed ['Ulysses', 'Beloved', 'Matilda'] packed ['Persuasion'] 3 boxes
Loops in real apps
Loops are everywhere in LangGraph. An agent loops between the model and its tools. A writer loops, drafting and checking. A process retries, until it succeeds. Every loop needs a way out, which is the next lesson.
| key | value |
|---|---|
| Agents | model ↔ tools |
| Writers | draft ↔ check |
| Retries | until success |
| Always | a way out |
Summary
A conditional edge that points back makes a loop. The routing function decides when to stop. Next, making sure loops always stop.
Key takeaways- Edge points back
- Repeat the work
- Route decides when to stop