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

# Langchain v1

title: LangChain v1 迁移指南
sidebarTitle: LangChain v1
--------------------------

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

## 简化的包

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

### 命名空间

| 模块                                                                                    | 可用内容                                                                                                                                                                                                                       | 备注                      |
| ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| [`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-4.1",
      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-4.1",
      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": "请在发送前审查此邮件",
                      "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. **通过 [`state_schema`](https://reference.langchain.com/python/langchain/middleware/#langchain.agents.middleware.AgentMiddleware.state_schema) 上的 [`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent)** - 最适合在工具中使用的状态
2. **通过中间件** - 最适合由特定中间件钩子和附加到该中间件的工具管理的状态

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

  `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` 装饰即可。
如果您需要执行验证，请在中间件钩子中处理。

### 模型

动态模型选择允许您根据运行时上下文（例如任务复杂性、成本约束或用户偏好）选择不同的模型。[`create_react_agent`](https://reference.langchain.com/python/langchain-classic/agents/react/agent/create_react_agent) 在 [`langgraph-prebuilt`](https://pypi.org/project/langgraph-prebuilt) v0.6 中发布，支持通过传递给 `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")

  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")

  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-4.1-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"工具错误：请检查您的输入并重试。({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"工具错误：请检查您的输入并重试。({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-4.1-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-4.1-mini",
      tools=tools,
      # 默认使用工具策略，无提供者策略选项
      response_format=OutputSchema  # [!code highlight]
  )

  # 或者

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

#### 移除提示式输出

**提示式输出**不再通过 `response_format` 参数支持。与人工工具调用和提供者原生结构化输出等策略相比，提示式输出已被证明不太可靠。

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

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

### 运行时上下文

当您调用代理时，通常您需要传递两种类型的数据：

* 在整个对话过程中变化的动态状态（例如，消息历史）
* 在对话期间不会变化的静态上下文（例如，用户元数据）

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

<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) 中
* 可选地将标准块序列化为 `content`，通过 `LC_OUTPUT_VERSION=v1` 或 `output_version="v1"`

### 读取标准化内容

<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 Environment variable theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  export LC_OUTPUT_VERSION=v1
  ```

  ```python Initialization parameter 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>

***

## 简化的包

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

### 命名空间

| 模块                                                                                    | 可用内容                                                                                                                                                                                                                       | 备注                      |
| ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| [`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 Responses 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-4.1-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="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\python\migrate\langchain-v1.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
