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).
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:
Example:
Sources: README.md168-278 src/agents/run.py279-354 examples/memory/redis_session_example.py1-178
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.
Sources: src/agents/run.py279-354 src/agents/memory/session.py src/agents/extensions/memory/redis_session.py42-268 README.md242-278
Backend | Use Case | Pros | Cons | Install |
---|---|---|---|---|
SQLiteSession | Development, testing, single-process | No dependencies, simple, built-in | Not distributed | Built-in |
RedisSession | Production, distributed, scalable | Fast, distributed, TTL support | Requires Redis server | pip install openai-agents[redis] |
OpenAIConversationsSession | Cloud-hosted, serverless | No infra to manage | Requires OpenAI API | Built-in |
Sources: README.md211-238 src/agents/extensions/memory/redis_session.py42-268
Sources: README.md211-238 src/agents/extensions/memory/redis_session.py42-268
Example:
Sources: README.md172-208 examples/memory/redis_session_example.py52-78
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
Runner.run()
Sources: src/agents/run.py279-354 src/agents/memory/session.py
SQLiteSession
is the default choice for development because it requires no external dependencies:
Key characteristics:
asyncio.Lock
for concurrent access src/agents/memory/session.py51-53Runner.run_sync()
README.md201-207Sources: src/agents/memory/session.py README.md216-220
Sources: src/agents/memory/session.py28-137
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.
Sources: src/agents/extensions/memory/redis_session.py42-268 examples/memory/redis_session_example.py29-46
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:
{key_prefix}:{session_id}
{key_prefix}:{session_id}:messages
{key_prefix}:{session_id}:counter
Sources: src/agents/extensions/memory/redis_session.py45-74 examples/memory/redis_session_example.py149-173
RedisSession.from_url
, the session owns the Redis client and you should call session.close()
when done.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
Sources: src/agents/extensions/memory/redis_session.py42-74 examples/memory/redis_session_example.py29-46
SQLAlchemySession
provides relational database features with ACID compliance:
Sources: src/agents/extensions/memory/sqlalchemy_session.py1-313
The implementation uses a two-table schema optimized for conversation history:
Diagram: SQLAlchemySession Database Schema
Index structure:
agent_sessions.session_id
: Primary keyagent_messages.id
: Auto-increment primary keyidx_agent_messages_session_time
: Composite index on (session_id, created_at)
for efficient retrievalSources: src/agents/extensions/memory/sqlalchemy_session.py86-128
Sources: src/agents/extensions/memory/sqlalchemy_session.py59-81
For production deployments, disable create_tables=True
and use proper migrations:
Sources: src/agents/extensions/memory/sqlalchemy_session.py86-128
EncryptedSession
provides at-rest encryption by wrapping any session implementation:
Sources: pyproject.toml42 src/agents/extensions/memory/__init__.py22-31
Sources: pyproject.toml42 src/agents/extensions/memory/__init__.py22-31
Implement the SessionABC
protocol for custom storage backends:
Sources: README.md242-278 src/agents/memory/session.py
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
Migrate sessions between backends without losing data:
Sources: src/agents/memory/session.py
Use different backends for different purposes:
Sources: src/agents/extensions/memory/redis_session.py src/agents/extensions/memory/sqlalchemy_session.py
Diagram: Session Backend Performance Trade-offs
Pattern | Implementation | Benefit |
---|---|---|
Limit retrieval | get_items(limit=20) | Reduce memory and network overhead |
Connection pooling | SQLAlchemy pool_size=20 | Reduce connection overhead |
Redis pipelining | Used internally in add_items() | Batch operations |
Async batch writes | Group multiple add_items() calls | Reduce round-trips |
TTL for cache | RedisSession with ttl=3600 | Automatic cleanup |
Index optimization | Composite 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
Sources: src/agents/memory/session.py22-27 src/agents/extensions/memory/redis_session.py134-169
Component | Development | Production |
---|---|---|
Session backend | SQLiteSession(:memory:) | RedisSession or SQLAlchemySession |
Database | In-memory/file | Managed Redis/PostgreSQL cluster |
Schema management | create_tables=True | Migration scripts (Alembic) |
Error handling | Raise exceptions | Graceful degradation + logging |
Monitoring | Optional | Session metrics, latency tracking |
Encryption | Optional | EncryptedSession for sensitive data |
Connection pooling | Default | Tuned pool_size settings |
Cleanup strategy | Manual clear_session() | TTL or scheduled cleanup |
Sources: src/agents/extensions/memory/redis_session.py1-268 src/agents/extensions/memory/sqlalchemy_session.py1-313
Sources: src/agents/extensions/memory/redis_session.py257-268
Key metrics to track in production:
get_items()
, add_items()
call ratesget_items()
Sources: src/agents/extensions/memory/redis_session.py src/agents/extensions/memory/sqlalchemy_session.py
Refresh this wiki
This wiki was recently refreshed. Please wait 5 days to refresh again.