Agent Session Management

Build stateful applications with persistent sessions in PraisonAI

Sessions enable your agents to remember conversations across restarts. Just add a session_id to your agent’s memory configuration.

Diagram

session_id

👤 User

🤖 Agent

💾 memory=

📁 Session Store

🔄 Resume Later

Quick Start

  1. Install PraisonAI Agents
    bash
    pip install praisonaiagents
  2. Create Agent with Session
    python
    from praisonaiagents import Agent
    
    # Create agent with session persistence
    agent = Agent(
        name="Assistant",
        instructions="You are a helpful assistant",
        memory={"session_id": "my-session-123"}  # Enable persistence!
    )
    
    # First conversation
    agent.start("My name is Alice and I love pizza")
  3. Resume Later
    python
    # In a new Python process - history is automatically restored!
    from praisonaiagents import Agent
    
    agent = Agent(
        name="Assistant",
        instructions="You are a helpful assistant",
        memory={"session_id": "my-session-123"}  # Same session_id
    )
    
    agent.start("What's my name?")  # Agent remembers: "Alice"

How It Works

Diagram

‘Later Run’

‘First Run’

Persisted

Agent Created

memory=session_id

Chat: ‘I’m Alice’

💾 Auto-saved to disk

Agent Created

Same session_id

📂 History Restored

Chat: ‘What’s my name?’

✓ Remembers Alice!

ScenarioBehavior
memory={"session_id": "..."}✅ Auto-persisted to JSON
memory={"session_id": "...", "db": "..."}✅ Persisted to database
memory=True (no session_id)⚠️ In-memory only (lost on restart)
No memory config⚠️ In-memory only (lost on restart)

Configuration Options

Using MemoryConfig (Recommended)

For full control, use the MemoryConfig class:

python
from praisonaiagents import Agent, MemoryConfig

agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant",
    memory=MemoryConfig(
        session_id="my-session-123",
        user_id="user-456",           # Optional: for multi-user apps
        backend="file",               # "file", "sqlite", "redis", "postgres"
        auto_memory=True,             # Auto-extract important info
    )
)

Using Dict Shorthand

For quick setup, use a dictionary:

python
from praisonaiagents import Agent

# Simple session persistence
agent = Agent(
    name="Assistant",
    memory={"session_id": "my-session"}
)

# With database backend
agent = Agent(
    name="Assistant",
    memory={
        "session_id": "my-session",
        "db": "postgresql://localhost/mydb"
    }
)

Database Persistence

For production apps, persist sessions to a database:

Diagram

🤖 Agent

memory=

📄 JSON File

SQLite

PostgreSQL

Redis

PostgreSQL
from praisonaiagents import Agent

agent = Agent(
    name="Assistant",
    memory={
        "session_id": "user-123",
        "db": "postgresql://user:pass@localhost/mydb"
    }
)
SQLite
from praisonaiagents import Agent

agent = Agent(
    name="Assistant",
    memory={
        "session_id": "user-123",
        "db": "sqlite:///sessions.db"
    }
)
Redis
from praisonaiagents import Agent

agent = Agent(
    name="Assistant",
    memory={
        "session_id": "user-123",
        "db": "redis://localhost:6379"
    }
)

Multi-User Sessions

For apps with multiple users, include user_id to isolate conversations:

python
from praisonaiagents import Agent, MemoryConfig

def create_agent_for_user(user_id: str):
    return Agent(
        name="Assistant",
        instructions="You are a helpful assistant",
        memory=MemoryConfig(
            session_id=f"user-{user_id}-main",
            user_id=user_id,
        )
    )

# Each user gets isolated sessions
alice_agent = create_agent_for_user("alice")
bob_agent = create_agent_for_user("bob")

# Alice's conversations are separate from Bob's
alice_agent.start("My favorite color is blue")
bob_agent.start("My favorite color is red")

Using the Session Class

For advanced control over memory and knowledge, use the Session class:

python
from praisonaiagents import Session

# Create a session
session = Session(
    session_id="research-project",
    user_id="researcher-1"
)

# Create agent within session context
agent = session.Agent(
    name="Research Assistant",
    instructions="Help with research tasks",
    memory=True
)

# Chat with the agent
response = agent.start("Find papers about machine learning")

# Save custom state
session.save_state({
    "project": "ML Research",
    "papers_found": 5
})

Advanced Topics

Hierarchical Sessions (Forking & Snapshots)

For complex workflows, use hierarchical sessions with forking and snapshots:

python
from praisonaiagents.session.hierarchy import HierarchicalSessionStore

store = HierarchicalSessionStore()

# Create main session
main_id = store.create_session(title="Main Conversation")
store.add_message(main_id, "user", "Let's discuss Python")

# Create a snapshot before risky changes
snapshot_id = store.create_snapshot(main_id, label="Safe point")

# Fork to explore alternatives
fork_id = store.fork_session(main_id, title="Alternative approach")

# Revert if needed
store.revert_to_snapshot(main_id, snapshot_id)

See Session Hierarchy for full documentation.

Remote Agent Sessions

Connect to agents running on remote machines:

python
from praisonaiagents import Session

