Skip to content

Commit 097b12f

Browse files
authored
Docs: Add SQLAlchemy-powered sessions (#1549)
Documentation for SQLAlchemy-powered sessions, to be merged after merging and releasing #1357
1 parent e382ec0 commit 097b12f

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

docs/sessions.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,64 @@ result2 = await Runner.run(
164164
)
165165
```
166166

167+
### SQLAlchemy-powered sessions
168+
169+
For more advanced use cases, you can use a SQLAlchemy-powered session backend. This allows you to use any database supported by SQLAlchemy (PostgreSQL, MySQL, SQLite, etc.) for session storage.
170+
171+
**Example 1: Using `from_url` with in-memory SQLite**
172+
173+
This is the simplest way to get started, ideal for development and testing.
174+
175+
```python
176+
import asyncio
177+
from agents import Agent, Runner
178+
from agents.extensions.memory.sqlalchemy_session import SQLAlchemySession
179+
180+
async def main():
181+
agent = Agent("Assistant")
182+
session = SQLAlchemySession.from_url(
183+
"user-123",
184+
url="sqlite+aiosqlite:///:memory:",
185+
create_tables=True, # Auto-create tables for the demo
186+
)
187+
188+
result = await Runner.run(agent, "Hello", session=session)
189+
190+
if __name__ == "__main__":
191+
asyncio.run(main())
192+
```
193+
194+
**Example 2: Using an existing SQLAlchemy engine**
195+
196+
In a production application, you likely already have a SQLAlchemy `AsyncEngine` instance. You can pass it directly to the session.
197+
198+
```python
199+
import asyncio
200+
from agents import Agent, Runner
201+
from agents.extensions.memory.sqlalchemy_session import SQLAlchemySession
202+
from sqlalchemy.ext.asyncio import create_async_engine
203+
204+
async def main():
205+
# In your application, you would use your existing engine
206+
engine = create_async_engine("sqlite+aiosqlite:///conversations.db")
207+
208+
agent = Agent("Assistant")
209+
session = SQLAlchemySession(
210+
"user-456",
211+
engine=engine,
212+
create_tables=True, # Auto-create tables for the demo
213+
)
214+
215+
result = await Runner.run(agent, "Hello", session=session)
216+
print(result.final_output)
217+
218+
await engine.dispose()
219+
220+
if __name__ == "__main__":
221+
asyncio.run(main())
222+
```
223+
224+
167225
## Custom memory implementations
168226

169227
You can implement your own session memory by creating a class that follows the [`Session`][agents.memory.session.Session] protocol:

0 commit comments

Comments
 (0)