AI Agents with LangGraph

Nov 12 2024 · Python 3.12, LangGraph 0.2.x, JupyterLab 4.2.4

Lesson 02: Fundamentals of LangGraph

State Demo

Episode complete

Play next episode

Next
Transcript

State Demo

Open the empty state-demo.ipynb notebook in the Starter folder. You’ll make a graph that adds toppings to a pizza. First, define your State class:

from typing import TypedDict

class PizzaState(TypedDict):
  toppings: list[str]
  quantity: int

Define a function to add cheese to the pizza:

def add_cheese(state):
  quantity = state["quantity"] + 1
  return {"toppings": ["cheese"], "quantity": quantity}

Then, construct a one-node graph:

from langgraph.graph import StateGraph

graph = StateGraph(PizzaState)

graph.add_node("cheese", add_cheese)

graph.set_entry_point("cheese")
graph.set_finish_point("cheese")

app = graph.compile()

initial_state = {"toppings": [], "quantity": 0}
app.invoke(initial_state)

To see how the state is modified, add another function below add_cheese:

def add_meat(state):
  quantity = state["quantity"] + 1
  return {"toppings": ["meat"], "quantity": quantity}

Also, add a node for “meat”:

graph.add_node("meat", add_meat)

Connect the cheese and meat nodes:

graph.add_edge("cheese", "meat")

Then, update the END node:

graph.set_finish_point("meat")

Rerun those cells. You can see that the quantity is 2 as you’d expect, but there’s no cheese now. To fix that, add the add reducer function. Return to the top cell and add the Annotated type and add operator. Then, modify the toppings entry:

from typing import TypedDict, Annotated
from operator import add

class PizzaState(TypedDict):
  toppings: Annotated[list[str], add]
  quantity: int

Rerun all the cells. This time you can see that toppings has both meat and cheese. The meat was appended to the list rather than replacing the cheese.

See forum comments
Cinema mode Download course materials from Github
Previous: State Next: Project Demo