Google ADK#

SQLSpec provides session, event, memory, and artifact service contracts. These contracts support the Google Agent Development Kit.

Session Service#

class sqlspec.extensions.adk.SQLSpecSessionService[source]#

Bases: BaseSessionService

SQLSpec-backed implementation of BaseSessionService.

Provides session and event storage using SQLSpec database adapters. Delegates all database operations to a store implementation.

Parameters:

store (BaseAsyncADKStore | BaseSyncADKStore) -- Database store implementation.

__init__(store)[source]#

Initialize the session service.

Parameters:

store (BaseAsyncADKStore | BaseSyncADKStore) -- Database store implementation.

property store: BaseAsyncADKStore | BaseSyncADKStore#

Return the database store.

async create_session(*, app_name, user_id, state=None, session_id=None)[source]#

Create a new session.

Parameters:
  • app_name (str) -- Name of the application.

  • user_id (str) -- ID of the user.

  • state (dict[str, typing.Any] | None) -- Initial state of the session.

  • session_id (str | None) -- Client-provided session ID. If None, generates a UUID.

Return type:

Session

Returns:

The newly created session.

async get_session(*, app_name, user_id, session_id, config=None)[source]#

Get a session by ID.

Parameters:
  • app_name (str) -- Name of the application.

  • user_id (str) -- ID of the user.

  • session_id (str) -- Session identifier.

  • config (GetSessionConfig | None) -- Configuration for retrieving events.

Return type:

Session | None

Returns:

Session object if found, None otherwise.

async get_user_state(*, app_name, user_id)[source]#

Get user-scoped state for an app and user.

ADK's service API returns unprefixed user state keys, while SQLSpec stores the durable state using ADK's documented user: prefix.

Parameters:
  • app_name (str) -- Name of the application.

  • user_id (str) -- ID of the user.

Return type:

dict[str, typing.Any]

Returns:

User-scoped state with user: prefixes removed.

async list_sessions(*, app_name, user_id=None)[source]#

List all sessions for an app, optionally filtered by user.

Parameters:
  • app_name (str) -- Name of the application.

  • user_id (str | None) -- ID of the user. If None, all sessions for the app are listed.

Return type:

ListSessionsResponse

Returns:

Response containing list of sessions (without events).

async delete_session(*, app_name, user_id, session_id)[source]#

Delete a session and all its events.

Parameters:
  • app_name (str) -- Name of the application.

  • user_id (str) -- ID of the user.

  • session_id (str) -- Session identifier.

Return type:

None

async append_event(session, event)[source]#

Append an event to a session.

Persists the event record and the post-append durable state atomically via store.append_event_and_update_state(), then updates the in-memory session only after persistence succeeds.

Implements stale-session detection: if the session has been modified in storage since it was last loaded, a ValueError is raised instead of silently overwriting.

temp: keys are stripped from the persisted state snapshot so they never survive a reload.

Parameters:
  • session (Session) -- Session to append to.

  • event (Event) -- Event to append.

Return type:

Event

Returns:

The appended event.

Raises:

ValueError -- If the session has been modified in storage since it was loaded (stale session).

Memory Services#

class sqlspec.extensions.adk.SQLSpecMemoryService[source]#

Bases: BaseMemoryService

SQLSpec-backed implementation of BaseMemoryService.

Provides memory entry storage using SQLSpec database adapters. Delegates all database operations to a store implementation.

ADK BaseMemoryService defines two core methods:
  • add_session_to_memory(session) - Ingests session into memory (returns void)

  • search_memory(app_name, user_id, query) - Searches stored memories

Parameters:

store (BaseAsyncADKMemoryStore | BaseSyncADKMemoryStore) -- Database store implementation.

__init__(store)[source]#

Initialize the memory service.

Parameters:

store (BaseAsyncADKMemoryStore | BaseSyncADKMemoryStore) -- Database store implementation.

property store: BaseAsyncADKMemoryStore | BaseSyncADKMemoryStore#

Return the database store.

async add_session_to_memory(session)[source]#

Add a completed session to the memory store.

Extracts all events with content from the session and stores them as searchable memory entries. Uses UPSERT to skip duplicates.

The Session object contains app_name and user_id properties. Events are converted to memory records and bulk inserted via store. Returns void per ADK BaseMemoryService contract.

Parameters:

session (Session) -- Completed ADK Session with events.

Return type:

None

async add_events_to_memory(*, app_name, user_id, events, session_id=None, custom_metadata=None)[source]#

Add an explicit list of events to the memory service.

Same Event-to-MemoryRecord extraction logic as add_session_to_memory, but operates on a sequence of Events directly (no Session wrapper needed).

Parameters:
  • app_name (str) -- The application name for memory scope.

  • user_id (str) -- The user ID for memory scope.

  • events (Sequence[Event]) -- The events to add to memory.

  • session_id (str | None) -- Optional session ID for memory scope/partitioning. If None, memory entries are user-scoped only.

  • custom_metadata (Mapping[str, object] | None) -- Optional portable metadata stored in MemoryRecord.metadata_json.

