Database Interface

This module defines the abstract interface and shared data models for all database backends in Agentstr. It provides a common interface that all database implementations must adhere to.

Overview

The central component is the BaseDatabase abstract base class, which outlines the required methods for any database backend, such as connecting, disconnecting, and performing CRUD operations on Nostr-related data. This ensures that different backends can be used interchangeably.

Key Components:

  • BaseDatabase: The abstract base class for all database implementations.

  • Shared Pydantic models for data consistency across backends.

Reference

Database abstraction layer with SQLite and Postgres implementations.

The module exposes a Database factory function that returns an instance of SQLiteDatabase or PostgresDatabase depending on the provided connection string. Supported schemes are:

sqlite://<path | :memory:>
postgresql://<user>:<pass>@<host>:<port>/<dbname>
postgres://<user>:<pass>@<host>:<port>/<dbname>

All implementations share the same async API.

class agentstr.database.base.BaseDatabase(conn_str: str, agent_name: str | None = None)[source]

Bases: ABC

Abstract base class for concrete database backends.

__init__(conn_str: str, agent_name: str | None = None)[source]
abstractmethod async async_init() BaseDatabase[source]

Perform any asynchronous initialisation required for the backend.

abstractmethod async close() None[source]

Close the underlying connection (if any).

abstractmethod async get_user(user_id: str) User[source]

Fetch a User by user_id. Non-existent users yield a default model with a zero balance.

abstractmethod async upsert_user(user: User) None[source]

Create or update user in storage atomically.

abstractmethod async add_message(thread_id: str, user_id: str, role: Literal['user', 'agent', 'tool'], message: str = '', content: str = '', kind: str = 'request', satoshis: int | None = None, extra_inputs: dict[str, Any] = {}, extra_outputs: dict[str, Any] = {}) Message[source]

Append a message to a thread and return the stored model.

abstractmethod async get_messages(thread_id: str, user_id: str, *, limit: int | None = None, before_idx: int | None = None, after_idx: int | None = None, reverse: bool = False) List[Message][source]

Retrieve messages for thread_id ordered by idx.

abstractmethod async get_current_thread_id(user_id: str) str | None[source]

Return the current thread id for user_id within this agent scope.

abstractmethod async set_current_thread_id(user_id: str, thread_id: str | None) None[source]

Persist thread_id as the current thread for user_id.

See Also