Movatterモバイル変換


[0]ホーム

URL:


콘텐츠로 이동

세션

Agents SDK 는 내장된 세션 메모리를 제공하여 여러 에이전트 실행에 걸쳐 대화 기록을 자동으로 유지하므로, 턴 사이에.to_input_list() 를 수동으로 처리할 필요가 없습니다.

Sessions 는 특정 세션의 대화 기록을 저장하여, 에이전트가 명시적인 수동 메모리 관리 없이도 컨텍스트를 유지할 수 있게 합니다. 이는 이전 상호작용을 에이전트가 기억하도록 하고 싶은 채팅 애플리케이션이나 멀티턴 대화를 구축할 때 특히 유용합니다.

빠른 시작

fromagentsimportAgent,Runner,SQLiteSession# Create agentagent=Agent(name="Assistant",instructions="Reply very concisely.",)# Create a session instance with a session IDsession=SQLiteSession("conversation_123")# First turnresult=awaitRunner.run(agent,"What city is the Golden Gate Bridge in?",session=session)print(result.final_output)# "San Francisco"# Second turn - agent automatically remembers previous contextresult=awaitRunner.run(agent,"What state is it in?",session=session)print(result.final_output)# "California"# Also works with synchronous runnerresult=Runner.run_sync(agent,"What's the population?",session=session)print(result.final_output)# "Approximately 39 million"

동작 방식

세션 메모리가 활성화되면:

  1. 각 실행 전: 러너가 해당 세션의 대화 기록을 자동으로 가져와 입력 항목 앞에 덧붙입니다
  2. 각 실행 후: 실행 중 생성된 모든 새 항목(사용자 입력, 어시스턴트 응답, 도구 호출 등)이 자동으로 세션에 저장됩니다
  3. 컨텍스트 유지: 동일한 세션으로 이후 실행할 때마다 전체 대화 기록이 포함되어, 에이전트가 컨텍스트를 유지할 수 있습니다

이로써.to_input_list() 를 수동으로 호출하고 실행 간 대화 상태를 관리할 필요가 없어집니다.

메모리 작업

기본 작업

Sessions 는 대화 기록 관리를 위한 여러 작업을 지원합니다:

fromagentsimportSQLiteSessionsession=SQLiteSession("user_123","conversations.db")# Get all items in a sessionitems=awaitsession.get_items()# Add new items to a sessionnew_items=[{"role":"user","content":"Hello"},{"role":"assistant","content":"Hi there!"}]awaitsession.add_items(new_items)# Remove and return the most recent itemlast_item=awaitsession.pop_item()print(last_item)# {"role": "assistant", "content": "Hi there!"}# Clear all items from a sessionawaitsession.clear_session()

수정에 pop_item 사용

pop_item 메서드는 대화에서 마지막 항목을 되돌리거나 수정하고 싶을 때 특히 유용합니다:

fromagentsimportAgent,Runner,SQLiteSessionagent=Agent(name="Assistant")session=SQLiteSession("correction_example")# Initial conversationresult=awaitRunner.run(agent,"What's 2 + 2?",session=session)print(f"Agent:{result.final_output}")# User wants to correct their questionassistant_item=awaitsession.pop_item()# Remove agent's responseuser_item=awaitsession.pop_item()# Remove user's question# Ask a corrected questionresult=awaitRunner.run(agent,"What's 2 + 3?",session=session)print(f"Agent:{result.final_output}")

세션 유형

SDK 는 다양한 사용 사례를 위한 여러 세션 구현을 제공합니다:

OpenAI Conversations API 세션

OpenAIConversationsSession 을 통해OpenAI's Conversations API 를 사용합니다.

fromagentsimportAgent,Runner,OpenAIConversationsSession# Create agentagent=Agent(name="Assistant",instructions="Reply very concisely.",)# Create a new conversationsession=OpenAIConversationsSession()# Optionally resume a previous conversation by passing a conversation ID# session = OpenAIConversationsSession(conversation_id="conv_123")# Start conversationresult=awaitRunner.run(agent,"What city is the Golden Gate Bridge in?",session=session)print(result.final_output)# "San Francisco"# Continue the conversationresult=awaitRunner.run(agent,"What state is it in?",session=session)print(result.final_output)# "California"

OpenAI Responses 압축 세션

OpenAIResponsesCompactionSession 을 사용해 Responses API (responses.compact) 로 세션 기록을 압축합니다. 이는 기반 세션을 감싸며,should_trigger_compaction 에 따라 각 턴 이후 자동으로 압축할 수 있습니다.

일반적인 사용법(자동 압축)

