セッション
セッションは、Agents SDK に 永続的なメモリレイヤー を提供します。Session インターフェースを実装する任意のオブジェクトを Runner.run に渡すと、SDK が残りを処理します。セッションが存在する場合、runner は自動的に次を行います。
- 以前に保存された会話アイテムを取得し、次のターンの先頭に追加します
- 各実行の完了後に、新しいユーザー入力と assistant の出力を永続化します
- 新しいユーザーテキストで runner を呼び出す場合でも、中断された
RunStateから再開する場合でも、将来のターンのためにセッションを利用可能なまま維持します
これにより、toInputList() を手動で呼び出したり、ターン間で履歴をつなぎ合わせたりする必要がなくなります。TypeScript SDK には 2 つの実装が含まれています。Conversations API 用の OpenAIConversationsSession と、ローカル開発向けの MemorySession です。これらは同じ Session インターフェースを共有しているため、独自のストレージバックエンドを差し込めます。Conversations API 以外の参考例として、examples/memory/ 配下の sample code セッションバックエンド( Prisma 、ファイルバックドなど)を確認してください。OpenAI Responses モデルを使う場合は、任意のセッションを OpenAIResponsesCompactionSession でラップすると、responses.compact により保存済みの会話履歴を自動的に縮小できます。
ヒント: このページの
OpenAIConversationsSessionの例を実行するには、SDK が Conversations API を呼び出せるようにOPENAI_API_KEY環境変数を設定してください(または、セッション構築時にapiKeyを指定してください)
SDK にクライアント側メモリの管理を任せたい場合は、セッションを使ってください。すでに conversationId や previousResponseId を使った OpenAI のサーバー管理状態を使用している場合は、通常、同じ会話履歴に対して追加でセッションは不要です。
クイックスタート
Section titled “クイックスタート”Conversations API とメモリを同期するには OpenAIConversationsSession を使うか、他の 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 のコンストラクターオプション:
| Option | Type | Notes |
|---|---|---|
conversationId | string | 遅延作成する代わりに、既存の会話を再利用します |
client | OpenAI | 設定済みの OpenAI クライアントを渡します |
apiKey | string | 内部の OpenAI クライアント作成時に使う API key です |
baseURL | string | OpenAI 互換エンドポイント用の Base URL です |
organization | string | リクエスト用の OpenAI organization ID です |
project | string | リクエスト用の OpenAI project ID です |
MemorySession のコンストラクターオプション:
| Option | Type | Notes |
|---|---|---|
sessionId | string | ログやテスト用の安定した識別子です。デフォルトでは自動生成されます |
initialItems | AgentInputItem[] | 既存の履歴でセッションを初期化します |
logger | Logger | デバッグ出力に使われる logger を上書きします |
MemorySession はすべてをローカルプロセスメモリに保存するため、プロセス終了時にリセットされます。
セッション構築前に会話 ID を事前作成する必要がある場合は、 startOpenAIConversationsSession(client?) を使い、返された ID を conversationId として渡してください。
セッションの基本動作
Section titled “セッションの基本動作”runner によるセッション利用方法
Section titled “runner によるセッション利用方法”- 各実行の前 に、セッション履歴を取得し、新しいターンの入力とマージして、その結合リストをエージェントに渡します
- 非ストリーミング実行の後 は、1 回の
session.addItems()呼び出しで、元のユーザー入力と最新ターンのモデル出力の両方を永続化します - ストリーミング実行では、最初にユーザー入力を書き込み、ターン完了後にストリーミング出力を追加します
RunResult.stateから再開する場合(承認やその他の中断時)は、同じsessionを渡し続けてください。再開されたターンは、入力を再準備せずにメモリへ追加されます
履歴の確認と編集
Section titled “履歴の確認と編集”セッションは、“undo”、“clear chat”、監査機能を構築できるよう、シンプルな 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 “カスタムストレージとマージ動作”独自ストレージの利用
Section titled “独自ストレージの利用”Redis 、 DynamoDB 、 SQLite 、または他のデータストアを使ってメモリを支えるには、Session インターフェースを実装します。必要なのは 5 つの非同期メソッドだけです。
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 を指定して、保存済み履歴と決定的にマージしてください。runner は既存履歴を読み込み、モデル呼び出しの前に コールバックを呼び出し、返された配列をそのターンの完全な入力としてモデルに渡します。このフックは、古いアイテムの削除、ツール結果の重複排除、またはモデルに見せたいコンテキストだけを強調する場合に最適です。
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]; },});文字列入力では runner が自動的に履歴をマージするため、コールバックは任意です。コールバックは、ターン入力がすでにアイテム配列である場合にのみ実行されます。
conversationId や previousResponseId も使っている場合は、コールバック結果に現在のターンから少なくとも 1 つの新規アイテムを残してください。これらのサーバー管理 API は現在のターン差分に依存しています。コールバックがすべての新規アイテムを削除すると、SDK は空の差分を送る代わりに元の新規入力を復元し、警告をログ出力します。
再開可能な実行
Section titled “再開可能な実行”承認と再開可能な実行の処理
Section titled “承認と再開可能な実行の処理”Human in the loop (人間の介入) フローでは、承認を待つために実行を一時停止することがよくあります。
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 から再開すると、新しいターンは同じメモリレコードに追加され、1 つの会話履歴が保たれます。Human in the loop (人間の介入) フローとの互換性も完全に維持されます。承認チェックポイントは引き続き RunState を通じて往復しつつ、セッションが完全な会話履歴を維持します。
高度な機能: 履歴の圧縮
Section titled “高度な機能: 履歴の圧縮”OpenAI Responses 履歴の自動圧縮
Section titled “OpenAI Responses 履歴の自動圧縮”OpenAIResponsesCompactionSession は任意の Session をデコレートし、OpenAI Responses API を使って長い保存履歴を、より短い等価な会話アイテムのリストに置き換えます。各ターンが永続化された後、runner は最新の responseId を runCompaction に渡します。これにより、判定フックが true を返したときに responses.compact が呼び出されます。compactionMode に応じて、リクエストは最新の Responses API チェーンまたはセッションの現在のアイテムのいずれかから構築されます。デフォルトのトリガーでは、少なくとも 10 件の非ユーザーアイテムが蓄積されると圧縮されます。トークン数やカスタムヒューリスティクスに基づいて判定したい場合は、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.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 のコンストラクターオプション:
| Option | Type | Notes |
|---|---|---|
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、候補アイテム、現在のセッションアイテムに基づくカスタムトリガーフックです |
compactionMode: 'previous_response_id' は、すでに Responses API の response ID でターンをチェーンしている場合に便利です。compactionMode: 'input' は、代わりに現在のセッションアイテムから圧縮リクエストを再構築します。これは、レスポンスチェーンが利用できない場合や、基盤セッションの内容を信頼できる唯一の情報源にしたい場合に役立ちます。
runCompaction(args) のオプション:
| Option | Type | Notes |
|---|---|---|
responseId | string | previous_response_id モード用の最新 Responses API response id です |
compactionMode | 'auto' | 'previous_response_id' | 'input' | 設定済みモードを呼び出し単位で上書きする任意オプションです |
store | boolean | 直前の実行でサーバー状態が保存されたかどうかを示します |
force | boolean | shouldTriggerCompaction をバイパスして即座に圧縮します |
低レイテンシーストリーミング向けの手動圧縮
Section titled “低レイテンシーストリーミング向けの手動圧縮”圧縮では基盤セッションをクリアして再書き込みするため、SDK はストリーミング実行を解決する前にその完了を待ちます。圧縮が重い場合、最後の出力トークンの後でも result.completed が数秒間 pending のままになることがあります。低レイテンシーなストリーミングや、より速いターンのやり取りが必要な場合は、自動圧縮を無効にして、ターン間(またはアイドル時間)に自分で 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 でデバッグログを有効にしてください。