adk-memory 3.0.0

Semantic memory and search for Rust Agent Development Kit (ADK-Rust) agents
Documentation

adk-memory

Semantic memory and search for Rust Agent Development Kit (ADK-Rust) agents.

Crates.io Documentation License

Stability: Stable — follows semantic versioning; the redis-memory, mongodb-memory and neo4j-memory backends are Alpha. See STABILITY.md.

Overview

adk-memory provides long-term memory capabilities for the Rust Agent Development Kit (ADK-Rust):

  • InMemoryMemoryService - Simple in-memory memory storage
  • SqliteMemoryService - SQLite-backed persistence (sqlite-memory feature)
  • PostgresMemoryService - PostgreSQL + pgvector persistence (database-memory feature)
  • MongoMemoryService - MongoDB-backed persistence (mongodb-memory feature)
  • Neo4jMemoryService - Neo4j-backed persistence (neo4j-memory feature)
  • RedisMemoryService - Redis-backed persistence (redis-memory feature)
  • VertexAiMemoryBankService - Vertex AI Agent Engine Memory Bank (vertex-memory feature)
  • GraphMemoryService - Bi-temporal knowledge graph of entities, relations, and observations on SQLite (graph-memory feature)
  • MemoryService - Trait for custom storage backends
  • Search - Keyword search on the in-memory, SQLite, and Redis backends; vector similarity with an EmbeddingProvider on PostgreSQL (pgvector, with a tsvector keyword fallback), MongoDB (Atlas Vector Search, with a text-search fallback), and Neo4j
  • Project-Scoped Isolation - Isolate memories by project within a user
  • Schema Migrations - Versioned, forward-only migrations for the SQL, MongoDB, and Neo4j backends

Agents reach memory through the runner, which attaches a memory service to each invocation (ToolContext::search_memory), and through adk-tool's memory-tools feature: LoadMemoryTool, and PreloadMemoryTool, which also converts into a BeforeModelCallback that injects memories at the start of a turn.

Installation

[dependencies]
adk-memory = "3.0.0"

Or use the meta-crate:

[dependencies]
adk-rust = { version = "3.0.0", features = ["memory"] }

Quick Start

The examples use these dependencies:

[dependencies]
adk-core = "3.0.0"
adk-memory = "3.0.0"
chrono = "0.4"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
use adk_core::Content;
use adk_memory::{InMemoryMemoryService, MemoryEntry, MemoryService, SearchRequest};
use chrono::Utc;

#[tokio::main]
async fn main() -> adk_core::Result<()> {
    let service = InMemoryMemoryService::new();

    let entries = vec![MemoryEntry::new(Content::new("user").with_text("The user prefers the dark theme."), "system")];

    service.add_session("my_app", "user_123", "session_456", entries).await?;

    let response = service
        .search(SearchRequest {
            query: "dark theme".to_string(),
            user_id: "user_123".to_string(),
            app_name: "my_app".to_string(),
            limit: None,
            min_score: None,
            project_id: None, // None = global entries only
        })
        .await?;

    assert_eq!(response.memories.len(), 1);
    for memory in response.memories {
        println!("Found: {:?}", memory.content);
    }
    Ok(())
}

The in-memory and Redis backends split text into runs of Unicode letters and digits, score each entry by the share of query words it contains (min_score filters on that score), and return the highest-scoring, then newest, entries.

Project-Scoped Memory

Memories can be scoped to a project within a user. The isolation key is (app_name, user_id, project_id?):

  • Global entries (project_id = None): visible in all project contexts and in global-only searches.
  • Project entries (project_id = Some(id)): visible only when searching within that specific project.
  • Project search (project_id = Some(id)): returns global entries + entries for that project.
  • Global search (project_id = None): returns only global entries.

Writing project-scoped entries

use adk_core::Content;
use adk_memory::{InMemoryMemoryService, MemoryEntry, MemoryService};
use chrono::Utc;

#[tokio::main]
async fn main() -> adk_core::Result<()> {
    let service = InMemoryMemoryService::new();
    let entry = MemoryEntry::new(Content::new("user").with_text("Launch is planned for March"), "user");

    // Global entry (no project scope)
    service.add_session("app", "user", "sess-1", vec![entry.clone()]).await?;

    // Project-scoped entries
    service
        .add_session_to_project("app", "user", "sess-2", "my-project", vec![entry.clone()])
        .await?;

    // Single entry to a project
    service.add_entry_to_project("app", "user", "my-project", entry).await?;
    Ok(())
}

Searching with project scope

use adk_memory::{MemoryService, SearchRequest, SearchResponse};

async fn search(service: &dyn MemoryService) -> adk_core::Result<(SearchResponse, SearchResponse)> {
    // Global-only search — returns only global entries
    let global = service
        .search(SearchRequest {
            query: "topic".into(),
            user_id: "user".into(),
            app_name: "app".into(),
            limit: None,
            min_score: None,
            project_id: None,
        })
        .await?;

    // Project search — returns global + project entries
    let project = service
        .search(SearchRequest {
            query: "topic".into(),
            user_id: "user".into(),
            app_name: "app".into(),
            limit: None,
            min_score: None,
            project_id: Some("my-project".into()),
        })
        .await?;
    Ok((global, project))
}

