跳到主要内容
代理将语言模型与工具相结合,创建能够对任务进行推理、决定使用哪些工具并迭代地解决问题的系统。 createAgent() 提供了一个生产就绪的代理实现。 LLM 代理在一个循环中运行工具以实现目标。代理会一直运行,直到满足停止条件——即,当模型发出最终输出或达到迭代限制时。
createAgent() 使用 LangGraph 构建一个基于的代理运行时。图由节点(步骤)和边(连接)组成,它们定义了代理如何处理信息。代理通过此图移动,执行模型节点(调用模型)、工具节点(执行工具)或中间件等节点。了解更多关于 图 API

核心组件

模型

模型是代理的推理引擎。它可以通过多种方式指定,支持静态和动态模型选择。

静态模型

静态模型在创建代理时配置一次,并在整个执行过程中保持不变。这是最常见和最直接的方法。 要从初始化静态模型:
import { createAgent } from "langchain";

const agent = createAgent({
  model: "gpt-5",
  tools: []
});
模型标识符字符串使用 `provider:model` 格式(例如 `“openai:gpt-5”`)。您可能希望对模型配置有更多控制,在这种情况下,您可以直接使用提供商包初始化模型实例
import { createAgent } from "langchain";
import { ChatOpenAI } from "@langchain/openai";

const model = new ChatOpenAI({
  model: "gpt-4o",
  temperature: 0.1,
  maxTokens: 1000,
  timeout: 30
});

const agent = createAgent({
  model,
  tools: []
});
模型实例为您提供了对配置的完全控制。当您需要设置特定参数(如 `temperature`、`max_tokens`、`timeouts`)或配置 API 密钥、`base_url` 以及其他提供商特定设置时,请使用它们。请参阅API 参考,了解模型上可用的参数和方法。

动态模型

动态模型在根据当前的和上下文进行选择。这支持复杂的路由逻辑和成本优化。 要使用动态模型,请使用 `wrapModelCall` 创建中间件,以修改请求中的模型:
import { ChatOpenAI } from "@langchain/openai";
import { createAgent, createMiddleware } from "langchain";

const basicModel = new ChatOpenAI({ model: "gpt-4o-mini" });
const advancedModel = new ChatOpenAI({ model: "gpt-4o" });

const dynamicModelSelection = createMiddleware({
  name: "DynamicModelSelection",
  wrapModelCall: (request, handler) => {
    // Choose model based on conversation complexity
    const messageCount = request.messages.length;

    return handler({
        ...request,
        model: messageCount > 10 ? advancedModel : basicModel,
    });
  },
});

const agent = createAgent({
  model: "gpt-4o-mini", // Base model (used when messageCount ≤ 10)
  tools,
  middleware: [dynamicModelSelection] as const,
});
有关中间件和高级模式的更多详细信息,请参阅中间件文档
有关模型配置详情,请参阅模型。有关动态模型选择模式,请参阅中间件中的动态模型

工具

工具赋予代理执行操作的能力。代理超越了简单的仅模型工具绑定,通过促进以下功能:
  • 按顺序多次调用工具(由单个提示触发)
  • 适时并行调用工具
  • 基于先前结果的动态工具选择
  • 工具重试逻辑和错误处理
  • 工具调用之间的状态持久性
更多信息请参见工具

定义工具

将工具列表传递给代理。
import * as z from "zod";
import { createAgent, tool } from "langchain";

const search = tool(
  ({ query }) => `Results for: ${query}`,
  {
    name: "search",
    description: "Search for information",
    schema: z.object({
      query: z.string().describe("The query to search for"),
    }),
  }
);

const getWeather = tool(
  ({ location }) => `Weather in ${location}: Sunny, 72°F`,
  {
    name: "get_weather",
    description: "Get weather information for a location",
    schema: z.object({
      location: z.string().describe("The location to get weather for"),
    }),
  }
);

const agent = createAgent({
  model: "gpt-4o",
  tools: [search, getWeather],
});
如果提供了空的工具列表,则代理将由一个不具备工具调用功能的单一 LLM 节点组成。

工具错误处理

要自定义工具错误的L处理方式,请在自定义中间件中使用 `wrapToolCall` 钩子
import { createAgent, createMiddleware, ToolMessage } from "langchain";

const handleToolErrors = createMiddleware({
  name: "HandleToolErrors",
  wrapToolCall: (request, handler) => {
    try {
      return handler(request);
    } catch (error) {
      // Return a custom error message to the model
      return new ToolMessage({
        content: `Tool error: Please check your input and try again. (${error})`,
        tool_call_id: request.toolCall.id!,
      });
    }
  },
});

const agent = createAgent({
  model: "gpt-4o",
  tools: [
    /* ... */
  ],
  middleware: [handleToolErrors] as const,
});
当工具失败时,代理将返回带有自定义错误消息的 @[ToolMessage]。

ReAct 循环中的工具使用

代理遵循 ReAct(“推理 + 行动”)模式,在简短的推理步骤与有针对性的工具调用之间交替,并将结果观察反馈到后续决策中,直到它们能够提供最终答案。
提示:识别当前最受欢迎的无线耳机并验证可用性。
================================ Human Message =================================

Find the most popular wireless headphones right now and check if they're in stock
  • 推理:“流行度是时间敏感的,我需要使用提供的搜索工具。”
  • 行动:调用 search_products("wireless headphones")
================================== Ai Message ==================================
Tool Calls:
  search_products (call_abc123)
 Call ID: call_abc123
  Args:
    query: wireless headphones
