跳到主要内容

文档索引

在以下地址获取完整的文档索引:https://docs.langchain.org.cn/llms.txt

在进一步探索之前,请使用此文件发现所有可用页面。

概览

LangChain 的 createAgent 在底层运行于 LangGraph 的运行时之上。 LangGraph 提供了一个 Runtime 对象,包含以下信息:
  1. 上下文 (Context):静态信息,如用户 ID、数据库连接或其他代理调用所需的依赖项
  2. 存储 (Store):一个用于长期记忆BaseStore 实例
  3. 流写入器 (Stream writer):一个用于通过 "custom" 流模式传输信息的对象
  4. 执行信息 (Execution info):当前执行的标识和重试信息(线程 ID、运行 ID、尝试次数)
  5. 服务器信息 (Server info):在 LangGraph Server 上运行时特有的元数据(助手 ID、图 ID、已认证用户)
运行时上下文是你贯穿代理数据流的方式。与其将内容存储在全局状态中,不如将值(例如数据库连接、用户会话或配置)附加到上下文中,并在工具和中间件内部访问它们。这使得代码保持无状态、可测试且可复用。
你可以在工具中间件内部访问运行时信息。

权限

使用 createAgent 创建代理时,你可以指定 contextSchema 来定义存储在代理 Runtime 中的 context 结构。 调用代理时,请传入 context 参数及运行所需的相关配置:
import * as z from "zod";
import { createAgent } from "langchain";

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

const agent = createAgent({
  model: "gpt-5.4",
  tools: [
    /* ... */
  ],
  contextSchema,
});

const result = await agent.invoke(
  { messages: [{ role: "user", content: "What's my name?" }] },
  { context: { userName: "John Smith" } }
);

工具内部

你可以在工具内部访问运行时信息以:
  • 访问上下文
  • 读取或写入长期记忆
  • 写入自定义流(例如:工具进度 / 更新)
使用 runtime 参数在工具内部访问 Runtime 对象。
import * as z from "zod";
import { tool } from "langchain";
import { type ToolRuntime } from "@langchain/core/tools";

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

const fetchUserEmailPreferences = tool(
  async (_, runtime: ToolRuntime<any, typeof contextSchema>) => {
    const userName = runtime.context?.userName;
    if (!userName) {
      throw new Error("userName is required");
    }

    let preferences = "The user prefers you to write a brief and polite email.";
    if (runtime.store) {
      const memory = await runtime.store?.get(["users"], userName);
      if (memory) {
        preferences = memory.value.preferences;
      }
    }
    return preferences;
  },
  {
    name: "fetch_user_email_preferences",
    description: "Fetch the user's email preferences.",
    schema: z.object({}),
  }
);

工具内的执行信息与服务器信息

通过 runtime.executionInfo 访问执行标识(线程 ID、运行 ID),并在 LangGraph Server 上运行时,通过 runtime.serverInfo 访问服务器特定元数据(助手 ID、已认证用户)。
import { tool } from "langchain";
import * as z from "zod";

const contextAwareTool = tool(
  async (_input, runtime) => {
    // Access thread and run IDs
    const info = runtime.executionInfo;
    console.log(`Thread: ${info.threadId}, Run: ${info.runId}`);

    // Access server info (only available on LangGraph Server)
    const server = runtime.serverInfo;
    if (server != null) {
      console.log(`Assistant: ${server.assistantId}`);
      if (server.user != null) {
        console.log(`User: ${server.user.identity}`);
      }
    }

    return "done";
  },
  {
    name: "context_aware_tool",
    description: "A tool that uses execution and server info.",
    schema: z.object({}),
  }
);
当不在 LangGraph Server 上运行(例如本地开发期间)时,serverInfonull
访问 runtime.executionInforuntime.serverInfo 需要 deepagents>=1.9.0(或 @langchain/langgraph>=1.2.8)。

中间件内部

你可以在中间件中访问运行时信息,以创建动态提示词、修改消息或根据用户上下文控制代理行为。 在中间件内部,使用 runtime 参数访问 Runtime 对象。
import * as z from "zod";
import { createAgent, createMiddleware, SystemMessage } from "langchain";

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

// Dynamic prompt middleware
const dynamicPromptMiddleware = createMiddleware({
  name: "DynamicPrompt",
  contextSchema,
  beforeModel: (state, runtime) => {
    const userName = runtime.context?.userName;
    if (!userName) {
      throw new Error("userName is required");
    }

    const systemMsg = `You are a helpful assistant. Address the user as ${userName}.`;
    return {
      messages: [new SystemMessage(systemMsg), ...state.messages],
    };
  },
});

// Logging middleware
const loggingMiddleware = createMiddleware({
  name: "Logging",
  contextSchema,
  beforeModel: (state, runtime) => {
    console.log(`Processing request for user: ${runtime.context?.userName}`);
    return;
  },
  afterModel: (state, runtime) => {
    console.log(`Completed request for user: ${runtime.context?.userName}`);
    return;
  },
});

const agent = createAgent({
  model: "gpt-5.4",
  tools: [
    /* ... */
  ],
  middleware: [dynamicPromptMiddleware, loggingMiddleware],
  contextSchema,
});

const result = await agent.invoke(
  { messages: [{ role: "user", content: "What's my name?" }] },
  { context: { userName: "John Smith" } }
);

中间件内的执行信息与服务器信息

中间件钩子也可以访问 runtime.executionInforuntime.serverInfo
import { createMiddleware } from "langchain";

const authGate = createMiddleware({
  name: "AuthGate",
  beforeModel: (state, runtime) => {
    const server = runtime.serverInfo;
    if (server != null && server.user == null) {
      throw new Error("Authentication required");
    }
    console.log(`Thread: ${runtime.executionInfo.threadId}`);
    return;
  },
});
需要 deepagents>=1.9.0(或 @langchain/langgraph>=1.2.8)。

© . This site is unofficial and not affiliated with LangChain, Inc.