Return type:

None

async add_memory(*, app_name, user_id, memories, custom_metadata=None)[source]#

Add explicit memory items directly to the memory service.

Each entry's content is serialized to content_json, text is extracted from content.parts for content_text, and custom_metadata merges the entry-level entry.custom_metadata with the call-level custom_metadata parameter.

Parameters:
  • app_name (str) -- The application name for memory scope.

  • user_id (str) -- The user ID for memory scope.

  • memories (Sequence[MemoryEntry]) -- Explicit memory items to add.

  • custom_metadata (Mapping[str, object] | None) -- Optional portable metadata for memory writes. Merged with each entry's custom_metadata.

Return type:

None

async search_memory(*, app_name, user_id, query)[source]#

Search memory entries by text query.

Uses the store's configured search strategy (simple ILIKE or FTS).

Parameters:
  • app_name (str) -- Name of the application.

  • user_id (str) -- ID of the user.

  • query (str) -- Text query to search for.

Returns:

List[MemoryEntry].

Return type:

SearchMemoryResponse

class sqlspec.extensions.adk.SQLSpecSyncMemoryService[source]#

Bases: object

Synchronous SQLSpec-backed memory service.

Provides memory entry storage using SQLSpec sync database adapters. This is a sync-compatible version for use with sync drivers like SQLite.

Note: This does NOT inherit from BaseMemoryService since ADK's base class requires async methods. Use this for sync-only deployments.

Parameters:

store (BaseSyncADKMemoryStore) -- Sync database store implementation.

__init__(store)[source]#

Initialize the sync memory service.

Parameters:

store (BaseSyncADKMemoryStore) -- Sync database store implementation.

property store: BaseSyncADKMemoryStore#

Return the database store.

add_session_to_memory(session)[source]#

Add a completed session to the memory store.

Extracts all events with content from the session and stores them as searchable memory entries. Uses UPSERT to skip duplicates.

Parameters:

session (Session) -- Completed ADK Session with events.

Return type:

None

search_memory(*, app_name, user_id, query)[source]#

Search memory entries by text query.

Parameters:
  • app_name (str) -- Name of the application.

  • user_id (str) -- ID of the user.

  • query (str) -- Text query to search for.

Return type:

list[MemoryEntry]

Returns:

List of MemoryEntry objects.

Artifact Service#

class sqlspec.extensions.adk.SQLSpecArtifactService[source]#

Bases: BaseArtifactService

SQLSpec-backed implementation of BaseArtifactService.

Composes SQL metadata storage with sqlspec/storage/ content backends to provide versioned artifact management for Google ADK.

Metadata (version number, filename, MIME type, custom metadata, canonical URI) is stored in a SQL table managed by the artifact store. Content bytes are stored in object storage (S3, GCS, Azure, local filesystem) via the storage registry.

Parameters:
  • store (BaseAsyncADKArtifactStore) -- Artifact metadata store implementation.

  • artifact_storage_uri (str) -- Base URI for content storage. Can also be a registered alias in the storage registry.

  • registry (StorageRegistry | None) -- Storage registry to use. Defaults to the global singleton.

__init__(store, artifact_storage_uri, registry=None)[source]#
property store: BaseAsyncADKArtifactStore#

Return the artifact metadata store.

property artifact_storage_uri: str#

Return the base URI for content storage.

async save_artifact(*, app_name, user_id, filename, artifact, session_id=None, custom_metadata=None)[source]#

Save an artifact, returning the new version number.

Writes content to object storage first, then inserts the metadata row. If content write succeeds but metadata insert fails, the orphaned content blob is logged but not automatically cleaned up (eventual consistency is acceptable; orphan sweep can be added later).

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • filename (str) -- Artifact filename.

  • artifact (Part | dict[str, typing.Any]) -- ADK Part or dict to save.

  • session_id (str | None) -- Session identifier (None for user-scoped).

  • custom_metadata (dict[str, typing.Any] | None) -- Optional per-version metadata dict.

Return type:

int

Returns:

The version number (0-based, incrementing).

async load_artifact(*, app_name, user_id, filename, session_id=None, version=None)[source]#

Load an artifact by reading metadata then fetching content.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • filename (str) -- Artifact filename.

  • session_id (str | None) -- Session identifier (None for user-scoped).

  • version (int | None) -- Specific version, or None for latest.

Return type:

Part | None

Returns:

Deserialized Part, or None if not found.

async list_artifact_keys(*, app_name, user_id, session_id=None)[source]#

List distinct artifact filenames.

When session_id is provided, returns both session-scoped and user-scoped filenames. When None, returns only user-scoped filenames.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • session_id (str | None) -- Session identifier.

Return type:

list[str]

Returns:

