Building Conditional Branch and Loop Graphs with LangGraph AI Agents

This tutorial demonstrates how to use LangGraph's low‑level API to create stateful conditional‑branch, loop, and combined graphs for AI agents, showing step‑by‑step definitions of Pydantic state models, node logic, edge configuration, compilation, and test execution with concrete code examples.

Fun with Large Models
Fun with Large Models
Fun with Large Models
Building Conditional Branch and Loop Graphs with LangGraph AI Agents

In this installment of the LangGraph AI Agent tutorial series, the author shows how to construct more complex graph patterns—conditional‑branch graphs, loop graphs, and a composite of both—using LangGraph's low‑level API.

1. Conditional Branch Graph

A MyState model is defined with fields x (int) and result (optional string). Three nodes are added: check_x: receives the state and forwards it unchanged. handle_even: marks result="even" when x is even. handle_odd: marks result="odd" when x is odd.

Conditional edges are created with add_conditional_edges using an is_even predicate, routing to handle_even or handle_odd. The start and end edges are linked, the graph is compiled, and tests show correct results for x=4 (even) and x=3 (odd).

from typing import Optional
from pydantic import BaseModel
from langgraph.graph import StateGraph, START, END

# Define structured state
class MyState(BaseModel):
    x: int
    result: Optional[str] = None

builder = StateGraph(MyState)

# Node logic
def check_x(state: MyState) -> MyState:
    print(f"[check_x] Received state: {state}")
    return state

def is_even(state: MyState) -> bool:
    return state.x % 2 == 0

def handle_even(state: MyState) -> MyState:
    print("[handle_even] x is even")
    return MyState(x=state.x, result="even")

def handle_odd(state: MyState) -> MyState:
    print("[handle_odd] x is odd")
    return MyState(x=state.x, result="odd")

builder.add_node("check_x", check_x)
builder.add_node("handle_even", handle_even)
builder.add_node("handle_odd", handle_odd)

builder.add_conditional_edges("check_x", is_even, {True: "handle_even", False: "handle_odd"})
builder.add_edge(START, "check_x")
builder.add_edge("handle_even", END)
builder.add_edge("handle_odd", END)

graph = builder.compile()
print("
Test x=4 (even)")
graph.invoke(MyState(x=4))
print("
Test x=3 (odd)")
graph.invoke(MyState(x=3))

2. Conditional Loop Graph

A LoopState model with a single integer field x is defined. An increment node adds 1 to x. The loop control uses add_conditional_edges with an is_done predicate that ends the graph when x > 10, otherwise it loops back to increment. Testing from x=6 shows the value increasing until the condition is met.

from pydantic import BaseModel
from langgraph.graph import StateGraph, START, END

class LoopState(BaseModel):
    x: int

builder = StateGraph(LoopState)

def increment(state: LoopState) -> LoopState:
    print(f"[increment] current x = {state.x}")
    return LoopState(x=state.x + 1)

builder.add_node("increment", increment)

def is_done(state: LoopState) -> bool:
    return state.x > 10

builder.add_conditional_edges("increment", is_done, {True: END, False: "increment"})
builder.add_edge(START, "increment")

graph = builder.compile()
print("
Execute loop until x > 10")
final_state = graph.invoke(LoopState(x=6))
print(f"[final result] -> x = {final_state['x']}")

3. Composite Conditional‑Loop Graph

A BranchLoopState model with fields x and done (bool) is introduced. Nodes: check_x: prints current x and returns state. increment: adds 1 to x (executed only for even values). done_node: marks done=True when x becomes odd.

Conditional edges route from check_x to increment if x is even, otherwise to done_node. An additional edge creates a loop from increment back to check_x. Tests demonstrate the flow for an initial even x=6 (enters loop) and an initial odd x=3 (directly finishes).

from pydantic import BaseModel
from typing import Optional
from langgraph.graph import StateGraph, START, END

class BranchLoopState(BaseModel):
    x: int
    done: Optional[bool] = False

def check_x(state: BranchLoopState) -> BranchLoopState:
    print(f"[check_x] current x = {state.x}")
    return state

def is_even(state: BranchLoopState) -> bool:
    return state.x % 2 == 0

def increment(state: BranchLoopState) -> BranchLoopState:
    print(f"[increment] x is even, +1 -> {state.x + 1}")
    return BranchLoopState(x=state.x + 1)

def done(state: BranchLoopState) -> BranchLoopState:
    print("[done] x is odd, ending")
    return BranchLoopState(x=state.x, done=True)

builder = StateGraph(BranchLoopState)
builder.add_node("check_x", check_x)
builder.add_node("increment", increment)
builder.add_node("done_node", done)
builder.add_conditional_edges("check_x", is_even, {True: "increment", False: "done_node"})
builder.add_edge("increment", "check_x")
builder.add_edge(START, "check_x")
builder.add_edge("done_node", END)

graph = builder.compile()
print("
Initial x=6 (even, enters loop)")
final_state1 = graph.invoke(BranchLoopState(x=6))
print("[final result1] ->", final_state1)
print("
Initial x=3 (odd, direct done)")
final_state2 = graph.invoke(BranchLoopState(x=3))
print("[final result2] ->", final_state2)

Special Note

LangGraph places all node names, state fields, and channel names in a single namespace and enforces strict conflict checking. To avoid ambiguity, node names should not duplicate field names (e.g., avoid a node named result when the state also contains result).

Conclusion

The article covered the essential techniques for building conditional‑branch, loop, and combined graphs with LangGraph's low‑level API, enabling developers to construct sophisticated control‑flow agents. The next tutorial will explore building a ReACT graph and integrating tool usage via the create_react_agent method.

PythonAI agentsLangGraphPydanticStateGraphconditional graphloop graph
Fun with Large Models
Written by

Fun with Large Models

Master's graduate from Beijing Institute of Technology, published four top‑journal papers, previously worked as a developer at ByteDance and Alibaba. Currently researching large models at a major state‑owned enterprise. Committed to sharing concise, practical AI large‑model development experience, believing that AI large models will become as essential as PCs in the future. Let's start experimenting now!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.