> ## Documentation Index
> Fetch the complete documentation index at: https://agno-v2.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Persistent Session with History Context

> Store agent conversation history in PostgreSQL and limit how many past runs are added to the context with num_history_runs.

Store conversation history in the session and add a configurable number of previous runs to the agent context.

## Code

```python persistent_session_history.py theme={null}
"""
This example shows how to use the session history to store the conversation history.
add_history_to_context flag is used to add the history to the messages.
num_history_runs is used to set the number of history runs to add to the messages.
"""

from agno.agent import Agent
from agno.db.postgres import PostgresDb
from agno.models.openai import OpenAIResponses

db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"

db = PostgresDb(db_url=db_url, session_table="sessions")

agent = Agent(
    model=OpenAIResponses(id="gpt-5.2"),
    db=db,
    add_history_to_context=True,
    num_history_runs=2,
)

agent.print_response("Tell me a new interesting fact about space")
```

## Usage

<Snippet file="create-venv-step.mdx" />

**1. Install required libraries**

```bash theme={null}
uv pip install -U agno openai sqlalchemy "psycopg[binary]"
```

**2. Set environment variables**

```bash theme={null}
export OPENAI_API_KEY=****
```

**3. Start PostgreSQL database**

```bash theme={null}
./cookbook/scripts/run_pgvector.sh
```

**4. Run the agent**

```bash theme={null}
python persistent_session_history.py
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.