08F.14 The Functional API and Streaming

Agents & multimodalLesson 14 of 1719,550 wordsReference14 parts
Module 08F · 0 of 10 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17

08F.10 taught the Graph API: you declare nodes, edges and a shared state, and LangGraph runs the result. That is not the only way to get LangGraph's runtime, and this lesson covers the other way and the one feature almost every user-facing agent needs. The first half is the Functional API: two decorators, @entrypoint and @task, that give an ordinary Python function checkpoints, resume after a pause or a crash, memory between calls and streaming, without drawing a graph. The second half is streaming: how a run that takes seconds or minutes shows progress while it works, through the stream modes (values, updates, messages, custom, checkpoints, tasks, debug), token streaming from models, custom events from your own code, streams out of subgraphs and tools, the newer event-streaming API, and what changes when you run all this on threads and event loops.

The two halves belong together for a practical reason. The Functional API is the shortest path from "I have a working Python function that calls a model and some tools" to "that function survives a crash, waits for a human and streams to a browser", and both of its selling points (replay after a pause, streaming progress) are the same machinery the Graph API uses. Reading them side by side shows what is really LangGraph (the runtime) and what is only the way you describe the work (nodes or functions). Nearly every sample runs on your machine without an API key (plain Python, scripted fake models, in-memory checkpointers) and every output shown is the real output of that run; the few that call a provider are labelled.

What you'll learn

  • What @entrypoint and @task are, what they return and accept, the single-argument rule, why generators are refused, and how tasks return futures that start running immediately
  • How to run tasks in parallel, where a task may be called from, what must serialize, and the silent trap of a task whose future nobody reads
  • Short-term memory with previous and entrypoint.final(value=, save=), the injectable parameters (config, store, writer, runtime, previous) and long-term memory with a store
  • How resume really works for a function (it replays from the first line), what belongs in a task, how to resume after a crash, and what happens when you change a workflow while runs are paused
  • Retries, caching and timeouts on tasks and entrypoints, and how to choose between the Graph API and the Functional API, including how to wrap code you already have
  • Every stream mode with its real payloads, the v1 and v2 chunk formats, output_keys, print_mode and durability, and the differences between invoke and stream
  • Token streaming with messages mode, filtering by node and tag, the nostream tag, disable_streaming, push_message, and streaming any LLM client through custom
  • Custom events with get_stream_writer(), the writer parameter and runtime.stream_writer, from nodes, tools, tasks and entrypoints
  • Streaming from subgraphs and agents (subgraphs=True, namespaces), and streaming interrupts
  • Event streaming (stream_events(version="v3"), beta): projections, the single-consumer rule, transformers, protocol events and the caveats
  • A production SSE gateway with error events and clean cancellation, and the concurrency facts: worker threads, one event loop, max_concurrency, same-thread races and Python version limits
  • Legacy streaming APIs you will meet in old tutorials, a decision table and a failure gallery

What you don't need

  • An API key. Every runnable sample uses plain-Python functions, a scripted fake model or none at all. Two samples call a real provider and are labelled illustrative (7.2 and 7.7).
  • Graph basics (state, reducers, Command, Send, compile). 08F.10 owns them. This lesson builds on its first look at invoke versus stream (08F.10, 10.2).
  • Checkpointers and the store in depth. 08F.11 owns backends, threads, state history, time travel and serializers. Here an in-memory checkpointer is the thing that makes previous and replay possible.
  • interrupt, retries, timeouts, caching and cancellation as features. 08F.12 owns them in full. Here they appear only where the Functional API uses them.
  • Subgraph design and multi-agent patterns (08F.13); this lesson covers only what a stream looks like when it crosses a subgraph boundary.
  • LangSmith tracing, testing and the Agent Server (11A.5), and provider-level streaming and SSE basics (03.3).

Setup

You need Python 3.11 or newer and uv; see 08F.4, Part 5 for the full project setup.

bash
uv init streaming-lab --bare --python 3.13 && cd streaming-lab   # first time only
uv add langgraph langchain
uv add python-dotenv langchain-openai openai                      # only for the two provider samples (7.2, 7.7)
uv add langgraph-checkpoint-sqlite aiosqlite                      # only for the async-checkpointer sample (12.4)
# or: pip install langgraph langchain python-dotenv langchain-openai openai langgraph-checkpoint-sqlite aiosqlite

No .env file is needed for the runnable samples. Run each with uv run python file.py. The streaming samples that need a model share one helper file, fakes.py: a scripted chat model that streams its reply word by word, so you can watch real token streaming with no key. It is a trimmed copy of the helper from 08F.8, Part 1.3; save it next to the samples that import it.

python
"""fakes.py: a scripted chat model that streams, so streaming samples run with no API key."""
import json
import re

from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessageChunk
from langchain_core.outputs import ChatGenerationChunk


class StreamingFakeModel(GenericFakeChatModel):
    """Replays the AIMessages you give it: text word by word, tool calls as one argument chunk each."""

    def bind_tools(self, tools, **kwargs):          # lets create_agent bind tools to the fake
        return self

    def _stream(self, messages, stop=None, run_manager=None, **kwargs):
        msg = self._generate(messages, stop=stop, run_manager=run_manager, **kwargs).generations[0].message
        for piece in (re.split(r"(\s)", msg.text) if msg.text else []):
            chunk = ChatGenerationChunk(message=AIMessageChunk(content=piece, id=msg.id))
            if run_manager:
                run_manager.on_llm_new_token(piece, chunk=chunk)
            yield chunk
        for i, call in enumerate(msg.tool_calls):
            yield ChatGenerationChunk(message=AIMessageChunk(
                content="", id=msg.id,
                tool_call_chunks=[{"name": call["name"], "args": json.dumps(call["args"]), "id": call["id"], "index": i}]))
        yield ChatGenerationChunk(message=AIMessageChunk(content="", id=msg.id, chunk_position="last"))

Versions (current at time of writing, read from PyPI and the docs on 14 November 2026; langgraph ships a patch release roughly weekly, so treat these as a snapshot): langgraph 1.2.22, langgraph-prebuilt 1.1.2, langgraph-checkpoint 4.3.2, langchain 1.5.0 and langchain-core 1.8.0. Every sample marked as run was executed on 14 November 2026 with Python 3.13.14 and these versions using uv run --no-project --python 3.13 --with langgraph --with langchain python sample.py; one sample (8.4) was also run on Python 3.10.20 and says so. The docs pages and the package source were checked on the same day. Event streaming (stream_events(version="v3")) is beta in these releases and labelled so throughout.


What you must be able to do after this lesson#

  • Write a workflow with entrypoint and task
  • Choose between the Graph API and the Functional API
  • Stream state updates with the right stream mode
  • Stream model tokens with messages mode
  • Emit custom events with a stream writer

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Do I have to rewrite my agent as a graph to get checkpoints?" Part 1 and 4.4
"I forgot .result() and got a Future." 1.4
"My task failed and the workflow said it finished." 1.5
"How do I keep a conversation or a basket between calls?" Part 2
"Why did my function run twice after the human answered?" 3.1 and 3.2
"Graph API or Functional API?" Part 4
"What is the difference between values, updates and messages?" Part 5 and Part 6
"How do I stream tokens, and only the ones I want?" Part 7
"How do I show a progress bar from inside a node or tool?" Part 8
"My agent's tokens vanished when I put it inside another graph." Part 9
"Everyone says to use stream_events(version=\"v3\")." Part 10
"How do I send all this to a browser, and stop when the user leaves?" Part 11
"Is a LangGraph node thread-safe?" Part 12
"This tutorial uses astream_events and stream_mode tuples." Part 13

Part 1: The Functional API: a workflow as an ordinary function#

1.1 What it is, and where the docs now put it#

The Functional API wraps ordinary functions with LangGraph's runtime features: persistence, memory, human-in-the-loop and streaming. It has two building blocks:

  • @entrypoint marks the function that is the start of a workflow. It manages execution, interrupts and checkpointing.
  • @task marks a discrete unit of work inside it, such as an API call or a model call. A call to a task returns a future immediately and the task runs in the background; its result is saved with the checkpoint, so a resumed run does not repeat it.

Both APIs compile to the same runtime object (a Pregel, 08F.10, 1.3), so everything you learn about invoke, stream, checkpointers and interrupts applies to both. The difference is only how you describe the work.

The documentation's position changed during 2026, and you should know it before you read older tutorials. The current Functional API page is a short concept reference that says: use it "when you already have existing code or are using a different framework and want to deploy it on LangSmith without rewriting that agent as a graph", and "prefer the Graph API for building new agents". Its comparison table points new LangGraph agents to the Graph API and existing agents from other frameworks (the Claude Agent SDK, Strands, CrewAI, AutoGen and others) to the Functional API, with a separate guide for deploying them on the Agent Server (link in Further resources). Older material presents the two as equal alternatives and builds long examples (essay writing with a human review, a hand-written ReAct agent) in the functional style. Those examples still work; the recommendation is what moved.

1.2 Your first entrypoint and task#

python
# f01_first.py: the smallest @entrypoint and @task, run three ways
from langgraph.func import entrypoint, task


@task
def shout(text: str) -> str:
    return text.upper()


@entrypoint()
def workflow(name: str) -> str:
    greeting = shout(f"hello, {name}").result()   # a task call returns a future; .result() waits for it
    return greeting + "!"


print("type of workflow :", type(workflow).__name__)
print("invoke           :", workflow.invoke("ana"))
print("stream (default) :", list(workflow.stream("ana")))
print("stream 'values'  :", list(workflow.stream("ana", stream_mode="values")))
print("stream 'updates' :", list(workflow.stream("ana", stream_mode="updates")))
print("shout is a       :", type(shout).__name__)
try:
    shout("x")                                 # a task called from ordinary code, outside any run
except RuntimeError as exc:
    print("outside a run    :", type(exc).__name__, exc)
Output7 lines
type of workflow : Pregel
invoke           : HELLO, ANA!
stream (default) : [{'shout': 'HELLO, ANA'}, {'workflow': 'HELLO, ANA!'}]
stream 'values'  : ['HELLO, ANA!']
stream 'updates' : [{'shout': 'HELLO, ANA'}, {'workflow': 'HELLO, ANA!'}]
shout is a       : _TaskFunction
outside a run    : RuntimeError Called get_config outside of a runnable context

Reading the output line by line:

  • workflow is a Pregel. @entrypoint() did not wrap your function in a decorator object; it compiled it. You call .invoke, .stream, .get_state and the rest directly on it. Note the parentheses: it is @entrypoint(), with options inside when you need them.
  • A task call returns a future. shout(...) started the task and gave back a handle; .result() waits for it. The entrypoint decides when to wait.
  • The default stream mode of an entrypoint is updates. You get one chunk per finished task, keyed by the task's name (shout), and one chunk for the entrypoint itself, keyed by its name (workflow) and holding its return value. This is what to expect in a progress display: tasks as they finish, then the whole function.
  • values mode emits once, at the end. A graph emits its full state after every step; an entrypoint has no shared state, so the only value is the final one.
  • A task cannot be called from ordinary code. The last line shows the failure: outside a running entrypoint, a graph node or another task, there is no run context for the task to attach to. The error mentions get_config, which is not obvious, so remember what it means: "you are not inside a LangGraph run".

1.3 The entrypoint rules, and what each error looks like#

python
# f02_rules.py: what @entrypoint accepts and rejects
import asyncio
from importlib.metadata import version

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint, task

print("langgraph", version("langgraph"), "| langchain", version("langchain"), "| langchain-core", version("langchain-core"))


def attempt(label, build):
    try:
        result = build()
        print(f"{label:34s} ok -> {result!r}")
    except Exception as exc:  # noqa: BLE001
        print(f"{label:34s} {type(exc).__name__}: {exc}")


# 1. no parameter
def no_param():
    @entrypoint()
    def wf() -> str:
        return "x"
    return wf
attempt("no parameter", no_param)


# 2. a generator
def generator():
    @entrypoint()
    def wf(x: int):
        yield x
    return wf
attempt("generator function", generator)


# 3. two required parameters: the input is ONE value
@entrypoint()
def two(a: int, b: int) -> int:
    return a + b

attempt("two params, one input", lambda: two.invoke(1))
attempt("two params, a dict input", lambda: two.invoke({"a": 1, "b": 2}))


# 4. the recommended shape for several values: one dict
@entrypoint()
def one_dict(args: dict) -> int:
    return args["a"] + args["b"]

attempt("dict input", lambda: one_dict.invoke({"a": 1, "b": 2}))


# 5. name of the node, and the Pregel object
@entrypoint()
def my_flow(x: int) -> int:
    return x + 1

print("node names in the graph           :", list(my_flow.nodes))
print("stream (default)                  :", list(my_flow.stream(1)))

# 6. get_graph: the Functional API has no static graph to draw
attempt("draw_mermaid()", lambda: my_flow.get_graph().draw_mermaid())

# 7. checkpointer: thread_id needed, input and output must serialize
@entrypoint(checkpointer=InMemorySaver())
def with_cp(x: int) -> int:
    return x

attempt("checkpointer, no thread_id", lambda: with_cp.invoke(1))
attempt("checkpointer, thread_id", lambda: with_cp.invoke(1, {"configurable": {"thread_id": "t"}}))


class Opaque:
    pass


@entrypoint(checkpointer=InMemorySaver())
def returns_opaque(x: int):
    return Opaque()

attempt("checkpointer, returns an object", lambda: returns_opaque.invoke(1, {"configurable": {"thread_id": "t"}}))


# 8. entrypoint without checkpointer: any object may flow
@entrypoint()
def no_cp(x: int):
    return Opaque()

attempt("no checkpointer, returns an object", lambda: type(no_cp.invoke(1)).__name__)


# 9. async entrypoint
@entrypoint()
async def async_flow(x: int) -> int:
    await asyncio.sleep(0)
    return x * 2

print("async ainvoke                     :", asyncio.run(async_flow.ainvoke(4)))
attempt("async entrypoint with invoke", lambda: async_flow.invoke(4))
Output16 lines
langgraph 1.2.22 | langchain 1.5.0 | langchain-core 1.8.0
no parameter                       ValueError: Entrypoint function must have at least one parameter
generator function                 NotImplementedError: Generators are not supported in the Functional API.
two params, one input              TypeError: two() missing 1 required positional argument: 'b'
two params, a dict input           TypeError: two() missing 1 required positional argument: 'b'
dict input                         ok -> 3
node names in the graph           : ['my_flow']
stream (default)                  : [{'my_flow': 2}]
draw_mermaid()                     ok -> '---\nconfig:\n  flowchart:\n    curve: linear\n---\ngraph TD;\n\tmy_flow(my_flow)\n\t__start__([<p>__start__</p>]):::first\n\t__end__([<p>__end__</p>]):::last\n\t__start__ --> my_flow;\n\tmy_flow -.-> __end__;\n\tclassDef default fill:#f2f0ff,line-height:1.2\n\tclassDef first fill-opacity:0\n\tclassDef last fill:#bfb6fc\n'
checkpointer, no thread_id         ValueError: Checkpointer requires one or more of the following 'configurable' keys: thread_id, checkpoint_ns, checkpoint_id
checkpointer, thread_id            ok -> 1
checkpointer, returns an object    TypeError: Type is not msgpack serializable: Opaque
no checkpointer, returns an object ok -> 'Opaque'
async ainvoke                     : 8
async entrypoint with invoke       TypeError: No synchronous function provided to "async_flow".
Either initialize with a synchronous function or invoke via the async API (ainvoke, astream, etc.)

Collected rules:

Rule What happens if you break it
The function takes one input parameter (use a dict, a dataclass or a Pydantic model for several values) With no parameter: ValueError: Entrypoint function must have at least one parameter. With two required parameters you get a plain TypeError at call time, because LangGraph passes the single input to the first parameter only
The function is a normal function or async def, not a generator NotImplementedError: Generators are not supported in the Functional API. Stream through the stream modes instead of yielding
An async def entrypoint is run with ainvoke or astream invoke raises TypeError: No synchronous function provided; the reverse (a sync function under ainvoke) works
With a checkpointer, every call needs a thread_id in config["configurable"] ValueError: Checkpointer requires one or more of the following 'configurable' keys: thread_id, ...
With a checkpointer, the return value must serialize TypeError: Type is not msgpack serializable: Opaque. Without a checkpointer any object may flow out (the sample returned an instance of a class)

get_graph() still works on an entrypoint, and the sample shows what it draws: a single node named after your function. That is the honest meaning of "no static graph visualization". The structure of a functional workflow is the code of the function, and the places it reveals itself at run time are the stream (task names) and, with LangSmith, the trace (11A.5).

The full set of options, from the 1.2.22 source (langgraph.func):

text
@entrypoint(
    checkpointer=None,      # a checkpointer: required for previous, interrupts and resume
    store=None,             # a store for long-term memory (read it as runtime.store)
    cache=None,             # a cache backend, needed for cache_policy to take effect
    context_schema=None,    # type of the run-scoped context (read it as runtime.context)
    cache_policy=None,      # CachePolicy: cache the whole entrypoint by its input
    retry_policy=None,      # RetryPolicy or a sequence of them: retry the whole function
    timeout=None,           # float, timedelta or TimeoutPolicy: async entrypoints only
)
@task(name=None, retry_policy=None, cache_policy=None, timeout=None)   # bare @task works too

Two older keyword names still work and warn: config_schema (use context_schema) and retry (use retry_policy); 1.5 shows the warnings.

1.4 Tasks, futures and parallelism#

A task call starts the task immediately. The entrypoint blocks only when it asks for the result. That makes parallelism the default, and sequential code the thing you have to write deliberately:

python
# f03_parallel.py: task futures start immediately; waiting is explicit
import time

from langgraph.func import entrypoint, task


@task
def slow_square(n: int) -> int:
    time.sleep(0.5)
    return n * n


@entrypoint()
def sequential(numbers: list[int]) -> list[int]:
    return [slow_square(n).result() for n in numbers]       # wait inside the loop: one after the other


@entrypoint()
def parallel(numbers: list[int]) -> list[int]:
    futures = [slow_square(n) for n in numbers]            # start all four
    return [f.result() for f in futures]                   # then wait


@entrypoint()
def forgot_result(numbers: list[int]):
    futures = [slow_square(n) for n in numbers]
    return [type(f).__name__ for f in futures]             # never waits: returns the type of the futures


for label, wf in [("sequential", sequential), ("parallel", parallel)]:
    start = time.perf_counter()
    result = wf.invoke([1, 2, 3, 4])
    print(f"{label:11s} {result} in {time.perf_counter() - start:.1f}s")

print("forgot .result():", forgot_result.invoke([1, 2]))
Output3 lines
sequential  [1, 4, 9, 16] in 2.0s
parallel    [1, 4, 9, 16] in 0.5s
forgot .result(): ['Future', 'Future']

Waiting inside the loop (slow_square(n).result()) ran the four half-second calls one after another, 2.0 seconds. Starting all four first and then collecting (futures = [...] then [f.result() for f in futures]) took 0.5 seconds. The third workflow shows the opposite mistake: it never waited, so it returned the futures themselves. The rule of thumb: start every independent task before you wait for any of them.

The async form uses await on the task and asyncio.gather for parallelism. Async tasks need Python 3.11 or newer (the source docstring says so, and 12.5 shows what breaks on 3.10):

python
# f05_async.py: async entrypoint and tasks, gather, and the docstring bug
import asyncio
import time

from langgraph.func import entrypoint, task


@task
async def fetch(n: int) -> int:
    await asyncio.sleep(0.4)
    return n * 10


@entrypoint()
async def correct(numbers: list[int]) -> list[int]:
    futures = [fetch(n) for n in numbers]
    return await asyncio.gather(*futures)       # await the gather


@entrypoint()
async def one_by_one(numbers: list[int]) -> list[int]:
    return [await fetch(n) for n in numbers]


@entrypoint()
async def missing_await(numbers: list[int]):
    futures = [fetch(n) for n in numbers]
    return asyncio.gather(*futures)             # the docstring form: no await


async def main():
    for label, wf in [("gather", correct), ("await in a loop", one_by_one)]:
        start = time.perf_counter()
        print(f"{label:16s}", await wf.ainvoke([1, 2, 3]), f"in {time.perf_counter() - start:.1f}s")
    try:
        out = await missing_await.ainvoke([1, 2, 3])
        print("missing await    ", out)
    except Exception as exc:  # noqa: BLE001
        print("missing await    ", type(exc).__name__, str(exc)[:100])


asyncio.run(main())
Output3 lines
gather           [10, 20, 30] in 0.4s
await in a loop  [10, 20, 30] in 1.2s
missing await     <_GatheringFuture finished result=[10, 20, 30]>

Three details. gather took 0.4 seconds for three 0.4-second tasks, while awaiting in a loop took 1.2. The third entrypoint reproduces a bug that is in the @task source docstring: its async example reads return asyncio.gather(*futures) without an await. Without a checkpointer that returned an un-awaited _GatheringFuture object as the workflow's result instead of the list; with a checkpointer the same code fails with TypeError: Type is not msgpack serializable: _GatheringFuture (checked on the same versions). The correct form is return await asyncio.gather(*futures), which is also what the docs page's own async example does. If you copy from the docstring, add the await.

Where a task may be called from (docs and source): inside an entrypoint, inside another task, and inside a Graph API node. Tasks calling tasks works, and the same sample file in 1.5 shows it. A task inside a graph node gives that node the same replay protection a functional workflow has, which matters when the node contains an interrupt():

python
# f11_task_in_node.py: a @task called from a Graph API node, and the same job written both ways
from typing_extensions import TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import task
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt

calls = []


@task
def send_email(to: str) -> str:
    calls.append(to)
    return f"sent to {to}"


class State(TypedDict):
    to: str
    result: str


def notify(state: State):
    receipt = send_email(state["to"]).result()      # remembered if this node is replayed after an interrupt
    interrupt("anything else?")
    return {"result": receipt}


graph = (StateGraph(State).add_node(notify).add_edge(START, "notify").add_edge("notify", END)
         .compile(checkpointer=InMemorySaver()))
cfg = {"configurable": {"thread_id": "n"}}
graph.invoke({"to": "ana@example.com", "result": ""}, cfg)
print(graph.invoke(Command(resume="no"), cfg), "| email sent", len(calls), "time(s)")
print("graph nodes:", list(graph.get_graph().nodes))
Output2 lines
{'to': 'ana@example.com', 'result': 'sent to ana@example.com'} | email sent 1 time(s)
graph nodes: ['__start__', 'notify', '__end__']

The node notify runs twice (the interrupt and the resume, 08F.12, 1.6), but the email was sent once, because send_email is a task whose result was restored on the second run. Without the task, a plain call to the email function would have sent two.

1.5 Task options, failure, and the future nobody reads#

Tasks take retry_policy, cache_policy, timeout and name. Entrypoints take the same three policies. 08F.12 owns the semantics (retry rules and default_retry_on in Part 7, timeouts in Part 8, caching in Part 9); this sample shows how each looks on the functional side:

python
# f10_options.py: retry_policy, cache_policy, timeout and name on tasks and entrypoints
import asyncio
import time

from langgraph.cache.memory import InMemoryCache
from langgraph.func import entrypoint, task
from langgraph.types import CachePolicy, RetryPolicy, TimeoutPolicy