================================= Tool Message =================================

Found 5 products matching "wireless headphones". Top 5 results: WH-1000XM5, ...
  • 推理:“我需要在回答之前确认排名靠前的商品的可用性。”
  • 行动:调用 check_inventory("WH-1000XM5")
================================== Ai Message ==================================
Tool Calls:
  check_inventory (call_def456)
 Call ID: call_def456
  Args:
    product_id: WH-1000XM5
================================= Tool Message =================================

Product WH-1000XM5: 10 units in stock
  • 推理:“我已经有了最流行的型号及其库存状态。现在我可以回答用户的问题了。”
  • 行动:生成最终答案
================================== Ai Message ==================================

I found wireless headphones (model WH-1000XM5) with 10 units in stock...
要了解有关工具的更多信息,请参阅工具

系统提示

您可以通过提供提示来塑造代理处理任务的方式。@[system_prompt] 参数可以作为字符串提供
const agent = createAgent({
  model,
  tools,
  systemPrompt: "You are a helpful assistant. Be concise and accurate.",
});
未提供 @[system_prompt] 时,代理将直接从消息中推断其任务。

动态系统提示

对于需要根据运行时上下文或代理状态修改系统提示的更高级用例,您可以使用中间件
import * as z from "zod";
import { createAgent, dynamicSystemPromptMiddleware } from "langchain";

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

const agent = createAgent({
  model: "gpt-4o",
  tools: [/* ... */],
  contextSchema,
  middleware: [
    dynamicSystemPromptMiddleware<z.infer<typeof contextSchema>>((state, runtime) => {
      const userRole = runtime.context.userRole || "user";
      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;
    }),
  ],
});

// The system prompt will be set dynamically based on context
const result = await agent.invoke(
  { messages: [{ role: "user", content: "Explain machine learning" }] },
  { context: { userRole: "expert" } }
);
有关消息类型和格式的更多详细信息,请参阅消息。有关全面的中间件文档,请参阅中间件

调用

您可以通过向其State传递更新来调用代理。所有代理的状态中都包含一个消息序列;要调用代理,请传递一条新消息
await agent.invoke({
  messages: [{ role: "user", content: "What's the weather in San Francisco?" }],
})
有关从代理流式传输步骤和/或令牌的信息,请参阅流式传输指南。 否则,代理遵循 LangGraph Graph API 并支持所有相关方法。

高级概念

结构化输出

在某些情况下,您可能希望代理以特定格式返回输出。LangChain 提供了一种简单通用的方法,通过 `responseFormat` 参数来实现这一点。
import * as z from "zod";
import { createAgent } from "langchain";

const ContactInfo = z.object({
  name: z.string(),
  email: z.string(),
  phone: z.string(),
});

const agent = createAgent({
  model: "gpt-4o",
  responseFormat: ContactInfo,
});

const result = await agent.invoke({
  messages: [
    {
      role: "user",
      content: "Extract contact info from: John Doe, john@example.com, (555) 123-4567",
    },
  ],
});

console.log(result.structuredResponse);
// {
//   name: 'John Doe',
//   email: 'john@example.com',
//   phone: '(555) 123-4567'
// }
要了解结构化输出,请参阅结构化输出

内存

代理通过消息状态自动维护对话历史。您还可以配置代理使用自定义状态模式来记住对话期间的额外信息。 存储在状态中的信息可以被认为是代理的短期记忆
import * as z from "zod";
import { MessagesZodState } from "@langchain/langgraph";
import { createAgent, type BaseMessage } from "langchain";

const customAgentState = z.object({
  messages: MessagesZodState.shape.messages,
  userPreferences: z.record(z.string(), z.string()),
});

const CustomAgentState = createAgent({
  model: "gpt-4o",
  tools: [],
  stateSchema: customAgentState,
});
要了解有关内存的更多信息,请参阅内存。有关实现跨会话持久的长期内存的信息,请参阅长期内存

流式处理

我们已经了解了如何使用 `invoke` 调用代理以获取最终响应。如果代理执行多个步骤,这可能需要一段时间。为了显示中间进度,我们可以实时流回消息。
const stream = await agent.stream(
  {
    messages: [{
      role: "user",
      content: "Search for AI news and summarize the findings"
    }],
  },
  { streamMode: "values" }
);

for await (const chunk of stream) {
  // Each chunk contains the full state at that point
  const latestMessage = chunk.messages.at(-1);
  if (latestMessage?.content) {
    console.log(`Agent: ${latestMessage.content}`);
  } else if (latestMessage?.tool_calls) {
    const toolCallNames = latestMessage.tool_calls.map((tc) => tc.name);
    console.log(`Calling tools: ${toolCallNames.join(", ")}`);
  }
}
有关流式传输的更多详细信息,请参阅流式传输

中间件

中间件为在执行的不同阶段定制代理行为提供了强大的可扩展性。您可以使用中间件来
  • 在调用模型之前处理状态(例如,消息修剪、上下文注入)
  • 修改或验证模型的响应(例如,防护措施、内容过滤)
  • 使用自定义逻辑处理工具执行错误
  • 根据状态或上下文实现动态模型选择
  • 添加自定义日志记录、监控或分析
中间件无缝集成到代理的执行图,允许您在关键点拦截和修改数据流,而无需更改核心代理逻辑。
有关中间件的全面文档,包括 `beforeModel`、`afterModel` 和 `wrapToolCall` 等钩子,请参阅中间件

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