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

# SQLite Persistence

> Local file database persistence for development and single-instance applications

SQLite provides local file-based SQL database persistence, perfect for development, prototypes, and single-instance applications that need reliable data storage without external dependencies.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "SQLite Persistence"
        A[🧠 Agent] --> B[💬 Conversations]
        B --> C[📄 SQLite File]
        C --> D[💾 Local Disk]
        A --> E[🔍 Query History]
        E --> C
    end
    
    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef data fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef storage fill:#10B981,stroke:#7C90A0,color:#fff
    
    class A agent
    class B,E data
    class C,D storage
```

## Quick Start

<Steps>
  <Step title="Basic Setup">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, db

    agent = Agent(
        name="LocalBot",
        instructions="You are a helpful assistant.",
        db=db(database_url="sqlite:///agent_conversations.db"),
        session_id="local-session"
    )

    response = agent.chat("Hello! Can you remember this conversation?")
    print(response)  # Conversation automatically saved to SQLite
    ```
  </Step>

  <Step title="Custom Database Path">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, db
    import tempfile
    import os

    # Create database in specific location
    db_path = os.path.join(tempfile.gettempdir(), "my_agent.db")
    my_db = db.SQLiteDB(path=db_path)

    agent = Agent(
        name="CustomBot",
        instructions="You are a helpful assistant.",
        db=my_db,
        session_id="custom-session"
    )

    agent.chat("This is stored in my custom location!")
    ```
  </Step>
</Steps>

***

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant Agent
    participant SQLiteDB as SQLite Database
    participant File as Database File
    
    Agent->>SQLiteDB: Initialize connection
    SQLiteDB->>File: Create/open .db file
    Agent->>SQLiteDB: Save message
    SQLiteDB->>File: INSERT INTO messages
    Agent->>SQLiteDB: Query history
    SQLiteDB->>File: SELECT FROM messages
    File-->>SQLiteDB: Return rows
    SQLiteDB-->>Agent: Conversation history
```

SQLite stores conversation data in tables within a single file:

| Table        | Content                 | Purpose                           |
| ------------ | ----------------------- | --------------------------------- |
| `sessions`   | Session metadata        | Track conversation sessions       |
| `messages`   | User and agent messages | Complete conversation history     |
| `runs`       | Agent execution runs    | Track agent processing steps      |
| `tool_calls` | Tool usage              | Record function calls and results |

***

## Configuration Options

### Database URL Format

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Simple file path
db(database_url="sqlite:///conversations.db")

# Absolute path
db(database_url="sqlite:////absolute/path/to/database.db")

# Relative path with subdirectory
db(database_url="sqlite:///data/agent_storage.db")

# In-memory database (temporary)
db(database_url="sqlite:///:memory:")
```

### Advanced Configuration

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

# Custom SQLite database with specific options
my_db = db.SQLiteDB(
    path="./data/agents.db",
    # SQLite-specific options can be configured via the database URL
)

agent = Agent(
    name="ConfiguredBot",
    instructions="You are a helpful assistant.",
    db=my_db,
    session_id="configured-session"
)
```

***

## Session Resume Example

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

# First conversation
agent1 = Agent(
    name="Assistant",
    db=db(database_url="sqlite:///memory.db"),
    session_id="user-alice"
)

agent1.chat("My favorite color is blue")
agent1.chat("I work as a software engineer")

# Simulate application restart
agent1 = None

# Resume conversation - automatically loads history
agent2 = Agent(
    name="Assistant", 
    db=db(database_url="sqlite:///memory.db"),
    session_id="user-alice"  # Same session ID
)

response = agent2.chat("What's my favorite color and job?")
print(response)  # Will reference blue color and software engineering
```

***

## Direct Database Access

For advanced use cases, query the SQLite database directly:

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

# Create agent and have conversation
agent = Agent(
    name="DataBot",
    db=db(database_url="sqlite:///analytics.db"),
    session_id="data-session"
)

agent.chat("Analyze quarterly sales data")

# Direct database access for reporting
conn = sqlite3.connect("analytics.db")
cursor = conn.cursor()

# Query conversation history
cursor.execute("""
    SELECT role, content, created_at 
    FROM messages 
    WHERE session_id = 'data-session'
    ORDER BY created_at
""")

messages = cursor.fetchall()
for role, content, timestamp in messages:
    print(f"[{timestamp}] {role}: {content}")

conn.close()
```

***

## Production Considerations

<AccordionGroup>
  <Accordion title="File Permissions and Location">
    * Ensure the application has write permissions to the database directory
    * Use absolute paths for production deployments
    * Consider using environment variables for database paths
    * Back up the .db file regularly
  </Accordion>

  <Accordion title="Concurrent Access">
    * SQLite supports multiple readers but only one writer
    * Use WAL mode for better concurrency: `PRAGMA journal_mode=WAL`
    * Consider connection pooling for multi-threaded applications
    * For high concurrency, migrate to PostgreSQL or MySQL
  </Accordion>

  <Accordion title="Database Maintenance">
    * Monitor database file size growth
    * Use `VACUUM` periodically to reclaim space
    * Implement log rotation for old conversations
    * Set up automated backups of the .db file
  </Accordion>

  <Accordion title="Migration Path">
    * Start with SQLite for development and MVP
    * SQLite can handle thousands of conversations efficiently
    * Migrate to PostgreSQL when you need multi-instance deployment
    * Export data using SQL dumps for migration
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="PostgreSQL Persistence" icon="elephant" href="/docs/features/persistence-postgres">
    Scale up to production PostgreSQL when you outgrow SQLite
  </Card>

  <Card title="Database Persistence Overview" icon="database" href="/docs/features/persistence">
    Compare all available persistence backends
  </Card>
</CardGroup>
