LangGraphLangGraph 1.2 · Python 3.10+
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
37 small wins to finish your pathNext lesson

Going in circles

A conditional edge can point back to a node that already ran. That one fact is the reason LangGraph exists.

The same node, more than once
draft. Writes an answer. Each time it runs it tries again, and counts the attempt.Step 1 of 4

A state that can count

The counter is not decoration. It is the thing that changes between attempts, and without something changing the loop could never end.

python
from typing_extensions import TypedDict

class State(TypedDict):
    answer: str
    tries: int

A node that tries again

python
def draft(state):
    tries = state["tries"] + 1
    print("attempt", tries)
    return {"answer": "too short" if tries < 3 else "a good long answer", "tries": tries}

The counter is the important part. Every run of this node moves the state forward, and that is what lets the loop finish.

A question with two answers

A conditional edge, exactly like lesson 6. The difference is where one of the answers points.

python
from langgraph.graph import END

def long_enough(state):
    return END if len(state["answer"]) > 12 else "draft"

Returning "draft" names a node that has already run. Naming it again is all it takes to go round. END is the way out, and every loop needs one.

Wire it, with the edge pointing back

python
from langgraph.graph import StateGraph, START

builder = StateGraph(State)
builder.add_node("draft", draft)
builder.add_edge(START, "draft")
builder.add_conditional_edges("draft", long_enough, ["draft", END])
Example
print(builder.compile().invoke({"answer": "", "tries": 0})["answer"])

Three attempts, then the answer. There is no while loop anywhere in that program. The repetition comes entirely from an edge pointing backwards.

Why this is a big deal

A straight sequence of steps can only go forwards. Anything that has to check its own work and try again has to be able to go back.

That is the difference between a program that runs a fixed list of steps and one that keeps working until the job is done. It is also the difference between a workflow and an agent, and every agent you build later is this loop with a model making the decision instead of a length check.

Notice what is stopping it
Take the tries counter away and the answer never gets longer, so long_enough is never satisfied. That is the next lesson.
Try it yourself
  • Change 12 to 5 and watch the loop end on the first attempt.
  • Make draft always return "too short" and see what happens. Read the next lesson before you worry.
  • Print the whole state at the top of draft and watch it change.

You understood something today that you didn't yesterday.