# Connect to remote agent
session = Session(
    agent_url="http://192.168.1.100:8000/agent",
    session_id="remote-user-123"
)

# Chat with remote agent
response = session.chat("Hello from remote client!")
Custom Database Adapter

Implement the DbAdapter protocol for custom persistence:

python
from praisonaiagents import Agent

class MyDbAdapter:
    def on_agent_start(self, agent_name, session_id, user_id=None, metadata=None):
        # Return previous messages for resume
        return []

    def on_user_message(self, session_id, content, metadata=None):
        # Save user message
        pass

    def on_agent_message(self, session_id, content, metadata=None):
        # Save agent response
        pass

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

See Database Adapters for full protocol.

Direct Session Store Access

For low-level control, access the session store directly:

python
from praisonaiagents.session import get_default_session_store

store = get_default_session_store()

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

# Get chat history
history = store.get_chat_history("session-123")

# List all sessions
sessions = store.list_sessions(limit=50)

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

Atomic batch replace — when you need to rewrite the whole history under a single lock (compaction, redaction, multi-worker bot saves):

python
from praisonaiagents.session import get_default_session_store

store = get_default_session_store()

store.set_chat_history(
    "session-123",
    [
        {"role": "user", "content": "Hello"},
        {"role": "assistant", "content": "Hi there!"},
    ],
)

Safer than clear_session() + a loop of add_message() — there is no window where another worker can read an empty history.

Best Practices

Session ID Patterns

python
from praisonaiagents import Agent

# Pattern 1: User-based (recommended for most apps)
agent = Agent(
    name="Assistant",
    memory={"session_id": f"user-{user_id}-main"}
)

# Pattern 2: Conversation-based (new session per chat)
import uuid
agent = Agent(
    name="Assistant",
    memory={"session_id": f"conv-{uuid.uuid4().hex[:8]}"}
)

# Pattern 3: Task-based (for workflows)
agent = Agent(
    name="Assistant",
    memory={"session_id": f"task-{task_id}-{user_id}"}
)

CLI Commands

bash
# List all sessions
praisonai session list

# Start interactive session
praisonai session start my-session

# Resume a session
praisonai session resume my-session

# Show session details
praisonai session show my-session

# Delete a session
praisonai session delete my-session

Session Lifecycle & Cleanup

Session.close() now properly invokes memory.close_connections(), which closes the underlying adapter (ChromaDB references, MongoDB client, etc.):

Diagram
sequenceDiagram
    participant User
    participant Session
    participant Memory
    participant Adapter

    User->>Session: close()
    Session->>Memory: close_connections()
    Memory->>Adapter: close()
    Adapter-->>Memory: cleanup complete
    Memory-->>Session: cleanup complete
    Session-->>User: session closed

    classDef user fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef session fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef memory fill:#10B981,stroke:#7C90A0,color:#fff
    classDef adapter fill:#F59E0B,stroke:#7C90A0,color:#fff

    class User user
    class Session session
    class Memory memory
    class Adapter adapter

Automatic Cleanup Example

python
from praisonaiagents import Agent

# Session cleanup no longer requires manual teardown
try:
    agent = Agent(
        name="Assistant",
        memory={"session_id": "my-session"}
    )

    # Use agent...
    agent.start("Hello")

finally:
    # Session.close() automatically handles memory cleanup
    if hasattr(agent, '_memory_instance'):
        agent._memory_instance.close_connections()

Troubleshooting

Session not restoring
  • Verify session_id is exactly the same
  • Check storage directory exists: ~/.praisonai/sessions/
  • Ensure file permissions allow read/write
  • Try invalidating cache: store.invalidate_cache(session_id)
File lock timeout
  • Another process may be holding the lock
  • Increase lock_timeout parameter
  • Check for stale .lock files and remove them
Memory issues with large sessions
  • Set max_messages limit on DefaultSessionStore
  • Use get_chat_history(max_messages=50) to limit retrieval
  • Consider using SQLite backend for better performance
Remote session connection failed
  • Verify agent URL is correct and accessible
  • Check firewall/network settings
  • Ensure remote agent has /health endpoint
  • Increase timeout parameter for slow networks

API Reference

Agent Session Parameters

The memory parameter on Agent accepts these session-related options:

ParameterTypeDescription
session_idstrUnique session identifier for persistence
user_idstrUser identifier for multi-user isolation
dbstrDatabase URL (postgresql://..., sqlite:///..., redis://...)
backendstrStorage backend: "file", "sqlite", "redis", "postgres"
auto_memoryboolAuto-extract important info from conversations
python
from praisonaiagents import Agent, MemoryConfig

# Full configuration example
agent = Agent(
    name="Assistant",
    memory=MemoryConfig(
        session_id="user-123-main",
        user_id="user-123",
        backend="postgres",
        db="postgresql://localhost/mydb",
        auto_memory=True,
    )
)

Session Class Parameters

ParameterTypeDefaultDescription
session_idstrAuto-generatedUnique session identifier
user_idstr"default_user"User identifier
agent_urlstrNoneURL for remote agent
timeoutint30HTTP timeout (seconds)

Related Documentation