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.
Quick Start
- Install PraisonAI Agents
bash pip install praisonaiagents - 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") - 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
| Scenario | Behavior |
|---|---|
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:
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"
}
)from praisonaiagents import Agent
agent = Agent(
name="Assistant",
memory={
"session_id": "user-123",
"db": "sqlite:///sessions.db"
}
)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:
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
Hierarchical Sessions (Forking & Snapshots)
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.
Remote Agent Sessions
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!")Custom Database Adapter
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.
Direct Session Store Access
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")Atomic batch replace — when you need to rewrite the whole history under a single lock (compaction, redaction, multi-worker bot saves):
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
Include user ID or task context: user-123-main, task-456-research
Always include user_id in multi-user apps to prevent data leakage
JSON for dev, SQLite for single-server, PostgreSQL for production
Set Message LimitsUse 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-sessionSession Lifecycle & Cleanup
Session.close() now properly invokes memory.close_connections(), which closes the underlying adapter (ChromaDB references, MongoDB client, etc.):
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 adapterAutomatic Cleanup Example
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_idis 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_timeoutparameter - Check for stale
.lockfiles and remove them
Memory issues with large sessions
- Set
max_messageslimit 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
/healthendpoint - Increase
timeoutparameter for slow networks
API Reference
Agent Session Parameters
The memory parameter on Agent accepts these session-related options:
| Parameter | Type | Description |
|---|---|---|
session_id | str | Unique session identifier for persistence |
user_id | str | User identifier for multi-user isolation |
db | str | Database URL (postgresql://..., sqlite:///..., redis://...) |
backend | str | Storage backend: "file", "sqlite", "redis", "postgres" |
auto_memory | bool | Auto-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
| Parameter | Type | Default | Description |
|---|---|---|---|
session_id | str | Auto-generated | Unique session identifier |
user_id | str | "default_user" | User identifier |
agent_url | str | None | URL for remote agent |
timeout | int | 30 | HTTP timeout (seconds) |