fromagentsimportAgent,Runner,SQLiteSessionfromagents.memoryimportOpenAIResponsesCompactionSessionunderlying=SQLiteSession("conversation_123")session=OpenAIResponsesCompactionSession(session_id="conversation_123",underlying_session=underlying,)agent=Agent(name="Assistant")result=awaitRunner.run(agent,"Hello",session=session)print(result.final_output)

기본적으로 후보 임계값에 도달하면 각 턴 이후 압축이 실행됩니다.

자동 압축은 스트리밍을 차단할 수 있음

압축은 세션 기록을 지우고 다시 작성하므로, SDK 는 압축이 끝나야 실행이 완료된 것으로 간주합니다. 스트리밍 모드에서는 압축이 무거운 경우 마지막 출력 토큰 이후에도run.stream_events() 가 몇 초 동안 열린 상태로 남을 수 있습니다.

낮은 지연의 스트리밍이나 빠른 턴 전환을 원한다면 자동 압축을 비활성화하고, 턴 사이(또는 유휴 시간)에 직접run_compaction() 을 호출하세요. 자체 기준에 따라 언제 압축을 강제할지 결정할 수 있습니다.

fromagentsimportAgent,Runner,SQLiteSessionfromagents.memoryimportOpenAIResponsesCompactionSessionunderlying=SQLiteSession("conversation_123")session=OpenAIResponsesCompactionSession(session_id="conversation_123",underlying_session=underlying,# Disable triggering the auto compactionshould_trigger_compaction=lambda_:False,)agent=Agent(name="Assistant")result=awaitRunner.run(agent,"Hello",session=session)# Decide when to compact (e.g., on idle, every N turns, or size thresholds).awaitsession.run_compaction({"force":True})

SQLite 세션

SQLite 를 사용하는 기본 경량 세션 구현입니다:

fromagentsimportSQLiteSession# In-memory database (lost when process ends)session=SQLiteSession("user_123")# Persistent file-based databasesession=SQLiteSession("user_123","conversations.db")# Use the sessionresult=awaitRunner.run(agent,"Hello",session=session)

SQLAlchemy 세션

SQLAlchemy 가 지원하는 어떤 데이터베이스든 사용할 수 있는 프로덕션 준비 세션입니다:

fromagents.extensions.memoryimportSQLAlchemySession# Using database URLsession=SQLAlchemySession.from_url("user_123",url="postgresql+asyncpg://user:pass@localhost/db",create_tables=True)# Using existing enginefromsqlalchemy.ext.asyncioimportcreate_async_engineengine=create_async_engine("postgresql+asyncpg://user:pass@localhost/db")session=SQLAlchemySession("user_123",engine=engine,create_tables=True)

자세한 문서는SQLAlchemy Sessions 를 참고하세요.

고급 SQLite 세션

대화 브랜칭, 사용량 분석, structured 쿼리를 제공하는 강화된 SQLite 세션입니다:

fromagents.extensions.memoryimportAdvancedSQLiteSession# Create with advanced featuressession=AdvancedSQLiteSession(session_id="user_123",db_path="conversations.db",create_tables=True)# Automatic usage trackingresult=awaitRunner.run(agent,"Hello",session=session)awaitsession.store_run_usage(result)# Track token usage# Conversation branchingawaitsession.create_branch_from_turn(2)# Branch from turn 2

자세한 문서는Advanced SQLite Sessions 를 참고하세요.

암호화 세션

어떤 세션 구현에도 적용할 수 있는 투명한 암호화 래퍼입니다:

fromagents.extensions.memoryimportEncryptedSession,SQLAlchemySession# Create underlying sessionunderlying_session=SQLAlchemySession.from_url("user_123",url="sqlite+aiosqlite:///conversations.db",create_tables=True)# Wrap with encryption and TTLsession=EncryptedSession(session_id="user_123",underlying_session=underlying_session,encryption_key="your-secret-key",ttl=600# 10 minutes)result=awaitRunner.run(agent,"Hello",session=session)

자세한 문서는Encrypted Sessions 를 참고하세요.

기타 세션 유형

내장된 옵션이 몇 가지 더 있습니다.examples/memory/extensions/memory/ 아래의 소스 코드를 참고하세요.

세션 관리

세션 ID 네이밍

대화를 정리하는 데 도움이 되는 의미 있는 세션 ID 를 사용하세요:

  • 사용자 기반:"user_12345"
  • 스레드 기반:"thread_abc123"
  • 컨텍스트 기반:"support_ticket_456"

메모리 영속성

  • 임시 대화에는 인메모리 SQLite (SQLiteSession("session_id")) 를 사용하세요
  • 영속적 대화에는 파일 기반 SQLite (SQLiteSession("session_id", "path/to/db.sqlite")) 를 사용하세요
  • SQLAlchemy 가 지원하는 기존 데이터베이스를 사용하는 프로덕션 시스템에는 SQLAlchemy 기반 세션 (SQLAlchemySession("session_id", engine=engine, create_tables=True)) 을 사용하세요
  • 내장 텔레메트리, 트레이싱, 데이터 격리를 갖춘 30+ 데이터베이스 백엔드를 지원하는 프로덕션 클라우드 네이티브 배포에는 Dapr 상태 저장소 세션 (DaprSession.from_address("session_id", state_store_name="statestore", dapr_address="localhost:50001")) 을 사용하세요
  • 기록을 OpenAI Conversations API 에 저장하고 싶다면 OpenAI 호스트하는 스토리지 (OpenAIConversationsSession()) 를 사용하세요
  • 투명한 암호화 및 TTL 기반 만료를 위해 어떤 세션이든 감싸려면 암호화 세션 (EncryptedSession(session_id, underlying_session, encryption_key)) 을 사용하세요
  • 더 고급 사용 사례를 위해 다른 프로덕션 시스템(Redis, Django 등)에 대한 커스텀 세션 백엔드를 구현하는 것도 고려하세요

여러 세션

fromagentsimportAgent,Runner,SQLiteSessionagent=Agent(name="Assistant")# Different sessions maintain separate conversation historiessession_1=SQLiteSession("user_123","conversations.db")session_2=SQLiteSession("user_456","conversations.db")result1=awaitRunner.run(agent,"Help me with my account",session=session_1)result2=awaitRunner.run(agent,"What are my charges?",session=session_2)

세션 공유

# Different agents can share the same sessionsupport_agent=Agent(name="Support")billing_agent=Agent(name="Billing")session=SQLiteSession("user_123")# Both agents will see the same conversation historyresult1=awaitRunner.run(support_agent,"Help me with my account",session=session)result2=awaitRunner.run(billing_agent,"What are my charges?",session=session)

전체 예제

다음은 세션 메모리가 실제로 동작하는 전체 예제입니다:

importasynciofromagentsimportAgent,Runner,SQLiteSessionasyncdefmain():# Create an agentagent=Agent(name="Assistant",instructions="Reply very concisely.",)# Create a session instance that will persist across runssession=SQLiteSession("conversation_123","conversation_history.db")print("=== Sessions Example ===")print("The agent will remember previous messages automatically.\n")# First turnprint("First turn:")print("User: What city is the Golden Gate Bridge in?")result=awaitRunner.run(agent,"What city is the Golden Gate Bridge in?",session=session)print(f"Assistant:{result.final_output}")print()# Second turn - the agent will remember the previous conversationprint("Second turn:")print("User: What state is it in?")result=awaitRunner.run(agent,"What state is it in?",session=session)print(f"Assistant:{result.final_output}")print()# Third turn - continuing the conversationprint("Third turn:")print("User: What's the population of that state?")result=awaitRunner.run(agent,"What's the population of that state?",session=session)print(f"Assistant:{result.final_output}")print()print("=== Conversation Complete ===")print("Notice how the agent remembered the context from previous turns!")print("Sessions automatically handles conversation history.")if__name__=="__main__":asyncio.run(main())

커스텀 세션 구현

Session 프로토콜을 따르는 클래스를 만들어 자체 세션 메모리를 구현할 수 있습니다:

fromagents.memory.sessionimportSessionABCfromagents.itemsimportTResponseInputItemfromtypingimportListclassMyCustomSession(SessionABC):"""Custom session implementation following the Session protocol."""def__init__(self,session_id:str):self.session_id=session_id# Your initialization hereasyncdefget_items(self,limit:int|None=None)->List[TResponseInputItem]:"""Retrieve conversation history for this session."""# Your implementation herepassasyncdefadd_items(self,items:List[TResponseInputItem])->None:"""Store new items for this session."""# Your implementation herepassasyncdefpop_item(self)->TResponseInputItem|None:"""Remove and return the most recent item from this session."""# Your implementation herepassasyncdefclear_session(self)->None:"""Clear all items for this session."""# Your implementation herepass# Use your custom sessionagent=Agent(name="Assistant")result=awaitRunner.run(agent,"Hello",session=MyCustomSession("my_session"))

커뮤니티 세션 구현

커뮤니티에서 추가 세션 구현을 개발했습니다:

PackageDescription
openai-django-sessionsDjango 가 지원하는 어떤 데이터베이스(PostgreSQL, MySQL, SQLite 등)에도 사용할 수 있는 Django ORM 기반 세션

세션 구현을 만들었다면, 여기에 추가할 수 있도록 문서 PR 을 제출해 주세요!

API Reference

자세한 API 문서는 다음을 참고하세요:


[8]ページ先頭

©2009-2026 Movatter.jp