运行时 (Runtime)
概述
LangChain 的 createAgent 底层运行在 LangGraph 的运行时上。
LangGraph 暴露了一个 Runtime 对象,包含以下信息:
- Context(上下文):静态信息,如用户 ID、数据库连接或智能体调用的其他依赖项
- Store(存储):用于长期记忆的 BaseStore 实例
- Stream writer(流写入器):用于通过
"custom"流模式流式传输信息的对象
提示:运行时上下文是你在智能体中传递数据的方式。与其将内容存储在全局状态中,你可以将值(如数据库连接、用户会话或配置)附加到上下文中,并在工具和中间件内部访问它们。这使得代码保持无状态、可测试和可复用。
访问
使用 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-4o",
tools: [
/* ... */
],
contextSchema,
});
const result = await agent.invoke(
{ messages: [{ role: "user", content: "我叫什么名字?" }] },
{ context: { userName: "张三" } }
);
在工具中
你可以在工具内部访问运行时信息来:
- 访问上下文
- 读取或写入长期记忆
- 写入自定义流(例如,工具进度/更新)
使用 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");
}
let preferences = "用户喜欢简短礼貌的邮件。";
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: "获取用户的邮件偏好设置。",
schema: z.object({}),
}
);
在中间件中
你可以在中间件中访问运行时信息来创建动态提示、修改消息或根据用户上下文控制智能体行为。
使用 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");
}
const systemMsg = `你是一个有帮助的助手。请称呼用户为 ${userName}。`;
return {
messages: [new SystemMessage(systemMsg), ...state.messages],
};
},
});
// 日志中间件
const loggingMiddleware = createMiddleware({
name: "Logging",
contextSchema,
beforeModel: (state, runtime) => {
console.log(`正在为用户处理请求: ${runtime.context?.userName}`);
return;
},
afterModel: (state, runtime) => {
console.log(`已完成用户请求: ${runtime.context?.userName}`);
return;
},
});
const agent = createAgent({
model: "gpt-4o",
tools: [
/* ... */
],
middleware: [dynamicPromptMiddleware, loggingMiddleware],
contextSchema,
});
const result = await agent.invoke(
{ messages: [{ role: "user", content: "我叫什么名字?" }] },
{ context: { userName: "张三" } }
);