List of artifact filenames.

async delete_artifact(*, app_name, user_id, filename, session_id=None)[source]#

Delete an artifact and all its versions.

Deletes metadata rows first (fail-fast), then removes content objects from storage (best-effort).

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • filename (str) -- Artifact filename.

  • session_id (str | None) -- Session identifier (None for user-scoped).

Return type:

None

async list_versions(*, app_name, user_id, filename, session_id=None)[source]#

List all version numbers for an artifact.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • filename (str) -- Artifact filename.

  • session_id (str | None) -- Session identifier (None for user-scoped).

Return type:

list[int]

Returns:

Sorted list of version numbers.

async list_artifact_versions(*, app_name, user_id, filename, session_id=None)[source]#

List all versions with full metadata for an artifact.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • filename (str) -- Artifact filename.

  • session_id (str | None) -- Session identifier (None for user-scoped).

Return type:

list[ArtifactVersion]

Returns:

List of ArtifactVersion objects ordered by version ascending.

async get_artifact_version(*, app_name, user_id, filename, session_id=None, version=None)[source]#

Get metadata for a specific artifact version.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • filename (str) -- Artifact filename.

  • session_id (str | None) -- Session identifier (None for user-scoped).

  • version (int | None) -- Version number, or None for latest.

Return type:

ArtifactVersion | None

Returns:

ArtifactVersion if found, None otherwise.

Store Base Classes#

class sqlspec.extensions.adk.BaseAsyncADKStore[source]#

Bases: _ADKStoreCommon[ConfigT], ABC

Base class for async SQLSpec-backed ADK session stores.

Implements storage operations for Google ADK sessions and events using SQLSpec database adapters with async/await.

This abstract base class provides common functionality for all database-specific store implementations including: - Connection management via SQLSpec configs - Table name validation - Session and event CRUD operations

Subclasses must implement dialect-specific SQL queries and will be created in each adapter directory (e.g., sqlspec/adapters/asyncpg/adk/store.py).

Parameters:

config (TypeVar(ConfigT, bound= DatabaseConfigProtocol[Any, Any, Any])) -- SQLSpec database configuration with extension_config["adk"] settings.

Notes

Configuration is read from config.extension_config["adk"]: - session_table: Sessions table name (default: "adk_session") - events_table: Events table name (default: "adk_event") - app_state_table: App-scoped state table name (default: "adk_app_state") - user_state_table: User-scoped state table name (default: "adk_user_state") - metadata_table: Internal metadata table name (default: "adk_internal_metadata") - owner_id_column: Optional owner FK column DDL (default: None)

async create_tables()[source]#

Create the sessions and events tables if they don't exist.

Return type:

None

async prepare_schema_async(driver)[source]#

Prepare adapter-specific schema decisions with an asynchronous driver.

Return type:

None

async create_session(session_id, app_name, user_id, state, owner_id=None)[source]#

Create a new session.

Parameters:
  • session_id (str) -- Unique identifier for the session.

  • app_name (str) -- Name of the application.

  • user_id (str) -- ID of the user.

  • state (dict[str, typing.Any]) -- Session state dictionary.

  • owner_id (Optional[typing.Any]) -- Optional owner ID value for owner_id_column (if configured).

Return type:

SessionRecord

Returns:

The created session record.

abstractmethod async get_session(app_name, user_id, session_id, *, renew_for=None)[source]#

Get a session.

Parameters:
  • app_name (str) -- Name of the application.

  • user_id (str) -- ID of the user.

  • session_id (str) -- Session identifier.

  • renew_for (int | timedelta | None) -- If positive, touch the session update timestamp while reading.

Return type:

SessionRecord | None

Returns:

Session record if found, None otherwise.

abstractmethod async update_session_state(app_name, user_id, session_id, state)[source]#

Update session state.

Parameters:
  • app_name (str) -- Name of the application.

  • user_id (str) -- ID of the user.

  • session_id (str) -- Session identifier.

  • state (dict[str, typing.Any]) -- New state dictionary.

Return type:

None

abstractmethod async list_sessions(app_name, user_id=None)[source]#

List all sessions for an app, optionally filtered by user.

Parameters:
  • app_name (str) -- Name of the application.

  • user_id (str | None) -- ID of the user. If None, returns all sessions for the app.

Return type:

list[SessionRecord]

Returns:

List of session records.

abstractmethod async delete_session(app_name, user_id, session_id)[source]#

Delete a session and its events.

Parameters:
  • app_name (str) -- Name of the application.

  • user_id (str) -- ID of the user.

  • session_id (str) -- Session identifier.

Return type:

None

abstractmethod async append_event(event_record)[source]#

Append an event to a session.

Parameters:

event_record (EventRecord) -- Event record to store.

Return type:

None

abstractmethod async append_event_and_update_state(event_record, app_name, user_id, session_id, state, *, app_state=None, user_state=None)[source]#