Project-scoped deletion

use adk_memory::MemoryService;

async fn delete(service: &dyn MemoryService) -> adk_core::Result<()> {
    // Delete entries matching a query within a project only
    service.delete_entries_in_project("app", "user", "my-project", "query").await?;

    // Delete ALL entries for a project
    service.delete_project("app", "user", "my-project").await?;

    // Global delete — only removes global entries
    service.delete_entries("app", "user", "query").await?;

    // delete_user removes everything (global + all projects)
    service.delete_user("app", "user").await?;
    Ok(())
}

MemoryServiceAdapter with project scope

use std::sync::Arc;

use adk_core::{Content, Memory, MemoryEntry};
use adk_memory::{InMemoryMemoryService, MemoryServiceAdapter};

#[tokio::main]
async fn main() -> adk_core::Result<()> {
    let service = Arc::new(InMemoryMemoryService::new());

    // Adapter without project — operates on global entries
    let global_adapter = MemoryServiceAdapter::new(service.clone(), "app", "user");

    // Adapter with project — all operations scoped to the project
    let _project_adapter =
        MemoryServiceAdapter::new(service.clone(), "app", "user").with_project_id("my-project");

    // Core Memory trait methods for ad-hoc project access
    let entry = MemoryEntry {
        content: Content::new("user").with_text("Budget approved"),
        author: "user".to_string(),
    };
    global_adapter.add_to_project(entry, "other-project").await?;
    let found = global_adapter.search_in_project("budget", "other-project").await?;
    assert_eq!(found.len(), 1);
    Ok(())
}

Project ID validation

use adk_memory::validate_project_id;

fn main() {
    assert!(validate_project_id("my-project").is_ok());
    assert!(validate_project_id("").is_err()); // must not be empty
    assert!(validate_project_id(&"x".repeat(257)).is_err()); // longer than 256 bytes
}

Feature Flags

Feature Backend Description
sqlite-memory SQLite Single-node persistence via sqlx
database-memory PostgreSQL pgvector-backed semantic search
redis-memory Redis Low-latency in-memory persistence via fred
mongodb-memory MongoDB Document-oriented persistence
neo4j-memory Neo4j Graph database persistence
vertex-memory Vertex AI Memory Bank Managed memory generation and retrieval on the Gemini Enterprise Agent Platform
graph-memory SQLite GraphMemoryService knowledge graph (implies sqlite-memory)
embedding-trait — The EmbeddingProvider trait without a vector backend
conformance — adk_memory::conformance and memory_conformance_tests!, the id and expiry suite for a backend's tests
# SQLite
adk-memory = { version = "3.0.0", features = ["sqlite-memory"] }

# PostgreSQL + pgvector
adk-memory = { version = "3.0.0", features = ["database-memory"] }

Backend Notes

Backend Behaviour
SQLite Search matches entries containing every query word; FTS5 syntax in the query is matched literally.
Redis Key segments are percent-encoded (% → %25, : → %3A); identifiers without either character keep their keys. delete_user deletes only the named user's keys.
Neo4j Entry ids are scoped by app, user, project and session; add_session merges on them, so re-ingesting a session updates it. Vector search over-fetches candidates before filtering to the tenant — see Neo4jMemoryService::with_vector_candidate_cap.

Artifact References

A memory can refer to an artifact without holding its bytes: MemoryEntry::with_artifact(uri, mime_type) adds a Part::FileData after the text, and MemoryEntry::artifact_references() returns the references. Search matches the text alone (text::extract_text is unchanged). Every backend that stores the entry's content keeps the references; the knowledge graph's episodic log keeps them in a column of its own (migration 3); Vertex AI Memory Bank stores extracted facts as text and keeps none.

Expiry and Deletion

Every backend stores an id and an expiry with each entry, never returns an expired entry from search or list_recent, and implements delete_memory and purge_expired. The rule lives in adk_memory::expiry; the conformance suite holds each backend to it.

API Behaviour
MemoryEntry::with_ttl, with_expires_at The entry's own expiry
with_default_ttl on each service (RedisMemoryConfig::ttl for Redis) The expiry of an entry written without one, measured from the write
MemoryService::delete_memory(app, user, id) Removes the entry with that id, global or in any project; returns how many it removed
MemoryService::purge_expired() Removes every expired entry; Redis keys, the MongoDB TTL index, and Memory Bank also expire entries natively
expiry::spawn_expiry_sweep(service, every) Runs purge_expired on an interval
use adk_core::Content;
use adk_memory::{InMemoryMemoryService, MemoryEntry, MemoryService};
use std::time::Duration;

#[tokio::main]
async fn main() -> adk_core::Result<()> {
    let memory = InMemoryMemoryService::new().with_default_ttl(Duration::from_secs(30 * 24 * 3600));
    let parking = MemoryEntry::new(Content::new("user").with_text("Parked on level 3"), "user")
        .with_id("parking")
        .with_ttl(Duration::from_secs(8 * 3600));
    memory.add_session("app", "ada", "s1", vec![parking]).await?;
    assert_eq!(memory.delete_memory("app", "ada", "parking").await?, 1);
    Ok(())
}

