Thanks to visit codestin.com
Credit goes to openai.github.io

跳转到内容

上下文管理

“Context”一词含义较多。通常有两大类你需要关注的上下文:

  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 搜索工具,将响应基于来自文件、数据库或网页的相关数据。