attempts = {"flaky": 0, "slow": 0, "entry": 0}


# 1. retry on a task
@task(retry_policy=RetryPolicy(max_attempts=3, initial_interval=0.01, jitter=False))
def flaky(x: int) -> int:
    attempts["flaky"] += 1
    if attempts["flaky"] < 3:
        raise ConnectionError("temporary")
    return x * 2


@entrypoint()
def with_retry(x: int) -> int:
    return flaky(x).result()


print("retry       :", with_retry.invoke(21), "after", attempts["flaky"], "attempts")


# 2. cache on a task: needs cache= on the entrypoint
@task(cache_policy=CachePolicy(ttl=60))
def expensive(x: int) -> int:
    attempts["slow"] += 1
    return x * x


@entrypoint(cache=InMemoryCache())
def cached(x: int) -> int:
    return expensive(x).result()


print("cache       :", [cached.invoke(4), cached.invoke(4), cached.invoke(5)], "body ran", attempts["slow"], "times")
print("cache cleared:", expensive.clear_cache(cached.cache) if hasattr(cached, "cache") else "n/a")
print("after clear :", cached.invoke(4), "body ran", attempts["slow"], "times")


# 3. cached updates stream
print("updates     :", list(cached.stream(4, stream_mode="updates")))


# 4. name= changes the name used in streams
@task(name="square_it")
def sq(x: int) -> int:
    return x * x


@entrypoint()
def named(x: int) -> int:
    return sq(x).result()


print("task name   :", list(named.stream(3)))


# 5. timeout: async only
try:
    @task(timeout=1.0)
    def sync_with_timeout(x: int) -> int:
        return x
except Exception as exc:  # noqa: BLE001
    print("sync timeout:", type(exc).__name__, str(exc)[:130])


@task(timeout=0.2)
async def slow_async(x: int) -> int:
    await asyncio.sleep(1)
    return x


@entrypoint()
async def with_timeout(x: int) -> int:
    return await slow_async(x)


async def main():
    start = time.perf_counter()
    try:
        await with_timeout.ainvoke(1)
    except Exception as exc:  # noqa: BLE001
        print("async timeout:", type(exc).__name__, str(exc)[:100], f"after {time.perf_counter() - start:.1f}s")


asyncio.run(main())


# 6. entrypoint-level retry_policy re-runs the WHOLE function
@entrypoint(retry_policy=RetryPolicy(max_attempts=3, initial_interval=0.01, jitter=False))
def whole(x: int) -> int:
    attempts["entry"] += 1
    if attempts["entry"] < 3:
        raise ConnectionError("boom")
    return x


print("entry retry :", whole.invoke(7), "after", attempts["entry"], "attempts")


# 7. deprecated names
import warnings

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")

    @task(retry=RetryPolicy())
    def old(x: int) -> int:
        return x

    @entrypoint(config_schema=dict)
    def old_ep(x: int) -> int:
        return x

for w in caught:
    print("warning     :", w.category.__name__, str(w.message)[:110])
Output11 lines
retry       : 42 after 3 attempts
cache       : [16, 16, 25] body ran 2 times
cache cleared: None
after clear : 16 body ran 3 times
updates     : [{'expensive': 16, '__metadata__': {'cached': True}}, {'cached': 16}]
task name   : [{'square_it': 9}, {'named': 9}]
sync timeout: ValueError Node timeouts are only supported for async nodes because sync Python execution cannot be safely cancelled in-process. Task 'sync_w
async timeout: NodeTimeoutError Node 'slow_async' exceeded its run timeout of 0.200s (elapsed: 0.202s). after 0.2s
entry retry : 7 after 3 attempts
warning     : LangGraphDeprecatedSinceV05 `retry` is deprecated and will be removed. Please use `retry_policy` instead. Deprecated in LangGraph V0.5 to
warning     : LangGraphDeprecatedSinceV10 `config_schema` is deprecated and will be removed. Please use `context_schema` instead. Deprecated in LangGrap

What the sample proved:

  • Retry on a task re-runs only that task. The flaky function failed twice and succeeded on its third attempt, and max_attempts counts the first attempt (08F.12, 7.2).
  • A task cache needs a cache backend on the entrypoint (cache=InMemoryCache()) as well as cache_policy on the task. Two calls with the same input ran the body once; the second call came back in the updates stream with '__metadata__': {'cached': True}. clear_cache on the task function empties its entries.
  • name= changes the key in streams (square_it instead of sq) and the name in traces. Rename a task and anything that filters your stream by name must change too.
  • Timeouts are async only. A sync task with timeout= fails when the decorator runs (ValueError: Node timeouts are only supported for async nodes because sync Python execution cannot be safely cancelled in-process); an async task times out with NodeTimeoutError (08F.12, Part 8).
  • An entrypoint-level retry_policy re-runs the whole function, so prefer it for coarse transient failures and put a retry_policy on a task when only one call is flaky.
  • The deprecated retry= and config_schema= names warn (LangGraphDeprecatedSinceV05, LangGraphDeprecatedSinceV10) and are removed in a later major version.

Now the failure behaviour, which has one result that surprises almost everyone:

python
# f14_task_errors.py: where a task's exception surfaces, nesting, and futures read twice
from langgraph.func import entrypoint, task

ran = []


@task
def explode(label: str) -> str:
    ran.append(label)
    raise ValueError(f"{label} failed")


@task
def inner(x: int) -> int:
    return x + 1


@task
def outer(x: int) -> int:
    return inner(x).result() * 10          # a task may call another task


@entrypoint()
def never_read(_: str) -> str:
    explode("unread")                      # started, never waited for
    return "finished normally"


@entrypoint()
def read_it(_: str) -> str:
    return explode("read").result()


@entrypoint()
def two_failures(_: str) -> str:
    a, b = explode("first"), explode("second")
    return a.result() + b.result()


@entrypoint()
def nested(x: int) -> list[int]:
    future = outer(x)
    return [future.result(), future.result()]      # a future can be read more than once


for label, wf, arg in [("never_read", never_read, "x"), ("read_it", read_it, "x"), ("two_failures", two_failures, "x"), ("nested", nested, 4)]:
    try:
        print(f"{label:12s} ->", wf.invoke(arg))
    except Exception as exc:  # noqa: BLE001
        print(f"{label:12s} -> raised {type(exc).__name__}: {exc}")
print("tasks that ran:", ran)
Output5 lines
never_read   -> finished normally
read_it      -> raised ValueError: read failed
two_failures -> raised ValueError: first failed
nested       -> [50, 50]
tasks that ran: ['unread', 'read', 'first', 'second']

Also visible: a future can be read twice (nested returned [50, 50]), and tasks can call tasks (outer called inner and multiplied).

1.6 What has to serialize#

With a checkpointer, results are stored, so they must serialize. The sample checks the three common cases:

python
# f04_serialise.py: with a checkpointer, task inputs and outputs have to serialize
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint, task


class Opaque:
    def __init__(self):
        self.value = 1


@task
def make_object(x: int):
    return Opaque()


@task
def take_object(obj) -> int:
    return obj.value


@task
def make_set(x: int):
    return {1, 2, 3}


def run(label, wf):
    try:
        print(f"{label:30s} ok -> {wf.invoke(1, {'configurable': {'thread_id': label}})!r}")
    except Exception as exc:  # noqa: BLE001
        print(f"{label:30s} {type(exc).__name__}: {str(exc)[:110]}")


@entrypoint(checkpointer=InMemorySaver())
def task_returns_object(x: int):
    return make_object(x).result().value

@entrypoint(checkpointer=InMemorySaver())
def task_takes_object(x: int):
    return take_object(Opaque()).result()

@entrypoint(checkpointer=InMemorySaver())
def task_returns_set(x: int):
    return sorted(make_set(x).result())

@entrypoint()
def no_checkpointer(x: int):
    return make_object(x).result().value

run("task returns an object", task_returns_object)
run("task takes an object", task_takes_object)
run("task returns a set", task_returns_set)
run("no checkpointer, same code", no_checkpointer)
Output4 lines
task returns an object         TypeError: Type is not msgpack serializable: Opaque
task takes an object           ok -> 1
task returns a set             ok -> [1, 2, 3]
no checkpointer, same code     ok -> 1

A task's return value must serialize when a checkpointer is configured (Type is not msgpack serializable: Opaque), and the same code runs fine without a checkpointer. Sets, and the other types the default serializer knows, are fine (08F.11 owns serializers). The docs and the source docstring also say task inputs must serialize when a checkpointer is enabled; in 1.2.22 the in-memory checkpointer accepted a task input that was a plain class instance (task takes an object printed ok), so that rule is not enforced the same way everywhere. Do not rely on the leniency: a durable checkpointer, a retry or a cache key can make the input matter, and passing plain data (strings, numbers, dicts, lists, dataclasses, Pydantic models) is the safe habit. Return an ID or a dict from a task, and rebuild the rich object (a database session, an HTTP client, a loaded model) inside the task that needs it.


Part 2: Memory across runs: previous, entrypoint.final and injected parameters#

Deep-dive

2.1 previous: the last value saved on this thread#

A workflow with a checkpointer remembers one value per thread. Add a keyword-only parameter named previous and LangGraph fills it with the value saved by the last run on the same thread_id; on the first run it is None. By default the saved value is whatever the function returns. To return one thing and save another, return entrypoint.final(value=..., save=...):

python
# f06_previous.py: short-term memory with `previous` and entrypoint.final
from typing import Any

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint

# 1. the documented example: return one value, save another
@entrypoint(checkpointer=InMemorySaver())
def doubler(number: int, *, previous: Any = None) -> entrypoint.final[int, int]:
    previous = previous or 0
    return entrypoint.final(value=previous, save=2 * number)

cfg = {"configurable": {"thread_id": "a"}}
print("doubler(3):", doubler.invoke(3, cfg))
print("doubler(1):", doubler.invoke(1, cfg))
print("doubler(5):", doubler.invoke(5, cfg))
print("other thread:", doubler.invoke(7, {"configurable": {"thread_id": "b"}}))
print("saved state:", doubler.get_state(cfg).values)

# 2. no entrypoint.final: the return value is what is saved, so `previous` is last time's answer
@entrypoint(checkpointer=InMemorySaver())
def running_total(amount: int, *, previous: int | None = None) -> int:
    return (previous or 0) + amount

cfg = {"configurable": {"thread_id": "t"}}
print("running_total:", [running_total.invoke(n, cfg) for n in (10, 5, 1)])

# 3. a chat transcript: return the reply, save the whole history
@entrypoint(checkpointer=InMemorySaver())
def chat(text: str, *, previous: list | None = None) -> entrypoint.final[str, list]:
    history = (previous or []) + [("user", text)]
    reply = f"you have said {sum(1 for r, _ in history if r == 'user')} thing(s)"
    return entrypoint.final(value=reply, save=history + [("ai", reply)])

cfg = {"configurable": {"thread_id": "chat"}}
print(chat.invoke("hi", cfg))
print(chat.invoke("again", cfg))
print("history saved:", chat.get_state(cfg).values)

# 4. no checkpointer: previous is None, always
@entrypoint()
def stateless(x: int, *, previous: Any = None) -> str:
    return f"previous={previous!r}"

print("no checkpointer:", stateless.invoke(1), stateless.invoke(2))

# 5. positional use of entrypoint.final is not allowed
try:
    entrypoint.final(1, 2)
except TypeError as exc:
    print("positional final:", exc)

# 6. a wrong number of type arguments
try:
    entrypoint.final[int]
except TypeError as exc:
    print("final[int]:", type(exc).__name__, exc)

# 7. history of saves across invocations
print("checkpoints:", len(list(chat.get_state_history(cfg))))
Output13 lines
doubler(3): 0
doubler(1): 6
doubler(5): 2
other thread: 0
saved state: 2
running_total: [10, 15, 16]
you have said 1 thing(s)
you have said 2 thing(s)
history saved: you have said 2 thing(s)
no checkpointer: previous=None previous=None
positional final: entrypoint.final.__init__() takes 1 positional argument but 3 were given
final[int]: TypeError Too few arguments for <class 'langgraph.func.entrypoint.final'>; actual 1, expected at least 2
checkpoints: 4

Walk through it:

  1. doubler is the documented example. The first call returned 0 (previous was None, so previous or 0) and saved 2 * 3 = 6. The second call returned 6, the value saved by the first call, and saved 2. The third returned 2. A call on another thread started from None again: memory is per thread.
  2. get_state(cfg).values shows what the workflow returned (2), not what it saved. The saved value (10 after the third call) is what previous will hold next time; this is easy to misread when you debug with get_state.
  3. running_total has no entrypoint.final, so the return value is also the saved value: [10, 15, 16].
  4. chat is the useful shape. It returns a short reply to the caller and saves the whole history list, so the next call receives the full history in previous. Without entrypoint.final you would have to return the whole history every time.
  5. Without a checkpointer previous is always None: it exists only when you pass one.
  6. entrypoint.final takes keyword arguments only (value= and save=; positional use is a TypeError), and its annotation takes exactly two type arguments, entrypoint.final[ReturnType, SaveType] (final[int] raises). An un-parameterized entrypoint.final annotation is allowed.
  7. Each invocation wrote two checkpoints, so get_state_history listed four after two calls (08F.11 covers the history and time travel).

2.2 Injected parameters#

Besides previous, an entrypoint (and a task) can ask LangGraph for run objects by declaring a parameter with the right name and annotation:

Parameter Annotation What you get
previous any (keyword-only) The value saved by the last run on this thread (entrypoint only; needs a checkpointer)
config RunnableConfig The run configuration: thread_id, tags, metadata, callbacks
store BaseStore (annotation optional) The store passed to @entrypoint(store=...); also runtime.store
writer StreamWriter A function that emits custom stream events; also runtime.stream_writer (Part 8)
runtime Runtime (or Runtime[ContextType]) A bundle: context, store, stream_writer, previous, execution_info and more (08F.10, Part 9)
python
# f07_inject.py: injectable parameters of an entrypoint and a task
from dataclasses import dataclass
from typing import Any

from langchain_core.runnables import RunnableConfig
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint, task
from langgraph.runtime import Runtime
from langgraph.store.memory import InMemoryStore
from langgraph.types import StreamWriter


@dataclass
class Ctx:
    user: str


@task
def lookup(key: str, *, config: RunnableConfig) -> str:
    return f"task saw thread {config['configurable']['thread_id']!r}"


@entrypoint(checkpointer=InMemorySaver(), store=InMemoryStore(), context_schema=Ctx)
def wf(
    payload: dict,
    *,
    previous: Any = None,
    config: RunnableConfig,
    store,
    writer: StreamWriter,
    runtime: Runtime[Ctx],
):
    writer({"stage": "start"})
    runtime.store.put(("notes", runtime.context.user), "n1", {"text": payload["note"]})
    saved = store.get(("notes", runtime.context.user), "n1").value
    return {
        "previous": previous,
        "thread": config["configurable"]["thread_id"],
        "user": runtime.context.user,
        "saved": saved,
        "store_is_runtime_store": store is runtime.store,
        "task": lookup("k").result(),
        "runtime_fields": sorted(f for f in ("context", "store", "stream_writer", "previous", "execution_info") if hasattr(runtime, f)),
    }


cfg = {"configurable": {"thread_id": "inj"}}
print(wf.invoke({"note": "hello"}, cfg, context=Ctx(user="ana")))
print("custom stream:", list(wf.stream({"note": "x"}, cfg, context=Ctx(user="ana"), stream_mode="custom")))
Output2 lines
{'previous': None, 'thread': 'inj', 'user': 'ana', 'saved': {'text': 'hello'}, 'store_is_runtime_store': True, 'task': "task saw thread 'inj'", 'runtime_fields': ['context', 'execution_info', 'previous', 'store', 'stream_writer']}
custom stream: [{'stage': 'start'}]

Everything arrived: the previous value (None on a first run), the thread id read from config, the run context (context_schema=Ctx on the decorator, context=Ctx(...) on the call), a store write followed by a read, and the same store object reachable as store and runtime.store. A task received config too (task saw thread 'inj'). The writer call surfaced in the custom stream on the second line. As in the Graph API, the context you pass is not restored from a checkpoint on resume: pass it again on every call, including the resume (08F.10, Part 9, 08F.12, Part 6).

2.3 Long-term memory: the store#

