> ## 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 是一个专注、生产就绪的智能体构建基础框架。** 我们围绕三个核心改进精简了框架：

<CardGroup cols={1}>
  <Card title="create_agent" icon="robot" href="#create_agent" arrow>
    LangChain 中构建智能体的新标准，取代了
    `langgraph.prebuilt.create_react_agent`。
  </Card>

  <Card title="标准内容块" icon="cube" href="#standard-content-blocks" arrow>
    新的 `content_blocks` 属性，提供跨提供商的现代 LLM 功能统一访问方式。
  </Card>

  <Card title="简化命名空间" icon="sitemap" href="#simplified-package" arrow>
    `langchain` 命名空间已精简，专注于智能体的核心构建模块，遗留功能已移至
    `langchain-classic`。
  </Card>
</CardGroup>

要升级，请运行：

<CodeGroup>
  `bash pip pip install -U langchain ` `bash uv uv add langchain `
</CodeGroup>

完整的变更列表，请参阅[迁移指南](/oss/python/migrate/langchain-v1)。

## `create_agent`

[`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 是 LangChain 1.0 中构建智能体的标准方式。它提供了比 [`langgraph.prebuilt.create_react_agent`](https://reference.langchain.com/python/langchain-classic/agents/react/agent/create_react_agent) 更简单的接口，同时通过使用[中间件](#middleware)提供了更大的定制潜力。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.agents import create_agent

agent = create_agent(
    model="claude-sonnet-4-6",
    tools=[search_web, analyze_data, send_email],
    system_prompt="You are a helpful research assistant."
)

result = agent.invoke({
    "messages": [
        {"role": "user", "content": "Research AI safety trends"}
    ]
})
```

在底层，[`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 基于基本的智能体循环构建——调用模型，让其选择要执行的工具，然后在不再调用工具时结束：

<div style={{ display: "flex", justifyContent: "center" }}>
  <img src="https://mintcdn.com/other-405835d4/3NQVGWwcrOYcKZbP/oss/images/core_agent_loop.png?fit=max&auto=format&n=3NQVGWwcrOYcKZbP&q=85&s=e80aadacf0a151589aaa821313e0916c" alt="核心智能体循环图" className="rounded-lg" width="300" height="268" data-path="oss/images/core_agent_loop.png" />
</div>

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

### 中间件

中间件是 [`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 的核心特性。它提供了一个高度可定制的入口点，提升了你能构建的智能体的上限。

优秀的智能体需要[上下文工程](/oss/python/langchain/context-engineering)：在正确的时间将正确的信息提供给模型。中间件通过可组合的抽象，帮助你控制动态提示、对话摘要、选择性工具访问、状态管理和防护栏。

#### 预构建中间件

LangChain 提供了一些用于常见模式的[预构建中间件](/oss/python/langchain/middleware#built-in-middleware)，包括：

* [`PIIMiddleware`](https://reference.langchain.com/python/langchain/agents/middleware/pii/PIIMiddleware)：在发送给模型之前编辑敏感信息
* [`SummarizationMiddleware`](https://reference.langchain.com/python/langchain/agents/middleware/summarization/SummarizationMiddleware)：当对话历史过长时进行压缩
* [`HumanInTheLoopMiddleware`](https://reference.langchain.com/python/langchain/agents/middleware/human_in_the_loop/HumanInTheLoopMiddleware)：对敏感工具调用要求批准

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.agents import create_agent
from langchain.agents.middleware import (
    PIIMiddleware,
    SummarizationMiddleware,
    HumanInTheLoopMiddleware
)


agent = create_agent(
    model="claude-sonnet-4-6",
    tools=[read_email, send_email],
    middleware=[
        PIIMiddleware("email", strategy="redact", apply_to_input=True),
        PIIMiddleware(
            "phone_number",
            detector=(
                r"(?:\+?\d{1,3}[\s.-]?)?"
                r"(?:\(?\d{2,4}\)?[\s.-]?)?"
                r"\d{3,4}[\s.-]?\d{4}"
			),
			strategy="block"
        ),
        SummarizationMiddleware(
            model="claude-sonnet-4-6",
            trigger={"tokens": 500}
        ),
        HumanInTheLoopMiddleware(
            interrupt_on={
                "send_email": {
                    "allowed_decisions": ["approve", "edit", "reject"]
                }
            }
        ),
    ]
)
```

#### 自定义中间件

你也可以构建自定义中间件以满足你的需求。中间件在智能体执行的每个步骤都暴露了钩子：

<div style={{ display: "flex", justifyContent: "center" }}>
  <img src="https://mintcdn.com/other-405835d4/3NQVGWwcrOYcKZbP/oss/images/middleware_final.png?fit=max&auto=format&n=3NQVGWwcrOYcKZbP&q=85&s=4c4db62fcf650935ce6703625c5aa548" alt="中间件流程图" className="rounded-lg" width="500" height="560" data-path="oss/images/middleware_final.png" />
</div>

通过在 [`AgentMiddleware`](https://reference.langchain.com/python/langchain/agents/middleware/types/AgentMiddleware) 类的子类上实现以下任一钩子来构建自定义中间件：

| 钩子                | 运行时机        | 用例         |
| ----------------- | ----------- | ---------- |
| `before_agent`    | 调用智能体之前     | 加载记忆、验证输入  |
| `before_model`    | 每次 LLM 调用之前 | 更新提示、修剪消息  |
| `wrap_model_call` | 围绕每次 LLM 调用 | 拦截并修改请求/响应 |
| `wrap_tool_call`  | 围绕每次工具调用    | 拦截并修改工具执行  |
| `after_model`     | 每次 LLM 响应之后 | 验证输出、应用防护栏 |
| `after_agent`     | 智能体完成后      | 保存结果、清理    |

自定义中间件示例：

```python expandable theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from dataclasses import dataclass
from typing import Callable

from langchain_openai import ChatOpenAI

from langchain.agents.middleware import (
    AgentMiddleware,
    ModelRequest
)
from langchain.agents.middleware.types import ModelResponse

@dataclass
class Context:
    user_expertise: str = "beginner"

class ExpertiseBasedToolMiddleware(AgentMiddleware):
    def wrap_model_call(
        self,
        request: ModelRequest,
        handler: Callable[[ModelRequest], ModelResponse]
    ) -> ModelResponse:
        user_level = request.runtime.context.user_expertise

        if user_level == "expert":
            # 更强大的模型
            model = ChatOpenAI(model="gpt-5.4")
            tools = [advanced_search, data_analysis]
        else:
            # 较弱的模型
            model = ChatOpenAI(model="gpt-5-nano")
            tools = [simple_search, basic_calculator]

        return handler(request.override(model=model, tools=tools))

agent = create_agent(
    model="claude-sonnet-4-6",
    tools=[
        simple_search,
        advanced_search,
        basic_calculator,
        data_analysis
    ],
    middleware=[ExpertiseBasedToolMiddleware()],
    context_schema=Context
)
```

更多信息，请参阅[完整的中间件指南](/oss/python/langchain/middleware)。

### 基于 LangGraph 构建

因为 [`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 是基于 [LangGraph](/oss/python/langgraph) 构建的，你自动获得了对长时间运行和可靠智能体的内置支持，通过：

<CardGroup cols={2}>
  <Card title="持久化" icon="database">
    对话通过内置检查点自动跨会话持久化
  </Card>

  <Card title="流式传输" icon="droplet">
    实时流式传输令牌、工具调用和推理轨迹
  </Card>

  <Card title="Human in the Loop" icon="hand-stop">
    在敏感操作前暂停智能体执行以供人类批准
  </Card>

  <Card title="时间旅行" icon="history">
    将对话倒回至任意点，并探索替代路径和提示
  </Card>
</CardGroup>

你无需学习 LangGraph 即可使用这些功能——它们开箱即用。

### 结构化输出

[`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 改进了结构化输出生成：

* **主循环集成**：结构化输出现在在主循环中生成，无需额外的 LLM 调用
* **结构化输出策略**：模型可以选择调用工具或使用提供商端的结构化输出生成
* **成本降低**：消除了额外 LLM 调用带来的额外开销

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.agents import create_agent
from langchain.agents.structured_output import ToolStrategy
from pydantic import BaseModel


class Weather(BaseModel):
    temperature: float
    condition: str

def weather_tool(city: str) -> str:
    """获取城市的天气。"""
    return f"it's sunny and 70 degrees in {city}"

agent = create_agent(
    "gpt-5.4-mini",
    tools=[weather_tool],
    response_format=ToolStrategy(Weather)
)

result = agent.invoke({
    "messages": [{"role": "user", "content": "What's the weather in SF?"}]
})

print(repr(result["structured_response"]))
# 结果为 `Weather(temperature=70.0, condition='sunny')`
```

**错误处理**：通过 `ToolStrategy` 的 `handle_errors` 参数控制错误处理：

* **解析错误**：模型生成的数据与所需结构不匹配
* **多次工具调用**：模型为结构化输出模式生成 2 次以上的工具调用

***

## 标准内容块

<Note>
  内容块支持目前仅适用于以下集成：

  * [`langchain-anthropic`](https://pypi.org/project/langchain-anthropic/)
  * [`langchain-aws`](https://pypi.org/project/langchain-aws/)
  * [`langchain-openai`](https://pypi.org/project/langchain-openai/)
  * [`langchain-google-genai`](https://pypi.org/project/langchain-google-genai/)
  * [`langchain-ollama`](https://pypi.org/project/langchain-ollama/)

  对内容块的更广泛支持将逐步扩展到更多提供商。
</Note>

新的 [`content_blocks`](https://reference.langchain.com/python/langchain-core/messages/base/BaseMessage) 属性引入了一种标准的消息内容表示方式，可跨提供商工作：

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

model = ChatAnthropic(model="claude-sonnet-4-6")
response = model.invoke("What's the capital of France?")

# 统一访问内容块
for block in response.content_blocks:
    if block["type"] == "reasoning":
        print(f"模型推理: {block['reasoning']}")
    elif block["type"] == "text":
        print(f"响应: {block['text']}")
    elif block["type"] == "tool_call":
        print(f"工具调用: {block['name']}({block['args']})")
```

### 优势

* **提供商无关**：使用相同的 API 访问推理轨迹、引用、内置工具（网络搜索、代码解释器等）和其他功能，无论提供商如何
* **类型安全**：所有内容块类型都有完整的类型提示
* **向后兼容**：标准内容可以[延迟加载](/oss/python/langchain/messages#standard-content-blocks)，因此没有相关的破坏性变更

更多信息，请参阅我们的[内容块](/oss/python/langchain/messages#standard-content-blocks)指南。

***

## 简化包

LangChain v1 精简了 [`langchain`](https://pypi.org/project/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`](https://reference.langchain.com/python/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`](https://reference.langchain.com/python/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) | [`Embeddings`](https://reference.langchain.com/python/langchain-core/embeddings/embeddings/Embeddings), [`init_embeddings`](https://reference.langchain.com/python/langchain/embeddings/base/init_embeddings)              | 嵌入模型                                                                              |

其中大部分是从 `langchain-core` 重新导出的，以方便使用，这为你构建智能体提供了一个专注的 API 表面。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 智能体构建
from langchain.agents import create_agent

# 消息和内容
from langchain.messages import AIMessage, HumanMessage

# 工具
from langchain.tools import tool

# 模型初始化
from langchain.chat_models import init_chat_model
from langchain.embeddings import init_embeddings
```

### `langchain-classic`

遗留功能已移至 [`langchain-classic`](https://pypi.org/project/langchain-classic)，以保持核心包的精简和专注。

**`langchain-classic` 中包含的内容：**

* 遗留的链和链实现
* 检索器（例如 `MultiQueryRetriever` 或之前 `langchain.retrievers` 模块中的任何内容）
* 索引 API
* hub 模块（用于以编程方式管理提示）
* [`langchain-community`](https://pypi.org/project/langchain-community) 导出
* 其他已弃用的功能

如果你使用其中任何功能，请安装 [`langchain-classic`](https://pypi.org/project/langchain-classic)：

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

然后更新你的导入：

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

from langchain.chains import ...  # [!code --]
from langchain_classic.chains import ...  # [!code ++]

from langchain.retrievers import ...  # [!code --]
from langchain_classic.retrievers import ...  # [!code ++]

from langchain import hub  # [!code --]
from langchain_classic import hub  # [!code ++]
```

## 迁移指南

请参阅我们的[迁移指南](/oss/python/migrate/langchain-v1)以获取将代码更新到 LangChain v1 的帮助。

## 报告问题

请在 [GitHub](https://github.com/langchain-ai/langchain/issues) 上使用 `'v1'` [标签](https://github.com/langchain-ai/langchain/issues?q=state%3Aopen%20label%3Av1)报告在 1.0 中发现的任何问题。

## 附加资源

<CardGroup cols={3}>
  <Card title="LangChain 1.0" icon="rocket" href="https://blog.langchain.com/langchain-langchain-1-0-alpha-releases/">
    阅读公告
  </Card>

  <Card title="中间件指南" icon="puzzle" href="https://blog.langchain.com/agent-middleware/">
    深入了解中间件
  </Card>

  <Card title="智能体文档" icon="book" href="/oss/python/langchain/agents" arrow>
    完整的智能体文档
  </Card>

  <Card title="消息内容" icon="message" href="/oss/python/langchain/messages#message-content" arrow>
    新的内容块 API
  </Card>

  <Card title="迁移指南" icon="arrows-exchange" href="/oss/python/migrate/langchain-v1" arrow>
    如何迁移到 LangChain v1
  </Card>

  <Card title="GitHub" icon="brand-github" href="https://github.com/langchain-ai/langchain">
    报告问题或贡献
  </Card>
</CardGroup>

## 另请参阅

* [版本控制](/oss/python/versioning) – 理解版本号
* [发布策略](/oss/python/release-policy) – 详细的发布策略

***

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

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