Schema Migrations

The SQLite, PostgreSQL, MongoDB, and Neo4j backends include a versioned migration system. Migrations are forward-only, idempotent, and tracked in a registry table. schema_version() returns 0 only when the registry table does not exist; a failed read is an error. PostgreSQL migrate() holds the advisory lock PostgresMemoryService::ADVISORY_LOCK_KEY on one connection. SQLite runs each step in a BEGIN IMMEDIATE transaction that re-reads the registry, and MongoDB and Neo4j create indexes and constraints idempotently and record each version once, with an upsert or MERGE, so several processes can migrate one database at once.

The example below needs the sqlite-memory feature.

Version Description
v1 Initial schema (tables, indexes, FTS)
v2 Add project_id column/index for project-scoped memory
v3 Add memory_id and expires_at (MongoDB: a TTL index on expires_at); existing entries get ids
use adk_memory::SqliteMemoryService;

#[tokio::main]
async fn main() -> adk_core::Result<()> {
    let service = SqliteMemoryService::new("sqlite:memory.db?mode=rwc").await?;

    // Run all pending migrations
    service.migrate().await?;

    // Check the current schema version
    let version = service.schema_version().await?;
    println!("Schema version: {version}");
    Ok(())
}

MemoryService Trait

Method Default
add_session(app, user, session, entries) required
search(SearchRequest) required
delete_user, delete_session, add_entry, delete_entries, list_recent Return a "not implemented" error; backends override them
delete_memory(app, user, id), purge_expired() Return an error; every backend in this crate implements them
export_user(app, user) Returns subject.unsupported; every backend in this crate lists the user's entries, global and project-scoped
health_check() Ok(())
supports_project_scoping() false
add_session_to_project, add_entry_to_project, delete_entries_in_project, delete_project Return an error

The project methods refuse instead of falling back to global writes or deletes, which would cross the project boundary. Every backend in this crate except VertexAiMemoryBankService and GraphMemoryService implements them and returns true from supports_project_scoping().

Subject Export and Erasure

MemorySubjectData adapts any MemoryService to adk_core::subject::SubjectDataStore: it exports a subject's entries through export_user and erases them through delete_user, for each of the subject's user ids in each covered application. Every backend passes adk_core::subject_data_store_conformance_tests!.

use std::sync::Arc;

use adk_core::subject::{InMemoryConsentStore, InMemorySubjectRegistry, SubjectRights};
use adk_memory::{InMemoryMemoryService, MemorySubjectData};

let rights = SubjectRights::new(
    Arc::new(InMemorySubjectRegistry::new()),
    Arc::new(InMemoryConsentStore::new()),
)
.with_app("support")
.with_store(Arc::new(MemorySubjectData::new(Arc::new(InMemoryMemoryService::new()))));

Consent-Gated Memory

ConsentGatedMemoryService wraps any MemoryService with an adk_core::subject::ConsentGate: for a gated user (a visitor id by default) without consent for persistent_profile, adds are skipped and search returns nothing; deletes and exports always pass through. See Subject Rights.

Related Crates

  • adk-rust - Meta-crate with all components
  • adk-core - Core Memory trait
  • adk-runner - Attaches the memory service to each invocation
  • adk-tool - LoadMemoryTool and PreloadMemoryTool (memory-tools feature)
  • adk-rag - RAG pipeline with vector stores

Changes in 3.0

Change Migration
SQL backends use SQLx 0.9; sqlx and pgvector are no longer implicit features, and pgvector moves to 0.4.2 Depend on SQLx 0.9 when sharing a pool; enable sqlite-memory or database-memory
adk-gcp, fred, google-cloud-auth, and reqwest are no longer implicit features Enable redis-memory or vertex-memory
schema_version() returns read failures as errors —
Keyword search matches through punctuation and returns the best matches first —
PostgreSQL migrate() releases its advisory lock —
MemoryEntry gains id and expires_at and is #[non_exhaustive] Build it with MemoryEntry::new and its with_* methods
MemoryService gains delete_memory and purge_expired A wrapper forwards both
RedisMemoryConfig::ttl is each entry's default TTL, not a session list's —

See the 2.x to 3.0 migration guide and the changelog for the full list.

SQLx compatibility

ADK-Rust 3.0 SQL backends use SQLx 0.9. SQLx types appear in this crate's public API — from_pool on SqliteMemoryService, GraphMemoryService and PostgresMemoryService, and the migration runners — so an application that passes in its own pool must depend on SQLx 0.9 too. Applications that let ADK open its own connections need no SQLx dependency. The SQLx 0.9 migration guide lists who is affected and what changed, and its TLS behaviour section covers PostgreSQL certificate verification.

License

Apache-2.0

Part of ADK-Rust

This crate is part of the ADK-Rust framework for building AI agents in Rust.