Atomically append an event and update the session's durable state.

This is the authoritative durable write boundary for post-creation session mutations. The event insert, session state update, and the optional scoped-state upserts must succeed together or fail together, and the updated session record is returned in the same round-trip so callers don't need a follow-up read.

When app_state is provided (non-None), it is a full merged app-scoped snapshot to replace/upsert for app_name. When user_state is provided, it is a full merged user-scoped snapshot to replace/upsert for (app_name, user_id). None means that scope was untouched by the event and must not be written.

Parameters:
  • event_record (EventRecord) -- Event record to store.

  • app_name (str) -- Application name for routing scoped-state upserts.

  • user_id (str) -- User identifier for routing user-scoped upserts.

  • session_id (str) -- Session identifier whose state should be updated.

  • state (dict[str, typing.Any]) -- Post-append durable session-scoped state snapshot (temp: keys already stripped by the service layer).

  • app_state (dict[str, typing.Any] | None) -- Full app-scoped state snapshot (app:* keys) to upsert atomically, or None when untouched.

  • user_state (dict[str, typing.Any] | None) -- Full user-scoped state snapshot (user:* keys) to upsert atomically, or None when untouched.

Return type:

SessionRecord

Returns:

The updated SessionRecord reflecting the new state and update_time.

Raises:

ValueError -- If the session row no longer exists at update time (raced with delete_session).

abstractmethod async get_events(app_name, user_id, session_id, after_timestamp=None, limit=None)[source]#

Get events for a session.

Parameters:
  • app_name (str) -- Name of the application.

  • user_id (str) -- ID of the user.

  • session_id (str) -- Session identifier.

  • after_timestamp (datetime | None) -- Only return events after this time.

  • limit (int | None) -- Maximum number of events to return.

Return type:

list[EventRecord]

Returns:

List of event records ordered by timestamp ascending.

abstractmethod async delete_expired_events(before)[source]#

Delete events older than the given timestamp.

Parameters:

before (datetime) -- Timestamp threshold; events with timestamp earlier than this value are deleted.

Return type:

int

Returns:

Number of event rows deleted.

abstractmethod async delete_idle_sessions(updated_before)[source]#

Delete sessions whose update_time predates the given threshold.

Parameters:

updated_before (datetime) -- Timestamp threshold; sessions updated earlier than this value are deleted.

Return type:

int

Returns:

Number of session rows deleted.

abstractmethod async get_app_state(app_name)[source]#

Return app-scoped state for an application.

Parameters:

app_name (str) -- Application name.

Return type:

dict[str, typing.Any] | None

Returns:

App-scoped state mapping if present, otherwise None.

abstractmethod async get_user_state(app_name, user_id)[source]#

Return user-scoped state for an application user.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

Return type:

dict[str, typing.Any] | None

Returns:

User-scoped state mapping if present, otherwise None.

abstractmethod async upsert_app_state(app_name, state)[source]#

Insert or replace app-scoped state for an application.

Parameters:
  • app_name (str) -- Application name.

  • state (dict[str, typing.Any]) -- App-scoped state mapping.

Return type:

None

abstractmethod async upsert_user_state(app_name, user_id, state)[source]#

Insert or replace user-scoped state for an application user.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • state (dict[str, typing.Any]) -- User-scoped state mapping.

Return type:

None

abstractmethod async get_metadata(key)[source]#

Return a value from the ADK internal metadata table.

Parameters:

key (str) -- Metadata key.

Return type:

str | None

Returns:

Metadata value if present, otherwise None.

abstractmethod async set_metadata(key, value)[source]#

Set a value in the ADK internal metadata table.

Parameters:
  • key (str) -- Metadata key.

  • value (str) -- Metadata value.

Return type:

None

async reconcile_schema(*, assume_existing=False)[source]#

Apply additive ADK table changes from canonical adapter DDL.

Parameters:

assume_existing (bool) -- Skip table discovery after adapter-level creation.

Return type:

None

async ensure_tables()[source]#

Create tables and emit a standardized log entry.

Return type:

None

async drop_tables()[source]#

Drop all ADK tables managed by this store in FK-safe order.

Return type:

None

async recreate_tables()[source]#

Drop and recreate all ADK tables managed by this store.

Return type:

None

class sqlspec.extensions.adk.BaseSyncADKStore[source]#

Bases: _ADKStoreCommon[ConfigT], ABC

Base class for sync SQLSpec-backed ADK session stores.

Sync-backed adapters expose a real synchronous API for direct use in synchronous applications. Async bridging belongs in SQLSpecSessionService when Google ADK calls into a sync store from its async service surface.

Parameters:

config (TypeVar(ConfigT, bound= DatabaseConfigProtocol[Any, Any, Any])) -- SQLSpec database configuration with extension_config["adk"] settings.

abstractmethod create_tables()[source]#

Create the sessions and events tables if they don't exist.

Return type:

None

