LangGraph Conditional Edges and Loops
A conditional edge lets a LangGraph graph choose its next node by looking at the state. You pass add_conditional_edges a function that returns the name of the next node, and the graph follows it. Point an edge back to an earlier node and you have a loop, which is exactly what an agent is: do some work, check, and repeat until done.
A routing function
The router reads the state and returns a string. This example classifies a number as small or large and sends it down different branches.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
number: int
label: str
def start_node(state: State) -> dict:
return {}
def small(state: State) -> dict:
return {"label": "small"}
def large(state: State) -> dict:
return {"label": "large"}
def route(state: State) -> str:
return "small" if state["number"] < 100 else "large"
builder = StateGraph(State)
builder.add_node("start_node", start_node)
builder.add_node("small", small)
builder.add_node("large", large)
builder.add_edge(START, "start_node")
builder.add_conditional_edges("start_node", route, ["small", "large"])
builder.add_edge("small", END)
builder.add_edge("large", END)
graph = builder.compile()
print(graph.invoke({"number": 7}))
print(graph.invoke({"number": 700}))
The first call prints a state with label set to small, the second with large. The third argument lists the possible targets, which helps LangGraph draw the graph correctly. You can also use a dictionary that maps the router's return values to node names.
Build a loop
A loop is just a conditional edge that sometimes points backwards. This graph keeps doubling a value until it passes a target:
class LoopState(TypedDict):
value: int
steps: int
def double(state: LoopState) -> dict:
return {"value": state["value"] * 2, "steps": state["steps"] + 1}
def check(state: LoopState) -> str:
return "done" if state["value"] >= 100 else "again"
b = StateGraph(LoopState)
b.add_node("double", double)
b.add_edge(START, "double")
b.add_conditional_edges("double", check, {"again": "double", "done": END})
loop_graph = b.compile()
print(loop_graph.invoke({"value": 3, "steps": 0}))
The result shows value of 192 after six steps. The mapping {"again": "double", "done": END} sends the router's answer to a node or to the end.
Why this is an agent
Replace the router with the rule "if the last message has tool calls, go to the tools node, otherwise end" and you have the standard tool-calling agent. LangGraph ships a helper for that rule called tools_condition, covered in a later post. The pattern generalizes: any decision your code or your model makes can become a router.
Protect against endless loops
A bug in the router can make a graph loop forever, and each lap may cost money if a model is inside. LangGraph stops a run after a number of steps and raises an error. Set the limit yourself in the config:
from langgraph.errors import GraphRecursionError
try:
loop_graph.invoke({"value": 0, "steps": 0}, config={"recursion_limit": 10})
except GraphRecursionError:
print("stopped: too many steps")
Starting from zero, doubling never reaches 100, so the guard fires after ten steps. Always carry a counter or a limit in any loop that calls a model.
Tips for good routers
- Keep routers small and pure: read state, return a name, change nothing.
- Return strings that match node names exactly; a typo is a runtime error.
- Put the decision data in state (a counter, a flag, a score) so you can inspect it later.
- Test routers like ordinary functions with sample states.
- Add a maximum-attempts counter to every retry loop.
Routing on model output
Routers become powerful when they depend on a model's decision. A common pattern is to ask the model to classify the request, store the label in state, and let the router read the label. The model does the thinking and your code keeps control over what can happen next. Because the possible destinations are a fixed list of node names, the model cannot send the run somewhere you did not allow.
from typing import Literal, TypedDict
from pydantic import BaseModel
from langchain.chat_models import init_chat_model
class Decision(BaseModel):
intent: Literal["billing", "technical"]
classifier = init_chat_model("anthropic:claude-sonnet-5-5").with_structured_output(Decision)
class TicketState(TypedDict):
ticket: str
intent: str
def classify(state: TicketState) -> dict:
decision = classifier.invoke(state["ticket"])
return {"intent": decision.intent}
def pick(state: TicketState) -> str:
return state["intent"]
Wire pick with add_conditional_edges("classify", pick, ["billing", "technical"]) and each ticket flows to the matching node. Using a Literal type for the label means the structured output can only be one of the allowed values.
Testing graphs without a model
Because routers and nodes are plain functions, you can test most of a graph with ordinary unit tests. Call the router with a hand-made state and check the string it returns, or invoke the compiled graph with fake nodes in place of model calls. Doing this early catches wiring mistakes, such as a misspelled node name, long before you spend tokens on a real run.
Comments
No comments yet. Have a question or a tip? Be the first to share it.