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

# LangChain v1 迁移指南

> description="将代码库迁移到 LangChain v1." icon="arrow-right" actions={["copy"]} 将此代码库迁移到 LangChain v1（需要 langchain>=1.0.0、langchain-core>=1.0.0 和 Python 3.10+）。

将代码库迁移到 LangChain v1.

将此代码库迁移到 LangChain v1（需要 `langchain>=1.0.0`、`langchain-core>=1.0.0` 和 Python 3.10+）。

关键变更：

1. **包命名空间缩减**： `langchain` 包专注于智能体、消息、工具、对话模型和嵌入。遗留链、检索器、索引、Hub、嵌入辅助类（如 `CacheBackedEmbeddings`）以及社区重导出内容已迁移至 `langchain-classic`。安装 `langchain-classic` 并更新相关导入为 `langchain_classic.*`。直接安装提供者包（例如 `langchain-openai`）而非依赖 `langchain` 对社区集成的重导出。

2. **`create_react_agent` → `create_agent`**：用 `from langchain.agents import create_agent` 替换 `from langgraph.prebuilt import create_react_agent`。将 `prompt=` 重命名为 `system_prompt=`。通过 `agent.invoke({"messages": [...]})` / `agent.stream(...)` 调用。优先使用 `langchain.agents.AgentState` 而非遗留的 `langgraph.prebuilt` 智能体状态辅助函数。

3. **钩子转为中间件**：用 `create_agent` 中间件（`before_model`、`after_model`、`@wrap_model_call`、`@wrap_tool_call`）替代 `pre_model_hook=`、`post_model_hook=`、`state_modifier=` 的自定义。人工介入工具审批时，使用 `HumanInTheLoopMiddleware(interrupt_on={...})`（来自 `langchain.agents.middleware`）。

4. **结构化输出**：保留 `response_format=`，但使用 `langchain.agents.structured_output` 的 `ToolStrategy` / `ProviderStrategy`。 `response_format=("please generate ...", Schema)` 类提示输出形式已移除。

5. **流式节点名称**：过滤或匹配流式事件时，将 `"agent"` 更新为 `"model"`。

6. **运行时上下文**：通过 `invoke` / `stream`（以及 `create_agent` 上的 `context_schema=`）的 `context=` 参数传递静态上下文，而非仅 `config["configurable"]`。

7. **标准内容块**：优先使用 `message.content_blocks` 进行提供者无关内容。现有 `message.content` 仍有效。

搜索代码库中的 `create_react_agent`、`pre_model_hook`、`post_model_hook`、`state_modifier`、来自 `langgraph.prebuilt` 的导入，以及 `langchain` 模块（如 `langchain.chains`、`langchain.retrievers`、`langchain.indexes`、`langchain.hub`），应用必要变更。标记无法自动迁移的内容。