prepare_schema_sync(driver)[source]#

Prepare adapter-specific schema decisions with a synchronous driver.

Return type:

None

abstractmethod create_session(session_id, app_name, user_id, state, owner_id=None)[source]#

Create a new session.

Return type:

SessionRecord

abstractmethod get_session(app_name, user_id, session_id, *, renew_for=None)[source]#

Get a session.

Return type:

SessionRecord | None

abstractmethod update_session_state(app_name, user_id, session_id, state)[source]#

Update session state.

Return type:

None

abstractmethod list_sessions(app_name, user_id=None)[source]#

List all sessions for an app, optionally filtered by user.

Return type:

list[SessionRecord]

abstractmethod delete_session(app_name, user_id, session_id)[source]#

Delete a session and its events.

Return type:

None

abstractmethod append_event(event_record)[source]#

Append an event to a session.

Return type:

None

abstractmethod append_event_and_update_state(event_record, app_name, user_id, session_id, state, *, app_state=None, user_state=None)[source]#

Atomically append an event and update the session's durable state.

Return type:

SessionRecord

abstractmethod get_events(app_name, user_id, session_id, after_timestamp=None, limit=None)[source]#

Get events for a session.

Return type:

list[EventRecord]

abstractmethod delete_expired_events(before)[source]#

Delete events older than the given timestamp.

Return type:

int

abstractmethod delete_idle_sessions(updated_before)[source]#

Delete sessions whose update_time predates the given threshold.

Return type:

int

abstractmethod get_app_state(app_name)[source]#

Return app-scoped state for an application.

Return type:

dict[str, typing.Any] | None

abstractmethod get_user_state(app_name, user_id)[source]#

Return user-scoped state for an application user.

Return type:

dict[str, typing.Any] | None

abstractmethod upsert_app_state(app_name, state)[source]#

Insert or replace app-scoped state for an application.

Return type:

None

abstractmethod upsert_user_state(app_name, user_id, state)[source]#

Insert or replace user-scoped state for an application user.

Return type:

None

abstractmethod get_metadata(key)[source]#

Return a value from the ADK internal metadata table.

Return type:

str | None

abstractmethod set_metadata(key, value)[source]#

Set a value in the ADK internal metadata table.

Return type:

None

reconcile_schema(*, assume_existing=False)[source]#

Apply additive ADK table changes from canonical adapter DDL.

Parameters:

assume_existing (bool) -- Skip table discovery after adapter-level creation.

Return type:

None

ensure_tables()[source]#

Create tables and emit a standardized log entry.

Return type:

None

drop_tables()[source]#

Drop all ADK tables managed by this store in FK-safe order.

Return type:

None

recreate_tables()[source]#

Drop and recreate all ADK tables managed by this store.

Return type:

None

Memory Store Base Classes#

class sqlspec.extensions.adk.BaseAsyncADKMemoryStore[source]#

Bases: _ADKMemoryStoreCommon[ConfigT], ABC

Base class for async SQLSpec-backed ADK memory stores.

Implements storage operations for Google ADK memory entries using SQLSpec database adapters with async/await.

This abstract base class provides common functionality for all database-specific memory store implementations including: - Connection management via SQLSpec configs - Table name validation - Memory entry CRUD operations - Text search with optional full-text search support

Subclasses must implement dialect-specific SQL queries and will be created in each adapter directory.

Parameters:

config (TypeVar(ConfigT, bound= DatabaseConfigProtocol[Any, Any, Any])) -- SQLSpec database configuration with extension_config["adk"] settings.

abstractmethod async create_tables()[source]#

Create the memory table and indexes if they don't exist.

Should check self._enabled and skip table creation if False.

Return type:

None

async prepare_schema_async(driver)[source]#

Prepare adapter-specific schema decisions with an asynchronous driver.

Return type:

None

async ensure_tables()[source]#

Create tables when enabled and emit a standardized log entry.

Return type:

None

async reconcile_schema(*, assume_existing=False)[source]#

Apply additive memory-table changes from canonical adapter DDL.

Parameters:

assume_existing (bool) -- Skip table discovery after adapter-level creation.

Return type:

None

abstractmethod async insert_memory_entries(entries, owner_id=None)[source]#

Bulk insert memory entries with deduplication.

Uses UPSERT pattern to skip duplicates based on event_id.

Parameters:
  • entries (list[MemoryRecord]) -- List of memory records to insert.

  • owner_id (object | None) -- Optional owner ID value for owner_id_column (if configured).

Return type:

int

Returns:

Number of entries actually inserted (excludes duplicates).

Raises:

RuntimeError -- If memory store is disabled.

abstractmethod async search_entries(query, app_name, user_id, limit=None)[source]#

Search memory entries by text query.

Uses the configured search strategy (simple ILIKE or FTS).

