会话
会话为 Agents SDK 提供了一个持久化内存层。将任何实现了 Session 接口的对象传给 Runner.run,其余交给 SDK 处理。当会话存在时,运行器会自动:
- 获取此前存储的对话项,并在下一轮次前置这些内容。
- 在每次运行完成后持久化新的用户输入与助手输出。
- 保持会话可用于后续轮次,无论是用新的用户文本调用运行器,还是从中断的
RunState恢复。
这消除了手动调用 toInputList() 或在轮次之间拼接历史的需求。TypeScript SDK 自带两种实现:用于 Conversations API 的 OpenAIConversationsSession,以及用于本地开发的 MemorySession。由于它们共享 Session 接口,您可以插入自定义存储后端。若想获得除 Conversations API 之外的灵感,可探索 examples/memory/ 下的示例会话后端(Prisma、文件后端等)。当使用 OpenAI Responses 模型时,用 OpenAIResponsesCompactionSession 包裹任意会话以通过 responses.compact 自动缩短已存储的对话记录。
提示:要运行本页中的
OpenAIConversationsSession示例,请设置OPENAI_API_KEY环境变量(或在构造会话时提供apiKey),以便 SDK 能调用 Conversations API。
使用 OpenAIConversationsSession 将内存与 Conversations API 同步,或替换为任意其他 Session 实现。
import { Agent, OpenAIConversationsSession, run } from '@openai/agents';
const agent = new Agent({ name: 'TourGuide', instructions: 'Answer with compact travel facts.',});
// Any object that implements the Session interface works here. This example uses// the built-in OpenAIConversationsSession, but you can swap in a custom Session.const session = new OpenAIConversationsSession();
const firstTurn = await run(agent, 'What city is the Golden Gate Bridge in?', { session,});console.log(firstTurn.finalOutput); // "San Francisco"
const secondTurn = await run(agent, 'What state is it in?', { session });console.log(secondTurn.finalOutput); // "California"复用同一个会话实例可确保在每一轮之前,智能体都能收到完整的对话历史,并自动持久化新条目。切换到不同的 Session 实现无需改动其他代码。
OpenAIConversationsSession 构造函数选项:
| 选项 | 类型 | 说明 |
|---|---|---|
conversationId | string | 复用已有会话,而不是按需创建。 |
client | OpenAI | 传入已预配置的 OpenAI 客户端。 |
apiKey | string | 在内部创建 OpenAI 客户端时使用的 API key。 |
baseURL | string | OpenAI 兼容端点的基础 URL。 |
organization | string | 请求所用的 OpenAI 组织 ID。 |
project | string | 请求所用的 OpenAI 项目 ID。 |
运行器如何使用会话
Section titled “运行器如何使用会话”- 在每次运行之前,它会检索会话历史,与新一轮输入合并,并将合并后的列表传给智能体。
- 在非流式运行之后,通过一次
session.addItems()调用即可持久化最新一轮中的原始用户输入和模型输出。 - 对于流式传输运行,它会先写入用户输入,并在该轮完成后追加流式输出。
- 当从
RunResult.state恢复(审批或其他中断)时,继续传入同一个session。恢复的轮次会被加入内存,无需重新准备输入。
检查与编辑历史
Section titled “检查与编辑历史”会话提供简单的 CRUD 帮助器,便于构建“撤销”“清空聊天”或审计等功能。
import { OpenAIConversationsSession } from '@openai/agents';import type { AgentInputItem } from '@openai/agents-core';
// Replace OpenAIConversationsSession with any other Session implementation that// supports get/add/pop/clear if you store history elsewhere.const session = new OpenAIConversationsSession({ conversationId: 'conv_123', // Resume an existing conversation if you have one.});
const history = await session.getItems();console.log(`Loaded ${history.length} prior items.`);
const followUp: AgentInputItem[] = [ { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Let’s continue later.' }], },];await session.addItems(followUp);
const undone = await session.popItem();
if (undone?.type === 'message') { console.log(undone.role); // "user"}
await session.clearSession();session.getItems() 会返回已存储的 AgentInputItem[]。调用 popItem() 可移除最后一个条目——在重新运行智能体前用于用户更正很有用。
实现 Session 接口,以 Redis、DynamoDB、SQLite 或其他数据存储来支撑内存。只需要五个异步方法。
import { Agent, run } from '@openai/agents';import { randomUUID } from '@openai/agents-core/_shims';import { getLogger } from '@openai/agents-core';import type { AgentInputItem, Session } from '@openai/agents-core';
/** * Minimal example of a Session implementation; swap this class for any storage-backed version. */export class CustomMemorySession implements Session { private readonly sessionId: string; private readonly logger: ReturnType<typeof getLogger>;
private items: AgentInputItem[];
constructor( options: { sessionId?: string; initialItems?: AgentInputItem[]; logger?: ReturnType<typeof getLogger>; } = {}, ) { this.sessionId = options.sessionId ?? randomUUID(); this.items = options.initialItems ? options.initialItems.map(cloneAgentItem) : []; this.logger = options.logger ?? getLogger('openai-agents:memory-session'); }
async getSessionId(): Promise<string> { return this.sessionId; }
async getItems(limit?: number): Promise<AgentInputItem[]> { if (limit === undefined) { const cloned = this.items.map(cloneAgentItem); this.logger.debug( `Getting items from memory session (${this.sessionId}): ${JSON.stringify(cloned)}`, ); return cloned; } if (limit <= 0) { return []; } const start = Math.max(this.items.length - limit, 0); const items = this.items.slice(start).map(cloneAgentItem); this.logger.debug( `Getting items from memory session (${this.sessionId}): ${JSON.stringify(items)}`, ); return items; }
async addItems(items: AgentInputItem[]): Promise<void> { if (items.length === 0) { return; } const cloned = items.map(cloneAgentItem); this.logger.debug( `Adding items to memory session (${this.sessionId}): ${JSON.stringify(cloned)}`, ); this.items = [...this.items, ...cloned]; }
async popItem(): Promise<AgentInputItem | undefined> { if (this.items.length === 0) { return undefined; } const item = this.items[this.items.length - 1]; const cloned = cloneAgentItem(item); this.logger.debug( `Popping item from memory session (${this.sessionId}): ${JSON.stringify(cloned)}`, ); this.items = this.items.slice(0, -1); return cloned; }
async clearSession(): Promise<void> { this.logger.debug(`Clearing memory session (${this.sessionId})`); this.items = []; }}
function cloneAgentItem<T extends AgentInputItem>(item: T): T { return structuredClone(item);}
const agent = new Agent({ name: 'MemoryDemo', instructions: 'Remember the running total.',});
// Using the above custom memory session implementation hereconst session = new CustomMemorySession({ sessionId: 'session-123-4567',});
const first = await run(agent, 'Add 3 to the total.', { session });console.log(first.finalOutput);
const second = await run(agent, 'Add 4 more.', { session });console.log(second.finalOutput);自定义会话可用于实施保留策略、添加加密,或在持久化前为每次对话轮次附加元数据。
控制历史与新项的合并方式
Section titled “控制历史与新项的合并方式”当您将 AgentInputItem 数组作为运行输入时,提供一个 sessionInputCallback,以确定性地将其与存储的历史合并。运行器会加载现有历史,在模型调用之前调用您的回调,并将返回的数组作为该轮的完整输入传给模型。此钩子非常适合裁剪旧条目、对工具结果去重,或仅突出您希望模型看到的上下文。
import { Agent, OpenAIConversationsSession, run } from '@openai/agents';import type { AgentInputItem } from '@openai/agents-core';
const agent = new Agent({ name: 'Planner', instructions: 'Track outstanding tasks before responding.',});
// Any Session implementation can be passed here; customize storage as needed.const session = new OpenAIConversationsSession();
const todoUpdate: AgentInputItem[] = [ { type: 'message', role: 'user', content: [ { type: 'input_text', text: 'Add booking a hotel to my todo list.' }, ], },];
await run(agent, todoUpdate, { session, // function that combines session history with new input items before the model call sessionInputCallback: (history, newItems) => { const recentHistory = history.slice(-8); return [...recentHistory, ...newItems]; },});对于字符串输入,运行器会自动合并历史,因此该回调是可选的。
处理审批与可恢复运行
Section titled “处理审批与可恢复运行”Human-in-the-loop 流程通常会暂停运行以等待审批:
const result = await runner.run(agent, 'Search the itinerary', { session, stream: true,});
if (result.requiresApproval) { // ... collect user feedback, then resume the agent in a later turn const continuation = await runner.run(agent, result.state, { session }); console.log(continuation.finalOutput);}当您从先前的 RunState 恢复时,新一轮会追加到同一条内存记录中,从而保留单一的对话历史。人工干预(HITL)流程完全兼容——审批检查点仍通过 RunState 往返,而会话保持完整的对话记录。
自动压缩 OpenAI Responses 历史
Section titled “自动压缩 OpenAI Responses 历史”OpenAIResponsesCompactionSession 会装饰任意 Session,并依赖 OpenAI Responses API 来保持对话记录简短。在每次持久化轮次后,运行器会将最新的 responseId 传入 runCompaction,当您的决策钩子返回 true 时,它会调用 responses.compact。默认触发条件是在累计至少 10 个非用户条目后压缩;通过重写 shouldTriggerCompaction,您可以基于 token 数或自定义启发式来决策。该装饰器会清空并用压缩后的输出重写底层会话,因此请避免将其与 OpenAIConversationsSession 搭配使用,后者使用不同的服务器管理历史流程。
import { Agent, MemorySession, OpenAIResponsesCompactionSession, run,} from '@openai/agents';
const agent = new Agent({ name: 'Support', instructions: 'Answer briefly and keep track of prior context.', model: 'gpt-5.2',});
// Wrap any Session to trigger responses.compact once history grows beyond your threshold.const session = new OpenAIResponsesCompactionSession({ // You can pass any Session implementation except OpenAIConversationsSession underlyingSession: new MemorySession(), // (optional) The model used for calling responses.compact API model: 'gpt-5.2', // (optional) your custom logic here shouldTriggerCompaction: ({ compactionCandidateItems }) => { return compactionCandidateItems.length >= 12; },});
await run(agent, 'Summarize order #8472 in one sentence.', { session });await run(agent, 'Remind me of the shipping address.', { session });
// Compaction runs automatically after each persisted turn. You can also force it manually.await session.runCompaction({ force: true });OpenAIResponsesCompactionSession 构造函数选项:
| 选项 | 类型 | 说明 |
|---|---|---|
client | OpenAI | 用于 responses.compact 的 OpenAI 客户端。 |
underlyingSession | Session | 用于清空/重写为压缩条目的底层会话存储(不能为 OpenAIConversationsSession)。 |
model | OpenAI.ResponsesModel | 用于压缩请求的模型。 |
compactionMode | 'auto' | 'previous_response_id' | 'input' | 控制压缩使用服务器响应链式模式还是本地输入条目。 |
shouldTriggerCompaction | (context) => boolean | Promise<boolean> | 基于 responseId、compactionMode、候选条目与当前会话条目的自定义触发钩子。 |
runCompaction(args) 选项:
| 选项 | 类型 | 说明 |
|---|---|---|
responseId | string | 用于 previous_response_id 模式的最新 Responses API 响应 ID。 |
compactionMode | 'auto' | 'previous_response_id' | 'input' | 可选:按调用覆盖已配置的模式。 |
store | boolean | 指示上一次运行是否存储了服务器状态。 |
force | boolean | 跳过 shouldTriggerCompaction,立即执行压缩。 |
面向低延迟流式传输的手动压缩
Section titled “面向低延迟流式传输的手动压缩”压缩会清空并重写底层会话,因此 SDK 会在完成压缩后才解析流式运行。如果压缩较重,则在最后一个输出 token 后,result.completed 可能会再等待几秒。对于低延迟流式传输或更快的轮次交替,禁用自动压缩,并在轮次之间(或空闲时)自行调用 runCompaction。
import { Agent, MemorySession, OpenAIResponsesCompactionSession, run,} from '@openai/agents';
const agent = new Agent({ name: 'Support', instructions: 'Answer briefly and keep track of prior context.', model: 'gpt-5.2',});
// Disable auto-compaction to avoid delaying stream completion.const session = new OpenAIResponsesCompactionSession({ underlyingSession: new MemorySession(), shouldTriggerCompaction: () => false,});
const result = await run(agent, 'Share the latest ticket update.', { session, stream: true,});
// Wait for the streaming run to finish before compacting.await result.completed;
// Choose force based on your own thresholds or heuristics, between turns or during idle time.await session.runCompaction({ force: true });您可以随时调用 runCompaction({ force: true }) 在归档或交接前缩短历史。使用 DEBUG=openai-agents:openai:compaction 启用调试日志以追踪压缩决策。