Skip to main content
本迁移指南概述了LangChain v1的主要变更。要了解更多关于v1的新功能,请参阅介绍帖子 升级,
npm install langchain@latest @langchain/core@latest

createAgent

在v1版本中,react智能体预构建现在包含在langchain包中。下表概述了哪些功能已发生变化:
部分变化内容
导入路径包从 @langchain/langgraph/prebuilts 移动到 langchain
提示参数重命名为 systemPrompt,动态提示使用中间件
模型前钩被具有 beforeModel 方法的中间件替换
模型后钩被具有 afterModel 方法的中间件替换
自定义状态在中间件中定义,仅限 zod 对象
模型通过中间件动态选择,不支持预绑定模型
工具工具错误处理移动到具有 wrapToolCall 的中间件
结构化输出移除提示输出,使用 toolStrategy/providerStrategy
流节点名称节点名称从 "agent" 更改为 "model"
运行时上下文使用 context 属性代替 config.configurable
命名空间简化以专注于智能体构建块,旧代码移动到 @langchain/classic

导入路径

react智能体预构建的导入路径已从 @langchain/langgraph/prebuilts 更改为 langchain。函数名称已从 createReactAgent 更改为 createAgent
import { createReactAgent } from "@langchain/langgraph/prebuilts"; 
import { createAgent } from "langchain"; 

提示

静态提示重命名

prompt 参数已被重命名为 systemPrompt
import { createAgent } from "langchain";

agent = createAgent({
  model,
  tools,
  systemPrompt: "You are a helpful assistant.", 
});

SystemMessage

如果在使用系统提示中的 SystemMessage 对象,现在将直接使用字符串内容:
import { SystemMessage, createAgent } from "langchain";

const agent = createAgent({
  model,
  tools,
  systemPrompt: "You are a helpful assistant.", 
});

动态提示

动态提示是一种核心的上下文工程模式——它们根据当前的对话状态调整你对模型所说的内容。为此,请使用 dynamicSystemPromptMiddleware
import { createAgent, dynamicSystemPromptMiddleware } from "langchain";
import * as z from "zod";

const contextSchema = z.object({
  userRole: z.enum(["expert", "beginner"]).default("user"),
});

const userRolePrompt = dynamicSystemPromptMiddleware((request) => { 
  const userRole = request.runtime.context.userRole;
  const basePrompt = "You are a helpful assistant.";

  if (userRole === "expert") {
    return `${basePrompt} Provide detailed technical responses.`;
  } else if (userRole === "beginner") {
    return `${basePrompt} Explain concepts simply and avoid jargon.`;
  }
  return basePrompt; 
});

const agent = createAgent({
  model,
  tools,
  middleware: [userRolePrompt],
  contextSchema,
});

await agent.invoke({
  messages: [new HumanMessage("Explain async programming")],
  context: {
    userRole: "expert",
  },
})

预模型钩子

预模型钩子现在已实现为具有 beforeModel 方法的中间件。这种模式更易于扩展——您可以在调用模型之前定义多个中间件,并在多个智能体之间重用它们。 常见用例包括:
  • 概括对话历史
  • 剪裁消息
  • 输入防护措施,如个人敏感信息(PII)的编辑
v1 包含内置的摘要中间件:
import { createAgent, summarizationMiddleware } from "langchain";

const agent = createAgent({
  model: "anthropic:claude-sonnet-4-5",
  tools,
  middleware: [
    summarizationMiddleware({
      model: "anthropic:claude-sonnet-4-5",
      maxTokensBeforeSummary: 1000,
    }),
  ],
});

模型后钩子

模型后钩现在已实现为具有 afterModel 方法的中间件。这使得您可以在模型响应后组合多个处理器。 常见用例包括:
  • 人工审核
  • 输出限制
v1 包含内置的人机交互中间件:
import { createAgent, humanInTheLoopMiddleware } from "langchain";

const agent = createAgent({
  model: "anthropic:claude-sonnet-4-5",
  tools: [readEmail, sendEmail],
  middleware: [
    humanInTheLoopMiddleware({
      interruptOn: {
        sendEmail: { allowedDecisions: ["approve", "edit", "reject"] },
      },
    }),
  ],
});

自定义状态

自定义状态现在使用 stateSchema 属性在中间件中定义。使用 Zod 声明通过智能体运行携带的额外状态字段。
import * as z from "zod";
import { createAgent, createMiddleware, tool } from "langchain";

const UserState = z.object({
  userName: z.string(),
});

const userState = createMiddleware({
  name: "UserState",
  stateSchema: UserState,
  beforeModel: (state) => {
    // Access custom state properties
    const name = state.userName;
    // Optionally modify messages/system prompt based on state
    return;
  },
});