Parameters:
  • query (str) -- Text query to search for.

  • app_name (str) -- Application name to filter by.

  • user_id (str) -- User ID to filter by.

  • limit (int | None) -- Maximum number of results (defaults to max_results config).

Return type:

list[MemoryRecord]

Returns:

List of matching memory records ordered by relevance/timestamp.

Raises:

RuntimeError -- If memory store is disabled.

abstractmethod async delete_entries_by_session(session_id)[source]#

Delete all memory entries for a specific session.

Parameters:

session_id (str) -- Session ID to delete entries for.

Return type:

int

Returns:

Number of entries deleted.

abstractmethod async delete_entries_older_than(days)[source]#

Delete memory entries older than specified days.

Used for TTL cleanup operations.

Parameters:

days (int) -- Number of days to retain entries.

Return type:

int

Returns:

Number of entries deleted.

class sqlspec.extensions.adk.BaseSyncADKMemoryStore[source]#

Bases: _ADKMemoryStoreCommon[ConfigT], ABC

Base class for sync SQLSpec-backed ADK memory stores.

Implements storage operations for Google ADK memory entries using SQLSpec database adapters with synchronous execution.

This abstract base class provides common functionality for sync database-specific memory store implementations including: - Connection management via SQLSpec configs - Table name validation - Memory entry CRUD operations - Text search with optional full-text search support

Subclasses must implement dialect-specific SQL queries and will be created in each adapter directory.

Parameters:

config (TypeVar(ConfigT, bound= DatabaseConfigProtocol[Any, Any, Any])) -- SQLSpec database configuration with extension_config["adk"] settings.

abstractmethod create_tables()[source]#

Create the memory table and indexes if they don't exist.

Should check self._enabled and skip table creation if False.

Return type:

None

prepare_schema_sync(driver)[source]#

Prepare adapter-specific schema decisions with a synchronous driver.

Return type:

None

ensure_tables()[source]#

Create tables when enabled and emit a standardized log entry.

Return type:

None

reconcile_schema(*, assume_existing=False)[source]#

Apply additive memory-table changes from canonical adapter DDL.

Parameters:

assume_existing (bool) -- Skip table discovery after adapter-level creation.

Return type:

None

abstractmethod insert_memory_entries(entries, owner_id=None)[source]#

Bulk insert memory entries with deduplication.

Uses UPSERT pattern to skip duplicates based on event_id.

Parameters:
  • entries (list[MemoryRecord]) -- List of memory records to insert.

  • owner_id (object | None) -- Optional owner ID value for owner_id_column (if configured).

Return type:

int

Returns:

Number of entries actually inserted (excludes duplicates).

Raises:

RuntimeError -- If memory store is disabled.

abstractmethod search_entries(query, app_name, user_id, limit=None)[source]#

Search memory entries by text query.

Uses the configured search strategy (simple ILIKE or FTS).

Parameters:
  • query (str) -- Text query to search for.

  • app_name (str) -- Application name to filter by.

  • user_id (str) -- User ID to filter by.

  • limit (int | None) -- Maximum number of results (defaults to max_results config).

Return type:

list[MemoryRecord]

Returns:

List of matching memory records ordered by relevance/timestamp.

Raises:

RuntimeError -- If memory store is disabled.

abstractmethod delete_entries_by_session(session_id)[source]#

Delete all memory entries for a specific session.

Parameters:

session_id (str) -- Session ID to delete entries for.

Return type:

int

Returns:

Number of entries deleted.

abstractmethod delete_entries_older_than(days)[source]#

Delete memory entries older than specified days.

Used for TTL cleanup operations.

Parameters:

days (int) -- Number of days to retain entries.

Return type:

int

Returns:

Number of entries deleted.

Artifact Store Base Classes#

class sqlspec.extensions.adk.BaseAsyncADKArtifactStore[source]#

Bases: _ADKArtifactStoreCommon[ConfigT], ABC

Base class for async SQLSpec-backed ADK artifact metadata stores.

Manages artifact version metadata in a SQL table. Content bytes are stored externally via sqlspec/storage/ backends and referenced by canonical URI in each metadata row.

Subclasses must implement dialect-specific SQL queries.

Parameters:

config (TypeVar(ConfigT, bound= DatabaseConfigProtocol[Any, Any, Any])) -- SQLSpec database configuration with extension_config["adk"] settings.

abstractmethod async insert_artifact(record)[source]#

Insert an artifact version metadata row.

Parameters:

record (ArtifactRecord) -- Artifact metadata record to insert.

Return type:

None

abstractmethod async get_artifact(app_name, user_id, filename, session_id=None, version=None)[source]#

Get a specific artifact version's metadata.

When version is None, returns the latest version.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • filename (str) -- Artifact filename.

  • session_id (str | None) -- Session identifier (None for user-scoped).

  • version (int | None) -- Specific version number, or None for latest.

Return type:

ArtifactRecord | None

Returns:

Artifact record if found, None otherwise.

