Menu

Session Persistence Patterns

Relevant source files

This page documents practical patterns for using session memory in the OpenAI Agents SDK to maintain conversation state across multiple agent runs. For the session protocol and core API, see page 5.1. For backend-specific details, see page 5.2 (RedisSession) and page 5.3 (Conversation Tracking Modes).

Overview

Session memory in the SDK enables automatic management of conversation history, so you do not need to manually pass message lists between agent runs. The SDK uses a protocol-based architecture, allowing different storage backends to be swapped without changing agent logic.

Session usage pattern:

  • Without session: You must manually manage and pass conversation history.
  • With session: The SDK automatically loads and updates conversation history.

Example:

Sources: README.md168-278 src/agents/run.py279-354 examples/memory/redis_session_example.py1-178

Session Protocol Architecture

All session implementations conform to the Session protocol, which defines four core operations: get_items, add_items, pop_item, and clear_session. This protocol is used by the Runner to manage conversation history, regardless of the underlying storage backend.

Diagram: Session Protocol and Implementations

Sources: src/agents/run.py279-354 src/agents/memory/session.py src/agents/extensions/memory/redis_session.py42-268 README.md242-278

Choosing a Session Backend

Decision Matrix

BackendUse CaseProsConsInstall
SQLiteSessionDevelopment, testing, single-processNo dependencies, simple, built-inNot distributedBuilt-in
RedisSessionProduction, distributed, scalableFast, distributed, TTL supportRequires Redis serverpip install openai-agents[redis]
OpenAIConversationsSessionCloud-hosted, serverlessNo infra to manageRequires OpenAI APIBuilt-in

Sources: README.md211-238 src/agents/extensions/memory/redis_session.py42-268

Diagram: Session Backend Selection Flow

Sources: README.md211-238 src/agents/extensions/memory/redis_session.py42-268

Basic Usage Patterns

Single-Turn vs Multi-Turn Conversations

  • Single-turn: No session needed; each call is stateless.
  • Multi-turn: Use a session to maintain context across turns.

Example:

Sources: README.md172-208 examples/memory/redis_session_example.py52-78

Session Isolation

Each session_id creates an isolated conversation history. Sessions with different IDs do not share state.

Example:

Sources: README.md226-238 tests/extensions/memory/test_redis_session.py157-191

Diagram: Session Lifecycle in Runner.run()

Sources: src/agents/run.py279-354 src/agents/memory/session.py

SQLiteSession Patterns

Development and Testing

SQLiteSession is the default choice for development because it requires no external dependencies:

Key characteristics:

Sources: src/agents/memory/session.py README.md216-220

Testing Pattern with In-Memory Database

Sources: src/agents/memory/session.py28-137

RedisSession Patterns

Distributed System with TTL

RedisSession is suitable for distributed, production systems. It supports automatic expiration (TTL), multi-process access, and can be used with a shared or dedicated Redis client.

  • Create a session from a Redis URL (with optional TTL).
  • Optionally, inject an existing Redis client for shared connection management.

Sources: src/agents/extensions/memory/redis_session.py42-268 examples/memory/redis_session_example.py29-46

Multi-Tenancy with Key Prefixes

Use the key_prefix parameter to isolate sessions for different applications or tenants within the same Redis instance. Each session's keys are namespaced by the prefix.

Redis key structure:

  • Session metadata: {key_prefix}:{session_id}
  • Messages list: {key_prefix}:{session_id}:messages
  • Counter: {key_prefix}:{session_id}:counter

Sources: src/agents/extensions/memory/redis_session.py45-74 examples/memory/redis_session_example.py149-173

Connection Management

  • If you create a session via RedisSession.from_url, the session owns the Redis client and you should call session.close() when done.
  • If you inject a shared Redis client, do not call session.close(); manage the client lifecycle at the application level.

Sources: src/agents/extensions/memory/redis_session.py247-268 tests/extensions/memory/test_redis_session.py473-515

Diagram: RedisSession Distributed Architecture and Code Entities

Sources: src/agents/extensions/memory/redis_session.py42-74 examples/memory/redis_session_example.py29-46

