Skip to content

Conditional Graph

Updated
17 Sept 2026
1 min read
0 sections
Page 14 of 18
Langgraph

Objectives ✅

  1. Implement conditional logic to route the flow of data to different nodes.
  2. Use Start and End nodes, to manage entry and exit points explicitly.
  3. Design multiple nodes to perform different operations(addition, subtraction).
  4. Create a router node to handel decision -making and control graph flow
python
from typing import TypedDict
from langgraph.graph import StateGraph, START, END

class AgentState(TypedDict):
    number1: int
    operation: str
    number2: int
    finalNumber: int
python
def adder(state: AgentState) -> AgentState:
    """This node adds two numbers together."""
    state['finalNumber'] = state['number1'] + state['number2']
    return state

def subtractor(state: AgentState) -> AgentState:
    """This node subtracts two numbers."""
    state["finalNumber"] = state["number1"] - state["number2"]
    return state

def decide_next_node(state: AgentState) -> AgentState:
    """This node will select the next node of the graph"""
    if state["operation"] == "+":
        return "addition_operation"
    elif state["operation"] == "-":
        return "subtraction_operation"
python
graph = StateGraph(AgentState)

graph.add_node("add_node", adder)
graph.add_node("subtract_node", subtractor)
graph.add_node("router", lambda state: state) # Pass-through Node

graph.add_edge(START, "router")
graph.add_conditional_edges(
    "router",
    decide_next_node,
    {
        # Edge: Node
        "addition_operation": "add_node",
        "subtraction_operation": "subtract_node"
    }
)
graph.add_edge("add_node", END)

app = graph.compile()
conditional graph
conditional graph
python
result = app.invoke({"number1": 15, "number2": 30, "operation": "+"})

print(result["finalNumber"])
powershell
OUTPUT:

'45'