Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

LangChain Streaming Output Streaming

LangChain Streaming Output Streaming

Streaming allows AI to gradually return content while generating a reply, instead of waiting until the entire task is complete to display the result all at once.

For example, ChatGPT's typing effect is a common form of streaming interaction.

In LangChain, you can not only stream model text, but also observe an Agent's tool calls, node updates, and custom task progress in real time.

This chapter introduces LangChain 1.x's stream()、astream() and various stream_mode, and finally uses FastAPI to implement an SSE streaming interface that can be called by the frontend.


1. Why is streaming output needed?

Use invoke() , the program usually needs to wait for the model or Agent to finish executing before obtaining the complete result.

If an Agent needs to call multiple tools, the user may see no progress during the wait.

Streaming output can continuously send events during task execution, letting users see model text, tool calls, or task status earlier.

Method Return method Applicable scenarios
invoke() Wait for execution to complete and then return the result Scripts, batch processing, normal APIs
stream() Iterate over streaming events synchronously Terminal display, execution tracing
ainvoke() Asynchronously wait for the complete result Asynchronous web applications
astream() Iterate over streaming events asynchronously SSE, WebSocket, real-time chat

**Note:** Streaming output mainly improves the visibility of the response content and does not guarantee a shorter total execution time for the entire task.

In addition, Streaming does not necessarily return one Token at a time; what is actually returned is message fragments or execution events.


2. Installation and Environment Setup

This tutorial uses LangChain 1.x, LangGraph 1.1 or newer, and uses DeepSeek Flash as the demonstration model.

Install dependencies:

pip install -U langchain langgraph langchain-deepseek python-dotenv

Create in the project directory .env File:

DEEPSEEK_API_KEY=your_deepseek_api_key

Initialize the model and Agent:

Example

from

dotenv

import

load_dotenv

from

langchain.

agents

import

create_agent

load_dotenv

(

)

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    system_prompt

=

"You are a Chinese programming assistant for Runoob Tutorial RUNOOB."

)

The following examples uniformly use version="v2"。

Unlike the legacy streaming format, v2 events use a unified structure:

{

    "type": "messages",

    "ns": [],

    "data": (...)

}

Where:


3. stream_mode="messages": Real-time output of model text

stream_mode="messages" It is used to obtain message chunks produced during language model generation.

It is very suitable for implementing the typing effect of AI chat.

In the v2 format, the event's data usually contains:

(message_chunk, metadata)

message_chunk is a message fragment,metadata contains related information such as the node source.

Example: Terminal streaming output

Example

from

dotenv

import

load_dotenv

from

langchain.

agents

import

create_agent

load_dotenv

(

)

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    system_prompt

=

"You are a Chinese programming assistant for Runoob Tutorial RUNOOB."

)

print

(

"Real-time streaming output:"

)

for

event

in

agent.

stream

(

   

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Introduce Runoob Tutorial RUNOOB in one sentence."

}

]

}

,

    stream_mode

=

"messages"

,

    version

=

"v2"

)

:

   

if

event

[

"type"

]

!=

"messages"

:

       

continue

   

chunk

,

metadata

=

event

[

"data"

]

   

if

metadata.

get

(

"langgraph_node"

)

==

"model"

and

chunk

.

text

:

       

print

(

chunk

.

text

,

end

=

""

,

flush

=

True

)

print

(

)

If the model returns content normally, the terminal will gradually display text like:

实时流式输出:

Runoob Tutorial RUNOOB 是一个提供编程语言、开发工具和相关技术教程的在线学习网站。

The difference between invoke() different; here, for is used to receive messages gradually through a loop.

chunk.text is used to extract the text from the message fragment, rather than directly printing the entire content。

**Note:** Streaming responses may contain tool call fragments, reasoning content, or other structured content; you cannot assume all fragments are plain strings.


4. Understanding message_chunk and metadata

In addition to displaying text, developers can also view the type and source of streaming messages.

For example:

Example: Viewing message metadata

Example

first_info

=

None

for

event

in

agent.

stream

(

   

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Hello, please introduce yourself."

}

]

}

,

    stream_mode

=

"messages"

,

    version

=

