Database Persistence

Persist agent conversations, state, and knowledge across SQL, key-value, vector, and cloud backends

Database persistence keeps conversation history and state across restarts — pick a backend for your scale.

python
from praisonaiagents import Agent, MemoryConfig
from praisonaiagents import db

agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant.",
    memory=MemoryConfig(
        db=db(database_url="sqlite:///conversations.db"),
        session_id="my-session",
    ),
)
agent.start("Hello — saved automatically")

The user returns later; the configured backend restores conversation history and agent state.

Diagram

🤖 Agent

💬 Conversations

🔄 State

📚 Knowledge

SQL / Turso / Supabase

Redis / Valkey / DynamoDB / GCS

pgvector / Pinecone / Chroma / …

Quick Start

  1. Simple Usage
    python
    from praisonaiagents import Agent, MemoryConfig
    from praisonaiagents import db
    
    agent = Agent(
        name="Assistant",
        memory=MemoryConfig(
            db=db(database_url="sqlite:///conversations.db"),
            session_id="session-1",
        ),
    )
    agent.start("Hello!")
  2. With Configuration

    Hybrid setup — SQL for conversations, Redis for state:

    python
    import os
    from praisonaiagents import Agent, MemoryConfig
    from praisonaiagents import db
    
    agent = Agent(
        name="Assistant",
        memory=MemoryConfig(
            db=db(
                database_url=os.getenv("PRAISON_CONVERSATION_URL", "sqlite:///conversations.db"),
                state_url=os.getenv("PRAISON_STATE_URL", "redis://localhost:6379"),
            ),
            session_id="hybrid-session",
        ),
    )
    agent.start("Conversations in SQL, state in Redis")

How It Works

Diagram
Storage BackendAgentUserStorage BackendAgentUserstart(prompt)load historyprior messagessave user + agent messagesreply
ComponentPurposeExample backendsAsync variant
ConversationStoreMessages, sessions, metadataSQLite, PostgreSQL, MySQLAsyncConversationStore
StateStoreApplication state, key-value dataRedis, MongoDBAsyncStateStore
KnowledgeStoreVector embeddings for RAGQdrant, Pinecone, pgvectorAsyncKnowledgeStore
DefaultSessionStoreFile-based sessionsJSON files on disk—

Storage Backend Options

The registry supports 12 conversation, 9 state, and 20 knowledge backends — configure each store by URL scheme.

Conversation

BackendAliasesBest for
sqlite—Local development, single instance
sync_sqlitesqlite_syncSynchronous file access
async_sqliteaiosqlite, sqlite_asyncAsync file access
postgresneon, cockroachdb, crdb, cockroach, xataProduction SQL
async_postgresasyncpg, postgres_asyncAsync Postgres
mysql—Existing MySQL infrastructure
async_mysqlaiomysql, mysql_asyncAsync MySQL
tursolibsqlServerless SQLite over the network
supabase—Managed Postgres platform
singlestore—Distributed SQL
surrealdb—Multi-model database
json—Zero-dependency file storage

State

BackendAliasesBest for
memory—In-process, non-persistent
redis—Sub-millisecond in-memory state
valkey—Redis-compatible OSS fork
upstash—Serverless cloud KV
dynamodb—AWS-managed KV
firestore—Google Cloud document store
mongodb—Document-based state
async_mongodbmotor, mongodb_asyncAsync MongoDB
gcs—Object storage (requires bucket_name)

Knowledge

BackendAliasesBest for
chromachromadbEmbedded vector store
qdrant—Managed vector search
pinecone—Serverless vector database
weaviate—Hybrid search
lancedb—Embedded columnar vectors
milvus—Scalable vector search
pgvector—Postgres vector extension
redis—Redis vector index
valkey—Valkey vector index
cassandra—Wide-column vectors
clickhouse—Analytics-backed vectors
mongodb_vectormongodb_atlas, mongo_vectorMongoDB Atlas vectors
couchbase—Distributed document vectors
singlestore_vectorsinglestore_vDistributed SQL vectors
surrealdb_vectorsurrealdb_vMulti-model vectors
upstash_vectorupstash_vServerless vector KV
cosmosdbcosmos, azure_cosmos, cosmosdb_vectorAzure Cosmos DB vectors
lightrag—Graph-augmented retrieval
langchainlangchain_adapterLangChain vector adapter
llamaindexllama_index, llamaindex_adapterLlamaIndex adapter

Dedicated guides exist for the most common backends:


Selecting a backend

The store kind narrows which URL schemes resolve to a registered backend. database_url= reaches conversation stores, state_url= reaches state stores, and knowledge_url= reaches vector stores. Kind-specific schemes take priority over generic http(s):// sniffing, so state_url="mongodb://…" reaches the MongoDB state store rather than falling through to conversation detection.

