Going in circles
A conditional edge can point back to a node that already ran. That one fact is the reason LangGraph exists.
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.
from typing_extensions import TypedDict
class State(TypedDict):
answer: str
tries: intA node that tries again
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.
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
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])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.
tries counter away and the answer never gets longer, so long_enough is never satisfied. That is the next lesson.- Change 12 to 5 and watch the loop end on the first attempt.
- Make
draftalways return"too short"and see what happens. Read the next lesson before you worry. - Print the whole state at the top of
draftand watch it change.
You understood something today that you didn't yesterday.