const greet = tool(
  async () => {
    return "Hello!";
  },
  {
    name: "greet",
    description: "Greet the user",
    schema: z.object({}),
  }
);

const agent = createAgent({
  model: "anthropic:claude-sonnet-4-5",
  tools: [greet],
  middleware: [userState],
});

await agent.invoke({
  messages: [{ role: "user", content: "Hi" }],
  userName: "Ada",
});

模型

动态模型选择现在通过中间件进行。使用 wrapModelCall 根据状态或运行时上下文交换模型(和工具)。在 createReactAgent 中,这是通过传递给 model 参数的函数来实现的。 此功能已移植到v1版本的中间件接口中。

动态模型选择

import { createAgent, createMiddleware } from "langchain";

const dynamicModel = createMiddleware({
  name: "DynamicModel",
  wrapModelCall: (request, handler) => {
    const messageCount = request.state.messages.length;
    const model = messageCount > 10 ? "openai:gpt-5" : "openai:gpt-5-nano";
    return handler({ ...request, model });
  },
});

const agent = createAgent({
  model: "openai:gpt-5-nano",
  tools,
  middleware: [dynamicModel],
});

预绑定模型

为了更好地支持结构化输出,createAgent 应接收一个纯模型(字符串或实例)以及一个单独的 tools 列表。在使用结构化输出时,请避免传递预先绑定工具的模型。
// No longer supported
// const modelWithTools = new ChatOpenAI({ model: "gpt-4o-mini" }).bindTools([someTool]);
// const agent = createAgent({ model: modelWithTools, tools: [] });

// Use instead
const agent = createAgent({ model: "openai:gpt-4o-mini", tools: [someTool] });

工具

The tools 参数接受:
  • 使用 tool 创建的函数
  • LangChain 工具实例
  • 代表内置提供者工具的对象
使用中间件 wrapToolCall 来集中处理工具的错误和日志记录。
import { createAgent, createMiddleware } from "langchain";

const errorHandling = createMiddleware({
  name: "ToolErrors",
  wrapToolCall: async (request, handler) => {
    try {
      return await handler(request);
    } catch (err) {
      return `Error executing ${request.toolName}: ${String(err)}`;
    }
  },
});

const agent = createAgent({
  model: "anthropic:claude-sonnet-4-5",
  tools: [checkWeather, searchWeb],
  middleware: [errorHandling],
});

结构化输出

节点变更

结构化输出曾经是在主智能体之外的一个单独节点中生成的。这种情况已经不再存在了。结构化输出现在在主循环中生成(无需额外的LLM调用),从而降低了成本和延迟。

工具和提供商策略

在v1版本中,有两种策略:
  • toolStrategy 使用人工工具调用以生成结构化输出
  • providerStrategy 使用提供者本地的结构化输出生成
import { createAgent, toolStrategy } from "langchain";
import * as z from "zod";

const OutputSchema = z.object({
  summary: z.string(),
  sentiment: z.string(),
});

const agent = createAgent({
  model: "openai:gpt-4o-mini",
  tools,
  // explicitly using tool strategy
  responseFormat: toolStrategy(OutputSchema), 
});

提示输出已移除

通过 responseFormat 中的自定义指令触发的提示输出已被移除,以支持上述策略。

流式节点名称重命名

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

运行时上下文

在调用智能体时,通过 context 配置参数传递静态、只读配置。这替代了使用 config.configurable 的模式。
import { createAgent, HumanMessage } from "langchain";
import * as z from "zod";

const agent = createAgent({
  model: "openai:gpt-4o",
  tools,
  contextSchema: z.object({ userId: z.string(), sessionId: z.string() }),
});

const result = await agent.invoke(
  { messages: [new HumanMessage("Hello")] },
  { context: { userId: "123", sessionId: "abc" } }, 
);
旧的 config.configurable 模式仍然适用于向后兼容,但建议对于新应用或迁移到 v1 的应用使用新的 context 参数。

标准内容

在v1版本中,消息获得了供应商无关的标准内容块。通过 message.contentBlocks 访问它们,以实现跨供应商的一致、类型化的视图。现有的 message.content 字段对于字符串或供应商原生结构保持不变。

发生了什么变化

  • 消息中新增用于标准化内容的 contentBlocks 属性。
  • ContentBlock 下新增 TypeScript 类型以实现强类型。
  • 可选地将标准块序列化为 content,通过 LC_OUTPUT_VERSION=v1outputVersion: "v1" 实现。

读取标准化内容

import { initChatModel } from "langchain";

const model = await initChatModel("openai:gpt-5-nano");
const response = await model.invoke("Explain AI");

for (const block of response.contentBlocks) {
  if (block.type === "reasoning") {
    console.log(block.reasoning);
  } else if (block.type === "text") {
    console.log(block.text);
  }
}

