OpenAI Agents Python 21 files ยท 0 subfolders
Copy to Workspace 07_MEMORY_SESSIONS Shared from "OpenAI Agents Python" on Inkdown
Memory & Sessions - Comprehensive Deep Dive
Overview
Memory and Sessions in the OpenAI Agents SDK enable conversation persistence across agent runs. Think of sessions as "conversation memory" - they allow agents to remember previous interactions, maintain context over time, and provide continuity in multi-turn conversations. This is essential for building chatbots, assistants, and any application where conversation history matters.
Core Concepts
What is a Session?
A session is a persistent store of conversation history between a user and an agent (or multiple agents). It:
Stores all messages, tool calls, and outputs from a conversation
Retrieves relevant history when resuming a conversation
Manages conversation length and token usage
Compacts long conversations to preserve context while reducing tokens
Why Sessions Matter
01_AGENT_SYSTEM.md
Context Continuity - Agents remember previous interactions
Multi-Turn Conversations - Enable back-and-forth dialogue
Token Efficiency - Intelligent history management
Conversation Analytics - Track conversation patterns
Resume Capability - Pause and resume conversations
Multi-Agent History - Track which agent said what
Session Types The SDK supports several session implementations:
SQLiteSession - Local SQLite database storage
OpenAIConversationsSession - OpenAI's server-managed conversations
OpenAIResponsesCompactionSession - OpenAI Responses API with compaction
Custom Sessions - Implement your own session backend
Session Interface
Session ABC All sessions implement the SessionABC base class:
save_items() - Store conversation items
load_items() - Retrieve conversation items
Session Settings Configure session behavior:
SQLite Session
Basic Usage
Session Initialization
Conversation IDs Conversation IDs identify unique conversations:
Use user IDs for per-user conversations
Use thread IDs for conversation threads
Use UUIDs for unique identifiers
Avoid hardcoded IDs in production
Session Limits Control how much history is loaded:
Reduce token usage
Improve response time
Focus on recent context
Manage memory
OpenAI Conversations Session
Server-Managed Conversations OpenAI provides server-managed conversation storage:
No local storage needed
Automatic prompt caching
Better performance
Managed by OpenAI
OpenAI stores conversation history on their servers
Only deltas (new items) are sent
The server maintains full context
Session persistence is handled automatically
When to Use Use OpenAIConversationsSession when:
You want to reduce local storage
You're using OpenAI's Responses API
You want automatic prompt caching
You don't need custom session logic
You need local control over data
You want custom session logic
You're not using OpenAI exclusively
You need to analyze conversation data
OpenAI Responses Compaction Session
Intelligent Compaction The Responses API supports intelligent conversation compaction:
Older messages are summarized
Key information is preserved
Token usage is reduced
Context is maintained
Compaction Configuration
Session Input Callback
Custom Input Handling Control how new input is combined with session history:
Custom history filtering
Special input processing
Context window management
Custom formatting
Session and Agent Lifecycle
Session Persistence Across Runs
Session with Handoffs Sessions track which agent generated each item:
Session with Multiple Conversations
Session Implementation Details
Item Storage Sessions store items as input items:
Item Retrieval Sessions retrieve items with optional limits:
Session and RunState RunState includes session information:
Custom Session Implementation
Creating a Custom Session Implement the SessionABC interface:
Using Custom Session
Redis/MongoDB storage
Cloud storage (S3, etc.)
Custom encryption
Distributed systems
Session and Tracing
Session Metadata in Traces Sessions include metadata in traces:
Session Analytics
Session Best Practices
1. Use Unique Conversation IDs Always use unique identifiers:
2. Set Appropriate Limits Configure session limits based on your needs:
3. Handle Session Errors Handle session failures gracefully:
4. Clean Up Old Sessions Implement cleanup for old sessions:
5. Monitor Session Performance Track session performance:
Session Patterns
1. Per-User Sessions Each user gets their own conversation history:
2. Thread-Based Sessions Each conversation thread gets its own history:
3. Session with Context Window Management Manage context window with sessions:
4. Session with Encryption Encrypt sensitive session data:
5. Session with Analytics Track conversation analytics:
Session and Server-Managed Conversations
Compatibility Server-managed conversations have limitations:
When to Avoid Server-Managed
You need custom session logic
You need to analyze conversation data locally
You're not using OpenAI exclusively
You need fine-grained control
Session and Memory Rollouts
Sandbox Memory Rollouts For sandbox agents, sessions can include memory rollouts:
Session Error Handling
Session Errors Handle session-related errors:
Recovery Strategies Implement recovery strategies:
Session Performance
Optimization Techniques Optimize session performance:
Monitoring Session Performance
Summary Sessions enable conversation persistence. Key takeaways:
Sessions store conversation history
SQLiteSession provides local SQLite storage
OpenAIConversationsSession uses server-managed storage
Conversation IDs identify unique conversations
Session limits control history size
Compaction reduces token usage for long conversations
Input callbacks customize history combination
Custom sessions can implement custom backends
SessionABC defines the session interface
Item storage uses input item format
Item retrieval supports optional limits
RunState includes session information
Handoffs are tracked across agents
Multiple conversations can coexist
Tracing includes session metadata
Analytics can track conversation patterns
Encryption can protect sensitive data
Performance can be optimized
Error handling should be graceful
Cleanup prevents data bloat
Sessions are essential for building conversational agents that remember context across interactions.