docs/sessions/sqlalchemy_session.md
SQLAlchemySession uses SQLAlchemy to provide a production-ready session implementation, allowing you to use any database supported by SQLAlchemy (PostgreSQL, MySQL, SQLite, etc.) for session storage.
SQLAlchemy sessions require the sqlalchemy extra:
pip install openai-agents[sqlalchemy]
The simplest way to get started:
import asyncio
from agents import Agent, Runner
from agents.extensions.memory import SQLAlchemySession
async def main():
agent = Agent("Assistant")
# Create session using database URL
session = SQLAlchemySession.from_url(
"user-123",
url="sqlite+aiosqlite:///:memory:",
create_tables=True
)
result = await Runner.run(agent, "Hello", session=session)
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())
For applications with existing SQLAlchemy engines:
import asyncio
from agents import Agent, Runner
from agents.extensions.memory import SQLAlchemySession
from sqlalchemy.ext.asyncio import create_async_engine
async def main():
# Create your database engine
engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db")
agent = Agent("Assistant")
session = SQLAlchemySession(
"user-456",
engine=engine,
create_tables=True
)
result = await Runner.run(agent, "Hello", session=session)
print(result.final_output)
# Clean up
await engine.dispose()
if __name__ == "__main__":
asyncio.run(main())
By default, SQLAlchemySession escapes non-ASCII characters when it serializes session items to JSON. This preserves the historical storage format while still round-tripping the original text when items are loaded.
Set ensure_ascii=False when you want multilingual text to remain readable in the stored JSON:
session = SQLAlchemySession.from_url(
"user-123",
url="sqlite+aiosqlite:///conversations.db",
create_tables=True,
ensure_ascii=False,
)
You can pass the same option directly to SQLAlchemySession(...) when using an existing engine. This setting changes only the JSON representation stored in the database; it does not change the values returned by session methods.
SQLAlchemySession][agents.extensions.memory.sqlalchemy_session.SQLAlchemySession] - Main classSession][agents.memory.session.Session] - Base session protocol