🚀
langraph
5. Conditional Graph

Conditional Graph 🚧

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
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
 
class AgentState(TypedDict):
    number1: int
    operation: str
    number2: int
    finalNumber: int
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"
 
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"

result = app.invoke({"number1": 15, "number2": 30, "operation": "+"})
 
print(result["finalNumber"])
OUTPUT:
 
'45'

© 2024 Driptanil Datta.All rights reserved

Made with Love ❤️

Last updated on Mon Oct 20 2025