> ## 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.

# 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.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    User([👤 User]) --> Agent[🤖 Agent]
    Agent --> Memory{💾 memory=}
    Memory -->|session_id| Store[📁 Session Store]
    Store --> Resume([🔄 Resume Later])
    
    classDef user fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef agent fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef store fill:#2E8B57,stroke:#7C90A0,color:#fff
    
    class User,Resume user
    class Agent,Memory agent
    class Store store
```

## Quick Start

<Steps>
  <Step title="Install PraisonAI Agents">
    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    pip install praisonaiagents
    ```
  </Step>

  <Step title="Create Agent with Session">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    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")
    ```
  </Step>

  <Step title="Resume Later">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # 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"
    ```
  </Step>
</Steps>

<Note>
  **Default Storage**: `~/.praisonai/sessions/{session_id}.json`
</Note>

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph TB
    subgraph "First Run"
        A1[Agent Created] --> A2[memory=session_id]
        A2 --> A3[Chat: "I'm Alice"]
        A3 --> A4[💾 Auto-saved to disk]
    end
    
    subgraph "Later Run"
        B1[Agent Created] --> B2[Same session_id]
        B2 --> B3[📂 History Restored]
        B3 --> B4[Chat: "What's my name?"]
        B4 --> B5[✓ Remembers Alice!]
    end
    
    A4 -.->|Persisted| B3
    
    classDef first fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef later fill:#2E8B57,stroke:#7C90A0,color:#fff
    
    class A1,A2,A3,A4 first
    class B1,B2,B3,B4,B5 later
```

| 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:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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 theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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:

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    Agent[🤖 Agent] --> Memory{memory=}
    Memory --> JSON[📄 JSON File]
    Memory --> SQLite[(SQLite)]
    Memory --> Postgres[(PostgreSQL)]
    Memory --> Redis[(Redis)]
    
    classDef agent fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef db fill:#2E8B57,stroke:#7C90A0,color:#fff
    
    class Agent,Memory agent
    class JSON,SQLite,Postgres,Redis db
```

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

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

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

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

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

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

## Multi-User Sessions

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

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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 theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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

<Accordion title="Hierarchical Sessions (Forking & Snapshots)">
  For complex workflows, use hierarchical sessions with forking and snapshots:

  ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
  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](/features/session-hierarchy) for full documentation.
</Accordion>

<Accordion title="Remote Agent Sessions">
  Connect to agents running on remote machines:

  ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
  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!")
  ```

  <Warning>
    Remote sessions don't support local memory operations.
  </Warning>
</Accordion>

<Accordion title="Custom Database Adapter">
  Implement the `DbAdapter` protocol for custom persistence:

  ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
  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](/sdk/praisonaiagents/db) for full protocol.
</Accordion>

<Accordion title="Direct Session Store Access">
  For low-level control, 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 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")
  ```
</Accordion>

## Best Practices

<CardGroup cols={2}>
  <Card title="Use Meaningful Session IDs" icon="fingerprint">
    Include user ID or task context: `user-123-main`, `task-456-research`
  </Card>

  <Card title="Isolate Users" icon="users">
    Always include `user_id` in multi-user apps to prevent data leakage
  </Card>

  <Card title="Choose Right Backend" icon="database">
    JSON for dev, SQLite for single-server, PostgreSQL for production
  </Card>

  <Card title="Set Message Limits" icon="list-ol">
    Use `max_messages` to prevent unbounded growth
  </Card>
</CardGroup>

### Session ID Patterns

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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 theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# 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.):

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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 theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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

<AccordionGroup>
  <Accordion title="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)`
  </Accordion>

  <Accordion title="File lock timeout">
    * Another process may be holding the lock
    * Increase `lock_timeout` parameter
    * Check for stale `.lock` files and remove them
  </Accordion>

  <Accordion title="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
  </Accordion>

  <Accordion title="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
  </Accordion>
</AccordionGroup>

## 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                    |

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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)    |

## Related Documentation

<CardGroup cols={2}>
  <Card title="Session Persistence" icon="database" href="/features/session-persistence">
    Detailed persistence options
  </Card>

  <Card title="Session Hierarchy" icon="sitemap" href="/features/session-hierarchy">
    Forking and snapshots
  </Card>

  <Card title="Memory System" icon="brain" href="/concepts/memory">
    Memory integration
  </Card>

  <Card title="CLI Commands" icon="terminal" href="/cli/session">
    Command-line management
  </Card>
</CardGroup>