Diagram

state_url

knowledge_url

database_url

🔗 store URL

Which kind?

state schemes

knowledge schemes

conversation schemes

⚙️ state_backend= / knowledge_backend= / database_backend=

✅ wins over URL detection

🗄️ registered backend

URL schemes per store kind

State schemes

state_url= resolves these schemes to a state backend (from PraisonAIDB._STATE_URL_SCHEMES):

SchemeResolves to state backend
redis://, rediss://redis
valkey://valkey
dynamodb://dynamodb
firestore://firestore
mongodb://, mongodb+srv://mongodb
upstash://upstash
memory://memory

Knowledge schemes

knowledge_url= resolves these schemes to a knowledge backend (from PraisonAIDB._KNOWLEDGE_URL_SCHEMES):

SchemeResolves to knowledge backend
chroma://, chromadb://chroma
qdrant://qdrant
weaviate://weaviate
lancedb://lancedb
milvus://milvus
pgvector://pgvector (rewritten to postgresql:// before it reaches psycopg2)
surrealdb://surrealdb_vector
redis://redis
valkey://valkey

Explicit backend override

Some registered backends need out-of-band config the URL cannot carry — GCS (bucket_name), Cosmos DB (connection_string + database + container), and any custom driver whose scheme is not listed above. Reach them by naming the backend explicitly:

python
from praisonaiagents import Agent, MemoryConfig
from praisonaiagents import db

agent = Agent(
    name="Assistant",
    memory=MemoryConfig(
        db=db(
            state_backend="gcs",            # scheme-less state backend
            state_options={"bucket_name": "my-state-bucket"},
            knowledge_backend="cosmosdb",   # scheme-less knowledge backend
            knowledge_options={
                "connection_string": "AccountEndpoint=…",
                "database": "praison",
                "container": "vectors",
            },
        ),
        session_id="session-1",
    ),
)
agent.start("State in GCS, vectors in Cosmos DB")

database_backend=, state_backend=, and knowledge_backend= are keyword-only and always win over URL scheme detection — use them to reach any registered backend whose scheme is not auto-inferable (e.g. a private or custom driver).

Unknown scheme

PraisonAIDB fails loudly on a scheme it cannot map, pointing at the override:

ValueError: Unable to infer DB backend from URL 'foo://bar';
supported schemes: postgres://, mysql://, sqlite://, redis://, libsql://, http(s)://;
or pass an explicit state_backend= to select a registered state backend

Backend Aliases

Configure with either name — the registry resolves aliases before instantiating the factory (PraisonAI PR #2669).

AliasResolves toStore
neon, xata, cockroachdb, crdb, cockroachpostgresConversation
asyncpg, postgres_asyncasync_postgresConversation
aiomysql, mysql_asyncasync_mysqlConversation
sqlite_syncsync_sqliteConversation
aiosqlite, sqlite_asyncasync_sqliteConversation
libsqltursoConversation
motor, mongodb_asyncasync_mongodbState
mongodb_atlas, mongo_vectormongodb_vectorKnowledge
chromadbchromaKnowledge
cosmos, azure_cosmos, cosmosdb_vectorcosmosdbKnowledge
llama_index, llamaindex_adapterllamaindexKnowledge
langchain_adapterlangchainKnowledge

PersistenceConfig(state_store="motor").validate() now succeeds and resolves to AsyncMongoDBStateStore. Unknown names still fail loudly, listing the current registry backends.


Configuration Options

ParameterDescription
database_urlConversation store URL
state_urlState / run history store
knowledge_urlVector or knowledge store
database_backendExplicit conversation backend name (keyword-only; wins over URL scheme detection)
state_backendExplicit state backend name (keyword-only; wins over URL scheme detection)
knowledge_backendExplicit knowledge/vector backend name (keyword-only; wins over URL scheme detection)

See Selecting a backend for the scheme tables and override examples.

python
import os
from praisonaiagents import Agent, MemoryConfig
from praisonaiagents import db

agent = Agent(
    name="Researcher",
    memory=MemoryConfig(
        db=db(
            database_url=os.getenv("PRAISON_CONVERSATION_URL"),
            state_url=os.getenv("PRAISON_STATE_URL"),
        ),
        session_id="research-42",
    ),
)
agent.start("Continue our research thread")

Best Practices

Choose the right backend

SQLite for development; PostgreSQL or MySQL for multi-user production; Redis for fast state; JSON files for minimal dependencies.

Use meaningful session IDs

Set session_id="user-123" so conversations resume reliably across restarts.

Read credentials from the environment

Never hardcode database URLs — use os.getenv("PRAISON_CONVERSATION_URL").

Separate stores by concern

Conversation history, run traces, and vectors scale differently — configure each URL independently.


Related