abstractmethod async list_artifact_keys(app_name, user_id, session_id=None)[source]#

List distinct artifact filenames.

When session_id is provided, returns filenames from both session-scoped and user-scoped artifacts. When None, returns only user-scoped artifact filenames.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • session_id (str | None) -- Session identifier (None for user-scoped only).

Return type:

list[str]

Returns:

List of distinct artifact filenames.

abstractmethod async list_artifact_versions(app_name, user_id, filename, session_id=None)[source]#

List all version records for an artifact, ordered by version ascending.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • filename (str) -- Artifact filename.

  • session_id (str | None) -- Session identifier (None for user-scoped).

Return type:

list[ArtifactRecord]

Returns:

List of artifact records ordered by version ascending.

abstractmethod async delete_artifact(app_name, user_id, filename, session_id=None)[source]#

Delete all version records for an artifact and return them.

The caller uses the returned records to clean up content from object storage. Metadata is deleted first (fail-fast); content cleanup is best-effort.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • filename (str) -- Artifact filename.

  • session_id (str | None) -- Session identifier (None for user-scoped).

Return type:

list[ArtifactRecord]

Returns:

List of deleted artifact records (needed for content cleanup).

abstractmethod async get_next_version(app_name, user_id, filename, session_id=None)[source]#

Get the next version number for an artifact.

Returns 0 if no versions exist (first version), otherwise max(version) + 1.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • filename (str) -- Artifact filename.

  • session_id (str | None) -- Session identifier (None for user-scoped).

Return type:

int

Returns:

Next version number (0-based).

abstractmethod async create_table()[source]#

Create the artifact versions table if it does not exist.

Return type:

None

async ensure_table()[source]#

Create the artifact table and emit a standardized log entry.

Return type:

None

class sqlspec.extensions.adk.BaseSyncADKArtifactStore[source]#

Bases: _ADKArtifactStoreCommon[ConfigT], ABC

Base class for sync SQLSpec-backed ADK artifact metadata stores.

Synchronous counterpart of BaseAsyncADKArtifactStore.

Parameters:

config (TypeVar(ConfigT, bound= DatabaseConfigProtocol[Any, Any, Any])) -- SQLSpec database configuration with extension_config["adk"] settings.

abstractmethod insert_artifact(record)[source]#

Insert an artifact version metadata row.

Parameters:

record (ArtifactRecord) -- Artifact metadata record to insert.

Return type:

None

abstractmethod get_artifact(app_name, user_id, filename, session_id=None, version=None)[source]#

Get a specific artifact version's metadata.

When version is None, returns the latest version.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • filename (str) -- Artifact filename.

  • session_id (str | None) -- Session identifier (None for user-scoped).

  • version (int | None) -- Specific version number, or None for latest.

Return type:

ArtifactRecord | None

Returns:

Artifact record if found, None otherwise.

abstractmethod list_artifact_keys(app_name, user_id, session_id=None)[source]#

List distinct artifact filenames.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • session_id (str | None) -- Session identifier (None for user-scoped only).

Return type:

list[str]

Returns:

List of distinct artifact filenames.

abstractmethod list_artifact_versions(app_name, user_id, filename, session_id=None)[source]#

List all version records for an artifact, ordered by version ascending.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • filename (str) -- Artifact filename.

  • session_id (str | None) -- Session identifier (None for user-scoped).

Return type:

list[ArtifactRecord]

Returns:

List of artifact records ordered by version ascending.

abstractmethod delete_artifact(app_name, user_id, filename, session_id=None)[source]#

Delete all version records for an artifact and return them.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • filename (str) -- Artifact filename.

  • session_id (str | None) -- Session identifier (None for user-scoped).

Return type:

list[ArtifactRecord]

Returns:

List of deleted artifact records (needed for content cleanup).

abstractmethod get_next_version(app_name, user_id, filename, session_id=None)[source]#

Get the next version number for an artifact.

Parameters:
  • app_name (str) -- Application name.

  • user_id (str) -- User identifier.

  • filename (str) -- Artifact filename.

  • session_id (str | None) -- Session identifier (None for user-scoped).

Return type:

int

Returns:

Next version number (0-based).

abstractmethod create_table()[source]#

Create the artifact versions table if it does not exist.

Return type:

None

ensure_table()[source]#

Create the artifact table and emit a standardized log entry.

Return type:

None

Record Types#

class sqlspec.extensions.adk.SessionRecord[source]#

Bases: TypedDict

Database record for a session.

Represents the schema for sessions stored in the database.

class sqlspec.extensions.adk.EventRecord[source]#

Bases: TypedDict

Database record for an event.

Stores the full ADK Event as a single JSON blob (event_data) alongside indexed scalar columns used for scoped query filtering.

This design eliminates column drift with upstream ADK: new Event fields are automatically captured in event_data without schema changes.

class sqlspec.extensions.adk.MemoryRecord[source]#

Bases: TypedDict

