> ## Documentation Index
> Fetch the complete documentation index at: https://nvd-54.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 流式输出

> 从智能体运行中流式输出实时更新

<Info>
  **预览功能：** 尝试对消息、工具调用、状态和最终输出进行事件流式输出的类型化智能体投影。从 [LangChain 事件流式输出](/oss/python/langchain/event-streaming)开始，或探索[流式输出 cookbook](https://github.com/langchain-ai/streaming-cookbook) 中的可运行示例。
</Info>

LangChain 实现了一个流式输出系统来展示实时更新。

流式输出对于提升基于 LLM 构建的应用程序的响应性至关重要。通过逐步显示输出，即使在完整响应准备好之前，流式输出也能显著改善用户体验（UX），特别是在处理 LLM 的延迟时。

## 概述

LangChain 的流式输出系统让你可以将智能体运行中的实时反馈展示给你的应用程序。

LangChain 流式输出的功能：

* <Icon icon="brain" size={16} /> [**流式输出智能体进度**](#agent-progress) — 在每个智能体步骤后获取状态更新。
* <Icon icon="binary" size={16} /> [**流式输出 LLM Token**](#llm-tokens) — 在语言模型生成 Token 时进行流式输出。
* <Icon icon="bulb" size={16} /> [**流式输出思考/推理 Token**](#streaming-thinking-/-reasoning-tokens) — 在模型推理生成时展示推理过程。
* <Icon icon="table" size={16} /> [**流式输出自定义更新**](#custom-updates) — 发出用户定义的信号（例如 `"Fetched 10/100 records"`）。
* <Icon icon="stack-push" size={16} /> [**流式输出多种模式**](#stream-multiple-modes) — 从 `updates`（智能体进度）、`messages`（LLM Token + 元数据）或 `custom`（任意用户数据）中选择。

有关更多端到端示例，请参阅下面的[常见模式](#common-patterns)部分。

## 支持的流式模式

将以下一个或多个流式模式作为列表传递给 [`stream`](https://reference.langchain.com/python/langgraph/graphs/#langgraph.graph.state.CompiledStateGraph.stream) 或 [`astream`](https://reference.langchain.com/python/langgraph/graphs/#langgraph.graph.state.CompiledStateGraph.astream) 方法：

| 模式         | 描述                                                        |
| ---------- | --------------------------------------------------------- |
| `updates`  | 在每个智能体步骤后流式输出状态更新。如果在同一步骤中进行了多次更新（例如运行了多个节点），这些更新会分别流式输出。 |
| `messages` | 从调用了 LLM 的任何图节点中流式输出 `(token, metadata)` 元组。              |
| `custom`   | 使用 stream writer 从图节点内部流式输出自定义数据。                         |

## 智能体进度

要流式输出智能体进度，使用 [`stream`](https://reference.langchain.com/python/langgraph/graphs/#langgraph.graph.state.CompiledStateGraph.stream) 或 [`astream`](https://reference.langchain.com/python/langgraph/graphs/#langgraph.graph.state.CompiledStateGraph.astream) 方法并设置 `stream_mode="updates"`。这会在每个智能体步骤后发出一个事件。

例如，如果你有一个调用了一次工具的智能体，你应该看到以下更新：

* **LLM 节点**：包含工具调用请求的 [`AIMessage`](https://reference.langchain.com/python/langchain-core/messages/ai/AIMessage)
* **工具节点**：包含执行结果的 [`ToolMessage`](https://reference.langchain.com/python/langchain-core/messages/tool/ToolMessage)
* **LLM 节点**：最终 AI 响应

```python title="流式输出智能体进度" theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.agents import create_agent


def get_weather(city: str) -> str:
    """Get weather for a given city."""

    return f"It's always sunny in {city}!"

agent = create_agent(
    model="gpt-5-nano",
    tools=[get_weather],
)
for chunk in agent.stream(  # [!code highlight]
    {"messages": [{"role": "user", "content": "What is the weather in SF?"}]},
    stream_mode="updates",
    version="v2",  # [!code highlight]
):
    if chunk["type"] == "updates":  # [!code highlight]
        for step, data in chunk["data"].items():  # [!code highlight]
            print(f"step: {step}")
            print(f"content: {data['messages'][-1].content_blocks}")
```

```shell title="输出" theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
step: model
content: [{'type': 'tool_call', 'name': 'get_weather', 'args': {'city': 'San Francisco'}, 'id': 'call_OW2NYNsNSKhRZpjW0wm2Aszd'}]

step: tools
content: [{'type': 'text', 'text': "It's always sunny in San Francisco!"}]

step: model
content: [{'type': 'text', 'text': 'It's always sunny in San Francisco!'}]
```

## LLM Token

要在 LLM 生成 Token 时进行流式输出，使用 `stream_mode="messages"`。下面你可以看到智能体流式输出工具调用和最终响应的输出。

```python title="流式输出 LLM Token" theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.agents import create_agent


def get_weather(city: str) -> str:
    """Get weather for a given city."""

    return f"It's always sunny in {city}!"

agent = create_agent(
    model="gpt-5-nano",
    tools=[get_weather],
)
for chunk in agent.stream(  # [!code highlight]
    {"messages": [{"role": "user", "content": "What is the weather in SF?"}]},
    stream_mode="messages",
    version="v2",  # [!code highlight]
):
    if chunk["type"] == "messages":  # [!code highlight]
        token, metadata = chunk["data"]  # [!code highlight]
        print(f"node: {metadata['langgraph_node']}")
        print(f"content: {token.content_blocks}")
        print("\n")
```

## 自定义更新

要在工具执行期间流式输出更新，可以使用 [`get_stream_writer`](https://reference.langchain.com/python/langgraph/config/get_stream_writer)。

```python title="流式输出自定义更新" theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.agents import create_agent
from langgraph.config import get_stream_writer  # [!code highlight]


def get_weather(city: str) -> str:
    """Get weather for a given city."""
    writer = get_stream_writer()  # [!code highlight]
    # 流式输出任意数据
    writer(f"Looking up data for city: {city}")
    writer(f"Acquired data for city: {city}")
    return f"It's always sunny in {city}!"

agent = create_agent(
    model="claude-sonnet-4-6",
    tools=[get_weather],
)

for chunk in agent.stream(
    {"messages": [{"role": "user", "content": "What is the weather in SF?"}]},
    stream_mode="custom",  # [!code highlight]
    version="v2",  # [!code highlight]
):
    if chunk["type"] == "custom":  # [!code highlight]
        print(chunk["data"])  # [!code highlight]
```

```shell title="输出" theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Looking up data for city: San Francisco
Acquired data for city: San Francisco
```

<Note>
  如果你在工具内添加了 [`get_stream_writer`](https://reference.langchain.com/python/langgraph/config/get_stream_writer)，你将无法在 LangGraph 执行上下文之外调用该工具。
</Note>

## 流式输出多种模式

你可以通过将流式模式作为列表传递来指定多种流式模式：`stream_mode=["updates", "custom"]`。

每个流式块是一个包含 `type`、`ns` 和 `data` 键的 `StreamPart` 字典。使用 `chunk["type"]` 来确定流式模式，使用 `chunk["data"]` 来访问负载。

## 常见模式

以下是展示流式输出常见用例的示例。

### 流式输出思考/推理 Token

一些模型在产生最终答案之前会执行内部推理。你可以通过过滤[标准内容块](/oss/python/langchain/messages#standard-content-blocks)中 `type` 为 `"reasoning"` 的内容来流式输出这些思考/推理 Token。

<Note>
  必须在模型上启用推理输出。

  有关配置详情，请参阅[推理部分](/oss/python/langchain/models#reasoning)和你的[提供商集成页面](/oss/python/integrations/providers/overview)。

  要快速检查模型的推理支持，请参阅 [models.dev](https://models.dev)。
</Note>

要从智能体流式输出思考 Token，使用 `stream_mode="messages"` 并过滤推理内容块：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.agents import create_agent
from langchain.messages import AIMessageChunk
from langchain_anthropic import ChatAnthropic
from langchain_core.runnables import Runnable


def get_weather(city: str) -> str:
    """Get weather for a given city."""
    return f"It's always sunny in {city}!"


model = ChatAnthropic(
    model_name="claude-sonnet-4-6",
    timeout=None,
    stop=None,
    thinking={"type": "enabled", "budget_tokens": 5000},
)
agent: Runnable = create_agent(
    model=model,
    tools=[get_weather],
)

for token, metadata in agent.stream(
    {"messages": [{"role": "user", "content": "What is the weather in SF?"}]},
    stream_mode="messages",  # [!code highlight]
):
    if not isinstance(token, AIMessageChunk):
        continue
    reasoning = [b for b in token.content_blocks if b["type"] == "reasoning"]
    text = [b for b in token.content_blocks if b["type"] == "text"]
    if reasoning:
        print(f"[thinking] {reasoning[0]['reasoning']}", end="")
    if text:
        print(text[0]["text"], end="")
```

```shell title="输出" theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[thinking] The user is asking about the weather in San Francisco. I have a tool
[thinking]  available to get this information. Let me call the get_weather tool
[thinking]  with "San Francisco" as the city parameter.
The weather in San Francisco is: It's always sunny in San Francisco!
```

无论模型提供商如何，这都以相同方式工作——LangChain 通过 [`content_blocks`](/oss/python/langchain/messages#standard-content-blocks) 属性将提供商特定的格式（Anthropic `thinking` 块、OpenAI `reasoning` 摘要等）规范化为标准的 `"reasoning"` 内容块类型。

要直接从聊天模型流式输出推理 Token（不使用智能体），请参阅[聊天模型的流式输出](/oss/python/langchain/models#reasoning)。

### 流式输出工具调用

你可能希望同时流式输出：

1. [工具调用](/oss/python/langchain/models#tool-calling)生成时的部分 JSON
2. 被执行的已完成、已解析的工具调用

指定 [`stream_mode="messages"`](#llm-tokens) 将流式输出智能体中所有 LLM 调用生成的增量[消息块](/oss/python/langchain/messages#streaming-and-chunks)。要访问包含已解析工具调用的完整消息：

1. 如果这些消息被跟踪在[状态](/oss/python/langchain/agents#memory)中（如 [`create_agent`](/oss/python/langchain/agents) 的 model 节点），使用 `stream_mode=["messages", "updates"]` 通过[状态更新](#agent-progress)访问完整消息（如下演示）。
2. 如果这些消息未被跟踪在状态中，使用[自定义更新](#custom-updates)或在流式循环中聚合块（[下一节](#accessing-completed-messages)）。

### 带人机协作的流式输出

要处理人机协作[中断](/oss/python/langchain/human-in-the-loop)，我们在[上面的示例](#streaming-tool-calls)基础上构建：

1. 我们使用[人机协作中间件和检查点](/oss/python/langchain/human-in-the-loop#configuring-interrupts)配置智能体
2. 我们收集在 `"updates"` 流式模式期间生成的中断
3. 我们使用[命令](/oss/python/langchain/human-in-the-loop#responding-to-interrupts)响应这些中断

### 从子智能体流式输出

当智能体中的任何点有多个 LLM 时，通常需要消除消息生成来源的歧义。

为此，在创建每个智能体时传递一个 [`name`](https://reference.langchain.com/python/langchain/agents/#langchain.agents.create_agent\(name\))。在 `"messages"` 模式下流式输出时，此名称可通过 `lc_agent_name` 键在元数据中获取。

<Tip>
  当你在智能体上设置 `name` 时，该名称也会附加到该智能体生成的任何 `AIMessage` 上。
</Tip>

## 禁用流式输出

在某些应用程序中，你可能需要为给定模型禁用单个 Token 的流式输出。这在以下场景中很有用：

* 使用[多智能体](/oss/python/langchain/multi-agent)系统来控制哪些智能体流式输出其输出
* 混合使用支持流式输出和不支持流式输出的模型
* 部署到 [LangSmith](/langsmith/home) 并希望防止某些模型输出被流式传输到客户端

在初始化模型时设置 `streaming=False`。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_openai import ChatOpenAI

model = ChatOpenAI(
    model="gpt-5.4",
    streaming=False  # [!code highlight]
)
```

<Tip>
  部署到 LangSmith 时，在你不希望将其输出流式传输到客户端的任何模型上设置 `streaming=False`。这在部署前在你的图代码中配置。
</Tip>

<Note>
  并非所有聊天模型集成都支持 `streaming` 参数。如果你的模型不支持它，请使用 `disable_streaming=True` 代替。此参数通过基类在所有聊天模型上可用。
</Note>

有关更多详情，请参阅 [LangGraph 流式输出指南](/oss/python/langgraph/streaming#disable-streaming-for-specific-chat-models)。

## v2 流式输出格式

<Note>
  需要 LangGraph >= 1.1。
</Note>

向 `stream()` 或 `astream()` 传递 `version="v2"` 以获取统一的输出格式。每个块是一个包含 `type`、`ns` 和 `data` 键的 `StreamPart` 字典——无论流式模式或模式数量如何，形状都相同：

<CodeGroup>
  ```python v2（新版） theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  # 统一格式——不再需要元组解包
  for chunk in agent.stream(
      {"messages": [{"role": "user", "content": "What is the weather in SF?"}]},
      stream_mode=["updates", "custom"],
      version="v2",
  ):
      print(chunk["type"])  # "updates" 或 "custom"
      print(chunk["data"])  # 负载
  ```

  ```python v1（当前默认） theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  # 必须解包 (mode, data) 元组
  for mode, chunk in agent.stream(
      {"messages": [{"role": "user", "content": "What is the weather in SF?"}]},
      stream_mode=["updates", "custom"],
  ):
      print(mode)   # "updates" 或 "custom"
      print(chunk)  # 负载
  ```
</CodeGroup>

v2 格式还改进了 `invoke()` —— 它返回一个具有 `.value` 和 `.interrupts` 属性的 `GraphOutput` 对象，将状态与中断元数据清晰分离：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
result = agent.invoke(
    {"messages": [{"role": "user", "content": "Hello"}]},
    version="v2",
)
print(result.value)       # 状态（dict、Pydantic 模型或 dataclass）
print(result.interrupts)  # Interrupt 对象的元组（如果没有则为空）
```

有关 v2 格式的更多详情，包括类型缩窄、Pydantic/dataclass 转换和子图流式输出，请参阅 [LangGraph 流式输出文档](/oss/python/langgraph/streaming#stream-output-format-v2)。

## 相关内容

* [前端流式输出](/oss/python/langchain/streaming/frontend) — 使用 `useStream` 构建 React UI 以实现实时智能体交互
* [聊天模型的流式输出](/oss/python/langchain/models#stream) — 直接从聊天模型流式输出 Token，无需使用智能体或图
* [聊天模型的推理](/oss/python/langchain/models#reasoning) — 配置和访问聊天模型的推理输出
* [标准内容块](/oss/python/langchain/messages#standard-content-blocks) — 了解用于推理、文本和其他内容类型的规范化内容块格式
* [带人机协作的流式输出](/oss/python/langchain/human-in-the-loop#streaming-with-human-in-the-loop) — 在处理人工审查中断时流式输出智能体进度
* [LangGraph 流式输出](/oss/python/langgraph/streaming) — 高级流式输出选项，包括 `values`、`debug` 模式和子图流式输出

***

<div className="source-links">
  <Callout icon="terminal-2">
    [连接这些文档](/use-these-docs)到 Claude、VSCode 等工具，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/langchain/streaming.mdx)或[提交 issue](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
