会话
会话为 Agents SDK 提供了一个持久化记忆层。向 Runner.run 提供任何实现 Session 接口的对象,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。
如果希望由 SDK 管理客户端记忆,请使用会话。如果您已经通过 conversationId 或 previousResponseId 使用由 OpenAI 服务器管理的状态,通常无需再为同一段对话历史记录使用会话。
使用 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 实现时,无需更改任何其他代码。
对于本地演示、测试或进程本地聊天状态,MemorySession 提供相同的接口,且无需与 OpenAI 通信:
import { Agent, MemorySession, run } from '@openai/agents';
const agent = new Agent({ name: 'TourGuide', instructions: 'Answer with compact travel facts.',});
const session = new MemorySession();const result = await run(agent, 'What city is the Golden Gate Bridge in?', { session,});
console.log(result.finalOutput);OpenAIConversationsSession 构造函数选项:
| 选项 | 类型 | 说明 |
|---|---|---|
conversationId | string | 复用现有对话,而不是按需创建新对话。 |
client | OpenAI | 传入预先配置的 OpenAI 客户端。 |
apiKey | string | 创建内部 OpenAI 客户端时使用的 API 密钥。 |
baseURL | string | OpenAI 兼容端点的基础 URL。 |
organization | string | 请求所使用的 OpenAI 组织 ID。 |
project | string | 请求所使用的 OpenAI 项目 ID。 |
MemorySession 构造函数选项:
| 选项 | 类型 | 说明 |
|---|---|---|
sessionId | string | 用于日志或测试的稳定标识符。默认自动生成。 |
initialItems | AgentInputItem[] | 使用现有历史记录初始化会话。 |
logger | Logger | 覆盖用于调试输出的日志记录器。 |
MemorySession 将所有内容存储在本地进程内存中,因此进程退出时会重置。
如果需要在构造会话之前预先创建对话 ID,请使用 startOpenAIConversationsSession(client?),并将返回的 ID 作为 conversationId 传入。
核心会话行为
Section titled “核心会话行为”运行器的会话使用方式
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() 可以移除最后一个条目,这适用于在重新运行智能体之前更正用户输入。
自定义存储与合并行为
Section titled “自定义存储与合并行为”实现 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 “使用运行上下文限定自定义会话范围”当自定义会话需要使用当前 RunContext 进行存储路由或添加元数据时,请实现 RunContextAwareSession<TContext>,并将 acceptsRunContext 设置为 true。在一次运行期间,运行器会将同一个上下文实例传递给所有历史记录操作,包括流式持久化和恢复后的运行。仅实现 Session 的会话会保留现有方法签名,调用时不会传入额外参数。
import { Agent, run, type AgentInputItem, type RunContext, type RunContextAwareSession,} from '@openai/agents';
type TenantContext = { tenantId: string;};
class TenantSession implements RunContextAwareSession<TenantContext> { readonly acceptsRunContext = true; private readonly itemsByTenant = new Map<string, AgentInputItem[]>();
async getSessionId(): Promise<string> { return 'shared-tenant-session'; }
async getItems( limit?: number, runContext?: RunContext<TenantContext>, ): Promise<AgentInputItem[]> { const items = this.getTenantItems(runContext); return limit === undefined ? [...items] : items.slice(-limit); }
async addItems( items: AgentInputItem[], runContext?: RunContext<TenantContext>, ): Promise<void> { this.getTenantItems(runContext).push(...items); }
async popItem( runContext?: RunContext<TenantContext>, ): Promise<AgentInputItem | undefined> { return this.getTenantItems(runContext).pop(); }
async clearSession(runContext?: RunContext<TenantContext>): Promise<void> { this.itemsByTenant.set(this.getTenantId(runContext), []); }
private getTenantItems( runContext: RunContext<TenantContext> | undefined, ): AgentInputItem[] { const tenantId = this.getTenantId(runContext); const items = this.itemsByTenant.get(tenantId) ?? []; this.itemsByTenant.set(tenantId, items); return items; }
private getTenantId( runContext: RunContext<TenantContext> | undefined, ): string { if (!runContext) { throw new Error('TenantSession requires a run context.'); } return runContext.context.tenantId; }}
const agent = new Agent<TenantContext>({ name: 'Assistant', instructions: 'Reply concisely.',});const session = new TenantSession();
await run(agent, 'Remember that my favorite color is green.', { context: { tenantId: 'tenant-a' }, session,});
await run(agent, 'What is my favorite color?', { context: { tenantId: 'tenant-a' }, session,});OpenAIResponsesCompactionSession 不会将运行上下文转发给底层会话。如果要结合使用这些功能,请为每个上下文范围保留一个压缩会话实例。
历史记录与新条目的合并控制
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]; },});对于字符串输入,运行器会自动合并历史记录,因此回调是可选的。仅当本轮输入已经是条目数组时,才会运行该回调。
如果您还使用 conversationId 或 previousResponseId,请确保回调结果至少保留当前轮次的一个新条目。这些由服务器管理的 API 依赖当前轮次的增量。如果回调删除了所有新条目,SDK 会恢复原始的新输入并记录警告,而不是发送空增量。
审批与可恢复运行的处理
Section titled “审批与可恢复运行的处理”人工干预流程通常会暂停运行以等待审批:
import { Agent, MemorySession, Runner } from '@openai/agents';
const agent = new Agent({ name: 'Trip Planner', instructions: 'Plan trips and ask for approval before booking anything.',});
const runner = new Runner();const session = new MemorySession();
const result = await runner.run(agent, 'Search the itinerary', { session,});
if (result.interruptions?.length) { // ... collect user feedback, then resume the agent in a later turn. for (const interruption of result.interruptions) { result.state.approve(interruption); }
const continuation = await runner.run(agent, result.state, { session }); console.log(continuation.finalOutput);}从之前的 RunState 恢复时,新轮次会追加到同一条记忆记录中,从而保留单一的对话历史记录。人工干预(HITL)流程仍完全兼容:审批检查点依然会通过 RunState 往返传递,而会话则持续维护完整的对话历史记录。
高级:历史记录压缩
Section titled “高级:历史记录压缩”OpenAI Responses 历史记录的自动压缩
Section titled “OpenAI Responses 历史记录的自动压缩”OpenAIResponsesCompactionSession 可以装饰任何 Session,并使用 OpenAI Responses API 将较长的已存储历史记录替换为更短但等效的对话条目列表。每次持久化轮次后,运行器都会将最新的 responseId 传入 runCompaction;当您的决策钩子返回 true 时,它会调用 responses.compact。根据 compactionMode,请求会基于最新的 Responses API 响应链或会话当前条目构建。默认触发条件是在至少积累 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.4',});
// 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.4', // (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 | 用于压缩请求的模型。默认使用 SDK 当前的默认 OpenAI 模型。 |
compactionMode | 'auto' | 'previous_response_id' | 'input' | 控制压缩使用服务器响应链还是本地输入条目。 |
shouldTriggerCompaction | (context) => boolean | Promise<boolean> | 自定义触发钩子,根据 responseId、compactionMode、候选条目和当前会话条目作出判断。 |
当您已经使用 Responses API 响应 ID 串联不同轮次时, compactionMode: 'previous_response_id' 非常有用。compactionMode: 'input' 则会基于当前会话条目重新构建压缩请求,适用于响应链不可用,或您希望将底层会话内容作为事实来源的情况。
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.4',});
// 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 启用调试日志,以追踪压缩决策。