"v2"

)

:

   

if

event

[

"type"

]

!=

"messages"

:

       

continue

   

chunk

,

metadata

=

event

[

"data"

]

   

if

first_info

is

None

and

chunk

.

text

:

        first_info

=

{

           

"text"

:

chunk

.

text

,

           

"node"

: metadata.

get

(

"langgraph_node"

)

,

           

"type"

:

type

(

chunk

)

.name

       

}

if

first_info:

   

print

(

"Text fragment:"

,

first_info

[

"text"

]

)

   

print

(

"Source node:"

,

first_info

[

"node"

]

)

   

print

(

"Message type:"

,

first_info

[

"type"

]

)

Possible output:

文本片段: 你好

来源节点: model

消息类型: AIMessageChunk

Here, the event stream is fully consumed first, and then the first non-empty text fragment collected is printed.

It is not recommended to arbitrarily breakin the streaming loop just to view one fragment, because this may cause the current stream not to be fully consumed.

AIMessageChunk is not equal to one Token

AIMessageChunk represents part of a streaming model message.

One return may contain a few characters, a word, a piece of text, or even a tool call parameter fragment.

Therefore, Token consumption should not be calculated as 'one Chunk equals one Token'.


5. stream_mode="updates": Viewing the Agent execution process

updates mode is used to view the state updates produced by each node in the Agent execution graph.

For example, a course query Agent may run in the following order:

用户提问

   ↓

model:请求调用 search_course

   ↓

tools:执行搜索

   ↓

model:生成最终回答

This is very suitable for observing the Agent's tool execution process during development.

**Note:** Node updates show execution steps and are not equal to the model's internal private reasoning process.

Example: Tracing tool calls

Example

from

langchain.

tools

import

tool

from

langchain.

agents

import

create_agent

@

tool

def

search_course

(

keyword

:

str

)

str

:

   

"""Query mock programming courses by keyword."""

    courses

=

{

"python"

:

"Python3 Basic Tutorial"

,

"html"

:

"HTML Basics Tutorial"

}

   

return

courses.

get

(

keyword

.

lower

(

)

,

"No relevant mock courses found"

)

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

search_course

]

,

    system_prompt

=

"You are a course advisor. Use tools when the user asks to query courses; tool data is for demonstration only."

)

for

event

in

agent.

stream

(

   

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Please use a tool to search for python courses."

}

]

}

,

    stream_mode

=

"updates"

,

    version

=

"v2"

)

:

   

if

event

[

"type"

]

!=

"updates"

:

       

continue

   

for

node

,

update

in

event

[

"data"

]

.

items

(

)

:

       

print

(

"Node:"

,

node

)

       

if

not

isinstance

(

update

,

dict

)

:

           

continue

       

for

msg

in

update.

get

(

"messages"

,

[

]

)

:

           

if

msg.

type

==

"ai"

and

msg.

tool_calls

:

               

print

(

"Tool requests:"

,

[

(

c

[

"name"

]

,

c

[

"args"

]

)

for

c

in

msg.

tool_calls

]

)

           

elif

msg.

type

==

"tool"

:

               

print

(

"Tool results:"

,

msg.

name

,

msg.

content

)

           

elif

msg.

type

==

"ai"

and

msg.

text

:

               

print

(

"AI answer:"

,

msg.

text

)

If the model chooses to call the tool, the execution log may look like:

节点: model

工具请求: [('search_course', {'keyword': 'python'})]



节点: tools

工具结果: search_course Python3 基础教程



节点: model

AI 回答:可以先学习 Python3 基础教程。

The actual number of tool calls and the output order are determined by the model and are not fixed to three steps.

In addition, a tools node update may contain multiple tool execution results.


6. stream_mode="values": Viewing the complete state

updates returns node updates, while values is used to observe the complete State during the running process.

For example, you can see how the message history gradually increases.

Example

Example

for

event

in

agent.

stream

(

   

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Please search for python courses."

}

]

}

,

    stream_mode

=

"values"

,

    version

=

"v2"

)

:

   

if

event

[

"type"

]

!=

"values"

:

       

continue

    messages

=

event

[

"data"

]

.

