AI Hints
Home›LangGraph Tutorial›Branches and Loops
LangGraph · Lesson 15 of 120

Loops

Going round again.

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

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.

Loops
From the video: Loops
  • 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.

loop.pypython
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")
Output
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.

keyvalue
Agentsmodel ↔ tools
Writersdraft ↔ check
Retriesuntil success
Alwaysa 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
Next up: Stopping Loops — exit conditions