Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 32 ยท LangGraph Workflows

Conditional Edges and Loops

Route a LangGraph with add_conditional_edges, build loops with a back edge, set recursion limits and rebuild a ReAct agent by hand. Runnable Python stand-ins included.

A straight line of nodes is only the beginning. The real power of a graph is that the next step can depend on the current state. A conditional edge runs a small routing function after a node and uses its answer to pick the next node. Point one of those choices back at an earlier node and you have a loop. Branching plus looping is exactly what an agent is: call the model; if it asked for tools, run them and go back to the model; otherwise finish. In this lesson you build that agent by hand.

LangGraph is not available on this site, so real code is read-only. The runnable examples use a MiniGraph stand-in with the same method names as the real StateGraph, plus a scripted "model".

Conditional edges

Python
# Real LangGraph (read-only)
from typing import Literal, TypedDict
from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    text: str
    kind: str

def classify(state: State) -> dict:
    return {"kind": "question" if state["text"].endswith("?") else "statement"}

def route(state: State) -> Literal["answer", "acknowledge"]:
    return "answer" if state["kind"] == "question" else "acknowledge"

builder = StateGraph(State)
builder.add_node("classify", classify)
builder.add_node("answer", lambda s: {"text": "Let me look into that."})
builder.add_node("acknowledge", lambda s: {"text": "Noted."})

builder.add_edge(START, "classify")
builder.add_conditional_edges("classify", route)   # route() returns the next node's name
builder.add_edge("answer", END)
builder.add_edge("acknowledge", END)
graph = builder.compile()

add_conditional_edges(source, routing_function, mapping=None): after source finishes, the routing function receives the state and returns a node name (or END). If you supply a mapping dict, the function returns labels and the dict translates labels to node names. The Literal[...] return annotation lets LangGraph draw all possible paths in diagrams.

flowchart TD
    S(("START")) --> C["classify"]
    C -->|"question"| A["answer"]
    C -->|"statement"| K["acknowledge"]
    A --> E(("END"))
    K --> E

One decision point, two branches.

A MiniGraph with conditional edges

Python Stand-in: route by state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Loops are just edges that go back

A loop needs two things: an edge pointing to an earlier node, and a condition that eventually sends the flow to END. A classic use is generate, check, retry: write a draft, test it, and if it fails, go back and write again with the feedback.

Python Stand-in: generate, check, retry loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second run shows why the limit matters. In real LangGraph the limit is config={"recursion_limit": N} and exceeding it raises GraphRecursionError.

Rebuilding a ReAct agent

Now put branches and loops together. The graph has two nodes, model and tools. After model, a conditional edge checks whether the last AI message has tool calls. If yes, go to tools, then back to model. If no, finish.

Python
# Real LangGraph (read-only)
from langgraph.graph import StateGraph, START, END, MessagesState
from langgraph.prebuilt import ToolNode, tools_condition

model_with_tools = model.bind_tools(tools)

def call_model(state: MessagesState):
    return {"messages": [model_with_tools.invoke(state["messages"])]}

builder = StateGraph(MessagesState)
builder.add_node("model", call_model)
builder.add_node("tools", ToolNode(tools))        # runs every tool call in the last AI message
builder.add_edge(START, "model")
builder.add_conditional_edges("model", tools_condition)   # "tools" if tool_calls else END
builder.add_edge("tools", "model")                          # the loop
agent = builder.compile()

tools_condition is a prebuilt router and ToolNode is a prebuilt node that executes tool calls and returns the ToolMessage results. Everything create_agent does can be rebuilt this way, which is useful when you need an extra node (a guardrail check, a planner, a summarizer) in the middle.

flowchart TD
    S(("START")) --> M["model"]
    M -->|"tool_calls"| T["tools"]
    T --> M
    M -->|"no tool_calls"| E(("END"))

The agent graph: model, conditional edge, tools, back to model.

Python Stand-in: a ReAct agent as a graph

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Design tips

  • Keep routing functions pure and small: read the state, return a name. Put work in nodes.
  • Give every loop an exit condition and a recursion limit.
  • Store loop counters and feedback in state, so the next iteration can use them.
  • Name nodes after what they do (grade_documents, not node3); names appear in traces and diagrams.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does add_conditional_edges use to pick the next node?

    After the source node runs, the routing function returns the name of the next node or END.
  2. 2. How do you create a loop in a graph?

    A back edge plus a condition that eventually reaches END forms a loop.
  3. 3. What does tools_condition decide?

    It routes to the tools node if there are tool calls, otherwise to END.
  4. 4. What protects you from a loop whose exit condition never triggers?

    Exceeding recursion_limit raises GraphRecursionError instead of running forever.

Summary

  • A conditional edge runs a routing function on the state to choose the next node.
  • A loop is a back edge with an exit condition; always set a recursion limit.
  • The ReAct agent is two nodes, a conditional edge (tools_condition) and a back edge.
  • Rebuilding the agent by hand lets you add custom nodes such as guards and planners.

Next: Human in the Loop