> ## Documentation Index
> Fetch the complete documentation index at: https://docs.praison.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Session Persistence

> Automatic session persistence with zero configuration

# Session Persistence

PraisonAI Agents provides automatic session persistence with zero configuration. Simply provide a `session_id` to your Agent and conversation history is automatically saved and restored.

## Quick Start

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

# First conversation
agent = Agent(
    name="Assistant",
    memory={"session_id": "my-session-123"}
)
agent.start("My name is Alice and I love pizza")

# Later, in a new process - history is restored automatically
agent = Agent(
    name="Assistant", 
    memory={"session_id": "my-session-123"}
)
agent.start("What is my name?")  # Agent remembers: "Alice"
```

## How It Works

When you provide a `session_id` to an Agent:

1. **Automatic Persistence**: Conversation history is automatically saved to disk after each message
2. **Automatic Restoration**: When a new Agent is created with the same `session_id`, history is restored
3. **Zero Configuration**: No database setup required - uses JSON files by default

### Default Storage Location

Sessions are stored in: `~/.praisonai/sessions/{session_id}.json`

## Behavior Matrix

| Scenario                             | Behavior                     |
| ------------------------------------ | ---------------------------- |
| `session_id` provided, no DB         | JSON persistence (automatic) |
| `session_id` provided, with DB       | DB adapter used              |
| No `session_id`, same Agent instance | In-memory only               |
| No `session_id`, new Agent instance  | No history                   |

## In-Memory Memory (Default)

Even without `session_id`, the same Agent instance remembers previous messages:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(name="Assistant")

# First message
agent.chat("My favorite number is 42")

# Second message - agent remembers
agent.chat("What is my favorite number?")  # Agent responds: "42"
```

<Note>
  In-memory memory is lost when the Agent instance is garbage collected or the process ends.
  Use `session_id` for persistence across processes.
</Note>

## Persistent Sessions

### Basic Usage

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

# Create agent with session_id
agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant.",
    memory={"session_id": "user-123-chat"}
)

# Conversation is automatically persisted
response = agent.chat("Remember that my birthday is January 15th")
```

### Resuming Sessions

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# In a new Python process or after restart
from praisonaiagents import Agent

# Same session_id restores history
agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant.",
    memory={"session_id": "user-123-chat"}
)

# Agent remembers previous conversation
response = agent.chat("When is my birthday?")
# Agent responds: "Your birthday is January 15th"
```

### Session File Format

Sessions are stored as JSON files:

```json theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
{
  "session_id": "user-123-chat",
  "messages": [
    {"role": "user", "content": "Remember my birthday is January 15th", "timestamp": 1704153600.0},
    {"role": "assistant", "content": "I'll remember that!", "timestamp": 1704153601.5}
  ],
  "created_at": "2026-01-02T04:00:00+00:00",
  "updated_at": "2026-01-02T04:01:00+00:00",
  "agent_name": "Assistant"
}
```

## Multi-Process Safety

The session store uses file locking to ensure safe concurrent access:

* **Unix**: Uses `fcntl.flock()` for file locking
* **Windows**: Uses `msvcrt.locking()` for file locking
* **Atomic Writes**: Uses temp file + rename to prevent corruption

Multiple processes can safely read/write to the same session.

## Direct Session Store Access

For advanced use cases, you can access the session store directly:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents.session import get_default_session_store

store = get_default_session_store()

# Add messages
store.add_user_message("session-123", "Hello")
store.add_assistant_message("session-123", "Hi there!")

# Get history
history = store.get_chat_history("session-123")
# [{"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi there!"}]

# List all sessions
sessions = store.list_sessions()

# Delete a session
store.delete_session("session-123")
```

### Custom Session Directory

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents.session import DefaultSessionStore

store = DefaultSessionStore(
    session_dir="/custom/path/sessions",
    max_messages=200,  # Default: 100
    lock_timeout=10.0,  # Default: 5.0 seconds
)
```

## Using with DB Adapter

When a DB adapter is provided, it takes precedence over JSON persistence:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

# Custom DB adapter (e.g., PostgreSQL, MongoDB)
class MyDbAdapter:
    def on_agent_start(self, agent_name, session_id, user_id=None, metadata=None):
        # Load history from database
        return []
    
    def on_user_message(self, session_id, content):
        # Save user message to database
        pass
    
    def on_agent_message(self, session_id, content):
        # Save agent message to database
        pass

agent = Agent(
    name="Assistant",
    memory={"session_id": "my-session"},
    db=MyDbAdapter()
)
```

## Context Caching

For cost optimization with Anthropic models, use `caching=True`:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
agent = Agent(
    name="Assistant",
    memory={"session_id": "my-session"},
    caching=True,  # Enables Anthropic prompt caching
)
```

This caches the system prompt, reducing token costs for repeated conversations.

## Bot Session Persistence

Bots now use the **same session store** as agents. Each user gets a persistent session that survives bot restarts:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents.session import get_default_session_store

# BotSessionManager with persistent store
from praisonai.bots._session import BotSessionManager

mgr = BotSessionManager(
    store=get_default_session_store(),
    platform="telegram",
)

# Each user gets a unique session key: bot_telegram_{user_id}
response = await mgr.chat(agent, "user123", "Hello!")
# Session persisted to ~/.praisonai/sessions/bot_telegram_user123.json
```

<Note>
  Without a `store` parameter, `BotSessionManager` falls back to in-memory-only mode for backward compatibility.
</Note>

## Session Store Protocol

All session stores implement `SessionStoreProtocol` — a lightweight interface that enables swapping backends:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents.session import SessionStoreProtocol

# Any class with these 5 methods satisfies the protocol:
# add_message(), get_chat_history(), clear_session(),
# delete_session(), session_exists()

assert isinstance(get_default_session_store(), SessionStoreProtocol)
```

<Card icon="plug" href="/features/session-protocol">
  Learn more about building custom session stores
</Card>

## Best Practices

1. **Use meaningful session IDs**: Include user ID or context in the session ID
   ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
   session_id = f"user-{user_id}-{conversation_type}"
   ```

2. **Handle session limits**: Default max messages is 100. Older messages are trimmed.

3. **Clean up old sessions**: Use `store.delete_session()` to remove unused sessions.

4. **Use prompt caching**: Enable `caching=True` for Anthropic models to reduce costs.

## API Reference

### Agent Parameters

| Parameter        | Type        | Description                                |
| ---------------- | ----------- | ------------------------------------------ |
| `session_id`     | `str`       | Session identifier for persistence         |
| `db`             | `DbAdapter` | Optional database adapter (overrides JSON) |
| `prompt_caching` | `bool`      | Enable Anthropic prompt caching            |

### DefaultSessionStore Methods

| Method                                       | Description               |
| -------------------------------------------- | ------------------------- |
| `add_message(session_id, role, content)`     | Add a message             |
| `add_user_message(session_id, content)`      | Add a user message        |
| `add_assistant_message(session_id, content)` | Add an assistant message  |
| `get_chat_history(session_id, max_messages)` | Get chat history          |
| `get_session(session_id)`                    | Get full session data     |
| `clear_session(session_id)`                  | Clear all messages        |
| `delete_session(session_id)`                 | Delete session completely |
| `list_sessions(limit)`                       | List all sessions         |
| `session_exists(session_id)`                 | Check if session exists   |
