跳转到内容

上下文管理

“上下文”是一个含义很丰富的术语。通常你会关心两大类上下文:

  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.
}
main().catch((error) => {
console.error(error);
process.exit(1);
});

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

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

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

当调用 LLM 时,它只能看到对话历史中的数据。若要提供额外信息,你有以下几种方式:

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