get

(

"messages"

,

[

]

)

   

print

(

"Current message count:"

,

len

(

messages

)

)

   

print

(

"Message type:"

,

[

msg.

type

for

msg

in

messages

]

)

If the model made one tool call, the message history may contain in order:

['human']

['human', 'ai']

['human', 'ai', 'tool']

['human', 'ai', 'tool', 'ai']

But the number of state snapshots and messages is not guaranteed to be fixed.

For applications that need to observe all conversation content or debug custom State,values compared to updates is more convenient.

However, the complete State may contain a lot of data, so it is not recommended to unconditionally return all states to the frontend in production.


7. stream_mode="custom": Custom progress events

In addition to model text and node updates, LangChain also allows developers to send custom events.

For example, when processing multiple files, you can report the current progress in real time:

正在处理文件 1/3

正在处理文件 2/3

正在处理文件 3/3

can be used via get_stream_writer() Send custom data in supported graph nodes or tool execution contexts.

Example: Tool sends mock progress

Example

from

langchain.

tools

import

tool

from

langchain.

agents

import

create_agent

from

langgraph.

config

import

get_stream_writer

@

tool

def

process_files

(

task:

str

)

str

:

   

"""Simulate processing three files and report processing progress."""

    writer

=

get_stream_writer

(

)

   

for

i

in

range

(

1

,

4

)

:

        writer

(

{

"task"

: task

,

"current"

: i

,

"total"

:

3

,

"message"

: f

"Processed {i}/3"

}

)

   

return

"Three mock files processed"

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

process_files

]

,

    system_prompt

=

"You are a file processing assistant. Use process_files when the user asks to perform simulated processing."

)

for

event

in

agent.

stream

(

   

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Please use a tool to simulate processing the test files."

}

]

}

,

    stream_mode

=

"custom"

,

    version

=

"v2"

)

:

   

if

event

[

"type"

]

==

"custom"

:

       

print

(

event

[

"data"

]

)

If the model calls this tool, it may receive:

{'task': '测试文件', 'current': 1, 'total': 3, 'message': '已处理 1/3'}

{'task': '测试文件', 'current': 2, 'total': 3, 'message': '已处理 2/3'}

{'task': '测试文件', 'current': 3, 'total': 3, 'message': '已处理 3/3'}

No real files are processed here; it is only mock progress.

Custom events can be sent not only from Middleware, but also from tools and LangGraph nodes.

Note:get_stream_writer() They need to be used in a supported runtime context; you cannot assume a streaming writer exists when calling a normal Python function directly.


8. Combining multiple stream_modes

In real Agent applications, you usually need to display at the same time:

You can combine multiple stream modes:

stream_mode=["messages", "updates", "custom"]

When using the v2 format, you can use event["type"] to distinguish different events.

Example: Displaying model text and tool results at the same time

Example

for

event

in

agent.

stream

(

   

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Please simulate processing the test files."

}

]

}

,

    stream_mode

=

[

"messages"

,

"updates"

,

"custom"

]

,

    version

=

"v2"

)

:

    mode

,

data

=

event

[

"type"

]

,

event

[

"data"

]

   

if

mode

==

"messages"

:

       

chunk

,

metadata

=

data

       

if

metadata.

get

(

"langgraph_node"

)

==

"model"

and

chunk

.

text

:

           

print

(

chunk

.

text

,

end

=

""

,

flush

=

True

)

   

elif

mode

==

"updates"

:

       

for

node

in

data:

           

print

(

f

"\n[Node] {node}"

)

   

elif

mode

==

"custom"

:

       

print

(

f

"\n[Progress] {data.get('message', data)}"

)

print

(

)

This example reuses the previous section's process_files tools and their Agent.

You may observe:

[节点] model

[进度] 已处理 1/3

[进度] 已处理 2/3

[进度] 已处理 3/3

[节点] tools

三个模拟文件处理完成

[节点] model

The actual number and order of events, as well as the model text, may vary.

The combine mode is suitable for a complete Agent frontend interface, but if there are too many events, you also need to consider frontend rendering and network transfer costs.


9. Asynchronous Streaming Output astream()

