跳转到内容

上下文管理

“上下文”一词有多重含义。这里主要有两类你需要关心的上下文:

  1. 本地上下文:你的代码在一次运行期间可访问的内容,例如工具所需的依赖或数据、onHandoff 之类的回调,以及生命周期钩子。
  2. 智能体/LLM 上下文:语言模型在生成回复时可见的内容。

本地上下文由 RunContext<T> 类型表示。你可以创建任意对象来保存状态或依赖,并将其传给 Runner.run()。所有工具调用和钩子都会接收一个 RunContext 包装器,以便读取或修改该对象。

本地上下文示例
import { Agent, run, RunContext, tool } from '@openai/agents';
import { z } from 'zod';
interface UserInfo {
name: string;
uid: number;
}
const fetchUserAge = tool({
name: 'fetch_user_age',
description: 'Return the age of the current user',
parameters: z.object({}),
execute: async (
_args,
runContext?: RunContext<UserInfo>,
): Promise<string> => {
return `User ${runContext?.context.name} is 47 years old`;
},
});
async function main() {
const userInfo: UserInfo = { name: 'John', uid: 123 };
const agent = new Agent<UserInfo>({
name: 'Assistant',
tools: [fetchUserAge],
});
const result = await run(agent, 'What is the age of the user?', {
context: userInfo,
});
console.log(result.finalOutput);
// The user John is 47 years old.
}
if (require.main === module) {
main().catch(console.error);
}

参与同一次运行的每个智能体、工具和钩子,必须使用相同类型的上下文。

本地上下文适用于以下场景:

  • 有关本次运行的数据(用户名、ID 等)
  • 日志器或数据获取器等依赖
  • 帮助函数

当调用 LLM 时,它只能看到会话历史。若要提供额外信息,你可以:

  1. 将其添加到智能体的 instructions——也称系统或开发者消息。它可以是静态字符串,或接收上下文并返回字符串的函数。
  2. 在调用 Runner.run() 时包含到 input 中。与 instructions 技术类似,但允许你将消息放在更低的指令链位置。
  3. 通过函数工具暴露,使 LLM 可按需获取数据。
  4. 使用检索或 Web 搜索工具,将回复基于来自文件、数据库或网络的相关数据。