AI Hints
Home›LangGraph Tutorial›Time Travel
LangGraph · Lesson 47 of 120

Forking

A different path.

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

Replay runs the same steps again. Forking goes further. Change the state at a past checkpoint, then run from there. It's like asking, what if the customer had ordered three copies?

Forking
From the video: Forking
  • Replay repeats
  • Forking changes the past
  • What if?

What if they ordered three?

We find the checkpoint just before price. Update state, given that checkpoint's config, changes the quantity there, and returns a new config, a fork. Invoking from the fork reruns price and receipt with the new quantity. Run it. The original receipt says two copies. The fork says three, with a new total.

fork.pypython
from order_graph import graph

config = {"configurable": {"thread_id": "order-5"}}
print("original:", graph.invoke({"title": "dune", "quantity": 2}, config)["receipt"])

before_price = next(s for s in graph.get_state_history(config) if s.next == ("price",))
fork = graph.update_state(before_price.config, {"quantity": 3})
print("fork:    ", graph.invoke(None, fork)["receipt"])
Output
original: 2 x Dune = £19.98
fork:     3 x Dune = £29.97
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())

Forks in practice

Forks are how you correct an agent's mistake, mid way, and let it continue. Or try different choices, and compare the results. The original path stays in the history, untouched.

keyvalue
Correcta wrong step
Explorewhat if
Comparedifferent results
Originalkept in history

Summary

Update state at a past checkpoint creates a fork. Invoke from the fork to run a different path. Next, a quiz on persistence.

Key takeaways
  • update_state(old config)
  • Returns a fork
  • invoke(None, fork)
Next up: Persistence Quiz — test yourself