Skip to main content

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

from praisonaiagents import Agent

# First conversation
agent = Agent(
    name="Assistant",
    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", 
    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: ~/.praison/sessions/{session_id}.json

Behavior Matrix

ScenarioBehavior
session_id provided, no DBJSON persistence (automatic)
session_id provided, with DBDB adapter used
No session_id, same Agent instanceIn-memory only
No session_id, new Agent instanceNo history

In-Memory Memory (Default)

Even without session_id, the same Agent instance remembers previous messages:
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"
In-memory memory is lost when the Agent instance is garbage collected or the process ends. Use session_id for persistence across processes.

Persistent Sessions

Basic Usage

from praisonaiagents import Agent

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

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

Resuming Sessions

# 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.",
    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:
{
  "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:
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

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:
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",
    session_id="my-session",
    db=MyDbAdapter()
)

Context Caching

For cost optimization with Anthropic models, use prompt_caching=True:
agent = Agent(
    name="Assistant",
    session_id="my-session",
    prompt_caching=True,  # Enables Anthropic prompt caching
)
This caches the system prompt, reducing token costs for repeated conversations.

Best Practices

  1. Use meaningful session IDs: Include user ID or context in the session ID
    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 prompt_caching=True for Anthropic models to reduce costs.

API Reference

Agent Parameters

ParameterTypeDescription
session_idstrSession identifier for persistence
dbDbAdapterOptional database adapter (overrides JSON)
prompt_cachingboolEnable Anthropic prompt caching

DefaultSessionStore Methods

MethodDescription
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