Skip to content

Add Sessions for Automatic Conversation History Management #752

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 26 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
d849c93
Add session memory functionality to the Agents SDK
knowsuchagency May 24, 2025
63a786f
Enhance session memory validation in Runner class
knowsuchagency May 24, 2025
6aab1e8
Add custom session memory implementation examples to README
knowsuchagency May 24, 2025
53d4132
Implement session memory instance reuse in Runner class
knowsuchagency May 24, 2025
14600ee
Refactor session memory usage in README and examples
knowsuchagency May 24, 2025
54e9dfa
Add session memory documentation and examples
knowsuchagency May 24, 2025
5e4f456
Add memory documentation and update references
knowsuchagency May 24, 2025
14edb3c
revert changes to Agent. memory is a concern of the runner
knowsuchagency May 24, 2025
b422736
Enhance SQLiteSessionMemory to support customizable table names for s…
knowsuchagency May 24, 2025
ad03ae7
Add pop_message functionality to SQLiteSessionMemory
knowsuchagency May 24, 2025
f0241db
Refactor SQLiteSessionMemory methods to support asynchronous execution
knowsuchagency May 24, 2025
dcae4c7
Add validation for session_id when memory is disabled in Runner class
knowsuchagency May 24, 2025
4af2192
Refactor session memory handling in documentation and examples
knowsuchagency May 24, 2025
57b4f5e
Refactor database initialization in SQLiteSessionMemory
knowsuchagency May 24, 2025
764e82c
Remove redundant database initialization method in SQLiteSessionMemory
knowsuchagency May 24, 2025
1827673
Enhance SQLiteSessionMemory for thread safety and connection management
knowsuchagency May 24, 2025
131c5dc
Initialize database schema for file databases in SQLiteSessionMemory
knowsuchagency May 24, 2025
b810992
Refactor Runner class to improve error handling and input preparation
knowsuchagency May 24, 2025
8b827f2
Refactor test_session_memory.py to simplify imports
knowsuchagency May 24, 2025
0cf4f88
Refactor session memory implementation to simplify usage and improve …
knowsuchagency May 24, 2025
b9be6b9
Update session memory documentation and refactor references
knowsuchagency May 24, 2025
3a79e38
Update documentation to reflect renaming of Session Memory to Sessions
knowsuchagency May 24, 2025
8e9edd8
Update documentation and references for Sessions
knowsuchagency May 24, 2025
92f7db5
Enhance session message retrieval functionality
knowsuchagency May 24, 2025
b5ad785
Update AGENTS.md to include note on executing CLI commands in virtual…
knowsuchagency May 24, 2025
e26aed1
Update README to reflect changes from "Memory options" to "Session op…
knowsuchagency May 24, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ Welcome to the OpenAI Agents SDK repository. This file contains the main points

Coverage can be generated with `make coverage`.

*Note*: Use `uv run ...` to execute arbitrary cli commands within the project's virtual environment.

## Snapshot tests

