> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 运行时

## 概述

LangChain 的 `createAgent` 底层运行在 LangGraph 的运行时上。

LangGraph 暴露了一个 [`Runtime`](https://reference.langchain.com/javascript/langchain/index/Runtime) 对象，包含以下信息：

1. **上下文**：静态信息，如用户ID、数据库连接或代理调用的其他依赖项
2. **存储**：一个 [BaseStore](https://reference.langchain.com/javascript/langchain-core/stores/BaseStore) 实例，用于[长期记忆](/oss/javascript/langchain/long-term-memory)
3. **流写入器**：一个用于通过 `"custom"` 流模式传输信息的对象
4. **执行信息**：当前执行的身份和重试信息（线程ID、运行ID、尝试次数）
5. **服务器信息**：在 LangGraph Server 上运行时的特定元数据（助手ID、图ID、已认证用户）

<Tip>
  运行时上下文是您在代理中传递数据的方式。您无需将内容存储在全局状态中，而是可以将值（如数据库连接、用户会话或配置）附加到上下文，并在工具和中间件中访问它们。这使得内容保持无状态、可测试和可重用。
</Tip>

您可以在[工具](#工具内部)和[中间件](#中间件内部)中访问运行时信息。

## 访问方式

使用 `createAgent` 创建代理时，您可以指定 `contextSchema` 来定义存储在代理 [`Runtime`](https://reference.langchain.com/javascript/langchain/index/Runtime) 中的 `context` 的结构。

调用代理时，传递 `context` 参数并包含运行的相关配置：

```ts theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import * as z from "zod";
import { createAgent } from "langchain";

const contextSchema = z.object({ // [!code highlight]
  userName: z.string(), // [!code highlight]
}); // [!code highlight]

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

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

### 工具内部

您可以在工具内部访问运行时信息，以：

* 访问上下文
* 读取或写入长期记忆
* 写入[自定义流](/oss/javascript/langchain/streaming#custom-updates)（例如，工具进度/更新）

使用 `runtime` 参数在工具内部访问 [`Runtime`](https://reference.langchain.com/javascript/langchain/index/Runtime) 对象。

```ts theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import * as z from "zod";
import { tool } from "langchain";
import { type ToolRuntime } from "@langchain/core/tools"; // [!code highlight]

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

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

    let preferences = "The user prefers you to write a brief and polite email.";
    if (runtime.store) { // [!code highlight]
      const memory = await runtime.store?.get(["users"], userName); // [!code highlight]
      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、已认证用户）：

```ts theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { tool } from "langchain";
import * as z from "zod";

const contextAwareTool = tool(
  async (_input, runtime) => {
    // 访问线程和运行ID
    const info = runtime.executionInfo;
    console.log(`Thread: ${info.threadId}, Run: ${info.runId}`);  // [!code highlight]

    // 访问服务器信息（仅在 LangGraph Server 上可用）
    const server = runtime.serverInfo;
    if (server != null) {
      console.log(`Assistant: ${server.assistantId}`);  // [!code highlight]
      if (server.user != null) {
        console.log(`User: ${server.user.identity}`);  // [!code highlight]
      }
    }

    return "done";
  },
  {
    name: "context_aware_tool",
    description: "A tool that uses execution and server info.",
    schema: z.object({}),
  }
);
```

当不在 LangGraph Server 上运行时（例如，在本地开发期间），`serverInfo` 为 `null`。

<Note>
  需要 `deepagents>=1.9.0`（或 `@langchain/langgraph>=1.2.8`）才能使用 `runtime.executionInfo` 和 `runtime.serverInfo`。
</Note>

### 中间件内部

您可以在中间件中访问运行时信息，以创建动态提示、修改消息或根据用户上下文控制代理行为。

使用 `runtime` 参数在中间件内部访问 [`Runtime`](https://reference.langchain.com/javascript/langchain/index/Runtime) 对象。

```ts theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import * as z from "zod";
import { createAgent, createMiddleware, SystemMessage } from "langchain";

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

// 动态提示中间件
const dynamicPromptMiddleware = createMiddleware({
  name: "DynamicPrompt",
  contextSchema,
  beforeModel: (state, runtime) => { // [!code highlight]
    const userName = runtime.context?.userName; // [!code highlight]
    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],
    };
  },
});

// 日志记录中间件
const loggingMiddleware = createMiddleware({
  name: "Logging",
  contextSchema,
  beforeModel: (state, runtime) => {  // [!code highlight]
    console.log(`Processing request for user: ${runtime.context?.userName}`);  // [!code highlight]
    return;
  },
  afterModel: (state, runtime) => {  // [!code highlight]
    console.log(`Completed request for user: ${runtime.context?.userName}`);  // [!code highlight]
    return;
  },
});

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

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

```

### 中间件内部的执行信息和服务器信息

中间件钩子也可以访问 `runtime.executionInfo` 和 `runtime.serverInfo`：

```ts theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { createMiddleware } from "langchain";

const authGate = createMiddleware({
  name: "AuthGate",
  beforeModel: (state, runtime) => {
    const server = runtime.serverInfo;
    if (server != null && server.user == null) {  // [!code highlight]
      throw new Error("Authentication required");
    }
    console.log(`Thread: ${runtime.executionInfo.threadId}`);  // [!code highlight]
    return;
  },
});
```

<Note>
  需要 `deepagents>=1.9.0`（或 `@langchain/langgraph>=1.2.8`）。
</Note>

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档连接](/use-these-docs)到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/langchain/runtime.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
