AI Hints
Home›LangGraph Tutorial›Inspecting and Editing State
LangGraph · Lesson 44 of 120

Editing State

Update_state.

⏱ 2 min read▶ Video at 46:19🎓 Free
Watch this lesson in the LangGraph courseWatch on YouTube ↗Full LangGraph course

Sometimes the saved state needs fixing. A customer changes their mind, or staff correct a mistake. Update state writes to a thread's state, just as if a node had returned that update.

Editing State
From the video: Editing State
  • Fix saved state
  • Customers change their minds
  • update_state

Changing a saved order

First we run the order pipeline on a thread. Then update state changes the quantity, from two to three. The update goes through the reducers, like any node update. Run it. Get state shows the new quantity. Notice the total hasn't changed, because no node has run since. That's what the next lessons fix.

update_state.pypython
from order_graph import graph

config = {"configurable": {"thread_id": "order-2"}}
graph.invoke({"title": "dune", "quantity": 2}, config)
print("before:", graph.get_state(config).values)

graph.update_state(config, {"quantity": 3})
print("after: ", graph.get_state(config).values)
Output
before: {'title': 'Dune', 'quantity': 2, 'total': 19.98, 'receipt': '2 x Dune = £19.98'}
after:  {'title': 'Dune', 'quantity': 3, 'total': 19.98, 'receipt': '2 x Dune = £19.98'}
Also uses order_graph.py
from typing import TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import StateGraph, START, END

PRICES = {"Dune": 9.99, "Circe": 10.99}

class Order(TypedDict):
    title: str
    quantity: int
    total: float
    receipt: str

def clean(s):
    return {"title": s["title"].strip().title()}
def price(s):
    return {"total": round(PRICES[s["title"]] * s["quantity"], 2)}
def receipt(s):
    return {"receipt": f"{s['quantity']} x {s['title']} = £{s['total']}"}

b = StateGraph(Order)
b.add_sequence([clean, price, receipt])
b.add_edge(START, "clean"); b.add_edge("receipt", END)
graph = b.compile(checkpointer=InMemorySaver())

Updating safely

Update state uses the same reducers as nodes. For a messages key, a new message is appended, or replaces one with the same ID. Updates are saved as a new checkpoint, so the old state is still in the history.

keyvalue
Reducersapply as usual
Messagesappend or replace
New checkpointold one kept
Use forcorrections

Summary

Update state changes a thread's saved state, through the reducers, as a new checkpoint. Next, looking back at every checkpoint.

Key takeaways
  • graph.update_state
  • Goes through reducers
  • Saved as a checkpoint
Next up: State History — every checkpoint