Database record for a memory entry.

Represents the schema for memory entries stored in the database. Contains extracted content from ADK events for searchable long-term memory.

class sqlspec.extensions.adk.ArtifactRecord[source]#

Bases: TypedDict

Database record for an artifact version.

Represents the schema for artifact metadata stored in the database. Content is stored separately in object storage; this record tracks versioning, ownership, and the canonical URI pointing to the content.

The composite key is (app_name, user_id, session_id, filename, version), where session_id may be NULL for user-scoped artifacts.

Configuration#

class sqlspec.extensions.adk.ADKConfig[source]#

Bases: TypedDict

Configuration options for ADK session and memory store extension.

All fields are optional with sensible defaults. Use in extension_config["adk"]:

Configuration supports three deployment scenarios:
  1. SQLSpec manages everything (runtime + migrations)

  2. SQLSpec runtime only (external migration tools like Alembic/Flyway)

  3. Selective features (sessions OR memory, not both)

migrations_path: NotRequired[str | Path]#

Directory containing this extension's migrations, or a '<dotted.module>:<subdir>' specification.

Overrides the default sqlspec.extensions.<name> lookup. Setting this auto-includes the extension in migration_config["include_extensions"].

manage_schema: NotRequired[bool]#

True.

Type:

Apply additive target-schema reconciliation. Default

create_schema: NotRequired[bool]#

True.

Type:

Create missing ADK tables during managed reconciliation. Default

run_migrations: NotRequired[bool]#

False.

Type:

Run packaged versioned migrations when an integration supplies a runner. Default

enable_sessions: NotRequired[bool]#

True.

When False: session service unavailable, session store operations disabled. Independent of migration control - can use externally-managed tables.

Type:

Enable session store at runtime. Default

enable_memory: NotRequired[bool]#

True.

When False: memory service unavailable, memory store operations disabled. Independent of migration control - can use externally-managed tables.

Type:

Enable memory store at runtime. Default

include_sessions_migration: NotRequired[bool]#

True.

When False: session migration DDL skipped (use external migration tools). Decoupled from enable_sessions - allows external table management with SQLSpec runtime.

Type:

Include session tables in SQLSpec migrations. Default

include_memory_migration: NotRequired[bool]#

True.

When False: memory migration DDL skipped (use external migration tools). Decoupled from enable_memory - allows external table management with SQLSpec runtime.

Type:

Include memory tables in SQLSpec migrations. Default

session_table: NotRequired[str]#

'adk_session'

Type:

Name of the sessions table. Default

events_table: NotRequired[str]#

'adk_event'

Type:

Name of the events table. Default

app_state_table: NotRequired[str]#

'adk_app_state'

Type:

Name of the app-scoped state table. Default

user_state_table: NotRequired[str]#

'adk_user_state'

Type:

Name of the user-scoped state table. Default

metadata_table: NotRequired[str]#

'adk_internal_metadata'

Type:

Name of the internal metadata table. Default

memory_table: NotRequired[str]#

'adk_memory'

Type:

Name of the memory entries table. Default

artifact_table: NotRequired[str]#

'adk_artifact'

Type:

Name of the artifact metadata table. Default

artifact_storage_uri: NotRequired[str]#

Base URI for artifact content storage.

Points to a sqlspec/storage/ backend where artifact binary content is stored. Can be a direct URI (s3://bucket/path, file:///path) or a registered alias in the storage registry.

memory_use_fts: NotRequired[bool]#

False.

When True, adapters will use their native FTS capabilities where available: - PostgreSQL: to_tsvector/to_tsquery with GIN index - SQLite: FTS5 virtual table - DuckDB: FTS extension with match_bm25 - Oracle: CONTAINS() with CTXSYS.CONTEXT index - Spanner: TOKENIZE_FULLTEXT with search index - MySQL: MATCH...AGAINST with FULLTEXT index

When False, adapters use simple LIKE/ILIKE queries (works without indexes).

Type:

Enable full-text search when supported. Default

memory_max_results: NotRequired[int]#

Limits the number of memory entries returned by search_memory(). Can be overridden per-query via the limit parameter.

Type:

Maximum number of results for memory search queries. Default

owner_id_column: NotRequired[str]#

Optional owner ID column definition to link sessions/memories to a user, tenant, team, or other entity.

Format: "column_name TYPE [NOT NULL] REFERENCES table(column) [options...]"

The entire definition is passed through to DDL verbatim. We only parse the column name (first word) for use in INSERT/SELECT statements.

This column is added to both session and memory tables for consistent multi-tenant isolation.

Supports:
  • Foreign key constraints: REFERENCES table(column)

  • Nullable or NOT NULL

  • CASCADE options: ON DELETE CASCADE, ON UPDATE CASCADE

  • Dialect-specific options (DEFERRABLE, ENABLE VALIDATE, etc.)

  • Plain columns without FK (just extra column storage)