check_age
is not a node, it should be the router from greet
to other three nodes, below is my code:
# https://stackoverflow.com/questions/79702608/why-the-condition-in-the-langraph-is-not-working
from IPython.display import display, Image
from langgraph.graph import StateGraph, START, END
from typing import TypedDict, Literal
class PersonDetails(TypedDict):
name: str
age: int
def greet(state: PersonDetails):
print(f"Hello {state["name"]}")
return state
# Add Literal here to indicates where the router should go
def check_age(state: PersonDetails) -> Literal["can_drink", "can_drive", "minor"]:
age = state["age"]
if age >= 21:
return "can_drink"
elif age >= 16:
return "can_drive"
else:
return "minor"
def can_drink(state: PersonDetails):
print("You can legally drink 🍺")
return state
def can_drive(state: PersonDetails):
print("You can drive 🚗")
return state
def minor(state: PersonDetails):
print("You're a minor 🚫")
return state
graph = StateGraph(PersonDetails)
graph.add_node("greet", greet)
graph.add_node("can_drink", can_drink)
graph.add_node("can_drive", can_drive)
graph.add_node("minor", minor)
graph.add_edge(START, "greet")
graph.add_conditional_edges(
"greet",
check_age,
{
"can_drink": "can_drink",
"can_drive": "can_drive",
"minor": "minor"
}
)
graph.add_edge("can_drink", END)
graph.add_edge("can_drive", END)
graph.add_edge("minor", END)
app = graph.compile()
# can should the whole graph in xx.ipynb notebook
display(Image(app.get_graph().draw_mermaid_png()))