For asynchronous applications such as FastAPI and WebSocket, you can use astream()。

It passes the question through async for to receive events step by step without blocking to wait for the full result.

Example: Asynchronous Streaming Chat

Example

import

asyncio

from

dotenv

import

load_dotenv

from

langchain.

agents

import

create_agent

load_dotenv

(

)

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    system_prompt

=

"You are the programming assistant of Runoob Tutorial RUNOOB."

)

async

def

main

(

)

:

    full_text

=

[

]

    async

for

event

in

agent.

astream

(

       

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Introduce three advantages of Python."

}

]

}

,

        stream_mode

=

"messages"

,

        version

=

"v2"

   

)

:

       

if

event

[

"type"

]

!=

"messages"

:

           

continue

       

chunk

,

metadata

=

event

[

"data"

]

       

if

metadata.

get

(

"langgraph_node"

)

==

"model"

and

chunk

.

text

:

            full_text.

append

(

chunk

.

text

)

           

print

(

chunk

.

text

,

end

=

""

,

flush

=

True

)

   

print

(

"\n\nTotal reply characters:"

,

len

(

""

.

join

(

full_text

)

)

)

if

name

==

"main"

:

    asyncio.

run

(

main

(

)

)

Here a list is used to collect the fragments, and finally "".join() the complete text is merged.

Compared to repeatedly concatenating strings in a loop, this approach is better suited for longer streaming responses.

**Note:** The character count is not equal to the Token count. If you need to track API Token consumption, you should read the usage information returned by the model.


10. FastAPI Integration: Implementing an SSE Streaming Interface

SSE (Server-Sent Events) is an HTTP-based one-way event push technology.

It is well suited to continuously pushing AI streaming text to the browser.

Below we use FastAPI to create a simple chat interface:

GET /chat?message=你好

The server, via StreamingResponse Return text/event-stream data object.

Install dependencies

pip install -U fastapi uvicorn langchain langgraph langchain-deepseek python-dotenv

Complete server code

Filename:main.py

Example

import

json

from

dotenv

import

load_dotenv

from

fastapi

import

FastAPI

,

Query

from

fastapi.

responses

import

StreamingResponse

from

langchain.

agents

import

create_agent

load_dotenv

(

)

app

=

FastAPI

(

)

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    system_prompt

=

"You are a Chinese programming assistant for Runoob Tutorial RUNOOB."

)

def

sse

(

event:

str

,

data:

dict

)

str

:

   

"""Generate a valid SSE JSON event."""

   

return

f

"event: {event}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"

@

app.

get

(

"/chat"

)

async

def

chat

(

message:

str

=

Query

(

min_length

=

1

,

max_length

=

2000

)

)

:

    async

def

generate

(

)

:

       

try

:

            async

for

item

in

agent.

astream

(

               

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

: message

}

]

}

,

                stream_mode

=

"messages"

,

                version

=

"v2"

           

)

:

               

if

item

[

"type"

]

!=

"messages"

:

                   

continue

               

chunk

,

metadata

=

item

[

"data"

]

               

if

metadata.

get

(

"langgraph_node"

)

==

"model"

and

chunk

.

text

:

                   

yield

sse

(

"token"

,

{

"text"

:

chunk

.

text

}

)

           

yield

sse

(

"done"

,

{

"finished"

:

True

}

)

       

except

Exception

:

           

yield

sse

(

"error"

,

{

"message"

:

"Model request failed, please try again later"

}

)

   

return

StreamingResponse

(

        generate

(

)

,

        media_type

=

"text/event-stream"

,

        headers

=

{

"Cache-Control"

:

"no-cache"

,

"X-Accel-Buffering"

:

"no"

}

   

)

Start the service:

uvicorn main:app --reload

Then visit:

http://127.0.0.1:8000/chat?message=你好

The server may continuously send:

event: token

data: {"text": "你好"}



event: token

data: {"text": "!欢迎"}



event: token

data: {"text": "学习 Python。"}



event: done

data: {"finished": true}

Here the text is not directly appended to data: but is first encoded as JSON.

This avoids breaking the SSE message format when the model output contains newlines or special characters.

