Sessions
The sessions module provides factory methods for creating and managing SQLiteSession instances with different storage configurations, integrating seamlessly with the OpenAI Agents SDK.
SessionFactory
The SessionFactory class provides static methods for creating configured SQLiteSession instances:
Session Types
In-Memory Sessions
Perfect for testing, temporary interactions, or when persistence isn't needed:
# Auto-generated session ID
session = SessionFactory.create_memory_session()
# Custom session ID
session = SessionFactory.create_memory_session("test_session_123")
Characteristics:
- Data stored in memory only
- Fast access and operations
- Data lost when application closes
- Ideal for development and testing
File-Based Sessions
Persistent storage for production use:
session = SessionFactory.create_file_session(
session_id="user_456",
db_path="data/sessions/user_456.db"
)
Characteristics:
- Data persisted to SQLite database file
- Survives application restarts
- Automatic directory creation
- Production-ready storage
Session Lifecycle Management
Creating New Sessions
from agency.sessions.session_factory import SessionFactory
import uuid
# Generate unique session ID
session_id = f"user_{uuid.uuid4().hex[:8]}"
# Create file-based session
session = SessionFactory.create_file_session(
session_id=session_id,
db_path=f"data/sessions/{session_id}.db"
)
Loading Existing Sessions
# Load existing session
session = SessionFactory.load_session(
session_id="user_456",
db_path="data/sessions/user_456.db"
)
if session:
print("Session loaded successfully")
else:
print("Session not found, creating new one")
session = SessionFactory.create_file_session("user_456", "data/sessions/user_456.db")
Session Validation
# Check if session exists
if SessionFactory.session_exists("data/sessions/user_456.db"):
session = SessionFactory.load_session("user_456", "data/sessions/user_456.db")
else:
session = SessionFactory.create_file_session("user_456", "data/sessions/user_456.db")
Session Management Operations
# List all session files in directory
sessions = SessionFactory.list_sessions("data/sessions/")
print(f"Found {len(sessions)} sessions")
# Session cleanup (removes old sessions)
SessionFactory.cleanup_sessions(
directory="data/sessions/",
older_than_days=30
)
# Backup session
SessionFactory.backup_session(
source_path="data/sessions/user_456.db",
backup_path="backups/user_456_backup.db"
)
# Session statistics
stats = SessionFactory.get_session_stats("data/sessions/user_456.db")
print(f"Session has {stats['message_count']} messages")
Integration Examples
With Agency Framework
from agency.factories.agency_factory import AgencyFactory
from agency.sessions.session_factory import SessionFactory
# Create session
session = SessionFactory.create_file_session(
session_id="support_session",
db_path="data/sessions/support.db"
)
# Use with agency
agency = AgencyFactory.create_agency(
config=config,
session=session
)
With ConversationManager
from agency.conversations.manager import ConversationManager
from agency.sessions.session_factory import SessionFactory
# Create session for conversation persistence
session = SessionFactory.create_file_session(
session_id="conv_123",
db_path="data/conversations/conv_123.db"
)
# Create conversation manager with session
manager = ConversationManager()
conversation = manager.create_conversation_with_session(
name="Customer Support",
session=session
)
Testing Scenarios
import pytest
from agency.sessions.session_factory import SessionFactory
def test_memory_session():
"""Test in-memory session creation."""
session = SessionFactory.create_memory_session("test")
assert session.session_id == "test"
def test_file_session():
"""Test file-based session creation."""
session = SessionFactory.create_file_session(
"test_file",
"test_data/test.db"
)
assert session.session_id == "test_file"
# Clean up
SessionFactory.cleanup_test_sessions("test_data/")
Configuration Options
Database Settings
# Custom database configuration
session = SessionFactory.create_file_session(
session_id="custom",
db_path="data/custom.db",
options={
"timeout": 30.0,
"check_same_thread": False,
"isolation_level": None
}
)
Path Management
from pathlib import Path
# Use Path objects for better path handling
db_path = Path("data") / "sessions" / f"user_{user_id}.db"
session = SessionFactory.create_file_session(
session_id=f"user_{user_id}",
db_path=str(db_path)
)
Performance Considerations
Memory Sessions
- Pros: Fastest access, no I/O overhead
- Cons: Limited by available RAM, no persistence
- Best for: Testing, temporary sessions, development
File Sessions
- Pros: Persistent storage, unlimited size
- Cons: I/O overhead, disk space usage
- Best for: Production use, long conversations
Session Pooling
class SessionPool:
"""Example session pool for managing multiple sessions."""
def __init__(self, base_dir: str):
self.base_dir = base_dir
self.active_sessions = {}
def get_session(self, session_id: str):
if session_id not in self.active_sessions:
self.active_sessions[session_id] = SessionFactory.create_file_session(
session_id=session_id,
db_path=f"{self.base_dir}/{session_id}.db"
)
return self.active_sessions[session_id]
def cleanup_inactive(self):
# Remove sessions that haven't been used recently
pass
Error Handling
try:
session = SessionFactory.create_file_session(
"user_123",
"/restricted/path/session.db"
)
except PermissionError:
print("Permission denied, using memory session")
session = SessionFactory.create_memory_session("user_123")
except Exception as e:
print(f"Session creation failed: {e}")
# Fallback to memory session
session = SessionFactory.create_memory_session()
Best Practices
- Session ID Naming: Use consistent, meaningful session IDs
- Path Management: Use pathlib for cross-platform compatibility
- Error Handling: Always have fallback session creation
- Resource Cleanup: Clean up old sessions periodically
- Testing: Use memory sessions for unit tests
- Production: Use file sessions with proper backup strategies
Migration Utilities
# Migrate from memory to file session
def migrate_session_to_file(memory_session, file_path):
"""Migrate in-memory session to file-based session."""
file_session = SessionFactory.create_file_session(
memory_session.session_id,
file_path
)
# Copy messages (implementation depends on session structure)
# This is a conceptual example
for message in memory_session.get_all_messages():
file_session.add_message(message)
return file_session
Next Steps
- Learn about Memory Management for overall architecture
- Explore Conversations for high-level conversation APIs
- Check Factories for other factory patterns