openai-agents-python/docs/sessions/sqlalchemy_session.md
dependabot[bot] 9d2b318dd0
fix(deps-dev): bump ruff from 0.9.2 to 0.16.8 (#5249)
* fix(deps-dev): bump ruff from 0.9.2 to 0.16.8

Bumps [ruff](https://github.com/astral-sh/ruff) from 0.9.2 to 0.16.8.
- [Release notes](https://github.com/astral-sh/ruff/releases)
- [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/ruff/compare/0.9.2...0.16.8)

---
updated-dependencies:
- dependency-name: ruff
  dependency-version: 0.16.8
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* fix: apply Ruff 0.16.8 formatting and lint updates

* fix: exclude generated translations from Ruff formatting

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Justin Beckwith <jbeckwith@openai.com>
2026-09-30 22:24:21 +00:00

3 KiB

SQLAlchemy sessions

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.

Installation

SQLAlchemy sessions require the sqlalchemy optional-dependency extra and an async database driver that matches your database URL.

For the SQLite examples below (sqlite+aiosqlite://), install aiosqlite alongside the extra:

pip install 'openai-agents[sqlalchemy]' aiosqlite

The extra already includes asyncpg for PostgreSQL URLs that start with postgresql+asyncpg://. For MySQL URLs that start with mysql+aiomysql://, install aiomysql alongside the extra. The driver's rsa extra supplies dependencies for MySQL's SHA-256 authentication methods:

pip install 'openai-agents[sqlalchemy]' 'aiomysql[rsa]'

Quick start

Using database URL

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())

Using existing engine

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())

Storing non-ASCII text

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.

API reference

  • [SQLAlchemySession][agents.extensions.memory.sqlalchemy_session.SQLAlchemySession] - Main class
  • [Session][agents.memory.session.Session] - Base session protocol