Module 5 · Streaming & production

Streaming tokens, state and events

6 min read

An agent that thinks, calls two tools and writes an answer can take ten to twenty seconds. Facing a frozen screen, the user thinks the application is broken. Streaming changes everything: the interface shows the current steps ("looking up your order…"), then the answer token by token. LangGraph offers several streaming modes, which can be combined, each exposing one facet of the run.

Streaming modes

ModeWhat is emittedTypical use
valuesThe complete state after each stepDebugging, interfaces showing the whole state
updatesThe update returned by each nodeShowing step-by-step progress
messagesThe LLMs' tokens, as they are generated, with their metadataShowing the answer live
customData emitted by your nodesBusiness progress, intermediate results
checkpointsAn event for each checkpoint createdSyncing an interface with the history
tasksThe start and end of each task, with results and errorsFine-grained observability
debugAs much information as possible about each stepIn-depth debugging

They are enabled with stream / astream, alone or as a list:

async for part in graph.astream(
    {"messages": [("user", text)]},
    config,
    context=Context("cus_lea"),
    stream_mode=["updates", "custom", "messages"],
    subgraphs=True,
    version="v2",
):
    ...

The v2 event format

With version="v2", each event is a dictionary with a uniform format:

{"type": "updates", "ns": (), "data": {"triage": {"intent": "refund", ...}}}
{"type": "custom", "ns": ("refund:5e8c…",), "data": {"step": "assess_item", "sku": "MUG-01"}}
{"type": "messages", "ns": (),
 "data": (AIMessageChunk(content="Your order…"), {"langgraph_node": "agent", ...})}
  • type: the streaming mode that produced the event;
  • ns: the namespace, i.e. the path of the subgraph the event comes from (empty for the main graph);
  • data: the payload, specific to each mode.

This format is simpler to process than the old one (tuples whose shape varied with the options): a single match part["type"] is enough.

updates: step-by-step progress

The updates mode emits, for each completed node, its name and the update it returned. Here is the output of examples/06_streaming.py for a refund request:

[updates  relay]  load_profile
[updates  relay]  triage
[updates  refund] load_order
[custom   refund] {'step': 'assess_item', 'sku': 'MUG-01'}
[custom   refund] {'step': 'assess_item', 'sku': 'TEA-12'}
[updates  refund] assess_item
[updates  refund] assess_item
[updates  refund] decide
[messages refund] (execute) C'est fait : un remboursement de 24.00 € (RF-0001) a été émis…
[updates  refund] execute
[updates  relay]  refund
[updates  relay]  finish

With subgraphs=True, the inner steps of the refund subgraph appear, identified by their namespace. Without this option, the subgraph would be a black box: you'd only see refund, once finished.

messages: live tokens

The messages mode captures the tokens of all LangChain model calls made in nodes, even if they use ainvoke and not a streaming method: LangGraph turns on the model's streaming automatically. Each event contains a message fragment and its metadata, including langgraph_node, the originating node.

This is essential: in Relay, triage and item assessment also call a model. Their outputs are technical JSON that must never be shown to the customer. So we filter by node:

if part["type"] == "messages":
    chunk, metadata = part["data"]
    if metadata.get("langgraph_node") == "agent" and isinstance(chunk.content, str) and chunk.content:
        yield chunk.content

Note the isinstance(chunk.content, str) test: depending on the model, a fragment's content can be a list of blocks (text, thinking, tool call). For robust display, extract the text blocks.

To mark model calls that should never be streamed, you can also attach a tag to them (model.with_config(tags=["internal"])) and filter on metadata["tags"].

custom: your own events

The custom mode streams what your nodes choose to emit, via a stream writer:

from langgraph.config import get_stream_writer


async def assess_item(task: ItemTask) -> dict:
    writer = get_stream_writer()
    writer({"step": "assess_item", "sku": task["item"]["sku"]})
    ...

It's the right tool for business progress: "2 of 3 items assessed", "searching 4 sources", "generating the report". Calling the writer costs almost nothing when nobody listens to the custom mode. Tools can also emit events, via runtime.stream_writer in ToolRuntime.

From the LangGraph stream to the browser: Server-Sent Events

For a browser to receive these events, Relay's server translates them into Server-Sent Events (SSE), a simple text format natively supported by browsers (EventSource):

def _sse(event: str, data: Any) -> str:
    return f"event: {event}\ndata: {json.dumps(data, ensure_ascii=False, default=str)}\n\n"


async def _stream_run(thread_id, graph_input, context):
    async for part in app.state.graph.astream(graph_input, _config(thread_id), context=context,
                                              stream_mode=["messages", "updates", "custom"],
                                              subgraphs=True, version="v2", durability="sync"):
        if part["type"] == "messages":
            ...  # → event: token
        elif part["type"] == "updates":
            ...  # → event: step
        elif part["type"] == "custom":
            ...  # → event: progress
    if pending := await _pending(thread_id):
        yield _sse("interrupt", pending)
    yield _sse("done", {...})

The client receives a sequence of typed events: step to display progress, token to build the answer, progress for business details, then interrupt if an approval is required, and finally done. The test_message_is_streamed test checks this sequence.

The stream ends when the graph interrupts: that's why the server checks pending interrupts after the loop and reports them to the client.

Designing the experience

  • Show progress in business words. "Checking your order" rather than "tools". A node → label mapping table is enough.
  • Only stream what is meant for the user. Filter internal nodes (triage, assessment) in the messages mode.
  • Handle disconnection. If the client closes the page, stream generation is cancelled. With a checkpointer, the state of already completed steps isn't lost; the conversation will resume at the next message.
  • Be careful with proxy buffering. Some proxies and CDNs buffer responses and break streaming; an X-Accel-Buffering: no header or suitable configuration is sometimes needed.

Key takeaways

  • Main modes: updates (progress), messages (tokens), custom (business events), values (full state).
  • version="v2" gives uniform {type, ns, data} events; subgraphs=True opens the subgraphs' black box.
  • The messages mode captures all model calls: filter by langgraph_node or by tag.
  • get_stream_writer() emits custom events from any node.
  • SSE is the simple, standard format to stream these events to a browser.

Practice

  1. Run examples/06_streaming.py adding the values mode: how much data is emitted at each step?
  2. In Relay's agent node, add a custom "thinking" event, emitted before calling the model.
  3. Write a small HTML page that connects to POST /threads/{id}/messages and progressively displays step and token events (hint: fetch and ReadableStream, since EventSource only does GET).

Resources