**Note:** The example is intended for local development. In production, you also need to add API authentication, request rate limiting, concurrency control, and error logging to prevent abuse of public interfaces.

Browser Receiving SSE

The frontend can use the native EventSourcewithout needing to install any additional JavaScript library.

Example

This code appends text via textContent rather than writing the model output directly into innerHTMLwhich avoids executing the model content as HTML.

If the frontend and the FastAPI service use different domains or ports, you also need to configure CORS correctly.

For production applications, it is recommended to serve SSE through a controlled HTTPS API and to consider the response buffering settings of reverse proxies.


11. stream_mode Quick Reference

Mode Returns Typical use
messages Model message fragments and metadata Real-time chat, typewriter effect
updates State updates after node execution Tool call tracing
values Complete State snapshot State debugging
custom Custom data sent by tools or nodes Processing progress, status hints
debug More detailed graph execution information Development troubleshooting
checkpoints Checkpoint creation events Inspecting the state saving process
tasks Task start, end, and related results In-depth observation of graph execution

For most Agent applications, it is enough to first master the following three modes:

messages:显示模型生成的文本

updates:显示 Agent 执行步骤

custom:显示业务处理进度

These modes can also be used in combination.


12. Frequently asked questions

1. Does Streaming mean the model generates faster?

Not necessarily. Streaming mainly lets users see the content already produced while the model continues generating.

It can shorten the wait time for the first visible response, but does not necessarily shorten the execution time of the whole task.

2. Why doesn't messages return complete sentences?

Because the model is outputting in segments. Each message fragment may contain only partial text.

If you need the complete content, you can collect the fragments and merge them after the stream ends.

3. Is an AIMessageChunk equal to one Token?

No. Chunks and Tokens do not necessarily correspond one-to-one, so you cannot accurately calculate Token consumption based on them.

4. Why isn't chunk.content a string?

Because multimodal and structured responses may use a list of content blocks.

For ordinary text display, you can use the currently supported chunk.text property to extract the text content.

5. What is the difference between updates and messages?

updates is mainly used to observe node execution and tool results,messages is mainly used to receive message fragments during model generation.

6. How to display tool calls and the AI typewriter effect at the same time?

You can use:

stream_mode=["messages", "updates"]

Handle model text and tool execution information separately by event type.

7. Can custom only be used in Middleware?

No. Tools and LangGraph nodes can also send custom events via StreamWriter.

8. Why doesn't EventSource receive messages?

You should check whether the server returns text/event-streamwhether the event format is correct, and whether there are CORS, reverse proxy buffering, or network connection issues.

9. Why can't SSE use direct string concatenation?

Because the model text may contain special content such as newlines.

It is recommended to encode each text fragment as JSON and then place it in the SSE data: fields are read.

10. Does FastAPI StreamingResponse support POST?

Yes. But the browser's native EventSource mainly uses GET requests.

If you need to send longer prompts or complex messages via POST, you can use fetch() to read the streaming response, or use a client that supports the relevant capability.

11. Can streaming output show the model's complete thinking process?

It cannot be understood that simply.

updates You can display tool requests and node execution information, but that does not mean you can obtain the model's internal private reasoning process.

Some models may provide public reasoning summaries or specific reasoning content blocks; whether these are visible depends on the model and the service interface.

12. How to handle user disconnections in production?

You need to consider request cancellation, backend resource release, timeouts, and error handling.

You cannot assume that all running tools will stop immediately after the browser closes the page.

For tools with side effects, you also need to design idempotency and task state management to prevent duplicate operations caused by disconnection retries.


Summary

Streaming is a very important interaction capability in LangChain Agents.

This chapter covers:

The most commonly used streaming code is as follows:

for event in agent.stream(

    inputs,

    stream_mode="messages",

    version="v2"

):

    if event["type"] == "messages":

        chunk, metadata = event["data"]

        print(chunk.text, end="", flush=True)

If you need to build a complete Agent frontend, it is recommended to combine messages、updates and customto display model text, tool execution, and business processing progress separately.

Core principles:Streaming output is not only about displaying AI text gradually; more importantly, it allows the Agent's execution progress to be observed and displayed in real time.