Some tests rely on inline snapshots. See `tests/README.md` for details on updating them:
Expand Down
111 changes: 110 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,119 @@ The OpenAI Agents SDK is a lightweight yet powerful framework for building multi
1. [**Agents**](https://openai.github.io/openai-agents-python/agents): LLMs configured with instructions, tools, guardrails, and handoffs
2. [**Handoffs**](https://openai.github.io/openai-agents-python/handoffs/): A specialized tool call used by the Agents SDK for transferring control between agents
3. [**Guardrails**](https://openai.github.io/openai-agents-python/guardrails/): Configurable safety checks for input and output validation
4. [**Tracing**](https://openai.github.io/openai-agents-python/tracing/): Built-in tracking of agent runs, allowing you to view, debug and optimize your workflows
4. [**Sessions**](#sessions): Automatic conversation history management across agent runs
5. [**Tracing**](https://openai.github.io/openai-agents-python/tracing/): Built-in tracking of agent runs, allowing you to view, debug and optimize your workflows

Explore the [examples](examples) directory to see the SDK in action, and read our [documentation](https://openai.github.io/openai-agents-python/) for more details.

## Sessions

The Agents SDK provides built-in session memory to automatically maintain conversation history across multiple agent runs, eliminating the need to manually handle `.to_input_list()` between turns.

### Quick start

```python
from agents import Agent, Runner, SQLiteSession

# Create agent
agent = Agent(
name="Assistant",
instructions="Reply very concisely.",
)

# Create a session instance
session = SQLiteSession("conversation_123")

# First turn
result = await Runner.run(
agent,
"What city is the Golden Gate Bridge in?",
session=session
)
print(result.final_output) # "San Francisco"

# Second turn - agent automatically remembers previous context
result = await Runner.run(
agent,
"What state is it in?",
session=session
)
print(result.final_output) # "California"

# Also works with synchronous runner
result = Runner.run_sync(
agent,
"What's the population?",
session=session
)
print(result.final_output) # "Approximately 39 million"
```

### Session options

- **No memory** (default): No session memory when session parameter is omitted
- **`session: Session = DatabaseSession(...)`**: Use a Session instance to manage conversation history

```python
from agents import Agent, Runner, SQLiteSession

# Custom SQLite database file
session = SQLiteSession("user_123", "conversations.db")
agent = Agent(name="Assistant")

# Different session IDs maintain separate conversation histories
result1 = await Runner.run(
agent,
"Hello",
session=session
)
result2 = await Runner.run(
agent,
"Hello",
session=SQLiteSession("user_456", "conversations.db")
)
```

### Custom session implementations

You can implement your own session memory by creating a class that follows the `Session` protocol:

```python
from agents.memory import Session
from typing import List

class MyCustomSession:
"""Custom session implementation following the Session protocol."""

def __init__(self, session_id: str):
self.session_id = session_id
# Your initialization here

async def get_messages(self) -> List[dict]:
# Retrieve conversation history for the session
pass

async def add_messages(self, messages: List[dict]) -> None:
# Store new messages for the session
pass

async def pop_message(self) -> dict | None:
# Remove and return the most recent message from the session
pass

async def clear_session(self) -> None:
# Clear all messages for the session
pass

# Use your custom session
agent = Agent(name="Assistant")
result = await Runner.run(
agent,
"Hello",
session=MyCustomSession("my_session")
)
```

## Get started

1. Set up your Python environment
Expand Down
2 changes: 2 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ The [OpenAI Agents SDK](https://github.com/openai/openai-agents-python) enables
- **Agents**, which are LLMs equipped with instructions and tools
- **Handoffs**, which allow agents to delegate to other agents for specific tasks
- **Guardrails**, which enable the inputs to agents to be validated
- **Sessions**, which automatically maintains conversation history across agent runs

In combination with Python, these primitives are powerful enough to express complex relationships between tools and agents, and allow you to build real-world applications without a steep learning curve. In addition, the SDK comes with built-in **tracing** that lets you visualize and debug your agentic flows, as well as evaluate them and even fine-tune models for your application.

Expand All @@ -21,6 +22,7 @@ Here are the main features of the SDK:
- Python-first: Use built-in language features to orchestrate and chain agents, rather than needing to learn new abstractions.
- Handoffs: A powerful feature to coordinate and delegate between multiple agents.
- Guardrails: Run input validations and checks in parallel to your agents, breaking early if the checks fail.
- Sessions: Automatic conversation history management across agent runs, eliminating manual state handling.
- Function tools: Turn any Python function into a tool, with automatic schema generation and Pydantic-powered validation.
- Tracing: Built-in tracing that lets you visualize, debug and monitor your workflows, as well as use the OpenAI suite of evaluation, fine-tuning and distillation tools.

Expand Down
8 changes: 8 additions & 0 deletions docs/ref/memory.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Memory

::: agents.memory

options:
members:
- Session
- SQLiteSession
37 changes: 36 additions & 1 deletion docs/running_agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ Calling any of the run methods can result in one or more agents running (and hen

At the end of the agent run, you can choose what to show to the user. For example, you might show the user every new item generated by the agents, or just the final output. Either way, the user might then ask a followup question, in which case you can call the run method again.

You can use the base [`RunResultBase.to_input_list()`][agents.result.RunResultBase.to_input_list] method to get the inputs for the next turn.
### Manual conversation management

You can manually manage conversation history using the [`RunResultBase.to_input_list()`][agents.result.RunResultBase.to_input_list] method to get the inputs for the next turn:

```python
async def main():
Expand All @@ -84,6 +86,39 @@ async def main():
# California
```

### Automatic conversation management with Sessions

For a simpler approach, you can use [Sessions](sessions.md) to automatically handle conversation history without manually calling `.to_input_list()`:

```python
from agents import Agent, Runner, SQLiteSession

async def main():
agent = Agent(name="Assistant", instructions="Reply very concisely.")

# Create session instance
session = SQLiteSession("conversation_123")

with trace(workflow_name="Conversation", group_id=thread_id):
# First turn
result = await Runner.run(agent, "What city is the Golden Gate Bridge in?", session=session)
print(result.final_output)
# San Francisco

# Second turn - agent automatically remembers previous context
result = await Runner.run(agent, "What state is it in?", session=session)
print(result.final_output)
# California
```

Sessions automatically:

- Retrieves conversation history before each run
- Stores new messages after each run
- Maintains separate conversations for different session IDs

See the [Sessions documentation](sessions.md) for more details.

## Exceptions

The SDK raises exceptions in certain cases. The full list is in [`agents.exceptions`][]. As an overview:
Expand Down
Loading