> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Async Conversation Store

> Implement non-blocking conversation persistence with the AsyncConversationStore protocol

Async conversation stores provide non-blocking persistence for conversation sessions and messages, enabling high-performance multi-agent systems.

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

agent = Agent(
    name="Assistant",
    instructions="Help users with their tasks.",
)
agent.start("Continue our conversation from yesterday.")
```

The user resumes a long chat; the async store loads session history without blocking other agents on the same event loop.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Async Conversation Flow"
        A[🤖 Agent] --> B[🔄 Orchestrator]
        B --> C{📊 instanceof?}
        C -->|AsyncConversationStore| D[⚡ await store.get_session]
        C -->|ConversationStore| E[🔄 asyncio.to_thread]
        D --> F[💾 Database]
        E --> F
    end
    
    classDef agent fill:#8B0000,color:#fff
    classDef tool fill:#189AB4,color:#fff
    
    class A agent
    class B,C,D,E,F tool
```

## Quick Start

<Steps>
  <Step title="Use Built-in Async Store">
    Use a built-in async conversation store with automatic resource management:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent
    from praisonai.persistence.conversation import AsyncPostgresConversationStore

    async def main():
        async with AsyncPostgresConversationStore(
            url="postgresql://user:pass@localhost/db"
        ) as store:
            agent = Agent(
                name="Assistant",
                instructions="Help users with their tasks",
                conversation_store=store
            )
            
            result = await agent.start("Hello, how are you?")
            print(result)

    # Run the async agent
    import asyncio
    asyncio.run(main())
    ```
  </Step>

  <Step title="Implement Custom Async Store">
    Create a custom async store by inheriting from `AsyncConversationStore`:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai.persistence.conversation import AsyncConversationStore, ConversationSession, ConversationMessage
    from typing import List, Optional

    class CustomAsyncStore(AsyncConversationStore):
        async def create_session(self, session: ConversationSession) -> ConversationSession:
            # Your async implementation
            return session
        
        async def get_session(self, session_id: str) -> Optional[ConversationSession]:
            # Your async implementation
            return None
        
        async def add_message(self, session_id: str, message: ConversationMessage) -> ConversationMessage:
            # Your async implementation
            return message
        
        # ... implement other required methods
        
        async def close(self) -> None:
            # Clean up async resources
            pass

    # Use your custom store
    store = CustomAsyncStore()
    agent = Agent(name="Assistant", conversation_store=store)
    ```
  </Step>
</Steps>

***

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant Agent
    participant Orchestrator
    participant AsyncStore as AsyncConversationStore
    participant Database
    
    Agent->>Orchestrator: start("Hello")
    Orchestrator->>Orchestrator: isinstance(store, AsyncConversationStore)?
    Orchestrator->>AsyncStore: await store.get_session(session_id)
    AsyncStore->>Database: SELECT * FROM sessions
    Database-->>AsyncStore: session data
    AsyncStore-->>Orchestrator: ConversationSession
    Orchestrator-->>Agent: Response
```

| Component                  | Role                                                     |
| -------------------------- | -------------------------------------------------------- |
| **Agent**                  | Initiates conversation requests                          |
| **Orchestrator**           | Routes requests based on store type using `isinstance()` |
| **AsyncConversationStore** | Handles async persistence operations                     |
| **Database**               | Stores session and message data                          |

***

## Configuration Options

<Card title="AsyncConversationStore API Reference" icon="code" href="/docs/sdk/praisonai/persistence">
  Complete method signatures and configuration options
</Card>

***

## Common Patterns

### Context Manager Usage

Always use `async with` for automatic resource management:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
async with AsyncPostgresConversationStore(url="postgresql://...") as store:
    session = await store.get_session("session_123")
    if session:
        message = ConversationMessage(
            session_id="session_123",
            role="user",
            content="Hello"
        )
        await store.add_message("session_123", message)
```

### Upsert Session Helper

Use the built-in `upsert_session()` method for create-or-update operations:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
session = ConversationSession(session_id="new_session", user_id="user_123")
updated_session = await store.upsert_session(session)  # Creates or updates
```

### Custom Async Store Implementation

When implementing a custom async store, inherit from `AsyncConversationStore`:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai.persistence.conversation import AsyncConversationStore

class MyAsyncStore(AsyncConversationStore):
    # MUST inherit AsyncConversationStore for proper orchestrator dispatch
    async def create_session(self, session: ConversationSession) -> ConversationSession:
        # Implementation here
        pass
```

***

## Best Practices

<AccordionGroup>
  <Accordion title="Always Use async with Context Manager">
    The async context manager ensures proper resource cleanup:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # ✅ Good - automatic cleanup
    async with store:
        await store.get_session("id")

    # ❌ Bad - manual cleanup required  
    try:
        await store.get_session("id")
    finally:
        await store.close()
    ```
  </Accordion>

  <Accordion title="Inherit AsyncConversationStore for Custom Stores">
    The orchestrator uses `isinstance()` checks to dispatch correctly:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # ✅ Good - proper inheritance
    class MyStore(AsyncConversationStore):
        pass

    # ❌ Bad - will be wrapped in asyncio.to_thread()
    class MyStore(ConversationStore):
        async def get_session(self):  # This won't work as expected
            pass
    ```
  </Accordion>

  <Accordion title="Don't Mix Sync and Async APIs">
    Use either sync or async consistently:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # ✅ Good - pure async
    async with AsyncPostgresConversationStore() as store:
        session = await store.get_session("id")

    # ❌ Bad - mixing patterns
    store = AsyncPostgresConversationStore()
    session = store.get_session("id")  # This is not the async method
    ```
  </Accordion>
</AccordionGroup>

***

<Warning>
  **Breaking Change in PR #1829**: The `async_*` prefixed methods have been removed from async stores:

  ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
  # Before (removed)
  session = await store.async_get_session(session_id)

  # After (current)
  session = await store.get_session(session_id)
  ```

  Update your code to use the non-prefixed async methods.
</Warning>

***

## Related

<CardGroup cols={2}>
  <Card title="Async DB Hooks" icon="webhook" href="/docs/features/async-db-hooks">
    Event-driven persistence hooks for async stores
  </Card>

  <Card title="Persistence Overview" icon="database" href="/docs/persistence/overview">
    Architecture and backend options
  </Card>
</CardGroup>
