概览

LangChain 的 createAgent 底层运行在 LangGraph runtime 之上。 LangGraph 暴露一个 Runtime 对象,其中包含以下信息:
  1. Context:代理调用的静态信息,例如用户 ID、数据库连接或其他依赖
  2. Store:用于 long-term memoryBaseStore 实例
  3. Stream writer:用于通过 "custom" stream mode 流式传输信息的对象
  4. Execution info:当前执行的身份和重试信息(thread ID、run ID、attempt number)
  5. Server info:在 LangGraph Server 上运行时的服务器特定元数据(assistant ID、graph ID、authenticated user)
Runtime context 是你在代理中传递数据的方式。与其把内容存储在全局状态中,不如将数据库连接、用户会话或配置等值附加到 context,并在工具和 middleware 中访问它们。这样可以保持无状态、可测试和可复用。
你可以在 toolsmiddleware 中访问 runtime 信息。

访问

使用 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 信息,用于:
  • 访问 context
  • 读取或写入长期记忆
  • 写入 custom stream(例如工具进度/更新)
使用 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({}),
  }
);

工具中的 execution info 和 server info

在 LangGraph Server 上运行时,通过 runtime.executionInfo 访问执行身份(thread ID、run ID),并通过 runtime.serverInfo 访问服务器特定元数据(assistant ID、authenticated user):
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)。

在 middleware 中

你可以在 middleware 中访问 runtime 信息,以创建动态 prompts、修改消息,或根据用户 context 控制代理行为。 使用 runtime 参数在 middleware 中访问 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" } }
);

Middleware 中的 execution info 和 server info

Middleware hooks 也可以访问 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)。