HOW-TO · RAG
How to Create Conditional Edges in LangGraph
Target environment
Ubuntu 24.04 · Ollama 0.4.x
PREREQUISITES
LangGraph graph defined with basic nodes/edges, Python 3.10+
What this does
Conditional edges let a LangGraph workflow branch dynamically based on node output — for example, routing to a tool node when the LLM requests a tool call, or ending the loop when complete.
Steps
- Define a routing function. This function receives the current state and returns the name of the next node.
from typing import TypedDict, Annotated
from langgraph.graph import StateGraph, END
class State(TypedDict):
input: str
score: int
def route_by_score(state: State) -> str:
if state["score"] > 5:
return "high_score"
elif state["score"] > 0:
return "medium_score"
else:
return END
- Add conditional edges to the graph. Use
add_conditional_edges.
workflow = StateGraph(State)
workflow.add_node("start", lambda s: s)
workflow.add_node("high_score", lambda s: {"score": s["score"]})
workflow.add_node("medium_score", lambda s: {"score": s["score"]})
workflow.set_entry_point("start")
workflow.add_conditional_edges(
"start",
route_by_score,
{
"high_score": "high_score",
"medium_score": "medium_score",
END: END,
}
)
workflow.add_edge("high_score", END)
workflow.add_edge("medium_score", END)
app = workflow.compile()
- Test routing with different inputs.
print(app.invoke({"input": "test", "score": 10})) # routes to high_score
print(app.invoke({"input": "test", "score": 3})) # routes to medium_score
print(app.invoke({"input": "test", "score": 0})) # routes to END
- Agent-style conditional routing. Check for tool calls in the last message.
def should_continue(state: State) -> str:
last_msg = state["messages"][-1]
if hasattr(last_msg, "tool_calls") and last_msg.tool_calls:
return "tools"
return END
workflow.add_conditional_edges(
"agent",
should_continue,
{"tools": "tools", END: END}
)
- Use a dictionary as routing map. The third argument maps return values to node names.
Verification
python -c "
from langgraph.graph import StateGraph, END
from typing import TypedDict
class S(TypedDict):
v: int
def route(s):
return 'a' if s['v'] > 0 else END
g = StateGraph(S)
g.add_node('start', lambda s: s)
g.add_node('a', lambda s: {'v': s['v']})
g.set_entry_point('start')
g.add_conditional_edges('start', route, {'a': 'a', END: END})
g.add_edge('a', END)
app = g.compile()
print(app.invoke({'v': 5})['v'])
# Expected: 5
"
Common failures
- Route function returns an unmapped value. If the function returns a string not in the routing dict, LangGraph raises
ValueError. Every possible return value must have a mapping. - Missing
ENDin routing map. A path that returnsENDbut omits it from the dict causes a runtime error. Always includeEND: END. - Condition reads state before it's populated. Nodes earlier in the graph must write the fields the condition reads. Add a default value in the state initialization.
- Version mismatch - The installed package or runtime differs from the command shown; check the version first and rerun the smallest verification command.
- Local environment drift - Another service, virtual environment, model, or path is being used; print the active binary path and configuration before changing the guide steps.
Related guides
- How to Set Up Basic LangGraph Agent from Scratch
- How to Implement Tool Calling in LangGraph Agents