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

Quick Start

1

Install PraisonAI Agents

pip install praisonaiagents
2

Create Agent with Session

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

# 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"
Default Storage: ~/.praisonai/sessions/{session_id}.json

How It Works

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

For full control, use the MemoryConfig class:
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:
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:
from praisonaiagents import Agent

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

Multi-User Sessions

For apps with multiple users, include user_id to isolate conversations:
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:
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

For complex workflows, use hierarchical sessions with forking and snapshots:
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.
Connect to agents running on remote machines:
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!")
Remote sessions don’t support local memory operations.
Implement the DbAdapter protocol for custom persistence:
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.
For low-level control, access the session store directly:
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")

Best Practices

Use Meaningful Session IDs

Include user ID or task context: user-123-main, task-456-research

Isolate Users

Always include user_id in multi-user apps to prevent data leakage

Choose Right Backend

JSON for dev, SQLite for single-server, PostgreSQL for production

Set Message Limits

Use max_messages to prevent unbounded growth

Session ID Patterns

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

# 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

Troubleshooting

  • 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)
  • Another process may be holding the lock
  • Increase lock_timeout parameter
  • Check for stale .lock files and remove them
  • Set max_messages limit on DefaultSessionStore
  • Use get_chat_history(max_messages=50) to limit retrieval
  • Consider using SQLite backend for better performance
  • 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
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)