콘텐츠로 이동

세션

세션은 Agents SDK에 지속 메모리 계층을 제공합니다. Session 인터페이스를 구현하는 객체를 Runner.run에 전달하면, 나머지는 SDK가 처리합니다. 세션이 있으면 러너는 자동으로 다음을 수행합니다:

  1. 이전에 저장된 대화 항목을 가져와 다음 턴 앞에 추가합니다.
  2. 각 실행이 완료된 후 새 사용자 입력과 어시스턴트 출력을 영속화합니다.
  3. 새로운 사용자 텍스트로 러너를 호출하거나 인터럽트된 RunState에서 재개하든, 향후 턴을 위해 세션을 계속 사용 가능하게 유지합니다.

이로써 toInputList()를 수동으로 호출하거나 턴 간 히스토리를 이어 붙일 필요가 없습니다. TypeScript SDK는 두 가지 구현을 제공합니다: Conversations API용 OpenAIConversationsSession과 로컬 개발을 위한 MemorySession. 둘 모두 Session 인터페이스를 공유하므로, 자체 스토리지 백엔드를 연결할 수 있습니다. Conversations API를 넘어 영감을 얻고 싶다면 examples/memory/ 아래의 샘플 세션 백엔드(Prisma, 파일 기반 등)를 살펴보세요. OpenAI Responses 모델을 사용할 때는 어떤 세션이든 OpenAIResponsesCompactionSession으로 감싸 responses.compact를 통해 저장된 대화록을 자동으로 축약하세요.

Tip: 이 페이지의 OpenAIConversationsSession 예제를 실행하려면 OPENAI_API_KEY 환경 변수를 설정하세요(또는 세션 생성 시 apiKey를 제공). 그러면 SDK가 Conversations API를 호출할 수 있습니다.


OpenAIConversationsSession을 사용해 Conversations API와 메모리를 동기화하거나, 다른 어떤 Session 구현으로 교체하세요.

Use the Conversations API as session memory
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 구현으로 전환해도 코드 변경은 필요하지 않습니다.


  • 각 실행 전에 세션 히스토리를 가져와 새 턴 입력과 병합하고, 결합된 리스트를 에이전트에 전달합니다.
  • 비-스트리밍 실행 후에는 한 번의 session.addItems() 호출로 최신 턴의 원본 사용자 입력과 모델 출력을 모두 영속화합니다.
  • 스트리밍 실행의 경우 사용자 입력을 먼저 기록하고, 턴이 완료되면 스트리밍된 출력을 이어서 추가합니다.
  • RunResult.state에서 재개할 때(승인 또는 기타 인터럽션)도 동일한 session을 계속 전달하세요. 재개된 턴은 입력을 다시 준비하지 않고 메모리에 추가됩니다.

세션은 간단한 CRUD 헬퍼를 제공하므로 “실행 취소”, “채팅 지우기”, 감사 기능을 구축할 수 있습니다.

Read and edit stored items
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 또는 기타 데이터 스토어로 메모리를 지원하세요. 필요한 비동기 메서드는 다섯 개뿐입니다.

Custom in-memory session implementation
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 here
const 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);

커스텀 세션을 사용하면 보존 정책을 강제하고, 암호화를 추가하며, 영속화 전에 각 대화 턴에 메타데이터를 첨부할 수 있습니다.


히스토리와 새 항목의 병합 제어

섹션 제목: “히스토리와 새 항목의 병합 제어”

실행 입력으로 AgentInputItem 배열을 전달할 때, sessionInputCallback을 제공해 저장된 히스토리와 결정적으로 병합하세요. 러너는 기존 히스토리를 로드하고, 모델 호출 이전에 콜백을 호출하며, 반환된 배열을 모델에 해당 턴의 완전한 입력으로 전달합니다. 이 훅은 오래된 항목을 자르거나, 도구 결과를 중복 제거하거나, 모델에 보여주고 싶은 컨텍스트만 강조하는 데 적합합니다.

Truncate history with 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];
},
});

문자열 입력의 경우 러너가 히스토리를 자동으로 병합하므로 콜백은 선택 사항입니다.


휴먼인더루프(HITL) 흐름은 종종 승인을 기다리기 위해 실행을 일시 중지합니다:

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 히스토리 자동 축약

섹션 제목: “OpenAI Responses 히스토리 자동 축약”

OpenAIResponsesCompactionSession은 어떤 Session이든 데코레이팅하고 OpenAI Responses API를 활용해 대화록을 짧게 유지합니다. 각 턴이 영속화된 후 러너는 최신 responseIdrunCompaction에 전달하며, 의사결정 훅이 true를 반환하면 responses.compact를 호출합니다. 기본 트리거는 사용자 이외의 항목이 최소 10개 누적되면 축약을 수행합니다. 토큰 수나 사용자 정의 휴리스틱에 따라 결정을 내리려면 shouldTriggerCompaction을 오버라이드하세요. 이 데코레이터는 축약된 출력으로 기본 세션을 지우고 다시 작성하므로, 서버 관리 히스토리 플로우가 다른 OpenAIConversationsSession과의 조합은 피하세요.

Decorate a session with OpenAIResponsesCompactionSession
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을 설정해 축약 결정 과정을 트레이싱하는 디버그 로그를 활성화하세요.