跳到主要内容

概览

构建智能体(或任何LLM应用程序)的难点在于使其足够可靠。虽然它们可能适用于原型,但在实际用例中往往会失败。

智能体为何会失败?

当智能体失败时,通常是因为智能体内部的LLM调用采取了错误的行动/没有达到我们预期的效果。LLM失败的原因有以下两种
  1. 底层LLM能力不足
  2. 没有将“正确”的上下文传递给LLM
通常情况下,实际上是第二个原因导致智能体不可靠。 上下文工程是提供正确的信息和工具,并以正确的格式呈现,以便LLM能够完成任务。这是AI工程师的首要任务。这种“正确”上下文的缺乏是实现更可靠智能体的首要障碍,而LangChain的智能体抽象设计独特,旨在促进上下文工程。
刚接触上下文工程?请从概念概述开始,了解不同类型的上下文及其使用时机。

智能体循环

典型的智能体循环包含两个主要步骤
  1. 模型调用 - 使用提示和可用工具调用LLM,返回响应或执行工具的请求
  2. 工具执行 - 执行LLM请求的工具,返回工具结果
Core agent loop diagram
此循环持续进行,直到LLM决定完成。

你可以控制什么

要构建可靠的智能体,你需要控制智能体循环的每个步骤中发生的事情,以及步骤之间发生的事情。
上下文类型你可以控制什么瞬态或持久性
模型上下文模型调用中包含的内容(指令、消息历史、工具、响应格式)瞬态
工具上下文工具可以访问和生成的内容(对状态、存储、运行时上下文的读取/写入)持久性
生命周期上下文模型和工具调用之间发生的事情(摘要、防护措施、日志记录等)持久性

瞬态上下文

LLM单次调用时看到的内容。你可以修改消息、工具或提示,而无需更改状态中保存的内容。

持久性上下文

在多次轮次中保存到状态的内容。生命周期钩子和工具写入会永久修改此内容。

数据源

在此过程中,你的智能体会访问(读取/写入)不同的数据源
数据源又称范围示例
运行时上下文静态配置会话范围用户 ID、API 密钥、数据库连接、权限、环境设置
状态短期记忆会话范围当前消息、上传文件、身份验证状态、工具结果
存储长期记忆跨对话用户偏好、提取的洞察、记忆、历史数据

工作原理

LangChain 中间件是底层机制,它使得LangChain开发人员可以实际进行上下文工程。 中间件允许你介入智能体生命周期中的任何步骤,并:
  • 更新上下文
  • 跳转到智能体生命周期中的不同步骤
在本指南中,你将频繁看到中间件 API 的使用,以此实现上下文工程。

模型上下文

控制每次模型调用中的内容——指令、可用工具、要使用的模型和输出格式。这些决策直接影响可靠性和成本。 所有这些类型的模型上下文都可以从状态(短期记忆)、存储(长期记忆)或运行时上下文(静态配置)中获取。

系统提示

系统提示设置了LLM的行为和能力。不同的用户、上下文或对话阶段需要不同的指令。成功的智能体利用记忆、偏好和配置来为当前的对话状态提供正确的指令。
  • 状态
  • 存储
  • 运行时上下文
从状态访问消息计数或对话上下文
import { createAgent } from "langchain";

const agent = createAgent({
  model: "gpt-4o",
  tools: [...],
  middleware: [
    dynamicSystemPromptMiddleware((state) => {
      // Read from State: check conversation length
      const messageCount = state.messages.length;

      let base = "You are a helpful assistant.";

      if (messageCount > 10) {
        base += "\nThis is a long conversation - be extra concise.";
      }

      return base;
    }),
  ],
});

消息

消息构成发送给LLM的提示。管理消息内容至关重要,以确保LLM拥有正确的信息来做出良好响应。
  • 状态
  • 存储
  • 运行时上下文
在与当前查询相关时,从状态注入上传的文件上下文
import { createMiddleware } from "langchain";

const injectFileContext = createMiddleware({
  name: "InjectFileContext",
  wrapModelCall: (request, handler) => {
    // request.state is a shortcut for request.state.messages
    const uploadedFiles = request.state.uploadedFiles || [];  

    if (uploadedFiles.length > 0) {
      // Build context about available files
      const fileDescriptions = uploadedFiles.map(file =>
        `- ${file.name} (${file.type}): ${file.summary}`
      );

      const fileContext = `Files you have access to in this conversation:
${fileDescriptions.join("\n")}

Reference these files when answering questions.`;

      // Inject file context before recent messages
      const messages = [  
        ...request.messages  // Rest of conversation
        { role: "user", content: fileContext }
      ];
      request = request.override({ messages });  
    }

    return handler(request);
  },
});

