运行时 (Runtime)
概述
LangChain 的 createAgent 底层运行在 LangGraph 的运行时之上。
LangGraph 暴露了一个包含以下信息的 Runtime 对象:
- Context:Agent 调用时的静态信息,如用户 ID、数据库连接或其他依赖项
- Store:用于长期记忆的 BaseStore 实例
- Stream writer:用于通过
"custom"流模式流式传输信息的对象 - Execution info:当前执行的标识与重试信息(线程 ID、运行 ID、尝试次数)
- Server info:在 LangGraph Server 上运行时特有的服务器元数据(助手 ID、图 ID、已认证用户)
TIP
运行时上下文(runtime context)是在 Agent 中传递数据的方式。你可以将数据(如数据库连接、用户会话或配置)附加到上下文并在工具和中间件内部访问它们,而不是将内容存储在全局状态中。这使得一切保持无状态、可测试且可复用。
访问
使用 createAgent 创建 Agent 时,你可以指定 contextSchema 来定义存储在 Agent Runtime 中的 context 结构。
在调用 Agent 时,传入包含该次运行相关配置的 context 参数:
import * as z from "zod";
import { createAgent } from "langchain";
const contextSchema = z.object({
userName: z.string(),
});
const agent = createAgent({
model: "gpt-5.5",
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({}),
}
);工具内的执行信息与服务器信息
在 LangGraph Server 上运行时,可以通过 runtime.executionInfo 访问执行标识(线程 ID、运行 ID),并通过 runtime.serverInfo 访问特定于服务器的元数据(助手 ID、已认证用户):
import { tool } from "langchain";
import * as z from "zod";
const contextAwareTool = tool(
async (_input, runtime) => {
// 访问线程 ID 和运行 ID
const info = runtime.executionInfo;
console.log(`Thread: ${info.threadId}, Run: ${info.runId}`);
// 访问服务器信息(仅在 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 上运行时(例如在本地开发期间),serverInfo 为 null。
NOTE
runtime.executionInfo 和 runtime.serverInfo 需要 deepagents>=1.9.0(或 @langchain/langgraph>=1.2.8)。
在中间件内部
你可以在中间件中访问运行时信息,以基于用户上下文创建动态提示词、修改消息或控制 Agent 行为。
在中间件内部使用 runtime 参数来访问 Runtime 对象。
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) => {
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],
};
},
});
// 日志记录中间件
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.5",
tools: [
/* ... */
],
middleware: [dynamicPromptMiddleware, loggingMiddleware],
contextSchema,
});
const result = await agent.invoke(
{ messages: [{ role: "user", content: "What's my name?" }] },
{ context: { userName: "John Smith" } }
);中间件内的执行信息与服务器信息
中间件钩子也可以访问 runtime.executionInfo 和 runtime.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;
},
});NOTE
需要 deepagents>=1.9.0(或 @langchain/langgraph>=1.2.8)。
