本指南概述了 LangChain v1 与之前版本之间的主要变化。
精简的软件包
该 langchain 包命名空间在 v1 中已大幅精简,专注于代理的核心构建模块。精简后的包使核心功能的发现和使用更加容易。
命名空间
| 模块 | 可用功能 | 备注 |
|---|---|---|
langchain.agents | create_agent, AgentState | 核心代理创建功能 |
langchain.messages | 消息类型、content blocks、trim_messages | 从以下模块重新导出 langchain-core |
langchain.tools | @tool, BaseTool | 消息注入辅助函数 |
langchain.chat_models | init_chat_model, BaseChatModel | 统一模型初始化 |
langchain.embeddings | init_embeddings, Embeddings | 嵌入模型 |
langchain-classic
如果您之前在 langchain 包中使用了以下任何功能,您需要安装 langchain-classic 并更新您的导入:
- - 旧版链(
LLMChain,ConversationChain等) - - 检索器(例如
MultiQueryRetriever或之前langchain.retrievers模块中的任何功能) - - 索引 API
- - 中心模块(用于以编程方式管理提示词)
- - 嵌入模块(例如
CacheBackedEmbeddings和社区嵌入) - -
langchain-communityre-exports - - 其他已弃用的功能
# 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
# Chains
from langchain_classic.chains import LLMChain
# Retrievers
from langchain.retrievers import ...
# Indexing
from langchain.indexes import ...
# Hub
from langchain import hub
安装方式:
pip install langchain-classic
uv add langchain-classic
迁移到 create_agent
在 v1.0 之前,我们推荐使用 @[langgraph.prebuilt.create_react_agent][create_react_代理]来构建代理。现在,我们推荐您使用 @[langchain.agents.create_agent][create_代理]来构建代理。
下表概述了 create_react_agent to create_agent:
| 部分 | 摘要 - 变化内容 |
|---|---|
| 导入路径 | 包已从以下位置移动 langgraph.prebuilt to langchain.agents |
| 提示词 | 参数已重命名为 @[system_prompt,动态提示词使用中间件 |
| 预模型钩子 | 已替换为具有以下功能的中间件 before_model 方法的中间件 |
| 后模型钩子 | 已替换为具有以下功能的中间件 after_model 方法的中间件 |
| 自定义状态 | TypedDict ,可通过 state_schema 或中间件定义 |
| 模型 | 通过中间件动态选择,不支持预绑定模型 |
| 工具 | 工具错误处理已移至中间件 wrap_tool_call |
| 结构化输出 | 提示输出已移除,请使用 ToolStrategy/ProviderStrategy |
| 流式节点名称 | 节点名称已从更改 "agent" to "model" |
| 运行时上下文 | 通过进行依赖注入 context 参数替换 config["configurable"] |
| 命名空间 | 精简为专注于代理构建块,旧代码移至 langchain-classic |
导入路径
代理预构建的导入路径已从更改 langgraph.prebuilt to langchain.agents. 函数名称已从 create_react_agent to create_agent:
from langgraph.prebuilt import create_react_agent # [!code --]
from langchain.agents import create_agent # [!code ++]
更多信息,请参阅 代理.
提示词
静态提示词重命名
prompt 参数已重命名为 system_prompt):
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]
)
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 对象在系统提示词中,请提取字符串内容:
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]
)
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 装饰器:
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")
)
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 method. 这种新模式更具可扩展性——你可以在模型调用之前定义多个中间件运行, 在不同的代理中重复使用通用模式。
常见用例包括: * 对话历史摘要 * 修剪消息 * 输入护栏,如 PII 脱敏
v1 现在有内置的摘要中间件作为选项:
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]
)
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 method. 这种新模式更具可扩展性——你可以在模型调用之后定义多个中间件运行, 在不同的代理中重复使用通用模式。
常见用例包括: * 人机交互 * 输出护栏
v1 有内置的中间件用于工具调用的人机交互批准:
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"]
}
}
)
]
)
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
)
自定义状态
自定义状态使用额外的字段扩展默认代理状态。你可以通过两种方式定义自定义状态:
- **通过
state_schemaoncreate_agent** - 适用于工具中使用的状态 - **通过中间件** - 适用于由特定中间件钩子和附加到该中间件的工具管理的状态
通过以下方式定义状态 state_schema
使用 @[state_schema参数当您的自定义状态需要被工具访问时:
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]
)
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 属性来定义自定义状态。 这有助于将状态扩展概念性地限定在相关中间件和工具的范围内。
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]
)
请参阅 中间件文档 了解更多通过中间件定义自定义状态的详情。
状态类型限制
@[create_agent仅支持 TypedDict 用于状态模式。不再支持 Pydantic 模型和数据类。
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]
)
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. 如需执行验证,请在中间件钩子中处理。
模型
动态模型选择允许您根据运行时上下文(例如任务复杂性、成本约束或用户偏好)选择不同的模型。@create_react_agent在 v0.6 中发布 [langgraph-prebuilt 支持通过传递给 @[ model parameter.
的可调用对象实现动态模型和工具选择。此功能已在 v1 中移植到中间件接口。
动态模型选择
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)]
)
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不再接受带有工具或配置的预绑定模型:
# 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])
工具
tools 参数 @[create_agent接受以下列表:
- * LangChain
BaseTool实例(使用 @[ 装饰的函数)@tool]) - * 可调用对象(函数),具有适当的类型提示和文档字符串
- *
dict表示内置提供商的工具
该参数将不再接受 ToolNode 实例。
from langchain.agents import create_agent
agent = create_agent(
model="claude-sonnet-4-6",
tools=[check_weather, search_web]
)
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 method.
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]
)
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使用提供者原生的结构化输出生成
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]
)
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" to "model" 更改为更好地反映节点的用途。
运行时上下文
调用代理时,通常需要传递两种类型的数据: * 在整个对话过程中变化的动态状态(例如消息历史) * 在对话过程中不变的静态上下文(例如用户元数据)
在 v1 中,通过设置以下内容支持静态上下文 context 参数为 invoke 和 stream.
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]
)
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]
)
标准内容
在 v1 中,消息获得提供者无关的标准内容块。通过 @[message.content_blocks][内容_块] 获取跨提供者的一致、类型化视图。现有的 @[message.content][BaseMessage(content_块)] 字段保持不变,用于字符串或提供者原生结构。
发生了什么变化
- - 新的 @[
content_blocks][BaseMessage(content_块)] 消息上的属性用于规范化内容 - - 标准化块形状,记录在 消息
- - 可选的标准块序列化到
content通过LC_OUTPUT_VERSION=v1oroutput_version="v1"
读取标准化内容
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"))
# 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
创建多模态消息
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])
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])
块形状示例
# 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",
}
参见内容块 参考 了解更多详情。
序列化标准内容
标准内容块是 **未序列化** 到 content 属性中。如果需要在 content 属性中访问标准内容块(例如向客户端发送消息时),可以选择将它们序列化到 content.
from langchain.chat_models import init_chat_model
model = init_chat_model(
"gpt-5-nano",
output_version="v1",
)
简化包
此 langchain v1中的包命名空间已大幅精简,专注于代理的核心构建块。精简后的包使核心功能的发现和使用变得更加容易。
命名空间
| 模块 | 可用内容 | 备注 |
|---|---|---|
langchain.agents | create_agent, AgentState | 核心代理创建功能 |
langchain.messages | 消息类型、内容块、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 并更新您的导入语句:
- - 旧版链(
LLMChain,ConversationChain等) - - 检索器(例如
MultiQueryRetriever或之前langchain.retrievers模块中的任何内容) - - 索引 API
- - Hub 模块(用于以编程方式管理提示词)
- - 嵌入模块(例如
CacheBackedEmbeddings和社区嵌入) - -
langchain-communityre-exports - - 其他已弃用的功能
# 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
# Chains
from langchain_classic.chains import LLMChain
# Retrievers
from langchain.retrievers import ...
# Indexing
from langchain.indexes import ...
# Hub
from langchain import hub
安装:
uv pip install langchain-classic
重大变更
放弃对 Python 3.9 的支持
所有 LangChain 包现在要求 **Python 3.10 或更高版本**。Python 3.9 于 停止支持 2025年10月。
聊天模型返回类型更新
聊天模型调用的返回类型签名已从 BaseMessage to AIMessage 修复。实现 bind_tools 应更新其返回签名:
def bind_tools(
...
) -> Runnable[LanguageModelInput, AIMessage]:
def bind_tools(
...
) -> Runnable[LanguageModelInput, BaseMessage]:
OpenAI Responses API 的默认消息格式
在与 Responses API 交互时, langchain-openai 现在默认为在消息中存储响应项 content。要恢复之前的行为,请设置 LC_OUTPUT_VERSION 环境变量为 v0,或指定 output_version="v0" 在实例化 ChatOpenAI.
# Enforce previous behavior with output_version flag
model = ChatOpenAI(model="gpt-5.4-mini", output_version="v0")
默认值 max_tokens in langchain-anthropic
在 max_tokens 中的 langchain-anthropic 参数现在默认为根据所选模型更高的值,而不是之前的默认值 1024。如果您依赖旧默认值,请显式设置 max_tokens=1024.
旧代码已移至 langchain-classic
标准接口和代理焦点之外现有功能已移至 langchain-classic 包。请参阅 简化命名空间 部分,了解核心中可用的内容 langchain 包以及哪些内容移至 langchain-classic.
已弃用 API 的移除
已弃用并计划在 1.0 中移除的方法、函数和其他对象已被删除。请查看 弃用通知 从先前版本中获取替换 API。
文本属性
对 .text() 方法在消息对象上的使用应去掉括号,因为它现在是一个属性:
# Property access
text = response.text
# Deprecated method call
text = response.text()
现有用法模式(即, .text())将继续工作,但现在会发出警告。方法形式将在 v2 中移除。
example 参数已从 AIMessage
example 参数已从 AIMessage 对象中移除。我们建议迁移到使用 additional_kwargs 来根据需要传递额外的元数据。
次要变更
- -
AIMessageChunk对象现在包含一个chunk_position属性,位置为'last'来表示流中的最终块。这允许更清晰地处理流式消息。如果该块不是最后一个,chunk_position将为None. - -
LanguageModelOutputVar现在类型为AIMessage而不是BaseMessage. - - 合并消息块的逻辑(
AIMessageChunk.add)已更新,具有更复杂的最终合并块 ID 选择处理。它优先使用提供商分配的 ID 而不是 LangChain 生成的 ID。 - - 我们现在使用
utf-8编码打开文件作为默认设置。 - - 标准测试现在使用多模态内容块。
归档文档
旧文档已归档以供参考:
- - v0.3 文档内容
- - v0.3 API 参考