previous is short-term memory: one value, one thread. Memory that must outlive a thread (a user's preferences, facts learned in earlier conversations) belongs in a store: pass store= to @entrypoint, then read and write runtime.store (the sample above did a put and a get against an InMemoryStore). The store's namespaces, search and semantic indexing are 08F.11's subject, and the concepts of memory types are 08B.2.

You need to remember Use Lives
The rest of this conversation previous (and entrypoint.final) Per thread, in the checkpoint
Work already done in this run (an API result, a model reply) A @task Per run, in the checkpoint, restored on replay
Facts about a user across conversations A store Across threads, in your store backend
Settings for this call (user id, role) context= Per call; you pass it again on resume

Part 3: Durability: resume, replay and determinism#

Deep-dive

3.1 The replay rule#

The most important property of a functional workflow is also the least obvious. When a run resumes (after an interrupt, after an error, after a deploy) it does not continue from the exact line where it stopped. LangGraph starts the entrypoint function again from its first line. Each @task that already finished returns its stored result without running its body; everything outside tasks runs again, and the function races forward until it reaches the point where it stopped the first time. 08F.12, 1.6 taught the same rule for graph nodes; for a function the unit that restarts is the whole entrypoint.

sequenceDiagram
    participant App as Your app
    participant E as Entrypoint function
    participant T as Task charge_card
    participant CP as Checkpointer
    App->>E: invoke("ORD-7", thread T1)
    E->>E: plain code runs (counter 1)
    E->>T: call task
    T-->>CP: result saved
    E->>E: interrupt asks a person
    E-->>App: returns, run is paused
    Note over App,E: minutes later, maybe another process
    App->>E: invoke(Command(resume="yes"), thread T1)
    E->>E: plain code runs AGAIN (counter 2)
    E->>CP: call task, result found
    CP-->>E: restored, task body not run
    E->>E: interrupt returns "yes"
    E-->>App: final result

The sample counts it:

python
# f08_replay.py: resume replays the entrypoint from its first line; only tasks are remembered
import random

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint, task
from langgraph.types import Command, interrupt

calls = {"outside": 0, "task": 0}


@task
def charge_card(order: str) -> str:
    calls["task"] += 1
    return f"charged {order}"


@entrypoint(checkpointer=InMemorySaver())
def checkout(order: str) -> dict:
    calls["outside"] += 1                          # plain code in the entrypoint: runs again on resume
    receipt = charge_card(order).result()          # a task: runs once, its result is stored
    approval = interrupt({"question": f"ship {order}?"})
    return {"receipt": receipt, "approval": approval}


cfg = {"configurable": {"thread_id": "o1"}}
first = checkout.invoke("ORD-7", cfg)
print("after first call :", first.get("__interrupt__") and first["__interrupt__"][0].value, calls)
final = checkout.invoke(Command(resume="yes"), cfg)
print("after resume     :", final, calls)

# the same trap with randomness: the value changes on replay unless it is a task
@task
def roll() -> int:
    return random.randint(1000, 9999)


@entrypoint(checkpointer=InMemorySaver())
def lottery(_: str) -> dict:
    outside = random.randint(1000, 9999)
    inside = roll().result()
    seen = interrupt({"outside": outside, "inside": inside})
    return {"outside": outside, "inside": inside, "seen_at_pause": seen}


cfg = {"configurable": {"thread_id": "l1"}}
paused = lottery.invoke("go", cfg)["__interrupt__"][0].value
result = lottery.invoke(Command(resume="ok"), cfg)
print("at the pause     :", paused)
print("after the resume :", result)
print("outside-task value changed:", paused["outside"] != result["outside"], "| task value kept:", paused["inside"] == result["inside"])
Output5 lines
after first call : {'question': 'ship ORD-7?'} {'outside': 1, 'task': 1}
after resume     : {'receipt': 'charged ORD-7', 'approval': 'yes'} {'outside': 2, 'task': 1}
at the pause     : {'outside': 4894, 'inside': 1858}
after the resume : {'outside': 3970, 'inside': 1858, 'seen_at_pause': 'ok'}
outside-task value changed: True | task value kept: True

The plain line in the entrypoint (calls["outside"] += 1) ran twice; the task body ran once, because on the second pass the stored result 'charged ORD-7' was handed back. The second half shows the consequence for non-determinism: a random number drawn outside a task is different after the resume (the human approved a workflow whose value then changed), while a random number drawn inside a task is the stored one. The sample prints the random values on purpose; the booleans on the last line are what is stable between runs.

3.2 What goes in a task#

The rule that follows is simple: everything with a side effect or a non-deterministic result belongs in a task, and each side effect gets its own task.

Put in a @task Why Safe to leave in the entrypoint body
Model calls Expensive, non-deterministic, and you do not want a second answer after an approval Branching on values that came from tasks or from the input
HTTP and database calls, file writes, emails, payments Side effects must not repeat on replay Pure computation: formatting, parsing, arithmetic
time.time(), datetime.now(), uuid4(), random A different value on replay can change which branch runs (the docs' example: a time check that picks different branches) Loops over data that came from the input or from tasks
Anything slow you want to run in parallel Futures give you parallelism for free (1.4) interrupt(...) itself

The docs illustrate it with two "incorrect and correct" pairs: a file write in the entrypoint runs again on every resume (move it to @task def write_to_file()), and t1 = time.time() in the entrypoint can send a replay down a different branch (wrap it in @task def get_time()).

3.3 Resuming after a crash#

A checkpointer is not only for human pauses. If a task raises and the error propagates, the run stops with the completed task results already saved. Fix the problem and call again on the same thread with None as the input: the entrypoint replays, completed tasks are restored, and only the failed work runs again.

python
# f12_error_resume.py: a crash in the middle of an entrypoint: completed tasks are kept, resume with None
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint, task

runs = []
state = {"fail": True}


@task
def step(name: str) -> str:
    runs.append(name)
    if name == "charge" and state["fail"]:
        raise ConnectionError("payment service down")
    return f"{name} done"


@entrypoint(checkpointer=InMemorySaver())
def order(order_id: str) -> list[str]:
    return [step("reserve").result(), step("charge").result(), step("ship").result()]


cfg = {"configurable": {"thread_id": "o-1"}}
try:
    order.invoke("o-1", cfg)
except ConnectionError as exc:
    print("first run failed :", exc, "| tasks run so far:", runs)

state["fail"] = False                      # the payment service comes back
print("resumed with None:", order.invoke(None, cfg))
print("all task runs    :", runs, "(reserve ran once: its result was restored)")
print("nothing to do now:", order.get_state(cfg).next)
Output4 lines
first run failed : payment service down | tasks run so far: ['reserve', 'charge']
resumed with None: ['reserve done', 'charge done', 'ship done']
all task runs    : ['reserve', 'charge', 'charge', 'ship'] (reserve ran once: its result was restored)
nothing to do now: ()

reserve ran once even though the entrypoint ran twice; charge ran twice (the failed attempt and the retry); ship ran once. In a real system this is the difference between "rerun the whole order, reserving stock twice" and "pick up at the payment". Calling with None is how you resume a thread that stopped on an error. durability (a keyword of invoke and stream) controls when checkpoints are written during a run, which decides how much work an abrupt crash can lose; the modes and their cost are in 08F.11, and 5.5 shows their effect on the number of saved checkpoints.

3.4 Interrupts inside an entrypoint, and changing a workflow while runs are paused#

interrupt() works in an entrypoint exactly as in a node (08F.12): call it, the run pauses and invoke returns with __interrupt__; call again with Command(resume=...) and it returns the answer. The docs' own example is a write_essay task followed by an interrupt for a review. The streaming shape of that pause is in 6.1, and the same workflow written as a graph is in 4.1. Two rules carry over:

  • Several interrupt() calls are matched to answers by position, so keep their number and order fixed (08F.12, 4.2).
  • Do not catch the interrupt with a bare except (08F.12, 4.1).

The deployment problem is the new part. If you ship a new version of an entrypoint while threads are paused on the old one, those threads replay the new code against the old checkpoint. The docs warn that adding, removing or reordering tasks or interrupts before the resume point mismatches the stored values (08F.11, 4.5 owns the rule and shows the graph-node version of both cases). Here is what 1.2.22 actually did when a "harmless" refactor swapped two task calls while a run waited for approval:

python
# f09_order.py: change a functional workflow while a run is paused: tasks and interrupts are matched by position
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint, task
from langgraph.types import Command, interrupt

runs = []


@task
def fetch_customer(order: str) -> str:
    runs.append("fetch_customer")
    return f"customer-of-{order}"


@task
def fetch_total(order: str) -> str:
    runs.append("fetch_total")
    return f"total-of-{order}"


saver = InMemorySaver()
cfg = {"configurable": {"thread_id": "t"}}


@entrypoint(checkpointer=saver)
def review(order: str) -> dict:
    customer = fetch_customer(order).result()     # call 1
    total = fetch_total(order).result()           # call 2
    verdict = interrupt({"customer": customer, "total": total})
    return {"customer": customer, "total": total, "verdict": verdict}


review_old = review    # keep a reference to the deployed version to start the thread
paused = review_old.invoke("ORD-1", cfg)["__interrupt__"][0].value
print("old paused with  :", paused, "| task runs so far:", runs)


# a deploy swaps the two lines while the thread waits; the entrypoint keeps its name
@entrypoint(checkpointer=saver)
def review(order: str) -> dict:
    total = fetch_total(order).result()           # now call 1
    customer = fetch_customer(order).result()     # now call 2
    verdict = interrupt({"customer": customer, "total": total})
    return {"customer": customer, "total": total, "verdict": verdict}


print("new after resume :", review.invoke(Command(resume="approved"), cfg), "| task runs:", runs)
Output2 lines
old paused with  : {'customer': 'customer-of-ORD-1', 'total': 'total-of-ORD-1'} | task runs so far: ['fetch_customer', 'fetch_total']
new after resume : {'customer': 'customer-of-ORD-1', 'total': 'total-of-ORD-1', 'verdict': 'approved'} | task runs: ['fetch_customer', 'fetch_total', 'fetch_total', 'fetch_customer']

The resumed run produced the right answer, but look at the list of task runs: fetch_total and fetch_customer both ran again. LangGraph identifies a stored result by the task's function name plus the position of the call (first call, second call, and so on; 08F.11, 4.5 has the rule and shows the graph-node version of both cases). Swapping two calls to different tasks moved each one to a position where no result with its name was stored, so both repeated. That is the benign case: wasteful, and a repeated side effect if the tasks send emails, but the answer is right.

The dangerous case is the same task called twice, with the two calls swapped. Both positions already hold a stored result under that task's name, so nothing repeats and nothing fails: the new code receives the old results attached to the wrong arguments. A task fetch(key) called as fetch("A") then fetch("B") before the pause, and as fetch("B") then fetch("A") after the deploy, resumes with the first call returning the value for "A" and the second the value for "B", the opposite of what the new code asked for:

python
# f09_same_task.py: the dangerous reorder: the SAME task called twice, with the two calls swapped
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint, task
from langgraph.types import Command, interrupt

runs = []


@task
def fetch(key: str) -> str:
    runs.append(key)
    return f"value-of-{key}"


saver = InMemorySaver()
cfg = {"configurable": {"thread_id": "t"}}


@entrypoint(checkpointer=saver)
def review(_: str) -> dict:
    r1 = fetch("A").result()                      # call 1 asks for A
    r2 = fetch("B").result()                      # call 2 asks for B
    interrupt("approve?")
    return {"r1": r1, "r2": r2}


review_old = review
review_old.invoke("x", cfg)
print("task runs before the deploy:", runs)


# a deploy swaps the arguments; the entrypoint keeps its name
@entrypoint(checkpointer=saver)
def review(_: str) -> dict:
    r1 = fetch("B").result()                      # now call 1 asks for B
    r2 = fetch("A").result()                      # now call 2 asks for A
    interrupt("approve?")
    return {"r1": r1, "r2": r2}


print("new code asked for B first, then A")
print("result after resume:", review.invoke(Command(resume="ok"), cfg), "| task runs:", runs)
Output3 lines
task runs before the deploy: ['A', 'B']
new code asked for B first, then A
result after resume: {'r1': 'value-of-A', 'r2': 'value-of-B'} | task runs: ['A', 'B']

The new code asked for B first, yet r1 is value-of-A, and the task-run list did not grow: nothing re-ran and nothing raised, so the stale values flowed on silently.

Two warnings about reproducing this yourself. The entrypoint's own name is part of the match, so renaming the entrypoint (for example review_v1 and review_v2) makes every stored result unfindable and everything simply re-runs with correct values, which hides the problem; that is also why a rename is a safe isolation tool (option 3 below) but a misleading way to test a reorder. And the dangerous case needs no interrupt: any replay of an entrypoint whose task call order changed (a crash resume, a deploy) behaves the same way. Treat the order of task calls, and the arguments at each position, as part of the persisted data.

The safe options from the docs:

  1. Let in-flight runs finish on the old version before you deploy (drain, then ship).
  2. Add new logic as a new @task at the end rather than inserting calls before the resume point.
  3. Register the new behaviour as a new entrypoint under a new graph name (in langgraph.json on the Agent Server) and send new threads to it. Old threads keep their old name and old results, which is exactly why renaming is safe.

The same non-determinism rules apply to tasks and interrupts used inside Graph API nodes; plain nodes simply re-run from their first line.


Part 4: Choosing the Graph API or the Functional API#

4.1 The same job, written both ways#

The fastest way to feel the difference is to write one job twice. The job is a refund triage: load an order and its customer, decide on a policy, ask a person to confirm, record the outcome. The business rules are plain functions that know nothing about LangGraph, so both versions share them:

python
# g01_two_styles.py: the same refund-triage job as a StateGraph and as an @entrypoint
from typing_extensions import TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint, task
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt

CUSTOMERS = {"c-1": {"name": "Ana", "tier": "gold"}}
ORDERS = {"o-9": {"customer": "c-1", "total": 480.0}}


# ---- shared business logic: plain functions, no LangGraph in them -------------------------------
def load_customer(customer_id: str) -> dict:
    return CUSTOMERS[customer_id]


def load_order(order_id: str) -> dict:
    return ORDERS[order_id]


def decide(customer: dict, order: dict) -> str:
    return "auto-approve" if customer["tier"] == "gold" and order["total"] < 500 else "needs-review"


# ---- Graph API ----------------------------------------------------------------------------------
class State(TypedDict):
    order_id: str
    customer: dict
    order: dict
    decision: str
    outcome: str


def g_load(state: State):
    order = load_order(state["order_id"])
    return {"order": order, "customer": load_customer(order["customer"])}


def g_decide(state: State):
    return {"decision": decide(state["customer"], state["order"])}


def g_confirm(state: State):
    answer = interrupt({"question": f"Refund {state['order']['total']} to {state['customer']['name']}?"})
    return {"outcome": "refunded" if answer == "yes" else "declined"}


graph = (StateGraph(State).add_node("load", g_load).add_node("decide", g_decide).add_node("confirm", g_confirm)
         .add_edge(START, "load").add_edge("load", "decide").add_edge("decide", "confirm").add_edge("confirm", END)
         .compile(checkpointer=InMemorySaver()))


# ---- Functional API -----------------------------------------------------------------------------
@task
def f_load(order_id: str) -> tuple[dict, dict]:
    order = load_order(order_id)
    return order, load_customer(order["customer"])


@entrypoint(checkpointer=InMemorySaver())
def workflow(order_id: str) -> dict:
    order, customer = f_load(order_id).result()
    decision = decide(customer, order)                # ordinary code, no node needed
    answer = interrupt({"question": f"Refund {order['total']} to {customer['name']}?"})
    return {"decision": decision, "outcome": "refunded" if answer == "yes" else "declined"}


# ---- run both the same way ----------------------------------------------------------------------
def drive(app, first_input, thread):
    cfg = {"configurable": {"thread_id": thread}}
    chunks = list(app.stream(first_input, cfg, stream_mode="updates"))
    asked = chunks[-1]["__interrupt__"][0].value["question"]
    chunks += list(app.stream(Command(resume="yes"), cfg, stream_mode="updates"))
    return asked, chunks


for label, app, first in [("graph", graph, {"order_id": "o-9"}), ("functional", workflow, "o-9")]:
    asked, chunks = drive(app, first, label)
    print(f"{label:10s} asked   : {asked}")
    print(f"{label:10s} updates : {[next(iter(c)) for c in chunks]}")
    print(f"{label:10s} nodes in get_graph(): {[n for n in app.get_graph().nodes if not n.startswith('__')]}")
Output6 lines
graph      asked   : Refund 480.0 to Ana?
graph      updates : ['load', 'decide', '__interrupt__', 'confirm']
graph      nodes in get_graph(): ['load', 'decide', 'confirm']
functional asked   : Refund 480.0 to Ana?
functional updates : ['f_load', '__interrupt__', 'workflow']
functional nodes in get_graph(): ['workflow']

Both versions asked the same question, resumed the same way and ended in the same outcome. What differs is visible in the last two lines of each block:

  • The graph streamed one update per node (load, decide, then confirm after the resume) and get_graph() listed three named nodes. The decision to separate "load" from "decide" was made in the graph's shape, and the intermediate values (customer, order, decision) live in a shared state that every node can read, that streams, and that you can inspect at any checkpoint.
  • The entrypoint streamed one update for the task (f_load) and then the whole function (workflow). decide was an ordinary function call in the middle of the body, with no node and nothing in the stream. get_graph() showed a single node.

The functional version is shorter and reads top to bottom like the code you would write without LangGraph. The graph version is longer and tells you, without running anything, what the workflow can do. Neither is better in general; 4.2 turns that into a decision.

4.2 The comparison table#

Graph API (StateGraph) Functional API
Control flow Nodes, edges, conditional edges, Command, Send Ordinary Python: if, loops, function calls
State A shared typed schema with reducers; every node reads and writes channels Values scoped to the entrypoint and tasks; previous and entrypoint.final for per-thread memory; no reducers
Checkpoints After every super-step Task results stored on the entrypoint's checkpoint; resume replays from the first line of the entrypoint
Visualization get_graph().draw_mermaid() and Studio's graph view None worth drawing (one node)
Parallelism Parallel branches in a super-step, Send for a dynamic number Task futures started in a loop
Streaming granularity One update per node, plus tokens and custom events One update per task and one for the function, plus tokens and custom events
Design-time checks compile() validates the structure (08F.10, 2.3) None: errors show up when the line runs
Changing a live workflow Named nodes make a diff reviewable; saved threads keep their position Control flow is the persisted structure; reordering tasks or interrupts re-runs work, and swapping calls to the same task returns stale results (3.4)
Docs' recommendation "Prefer for new agents" "Wrap existing code or another framework"
Interop Can call @task functions inside nodes Is a Pregel, so it can be used where the helper packages accept a compiled graph (8.21 owns that)
flowchart TD
    S["New LangGraph workflow"] --> Q1{"Do you already have working Python or another framework to keep?"}
    Q1 -- yes --> F["Functional API: wrap the expensive calls in tasks"]
    Q1 -- no --> Q2{"Do you need to see, review or draw the shape of the workflow?"}
    Q2 -- yes --> G["Graph API"]
    Q2 -- no --> Q3{"Parallel branches, Send, shared state with reducers, or Command routing?"}
    Q3 -- yes --> G
    Q3 -- no --> Q4{"Mostly ordinary loops and if statements?"}
    Q4 -- yes --> F
    Q4 -- no --> G

When both fit, three habits settle it:

  1. The team will read this in six months. A graph is a diagram you can walk a new colleague through. A function is code you have to read. Pick based on who maintains it.
  2. The workflow has a real shape (several agents, branches that merge, a router). That is a graph. If the shape is "do A, then B, then maybe C in a loop", that is a function.
  3. You are porting. If the code exists and works, the Functional API is the cheapest way to add durability and streaming, and you can always rewrite the stable parts as a graph later.

4.3 What tasks buy you, and what they cost#

Reasons to use a task (docs): checkpoint the result of long-running work, wrap non-repeatable work so a human pause does not repeat it, run I/O in parallel, get a named step in LangSmith traces, and attach retries. The cost is the serialization rule (1.6), one more name in your streams, and the need to remember .result() (1.5). A good rule: one task per side effect or per model call, and plain functions for everything else. Wrapping every helper in a task adds checkpoints and noise without adding safety.

4.4 Wrapping code you already have#

The strongest case for the Functional API is code that predates LangGraph, or code written for another framework, that now needs pauses, resume and streaming. The pattern: leave the old logic alone, make its expensive calls tasks, and put the control flow in an entrypoint.

python
# g02_wrap_existing.py: wrapping code you already have (no framework rewrite) to get checkpoints, resume and streaming
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint, task
from langgraph.types import Command, interrupt

calls = {"model": 0}


# ---- existing code: a plain function that calls "the model" and "a tool" -------------------------
def call_model(prompt: str) -> str:
    calls["model"] += 1
    return f"model answer to: {prompt}"


def run_legacy_agent(question: str, approve) -> str:
    plan = call_model(f"plan for {question}")
    if not approve(plan):
        return "cancelled"
    return call_model(f"execute {plan}")


# ---- the wrapper: the old function is untouched, only its two expensive calls become tasks --------
@task
def model_task(prompt: str) -> str:
    return call_model(prompt)


@entrypoint(checkpointer=InMemorySaver())
def wrapped(question: str) -> str:
    plan = model_task(f"plan for {question}").result()
    ok = interrupt({"approve this plan?": plan})
    return model_task(f"execute {plan}").result() if ok else "cancelled"


print("legacy, one call :", run_legacy_agent("refund o-9", lambda plan: True), "| model calls:", calls["model"])

calls["model"] = 0
cfg = {"configurable": {"thread_id": "w"}}
wrapped.invoke("refund o-9", cfg)
print("wrapped, paused  : model calls =", calls["model"])
print("wrapped, resumed :", wrapped.invoke(Command(resume=True), cfg), "| model calls =", calls["model"], "(the plan call was not repeated)")
Output3 lines
legacy, one call : model answer to: execute model answer to: plan for refund o-9 | model calls: 2
wrapped, paused  : model calls = 1
wrapped, resumed : model answer to: execute model answer to: plan for refund o-9 | model calls = 2 (the plan call was not repeated)

The old function ran straight through with two model calls. The wrapped version paused after the plan (one model call), and the resume ran only the execution call: the plan call was not repeated, so the person approved exactly the plan that was executed. That is the whole proposition of the Functional API in one run.

The docs have a dedicated guide for deploying agents written for other frameworks on the Agent Server by wrapping them this way (link in Further resources, and a survey of the server in 11A.5). Two honest limits: a wrapped function that makes its model calls through another framework's client will not stream tokens in messages mode unless the calls go through LangChain chat models (use the stream writer instead, 7.7), and the replay rule means the code you wrap must tolerate being re-entered from the top.

Because an entrypoint is a Pregel like any compiled graph, the multi-agent helper packages, which accept compiled graphs as agents, can also take a functional workflow (their source docstrings say so); 08F.13 covers the helpers and their status.


Part 5: Streaming fundamentals#

5.1 What there is to stream, and why#

A compiled graph or entrypoint can report what it is doing at four levels of detail: the state (the whole picture after each step), the updates (what each step changed), the model tokens (the words as they are written) and your own events (a progress message you decide to send). A run also has a debug level: checkpoints, task starts and task results. LangGraph gives each its own stream mode and lets you ask for several at once.

Why bother, given that invoke is simpler? Because an agent run takes seconds to minutes, and a user staring at a spinner for forty seconds assumes it is broken. Streaming turns the same wait into visible progress, which is the biggest perceived-latency win available. It also feeds debugging (which node ran, with what input), cancellation (stop paying when the user leaves) and approvals (show the question the moment the run pauses). The provider-level mechanics are 03.3; the chat-model level is 08F.5, 5.2; the agent level is 08F.8, Part 10. This part is the graph and entrypoint level, and what you learn here is what create_agent streams with, because an agent is a compiled graph.

5.2 stream and astream: the signatures and the defaults#

From the 1.2.22 source (astream takes the same arguments and returns an async iterator):

text
graph.stream(
    input, config=None, *,
    context=None,
    stream_mode=None,              # one mode or a list; None means the graph's default
    print_mode=(),                 # print these modes to the console, without changing what is yielded
    output_keys=None,              # restrict streamed channels to these keys
    interrupt_before=None, interrupt_after=None,
    durability=None,               # "sync" | "async" | "exit"
    control=None,                  # a RunControl, for graceful shutdown (08F.12, Part 10)
    subgraphs=False,               # also stream from subgraphs (Part 9)
    debug=None,                    # True prints "updates" and "values" to the console
    version="v1",                  # "v1" or "v2": the shape of each chunk (5.3)
)
StreamMode = "values" | "updates" | "checkpoints" | "tasks" | "debug" | "messages" | "custom"

The defaults are a classic trap, so memorize this table:

Call Default stream_mode Returns
graph.invoke(...) "values" The final state (or, with another mode, a list of that mode's chunks)
graph.stream(...) on a StateGraph.compile() result "updates" One dict per node: {node_name: update}
entrypoint.stream(...) "updates" One dict per finished task and one for the entrypoint (1.2)
A graph running as a node of another graph "values" Source comment: "if being called as a node in another graph, default to values mode"

invoke(..., stream_mode="updates") returns the list of chunks that stream would have yielded, which is a handy way to collect a whole stream in a test (08F.10, 10.2 ran it). Always pass stream_mode explicitly; then none of this matters.

5.3 Chunk formats: v1 and v2#

What one yielded chunk looks like depends on the options you chose, unless you pick version="v2". The sample runs the same two-node graph, with a subgraph so that subgraphs=True has something to report, in every combination:

python
# v01_shapes.py: the chunk shape of stream() in v1 (default) and v2, for every combination of options
from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    n: int


def inc(state: State):
    return {"n": state["n"] + 1}


# a subgraph, so that subgraphs=True has something to report
sub = StateGraph(State).add_node("sub_inc", inc).add_edge(START, "sub_inc").add_edge("sub_inc", END).compile()
graph = (StateGraph(State).add_node("first", inc).add_node("child", sub)
         .add_edge(START, "first").add_edge("first", "child").add_edge("child", END).compile())


def short(chunk):
    """Replace the random task id in a namespace so that the output is stable."""
    import re
    return re.sub(r"[0-9a-f]{8}-[0-9a-f-]{27}", "<id>", repr(chunk))


x = {"n": 0}
print("v1, one mode             :", short(next(iter(graph.stream(x, stream_mode="updates")))))
print("v1, list of modes        :", short(next(iter(graph.stream(x, stream_mode=["updates"])))))
print("v1, subgraphs=True       :", [short(c) for c in graph.stream(x, stream_mode="updates", subgraphs=True)])
print("v1, both                 :", short(next(iter(graph.stream(x, stream_mode=["updates"], subgraphs=True)))))
print()
for c in graph.stream(x, stream_mode="updates", subgraphs=True, version="v2"):
    print("v2, subgraphs=True       :", short(c))
print()
print("invoke v1                :", graph.invoke(x))
r = graph.invoke(x, version="v2")
print("invoke v2                :", type(r).__name__, r.value, r.interrupts)
print("invoke, one mode         :", graph.invoke(x, stream_mode="updates"))
print("invoke, v2 + updates     :", [short(p) for p in graph.invoke(x, stream_mode="updates", version="v2")][:1], "...")
Output13 lines
v1, one mode             : {'first': {'n': 1}}
v1, list of modes        : ('updates', {'first': {'n': 1}})
v1, subgraphs=True       : ["((), {'first': {'n': 1}})", "(('child:<id>',), {'sub_inc': {'n': 2}})", "((), {'child': {'n': 2}})"]
v1, both                 : ((), 'updates', {'first': {'n': 1}})

v2, subgraphs=True       : {'type': 'updates', 'ns': (), 'data': {'first': {'n': 1}}}
v2, subgraphs=True       : {'type': 'updates', 'ns': ('child:<id>',), 'data': {'sub_inc': {'n': 2}}}
v2, subgraphs=True       : {'type': 'updates', 'ns': (), 'data': {'child': {'n': 2}}}

invoke v1                : {'n': 2}
invoke v2                : GraphOutput {'n': 2} ()
invoke, one mode         : [{'first': {'n': 1}}, {'child': {'n': 2}}]
invoke, v2 + updates     : ["{'type': 'updates', 'ns': (), 'data': {'first': {'n': 1}}}"] ...
Options v1 chunk (the default) v2 chunk (version="v2")
One mode The raw data ({'first': {'n': 1}}) {"type": "updates", "ns": (), "data": {...}}
A list of modes A tuple (mode, data) The same dict, with type naming the mode
subgraphs=True A tuple (namespace, data) The same dict, with ns filled in (('child:<task id>',))
List of modes and subgraphs=True (namespace, mode, data) The same dict
invoke result A plain state dict (with an __interrupt__ key when paused) A GraphOutput with .value and .interrupts

v1 changes shape depending on the options, so code that handles one combination breaks when you add another. Add subgraphs=True to a loop written for a list of modes and every for mode, data in ... unpack fails. v2 always yields the same dict, so you branch on chunk["type"] and read chunk["ns"] when you care where it came from; v2 requires LangGraph 1.1 or newer, and the typed shapes (ValuesStreamPart, UpdatesStreamPart, MessagesStreamPart, CustomStreamPart and so on) are in langgraph.types with a union StreamPart that discriminates on chunk["type"]. Pydantic and dataclass state is coerced back to your model in v2 values output.

All the current docs examples use v2, and so does this lesson from here on. v1 is still the default in 1.2.22 (the docs call it "current default"; check the docs for when that changes), so you must pass version="v2" on every call. Two more notes: dict-style access on a v2 GraphOutput (result["key"]) is deprecated in favour of result.value and result.interrupts, and you must not mix the two shapes in one program (a helper that parses v1 chunks will fail on v2).

5.4 The modes at a glance#

flowchart TD
    Q["What does the client need?"]
    Q --> A["The latest full state"]
    Q --> B["What each step changed"]
    Q --> C["Model tokens as they are written"]
    Q --> D["My own progress messages"]
    Q --> E["To debug the run"]
    A --> A1["values"]
    B --> B1["updates"]
    C --> C1["messages"]
    D --> D1["custom"]
    E --> E1["tasks, checkpoints or debug"]
    A1 --> Z["Combine several: stream_mode as a list"]
    B1 --> Z
    C1 --> Z
    D1 --> Z
    E1 --> Z
Mode Emits Typical use
values The full state after each step A UI that re-renders the whole state; tests
updates {node_name: update} after each step Progress ("the triage node finished"), the cheapest mode to send to a browser
messages (llm_token_chunk, metadata) pairs from any model call inside nodes, tools, tasks and subgraphs Typing effect
custom Whatever your code passes to the stream writer Progress bars, partial results
checkpoints One event per checkpoint, the shape of get_state() Debugging persistence (needs a checkpointer)
tasks A start event and a result event for every task or node Debugging, timing
debug checkpoints and tasks together, with a timestamp and step Deep debugging

An internal "tools" mode appears in the source (the event-streaming code uses it) but is not in the public StreamMode literal or the docs; do not depend on it.

5.5 Four options that change what you see#

python
# st04_options.py: output_keys, print_mode, debug=True, durability
import io
import re
from contextlib import redirect_stdout

from typing_extensions import TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    question: str
    scratch: str
    answer: str


def think(state: State):
    return {"scratch": "private notes"}


def reply(state: State):
    return {"answer": "42"}


def build():
    return (StateGraph(State).add_node(think).add_node(reply)
            .add_edge(START, "think").add_edge("think", "reply").add_edge("reply", END)
            .compile(checkpointer=InMemorySaver()))


x = {"question": "?", "scratch": "", "answer": ""}
cfg = lambda t: {"configurable": {"thread_id": t}}  # noqa: E731

print("values            :", list(build().stream(x, cfg("1"), stream_mode="values"))[-1])
print("values + output_keys:", list(build().stream(x, cfg("2"), stream_mode="values", output_keys=["answer"]))[-1])

buffer = io.StringIO()
with redirect_stdout(buffer):
    chunks = list(build().stream(x, cfg("3"), stream_mode="updates", print_mode="values"))
print("print_mode: yielded", len(chunks), "chunks of type", type(chunks[0]).__name__, "| printed to stdout:", len(buffer.getvalue().splitlines()), "lines")
print("  first printed line:", re.sub(r"\x1b\[[0-9;]*m", "", buffer.getvalue().splitlines()[0]))   # colour codes removed

for mode in ("sync", "async", "exit"):
    g = build()
    list(g.stream(x, cfg("d"), stream_mode="updates", durability=mode))
    print(f"durability={mode:5s}: checkpoints saved for the thread =", len(list(g.get_state_history(cfg("d")))))
Output7 lines
values            : {'question': '?', 'scratch': 'private notes', 'answer': '42'}
values + output_keys: {'answer': '42'}
print_mode: yielded 2 chunks of type dict | printed to stdout: 3 lines
  first printed line: [values] {'question': '?', 'scratch': '', 'answer': ''}
durability=sync : checkpoints saved for the thread = 4
durability=async: checkpoints saved for the thread = 4
durability=exit : checkpoints saved for the thread = 1
  • output_keys limits which state keys a stream carries. The values stream normally carries everything, including private scratch keys; output_keys=["answer"] returned only answer. This is the cheap way to avoid leaking internals to a browser, though not a security boundary on its own (08F.10, Part 8 shows that schemas do not hide keys from stream).
  • print_mode prints a mode to the console in colour while you consume a different one: the call yielded two updates chunks and printed three lines of values. Use it in a notebook or a debugging session; it changes nothing about the data. (The sample strips the colour codes before printing the line.) debug=True is the shortcut that prints updates and values.
  • durability decides when checkpoints are written: "sync" (before the next step starts; safest), "async" (in the background while the next step runs) or "exit" (only when the run ends). The sample saved four checkpoints with sync and async and one with exit: an abrupt crash under exit loses everything since the start, in return for fewer writes. 08F.11 owns the trade-off.
  • control attaches a RunControl for graceful shutdown (08F.12, Part 10).

Part 6: The stream modes, one by one#

All samples in this part use version="v2".

6.1 The graph-state modes: values and updates#

A two-node graph (refine_topic, then generate_joke) with an in-memory checkpointer, run in each mode. The first two blocks of output are the ones you will use most:

python
# st01_modes.py: the five graph-state stream modes on one small graph (no model needed), version="v2" parts
from typing_extensions import TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    topic: str
    joke: str


def refine_topic(state: State):
    return {"topic": state["topic"] + " and cats"}


def generate_joke(state: State):
    return {"joke": f"This is a joke about {state['topic']}"}


graph = (StateGraph(State).add_node(refine_topic).add_node(generate_joke)
         .add_edge(START, "refine_topic").add_edge("refine_topic", "generate_joke").add_edge("generate_joke", END)
         .compile(checkpointer=InMemorySaver()))


def run(mode, thread):
    return graph.stream({"topic": "ice cream"}, {"configurable": {"thread_id": thread}}, stream_mode=mode, version="v2")


print("--- values: the whole state after each step")
for part in run("values", "v"):
    print(part["type"], part["ns"], part["data"])

print("\n--- updates: one node's return value per part")
for part in run("updates", "u"):
    print(part["type"], part["ns"], part["data"])

print("\n--- checkpoints: one snapshot per checkpoint, the shape of get_state()")
for part in run("checkpoints", "c"):
    d = part["data"]
    print(f"step={d['metadata']['step']:>2} source={d['metadata']['source']:5s} next={d['next']} values={d['values']}")
print("keys of one snapshot:", list(d))

print("\n--- tasks: a start event and a result event for every node")
for part in run("tasks", "t"):
    d = part["data"]
    if "input" in d:
        print(f"start  {d['name']:13s} input={d['input']} triggers={d['triggers']}")
    else:
        print(f"result {d['name']:13s} result={d['result']} error={d['error']} interrupts={d['interrupts']}")

print("\n--- debug: checkpoints and tasks together, each wrapped with step, timestamp and a type")
for part in run("debug", "d"):
    d = part["data"]
    print(f"step={d['step']:>2} type={d['type']:11s} payload keys={list(d['payload'])}")
print("outer keys:", list(d))
Output32 lines
--- values: the whole state after each step
values () {'topic': 'ice cream'}
values () {'topic': 'ice cream and cats'}
values () {'topic': 'ice cream and cats', 'joke': 'This is a joke about ice cream and cats'}

--- updates: one node's return value per part
updates () {'refine_topic': {'topic': 'ice cream and cats'}}
updates () {'generate_joke': {'joke': 'This is a joke about ice cream and cats'}}

--- checkpoints: one snapshot per checkpoint, the shape of get_state()
step=-1 source=input next=['__start__'] values={}
step= 0 source=loop  next=['refine_topic'] values={'topic': 'ice cream'}
step= 1 source=loop  next=['generate_joke'] values={'topic': 'ice cream and cats'}
step= 2 source=loop  next=[] values={'topic': 'ice cream and cats', 'joke': 'This is a joke about ice cream and cats'}
keys of one snapshot: ['config', 'parent_config', 'values', 'metadata', 'next', 'tasks']

--- tasks: a start event and a result event for every node
start  refine_topic  input={'topic': 'ice cream'} triggers=('branch:to:refine_topic',)
result refine_topic  result={'topic': 'ice cream and cats'} error=None interrupts=[]
start  generate_joke input={'topic': 'ice cream and cats'} triggers=('branch:to:generate_joke',)
result generate_joke result={'joke': 'This is a joke about ice cream and cats'} error=None interrupts=[]

--- debug: checkpoints and tasks together, each wrapped with step, timestamp and a type
step=-1 type=checkpoint  payload keys=['config', 'parent_config', 'values', 'metadata', 'next', 'tasks']
step= 0 type=checkpoint  payload keys=['config', 'parent_config', 'values', 'metadata', 'next', 'tasks']
step= 1 type=task        payload keys=['id', 'name', 'input', 'triggers']
step= 1 type=task_result payload keys=['id', 'name', 'error', 'result', 'interrupts']
step= 1 type=checkpoint  payload keys=['config', 'parent_config', 'values', 'metadata', 'next', 'tasks']
step= 2 type=task        payload keys=['id', 'name', 'input', 'triggers']
step= 2 type=task_result payload keys=['id', 'name', 'error', 'result', 'interrupts']
step= 2 type=checkpoint  payload keys=['config', 'parent_config', 'values', 'metadata', 'next', 'tasks']
outer keys: ['step', 'timestamp', 'type', 'payload']

values gave three snapshots: the input, then the state after each node. Each is the entire state at that moment. It is simple (render it and you are done) and wasteful for large states (every long message list goes over the wire again at every step). It also includes internal channels: declaring input and output schemas does not hide them from the stream, so a secret in state is a secret in the stream.

updates gave two chunks, each keyed by the node that produced it and holding only what that node returned. Several updates inside one step are emitted separately, and parallel nodes arrive in whatever order they finish, so never rely on arrival order between branches (08F.10, 7.2 sorted worker results for this reason). The updates stream carries three special keys alongside node names:

  • __interrupt__: a tuple of Interrupt objects when the run pauses (an invoke result has a list; a stream chunk a tuple). 08F.12, 2.1 lists every surface that exposes a pending interrupt.
  • __metadata__: extra facts about a chunk, such as {'cached': True} for a node or task answered from the cache (the cached sample in 1.5 shows one).
  • Node names of retries and error handlers (__error_handler__<node>, 08F.12, 7.5). A node or task retry_policy is honoured while a graph is streamed: a task that failed twice and succeeded on its third attempt, streamed in updates mode, produced its normal chunks with no extra retry chunks and ran three times. The Runnable-level with_retry wrapper behaves differently: streaming bypasses it (08F.7, 6.2).

An entrypoint produces the same kinds of chunks. A functional run with an interrupt, streamed in two legs, shows all of it:

python
# f13_stream_interrupt.py: what an entrypoint stream looks like around an interrupt
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint, task
from langgraph.types import Command, interrupt


@task
def draft(topic: str) -> str:
    return f"An essay about {topic}"


@entrypoint(checkpointer=InMemorySaver())
def review(topic: str) -> dict:
    essay = draft(topic).result()
    verdict = interrupt({"question": "Approve?", "essay": essay})
    return {"essay": essay, "verdict": verdict}


cfg = {"configurable": {"thread_id": "r"}}
for chunk in review.stream("cats", cfg):
    if "__interrupt__" in chunk:
        print("leg 1: __interrupt__ ->", chunk["__interrupt__"][0].value)    # a tuple of Interrupt objects
    else:
        print("leg 1:", chunk)
for chunk in review.stream(Command(resume="approved"), cfg):
    print("leg 2:", chunk)
print("invoke on a finished thread:", review.invoke(Command(resume="again"), cfg))
Output4 lines
leg 1: {'draft': 'An essay about cats'}
leg 1: __interrupt__ -> {'question': 'Approve?', 'essay': 'An essay about cats'}
leg 2: {'review': {'essay': 'An essay about cats', 'verdict': 'approved'}}
invoke on a finished thread: {'essay': 'An essay about cats', 'verdict': 'approved'}

Leg one yielded the draft task's result and then the __interrupt__ chunk with the question. Leg two, started with Command(resume=...), yielded only the entrypoint's own result: the draft task was restored, not re-run, so it does not appear in the stream again. A UI that builds a timeline from updates must expect a leg to show only the new work. Calling invoke(Command(resume=...)) on a finished thread returned the stored result without running anything (08F.12, 2.3).

6.2 The debugging modes: checkpoints, tasks and debug#

Continue reading the output above from the checkpoints section down:

  • checkpoints yields one event per checkpoint with exactly the shape of get_state(): config, parent_config, values, metadata (source, step, parents), next and tasks. Four checkpoints for a two-node run: the input (step=-1, source=input, next=['__start__']), one before each node and the final one with next=[]. Use it to watch persistence from the outside, for example to log each checkpoint id.
  • tasks yields a start event (id, name, input, triggers) and a result event (id, name, error, result, interrupts) for every node. It is the mode for timing a run and for seeing which inputs each node received.
  • debug is checkpoints and tasks merged: each item is wrapped as {step, timestamp, type, payload} with type one of checkpoint, task or task_result. The sample printed only the payload keys; the payloads are the ones above.

The docs say checkpoints and tasks need a checkpointer. The next sample checks that on a graph compiled without one, and shows what the same modes emit for an entrypoint:

python
# st03_nocheckpointer.py: do checkpoints and tasks modes really need a checkpointer?
from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    n: int


def inc(state: State):
    return {"n": state["n"] + 1}


graph = StateGraph(State).add_node(inc).add_edge(START, "inc").add_edge("inc", END).compile()
for mode in ["tasks", "checkpoints", "debug"]:
    try:
        parts = list(graph.stream({"n": 1}, stream_mode=mode, version="v2"))
        print(f"{mode:12s} without a checkpointer -> {len(parts)} part(s)", [p["data"].get("name", p["data"].get("type", "snapshot")) if isinstance(p["data"], dict) else p["data"] for p in parts][:4])
    except Exception as exc:  # noqa: BLE001
        print(f"{mode:12s} without a checkpointer -> {type(exc).__name__}: {exc}")
Output3 lines
tasks        without a checkpointer -> 2 part(s) ['inc', 'inc']
checkpoints  without a checkpointer -> 0 part(s) []
debug        without a checkpointer -> 2 part(s) ['task', 'task_result']

Observed in 1.2.22: checkpoints emits nothing without a checkpointer, but tasks and debug still work (the debug events are the task start and result; there are no checkpoint events). The docs' blanket statement is stricter than the behaviour; treat the checkpointer requirement as a rule for checkpoints and a "may change" for the others.

python
# st02_functional_modes.py: stream modes on an @entrypoint (what a task call and the entrypoint emit)
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint, task


@task
def double(n: int) -> int:
    return n * 2


@task
def add_one(n: int) -> int:
    return n + 1


@entrypoint(checkpointer=InMemorySaver())
def flow(n: int) -> dict:
    d = double(n).result()
    return {"answer": add_one(d).result()}


def run(mode, thread):
    return list(flow.stream(3, {"configurable": {"thread_id": thread}}, stream_mode=mode, version="v2"))


print("values     :", [(p["type"], p["data"]) for p in run("values", "1")])
print("updates    :", [(p["type"], p["data"]) for p in run("updates", "2")])
for p in run("tasks", "3"):
    d = p["data"]
    print("tasks      :", "start " if "input" in d else "result", d["name"], d.get("input", d.get("result")))
for p in run("checkpoints", "4"):
    d = p["data"]
    print(f"checkpoints: step={d['metadata']['step']} next={d['next']} values={d['values']}")
print("two modes  :", [(p["type"], p["data"]) for p in flow.stream(3, {"configurable": {"thread_id": "5"}}, stream_mode=["updates", "values"], version="v2")])
print("v1 default :", list(flow.stream(3, {"configurable": {"thread_id": "6"}})))
print("v1 two modes:", list(flow.stream(3, {"configurable": {"thread_id": "7"}}, stream_mode=["updates", "values"])))
Output13 lines
values     : [('values', {'answer': 7})]
updates    : [('updates', {'double': 6}), ('updates', {'add_one': 7}), ('updates', {'flow': {'answer': 7}})]
tasks      : start  flow 3
tasks      : start  double ((3,), {})
tasks      : result double {'__return__': 6}
tasks      : start  add_one ((6,), {})
tasks      : result add_one {'__return__': 7}
tasks      : result flow {'__end__': {'answer': 7}}
checkpoints: step=-1 next=['flow'] values=None
checkpoints: step=0 next=[] values={'answer': 7}
two modes  : [('updates', {'double': 6}), ('updates', {'add_one': 7}), ('updates', {'flow': {'answer': 7}}), ('values', {'answer': 7})]
v1 default : [{'double': 6}, {'add_one': 7}, {'flow': {'answer': 7}}]
v1 two modes: [('updates', {'double': 6}), ('updates', {'add_one': 7}), ('updates', {'flow': {'answer': 7}}), ('values', {'answer': 7})]

For an entrypoint:

  • values emits once, at the end (there is no shared state to snapshot).
  • updates names each task (double, add_one) and then the entrypoint (flow).
  • tasks shows the argument tuple a task received (start double ((3,), {}): positional arguments and keyword arguments), wraps a task's result as {'__return__': 6} and the entrypoint's as {'__end__': {...}}. The entrypoint itself appears as a task named after the function.
  • checkpoints shows two: before the function (values=None) and after it. The checkpoint count is smaller than a graph's because a functional run has one super-step.

6.3 Several modes at once#

Pass a list. With version="v2" each chunk is a dict whose type says which mode it came from; the two modes line above shows updates chunks and the final values chunk arriving in one stream. In v1 the same call yields (mode, data) tuples (the v1 two modes line). Order inside the combined stream is the order of production within a step: for a graph with a custom event inside a node, the custom chunk arrives before that node's updates chunk, as 8.1 shows. Do not assume more than that, and in particular do not assume the order of chunks from parallel nodes.


Part 7: Streaming model tokens: messages mode#

Deep-dive

7.1 What messages emits#

stream_mode="messages" yields (message_chunk, metadata) pairs for the tokens of any LangChain chat-model call made inside the run: in a node, a tool, a task or a subgraph. Two facts surprise people. First, the code does not have to call model.stream(...): a plain model.invoke(...) inside a node still streams its tokens, because LangGraph listens to the model's callbacks. Second, the same stream also carries whole messages that nodes add to state (such as tool results), which 7.6 explains. The sample uses a scripted fake chat model, GenericFakeChatModel, which streams its reply word by word:

python
# m01_messages.py: messages mode with a fake chat model inside a node, and what the metadata holds
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    topic: str
    joke: str


model = GenericFakeChatModel(messages=iter([AIMessage(content="Why did the cat sit on the keyboard? To keep an eye on the mouse.")]))


def write_joke(state: State):
    # NOTE: model.invoke, not model.stream: tokens still reach stream_mode="messages"
    reply = model.invoke(f"Tell a joke about {state['topic']}")
    return {"joke": reply.content}


graph = StateGraph(State).add_node(write_joke).add_edge(START, "write_joke").add_edge("write_joke", END).compile()

tokens = []
first_metadata = None
for part in graph.stream({"topic": "cats", "joke": ""}, stream_mode="messages", version="v2"):
    chunk, metadata = part["data"]
    first_metadata = first_metadata or metadata
    tokens.append(chunk.content)
print("parts type  :", part["type"], "| chunk class:", type(chunk).__name__)
print("tokens      :", tokens)
print("joined      :", "".join(tokens))
for key, value in first_metadata.items():
    if "checkpoint_ns" not in key:             # these hold a random run id, so they are left out of the printout
        print(f"metadata[{key!r}] = {value!r}")
Output11 lines
parts type  : messages | chunk class: AIMessageChunk
tokens      : ['Why', ' ', 'did', ' ', 'the', ' ', 'cat', ' ', 'sit', ' ', 'on', ' ', 'the', ' ', 'keyboard?', ' ', 'To', ' ', 'keep', ' ', 'an', ' ', 'eye', ' ', 'on', ' ', 'the', ' ', 'mouse.']
joined      : Why did the cat sit on the keyboard? To keep an eye on the mouse.
metadata['ls_integration'] = 'langchain_chat_model'
metadata['langgraph_step'] = 1
metadata['langgraph_node'] = 'write_joke'
metadata['langgraph_triggers'] = ('branch:to:write_joke',)
metadata['langgraph_path'] = ('__pregel_pull', 'write_joke')
metadata['ls_provider'] = 'genericfakechatmodel'
metadata['ls_model_type'] = 'chat'
metadata['lc_versions'] = {'langchain-core': '1.8.0', 'langchain': '1.5.0'}

Reading it:

  • Each chunk is an AIMessageChunk. Its content is the new text (a word or a space here; a few characters with a real provider). Join the chunks for the full reply, which is what a typing effect does.
  • The node called model.invoke, and the tokens still arrived: invoke inside a node streams.
  • The metadata tells you where the chunk came from. langgraph_node is the node name (or, in an entrypoint, the task name, 7.4), langgraph_step the super-step, langgraph_triggers and langgraph_path how the node was reached, and tags the tags set on the model (empty here, so the key is absent in this run). ls_provider and ls_model_type describe the model; the lines for checkpoint_ns and langgraph_checkpoint_ns, which hold a random run id, are left out of the printout.
  • Check for empty content before you print: a chunk that carries only a tool call, or the closing chunk of a message, has content == "". The docs' loop guards with if message_chunk.content:.

7.2 With a real model#

This is the same shape with a provider, from the docs' first token-streaming example. It is a sketch to run once you have a key; the fake-model sample above is the one that ran.

python
# tokens_real_model.py: token streaming from a real provider through a graph node (illustrative: needs a provider key)
from dataclasses import dataclass

from dotenv import load_dotenv
from langchain.chat_models import init_chat_model

from langgraph.graph import START, StateGraph

load_dotenv()  # reads OPENAI_API_KEY from .env


@dataclass
class State:
    topic: str
    joke: str = ""


# One line to change provider: "anthropic:claude-haiku-5-5" or "google_genai:gemini-3.8-flash" (optional) (08F.5 lists the prefixes).
model = init_chat_model("openai:gpt-6-luna", tags=["joke"])


def call_model(state: State):
    reply = model.invoke([{"role": "user", "content": f"Tell a short joke about {state.topic}"}])
    return {"joke": reply.content}


graph = StateGraph(State).add_node(call_model).add_edge(START, "call_model").compile()

for part in graph.stream({"topic": "ice cream"}, stream_mode="messages", version="v2"):
    chunk, metadata = part["data"]
    if chunk.content:
        print(chunk.content, end="|", flush=True)
print()
Example output · illustrative1 line
Why| did| the| ice| cream| go| to| school|?| To| get| a| sundae| education|!|

Streaming can be switched off on the model, which matters when a model must be called in one piece (a structured-output call you do not want streamed as raw JSON). init_chat_model(..., streaming=False) and ChatOpenAI(..., streaming=False) turn it off for integrations that have the flag; disable_streaming=True exists on every chat-model base class for those that do not. With streaming disabled the node still works and messages mode delivers the whole reply as a single chunk (7.3 shows it).

7.3 Filtering: by node, by tag, and silencing a model#

A graph with several model calls streams all of them into one messages stream. You choose what to show by reading the metadata. The sample runs three model calls: a joke in one node, and in the next a poem plus an internal classification call that must never reach the user.

python
# m02_filter.py: two model calls in one graph: filter tokens by node, by tag, and silence one with "nostream"
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    topic: str
    joke: str
    poem: str
    note: str


def make(text, **config):
    model = GenericFakeChatModel(messages=iter([AIMessage(content=text)]))
    return model.with_config(config) if config else model


joke_model = make("a joke about cats", tags=["joke"])
poem_model = make("a poem about dogs", tags=["poem"])
secret_model = make("an internal classification label", tags=["nostream"])


def write_joke(state: State):
    return {"joke": joke_model.invoke("joke").content}


def write_poem(state: State):
    return {"poem": poem_model.invoke("poem").content, "note": secret_model.invoke("classify").content}


graph = (StateGraph(State).add_node(write_joke).add_node(write_poem)
         .add_edge(START, "write_joke").add_edge("write_joke", "write_poem").add_edge("write_poem", END).compile())


def collect(predicate):
    text = []
    for part in graph.stream({"topic": "x", "joke": "", "poem": "", "note": ""}, stream_mode="messages", version="v2"):
        chunk, meta = part["data"]
        if predicate(meta):
            text.append(chunk.content)
    return "".join(text)


# the models are consumed once, so rebuild between runs
def fresh():
    global joke_model, poem_model, secret_model
    joke_model, poem_model, secret_model = make("a joke about cats", tags=["joke"]), make("a poem about dogs", tags=["poem"]), make("an internal classification label", tags=["nostream"])


fresh(); print("everything       :", repr(collect(lambda m: True)))
fresh(); print("node == write_poem:", repr(collect(lambda m: m["langgraph_node"] == "write_poem")))
fresh(); print("tag == joke       :", repr(collect(lambda m: "joke" in m["tags"])))

# 'nostream' is a tag, so the secret model's tokens never appear above; but it still ran
fresh()
final = graph.invoke({"topic": "x", "joke": "", "poem": "", "note": ""})
print("note in the state :", repr(final["note"]))
fresh()
print("updates still show:", [list(p["data"]["write_poem"]) for p in graph.stream({"topic": "x", "joke": "", "poem": "", "note": ""}, stream_mode="updates", version="v2") if "write_poem" in p["data"]])

# disable_streaming on the model: the node gets one chunk instead of many
whole = GenericFakeChatModel(messages=iter([AIMessage(content="one two three")]), disable_streaming=True)


def only(state: State):
    return {"joke": whole.invoke("x").content}


g2 = StateGraph(State).add_node("only", only).add_edge(START, "only").add_edge("only", END).compile()
print("disable_streaming :", [p["data"][0].content for p in g2.stream({"topic": "", "joke": "", "poem": "", "note": ""}, stream_mode="messages", version="v2")])
Output6 lines
everything       : 'a joke about catsa poem about dogs'
node == write_poem: 'a poem about dogs'
tag == joke       : 'a joke about cats'
note in the state : 'an internal classification label'
updates still show: [['poem', 'note']]
disable_streaming : ['one two three']
  • By node: metadata["langgraph_node"] == "write_poem" kept only the poem's tokens. Good when each node has one job.
  • By tag: tag the model (init_chat_model(..., tags=["joke"]) or model.with_config(tags=[...])) and test "joke" in metadata["tags"]. Tags travel with the model, so they keep working when the model is called from a helper or a tool. Use tags when one node makes several calls, or when you want a name that survives refactors.
  • The nostream tag (constant TAG_NOSTREAM in langgraph.constants, value "nostream") excludes that model's tokens from messages mode altogether. The third model carried it, and its text appears in no filter's output. Crucially, the model still ran: the label is in the state (note in the state) and in the updates stream ('poem', 'note'). nostream hides tokens, it does not skip the call. Use it for classification and structured-output calls, or when you stream the same content another way.
  • disable_streaming: the last line shows the node's reply arriving as one chunk, ['one two three'], instead of three words and two spaces.

7.4 Tokens from an entrypoint#

Token streaming does not need a graph. A model called inside a task streams, and the langgraph_node metadata carries the task's name:

python
# m03_entrypoint_tokens.py: token streaming from a model called inside a @task of an @entrypoint
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage

from langgraph.func import entrypoint, task

model = GenericFakeChatModel(messages=iter([AIMessage(content="Paris is the capital of France.")]))


@task
def answer(question: str) -> str:
    return model.invoke(question).content


@entrypoint()
def qa(question: str) -> str:
    return answer(question).result()


for part in qa.stream("Capital of France?", stream_mode="messages", version="v2"):
    chunk, meta = part["data"]
    print(repr(chunk.content), "| node:", meta["langgraph_node"])
Output11 lines
'Paris' | node: answer
' ' | node: answer
'is' | node: answer
' ' | node: answer
'the' | node: answer
' ' | node: answer
'capital' | node: answer
' ' | node: answer
'of' | node: answer
' ' | node: answer
'France.' | node: answer

Filter on the task name (answer) exactly as you would on a node name.

7.5 push_message: a message you write yourself#

Sometimes there is no model call to stream from, but you want a chat message to appear in the stream: a status line that belongs in the transcript, or a message assembled from several sources. push_message (from langgraph.graph.message) writes a message to the messages stream, and by default to state as well. The message needs an id:

python
# c02_push.py: push_message writes a message to the messages stream (and to state)
from langchain_core.messages import AIMessage
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.graph.message import push_message


def narrate(state: MessagesState):
    push_message(AIMessage(content="Searching the catalogue...", id="progress-1"))
    return {"messages": [AIMessage(content="Found 3 items.", id="final-1")]}


graph = StateGraph(MessagesState).add_node(narrate).add_edge(START, "narrate").add_edge("narrate", END).compile()
for part in graph.stream({"messages": [("user", "find boots")]}, stream_mode="messages", version="v2"):
    msg, meta = part["data"]
    print(type(msg).__name__, repr(msg.content), meta["langgraph_node"])
print([m.content for m in graph.invoke({"messages": [("user", "find boots")]})["messages"]])
Output3 lines
AIMessage 'Searching the catalogue...' narrate
AIMessage 'Found 3 items.' narrate
['find boots', 'Searching the catalogue...', 'Found 3 items.']

Both messages reached the messages stream tagged with the node that wrote them, and the pushed one is also in the final state ('Searching the catalogue...' sits between the user message and the node's return value). It is an advanced tool: if you only want progress that is not part of the conversation, use the stream writer (Part 8), which does not touch state.

7.6 What else is in a messages stream#

Three things beyond model tokens:

  1. Whole messages added to state by a node. A node that returns {"messages": [ToolMessage(...)]} makes that message appear in the stream when the node finishes. In an agent, the tools node emits tool messages this way, so a UI that prints every chunk as assistant text will print raw tool output as if the model had said it. Filter on metadata["langgraph_node"] or check the chunk's type (08F.8, 10.2 ran this).
  2. Tool-call fragments. While the model writes a tool call, chunks arrive with empty content and the call's name and argument fragments in the chunk's tool-call fields. Show a "calling a tool..." indicator from updates (the node boundary) rather than from half-written JSON.
  3. Reasoning text, if the provider streams it, as typed blocks; surface it only deliberately.

7.7 Streaming a model that is not a LangChain model#

messages mode listens to LangChain chat models. If your code calls a provider SDK directly (the OpenAI SDK, a local server, another framework), nothing is listening, and no tokens appear. Forward the chunks yourself through the stream writer and consume custom:

python
# custom_llm_stream.py: stream a raw OpenAI SDK call through stream_mode="custom" (illustrative: needs a provider key)
from dotenv import load_dotenv
from openai import OpenAI
from typing_extensions import TypedDict

from langgraph.config import get_stream_writer
from langgraph.graph import END, START, StateGraph

load_dotenv()  # reads OPENAI_API_KEY from .env
client = OpenAI()


class State(TypedDict):
    question: str
    answer: str


def ask(state: State):
    writer = get_stream_writer()
    pieces = []
    stream = client.responses.create(model="gpt-6-luna", input=state["question"], stream=True)
    for event in stream:
        if event.type == "response.output_text.delta":     # the Responses API text event (03.3)
            pieces.append(event.delta)
            writer({"custom_llm_chunk": event.delta})
    return {"answer": "".join(pieces)}


graph = StateGraph(State).add_node(ask).add_edge(START, "ask").add_edge("ask", END).compile()
for part in graph.stream({"question": "Name one benefit of streaming.", "answer": ""}, stream_mode="custom", version="v2"):
    print(part["data"]["custom_llm_chunk"], end="", flush=True)
print()
Example output · illustrative1 line
Users see progress immediately instead of waiting for the full answer.

The provider event names for each API are in 03.3, Part 3. The trade-off: you lose the automatic tags, node metadata and filtering that messages mode gives, and you now own the accumulation of the final text.

7.8 Async on Python older than 3.11#

On Python 3.11 and newer everything in this part works the same in async code. On older versions asyncio tasks have no context argument, so the callbacks that carry tokens do not propagate on their own: the docs say to pass the run's config explicitly to async model calls (await model.ainvoke(messages, config), with async def call_model(state, config)). Part 12 returns to the version limits; the course floor is 3.11, which avoids all of them.


Part 8: Custom events#

Deep-dive

8.1 Three ways to get a writer#

Tokens are one kind of progress. The rest is yours: "crawled 40 of 100 pages", "found 3 duplicate invoices", a partial result. The tool is the stream writer, a function that sends any serializable value into the custom stream. There are three ways to get one, and the sample uses each in a different node:

python
# c01_custom.py: stream_mode="custom": three ways to get a writer, and what happens if you forget the mode
import asyncio

from langchain_core.messages import AIMessage
from langchain_core.tools import tool
from typing_extensions import TypedDict

from langgraph.config import get_stream_writer
from langgraph.func import entrypoint, task
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode
from langgraph.runtime import Runtime
from langgraph.types import StreamWriter


class State(TypedDict):
    n: int


def with_get_writer(state: State):
    writer = get_stream_writer()                       # 1. from anywhere inside a running node
    writer({"via": "get_stream_writer", "pct": 10})
    return {"n": state["n"] + 1}


def with_param(state: State, writer: StreamWriter):    # 2. injected by name and annotation
    writer({"via": "writer parameter", "pct": 50})
    return {"n": state["n"] + 1}


def with_runtime(state: State, runtime: Runtime):      # 3. on the runtime object
    runtime.stream_writer({"via": "runtime.stream_writer", "pct": 90})
    return {"n": state["n"] + 1}


graph = (StateGraph(State).add_node(with_get_writer).add_node(with_param).add_node(with_runtime)
         .add_edge(START, "with_get_writer").add_edge("with_get_writer", "with_param")
         .add_edge("with_param", "with_runtime").add_edge("with_runtime", END).compile())

print("custom only      :", [p["data"] for p in graph.stream({"n": 0}, stream_mode="custom", version="v2")])
print("updates + custom :", [(p["type"], p["data"]) for p in graph.stream({"n": 0}, stream_mode=["updates", "custom"], version="v2")][:3], "...")
print("updates only     :", [p["type"] for p in graph.stream({"n": 0}, stream_mode="updates", version="v2")], "(the writer calls went nowhere)")
print("invoke           :", graph.invoke({"n": 0}))

# from a tool run by ToolNode
@tool
def query_database(query: str) -> str:
    """Run a query."""
    writer = get_stream_writer()
    writer({"type": "progress", "data": "Retrieved 0/100 records"})
    writer({"type": "progress", "data": "Retrieved 100/100 records"})
    return "100 rows"


tool_graph = (StateGraph(MessagesState).add_node("tools", ToolNode([query_database]))
              .add_edge(START, "tools").add_edge("tools", END).compile())
call = AIMessage(content="", tool_calls=[{"name": "query_database", "args": {"query": "select 1"}, "id": "c1", "type": "tool_call"}])
print("from a tool      :", [p["data"] for p in tool_graph.stream({"messages": [call]}, stream_mode="custom", version="v2")])


# from a task and the entrypoint of the Functional API
@task
def crunch(n: int) -> int:
    get_stream_writer()({"task": "crunching", "n": n})
    return n * n


@entrypoint()
def flow(n: int) -> int:
    get_stream_writer()({"entrypoint": "started"})
    return crunch(n).result()


print("functional       :", [p["data"] for p in flow.stream(4, stream_mode="custom", version="v2")])


# async node, writer by parameter
async def async_node(state: State, writer: StreamWriter):
    writer({"async": True})
    return {"n": 1}


agraph = StateGraph(State).add_node("a", async_node).add_edge(START, "a").add_edge("a", END).compile()


async def main():
    print("async            :", [p["data"] async for p in agraph.astream({"n": 0}, stream_mode="custom", version="v2")])


asyncio.run(main())

# get_stream_writer outside a run
try:
    get_stream_writer()
except Exception as exc:  # noqa: BLE001
    print("outside a run    :", type(exc).__name__, exc)
Output8 lines
custom only      : [{'via': 'get_stream_writer', 'pct': 10}, {'via': 'writer parameter', 'pct': 50}, {'via': 'runtime.stream_writer', 'pct': 90}]
updates + custom : [('custom', {'via': 'get_stream_writer', 'pct': 10}), ('updates', {'with_get_writer': {'n': 1}}), ('custom', {'via': 'writer parameter', 'pct': 50})] ...
updates only     : ['updates', 'updates', 'updates'] (the writer calls went nowhere)
invoke           : {'n': 3}
from a tool      : [{'type': 'progress', 'data': 'Retrieved 0/100 records'}, {'type': 'progress', 'data': 'Retrieved 100/100 records'}]
functional       : [{'entrypoint': 'started'}, {'task': 'crunching', 'n': 4}]
async            : [{'async': True}]
outside a run    : RuntimeError Called get_config outside of a runnable context
Way Code Works in
get_stream_writer() writer = get_stream_writer(); writer({...}) Any node, tool or task while a run is active; it is a function of langgraph.config
A writer parameter def node(state, writer: StreamWriter) Nodes, tasks, entrypoints and tools run by LangGraph (injected by name and annotation)
runtime.stream_writer def node(state, runtime: Runtime) then runtime.stream_writer({...}) Nodes and entrypoints; tools use ToolRuntime.stream_writer (08F.8, Part 3)

A StreamWriter is a plain callable (Callable[[Any], None]) that takes one value. What the sample showed:

  1. Custom events are separate from state. The custom only line shows the three events; invoke returned only the state change ({'n': 3}).
  2. The writer is a no-op unless "custom" is in stream_mode. updates only ran the same graph, the writer calls went nowhere and nothing failed. If your progress bar never moves, check the stream_mode before you check the code. A list such as ["updates", "custom"] is fine; you must include "custom".
  3. In a multi-mode stream the custom chunk for a node arrives before that node's updates chunk (the updates + custom line starts with custom, then updates).
  4. It works from a tool. A ToolNode ran the tool, and the two progress events came out. In create_agent agents the tool takes a ToolRuntime and calls runtime.stream_writer(...).
  5. It works from a task and from the entrypoint body (the functional line), and from an async node through the writer parameter.
  6. Outside a run there is no writer. Calling get_stream_writer() from ordinary code fails with the same get_config error as a task called outside a run.

8.2 Designing the events#

A stream consumer, usually a browser, will outlive your first version of the event payloads. Three habits:

  • Give every event a type. {"type": "progress", "done": 40, "total": 100} and {"type": "partial", "rows": [...]} let the consumer branch without guessing. A bare string works in a demo and boxes you in later.
  • Keep them small and serializable. They may be pushed through SSE, stored for replay or relayed through an Agent Server; do not send model objects, connections or giant lists.
  • Never put secrets in them, for the same reason you do not put secrets in values (6.1).

Exercise 4 builds a progress bar on this pattern.

8.3 Progress from tools in an agent#

In a create_agent agent, a tool reports progress with runtime.stream_writer and the caller streams ["updates", "custom"] (or ["messages", "custom"] for tokens and progress together), as 08F.8, 10.2 ran. Nothing new is needed: the agent is a graph, the tool is run by a ToolNode, and the writer finds the run through the same context the sample above used.

8.4 What changes on Python 3.10#

LangGraph itself still supports Python 3.10; langchain and langchain-core need 3.11 or newer. The docs describe the 3.10 limits of async code as: no get_stream_writer() in async nodes or tools (use a writer parameter), and no get_config() and get_store(). This sample was run on Python 3.10.20 with langgraph alone to check the advice:

python
# p310.py: async writer behaviour on Python 3.10 (langgraph alone; langchain needs 3.11)
import asyncio
import sys

from typing_extensions import TypedDict

from langgraph.config import get_stream_writer
from langgraph.graph import END, START, StateGraph
from langgraph.types import StreamWriter


class State(TypedDict):
    n: int


async def uses_get_stream_writer(state: State):
    get_stream_writer()({"via": "get_stream_writer"})
    return {"n": 1}


async def uses_param(state: State, writer: StreamWriter):
    writer({"via": "writer parameter"})
    return {"n": 1}


def build(node):
    return StateGraph(State).add_node("n", node).add_edge(START, "n").add_edge("n", END).compile()


async def main():
    print("python", sys.version.split()[0])
    for node in (uses_get_stream_writer, uses_param):
        try:
            print(f"{node.__name__:24s}", [c async for c in build(node).astream({"n": 0}, stream_mode="custom")])
        except Exception as exc:  # noqa: BLE001
            print(f"{node.__name__:24s}", type(exc).__name__, str(exc)[:100])


asyncio.run(main())
Output · on Python 3.13.14 (the course's Python)3 lines
python 3.13.14
uses_get_stream_writer   [{'via': 'get_stream_writer'}]
uses_param               [{'via': 'writer parameter'}]

Output on Python 3.10.20 (langgraph 1.2.22, uv run --no-project --python 3.10 --with langgraph python p310.py):

text
python 3.10.20
uses_get_stream_writer   RuntimeError Called get_config outside of a runnable context
uses_param               RuntimeError Called get_config outside of a runnable context

On 3.10 both ways failed in 1.2.22: the writer parameter raised the same get_config error as get_stream_writer(), because the writer calls get_config() internally to find the run. The docs recommend the parameter as the workaround; the installed package did not honour it in this check. The reliable fix is the one the course already assumes: use Python 3.11 or newer for any async LangGraph code that streams custom events. Sync nodes are unaffected by this limit.


Part 9: Streaming from subgraphs and agents#

Deep-dive

9.1 subgraphs=True, namespaces and create_agent#

A subgraph is a compiled graph used as a node of another graph (08F.13). create_agent returns a compiled graph, so an agent used as a node is a subgraph. By default a parent's stream shows only the parent's level, which is the cause of the commonest complaint: "my agent streams tokens by itself, but not when I put it inside another graph". The sample runs the same parent graph with and without subgraphs=True:

python
# v02_subgraph_agent.py: tokens from an agent used as a node: subgraphs=True decides whether you see them
import re

from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from typing_extensions import TypedDict

from fakes import StreamingFakeModel
from langgraph.graph import END, START, MessagesState, StateGraph


@tool
def get_weather(city: str) -> str:
    """Get the weather for a city."""
    return f"72F and sunny in {city}"


def build_parent():
    model = StreamingFakeModel(messages=iter([
        AIMessage(content="", tool_calls=[ToolCall(name="get_weather", args={"city": "Tokyo"}, id="c1")]),
        AIMessage(content="Sunny in Tokyo."),
    ]))
    agent = create_agent(model, tools=[get_weather])
    return StateGraph(MessagesState).add_node("weather_agent", agent).add_edge(START, "weather_agent").add_edge("weather_agent", END).compile()


request = {"messages": [HumanMessage("Weather in Tokyo?")]}


def ns_short(ns):
    return tuple(re.sub(r":[0-9a-f-]{36}", ":<id>", part) for part in ns)


print("--- parent stream, messages mode, subgraphs=False (default)")
parts = list(build_parent().stream(request, stream_mode="messages", version="v2"))
print("parts received:", len(parts))
for part in parts:
    chunk, meta = part["data"]
    print(f"  {type(chunk).__name__:15s} {chunk.text!r:32} node={meta['langgraph_node']!r}")

print("\n--- parent stream, messages mode, subgraphs=True")
text, seen = [], set()
for part in build_parent().stream(request, stream_mode="messages", subgraphs=True, version="v2"):
    chunk, meta = part["data"]
    seen.add((ns_short(part["ns"]), meta["langgraph_node"]))
    if meta["langgraph_node"] == "model" and chunk.text:
        text.append(chunk.text)
print("answer tokens:", "".join(text))
for item in sorted(seen):
    print("  ns =", item[0], "| langgraph_node =", item[1])

print("\n--- updates with subgraphs=True: who updated what")
for part in build_parent().stream(request, stream_mode="updates", subgraphs=True, version="v2"):
    print(" ", ns_short(part["ns"]), list(part["data"]))
Output16 lines
--- parent stream, messages mode, subgraphs=False (default)
parts received: 3
  AIMessage       ''                               node='weather_agent'
  ToolMessage     '72F and sunny in Tokyo'         node='weather_agent'
  AIMessage       'Sunny in Tokyo.'                node='weather_agent'

--- parent stream, messages mode, subgraphs=True
answer tokens: Sunny in Tokyo.
  ns = ('weather_agent:<id>',) | langgraph_node = model
  ns = ('weather_agent:<id>',) | langgraph_node = tools

--- updates with subgraphs=True: who updated what
  ('weather_agent:<id>',) ['model']
  ('weather_agent:<id>',) ['tools']
  ('weather_agent:<id>',) ['model']
  () ['weather_agent']
  • Without subgraphs=True, messages mode gave three parts, none of them tokens: the whole AIMessage with the tool call, the ToolMessage and the final AIMessage, each tagged with the parent's node name weather_agent. They arrived as the node's finished messages, not as a stream. A UI waiting for a typing effect sees a long pause and then the whole answer.
  • With subgraphs=True the agent's own tokens came through, labelled with the namespace ('weather_agent:<task id>',) and the agent's internal node names (model, tools). updates with subgraphs=True showed the inner steps (model, tools, model) before the parent's own update (weather_agent, namespace ()).
  • Use the namespace to decide what to show. An orchestrator that delegates to three specialist agents might show tokens from the namespace of the one speaking to the user and only progress lines for the others.

This applies to every mode, not just messages. v1 reports the namespace as the first element of a tuple; v2 puts it in chunk["ns"] (5.3). The task id after the colon changes on every run, so match on the part before it. Two recent fixes are in the release notes (1.2.21 and 1.2.22): whole-namespace-segment matching in get_subgraphs and streaming a child graph on its own thread to a caller that streams subgraphs.

9.2 Namespaces in the Functional API#

A functional entrypoint has namespaces too: with subgraphs=True, a custom event written inside a task came out under the namespace of the entrypoint (path: ["report_flow"] in the gateway sample in 11.1), while tokens from a model called in a task had an empty path. Treat the exact namespace of functional tasks as observed behaviour rather than a documented contract, and test the path your UI filters on.

9.3 Interrupts and subgraphs#

An interrupt raised inside a subgraph pauses the whole run. The parent streams it, and you resume on the parent with the same thread id (08F.12, Part 3, 08F.13):

python
# v03_sub_interrupt.py: an interrupt raised inside a subgraph, seen from the parent's stream
import re

from typing_extensions import TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt


class State(TypedDict):
    text: str


def ask(state: State):
    return {"text": interrupt("approve the draft?")}


child = StateGraph(State).add_node("ask", ask).add_edge(START, "ask").add_edge("ask", END).compile()      # no checkpointer of its own
parent = (StateGraph(State).add_node("review", child).add_edge(START, "review").add_edge("review", END)
          .compile(checkpointer=InMemorySaver()))


def short(ns):
    return tuple(re.sub(r":[0-9a-f-]{36}", ":<id>", part) for part in ns)


cfg = {"configurable": {"thread_id": "t"}}
print("--- leg 1")
for part in parent.stream({"text": ""}, cfg, stream_mode="updates", subgraphs=True, version="v2"):
    key = next(iter(part["data"]))
    detail = part["data"][key][0].value if key == "__interrupt__" else part["data"][key]
    print(short(part["ns"]), key, "->", detail)
print("next node waiting:", parent.get_state(cfg).next)

print("--- leg 2 (resume on the PARENT, same thread)")
for part in parent.stream(Command(resume="yes"), cfg, stream_mode="updates", subgraphs=True, version="v2"):
    print(short(part["ns"]), list(part["data"]), "->", list(part["data"].values())[0])
Output7 lines
--- leg 1
('review:<id>',) __interrupt__ -> approve the draft?
() __interrupt__ -> approve the draft?
next node waiting: ('review',)
--- leg 2 (resume on the PARENT, same thread)
('review:<id>',) ['ask'] -> {'text': 'yes'}
() ['review'] -> {'text': 'yes'}

With subgraphs=True the __interrupt__ chunk arrived twice, once under the subgraph's namespace and once at the root, both carrying the same question, and get_state on the parent showed the subgraph node (review) waiting. After the resume the subgraph's ask update came first, then the parent's review. A UI that streams ["updates", "messages"] with subgraphs=True should treat __interrupt__ at any namespace as "paused", show the question once, and stop its typing indicator.


Part 10: Event streaming: stream_events(version="v3") (beta)#

Reference

10.1 What it is, and how much to trust it#

Stream modes give you chunks and leave the assembly to you: you collect tokens into messages, notice when a model call starts, and match tool results to tool calls. Event streaming, introduced in LangGraph 1.2, flips that around. You call graph.stream_events(input, version="v3") and get back a run object with typed projections organized around what you want to render: one object per model call whose .text yields token deltas, state snapshots, subgraph runs, the final output, whether the run was interrupted.

Be clear about its status, because the sources disagree. The docs say "for new applications, we recommend event streaming" and call it "the recommended in-process streaming model for most LangGraph application code". The package source calls it "experimental and may change", the 1.2.0 release notes title it a beta, and the installed library prints a LangChainBetaWarning the first time you use it. This lesson teaches the stream modes first (stable, and what Studio and the Agent Server use) and event streaming second, labelled beta. A sensible policy is the one from 08F.8, 10.1: stream modes where stability matters more than ergonomics, event streaming where you want the typed projections and can accept some churn, and pin your versions either way. Check the event-streaming docs page before you rely on any attribute name in this part.

flowchart LR
    G["Graph run"] --> M["Stream mux: numbers each event with seq"]
    M --> T1["Built-in transformers: values, messages, subgraphs, lifecycle"]
    M --> T2["Your transformer: process(event)"]
    T1 --> P1["stream.values"]
    T1 --> P2["stream.messages"]
    T1 --> P3["stream.subgraphs"]
    T2 --> P4["stream.extensions"]
    M --> R["for event in stream: raw ProtocolEvent"]

The signatures, from the 1.2.22 source:

text
stream = graph.stream_events(input, config=None, *, version="v3",
                             interrupt_before=None, interrupt_after=None,
                             control=None, transformers=None, **kwargs)     # sync: a GraphRunStream
stream = await graph.astream_events(input, config, version="v3", ...)       # async: an AsyncGraphRunStream

Extra keyword arguments go to stream(...): context, durability, output_keys, print_mode and debug. stream_mode and subgraphs are refused (TypeError: ... do not accept stream_mode; v3 owns these), because event streaming chooses them itself. Without version="v3", stream_events and astream_events fall back to version="v2", which is LangChain core's older event schema (13.1).

10.2 The basics: messages, values, output#

python
# e01_v3_basics.py: stream_events(version="v3"): projections on a graph with a model node
import warnings

from langchain_core._api import LangChainBetaWarning

warnings.filterwarnings("ignore", category=LangChainBetaWarning)

from langchain_core.messages import AIMessage  # noqa: E402
from typing_extensions import TypedDict  # noqa: E402

from fakes import StreamingFakeModel  # noqa: E402
from langgraph.graph import END, START, StateGraph  # noqa: E402


class State(TypedDict):
    question: str
    answer: str


def build():
    model = StreamingFakeModel(messages=iter([AIMessage(content="Paris is the capital of France.")]))

    def ask(state: State):
        return {"answer": model.invoke(state["question"]).content}

    return StateGraph(State).add_node(ask).add_edge(START, "ask").add_edge("ask", END).compile()


x = {"question": "Capital of France?", "answer": ""}

# 1. messages: one ChatModelStream per LLM call
stream = build().stream_events(x, version="v3")
print("run object        :", type(stream).__name__)
for message in stream.messages:
    print("message object    :", type(message).__name__, "| node:", message.node, "| text deltas:", [d for d in message.text][:4], "...")
print("final state       :", stream.output)

# 2. the same text again, as one string
stream = build().stream_events(x, version="v3")
for message in stream.messages:
    print("str(message.text) :", repr(str(message.text)))
    print("message.output    :", type(message.output).__name__, repr(message.output.content))

# 3. values: a snapshot per step
stream = build().stream_events(x, version="v3")
print("values            :", [snap for snap in stream.values])

# 4. a projection can be read only once
stream = build().stream_events(x, version="v3")
first = [m for m in stream.messages]
try:
    second = [m for m in stream.messages]
    print("second read       :", len(second), "message(s)")
except Exception as exc:  # noqa: BLE001
    print("second read       :", type(exc).__name__, str(exc)[:110])

# 5. tee gives several readers
stream = build().stream_events(x, version="v3")
a, b = stream.messages.tee(2)
print("tee               :", len(list(a)), len(list(b)))

# 6. .output first: drives the run to the end, so the messages are already finished
stream = build().stream_events(x, version="v3")
print("output first      :", stream.output)
print("messages after    :", [str(m.text) for m in stream.messages])

# 7. interleave
stream = build().stream_events(x, version="v3")
print("interleave        :", [(name, type(item).__name__) for name, item in stream.interleave("values", "messages")])

# 8. a raw event, and an unregistered projection
stream = build().stream_events(x, version="v3")
events = list(stream)
print("raw events        :", len(events), "| first:", {k: events[0][k] for k in ("type", "method", "seq")}, "| params keys:", list(events[0]["params"]))
print("methods seen      :", sorted({e["method"] for e in events}))
stream = build().stream_events(x, version="v3")
try:
    stream.updates
except Exception as exc:  # noqa: BLE001
    print("stream.updates    :", type(exc).__name__, str(exc)[:130])
Output14 lines
run object        : GraphRunStream
message object    : ChatModelStream | node: ask | text deltas: ['Paris', ' ', 'is', ' '] ...
final state       : {'question': 'Capital of France?', 'answer': [{'type': 'text', 'text': 'Paris is the capital of France.', 'index': 0}]}
str(message.text) : 'Paris is the capital of France.'
message.output    : AIMessage [{'type': 'text', 'text': 'Paris is the capital of France.', 'index': 0}]
values            : [{'question': 'Capital of France?', 'answer': ''}, {'question': 'Capital of France?', 'answer': [{'type': 'text', 'text': 'Paris is the capital of France.', 'index': 0}]}]
second read       : RuntimeError StreamChannel already has a subscriber; use .tee(n) for fan-out.
tee               : 1 1
output first      : {'question': 'Capital of France?', 'answer': [{'type': 'text', 'text': 'Paris is the capital of France.', 'index': 0}]}
messages after    : []
interleave        : [('values', 'dict'), ('messages', 'ChatModelStream'), ('values', 'dict')]
raw events        : 17 | first: {'type': 'event', 'method': 'values', 'seq': 1} | params keys: ['namespace', 'timestamp', 'data', 'interrupts']
methods seen      : ['messages', 'values']
stream.updates    : AttributeError 'GraphRunStream' object has no attribute 'updates' (registered projections: lifecycle, messages, subgraphs, values)

Reading it:

  • stream.messages yields one ChatModelStream per model call, not one chunk per token. Iterate message.text for the token deltas, str(message.text) for the full text, and message.output for the assembled AIMessage. It also has message.node (the node name), message.reasoning, message.tool_calls and the message's id.
  • stream.values is the state snapshots, one per step. stream.output is the final state.
  • A surprise in the data: inside a v3 run the model reply's .content came back as a list of content blocks ([{'type': 'text', 'text': '...', 'index': 0}]), so the state key answer, which the node set from .content, holds that list instead of a string. In a v1 stream it would be a string. Event streaming uses the typed content-block protocol end to end. In your own nodes use .text (as fakes.py users do) when you want a string.
  • Reading a projection twice raises (RuntimeError: StreamChannel already has a subscriber; use .tee(n) for fan-out). Use stream.messages.tee(2) (or atee(n) in async) when two consumers need the same projection.
  • stream.output drives the run to the end. Reading it first meant that when we then asked for stream.messages, it was empty: the run had already finished and the tokens had gone past with no subscriber. The same applies to stream.interrupted and stream.interrupts. Decide what you will consume before you start reading, and read output last.
  • stream.interleave("values", "messages") merges projections in arrival order and yields (name, item) pairs. In synchronous code it is the way to read two projections in one pass.
  • The raw events (for event in stream) are ProtocolEvent dicts (10.7). 17 of them came out of this tiny run: values and messages events.
  • A projection whose transformer is not registered does not exist: stream.updates raised AttributeError and the message listed the registered projections (lifecycle, messages, subgraphs, values).

10.3 Consuming rules, sync and async#

Synchronous event streams have no background thread: the caller's for loop is the pump, and each step of your loop advances the graph. That has a consequence the sample just showed: with one thread you can read only one projection at a time, in order, and whichever you read first drives the run past the others. So in sync code use interleave(...) to read several projections in one pass, or read one projection and call .output afterwards.

In async code you can read projections concurrently, which is what the design is for. Each projection is separate: reading stream.messages does not consume the events that stream.values needs.

python
# e04_v3_async.py: async v3 streaming: read several projections at once with asyncio.gather
import asyncio
import warnings

from langchain_core._api import LangChainBetaWarning

warnings.filterwarnings("ignore", category=LangChainBetaWarning)

from langchain_core.messages import AIMessage  # noqa: E402
from typing_extensions import TypedDict  # noqa: E402

from fakes import StreamingFakeModel  # noqa: E402
from langgraph.graph import END, START, StateGraph  # noqa: E402


class State(TypedDict):
    text: str


model = StreamingFakeModel(messages=iter([AIMessage(content="Paris is the capital of France.")]))


def speak(state: State):
    return {"text": model.invoke("capital?").text}


graph = StateGraph(State).add_node(speak).add_edge(START, "speak").add_edge("speak", END).compile()


async def main():
    stream = await graph.astream_events({"text": ""}, version="v3")     # note the await: it returns the run object

    async def read_tokens():
        pieces = []
        async for message in stream.messages:
            async for delta in message.text:
                pieces.append(delta)
        return "".join(pieces)

    async def read_values():
        return [snapshot async for snapshot in stream.values]

    tokens, snapshots = await asyncio.gather(read_tokens(), read_values())   # both projections, one run
    print("tokens   :", repr(tokens))
    print("values   :", snapshots)
    print("output   :", await stream.output())                               # a method in the async twin


asyncio.run(main())
Output3 lines
tokens   : 'Paris is the capital of France.'
values   : [{'text': ''}, {'text': 'Paris is the capital of France.'}]
output   : {'text': 'Paris is the capital of France.'}

Two async details: astream_events is awaited and returns the run object, and in the async twin output is a method (await stream.output()), while in the sync GraphRunStream it is a property. message.text supports both async for (deltas) and await (the full text). The pattern to remember is one coroutine per projection, joined with asyncio.gather.

Other members of the run object: abort() closes the graph iterator and cancels in-flight nodes and subgraphs (idempotent), and the stream is a context manager that aborts on exit (08F.12, 10.2 ran both).

10.4 Subgraphs, lifecycle and interrupts#

python
# e02_v3_more.py: v3 subgraphs, lifecycle, interrupts, opt-in transformers, async
import warnings

from langchain_core._api import LangChainBetaWarning

warnings.filterwarnings("ignore", category=LangChainBetaWarning)

from langchain_core.messages import AIMessage  # noqa: E402
from typing_extensions import TypedDict  # noqa: E402

from fakes import StreamingFakeModel  # noqa: E402
from langgraph.checkpoint.memory import InMemorySaver  # noqa: E402
from langgraph.config import get_stream_writer  # noqa: E402
from langgraph.graph import END, START, StateGraph  # noqa: E402
from langgraph.stream import CustomTransformer, UpdatesTransformer  # noqa: E402
from langgraph.types import Command, interrupt  # noqa: E402


class State(TypedDict):
    text: str


def build_child():
    model = StreamingFakeModel(messages=iter([AIMessage(content="child says hi")]))

    def speak(state: State):
        get_stream_writer()({"progress": "child started"})
        return {"text": model.invoke("hi").text}

    return StateGraph(State).add_node("speak", speak).add_edge(START, "speak").add_edge("speak", END).compile()


def build_parent(checkpointer=None):
    def ask(state: State):
        return {"text": interrupt("approve?")}

    return (StateGraph(State).add_node("child", build_child()).add_node("ask", ask)
            .add_edge(START, "child").add_edge("child", "ask").add_edge("ask", END).compile(checkpointer=checkpointer))


x = {"text": ""}

# 1. subgraphs
stream = build_parent().stream_events(x, version="v3")
for sub in stream.subgraphs:
    print("subgraph          :", type(sub).__name__, "| name:", sub.graph_name, "| path:", sub.path[0].split(":")[0])
    print("  its messages    :", [str(m.text) for m in sub.messages])

# 1b. lifecycle events, read together with the subgraphs (one pass drives the run)
stream = build_parent().stream_events(x, version="v3")
for name, item in stream.interleave("lifecycle", "subgraphs"):
    if name == "lifecycle":
        print("lifecycle         :", item["event"], "| graph:", item.get("graph_name"))

# 2. interrupts
graph = build_parent(InMemorySaver())
cfg = {"configurable": {"thread_id": "p"}}
stream = graph.stream_events(x, cfg, version="v3")
print("interrupted       :", stream.interrupted, "|", [i.value for i in stream.interrupts])
stream = graph.stream_events(Command(resume="yes"), cfg, version="v3")
print("after resume      :", stream.interrupted, stream.output)

# 3. opt-in transformers: updates and custom
stream = build_parent().stream_events(x, version="v3", transformers=[UpdatesTransformer, CustomTransformer])
print("updates projection:", [list(u) for u in stream.updates][:3])
stream = build_parent().stream_events(x, version="v3", transformers=[UpdatesTransformer, CustomTransformer])
print("custom projection :", [c for c in stream.custom], "(the writer call was made inside the subgraph)")

# 4. kwargs v3 refuses
for kwargs in ({"stream_mode": "updates"}, {"subgraphs": True}):
    try:
        build_parent().stream_events(x, version="v3", **kwargs)
    except Exception as exc:  # noqa: BLE001
        print(f"{list(kwargs)[0]:18s}:", type(exc).__name__, str(exc).split(";")[0])
Output10 lines
subgraph          : SubgraphRunStream | name: child | path: child
  its messages    : ['child says hi']
lifecycle         : started | graph: child
lifecycle         : completed | graph: None
interrupted       : True | ['approve?']
after resume      : False {'text': 'yes'}
updates projection: [['child'], ['__interrupt__']]
custom projection : [] (the writer call was made inside the subgraph)
stream_mode       : TypeError stream_events(version='v3') / astream_events(version='v3') do not accept stream_mode
subgraphs         : TypeError stream_events(version='v3') / astream_events(version='v3') do not accept subgraphs
  • stream.subgraphs yields one SubgraphRunStream per subgraph run, with graph_name, path, and its own .messages and .values. The child's text came out of sub.messages rather than the parent's stream.messages, so you can render each agent's tokens in its own panel without parsing namespaces.
  • stream.lifecycle emits started and completed (also running, failed, interrupted) events with a namespace, a graph_name and optional error and cause. The first event carried the graph name child; the closing event, as the sample printed, had none (the completed event holds only the namespace).
  • Interrupts: stream.interrupted and stream.interrupts report a pause (reading either drives the run to the pause); resume with a new stream_events(Command(resume=...), config, version="v3") call. 08F.12, 2.2 has the full loop. After the resume the sample's output was {'text': 'yes'}.
  • Opt-in projections: stream.updates exists only because the call asked for UpdatesTransformer (10.5). Its output named the finished node (child) and the pause (__interrupt__).
  • The refusals: stream_mode and subgraphs raised TypeError.
  • A writer call inside the subgraph did not show up in the root custom projection (custom projection: []). A transformer registered at the root sees the root's events; events from a subgraph's namespace are that subgraph's. If you want custom events from inside subgraphs, check the event-streaming docs page for how to scope transformers.

10.5 Built-in transformers you can opt into#

By default a v3 run registers transformers for values, messages, subgraphs and lifecycle. Others are opt-in, passed by class in transformers=[...] at the call or registered for every run with builder.compile(transformers=[...]). All live in langgraph.stream, except the tool-call one:

Transformer Adds the projection Use
UpdatesTransformer stream.updates Per-node updates, like stream_mode="updates"
CustomTransformer stream.custom Events written with the stream writer
CheckpointsTransformer checkpoints Like stream_mode="checkpoints"
TasksTransformer tasks Like stream_mode="tasks"
DebugTransformer debug Like stream_mode="debug"
LifecycleTransformer, SubgraphTransformer lifecycle, subgraphs Registered by default
ToolCallTransformer (from langgraph.prebuilt) stream.tool_calls One object per tool call with tool_name, input, and the output once finished (08F.8, 10.3 ran it for agents)

transformers=[...] accepts classes; call-site transformers add to the compile-time ones. Each transformer declares which Pregel stream modes it needs (required_stream_modes), and the union of all of them is what the run requests.

10.6 Writing your own transformer#

A transformer watches every protocol event and builds a projection of your own. It is the supported way to compute something from the stream (token counts, tool activity, usage totals, a redaction) and expose it as a typed iterable. This one counts words per model call and publishes them as run.extensions["word_counts"]:

python
# e03_transformer.py: a custom StreamTransformer that turns raw protocol events into a projection of your own
import warnings

from langchain_core._api import LangChainBetaWarning

warnings.filterwarnings("ignore", category=LangChainBetaWarning)

from langchain_core.messages import AIMessage  # noqa: E402
from typing_extensions import TypedDict  # noqa: E402

from fakes import StreamingFakeModel  # noqa: E402
from langgraph.graph import END, START, StateGraph  # noqa: E402
from langgraph.stream import ProtocolEvent, StreamChannel, StreamTransformer  # noqa: E402


class State(TypedDict):
    text: str


class WordCounter(StreamTransformer):
    """Counts streamed text deltas per model call and exposes the totals as run.extensions['word_counts']."""

    required_stream_modes = ("messages",)          # without this, no messages events would reach process()

    def __init__(self, scope: tuple[str, ...] = ()) -> None:
        super().__init__(scope)
        self.word_counts = StreamChannel("word_counts")     # named: also emitted as a custom:word_counts event
        self._words = 0

    def init(self) -> dict:
        return {"word_counts": self.word_counts}

    def process(self, event: ProtocolEvent) -> bool:
        if event["method"] == "messages":
            payload, metadata = event["params"]["data"]      # in-process, a (protocol event, metadata) pair
            if payload["event"] == "content-block-delta" and payload["delta"]["type"] == "text-delta":
                self._words += len(payload["delta"]["text"].split())
            elif payload["event"] == "message-finish":
                self.word_counts.push({"node": metadata["langgraph_node"], "words": self._words})
                self._words = 0
        return True                                  # keep the event in the main log


model = StreamingFakeModel(messages=iter([AIMessage(content="one two three four five")]))


def speak(state: State):
    return {"text": model.invoke("go").text}


graph = StateGraph(State).add_node(speak).add_edge(START, "speak").add_edge("speak", END).compile()

stream = graph.stream_events({"text": ""}, version="v3", transformers=[WordCounter])
print("extensions keys :", list(stream.extensions))
print("word counts     :", list(stream.extensions["word_counts"]))
print("final           :", stream.output)

# the raw events, for comparison (a fresh model, because the scripted one is used up)
model = StreamingFakeModel(messages=iter([AIMessage(content="one two")]))
for event in graph.stream_events({"text": ""}, version="v3"):
    data = event["params"]["data"]
    shown = {k: v for k, v in data[0].items() if k != "id"} if event["method"] == "messages" else data   # the id differs on every run
    print(f"seq={event['seq']} method={event['method']:8s} {shown}")
Output12 lines
extensions keys : ['values', 'messages', 'lifecycle', 'subgraphs', 'word_counts']
word counts     : [{'node': 'speak', 'words': 5}]
final           : {'text': 'one two three four five'}
seq=1 method=values   {'text': ''}
seq=2 method=messages {'event': 'message-start', 'role': 'ai'}
seq=3 method=messages {'event': 'content-block-start', 'index': 0, 'content': {'type': 'text', 'text': ''}}
seq=4 method=messages {'event': 'content-block-delta', 'index': 0, 'delta': {'type': 'text-delta', 'text': 'one'}}
seq=5 method=messages {'event': 'content-block-delta', 'index': 0, 'delta': {'type': 'text-delta', 'text': ' '}}
seq=6 method=messages {'event': 'content-block-delta', 'index': 0, 'delta': {'type': 'text-delta', 'text': 'two'}}
seq=7 method=messages {'event': 'content-block-finish', 'index': 0, 'content': {'type': 'text', 'text': 'one two'}}
seq=8 method=messages {'event': 'message-finish'}
seq=9 method=values   {'text': 'one two'}

The moving parts, from the source:

  • Subclass StreamTransformer and implement init() (return a dict of projections; the keys become run.extensions entries) and process(event) (called for every event; return True to keep the event in the main log or False to suppress it). Optional hooks are finalize() and fail(err).
  • required_stream_modes = ("messages",) declares which modes the graph must emit. Without it the messages events would never reach process.
  • StreamChannel is the projection primitive: an iterable you push items into. An unnamed channel is local to the run; a named one (the sample's word_counts channel) also emits custom:word_counts protocol events, so remote consumers see it (its payloads must serialize). Channels are closed automatically when the run ends.
  • In-process, the messages events carry a tuple (protocol_event, metadata) in params["data"], as the unpacking in process shows. The metadata includes langgraph_node.
  • Async work: a transformer that needs await overrides aprocess (or calls self.schedule(coro) from process) and works only under the async API; registering it under sync stream_events raises. before_builtins = True makes a transformer run before the built-in ones, which is the hook for transformers that change content (redaction): they must act before the built-ins copy the text.

10.7 The protocol events underneath#

Iterating the run object itself yields the raw ProtocolEvent dicts. The printout above shows the nine events of one model call: a values event with the input, seven messages events and a final values event. The envelope:

Field Meaning
type Always "event"
seq A number, strictly increasing within a run. Use it for ordering; the timestamp is wall-clock and can go backwards
event_id An id for the event (when present)
method The channel: messages, values, updates, custom, tools, lifecycle, checkpoints, tasks, input, or custom:<name> for a named channel
params namespace (a list of path segments), timestamp (milliseconds), data, and interrupts on values events

Within the messages channel the sample shows the vocabulary: message-start, content-block-start, a series of content-block-delta events, content-block-finish and message-finish (which can carry usage). The documented delta types are text-delta, reasoning-delta, data-delta, tool-call-delta and block-delta; the sample saw only text deltas. The tools channel has tool-started, tool-output-delta, tool-finished and tool-error; lifecycle has started, running, completed, failed and interrupted. The docs' rule for consumers is the right one: ignore any delta type you do not recognize, so your code survives new content kinds.

The same events travel over the wire (the langchain-protocol package and the open Agent Protocol repository define the format; the Agent Server and the RemoteGraph client speak it). Keep in mind that the in-process objects, such as the (event, metadata) tuple above, are not necessarily the wire representation.

10.8 Caveats#

  • It is beta (10.1). Pin versions and re-test on upgrade.
  • v3 end to end: content-block streaming needs v3 across inner graphs too. Nesting a v1 stream(stream_mode="messages") call inside a node of a v3 run is "not fully supported", because the outer v3 handler reroutes chat-model calls through the v2 event protocol and the inner v1 handler never sees on_llm_new_token. Use v3 for the inner graph too, or call chat_model.stream(...) directly.
  • Argument chunks of tool calls carry only the new part in recent langchain-core versions, so upgrade clients before servers (08F.8, 10.3).
  • Frameworks built on it: LangChain agents (stream.tool_calls, middleware events), Deep Agents and the frontend useStream hooks are covered by their own docs pages (Further resources); the frontend side is JavaScript and outside this course.

Part 11: Streaming to a client#

Deep-dive

11.1 A graph-agnostic SSE gateway#

Part 10 of 08F.8 built an SSE generator for one agent. A real service streams several kinds of graph, so this version takes any compiled graph or entrypoint, streams messages, custom and updates together, labels each event with the subgraph path, reports an interrupt, turns exceptions into an error event, and stops the run when the client leaves. The workflow is a functional report pipeline (research, write, audit) so it also shows the Functional API streaming:

python
# sse01_gateway.py: a graph-agnostic SSE generator: tokens, progress, subgraph labels, errors, and clean cancellation
import asyncio
import json
import re

from langchain_core.messages import AIMessage
from typing_extensions import TypedDict

from fakes import StreamingFakeModel
from langgraph.config import get_stream_writer
from langgraph.func import entrypoint, task


def sse(event: str, data: dict) -> str:
    return f"event: {event}\ndata: {json.dumps(data)}\n\n"


async def graph_to_sse(graph, graph_input, config):
    """Yield SSE frames for any compiled graph or entrypoint. Closing the generator stops the run."""
    try:
        async for part in graph.astream(graph_input, config, stream_mode=["messages", "custom", "updates"], subgraphs=True, version="v2"):
            where = [segment.split(":")[0] for segment in part["ns"]]          # ["research"] for a subgraph
            if part["type"] == "messages":
                chunk, meta = part["data"]
                if chunk.text and meta.get("langgraph_node") != "tools":
                    yield sse("token", {"text": chunk.text, "node": meta["langgraph_node"], "path": where})
            elif part["type"] == "custom":
                yield sse("progress", {"data": part["data"], "path": where})
            elif "__interrupt__" in part["data"]:
                yield sse("interrupt", {"values": [i.value for i in part["data"]["__interrupt__"]]})
        yield sse("done", {})
    except asyncio.CancelledError:
        raise                                                                  # the client went away: let the cancellation through
    except Exception as exc:  # noqa: BLE001
        yield sse("error", {"type": type(exc).__name__, "message": str(exc)})  # tell the client instead of dropping the connection


progress = {"steps_after_disconnect": 0}
model = StreamingFakeModel(messages=iter([AIMessage(content="The report is ready for review.")]))


@task
async def research(topic: str) -> str:
    get_stream_writer()({"stage": "researching", "topic": topic})
    await asyncio.sleep(0.05)
    return f"notes on {topic}"


@task
async def write(notes: str) -> str:
    return (await model.ainvoke(notes)).text


@task
async def audit(report: str) -> str:
    await asyncio.sleep(0.3)
    progress["steps_after_disconnect"] += 1       # runs only if the run was NOT cancelled
    return "audited"


@entrypoint()
async def report_flow(topic: str) -> dict:
    notes = await research(topic)
    report = await write(notes)
    await audit(report)
    return {"report": report}


@entrypoint()
async def failing_flow(topic: str) -> str:
    await research(topic)
    raise RuntimeError("the model provider returned 503")


async def main():
    print("--- a full run")
    async for frame in graph_to_sse(report_flow, "Q3 sales", None):
        print(frame.strip().replace("\n", " | "))

    print("\n--- a failing run")
    async for frame in graph_to_sse(failing_flow, "Q3 sales", None):
        print(frame.strip().replace("\n", " | "))

    print("\n--- the client disconnects after the first token")
    global model
    progress["steps_after_disconnect"] = 0
    model = StreamingFakeModel(messages=iter([AIMessage(content="The report is ready for review.")]))
    stream = graph_to_sse(report_flow, "Q3 sales", None)
    async for frame in stream:
        if frame.startswith("event: token"):
            print("got a token, now closing the stream")
            break
    await stream.aclose()                          # what a web framework does when the socket closes
    await asyncio.sleep(0.6)
    print("audit steps that still ran after the disconnect:", progress["steps_after_disconnect"])


asyncio.run(main())
Output22 lines
--- a full run
event: progress | data: {"data": {"stage": "researching", "topic": "Q3 sales"}, "path": ["report_flow"]}
event: token | data: {"text": "The", "node": "write", "path": []}
event: token | data: {"text": " ", "node": "write", "path": []}
event: token | data: {"text": "report", "node": "write", "path": []}
event: token | data: {"text": " ", "node": "write", "path": []}
event: token | data: {"text": "is", "node": "write", "path": []}
event: token | data: {"text": " ", "node": "write", "path": []}
event: token | data: {"text": "ready", "node": "write", "path": []}
event: token | data: {"text": " ", "node": "write", "path": []}
event: token | data: {"text": "for", "node": "write", "path": []}
event: token | data: {"text": " ", "node": "write", "path": []}
event: token | data: {"text": "review.", "node": "write", "path": []}
event: done | data: {}

--- a failing run
event: progress | data: {"data": {"stage": "researching", "topic": "Q3 sales"}, "path": ["failing_flow"]}
event: error | data: {"type": "RuntimeError", "message": "the model provider returned 503"}

--- the client disconnects after the first token
got a token, now closing the stream
audit steps that still ran after the disconnect: 0

What each scenario shows:

  1. A full run. One progress event came from the research task's stream writer, then the tokens of the report from the write task, then done. Token events carry node (the task name) and path.
  2. A failing run. The exception from the workflow became an error event with the exception type and message. The client gets a clean frame instead of a dropped connection. (Send a generic message to browsers in production and keep details in your logs; the exception text here is only a demonstration.)
  3. A client that disconnects. After the first token the consumer called aclose() on the generator, which is what a web framework does when the socket closes. The run was cancelled: the slow audit task, which would have incremented the counter 0.3 seconds later, never ran (audit steps that still ran after the disconnect: 0). Closing the async generator closes astream, and the graph stops advancing. The except asyncio.CancelledError: raise clause matters, because swallowing the cancellation would hide it from the framework.

The path field shows the functional-namespace behaviour of 9.2: the custom event from the task carried ["report_flow"].

In FastAPI the gateway is StreamingResponse(graph_to_sse(graph, input, config), media_type="text/event-stream"); the frame format and the keep-alive rules are 03.3, Part 2.

11.2 The production checklist#

Concern What to do
Disconnects Stop the run when the client leaves (an abandoned agent keeps spending money). Closing the async generator did it above; with v3, abort() or leaving the with block
Errors Emit an error event, then close; never let an exception drop the connection silently. Return generic text to the browser and log the real one
What you send Prefer updates, messages filtered by node and custom events. Avoid raw values (the whole state at every step, internal keys included, 6.1), or restrict it with output_keys
Tool messages Filter them out of the token stream (7.6)
Interrupts Send an interrupt event with the question and end the stream; the next request carries Command(resume=...) on the same thread_id
Reconnects SSE can resend from a given event id; LangGraph streams are not replayable by themselves, so for reconnects keep the thread (the checkpoint) and re-fetch state, or use the Agent Server's join-stream features (check the docs)
Burst size Token events are tiny; at hundreds per second, coalesce a few words per frame if your proxy or browser struggles
Keep-alives Idle proxies close quiet connections; send an SSE comment line periodically during long tool calls (03.3, 2.4)
Identity Derive thread_id from the authenticated user and conversation on the server; never trust a client-supplied thread id, or one user can read another's thread
Backend and runtime A threaded or async server needs the concurrency care of Part 12; a serverless function with a short timeout needs the Agent Server or a queue instead

Part 12: Async, concurrency and thread safety#

Deep-dive

12.1 Where your code runs#

Your node and task functions run in one of two places, and the difference decides what is safe.

  • Sync functions run on a thread pool. When a super-step has several nodes (parallel branches), their sync functions run concurrently on worker threads, and so do sync tasks. The docs have no explicit thread-safety guidance; what follows is the consequence of the design (BackgroundExecutor delegates to a thread pool), the sample proves it, and "shared mutable objects need your own locking" is an inference, flagged as such.
  • Async functions run as asyncio tasks on one event loop. Parallel async nodes interleave only at await points.
python
# t01_threads.py: sync nodes of one super-step run on worker threads; shared state needs a lock
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from typing import Annotated
import operator

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    seen: Annotated[list[str], operator.add]


counter = {"value": 0}
safe = {"value": 0}
lock = threading.Lock()


def make_node(name):
    def node(state: State):
        # read-modify-write on a shared object, with a pause in the middle to expose the race
        current = counter["value"]
        time.sleep(0.05)
        counter["value"] = current + 1
        with lock:
            safe["value"] += 1
        return {"seen": [f"{name}@{threading.current_thread().name}"]}
    node.__name__ = name
    return node


builder = StateGraph(State)
for name in ("a", "b", "c", "d"):
    builder.add_node(name, make_node(name))
    builder.add_edge(START, name)
    builder.add_edge(name, END)
graph = builder.compile()

out = graph.invoke({"seen": []})
print("main thread    :", threading.current_thread().name)
print("nodes ran on   :", sorted(out["seen"]))
print("unprotected    :", counter["value"], "(4 nodes each added 1)")
print("with a Lock    :", safe["value"])

# max_concurrency limits how many run at once
active, peak = [0], [0]


def tracked(state: State):
    with lock:
        active[0] += 1
        peak[0] = max(peak[0], active[0])
    time.sleep(0.05)
    with lock:
        active[0] -= 1
    return {"seen": ["x"]}


builder = StateGraph(State)
for name in ("a", "b", "c", "d"):
    builder.add_node(name, tracked)
    builder.add_edge(START, name)
    builder.add_edge(name, END)
g2 = builder.compile()
g2.invoke({"seen": []})
print("peak, no limit :", peak[0])
peak[0] = 0
g2.invoke({"seen": []}, {"max_concurrency": 2})
print("peak, limit 2  :", peak[0])

# the same compiled graph can serve many threads, each with its own run
with ThreadPoolExecutor(4) as pool:
    results = list(pool.map(lambda i: g2.invoke({"seen": [f"req{i}"]})["seen"][0], range(4)))
print("4 threads, 1 graph:", results)
Output7 lines
main thread    : MainThread
nodes ran on   : ['a@ThreadPoolExecutor-1_0', 'b@ThreadPoolExecutor-1_1', 'c@ThreadPoolExecutor-1_2', 'd@ThreadPoolExecutor-1_3']
unprotected    : 1 (4 nodes each added 1)
with a Lock    : 4
peak, no limit : 4
peak, limit 2  : 2
4 threads, 1 graph: ['req0', 'req1', 'req2', 'req3']
  • Four nodes ran on four different worker threads (ThreadPoolExecutor-1_0 to _3), none of them the main thread.
  • An unprotected read-modify-write lost updates. Each node read the counter, paused 50 ms and wrote current + 1; all four read 0, so the counter ended at 1, not 4. The sleep makes the race certain; without it the same bug appears rarely and irreproducibly, which is worse. The version with a threading.Lock reached 4.
  • max_concurrency is a top-level key of the run config ({"max_concurrency": 2}) and caps how many nodes or tasks run at once: peak concurrency was 4 with no limit and 2 with the limit. Use it to protect a rate-limited API behind parallel branches.
  • One compiled graph serves many threads. Four caller threads each ran their own invocation of the same compiled graph and got their own results (req0 to req3); a compiled graph holds no per-run state of its own.

The practical rules: state that flows through the graph is safe (each node returns updates and LangGraph applies them); module-level or shared objects that parallel sync nodes mutate (a list, a dict, a counter, a client with internal state, a non-thread-safe SDK object) need a lock, a thread-safe type, or one instance per call. The bundled checkpointers protect themselves (according to the source, SqliteSaver and PostgresSaver use a threading.Lock, AsyncPostgresSaver an asyncio.Lock); that is a statement about their internals, not a promise about your code.

12.2 One event loop: never block it#

All async nodes share a single loop. A node that calls a blocking function (time.sleep, a synchronous HTTP client, a heavy computation) without await freezes every other async node and every other request in the process while it runs:

python
# t03_async.py: async nodes share ONE event loop: a blocking call stalls every other node
import asyncio
import time

from typing import Annotated
import operator

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    done: Annotated[list[str], operator.add]


async def good(state: State):
    await asyncio.sleep(0.5)
    return {"done": ["good"]}


async def also_good(state: State):
    await asyncio.sleep(0.5)
    return {"done": ["also_good"]}


async def blocking(state: State):
    time.sleep(0.5)                     # blocks the event loop
    return {"done": ["blocking"]}


async def offloaded(state: State):
    await asyncio.to_thread(time.sleep, 0.5)     # runs in a worker thread instead
    return {"done": ["offloaded"]}


def build(*nodes):
    b = StateGraph(State)
    for n in nodes:
        b.add_node(n)
        b.add_edge(START, n.__name__)
        b.add_edge(n.__name__, END)
    return b.compile()


async def timed(label, graph):
    start = time.perf_counter()
    await graph.ainvoke({"done": []})
    print(f"{label:34s} {time.perf_counter() - start:.1f}s")


async def main():
    await timed("two awaiting nodes", build(good, also_good))
    await timed("one awaiting, one blocking", build(good, blocking))
    await timed("one awaiting, one in to_thread", build(good, offloaded))


asyncio.run(main())
Output3 lines
two awaiting nodes                 0.5s
one awaiting, one blocking         1.0s
one awaiting, one in to_thread     0.5s

Two awaiting nodes overlapped (0.5 s for two half-second waits). Adding one blocking node made the pair take 1.0 s: the blocking call held the loop. Moving the same blocking work to asyncio.to_thread restored 0.5 s. Mixed graphs are fine under ainvoke: sync nodes are run on worker threads so they do not block the loop (08F.10, 4.4). Prefer an async client in an async node, and to_thread for the occasional blocking call you cannot avoid. A blocking call inside an async node also defeats node timeouts (08F.12, Part 8 observed this).

12.3 Two runs on the same thread#

Everything above is about parallel work inside one run. A different hazard is two runs on the same thread_id at the same time (a user double-clicks send, two browser tabs, a retrying client). Both read the checkpoint, both write theirs, and the later write wins:

python
# t02_same_thread.py: two runs on the SAME thread_id at the same time: read-modify-write through `previous` loses updates
import time
from concurrent.futures import ThreadPoolExecutor

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint


@entrypoint(checkpointer=InMemorySaver())
def add_to_total(amount: int, *, previous: int | None = None) -> int:
    total = previous or 0
    time.sleep(0.05)                      # a slow step between reading `previous` and saving the result
    return total + amount


cfg = {"configurable": {"thread_id": "shared"}}
with ThreadPoolExecutor(5) as pool:
    list(pool.map(lambda n: add_to_total.invoke(n, cfg), [10, 10, 10, 10, 10]))
print("five concurrent +10 calls on one thread, saved total:", add_to_total.get_state(cfg).values, "(sequential calls would give 50)")

cfg = {"configurable": {"thread_id": "serial"}}
for n in [10, 10, 10, 10, 10]:
    add_to_total.invoke(n, cfg)
print("five sequential +10 calls:", add_to_total.get_state(cfg).values)
Output2 lines
five concurrent +10 calls on one thread, saved total: 10 (sequential calls would give 50)
five sequential +10 calls: 50

Five concurrent calls that each added 10 to the total via previous left a saved total of 10, where five sequential calls left 50. Four of the five updates were lost, without an error. The same happens to any state a run reads at the start and saves at the end, in a graph or a function. The fix is to serialize runs per thread: a per-thread lock or queue in your service, a database advisory lock keyed by the thread id, or the Agent Server's policy for what to do with a second run on a busy thread (check its docs for the available strategies). Do this at the edge of your service, before the graph is called.

12.4 Async checkpointers#

An async run needs a checkpointer that supports async methods. The in-memory saver supports both; the SQLite and Postgres savers come in sync and async classes, and using the sync one under ainvoke fails:

python
# t04_async_saver.py: which checkpointers can back async execution?
import asyncio
import sqlite3

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
from langgraph.graph import END, START, StateGraph
from typing_extensions import TypedDict


class State(TypedDict):
    n: int


async def inc(state: State):
    return {"n": state["n"] + 1}


def build(saver):
    return StateGraph(State).add_node(inc).add_edge(START, "inc").add_edge("inc", END).compile(checkpointer=saver)


cfg = {"configurable": {"thread_id": "t"}}


async def main():
    print("InMemorySaver + ainvoke      :", await build(InMemorySaver()).ainvoke({"n": 0}, cfg))
    try:
        sync_saver = SqliteSaver(sqlite3.connect(":memory:", check_same_thread=False))
        print("SqliteSaver + ainvoke        :", await build(sync_saver).ainvoke({"n": 0}, cfg))
    except Exception as exc:  # noqa: BLE001
        print("SqliteSaver + ainvoke        :", type(exc).__name__, str(exc).splitlines()[0])
    async with AsyncSqliteSaver.from_conn_string(":memory:") as saver:
        print("AsyncSqliteSaver + ainvoke   :", await build(saver).ainvoke({"n": 0}, cfg))


asyncio.run(main())
Output3 lines
InMemorySaver + ainvoke      : {'n': 1}
SqliteSaver + ainvoke        : NotImplementedError The SqliteSaver does not support async methods. Consider using AsyncSqliteSaver instead.
AsyncSqliteSaver + ainvoke   : {'n': 1}

Use AsyncSqliteSaver and AsyncPostgresSaver (and the async store variants) with ainvoke, astream and astream_events; 08F.11 covers setup and connection handling.

12.5 Python versions, in one table#

Python langgraph langchain, langchain-core Async streaming of tokens and custom events
3.10 Supported (docs: 3.10+) Not supported (they need 3.11) Pass config to async model calls; get_stream_writer() and, as 8.4 observed, the writer parameter fail in async nodes
3.11 and newer Supported Supported Works as described in this lesson; async tasks need 3.11 as well

The course's floor is 3.11, which removes the whole table.

12.6 Stopping a run#

Cancellation tools by level, all from earlier sections: close the async generator or the astream iterator (11.1); abort() or a with block on a v3 stream (10.3); RunControl and GraphDrained for a graceful stop with a saved checkpoint (08F.12, Part 10); recursion_limit and call limits as a hard budget (08F.8, 7.5). Sync code cannot be cancelled in the middle of a function: the run stops at the next boundary, which is why timeouts are async-only.


Part 13: Legacy streaming, and where the docs and the packages disagree#

Reference

13.1 astream_events on a graph#

Older tutorials stream a graph (or an agent) with astream_events(..., version="v1") or "v2", the event API every LangChain Runnable has (08F.7, 7.3 owns it). Compiled graphs are Runnables, so it still works:

python
# l01_astream_events.py: the legacy astream_events(version="v2") on a graph: what old tutorials show
import asyncio
from collections import Counter

from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    answer: str


model = GenericFakeChatModel(messages=iter([AIMessage(content="hello there")]))


def speak(state: State):
    return {"answer": model.invoke("hi").content}


graph = StateGraph(State).add_node(speak).add_edge(START, "speak").add_edge("speak", END).compile()


async def main():
    counts, tokens = Counter(), []
    async for event in graph.astream_events({"answer": ""}, version="v2"):
        counts[event["event"]] += 1
        if event["event"] == "on_chat_model_stream":
            tokens.append(event["data"]["chunk"].content)
    print(dict(counts))
    print("tokens from on_chat_model_stream:", tokens)


asyncio.run(main())
Output2 lines
{'on_chain_start': 2, 'on_chat_model_start': 1, 'on_chat_model_stream': 3, 'on_chat_model_end': 1, 'on_chain_stream': 2, 'on_chain_end': 2}
tokens from on_chat_model_stream: ['hello', ' ', 'there']

You get a flood of on_chain_start, on_chain_stream, on_chain_end events for every internal step, plus the on_chat_model_stream events that carry tokens. It works, and old code filters it with include_names, include_tags and include_types. For graphs it is usually the wrong tool now: the stream modes give the same tokens (messages), node progress (updates) and custom events (custom) without the internal noise, and event streaming v3 gives typed projections. Two details from 08F.7, 7.5: version="v1" is deprecated, and the sync stream_events raises for v1 and v2, so the legacy API is async only. Event filters written against the 0.x agent node name "agent" must now use "model" (08F.4, Part 4).

13.2 Old names and shapes, and what replaced them#

In an old tutorial Today
for mode, data in graph.stream(x, stream_mode=["updates", "values"]) (a tuple per chunk) Still the v1 shape. New code passes version="v2" and reads chunk["type"] and chunk["data"]
for ns, data in graph.stream(x, subgraphs=True) v2: chunk["ns"]
result["__interrupt__"] on an invoke result invoke(..., version="v2") and result.interrupts
@entrypoint(config_schema=...), @task(retry=...), @entrypoint(retry=...) context_schema=, retry_policy= (both old names warn)
get_stream_writer() inside async nodes on Python 3.10, then a writer parameter as the fix Python 3.11 or newer (8.4)
Token streaming wired by hand with callback handlers and on_llm_new_token stream_mode="messages" or stream.messages
astream_events(version="v1"/"v2") to watch a graph Stream modes, or stream_events(version="v3") (beta)
Functional API as the default way to write a ReAct agent from scratch create_agent (08F.8) for agents, the Graph API for custom workflows, the Functional API for wrapping code
MessageGraph StateGraph with add_messages (08F.10, 3.4)

13.3 Docs versus reality, as observed on 14 November 2026#

This lesson ran the samples instead of trusting the pages. Where a page and the packages disagreed, the lesson teaches what ran:

Topic The docs or source say What ran on langgraph 1.2.22
Functional API role Older pages: an equal alternative; current page: "Prefer the Graph API for building new agents" Both compile to a Pregel; the recommendation is the only thing that changed (1.1)
Event streaming status Docs: recommended for new applications Package: LangChainBetaWarning, "experimental and may change" (Part 10)
checkpoints and tasks modes Docs: need a checkpointer checkpoints emitted nothing without one; tasks and debug worked (6.2)
Task inputs with a checkpointer Docs and source docstring: must serialize The in-memory saver accepted a plain object as a task input; outputs did fail (1.6)
writer parameter as the Python 3.10 workaround for async Docs: use a writer parameter Both the parameter and get_stream_writer() raised on 3.10.20 (8.4)
Async example in the @task docstring return asyncio.gather(*futures) Needs await; otherwise an un-awaited future is returned (1.4)
ToolRuntime docstring stream_writer.write(...) stream_writer is a plain callable (8.1)
Reordering tasks while a run is paused Docs: cached values mismatch Stored results were not found and both tasks re-ran (different tasks); the same task twice with swapped arguments returned the old results silently (3.4)
The messages stream of an agent used as a node Docs: tokens need subgraphs=True Without it, whole messages arrived at the node's end, no tokens (9.1)
get_graph() on an entrypoint Docs: no static visualization Returns a one-node graph (1.3)
Content of model replies inside a v3 run A typed content-block protocol A node that stores .content stores a list of blocks, not a string (10.2)
Whether the __interrupt__ chunk appears once Not spelled out With subgraphs=True it appeared at the subgraph namespace and at the root (9.3)

Re-run the relevant samples after upgrading langgraph: several of these rows (the 3.10 writer, the unserialized task input, the checkpoints mode) are the kind of thing a later patch release changes.


Reference

14.1 What do I use?#

You want Use Notes
A chat typing effect stream_mode="messages", filtered by langgraph_node or a tag Add subgraphs=True if the model runs inside a subgraph or an agent
A "what is the system doing" status line updates (node or task names) Cheap, small, one event per step
A progress bar inside a long step custom through the stream writer Remember the mode must include "custom"
Tokens and progress together stream_mode=["messages", "custom"], version="v2" Branch on chunk["type"]
Timing and inputs per step while debugging tasks or debug, or LangSmith traces (11A.5) print_mode for a quick look
Persistence debugging checkpoints, get_state_history (08F.11) checkpoints needs a checkpointer
A typed, per-message rendering in a new app Event streaming v3 (beta) Pin versions; read the docs page
To stream a provider SDK or a non-LangChain model The stream writer, custom You own the accumulation (7.7)
To collect a whole stream in a test invoke(x, stream_mode="updates", version="v2") Returns the list of parts
Streaming over HTTP without writing a gateway The Agent Server (11A.5) Same modes
Durable steps in code you already have Functional API (@entrypoint, @task) Part 4
A workflow whose shape you want to see and review Graph API 08F.10
Symptom Cause Fix
RuntimeError: Called get_config outside of a runnable context A task or get_stream_writer() called from ordinary code, or from an async node on Python 3.10 Call tasks only inside an entrypoint, a node or another task (1.2); use Python 3.11 or newer (8.4)
An output of <Future ...> or _GatheringFuture .result() or await missing Wait for the future (1.4); return await asyncio.gather(...)
The workflow "succeeded" but a task failed A started task whose future was never read (1.5) Read every future you start
TypeError: Type is not msgpack serializable A task or entrypoint returned an object a checkpointer cannot store Return plain data; rebuild rich objects inside the task (1.6)
ValueError: Entrypoint function must have at least one parameter, or TypeError ... missing 1 required positional argument The one-input rule Accept one parameter; pass several values in a dict (1.3)
A random number, a timestamp or an id changes after a resume Computed outside a task Move it into a task (3.2)
An email or payment happened twice Side effect outside a task, or a task that started and was retried A task per side effect, plus an idempotency key (3.2)
After a deploy, paused runs repeated work, or silently returned stale results for the wrong call Tasks or interrupts reordered while runs were paused Drain first, add new logic at the end, or use a new entrypoint name (3.4)
previous is always None No checkpointer, no thread_id, or a different thread Pass a checkpointer and the same thread_id (2.1)
The chat history grows without limit previous is saved whole every turn Trim or summarize before saving (2.1)
The custom stream is empty "custom" not in stream_mode Include it (8.1)
No tokens from my agent inside another graph subgraphs=True missing Add it and filter by namespace (9.1)
Tool output printed as if the assistant said it messages mode also carries tool messages Filter on langgraph_node (7.6)
An unpack error after adding an option to a stream loop v1 chunk shapes change with options Use version="v2" (5.3)
values leaks internal state to the browser values carries every channel output_keys, or send updates and custom (5.5)
A v3 projection is empty or raises Read twice, or after .output drove the run tee, interleave, or read .output last (10.2)
AttributeError on stream.updates Opt-in transformer not registered Pass it in transformers=[...] (10.5)
A counter or list is wrong after parallel branches Shared mutable state in sync nodes on threads A lock, a thread-safe type, or return state through the graph (12.1)
Everything freezes while one async node runs A blocking call in an async node An async client, or asyncio.to_thread (12.2)
A thread's saved state lost updates Two runs on the same thread_id at once Serialize runs per thread (12.3)
NotImplementedError: The SqliteSaver does not support async methods Sync saver with ainvoke Use the async saver (12.4)

Common misconceptions#

Misconception Reality
"The Functional API is a lighter, separate engine." It compiles to the same Pregel as the Graph API and shares checkpointers, interrupts and stream modes
"A task runs once, so its side effect cannot repeat." A completed task's result is restored; a task that started and did not finish can run again (3.2)
"Resume continues from the line where the function stopped." It replays from the first line; only finished tasks are skipped (3.1)
"A task call returns the result." It returns a future that is already running; .result() or await returns the value (1.4)
"If a task fails, the workflow fails." Only if its future is read (1.5)
"previous is the conversation history." It is one saved value you manage; with entrypoint.final you choose what it is (2.1)
"The Functional API can be drawn like a graph." get_graph() shows one node (1.3)
"invoke and stream default to the same mode." invoke defaults to values; stream on a compiled graph and on an entrypoint to updates (5.2)
"messages mode only works when I call model.stream." model.invoke inside a node also streams (7.1)
"nostream stops the model from running." It only hides the tokens; the call, its output and its updates remain (7.3)
"Schemas hide private keys from the stream." values streams every channel; use output_keys or updates (5.5)
"The writer always sends events." It is a no-op unless "custom" is in stream_mode (8.1)
"An agent inside another graph streams tokens to the parent." Not without subgraphs=True; you get whole messages (9.1)
"Event streaming is the stable, recommended API, so the modes are legacy." It is documented as recommended but labelled experimental in the package; the modes are the stable base (10.1)
"I can read all v3 projections one after another." Sync reads drive the run; read once, use interleave, or go async (10.3)
"LangGraph makes my nodes thread-safe." Sync nodes run concurrently on threads; shared mutable objects need your own locking (12.1)
"A checkpointer makes concurrent runs on one thread safe." The later write wins and updates are lost (12.3)
"Async nodes cannot block each other." One blocking call stalls the whole event loop (12.2)

Key takeaways#

  1. @entrypoint plus @task is LangGraph's runtime for ordinary Python. Same checkpoints, interrupts and streams, no graph to declare. Prefer the Graph API for new agents; use the Functional API to wrap code you have.
  2. Tasks return running futures. Start all independent tasks first, then wait; read every future so failures surface.
  3. Replay starts at the first line. Put model calls, I/O, time, randomness and every side effect in tasks; one task per side effect; add idempotency keys.
  4. Keep the workflow's shape stable while runs are paused. Reordering tasks or interrupts re-runs work, and swapping calls to the same task silently returns the old results for the wrong arguments; drain, append, or rename the entrypoint.
  5. previous and entrypoint.final give per-thread memory with no reducers; manage its size yourself. Long-term memory is the store.
  6. Pick the stream mode for the job. updates for status, messages for tokens, custom for your own progress, values for small states, checkpoints, tasks and debug for debugging.
  7. Pass stream_mode and version="v2" explicitly. The defaults differ between invoke and stream, and v1 chunk shapes change with every option.
  8. Filter tokens by node or tag; nostream hides a model's tokens but not the call. Tool messages share the messages stream.
  9. Custom events need "custom" in the mode and a run context; use Python 3.11 or newer for async.
  10. Subgraphs and agents need subgraphs=True and a namespace-aware consumer.
  11. Event streaming is beta. Learn it, use it where its typed projections pay off, pin versions, and read each projection once.
  12. Do not block the event loop; do not share mutable state across parallel sync nodes; do not run two writers on one thread.
  13. At the edge, stream small, typed events, turn errors into events, stop the run when the client leaves, and never trust a client-supplied thread id.

Terms introduced in this lesson#

Term One-line definition
Functional API LangGraph's way to add persistence, resume, memory and streaming to ordinary Python functions with @entrypoint and @task, without declaring a graph
@entrypoint The decorator that turns a one-argument function into a compiled, resumable workflow (a Pregel)
@task The decorator that marks a unit of work whose call returns a future and whose result is saved with the checkpoint
Task future The handle a task call returns; .result() (or await) gives the value, and the task's exception is raised only there
previous A keyword-only entrypoint parameter that holds the value saved by the last run on the same thread (None on the first run or without a checkpointer)
entrypoint.final A return wrapper, entrypoint.final(value=, save=), that returns one value to the caller and saves another for previous
Injected parameter A parameter (config, store, writer, runtime, previous) that LangGraph fills in by name and annotation
Replay (functional) Restarting the entrypoint from its first line on resume, restoring finished tasks' stored results
Stream mode A named kind of streamed output: values, updates, messages, custom, checkpoints, tasks, debug
values A stream mode that emits the full state after each step (once, at the end, for an entrypoint)
updates A stream mode that emits {node_or_task_name: update} per step, plus __interrupt__ and __metadata__ keys
messages A stream mode that emits (chunk, metadata) pairs for model tokens and for messages nodes add to state
custom A stream mode that emits whatever your code sends through the stream writer
tasks A stream mode that emits a start event and a result event for each node or task
checkpoints A stream mode that emits one get_state-shaped snapshot per checkpoint; needs a checkpointer
debug A stream mode that combines checkpoints and tasks, wrapped with step, timestamp and type
StreamPart (v2) The uniform chunk dict {"type", "ns", "data"} yielded when version="v2"
Namespace (ns) The path to the (sub)graph that produced a chunk; empty at the top level
subgraphs=True A stream option that also streams from subgraphs and agents used as nodes
Stream writer A callable (from get_stream_writer(), a writer parameter or runtime.stream_writer) that sends values into the custom stream
nostream tag A model tag that hides that model's tokens from messages mode without skipping the call
push_message A function that writes a message to the messages stream (and to state) without a model call
output_keys A stream option that limits streamed channels to chosen state keys
print_mode A stream option that prints modes to the console without changing what is yielded
durability A run option ("sync", "async", "exit") that controls when checkpoints are written
Event streaming (v3) The beta stream_events(version="v3") API that returns a run object with typed projections
Projection An iterable on a v3 run object, such as messages, values, subgraphs or lifecycle, that can be read once
ProtocolEvent The raw event envelope of event streaming: type, seq, method (the channel) and params
StreamTransformer A class that observes protocol events and builds your own projection, registered through transformers=[...]
StreamChannel The iterable a transformer pushes items into; a named channel also emits custom:<name> events
max_concurrency A top-level run config key that caps how many nodes or tasks run at once

Exercises#

Everything runs with no API key. Use uv run python file.py in the lesson's project.

  1. Parallel lookups. An entrypoint looks up a customer in three systems (crm, billing, shipping), each call taking 0.3 seconds. Write it sequentially, then in parallel, and print both timings.
  2. Fix the replay bug. The entrypoint below shows a human a ticket id, waits for approval, then saves the ticket. Run it and check whether the id the human saw is the id that was saved. Fix it.
python
@entrypoint(checkpointer=InMemorySaver())
def buggy(text: str) -> dict:
    ticket_id = str(uuid4())[:8]
    ok = interrupt({"ticket": ticket_id})
    return {"ticket": ticket_id, "ok": ok}
  1. A shopping basket. Use previous and entrypoint.final so that each call adds one item and returns a one-line summary, while the saved value is the list of items. Show two customers (two threads).
  2. A progress bar. A node processes a list of files. Use the stream writer to emit done, total and file events, and print a text progress bar from stream_mode=["custom", "updates"].
  3. Who is talking? Build a parent graph with one node and a subgraph with one node, each calling a fake chat model. Stream messages with subgraphs=True and print each reply with the path of the graph that produced it.
  4. The silent failure. A workflow starts a notification task and then saves a record. The notification server is down. Run it, explain why the workflow returns normally, and change it so the failure is raised without changing the order of work.
  5. Choose the API. For each case say Graph API or Functional API and why: (a) an existing 300-line script that calls an LLM three times and needs a human approval; (b) a router that sends tickets to one of five specialist agents, with a review loop; (c) a nightly job that fetches 200 pages in parallel and summarizes them; (d) a workflow that must be reviewed by a compliance officer from a diagram.
  6. Find the blocked loop. An async graph has two nodes that each await a one-second HTTP call and a third that calls requests.get (blocking) for one second. How long does ainvoke take if all three are in one super-step, and what are two fixes?
  7. A double-click. Users sometimes send two messages almost at once on the same conversation, and the saved history loses a message. Explain why, and describe where you would add the fix and what it looks like.
  8. Upgrade a tutorial loop. Rewrite this v1 loop for version="v2" and add subgraphs=True without breaking it. Say what the namespace is for an agent added as a node named researcher.
python
for mode, data in graph.stream(x, stream_mode=["updates", "messages"]):
    if mode == "messages":
        chunk, metadata = data
        print(chunk.content, end="")
    else:
        print(list(data))
Answers and hints
  1. Starting every task before waiting for any is the whole trick. Both versions ran on 14 November 2026:
python
# x01.py: exercise 1: a three-source lookup, sequential first, then parallel
import time

from langgraph.func import entrypoint, task


@task
def fetch(source: str) -> str:
    time.sleep(0.3)                     # stands in for an HTTP call
    return f"{source}: ok"


@entrypoint()
def sequential(sources: list[str]) -> list[str]:
    return [fetch(s).result() for s in sources]


@entrypoint()
def parallel(sources: list[str]) -> list[str]:
    futures = [fetch(s) for s in sources]
    return [f.result() for f in futures]


for label, wf in [("sequential", sequential), ("parallel", parallel)]:
    start = time.perf_counter()
    result = wf.invoke(["crm", "billing", "shipping"])
    print(f"{label:11s} {result} in {time.perf_counter() - start:.1f}s")
Output2 lines
sequential  ['crm: ok', 'billing: ok', 'shipping: ok'] in 0.9s
parallel    ['crm: ok', 'billing: ok', 'shipping: ok'] in 0.3s
  1. The id is generated outside a task, so the replay after the resume generates a new one. Wrap the generator in a task and the stored result is restored:
python
# x02.py: exercise 2: a ticket id generated outside a task changes on resume; fixed with a task
from uuid import uuid4

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint, task
from langgraph.types import Command, interrupt


@entrypoint(checkpointer=InMemorySaver())
def buggy(text: str) -> dict:
    ticket_id = str(uuid4())[:8]                     # BUG: a new value on every replay
    ok = interrupt({"ticket": ticket_id})
    return {"ticket": ticket_id, "ok": ok}


@task
def new_ticket_id() -> str:
    return str(uuid4())[:8]


@entrypoint(checkpointer=InMemorySaver())
def fixed(text: str) -> dict:
    ticket_id = new_ticket_id().result()             # stored with the checkpoint, restored on resume
    ok = interrupt({"ticket": ticket_id})
    return {"ticket": ticket_id, "ok": ok}


for label, wf in [("buggy", buggy), ("fixed", fixed)]:
    cfg = {"configurable": {"thread_id": label}}
    shown_to_human = wf.invoke("hello", cfg)["__interrupt__"][0].value["ticket"]
    saved = wf.invoke(Command(resume=True), cfg)["ticket"]
    print(f"{label}: the id the human saw is the id that was saved: {shown_to_human == saved}")
Output2 lines
buggy: the id the human saw is the id that was saved: False
fixed: the id the human saw is the id that was saved: True
  1. The return value is the summary, the saved value is the list, and each thread has its own basket:
python
# x03.py: exercise 3: a shopping basket kept with previous and entrypoint.final
from typing import Any

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint


@entrypoint(checkpointer=InMemorySaver())
def basket(item: str, *, previous: Any = None) -> entrypoint.final[str, list]:
    items = (previous or []) + [item]
    summary = f"{len(items)} item(s): {', '.join(items)}"
    return entrypoint.final(value=summary, save=items)      # return text, store the list


cfg = {"configurable": {"thread_id": "cart-1"}}
for item in ["boots", "socks", "laces"]:
    print(basket.invoke(item, cfg))
print("another customer:", basket.invoke("hat", {"configurable": {"thread_id": "cart-2"}}))
Output4 lines
1 item(s): boots
2 item(s): boots, socks
3 item(s): boots, socks, laces
another customer: 1 item(s): hat
  1. Events carry done, total and file; a multi-mode stream mixes them with the node's update, and the custom events for a node arrive before its update:
python
# x04.py: exercise 4: a progress bar for a batch job, driven by stream_mode="custom"
from typing_extensions import TypedDict

from langgraph.config import get_stream_writer
from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    files: list[str]
    processed: int


def process(state: State):
    writer = get_stream_writer()
    for i, name in enumerate(state["files"], start=1):
        writer({"done": i, "total": len(state["files"]), "file": name})
    return {"processed": len(state["files"])}


graph = StateGraph(State).add_node(process).add_edge(START, "process").add_edge("process", END).compile()
for part in graph.stream({"files": ["a.pdf", "b.pdf", "c.pdf"], "processed": 0}, stream_mode=["custom", "updates"], version="v2"):
    if part["type"] == "custom":
        d = part["data"]
        bar = "#" * d["done"] + "." * (d["total"] - d["done"])
        print(f"[{bar}] {d['done']}/{d['total']} {d['file']}")
    else:
        print("node finished:", list(part["data"]))
Output4 lines
[#..] 1/3 a.pdf
[##.] 2/3 b.pdf
[###] 3/3 c.pdf
node finished: ['process']
  1. Split the namespace segment on the colon to drop the task id. The root has an empty path:
python
# x05.py: exercise 5: label every token with the path of the (sub)graph that produced it
import re

from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    text: str


def speaker(words: str, node_name: str):
    model = GenericFakeChatModel(messages=iter([AIMessage(content=words)]))

    def node(state: State):
        return {"text": model.invoke("go").content}

    node.__name__ = node_name
    return node


inner = StateGraph(State).add_node(speaker("inner words", "talk")).add_edge(START, "talk").add_edge("talk", END).compile()
outer = (StateGraph(State).add_node(speaker("outer words", "intro")).add_node("team", inner)
         .add_edge(START, "intro").add_edge("intro", "team").add_edge("team", END).compile())

labelled = {}
for part in outer.stream({"text": ""}, stream_mode="messages", subgraphs=True, version="v2"):
    chunk, meta = part["data"]
    path = "/".join(re.sub(r":.*", "", seg) for seg in part["ns"]) or "(root)"
    labelled.setdefault((path, meta["langgraph_node"]), []).append(chunk.content)
for (path, node), pieces in labelled.items():
    print(f"{path:8s} {node:6s} {''.join(pieces)!r}")
Output2 lines
(root)   intro  'outer words'
team     talk   'inner words'
  1. The exception surfaces only where the future is read. broken never read the notification future, so the workflow saved the record and returned. In fixed the future is read after the work that must happen, so the error is raised, but note r2 was still saved before the error surfaced: reading the future later does not undo earlier work. If the order matters (do not save if notification fails), read the notification result first. Whether a failed notification should block the save is a business decision; the code just has to make the choice explicit.
python
# x06.py: exercise 6: a notification task that fails silently, and the fix
from langgraph.func import entrypoint, task

sent = []


@task
def notify(user: str) -> str:
    raise ConnectionError("mail server unreachable")


@task
def save(record: str) -> str:
    sent.append(record)
    return "saved"


@entrypoint()
def broken(record: str) -> str:
    notify("ana")                      # fire and forget: the failure is never read
    return save(record).result()


@entrypoint()
def fixed(record: str) -> str:
    pending = notify("ana")
    result = save(record).result()
    pending.result()                   # read it, even if the value is not needed: now the error is raised
    return result


print("broken:", broken.invoke("r1"))
try:
    print("fixed:", fixed.invoke("r2"))
except ConnectionError as exc:
    print("fixed: raised ConnectionError:", exc)
print("saved records:", sent)
Output3 lines
broken: saved
fixed: raised ConnectionError: mail server unreachable
saved records: ['r1', 'r2']
  1. (a) Functional: the code exists, the three LLM calls become tasks, the approval is an interrupt, and you gain resume without a rewrite. (b) Graph: a router, five targets and a loop are a shape worth drawing and reviewing; Command routing and a state with reducers fit. (c) Functional is natural (futures in a loop, tasks for each page), though a graph with Send is equally valid; choose by who maintains it. (d) Graph: a diagram is the requirement, and the Functional API has none.
  2. About 2 seconds, not 1: the two async nodes overlap for one second, but the blocking requests.get holds the event loop for another second (12.2). Fixes: use an async HTTP client for the third node, or run the blocking call with asyncio.to_thread. (A plain def node would also be moved to a worker thread by LangGraph.)
  3. Both runs read the same checkpoint, each adds its message to its copy and saves, and the later save overwrites the earlier one (12.3). The fix belongs in your service, before the graph is called: serialize runs per thread id with a per-thread queue or lock, or a database advisory lock keyed by the thread id, so the second request starts after the first has saved. A reply like "still working on your last message" is a valid alternative when you prefer to reject rather than queue.
  4. The v2 form has one shape for every combination:
python
for part in graph.stream(x, stream_mode=["updates", "messages"], subgraphs=True, version="v2"):
    if part["type"] == "messages":
        chunk, metadata = part["data"]
        print(chunk.content, end="")
    else:
        print(part["ns"], list(part["data"]))

The agent's namespace is ("researcher:<task id>",), where the id part changes on every run; match on the text before the colon. With v1 the same options would have turned each item into a three-element tuple (namespace, mode, data), which is why the old loop would have failed to unpack.


Check yourself#

  1. What does @entrypoint() return, and what rules does the decorated function have to follow?
  2. What does a task call return, and which line makes four 0.5-second tasks take 0.5 seconds instead of 2 seconds?
  3. A task raises an exception and the workflow returns normally. How is that possible, and how do you prevent it?
  4. After an interrupt and a resume, how many times does plain code in an entrypoint run, and how many times does a task body run?
  5. Name three kinds of code that belong in a task and why.
  6. What does previous hold, when is it None, and what does entrypoint.final(value=..., save=...) change?
  7. You deploy a refactor that swaps two task calls while runs are paused. What happens in 1.2.22, and what are the three safe options?
  8. Give two reasons to prefer the Graph API for a new agent and two reasons to choose the Functional API.
  9. What is the default stream_mode of invoke, of stream on a compiled graph and of stream on an entrypoint?
  10. Why should you pass version="v2", and what does a v2 chunk look like?
  11. A custom stream is empty although your node calls the writer. What do you check first?
  12. How do you show only the tokens of one model in a graph with three model calls, and what does the nostream tag do and not do?
  13. Your agent streams tokens alone but not inside a parent graph. Why, and what is the fix?
  14. What is the difference between reading stream.messages and stream.output on a v3 run, and what happens if you read output first?
  15. Four parallel sync nodes increment a shared counter and the result is 1. Why, and what are two fixes? What goes wrong if two requests run on the same thread at the same time?

Further resources#

Official sources only. The LangGraph documentation is larger and moves faster than any lesson, and it is the reference for every option and for the beta event-streaming API; where it is more complete, read it. 08F.17 is the closing lesson that explains how to keep up.


← 08F.13: Subgraphs and Multi-Agent Systems | Module 08F overview | 08F.15: Patterns, Pitfalls and Migration →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close