const agent = createAgent({
  model: "gpt-4o",
  tools: [...],
  middleware: [injectFileContext],
});
瞬态与持久性消息更新:上述示例使用 wrap_model_call 进行瞬态更新——修改单次调用发送给模型的消息,而不改变状态中保存的内容。对于修改状态的持久性更新(如生命周期上下文中的摘要示例),请使用 before_modelafter_model 等生命周期钩子来永久更新对话历史记录。有关更多详细信息,请参阅中间件文档

工具

工具让模型与数据库、API 和外部系统交互。你定义和选择工具的方式直接影响模型能否有效完成任务。

定义工具

每个工具都需要清晰的名称、描述、参数名称和参数描述。这些不仅仅是元数据,它们指导模型何时以及如何使用工具的推理。
import { tool } from "@langchain/core/tools";
import { z } from "zod";

const searchOrders = tool(
  async ({ userId, status, limit = 10 }) => {
    // Implementation here
  },
  {
    name: "search_orders",
    description: `Search for user orders by status.

    Use this when the user asks about order history or wants to check
    order status. Always filter by the provided status.`,
    schema: z.object({
      userId: z.string().describe("Unique identifier for the user"),
      status: z.enum(["pending", "shipped", "delivered"]).describe("Order status to filter by"),
      limit: z.number().default(10).describe("Maximum number of results to return"),
    }),
  }
);

选择工具

并非所有工具都适用于所有情况。过多的工具可能会让模型不堪重负(上下文过载)并增加错误;过少的工具会限制能力。动态工具选择根据身份验证状态、用户权限、功能标志或对话阶段调整可用工具集。
  • 状态
  • 存储
  • 运行时上下文
仅在达到某些对话里程碑后启用高级工具
import { createMiddleware } from "langchain";

const stateBasedTools = createMiddleware({
  name: "StateBasedTools",
  wrapModelCall: (request, handler) => {
    // Read from State: check authentication and conversation length
    const state = request.state;  
    const isAuthenticated = state.authenticated || false;  
    const messageCount = state.messages.length;

    let filteredTools = request.tools;

    // Only enable sensitive tools after authentication
    if (!isAuthenticated) {
      filteredTools = request.tools.filter(t => t.name.startsWith("public_"));  
    } else if (messageCount < 5) {
      filteredTools = request.tools.filter(t => t.name !== "advanced_search");  
    }

    return handler({ ...request, tools: filteredTools });  
  },
});
有关更多示例,请参阅动态选择工具

模型

不同的模型具有不同的优势、成本和上下文窗口。为手头的任务选择合适的模型,这可能会在智能体运行期间发生变化。
  • 状态
  • 存储
  • 运行时上下文
根据状态中的对话长度使用不同的模型
import { createMiddleware, initChatModel } from "langchain";

// Initialize models once outside the middleware
const largeModel = initChatModel("claude-sonnet-4-5-20250929");
const standardModel = initChatModel("gpt-4o");
const efficientModel = initChatModel("gpt-4o-mini");

const stateBasedModel = createMiddleware({
  name: "StateBasedModel",
  wrapModelCall: (request, handler) => {
    // request.messages is a shortcut for request.state.messages
    const messageCount = request.messages.length;  
    let model;

    if (messageCount > 20) {
      model = largeModel;
    } else if (messageCount > 10) {
      model = standardModel;
    } else {
      model = efficientModel;
    }

    return handler({ ...request, model });  
  },
});
有关更多示例,请参阅动态模型

响应格式

结构化输出将非结构化文本转换为经过验证的结构化数据。当提取特定字段或为下游系统返回数据时,自由格式文本是不够的。 工作原理:当你提供一个模式作为响应格式时,模型的最终响应保证符合该模式。智能体运行模型/工具调用循环,直到模型完成工具调用,然后将最终响应强制转换为所提供的格式。

定义格式

模式定义指导模型。字段名称、类型和描述精确指定了输出应遵循的格式。
import { z } from "zod";

const customerSupportTicket = z.object({
  category: z.enum(["billing", "technical", "account", "product"]).describe(
    "Issue category"
  ),
  priority: z.enum(["low", "medium", "high", "critical"]).describe(
    "Urgency level"
  ),
  summary: z.string().describe(
    "One-sentence summary of the customer's issue"
  ),
  customerSentiment: z.enum(["frustrated", "neutral", "satisfied"]).describe(
    "Customer's emotional tone"
  ),
}).describe("Structured ticket information extracted from customer message");

选择格式

动态响应格式选择根据用户偏好、对话阶段或角色调整模式——早期返回简单格式,随着复杂性增加返回详细格式。
  • 状态
  • 存储
  • 运行时上下文
根据对话状态配置结构化输出
import { createMiddleware } from "langchain";
import { z } from "zod";

const simpleResponse = z.object({
  answer: z.string().describe("A brief answer"),
});

const detailedResponse = z.object({
  answer: z.string().describe("A detailed answer"),
  reasoning: z.string().describe("Explanation of reasoning"),
  confidence: z.number().describe("Confidence score 0-1"),
});

