๐Ÿš€
๐Ÿ•ธ๏ธ LangGraph
5. Conditional Graph
AI

Conditional Graph ๐Ÿšง

1. Implement conditional logic to route the flow of data to different nodes.

Mar 202510 min read

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'

ยฉ 2026 Driptanil Datta. All rights reserved.

Software Developer & Engineer

Disclaimer:The content provided on this blog is for educational and informational purposes only. While I strive for accuracy, all information is provided "as is" without any warranties of completeness, reliability, or accuracy. Any action you take upon the information found on this website is strictly at your own risk.

Copyright & IP:Certain technical content, interview questions, and datasets are curated from external educational sources to provide a centralized learning resource. Respect for original authorship is maintained; no copyright infringement is intended. All trademarks, logos, and brand names are the property of their respective owners.

System Operational

Built with Love โค๏ธ | Last updated: Mar 16 2026