A conditional edge is a function that looks at the graph state and returns the name of the next node, turning a buried if-statement into an inspectable routing decision. It is how an agent node routes to a tool node, to a finish node, or to a specialist sub-agent based on what the last step produced. Add the routing function, list the nodes it may return, and test every branch, because a branch that never runs is a branch that is broken in secret.
What you need
- Python with langgraph installed and a graph that already runs
- A routing decision the graph must make, such as tool call or finish
- The names of the nodes each branch should reach
Step 1: Write the routing function
Write a function that reads the state and returns the name of the next node. Keep it to the state it needs, and return one of the nodes you will list in the next step.
Step 2: Add the conditional edge with its node list
Add the conditional edge from the deciding node, passing the routing function and the list of nodes it may return. A node the function can return but you did not list is a route to nowhere.
Step 3: Run one input per branch and check the route
Run the graph with an input for each branch and confirm it reaches the right node each time. If a branch never runs, the routing function is reading the wrong piece of state.
Worked example: synthetic routing test
The table below is a synthetic example. It shows the expected result of conditional routing; no graph was run.
| Input | Expected route | Reached? |
|---|---|---|
| Needs a tool | tool node | Yes |
| Answer is ready | finish | Yes |
| Needs a specialist | specialist node | Yes |
Expected result (UNTESTED). each input reaches the node the routing function chose for it, with no input taking the wrong branch. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- A conditional edge can only return nodes you listed, so list every branch the function may choose.
- The routing function reads state, so a state key it needs but the graph never sets will route wrong.
- Test every branch, because a branch that never runs in testing will be the one that breaks in production.
