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

# LangChain v1 迁移指南

本指南概述了 [LangChain v1](/oss/python/releases/langchain-v1) 与之前版本之间的主要变化。

## 简化的包

在 v1 中，`langchain` 包命名空间已大幅精简，专注于智能体的核心构建模块。精简后的包使得发现和使用核心功能变得更加容易。

### 命名空间

| 模块                                                                                    | 可用内容                                                                                                                                                                                                                       | 备注                      |
| ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| [`langchain.agents`](https://reference.langchain.com/python/langchain/agents)         | [`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent), [`AgentState`](https://reference.langchain.com/python/langchain/agents/middleware/types/AgentState)                        | 核心智能体创建功能               |
| [`langchain.messages`](https://reference.langchain.com/python/langchain/messages)     | 消息类型, [内容块](https://reference.langchain.com/python/langchain-core/messages/content/ContentBlock), [`trim_messages`](https://reference.langchain.com/python/langchain-core/messages/utils/trim_messages)                    | 从 `langchain-core` 重新导出 |
| [`langchain.tools`](https://reference.langchain.com/python/langchain/tools)           | [`@tool`](https://reference.langchain.com/python/langchain-core/tools/convert/tool), [`BaseTool`](https://reference.langchain.com/python/langchain-core/tools/base/BaseTool), 注入辅助工具                                       | 从 `langchain-core` 重新导出 |
| [`langchain.chat_models`](https://reference.langchain.com/python/langchain/models)    | [`init_chat_model`](https://reference.langchain.com/python/langchain/chat_models/base/init_chat_model), [`BaseChatModel`](https://reference.langchain.com/python/langchain-core/language_models/chat_models/BaseChatModel) | 统一的模型初始化                |
| [`langchain.embeddings`](https://reference.langchain.com/python/langchain/embeddings) | [`init_embeddings`](https://reference.langchain.com/python/langchain/embeddings/base/init_embeddings), [`Embeddings`](https://reference.langchain.com/python/langchain-core/embeddings/embeddings/Embeddings)              | 嵌入模型                    |

### `langchain-classic`

如果您之前使用了 `langchain` 包中的以下任何功能，您需要安装 [`langchain-classic`](https://pypi.org/project/langchain-classic/) 并更新您的导入：

* 旧版链（`LLMChain`、`ConversationChain` 等）
* 检索器（例如 `MultiQueryRetriever` 或之前 `langchain.retrievers` 模块中的任何内容）
* 索引 API
* Hub 模块（用于以编程方式管理提示）
* 嵌入模块（例如 `CacheBackedEmbeddings` 和社区嵌入）
* [`langchain-community`](https://pypi.org/project/langchain-community) 重新导出
* 其他已弃用的功能

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  # 链
  from langchain_classic.chains import LLMChain

  # 检索器
  from langchain_classic.retrievers import ...

  # 索引
  from langchain_classic.indexes import ...

  # Hub
  from langchain_classic import hub
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  # 链
  from langchain_classic.chains import LLMChain

  # 检索器
  from langchain.retrievers import ...

  # 索引
  from langchain.indexes import ...

  # Hub
  from langchain import hub
  ```
</CodeGroup>

安装方式：

<CodeGroup>
  ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pip install langchain-classic
  ```

  ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  uv add langchain-classic
  ```
</CodeGroup>

***

## 迁移到 `create_agent`

在 v1.0 之前，我们建议使用 [`langgraph.prebuilt.create_react_agent`](https://reference.langchain.com/python/langchain-classic/agents/react/agent/create_react_agent) 来构建智能体。现在，我们建议您使用 [`langchain.agents.create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 来构建智能体。

下表概述了从 [`create_react_agent`](https://reference.langchain.com/python/langchain-classic/agents/react/agent/create_react_agent) 到 [`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 的功能变化：

| 部分                                       | 简而言之 - 变化内容                                                                                                                                                        |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [导入路径](#import-path)                     | 包从 `langgraph.prebuilt` 移至 `langchain.agents`                                                                                                                      |
| [提示](#prompts)                           | 参数重命名为 [`system_prompt`](https://reference.langchain.com/python/langchain/agents/#langchain.agents.create_agent\(system_prompt\))，动态提示使用中间件                        |
| [模型前钩子](#pre-model-hook)                 | 被具有 `before_model` 方法的中间件取代                                                                                                                                        |
| [模型后钩子](#post-model-hook)                | 被具有 `after_model` 方法的中间件取代                                                                                                                                         |
| [自定义状态](#custom-state)                   | 仅支持 `TypedDict`，可通过 [`state_schema`](https://reference.langchain.com/python/langchain/middleware/#langchain.agents.middleware.AgentMiddleware.state_schema) 或中间件定义 |
| [模型](#model)                             | 通过中间件动态选择，不支持预绑定模型                                                                                                                                                 |
| [工具](#tools)                             | 工具错误处理移至具有 `wrap_tool_call` 的中间件                                                                                                                                   |
| [结构化输出](#structured-output)              | 移除了提示输出，使用 `ToolStrategy`/`ProviderStrategy`                                                                                                                       |
| [流式节点名称重命名](#streaming-node-name-rename) | 节点名称从 `"agent"` 更改为 `"model"`                                                                                                                                      |
| [运行时上下文](#runtime-context)               | 通过 `context` 参数进行依赖注入，而非 `config["configurable"]`                                                                                                                  |
| [命名空间](#simplified-package)              | 精简以专注于智能体构建模块，旧版代码移至 `langchain-classic`                                                                                                                           |

### 导入路径

智能体预构建的导入路径已从 `langgraph.prebuilt` 更改为 `langchain.agents`。
函数名称已从 [`create_react_agent`](https://reference.langchain.com/python/langchain-classic/agents/react/agent/create_react_agent) 更改为 [`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent)：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langgraph.prebuilt import create_react_agent # [!code --]
from langchain.agents import create_agent # [!code ++]
```

更多信息，请参阅 [智能体](/oss/python/langchain/agents)。

### 提示

#### 静态提示重命名

`prompt` 参数已重命名为 [`system_prompt`](https://reference.langchain.com/python/langchain/agents/#langchain.agents.create_agent\(system_prompt\))：

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.agents import create_agent

  agent = create_agent(
      model="claude-sonnet-4-6",
      tools=[check_weather],
      system_prompt="You are a helpful assistant"  # [!code highlight]
  )
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langgraph.prebuilt import create_react_agent

  agent = create_react_agent(
      model="claude-sonnet-4-6",
      tools=[check_weather],
      prompt="You are a helpful assistant"  # [!code highlight]
  )
  ```
</CodeGroup>

#### `SystemMessage` 转为字符串

如果在系统提示中使用 [`SystemMessage`](https://reference.langchain.com/python/langchain-core/messages/system/SystemMessage) 对象，请提取字符串内容：

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.agents import create_agent

  agent = create_agent(
      model="claude-sonnet-4-6",
      tools=[check_weather],
      system_prompt="You are a helpful assistant"  # [!code highlight]
  )
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.messages import SystemMessage
  from langgraph.prebuilt import create_react_agent

  agent = create_react_agent(
      model="claude-sonnet-4-6",
      tools=[check_weather],
      prompt=SystemMessage(content="You are a helpful assistant")  # [!code highlight]
  )
  ```
</CodeGroup>

#### 动态提示

动态提示是一种核心上下文工程模式——它们根据当前对话状态调整您告诉模型的内容。为此，请使用 [`@dynamic_prompt`](https://reference.langchain.com/python/langchain/agents/middleware/types/dynamic_prompt) 装饰器：

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from dataclasses import dataclass

  from langchain.agents import create_agent
  from langchain.agents.middleware import dynamic_prompt, ModelRequest
  from langgraph.runtime import Runtime


  @dataclass
  class Context:  # [!code highlight]
      user_role: str = "user"

  @dynamic_prompt  # [!code highlight]
  def dynamic_prompt(request: ModelRequest) -> str:  # [!code highlight]
      user_role = request.runtime.context.user_role
      base_prompt = "You are a helpful assistant."

      if user_role == "expert":
          prompt = (
              f"{base_prompt} Provide detailed technical responses."
          )
      elif user_role == "beginner":
          prompt = (
              f"{base_prompt} Explain concepts simply and avoid jargon."
          )
      else:
          prompt = base_prompt

      return prompt  # [!code highlight]

  agent = create_agent(
      model="gpt-5.4",
      tools=tools,
      middleware=[dynamic_prompt],  # [!code highlight]
      context_schema=Context
  )

  # 使用上下文
  agent.invoke(
      {"messages": [{"role": "user", "content": "Explain async programming"}]},
      context=Context(user_role="expert")
  )
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from dataclasses import dataclass

  from langgraph.prebuilt import create_react_agent, AgentState
  from langgraph.runtime import get_runtime

  @dataclass
  class Context:
      user_role: str

  def dynamic_prompt(state: AgentState) -> str:
      runtime = get_runtime(Context)  # [!code highlight]
      user_role = runtime.context.user_role
      base_prompt = "You are a helpful assistant."

      if user_role == "expert":
          return f"{base_prompt} Provide detailed technical responses."
      elif user_role == "beginner":
          return f"{base_prompt} Explain concepts simply and avoid jargon."
      return base_prompt

  agent = create_react_agent(
      model="gpt-5.4",
      tools=tools,
      prompt=dynamic_prompt,
      context_schema=Context
  )

  # 使用上下文
  agent.invoke(
      {"messages": [{"role": "user", "content": "Explain async programming"}]},
      context=Context(user_role="expert")
  )
  ```
</CodeGroup>

### 模型前钩子

模型前钩子现在通过具有 `before_model` 方法的中间件实现。
这种新模式更具扩展性——您可以定义多个中间件在调用模型之前运行，
在不同智能体之间重用常见模式。

常见用例包括：

* 总结对话历史
* 裁剪消息
* 输入防护栏，如 PII 脱敏

v1 现在内置了摘要中间件作为选项：

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.agents import create_agent
  from langchain.agents.middleware import SummarizationMiddleware

  agent = create_agent(
      model="claude-sonnet-4-6",
      tools=tools,
      middleware=[
          SummarizationMiddleware(  # [!code highlight]
              model="claude-sonnet-4-6",  # [!code highlight]
              trigger={"tokens": 1000}  # [!code highlight]
          )  # [!code highlight]
      ]  # [!code highlight]
  )
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langgraph.prebuilt import create_react_agent, AgentState

  def custom_summarization_function(state: AgentState):
      """消息摘要的自定义逻辑。"""
      ...

  agent = create_react_agent(
      model="claude-sonnet-4-6",
      tools=tools,
      pre_model_hook=custom_summarization_function
  )
  ```
</CodeGroup>

### 模型后钩子

模型后钩子现在通过具有 `after_model` 方法的中间件实现。
这种新模式更具扩展性——您可以定义多个中间件在调用模型之后运行，
在不同智能体之间重用常见模式。

常见用例包括：

* [人机协作](/oss/python/langchain/human-in-the-loop)
* 输出防护栏

v1 内置了用于工具调用的人机协作审批中间件：

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.agents import create_agent
  from langchain.agents.middleware import HumanInTheLoopMiddleware

  agent = create_agent(
      model="claude-sonnet-4-6",
      tools=[read_email, send_email],
      middleware=[
          HumanInTheLoopMiddleware(
              interrupt_on={
                  "send_email": {
                      "description": "Please review this email before sending",
                      "allowed_decisions": ["approve", "reject"]
                  }
              }
          )
      ]
  )
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langgraph.prebuilt import create_react_agent
  from langgraph.prebuilt import AgentState

  def custom_human_in_the_loop_hook(state: AgentState):
      """人机协作审批的自定义逻辑。"""
      ...

  agent = create_react_agent(
      model="claude-sonnet-4-6",
      tools=[read_email, send_email],
      post_model_hook=custom_human_in_the_loop_hook
  )
  ```
</CodeGroup>

### 自定义状态

自定义状态通过附加字段扩展默认智能体状态。您可以通过两种方式定义自定义状态：

1. **通过 [`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 上的 [`state_schema`](https://reference.langchain.com/python/langchain/middleware/#langchain.agents.middleware.AgentMiddleware.state_schema)** - 最适合工具中使用的状态
2. **通过中间件** - 最适合由特定中间件钩子和附加到该中间件的工具管理的状态

<Note>
  通过中间件定义自定义状态优于通过 [`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 上的 [`state_schema`](https://reference.langchain.com/python/langchain/middleware/#langchain.agents.middleware.AgentMiddleware.state_schema) 定义，因为它允许您将状态扩展在概念上限定在相关的中间件和工具范围内。

  `state_schema` 仍然在 `create_agent` 上支持以保持向后兼容性。
</Note>

#### 通过 `state_schema` 定义状态

当您的自定义状态需要被工具访问时，使用 [`state_schema`](https://reference.langchain.com/python/langchain/middleware/#langchain.agents.middleware.AgentMiddleware.state_schema) 参数：

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.tools import tool, ToolRuntime
  from langchain.agents import create_agent, AgentState  # [!code highlight]


  # 定义扩展 AgentState 的自定义状态
  class CustomState(AgentState):
      user_name: str

  @tool  # [!code highlight]
  def greet(
      runtime: ToolRuntime[None, CustomState]
  ) -> str:
      """用于按名称问候用户。"""
      user_name = runtime.state.get("user_name", "Unknown")  # [!code highlight]
      return f"Hello {user_name}!"

  agent = create_agent(  # [!code highlight]
      model="claude-sonnet-4-6",
      tools=[greet],
      state_schema=CustomState  # [!code highlight]
  )
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from typing import Annotated
  from langgraph.prebuilt import InjectedState, create_react_agent
  from langgraph.prebuilt.chat_agent_executor import AgentState

  class CustomState(AgentState):
      user_name: str

  def greet(
      state: Annotated[CustomState, InjectedState]
  ) -> str:
      """用于按名称问候用户。"""
      user_name = state["user_name"]
      return f"Hello {user_name}!"

  agent = create_react_agent(
      model="claude-sonnet-4-6",
      tools=[greet],
      state_schema=CustomState
  )
  ```
</CodeGroup>

#### 通过中间件定义状态

中间件也可以通过设置 [`state_schema`](https://reference.langchain.com/python/langchain/middleware/#langchain.agents.middleware.AgentMiddleware.state_schema) 属性来定义自定义状态。
这有助于将状态扩展在概念上限定在相关的中间件和工具范围内。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.agents.middleware import AgentState, AgentMiddleware
from typing_extensions import NotRequired
from typing import Any

class CustomState(AgentState):
    model_call_count: NotRequired[int]

class CallCounterMiddleware(AgentMiddleware[CustomState]):
    state_schema = CustomState  # [!code highlight]

    def before_model(self, state: CustomState, runtime) -> dict[str, Any] | None:
        count = state.get("model_call_count", 0)
        if count > 10:
            return {"jump_to": "end"}
        return None

    def after_model(self, state: CustomState, runtime) -> dict[str, Any] | None:
        return {"model_call_count": state.get("model_call_count", 0) + 1}

agent = create_agent(
    model="claude-sonnet-4-6",
    tools=[...],
    middleware=[CallCounterMiddleware()]  # [!code highlight]
)
```

有关通过中间件定义自定义状态的更多详细信息，请参阅[中间件文档](/oss/python/langchain/middleware#custom-state-schema)。

#### 状态类型限制

[`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 仅支持 `TypedDict` 作为状态模式。不再支持 Pydantic 模型和数据类。

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.agents import AgentState, create_agent

  # AgentState 是一个 TypedDict
  class CustomAgentState(AgentState):  # [!code highlight]
      user_id: str

  agent = create_agent(
      model="claude-sonnet-4-6",
      tools=tools,
      state_schema=CustomAgentState  # [!code highlight]
  )
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from typing_extensions import Annotated

  from pydantic import BaseModel
  from langgraph.graph import StateGraph
  from langgraph.graph.messages import add_messages
  from langchain.messages import AnyMessage


  class AgentState(BaseModel):  # [!code highlight]
      messages: Annotated[list[AnyMessage], add_messages]
      user_id: str

  agent = create_react_agent(
      model="claude-sonnet-4-6",
      tools=tools,
      state_schema=AgentState
  )
  ```
</CodeGroup>

只需继承 `langchain.agents.AgentState` 而不是 `BaseModel` 或使用 `dataclass` 装饰器。
如果需要执行验证，请在中间件钩子中处理。

### 模型

动态模型选择允许您根据运行时上下文（例如任务复杂性、成本约束或用户偏好）选择不同的模型。[`langgraph-prebuilt`](https://pypi.org/project/langgraph-prebuilt) v0.6 中发布的 [`create_react_agent`](https://reference.langchain.com/python/langchain-classic/agents/react/agent/create_react_agent) 支持通过传递给 `model` 参数的可调用对象进行动态模型和工具选择。

此功能已移植到 v1 的中间件接口中。

#### 动态模型选择

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.agents import create_agent
  from langchain.agents.middleware import (
      AgentMiddleware, ModelRequest
  )
  from langchain.agents.middleware.types import ModelResponse
  from langchain_openai import ChatOpenAI
  from typing import Callable

  basic_model = ChatOpenAI(model="gpt-5-nano")
  advanced_model = ChatOpenAI(model="gpt-5.4")

  class DynamicModelMiddleware(AgentMiddleware):

      def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse:
          if len(request.state.messages) > self.messages_threshold:
              model = advanced_model
          else:
              model = basic_model
          return handler(request.override(model=model))

      def __init__(self, messages_threshold: int) -> None:
          self.messages_threshold = messages_threshold

  agent = create_agent(
      model=basic_model,
      tools=tools,
      middleware=[DynamicModelMiddleware(messages_threshold=10)]
  )
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langgraph.prebuilt import create_react_agent, AgentState
  from langchain_openai import ChatOpenAI

  basic_model = ChatOpenAI(model="gpt-5-nano")
  advanced_model = ChatOpenAI(model="gpt-5.4")

  def select_model(state: AgentState) -> BaseChatModel:
      # 对于较长的对话使用更高级的模型
      if len(state.messages) > 10:
          return advanced_model
      return basic_model

  agent = create_react_agent(
      model=select_model,
      tools=tools,
  )
  ```
</CodeGroup>

#### 预绑定模型

为了更好地支持结构化输出，[`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 不再接受预绑定工具或配置的模型：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 不再支持
model_with_tools = ChatOpenAI().bind_tools([some_tool])
agent = create_agent(model_with_tools, tools=[])

# 改为使用
agent = create_agent("gpt-5.4-mini", tools=[some_tool])
```

<Note>
  如果*不*使用结构化输出，动态模型函数可以返回预绑定模型。
</Note>

### 工具

[`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 的 [`tools`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 参数接受以下列表：

* LangChain [`BaseTool`](https://reference.langchain.com/python/langchain-core/tools/base/BaseTool) 实例（使用 [`@tool`](https://reference.langchain.com/python/langchain-core/tools/convert/tool) 装饰的函数）
* 具有适当类型提示和文档字符串的可调用对象（函数）
* 表示内置提供商工具的 `dict`

该参数将不再接受 [`ToolNode`](https://reference.langchain.com/python/langgraph/agents/#langgraph.prebuilt.tool_node.ToolNode) 实例。

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.agents import create_agent

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

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langgraph.prebuilt import create_react_agent, ToolNode


  agent = create_react_agent(
      model="claude-sonnet-4-6",
      tools=ToolNode([check_weather, search_web]) # [!code highlight]
  )
  ```
</CodeGroup>

#### 处理工具错误

您现在可以通过实现 `wrap_tool_call` 方法的中间件来配置工具错误处理。

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.agents import create_agent
  from langchain.agents.middleware import wrap_tool_call
  from langchain.messages import ToolMessage


  @wrap_tool_call
  def handle_tool_errors(request, handler):
      """使用自定义消息处理工具执行错误。"""
      try:
          return handler(request)
      except Exception as e:
          # 仅处理由于无效输入导致的工具执行错误，
          # 这些输入通过了模式验证但在运行时失败（例如，无效的 SQL 语法）。
          # 不要处理：
          # - 网络故障（改用工具重试中间件）
          # - 不正确的工具实现错误（应向上冒泡）
          # - 模式不匹配错误（框架已自动处理）
          #
          # 向模型返回自定义错误消息
          return ToolMessage(
              content=f"Tool error: Please check your input and try again. ({str(e)})",
              tool_call_id=request.tool_call["id"]
          )

  agent = create_agent(
      model="claude-sonnet-4-6",
      tools=[check_weather, search_web],
      middleware=[handle_tool_errors]
  )
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langgraph.prebuilt import create_react_agent, ToolNode
  from langchain.messages import ToolMessage


  def handle_tool_error(error: Exception) -> str:
      """自定义错误处理函数。"""
      return f"Tool error: Please check your input and try again. ({str(error)})"

  agent = create_react_agent(
      model="claude-sonnet-4-6",
      tools=ToolNode(
          [check_weather, search_web],
          handle_tool_errors=handle_tool_error  # [!code highlight]
      )
  )
  ```
</CodeGroup>

### 结构化输出

#### 节点变化

结构化输出以前在与主智能体不同的节点中生成。现在情况已非如此。
我们在主循环中生成结构化输出，从而降低成本和延迟。

#### 工具和提供商策略

在 v1 中，有两种新的结构化输出策略：

* `ToolStrategy` 使用人工工具调用来生成结构化输出
* `ProviderStrategy` 使用提供商原生的结构化输出生成

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.agents import create_agent
  from langchain.agents.structured_output import ToolStrategy, ProviderStrategy
  from pydantic import BaseModel


  class OutputSchema(BaseModel):
      summary: str
      sentiment: str

  # 使用 ToolStrategy
  agent = create_agent(
      model="gpt-5.4-mini",
      tools=tools,
      # 显式使用工具策略
      response_format=ToolStrategy(OutputSchema)  # [!code highlight]
  )
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langgraph.prebuilt import create_react_agent
  from pydantic import BaseModel

  class OutputSchema(BaseModel):
      summary: str
      sentiment: str

  agent = create_react_agent(
      model="gpt-5.4-mini",
      tools=tools,
      # 默认使用工具策略，没有提供商策略选项
      response_format=OutputSchema  # [!code highlight]
  )

  # 或者

  agent = create_react_agent(
      model="gpt-5.4-mini",
      tools=tools,
      # 使用自定义提示指示模型生成输出模式
      response_format=("please generate ...", OutputSchema)  # [!code highlight]
  )
  ```
</CodeGroup>

#### 移除提示输出

**提示输出**不再通过 `response_format` 参数支持。与人工工具调用和提供商原生结构化输出等策略相比，提示输出尚未证明特别可靠。

### 流式节点名称重命名

从智能体流式传输事件时，节点名称已从 `"agent"` 更改为 `"model"`，以更好地反映节点的用途。

### 运行时上下文

当您调用智能体时，通常希望传递两种类型的数据：

* 在对话过程中变化的动态状态（例如消息历史记录）
* 在对话过程中不变的静态上下文（例如用户元数据）

在 v1 中，通过将 `context` 参数设置为 `invoke` 和 `stream` 来支持静态上下文。

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from dataclasses import dataclass

  from langchain.agents import create_agent


  @dataclass
  class Context:
      user_id: str
      session_id: str

  agent = create_agent(
      model=model,
      tools=tools,
      context_schema=Context  # [!code highlight]
  )

  result = agent.invoke(
      {"messages": [{"role": "user", "content": "Hello"}]},
      context=Context(user_id="123", session_id="abc")  # [!code highlight]
  )
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langgraph.prebuilt import create_react_agent


  agent = create_react_agent(model, tools)

  # 通过可配置项传递上下文
  result = agent.invoke(
      {"messages": [{"role": "user", "content": "Hello"}]},
      config={  # [!code highlight]
          "configurable": {  # [!code highlight]
              "user_id": "123",  # [!code highlight]
              "session_id": "abc"  # [!code highlight]
          }  # [!code highlight]
      }  # [!code highlight]
  )
  ```
</CodeGroup>

<Note>
  旧的 `config["configurable"]` 模式仍然可以向后兼容，但对于新应用程序或迁移到 v1 的应用程序，建议使用新的 `context` 参数。
</Note>

***

## 标准内容

在 v1 中，消息获得了与提供商无关的标准内容块。通过 [`message.content_blocks`](https://reference.langchain.com/python/langchain_core/language_models/#langchain_core.messages.BaseMessage.content_blocks) 访问它们，以获得跨提供商的一致、类型化的视图。现有的 [`message.content`](https://reference.langchain.com/python/langchain-core/messages/base/BaseMessage) 字段对于字符串或提供商原生结构保持不变。

### 变化内容

* 消息上新增 [`content_blocks`](https://reference.langchain.com/python/langchain-core/messages/base/BaseMessage) 属性，用于规范化内容
* 标准化块形状，记录在 [消息](/oss/python/langchain/messages#standard-content-blocks) 中
* 可选地通过 `LC_OUTPUT_VERSION=v1` 或 `output_version="v1"` 将标准块序列化到 `content` 中

### 读取标准化内容

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.chat_models import init_chat_model

  model = init_chat_model("gpt-5-nano")
  response = model.invoke("Explain AI")

  for block in response.content_blocks:
      if block["type"] == "reasoning":
          print(block.get("reasoning"))
      elif block["type"] == "text":
          print(block.get("text"))
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  # 提供商原生格式各不相同；您需要按提供商处理
  response = model.invoke("Explain AI")
  for item in response.content:
      if item.get("type") == "reasoning":
          ...  # OpenAI 风格的推理
      elif item.get("type") == "thinking":
          ...  # Anthropic 风格的思考
      elif item.get("type") == "text":
          ...  # 文本
  ```
</CodeGroup>

### 创建多模态消息

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.messages import HumanMessage

  message = HumanMessage(content_blocks=[
      {"type": "text", "text": "Describe this image."},
      {"type": "image", "url": "https://example.com/image.jpg"},
  ])
  res = model.invoke([message])
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.messages import HumanMessage

  message = HumanMessage(content=[
      # 提供商原生结构
      {"type": "text", "text": "Describe this image."},
      {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}},
  ])
  res = model.invoke([message])
  ```
</CodeGroup>

### 示例块形状

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 文本块
text_block = {
    "type": "text",
    "text": "Hello world",
}

# 图像块
image_block = {
    "type": "image",
    "url": "https://example.com/image.png",
    "mime_type": "image/png",
}
```

更多详细信息，请参阅内容块[参考](/oss/python/langchain/messages#content-block-reference)。

### 序列化标准内容

默认情况下，标准内容块**不会**序列化到 `content` 属性中。如果您需要在 `content` 属性中访问标准内容块（例如，向客户端发送消息时），您可以选择将其序列化到 `content` 中。

<CodeGroup>
  ```bash 环境变量 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  export LC_OUTPUT_VERSION=v1
  ```

  ```python 初始化参数 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.chat_models import init_chat_model

  model = init_chat_model(
      "gpt-5-nano",
      output_version="v1",
  )
  ```
</CodeGroup>

<Note>
  了解更多：[消息](/oss/python/langchain/messages#message-content)、[标准内容块](/oss/python/langchain/messages#standard-content-blocks) 和 [多模态](/oss/python/langchain/messages#multimodal)。
</Note>

***

## 简化的包

在 v1 中，`langchain` 包命名空间已大幅精简，专注于智能体的核心构建模块。精简后的包使得发现和使用核心功能变得更加容易。

### 命名空间

| 模块                                                                                    | 可用内容                                                                                                                                                                                                                       | 备注                      |
| ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| [`langchain.agents`](https://reference.langchain.com/python/langchain/agents)         | [`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent), [`AgentState`](https://reference.langchain.com/python/langchain/agents/middleware/types/AgentState)                        | 核心智能体创建功能               |
| [`langchain.messages`](https://reference.langchain.com/python/langchain/messages)     | 消息类型, [内容块](https://reference.langchain.com/python/langchain-core/messages/content/ContentBlock), [`trim_messages`](https://reference.langchain.com/python/langchain-core/messages/utils/trim_messages)                    | 从 `langchain-core` 重新导出 |
| [`langchain.tools`](https://reference.langchain.com/python/langchain/tools)           | [`@tool`](https://reference.langchain.com/python/langchain-core/tools/convert/tool), [`BaseTool`](https://reference.langchain.com/python/langchain-core/tools/base/BaseTool), 注入辅助工具                                       | 从 `langchain-core` 重新导出 |
| [`langchain.chat_models`](https://reference.langchain.com/python/langchain/models)    | [`init_chat_model`](https://reference.langchain.com/python/langchain/chat_models/base/init_chat_model), [`BaseChatModel`](https://reference.langchain.com/python/langchain-core/language_models/chat_models/BaseChatModel) | 统一的模型初始化                |
| [`langchain.embeddings`](https://reference.langchain.com/python/langchain/embeddings) | [`init_embeddings`](https://reference.langchain.com/python/langchain/embeddings/base/init_embeddings), [`Embeddings`](https://reference.langchain.com/python/langchain-core/embeddings/embeddings/Embeddings)              | 嵌入模型                    |

### `langchain-classic`

如果您之前使用了 `langchain` 包中的以下任何功能，您需要安装 [`langchain-classic`](https://pypi.org/project/langchain-classic/) 并更新您的导入：

* 旧版链（`LLMChain`、`ConversationChain` 等）
* 检索器（例如 `MultiQueryRetriever` 或之前 `langchain.retrievers` 模块中的任何内容）
* 索引 API
* Hub 模块（用于以编程方式管理提示）
* 嵌入模块（例如 `CacheBackedEmbeddings` 和社区嵌入）
* [`langchain-community`](https://pypi.org/project/langchain-community) 重新导出
* 其他已弃用的功能

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  # 链
  from langchain_classic.chains import LLMChain

  # 检索器
  from langchain_classic.retrievers import ...

  # 索引
  from langchain_classic.indexes import ...

  # Hub
  from langchain_classic import hub
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  # 链
  from langchain_classic.chains import LLMChain

  # 检索器
  from langchain.retrievers import ...

  # 索引
  from langchain.indexes import ...

  # Hub
  from langchain import hub
  ```
</CodeGroup>

**安装**：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
uv pip install langchain-classic
```

***

## 破坏性变更

### 放弃 Python 3.9 支持

所有 LangChain 包现在需要 **Python 3.10 或更高版本**。Python 3.9 将于 2025 年 10 月[停止支持](https://devguide.python.org/versions/)。

### 更新聊天模型的返回类型

聊天模型调用的返回类型签名已从 [`BaseMessage`](https://reference.langchain.com/python/langchain-core/messages/base/BaseMessage) 修正为 [`AIMessage`](https://reference.langchain.com/python/langchain-core/messages/ai/AIMessage)。实现 [`bind_tools`](https://reference.langchain.com/python/langchain-core/language_models/chat_models/BaseChatModel/bind_tools) 的自定义聊天模型应更新其返回签名：

<CodeGroup>
  ```python v1 (new) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  def bind_tools(
          ...
      ) -> Runnable[LanguageModelInput, AIMessage]:
  ```

  ```python v0 (old) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  def bind_tools(
          ...
      ) -> Runnable[LanguageModelInput, BaseMessage]:
  ```
</CodeGroup>

### OpenAI 响应 API 的默认消息格式

与 Responses API 交互时，`langchain-openai` 现在默认将响应项存储在消息 `content` 中。要恢复之前的行为，请将 `LC_OUTPUT_VERSION` 环境变量设置为 `v0`，或在实例化 [`ChatOpenAI`](https://reference.langchain.com/python/langchain-openai/chat_models/base/ChatOpenAI) 时指定 `output_version="v0"`。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 使用 output_version 标志强制执行之前的行为
model = ChatOpenAI(model="gpt-5.4-mini", output_version="v0")
```

### `langchain-anthropic` 中的默认 `max_tokens`

`langchain-anthropic` 中的 `max_tokens` 参数现在根据所选模型默认为更高的值，而不是之前的默认值 `1024`。如果您依赖旧的默认值，请显式设置 `max_tokens=1024`。

### 旧版代码移至 `langchain-classic`

标准接口和智能体焦点之外的现有功能已移至 [`langchain-classic`](https://pypi.org/project/langchain-classic) 包。有关核心 `langchain` 包中可用内容以及移至 `langchain-classic` 的内容的详细信息，请参阅[简化的命名空间](#simplified-package)部分。

### 移除已弃用的 API

已经弃用并计划在 1.0 中删除的方法、函数和其他对象已被删除。请查看之前版本的[弃用通知](https://python.langchain.com/docs/versions/migrating_chains)以获取替代 API。

### text 属性

在消息对象上使用 `.text()` 方法应去掉括号，因为它现在是一个属性：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 属性访问
text = response.text

# 已弃用的方法调用
text = response.text()
```

现有的使用模式（即 `.text()`）将继续有效，但现在会发出警告。方法形式将在 v2 中移除。

### 从 `AIMessage` 中移除 `example` 参数

`example` 参数已从 [`AIMessage`](https://reference.langchain.com/python/langchain-core/messages/ai/AIMessage) 对象中移除。我们建议根据需要迁移到使用 `additional_kwargs` 传递额外元数据。

## 次要变更

* `AIMessageChunk` 对象现在包含一个 `chunk_position` 属性，位置为 `'last'` 以指示流中的最后一个块。这允许更清晰地处理流式消息。如果块不是最后一个，`chunk_position` 将为 `None`。
* `LanguageModelOutputVar` 现在类型为 [`AIMessage`](https://reference.langchain.com/python/langchain-core/messages/ai/AIMessage) 而不是 [`BaseMessage`](https://reference.langchain.com/python/langchain-core/messages/base/BaseMessage)。
* 合并消息块（`AIMessageChunk.add`）的逻辑已更新，对合并块的最终 id 具有更复杂的选择处理。它优先考虑提供商分配的 ID 而不是 LangChain 生成的 ID。
* 我们现在默认使用 `utf-8` 编码打开文件。
* 标准测试现在使用多模态内容块。

## 归档文档

旧文档已归档以供参考：

* [v0.3 文档内容](https://github.com/langchain-ai/langchain/tree/v0.3/docs/docs)
* [v0.3 API 参考](https://reference.langchain.com/v0.3/python/)

***

<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/python/migrate/langchain-v1.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