SQLAlchemySession Patterns

Production Database Setup

SQLAlchemySession provides relational database features with ACID compliance:

Sources: src/agents/extensions/memory/sqlalchemy_session.py1-313

Database Schema

The implementation uses a two-table schema optimized for conversation history:

Diagram: SQLAlchemySession Database Schema

Index structure:

  • agent_sessions.session_id: Primary key
  • agent_messages.id: Auto-increment primary key
  • idx_agent_messages_session_time: Composite index on (session_id, created_at) for efficient retrieval

Sources: src/agents/extensions/memory/sqlalchemy_session.py86-128

Advanced Engine Configuration

Sources: src/agents/extensions/memory/sqlalchemy_session.py59-81

Migration Strategy

For production deployments, disable create_tables=True and use proper migrations:

Sources: src/agents/extensions/memory/sqlalchemy_session.py86-128

EncryptedSession Patterns

Wrapping Existing Sessions

EncryptedSession provides at-rest encryption by wrapping any session implementation:

Sources: pyproject.toml42 src/agents/extensions/memory/__init__.py22-31

Key Management Patterns

Sources: pyproject.toml42 src/agents/extensions/memory/__init__.py22-31

Advanced Usage Patterns

Custom Session Implementation

Implement the SessionABC protocol for custom storage backends:

Sources: README.md242-278 src/agents/memory/session.py

History Limiting Pattern

Limit conversation history to recent messages to control context window size and costs:

Sources: src/agents/memory/session.py22-27 src/agents/extensions/memory/redis_session.py134-169

Session Migration Pattern

Migrate sessions between backends without losing data:

Sources: src/agents/memory/session.py

Hybrid Storage Pattern

Use different backends for different purposes:

Sources: src/agents/extensions/memory/redis_session.py src/agents/extensions/memory/sqlalchemy_session.py

Performance Considerations

Session Backend Performance Characteristics

Diagram: Session Backend Performance Trade-offs

Optimization Strategies

PatternImplementationBenefit
Limit retrievalget_items(limit=20)Reduce memory and network overhead
Connection poolingSQLAlchemy pool_size=20Reduce connection overhead
Redis pipeliningUsed internally in add_items()Batch operations
Async batch writesGroup multiple add_items() callsReduce round-trips
TTL for cacheRedisSession with ttl=3600Automatic cleanup
Index optimizationComposite index on (session_id, created_at)Fast time-based queries

Sources: src/agents/extensions/memory/redis_session.py180-211 src/agents/extensions/memory/sqlalchemy_session.py122-127

Memory Usage Patterns

Sources: src/agents/memory/session.py22-27 src/agents/extensions/memory/redis_session.py134-169

Production Deployment Checklist

Deployment Readiness

ComponentDevelopmentProduction
Session backendSQLiteSession(:memory:)RedisSession or SQLAlchemySession
DatabaseIn-memory/fileManaged Redis/PostgreSQL cluster
Schema managementcreate_tables=TrueMigration scripts (Alembic)
Error handlingRaise exceptionsGraceful degradation + logging
MonitoringOptionalSession metrics, latency tracking
EncryptionOptionalEncryptedSession for sensitive data
Connection poolingDefaultTuned pool_size settings
Cleanup strategyManual clear_session()TTL or scheduled cleanup

Sources: src/agents/extensions/memory/redis_session.py1-268 src/agents/extensions/memory/sqlalchemy_session.py1-313

Error Handling Pattern

Sources: src/agents/extensions/memory/redis_session.py257-268

Monitoring Metrics

Key metrics to track in production:

  • Session operations per second: get_items(), add_items() call rates
  • Session retrieval latency: P50, P95, P99 latency for get_items()
  • Session size distribution: Number of items per session
  • Storage backend health: Redis/PostgreSQL connection status
  • Error rates: Session operation failures
  • Cache hit rates: For hybrid/caching patterns

Sources: src/agents/extensions/memory/redis_session.py src/agents/extensions/memory/sqlalchemy_session.py

Morty Proxy This is a proxified and sanitized view of the page, visit original site.