セッション
Agents SDK は、複数のエージェント実行にまたがる会話履歴を自動で保持する組み込みのセッションメモリを提供し、ターン間で手動で.to_input_list() を扱う必要をなくします。
セッションは特定のセッションの会話履歴を保存し、明示的な手動メモリ管理を行わなくてもエージェントがコンテキストを維持できるようにします。これは、チャットアプリケーションや、エージェントにこれまでのやり取りを覚えていてほしいマルチターンの会話を構築する際に特に有用です。
クイックスタート
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"仕組み
セッションメモリが有効な場合:
- 各実行の前: ランナーはセッションの会話履歴を自動で取得し、入力アイテムの先頭に追加します。
- 各実行の後: 実行中に生成されたすべての新規アイテム(ユーザー入力、アシスタントの応答、ツール呼び出しなど)は自動的にセッションへ保存されます。
- コンテキストの保持: 同じセッションでの後続の実行には完全な会話履歴が含まれ、エージェントはコンテキストを維持できます。
これにより、手動で.to_input_list() を呼び出し、実行間で会話状態を管理する必要がなくなります。
メモリ操作
基本操作
セッションは会話履歴を管理するためのいくつかの操作をサポートします:
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"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 セッション
会話の分岐、利用状況分析、構造化クエリを備えた強化版 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 ベース:
"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))を使用します - クラウドネイティブな本番デプロイには Dapr ステートストアセッション(
DaprSession.from_address("session_id", state_store_name="statestore", dapr_address="localhost:50001"))を使用します。組み込みのテレメトリー、トレーシング、データ分離を備え、30+ のデータベースバックエンドをサポートします - 履歴を 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"))コミュニティ製セッション実装
コミュニティによって追加のセッション実装が開発されています:
| パッケージ | 説明 |
|---|---|
| openai-django-sessions | 任意の Django 対応データベース(PostgreSQL、MySQL、SQLite など)向けの Django ORM ベースのセッション |
セッション実装を作成された場合は、ここに追加するためのドキュメント PR をぜひお寄せください。
API リファレンス
詳細な API ドキュメントは次を参照してください:
Session- プロトコルインターフェースOpenAIConversationsSession- OpenAI Conversations API 実装SQLiteSession- 基本的な SQLite 実装SQLAlchemySession- SQLAlchemy 駆動の実装DaprSession- Dapr ステートストア実装AdvancedSQLiteSession- 分岐と分析を備えた強化版 SQLiteEncryptedSession- 任意のセッション向けの暗号化ラッパー