创建多模态消息

import { HumanMessage } from "langchain";

const message = new HumanMessage({
  contentBlocks: [
    { type: "text", text: "Describe this image." },
    { type: "image", url: "https://example.com/image.jpg" },
  ],
});
const res = await model.invoke([message]);

示例块类型

import { ContentBlock } from "langchain";

const textBlock: ContentBlock.Text = {
  type: "text",
  text: "Hello world",
};

const imageBlock: ContentBlock.Multimodal.Image = {
  type: "image",
  url: "https://example.com/image.png",
  mimeType: "image/png",
};
查看参考中的内容块以获取更多详细信息。

序列化标准内容

标准内容块默认 不会 序列化到 content 属性中。如果您需要访问 content 属性中的标准内容块(例如,在向客户端发送消息时),可以选择将它们序列化到 content 中。
export LC_OUTPUT_VERSION=v1
了解更多:消息标准内容块。查看 多模态 以获取输入示例。

简化版包

langchain 包命名空间经过精简,专注于智能体构建模块。旧功能已迁移至 @langchain/classic。新包仅暴露最有用和相关的功能。

导出

v1 包包含:
模块可用功能备注
智能体createAgentAgentState核心智能体创建功能
消息消息类型、内容块、trimMessages@langchain/core 中导出
工具tool、工具类@langchain/core 中导出
聊天模型initChatModelBaseChatModel统一模型初始化

@langchain/classic

如果您使用旧版链、索引API或之前从 @langchain/community 重新导出的功能,请安装 @langchain/classic 并更新导入:
npm install @langchain/classic
// v1 (new)
import { ... } from "@langchain/classic";
import { ... } from "@langchain/classic/chains";

// v0 (old)
import { ... } from "langchain";
import { ... } from "langchain/chains";

破坏性变更

丢弃 Node 18 支持

所有 LangChain 包现在都需要 Node.js 20 或更高版本。Node.js 18 于 2025 年 3 月达到 生命周期的结束

新构建输出

现在构建所有langchain包都使用基于打包器的方案,而不是使用原始的TypeScript输出。如果您之前是从dist/目录导入文件(这不被推荐),您需要更新您的导入以使用新的模块系统。

旧代码已移动到 @langchain/classic

旧版功能已从标准接口和智能体关注的范围移至 @langchain/classic 包中。有关核心 langchain 包中包含的内容以及移至 @langchain/classic 的信息,请参阅 简化版包 部分。

已废弃API的移除

1.0 版本中已经弃用并计划删除的方法、函数和其他对象已被删除。
以下API已在v1版本中删除:

核心功能

  • TraceGroup - 使用 LangSmith 跟踪
  • BaseDocumentLoader.loadAndSplit - 使用 .load() 后跟文本分割器
  • RemoteRunnable - 已不再支持

提示

  • BasePromptTemplate.serialize.deserialize - 直接使用 JSON 序列化
  • ChatPromptTemplate.fromPromptMessages - 使用 ChatPromptTemplate.fromMessages

检索器

  • BaseRetrieverInterface.getRelevantDocuments - 使用 .invoke() 代替

可执行项

  • Runnable.bind - 使用 .bindTools() 或其他特定绑定方法
  • Runnable.map - 使用 .batch() 代替
  • RunnableBatchOptions.maxConcurrency - 在配置对象中使用 maxConcurrency

聊天模型

  • BaseChatModel.predictMessages - 使用 .invoke() 代替
  • BaseChatModel.predict - 使用 .invoke() 代替
  • BaseChatModel.serialize - 直接使用 JSON 序列化
  • BaseChatModel.callPrompt - 使用 .invoke() 代替
  • BaseChatModel.call - 使用 .invoke() 代替

大型语言模型

  • BaseLLMParams.concurrency - 在配置对象中使用 maxConcurrency
  • BaseLLM.call - 使用 .invoke() 代替
  • BaseLLM.predict - 使用 .invoke() 代替
  • BaseLLM.predictMessages - 使用 .invoke() 代替
  • BaseLLM.serialize - 直接使用 JSON 序列化

流式传输

  • createChatMessageChunkEncoderStream - 直接使用 .stream() 方法

跟踪

  • BaseTracer.runMap - 使用 LangSmith 跟踪 API
  • getTracingCallbackHandler - 使用 LangSmith 跟踪
  • getTracingV2CallbackHandler - 使用 LangSmith 跟踪
  • LangChainTracerV1 - 使用 LangSmith 跟踪

内存和存储

  • BaseListChatMessageHistory.addAIChatMessage - 使用 .addMessage()AIMessage
  • BaseStoreInterface - 使用特定的存储实现

工具

  • getRuntimeEnvironmentSync - 使用异步 getRuntimeEnvironment()