AI Hints
Home›LangGraph Tutorial›Streaming
LangGraph · Lesson 51 of 120

Streaming Tokens

Messages mode.

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

Values and updates arrive after each step. But a model step can take seconds, while it writes. Messages mode streams the model's words, token by token, from inside the node, as they're generated.

Streaming Tokens
From the video: Streaming Tokens
  • Steps can take seconds
  • Stream the words
  • From inside the node

Words as they arrive

The chat graph comes from a helper file. With stream mode messages, each item is a pair. A message chunk, and metadata, including which node produced it. We print each non empty piece, with a bar between. Run it. The answer arrives in several pieces, instead of all at the end.

stream_tokens.pypython
from chat_graph import graph

q = {"messages": [{"role": "user", "content": "Describe a cosy bookshop in two sentences."}]}
for chunk, meta in graph.stream(q, stream_mode="messages"):
    if chunk.text:
        print(chunk.text, end=" | ")
print("\nfrom node:", meta["langgraph_node"])
Output
Sun | light filters through towering oak shelves laden with worn leather bindings and
dust motes that |  dance in the air like quiet secrets. The rich scent of old paper and
roasted hazelnut coffee mingles in the room | , inviting you to curl up in a plush
velvet armchair and lose yourself for hours. |
from node: chat
Also uses chat_graph.py
from langchain.chat_models import init_chat_model
from langgraph.graph import MessagesState, StateGraph, START

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

def chat(s: MessagesState):
    return {"messages": [model.invoke(s["messages"])]}

b = StateGraph(MessagesState); b.add_node(chat); b.add_edge(START, "chat")
graph = b.compile()

Token streaming tips

Token streaming makes apps feel fast, because people start reading straight away. Use the metadata to show tokens only from the node you want, like the final answer node, and not from a hidden classifier.

keyvalue
Feels fastread immediately
Each item(chunk, metadata)
Filterby langgraph_node
Worksinside any node

Summary

Stream mode messages yields model tokens as they're written, with metadata saying which node made them. Next, sending your own progress data.

Key takeaways
  • stream_mode='messages'
  • (chunk, metadata)
  • Filter by node
Next up: Custom Stream Data — progress messages