LangChain v1 是构建智能体的专注、生产就绪的基础。 我们围绕三个核心改进精简了框架: 要升级,
npm install langchain @langchain/core
有关完整的更改列表,请参阅迁移指南

createAgent

createAgent 是在 LangChain 1.0 中构建智能体的标准方式。它提供了比从 LangGraph 导出的预构建 createReactAgent 更简单的接口,同时通过使用中间件提供更大的自定义潜力。
import { createAgent } from "langchain";

const agent = createAgent({
  model: "claude-sonnet-4-5-20250929",
  tools: [getWeather],
  systemPrompt: "You are a helpful assistant.",
});

const result = await agent.invoke({
  messages: [
    { role: "user", content: "What is the weather in Tokyo?" },
  ],
});

console.log(result.content);
在底层,createAgent 建立在基本智能体循环之上 — 调用模型,让它选择要执行的工具,然后在不再调用工具时完成:
核心智能体循环图
有关更多信息,请参阅智能体

中间件

中间件是 createAgent 的定义特性。它使 createAgent 高度可定制,提高了您可以构建的上限。 优秀的智能体需要上下文工程:在正确的时间将正确的信息提供给模型。中间件通过可组合的抽象帮助您控制动态提示、对话总结、选择性工具访问、状态管理和护栏。

预构建中间件

LangChain 为常见模式提供了一些预构建中间件,包括:
  • summarizationMiddleware:当对话历史太长时进行压缩
  • humanInTheLoopMiddleware:为敏感工具调用要求批准
  • piiRedactionMiddleware:在发送给模型之前编辑敏感信息
import {
  createAgent,
  summarizationMiddleware,
  humanInTheLoopMiddleware,
  piiRedactionMiddleware,
} from "langchain";

const agent = createAgent({
  model: "claude-sonnet-4-5-20250929",
  tools: [readEmail, sendEmail],
  middleware: [
    piiRedactionMiddleware({ patterns: ["email", "phone", "ssn"] }),
    summarizationMiddleware({
      model: "claude-sonnet-4-5-20250929",
      maxTokensBeforeSummary: 500,
    }),
    humanInTheLoopMiddleware({
      interruptOn: {
        sendEmail: {
          allowedDecisions: ["approve", "edit", "reject"],
        },
      },
    }),
  ] as const,
});

Custom middleware

You can also build custom middleware to fit your specific needs. Build custom middleware by implementing any of these hooks using the createMiddleware function:
HookWhen it runsUse cases
beforeAgentBefore calling the agentLoad memory, validate input
beforeModelBefore each LLM callUpdate prompts, trim messages
wrapModelCallAround each LLM callIntercept and modify requests/responses
wrapToolCallAround each tool callIntercept and modify tool execution
afterModelAfter each LLM responseValidate output, apply guardrails
afterAgentAfter agent completesSave results, cleanup
Middleware flow diagram
Example custom middleware:
import { createMiddleware } from "langchain";

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

const expertiseBasedToolMiddleware = createMiddleware({
  wrapModelCall: async (request, handler) => {
    const userLevel = request.runtime.context.userExpertise;
    if (userLevel === "expert") {
      const tools = [advancedSearch, dataAnalysis];
      return handler(
        request.replace("openai:gpt-5", tools)
      );
    }
    const tools = [simpleSearch, basicCalculator];
    return handler(
      request.replace("openai:gpt-5-nano", tools)
    );
  },
});

const agent = createAgent({
  model: "claude-sonnet-4-5-20250929",
  tools: [simpleSearch, advancedSearch, basicCalculator, dataAnalysis],
  middleware: [expertiseBasedToolMiddleware],
  contextSchema,
});
For more information, see the complete middleware guide.

Built on LangGraph

Because createAgent is built on LangGraph, you automatically get built in support for long running and reliable agents via:

Persistence

Conversations automatically persist across sessions with built-in checkpointing

Streaming

Stream tokens, tool calls, and reasoning traces in real-time

Human-in-the-loop

Pause agent execution for human approval before sensitive actions

Time travel

Rewind conversations to any point and explore alternate paths and prompts
You don’t need to learn LangGraph to use these features—they work out of the box.

Structured output

createAgent has improved structured output generation:
  • Main loop integration: Structured output is now generated in the main loop instead of requiring an additional LLM call
  • Structured output strategy: Models can choose between calling tools or using provider-side structured output generation
  • Cost reduction: Eliminates extra expense from additional LLM calls
import { createAgent } from "langchain";
import * as z from "zod";

const weatherSchema = z.object({
  temperature: z.number(),
  condition: z.string(),
});

const agent = createAgent({
  model: "gpt-4o-mini",
  tools: [getWeather],
  responseFormat: weatherSchema,
});

const result = await agent.invoke({
  messages: [
    { role: "user", content: "What is the weather in Tokyo?" },
  ],
});

console.log(result.structuredResponse);
Error handling: Control error handling via the handleErrors parameter to ToolStrategy:
  • Parsing errors: Model generates data that doesn’t match desired structure
  • Multiple tool calls: Model generates 2+ tool calls for structured output schemas

Standard content blocks

1.0 releases are available for most packages. Only the following currently support new content blocks:
  • langchain
  • @langchain/core
  • @langchain/anthropic
  • @langchain/openai
Broader support for content blocks is planned.

Benefits

  • Provider agnostic: Access reasoning traces, citations, built-in tools (web search, code interpreters, etc.), and other features using the same API regardless of provider
  • Type safe: Full type hints for all content block types
  • Backward compatible: Standard content can be loaded lazily, so there are no associated breaking changes
For more information, see our guide on content blocks

Simplified package

LangChain v1 streamlines the langchain package namespace to focus on essential building blocks for agents. The package exposes only the most useful and relevant functionality: Most of these are re-exported from @langchain/core for convenience, which gives you a focused API surface for building agents.

@langchain/classic

Legacy functionality has moved to @langchain/classic to keep the core package lean and focused.

What’s in @langchain/classic

  • Legacy chains and chain implementations
  • Retrievers
  • The indexing API
  • @langchain/community exports
  • Other deprecated functionality
If you use any of this functionality, install @langchain/classic:
npm install @langchain/classic
Then update your imports:
import { ... } from "langchain"; 
import { ... } from "@langchain/classic"; 

import { ... } from "langchain/chains"; 
import { ... } from "@langchain/classic/chains"; 

Reporting issues

Please report any issues discovered with 1.0 on GitHub using the 'v1' label.

Additional resources

See also


Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.