セッション
セッションは Agents SDK に 永続メモリ層 を提供します。Session インターフェースを実装する任意のオブジェクトを Runner.run に渡すだけで、残りは SDK が処理します。セッションがある場合、ランナーは自動的に次を行います。
- 以前に保存された会話アイテムを取得し、次のターンの先頭に付加する
- 各実行の完了後に、新しい ユーザー入力 と アシスタント出力 を永続化する
- 新しい ユーザー テキストでランナーを呼び出す場合も、中断された
RunStateから再開する場合も、将来のターンのためにセッションを利用可能に保つ
これにより、手動で toInputList() を呼び出したり、ターン間で履歴をつなぎ合わせたりする必要がなくなります。TypeScript SDK には 2 つの実装が同梱されています。Conversations API 用の OpenAIConversationsSession と、ローカル開発向けの MemorySession です。どちらも Session インターフェースを共有しているため、独自のストレージ バックエンドを差し込めます。Conversations API 以外の例としては、examples/memory/ 配下のサンプルセッションバックエンド(Prisma、ファイル永続化など)を参照してください。OpenAI Responses モデルを使う場合は、OpenAIResponsesCompactionSession で任意のセッションをラップすると、responses.compact により保存されたトランスクリプトを自動で縮約できます。
ヒント: このページの
OpenAIConversationsSessionの例を実行するには、OPENAI_API_KEY環境変数を設定する(またはセッション構築時にapiKeyを指定する)ことで、SDK が Conversations API を呼び出せるようにしてください。
クイックスタート
Section titled “クイックスタート”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 実装への切り替えでも、他のコード変更は不要です。
ランナーによるセッションの使用
Section titled “ランナーによるセッションの使用”- 各実行の前 にセッション履歴を取得し、新しいターンの入力とマージして、結合済みリストをエージェントに渡します
- 非ストリーミング実行の後 は 1 回の
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 など任意のデータストアでメモリを裏付けできます。必要なのは 5 つの非同期メソッドだけです。
import { Agent, run } from '@openai/agents';import { randomUUID } from '@openai/agents-core/_shims';import { logger, Logger } from '@openai/agents-core/dist/logger';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: Logger;
private items: AgentInputItem[];
constructor( options: { sessionId?: string; initialItems?: AgentInputItem[]; logger?: Logger; } = {}, ) { this.sessionId = options.sessionId ?? randomUUID(); this.items = options.initialItems ? options.initialItems.map(cloneAgentItem) : []; this.logger = options.logger ?? logger; }
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 から再開すると、新しいターンは同じメモリレコードに追記され、単一の会話履歴が保たれます。Human in the loop (人間の介入)(HITL)フローとの互換性は完全に維持されます。承認チェックポイントは引き続き RunState を経由してラウンドトリップし、セッション側はトランスクリプトを完全に保持します。
OpenAI Responses の履歴の自動圧縮
Section titled “OpenAI Responses の履歴の自動圧縮”OpenAIResponsesCompactionSession は任意の Session をデコレートし、OpenAI Responses API に依存してトランスクリプトを短く保ちます。各ターンの永続化後、ランナーは最新の responseId を runCompaction に渡します。これは、意思決定フックが true を返したときに responses.compact を呼び出します。デフォルトのトリガーは、少なくとも 10 個の ユーザー以外 のアイテムが蓄積された時点で 1 度コンパクト化します。shouldTriggerCompaction をオーバーライドして、トークン数や独自ヒューリスティクスに基づく判断に変更してください。デコレーターは、圧縮後の出力で基礎となるセッションをクリアして書き直すため、別のサーバー管理型の履歴フローを使う 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 });runCompaction({ force: true }) をいつでも呼び出して、アーカイブやハンドオフの前に履歴を縮小できます。DEBUG=openai-agents:openai:compaction を有効にすると、圧縮の判断をトレースできます。