本指南概述了 LangChain v1 与先前版本的主要差异。[LangChain v1](https://langchain-docs-zh.mintlify.site/langchain/oss/python/releases/langchain-v1.md)

## 简化版包

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

### 命名空间

| 模块 | 提供的功能 | 备注 |
| - | - | - |
| @\[`langchain.agents`] | @\[`create_agent`], @\[`AgentState`] | 智能体创建的核心功能 |
| @\[`langchain.messages`] | 消息类型, @\[content blocks]\[ContentBlock], @\[`trim_messages`] | 从 `langchain-core` 重导出 |
| @\[`langchain.tools`] | @\[`@tool`], @\[`BaseTool`], 注入辅助工具 | 从 `langchain-core` 重导出 |
| @\[`langchain.chat_models`] | @\[`init_chat_model`], @\[`BaseChatModel`] | 统一模型初始化 |
| @\[`langchain.embeddings`] | @\[`init_embeddings`], @\[`Embeddings`] | 嵌入模型 |

### `langchain-classic`

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

* 遗留链（`LLMChain`、`ConversationChain` 等）
* 检索器（例如 `MultiQueryRetriever` 或 `langchain.retrievers` 模块的任何内容）
* 索引 API
* 中心化模块（用于程序化管理提示词）
* 嵌入模块（例如 `CacheBackedEmbeddings` 和社区嵌入）
* [`langchain-community`](https://pypi.org/project/langchain-community) 重导出
* 其他已弃用功能

```python v1 (new) theme={null}
# Chains
from langchain_classic.chains import LLMChain

# Retrievers
from langchain_classic.retrievers import ...

# Indexing
from langchain_classic.indexes import ...

# Hub
from langchain_classic import hub
```

```python v0 (old) theme={null}
# Chains
from langchain_classic.chains import LLMChain

# Retrievers
from langchain.retrievers import ...

# Indexing
from langchain.indexes import ...

# Hub
from langchain import hub
```

安装方式：

```bash pip theme={null}
pip install langchain-classic
```

```bash uv theme={null}
uv add langchain-classic
```

***

## 迁移到 `create_agent`

在版本 v1.0 之前，我们推荐使用 @\[`langgraph.prebuilt.create_react_agent`]\[create\_react\_agent] 来构建智能体。现在我们推荐您使用 @\[`langchain.agents.create_agent`]\[create\_agent] 来构建智能体。

下表概述了从 @\[`create_react_agent`] 到 @\[`create_agent`] 的功能变更：

| 部件 | TL;DR - 变更内容 |
| - | - |
| [Import path](#导入路径) | 包从 `langgraph.prebuilt` 移动到 `langchain.agents` |
| [Prompts](#提示词) | 参数重命名为 @\[`system_prompt`]，动态提示使用中间件 |
| [Pre-model hook](#模型前钩子) | 已被 `before_model` 方法的中间件替代 |
| [Post-model hook](#模型后钩子) | 已被 `after_model` 方法的中间件替代 |
| [Custom state](#自定义状态) | 仅限 `TypedDict`，可通过 @\[`state_schema`] 或中间件定义 |
| [Model](#模型) | 通过中间件动态选择，不支持预绑定模型 |
| [Tools](#工具) | 工具错误处理移至中间件，使用 `wrap_tool_call` |
| [Structured output](#结构化输出) | 移除了提示式输出，改用 `ToolStrategy`/`ProviderStrategy` |
| [Streaming node name](#流式节点名称重命名) | 节点名称从 `"agent"` 更新为 `"model"` |
| [Runtime context](#运行时上下文) | 通过 `context` 参数注入依赖，替代 `config["configurable"]` |
| [Namespace](#简化版包) | 精简为聚焦智能体构建模块，遗留代码移至 `langchain-classic` |

### 导入路径

智能体预构建的导入路径已从 `langgraph.prebuilt` 更新为 `langchain.agents`。
函数名称已从 @\[`create_react_agent`] 更新为 @\[`create_agent`]：

```python theme={null}
from langgraph.prebuilt import create_react_agent # [!code --]
from langchain.agents import create_agent # [!code ++]
```

对于更多信息，请参考 [智能体](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/agents.md)。

### 提示词

#### 静态提示重命名

`prompt` 参数已重命名为 @\[`system_prompt`]：

```python v1 (new) theme={null}
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={null}
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]
)
```

#### `SystemMessage` 到字符串

若在系统提示中使用 @\[`SystemMessage`] 对象，需提取字符串内容：

```python v1 (new) theme={null}
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={null}
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]
)
```

#### 动态提示

动态提示是核心上下文工程模式——根据当前对话状态调整模型输入。使用 @\[`@dynamic_prompt`] 装饰器实现：

```python v1 (new) theme={null}
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.5",
    tools=tools,
    middleware=[dynamic_prompt],  # [!code highlight]
    context_schema=Context
)

# Use with context
agent.invoke(
    {"messages": [{"role": "user", "content": "Explain async programming"}]},
    context=Context(user_role="expert")
)
```

```python v0 (old) theme={null}
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.5",
    tools=tools,
    prompt=dynamic_prompt,
    context_schema=Context
)

# Use with context
agent.invoke(
    {"messages": [{"role": "user", "content": "Explain async programming"}]},
    context=Context(user_role="expert")
)
```

### 模型前钩子

预模型钩子现通过 `before_model` 方法实现为中间件。
此新模式更具扩展性——可定义多个中间件在模型调用前运行，复用不同智能体的通用模式。

常见用例包括：

* 会话历史摘要
* 消息截断
* 输入 guardrails（如隐私信息脱敏）

v1 内置了摘要中间件选项：

```python v1 (new) theme={null}
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={null}
from langgraph.prebuilt import create_react_agent, AgentState

def custom_summarization_function(state: AgentState):
    """Custom logic for message summarization."""
    ...

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

### 模型后钩子

模型后置钩子现以 `after_model` 方法实现为中间件。
这种新模式更具可扩展性——你可以定义多个中间件在模型调用后执行，
跨不同智能体复用常见模式。

常见的用例包括：

* [人在回路](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/human-in-the-loop.md)
* 输出护栏

v1 包含一个内置的中间件，用于人类在环中的工具调用审批：

```python v1 (new) theme={null}
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={null}
from langgraph.prebuilt import create_react_agent
from langgraph.prebuilt import AgentState

def custom_human_in_the_loop_hook(state: AgentState):
    """Custom logic for human in the loop approval."""
    ...

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

### 自定义状态

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

1. **通过 @\[`state_schema`] 在 @\[`create_agent`] 上** - 最适合用于工具中的状态
2. **通过中间件** - 最适合用于由特定中间件钩子和附加到该中间件的工具管理的状态

> [!NOTE]
>
> 通过中间件定义自定义状态比通过 @\[`state_schema`] 在 @\[`create_agent`] 上定义状态更受推荐，因为它允许你将状态扩展在概念上限制在相关的中间件和工具中。
>
> `state_schema` 仍然在 `create_agent` 上支持以保持向后兼容性。

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

当您的自定义状态需要被工具访问时，使用 @\[`state_schema`] 参数：

```python v1 (new) theme={null}
from langchain.tools import tool, ToolRuntime
from langchain.agents import create_agent, AgentState  # [!code highlight]


# Define custom state extending AgentState
class CustomState(AgentState):
    user_name: str

@tool  # [!code highlight]
def greet(
    runtime: ToolRuntime[None, CustomState]
) -> str:
    """Use this to greet the user by name."""
    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={null}
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:
    """Use this to greet the user by name."""
    user_name = state["user_name"]
    return f"Hello {user_name}!"

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

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

中间件也可以通过设置 @\[`state_schema`] 属性来定义自定义状态。
这有助于将状态扩展在概念上限定在相关的中间件和工具范围内。

```python theme={null}
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]
)
```

请参阅 [中间件文档](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/middleware/custom.md#自定义状态模式)，以获取更多关于通过中间件定义自定义状态的详细信息。

#### 状态类型限制

@\[`create_agent`] only supports `TypedDict` for state schemas. Pydantic models and dataclasses are no longer supported.

```python v1 (new) theme={null}
from langchain.agents import AgentState, create_agent

# AgentState is a 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={null}
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
)
```

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

### 模型

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

此功能已迁移到 v1 版本的中介接口中。

#### 动态模型选择

```python v1 (new) theme={null}
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.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={null}
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.5")

def select_model(state: AgentState) -> BaseChatModel:
    # use a more advanced model for longer conversations
    if len(state.messages) > 10:
        return advanced_model
    return basic_model

agent = create_react_agent(
    model=select_model,
    tools=tools,
)
```

#### 预绑定模型

为了更好地支持结构化输出，@\[`create_agent`] 不再接受带有工具或配置的预绑定模型：

```python theme={null}
# No longer supported
model_with_tools = ChatOpenAI().bind_tools([some_tool])
agent = create_agent(model_with_tools, tools=[])

# Use instead
agent = create_agent("gpt-5.4-mini", tools=[some_tool])
```

> [!NOTE]
>
> 动态模型函数如果*不*使用结构化输出，可以返回预绑定的模型。

### 工具

@\[`tools`]\[create\_agent(tools)] 参数用于 @\[`create_agent`]，它接受一个列表：

* LangChain @\[`BaseTool`] 实例（使用 @\[`@tool`] 装饰的函数）
* 带有正确类型提示和文档字符串的可调用对象（函数）
* `dict`，表示内置提供者工具

该参数将不再接受 @\[`ToolNode`] 实例。

```python v1 (new) theme={null}
from langchain.agents import create_agent

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

```python v0 (old) theme={null}
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]
)
```

#### 处理工具错误

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

```python v1 (new) theme={null}
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):
    """Handle tool execution errors with custom messages."""
    try:
        return handler(request)
    except Exception as e:
        # Only handle errors that occur during tool execution due to invalid inputs
        # that pass schema validation but fail at runtime (e.g., invalid SQL syntax).
        # Do NOT handle:
        # - Network failures (use tool retry middleware instead)
        # - Incorrect tool implementation errors (should bubble up)
        # - Schema mismatch errors (already auto-handled by the framework)
        #
        # Return a custom error message to the model
        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={null}
from langgraph.prebuilt import create_react_agent, ToolNode
from langchain.messages import ToolMessage


def handle_tool_error(error: Exception) -> str:
    """Custom error handler function."""
    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]
    )
)
```

### 结构化输出

#### 节点变更

结构化输出原本是在主智能体之外的独立节点中生成的。现在情况已不再如此。
我们在主循环中生成结构化输出，从而降低成本和延迟。

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

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

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

```python v1 (new) theme={null}
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

# Using ToolStrategy
agent = create_agent(
    model="gpt-5.4-mini",
    tools=tools,
    # explicitly using tool strategy
    response_format=ToolStrategy(OutputSchema)  # [!code highlight]
)
```

```python v0 (old) theme={null}
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,
    # using tool strategy by default with no option for provider strategy
    response_format=OutputSchema  # [!code highlight]
)

# OR

agent = create_react_agent(
    model="gpt-5.4-mini",
    tools=tools,
    # using a custom prompt to instruct the model to generate the output schema
    response_format=("please generate ...", OutputSchema)  # [!code highlight]
)
```

#### 提示词输出已移除

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

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

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

### 运行时上下文

当你调用一个智能体时，通常需要传递两种类型的数据：

* 在对话过程中会变化的动态状态（例如：消息历史）
* 在对话过程中不会变化的静态上下文（例如：用户元数据）
  在 v1 版本中，静态上下文通过将 `context` 参数设置为 `invoke` 和 `stream` 来支持。

```python v1 (new) theme={null}
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={null}
from langgraph.prebuilt import create_react_agent


agent = create_react_agent(model, tools)

# Pass context via configurable
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]
)
```

> [!NOTE]
>
> 旧的 `config["configurable"]` 模式仍然适用于向后兼容，但建议新应用或迁移到 v1 的应用使用新的 `context` 参数。

***

## 标准内容

在 v1 版本中，消息获得了与提供者无关的标准内容块。通过 @\[`message.content_blocks`]\[content\_blocks] 访问它们，以在各个提供者之间提供一致的、类型化的视图。现有的 @\[`message.content`]\[BaseMessage(content\_blocks)] 字段保持不变，用于字符串或提供者本地的结构。

### 变更内容

* 新增 @\[`content_blocks`]\[BaseMessage(content\_blocks)] 属性在消息中用于标准化内容
* 标准化块形状，文档记录在 [Messages](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#标准内容块)
* 可选地将标准块序列化到 `content` 通过 `LC_OUTPUT_VERSION=v1` 或 `output_version="v1"`

### 读取标准化内容

```python v1 (new) theme={null}
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={null}
# Provider-native formats vary; you needed per-provider handling
response = model.invoke("Explain AI")
for item in response.content:
    if item.get("type") == "reasoning":
        ...  # OpenAI-style reasoning
    elif item.get("type") == "thinking":
        ...  # Anthropic-style thinking
    elif item.get("type") == "text":
        ...  # Text
```

### 创建多模态消息

```python v1 (new) theme={null}
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={null}
from langchain.messages import HumanMessage

message = HumanMessage(content=[
    # Provider-native structure
    {"type": "text", "text": "Describe this image."},
    {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}},
])
res = model.invoke([message])
```

### 示例块形状

```python theme={null}
# Text block
text_block = {
    "type": "text",
    "text": "Hello world",
}

# Image block
image_block = {
    "type": "image",
    "url": "https://example.com/image.png",
    "mime_type": "image/png",
}
```

查看内容块 [参考](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#内容块参考) 以获取更多详细信息。

### 序列化标准内容

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

```bash Environment variable theme={null}
export LC_OUTPUT_VERSION=v1
```

```python Initialization parameter theme={null}
from langchain.chat_models import init_chat_model

model = init_chat_model(
    "gpt-5-nano",
    output_version="v1",
)
```

> [!NOTE]
>
> Learn more: [Messages](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#消息内容), [Standard content blocks](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#标准内容块), and [Multimodal](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#多模态).

***

## 不兼容变更

### 已移除对 Python 3.9 的支持

所有 LangChain 包现在都需要 **Python 3.10 或更高版本**。Python 3.9 将在 2025 年 10 月达到 [结束生命周期](https://devguide.python.org/versions/)。

### 更新对话模型的返回类型

对话模型调用的返回类型签名已从 @\[`BaseMessage`] 修复为 @\[`AIMessage`]。实现 @\[`bind_tools`]\[BaseChatModel.bind\_tools] 的自定义对话模型应更新其返回签名：

```python v1 (new) theme={null}
def bind_tools(
        ...
    ) -> Runnable[LanguageModelInput, AIMessage]:
```

```python v0 (old) theme={null}
def bind_tools(
        ...
    ) -> Runnable[LanguageModelInput, BaseMessage]:
```

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

当与响应 API 交互时，`langchain-openai` 现在默认将响应项存储在消息 `content` 中。如需恢复旧行为，可将 `LC_OUTPUT_VERSION` 环境变量设为 `v0`，或在实例化 @\[`ChatOpenAI`] 时指定 `output_version="v0"`。

```python theme={null}
# Enforce previous behavior with output_version flag
model = ChatOpenAI(model="gpt-5.4-mini", output_version="v0")
```

### 默认 `max_tokens` 在 `langchain-anthropic`

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

### 遗留代码迁移至 `langchain-classic`

标准接口和智能体之外的现有功能已迁移至 [`langchain-classic`](https://pypi.org/project/langchain-classic) 包。详见 [简化命名空间](#简化版包) 节了解核心 `langchain` 包的内容及迁移至 `langchain-classic` 包的部分。

### 已删除弃用 API

1.0 版本中已标记为废弃并计划删除的方法、函数和其他对象已被移除。

### 文本属性

消息对象上使用 `.text()` 方法的模式应移除括号，现已成为属性：

```python theme={null}
# Property access
text = response.text

# Deprecated method call
text = response.text()
```

现有使用模式（即 `.text()`）仍可正常工作但会触发警告。方法形式将在 v2 中移除。

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

@\[`AIMessage`] 对象已移除 `example` 参数。建议改用 `additional_kwargs` 传递额外元数据。

## 次要变更

* `AIMessageChunk` 对象新增 `chunk_position` 属性，位置 `'last'` 表示流式输出的最终片段。非最终片段时 `chunk_position` 将为 `None`。
* `LanguageModelOutputVar` 类型已从 @\[`BaseMessage`] 改为 @\[`AIMessage`]。
* `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/)

***

> 官方原文：[src/oss/python/migrate/langchain-v1.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/python/migrate/langchain-v1.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.