AI Hints
Home›LangGraph Tutorial›Branches and Loops
LangGraph · Lesson 13 of 120

Conditional Edges

Choosing a path.

⏱ 2 min read▶ Video at 12:58🎓 Free
Watch this lesson in the LangGraph courseWatch on YouTube ↗Full LangGraph course

So far, our graphs always take the same path. Real processes branch. If a book is in stock, confirm the order. If not, put it on back order. A conditional edge chooses the next node, based on the state.

Conditional Edges
From the video: Conditional Edges
  • Same path every time
  • Real processes branch
  • Choose the next node

In stock or not?

The check node looks up the stock, and saves it. Route is a plain function. It reads the state, and returns the name of the next node. Add conditional edges attaches route to the check node. Run it. Dune is in stock, so it's confirmed. Circe isn't, so it goes to back order.

conditional.pypython
from typing import TypedDict
from langgraph.graph import StateGraph, START, END

STOCK = {"Dune": 3, "Circe": 0}

class State(TypedDict):
    title: str
    stock: int
    reply: str

def check(s):     return {"stock": STOCK.get(s["title"], 0)}
def route(s):     return "confirm" if s["stock"] > 0 else "backorder"
def confirm(s):   return {"reply": f"{s['title']}: in stock, order confirmed."}
def backorder(s): return {"reply": f"{s['title']}: out of stock, we'll email you."}

b = StateGraph(State)
b.add_node(check); b.add_node(confirm); b.add_node(backorder)
b.add_edge(START, "check"); b.add_conditional_edges("check", route)
for t in ["Dune", "Circe"]: print(b.compile().invoke({"title": t})["reply"])
Output
Dune: in stock, order confirmed.
Circe: out of stock, we'll email you.

How it flows

Here's the shape. Start goes to check. From check, the route function picks one of two nodes. Each of them writes a reply, and the run ends. Only one branch runs each time.

  1. START
  2. check
  3. route()
  4. confirm / backorder
  5. END
How it flows
From the video: How it flows

Summary

A conditional edge calls a routing function, which returns the next node's name. Only the chosen branch runs. Next, routing functions in more detail.

Key takeaways
  • add_conditional_edges
  • Route returns a name
  • One branch runs
Next up: Routing Functions — decide with code