const stateBasedOutput = createMiddleware({
  name: "StateBasedOutput",
  wrapModelCall: (request, handler) => {
    // request.state is a shortcut for request.state.messages
    const messageCount = request.messages.length;  

    if (messageCount < 3) {
      // Early conversation - use simple format
      responseFormat = simpleResponse; 
    } else {
      // Established conversation - use detailed format
      responseFormat = detailedResponse; 
    }

    return handler({ ...request, responseFormat });
  },
});

工具上下文

工具的特殊之处在于它们既能读取上下文又能写入上下文。 在最基本的情况下,当工具执行时,它接收LLM的请求参数并返回一个工具消息。工具完成其工作并产生结果。 工具还可以为模型获取重要信息,使其能够执行和完成任务。

读取

大多数实际工具需要的不仅仅是LLM的参数。它们需要用于数据库查询的用户ID、用于外部服务的API密钥或当前会话状态来做出决策。工具从状态、存储和运行时上下文读取以访问这些信息。
  • 状态
  • 存储
  • 运行时上下文
从状态读取以检查当前会话信息
import * as z from "zod";
import { tool } from "@langchain/core/tools";
import { createAgent } from "langchain";

const checkAuthentication = tool(
  async (_, { runtime }) => {
    // Read from State: check current auth status
    const currentState = runtime.state;
    const isAuthenticated = currentState.authenticated || false;

    if (isAuthenticated) {
      return "User is authenticated";
    } else {
      return "User is not authenticated";
    }
  },
  {
    name: "check_authentication",
    description: "Check if user is authenticated",
    schema: z.object({}),
  }
);

写入

工具结果可用于帮助智能体完成给定任务。工具既可以直接将结果返回给模型,也可以更新智能体的记忆,从而使重要上下文可用于未来的步骤。
  • 状态
  • 存储
使用命令写入状态以跟踪会话特定信息
import * as z from "zod";
import { tool } from "@langchain/core/tools";
import { createAgent } from "langchain";
import { Command } from "@langchain/langgraph";

const authenticateUser = tool(
  async ({ password }, { runtime }) => {
    // Perform authentication
    if (password === "correct") {
      // Write to State: mark as authenticated using Command
      return new Command({
        update: { authenticated: true },
      });
    } else {
      return new Command({ update: { authenticated: false } });
    }
  },
  {
    name: "authenticate_user",
    description: "Authenticate user and update State",
    schema: z.object({
      password: z.string(),
    }),
  }
);
有关在工具中访问状态、存储和运行时上下文的全面示例,请参阅工具

生命周期上下文

控制核心智能体步骤之间发生的事情——拦截数据流以实现跨领域关注点,如摘要、防护措施和日志记录。 正如你在模型上下文工具上下文中看到的,中间件是使上下文工程切实可行的机制。中间件允许你介入智能体生命周期中的任何步骤,并:
  1. 更新上下文 - 修改状态和存储以持久化更改、更新对话历史或保存洞察
  2. 跳转生命周期 - 根据上下文移动到智能体生命周期中的不同步骤(例如,如果满足条件则跳过工具执行,使用修改后的上下文重复模型调用)
Middleware hooks in the agent loop

示例:摘要

最常见的生命周期模式之一是当对话历史变得过长时自动进行压缩。与模型上下文中所示的瞬态消息修剪不同,摘要功能会持久更新状态——用摘要永久替换旧消息,并保存以供所有未来的轮次使用。 LangChain 为此提供了内置中间件:
import { createAgent, summarizationMiddleware } from "langchain";

const agent = createAgent({
  model: "gpt-4o",
  tools: [...],
  middleware: [
    summarizationMiddleware({
      model: "gpt-4o-mini",
      maxTokensBeforeSummary: 4000, // Trigger summarization at 4000 tokens
      messagesToKeep: 20, // Keep last 20 messages after summary
    }),
  ],
});
当对话超出令牌限制时,SummarizationMiddleware 会自动执行以下操作:
  1. 使用单独的LLM调用对旧消息进行摘要
  2. 在状态中用摘要消息替换它们(永久性)
  3. 保持最近的消息完整以提供上下文
摘要后的对话历史记录会永久更新——未来的轮次将看到摘要而非原始消息。
有关内置中间件的完整列表、可用钩子以及如何创建自定义中间件,请参阅中间件文档

最佳实践

  1. 从简单开始 - 从静态提示和工具开始,仅在需要时添加动态功能
  2. 增量测试 - 一次添加一个上下文工程功能
  3. 监控性能 - 跟踪模型调用、令牌使用和延迟
  4. 使用内置中间件 - 利用 SummarizationMiddlewareLLMToolSelectorMiddleware 等。
  5. 记录你的上下文策略 - 明确传递了哪些上下文以及原因
  6. 理解瞬态与持久性:模型上下文的更改是瞬态的(每次调用),而生命周期上下文的更改会持久化到状态

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.