adk-rag
Give your AI agents a knowledge base. adk-rag adds Retrieval-Augmented Generation (RAG) to ADK-Rust so your agents can search documents and answer questions using your own data.
Stability: Stable — follows semantic versioning, so breaking changes wait for the next major release. See STABILITY.md.
ADK RAG
The adk-rag crate provides Retrieval-Augmented Generation capabilities for the ADK-Rust workspace. It offers a modular, trait-based architecture for document chunking, embedding generation, vector storage, similarity search, reranking, and agentic retrieval. The crate follows the ADK-Rust conventions of feature-gated backends, async-trait interfaces, and builder-pattern configuration. It integrates with existing ADK crates (adk-gemini for embeddings, adk-core for the Tool trait) and supports multiple vector store backends (in-memory, Qdrant, LanceDB, pgvector, Agent Retrieval), plus managed retrieval from Vertex AI RAG Engine corpora.
What is RAG?
RAG stands for Retrieval-Augmented Generation. Instead of relying only on what an LLM was trained on, RAG lets your agent look up relevant information from your documents before answering:
- Ingest — Documents are split into chunks, converted to vector embeddings, and stored
- Query — A user question is embedded and matched against stored chunks
- Generate — The most relevant chunks are passed to the LLM as context
Quick Start
A RAG pipeline with Gemini embeddings and the in-memory vector store. The program needs a GOOGLE_API_KEY from Google AI Studio.
[]
= { = "3.0.0", = ["gemini"] }
= { = "1", = ["full"] }
use Arc;
use *;
async
GOOGLE_API_KEY=your-key-here
Agent with RAG Tool
An agent that searches a knowledge base to answer questions. The agent decides when to call
rag_search and answers from the retrieved chunks.
[]
= { = "3.0.0", = ["gemini"] }
= "3.0.0"
= "3.0.0"
= "3.0.0"
= "3.0.0"
= "3.0.0"
= "0.3"
= { = "1", = ["full"] }
use Arc;
use LlmAgentBuilder;
use Content;
use GeminiModel;
use ;
use Runner;
use ;
use StreamExt;
async
The agent will automatically call rag_search when it needs information from your knowledge base.
How It Works
adk-rag is built from four pluggable components:
Documents → [Chunker] → [EmbeddingProvider] → [VectorStore]
↓
Query → [EmbeddingProvider] → [VectorStore search] → [Reranker] → Results
| Component | What it does | Built-in options |
|---|---|---|
| Chunker | Splits documents into smaller pieces | FixedSizeChunker, RecursiveChunker, MarkdownChunker |
| EmbeddingProvider | Converts text to vector embeddings | GeminiEmbeddingProvider¹, OpenAIEmbeddingProvider², OnnxEmbeddingProvider⁶ |
| VectorStore | Stores and searches embeddings | InMemoryVectorStore, QdrantVectorStore³, LanceDBVectorStore⁴, PgVectorStore⁵, AgentRetrievalStore⁷ |
| Reranker | Re-scores results after search | NoOpReranker (default), or write your own |
¹ gemini feature ² openai feature ³ qdrant feature ⁴ lancedb feature ⁵ pgvector feature ⁶ onnx feature ⁷ agent-retrieval feature
The RagPipeline wires these together. The RagTool wraps the pipeline as an adk_core::Tool so any ADK agent can call it. AgentRetrievalStore is a managed VectorStore on Google's Agent Retrieval service.
Embedding Providers
Gemini
Uses Google's gemini-embedding-2 model (3072 dimensions).
= { = "3.0.0", = ["gemini"] }
use ;
async
with_output_dimensionality(dims) requests shorter vectors and with_task_type(task) sets the
embedding task.
OpenAI
Uses text-embedding-3-small (1536 dimensions) by default. Supports dimension truncation via Matryoshka.
= { = "3.0.0", = ["openai"] }
use ;
async
Custom Embedding Provider
Implement the EmbeddingProvider trait to use any embedding model — a local model, a different API, or a mock for testing.
use ;
use async_trait;
;
embed_batch has a default implementation that calls embed for each text; override it when
your model accepts batches.
Add async-trait = "0.1" to your Cargo.toml when implementing traits.
Vector Stores
InMemoryVectorStore (default)
No external dependencies. Good for development, testing, and small datasets. Data is lost when the process exits. Results of equal score come back in ascending chunk-ID order, so a query returns the same chunks on every run.
use InMemoryVectorStore;
Qdrant
Connects to a Qdrant server over gRPC (QdrantVectorStore::default_url() uses http://localhost:6334).
= { = "3.0.0", = ["qdrant"] }
use QdrantVectorStore;
Qdrant accepts only unsigned integers and UUIDs as point IDs, so each chunk is stored under the
UUID v5 of its chunk ID and the chunk ID is kept in the point's chunk_id payload field. Search
returns the original chunk ID, and delete maps IDs the same way.
LanceDB
Embedded vector database with no server required. Data persists to disk.
= { = "3.0.0", = ["lancedb"] }
Requires
protocinstalled:brew install protobuf(macOS),apt install protobuf-compiler(Ubuntu).
use LanceDBVectorStore;
async
upsert replaces rows by scope and chunk id, so re-ingesting a document updates
its chunks instead of duplicating them. An embedding whose length differs from the
collection's dimensions returns RagError::VectorStoreError.
pgvector (PostgreSQL)
Use your existing PostgreSQL database for vector search.
= { = "3.0.0", = ["pgvector"] }
use PgVectorStore;
async
PgVectorStore::from_pool(pool) uses a pool the application already holds.
Each collection is stored in the table rag_<name>. A collection name must be 1
to 59 bytes of ASCII lowercase letters, digits and underscores, so the table name
fits PostgreSQL's 63-byte identifier limit. Any other name returns
RagError::VectorStoreError instead of being rewritten, so two distinct names
never share a table.
Agent Retrieval
Google's managed vector database on the Gemini Enterprise Agent Platform (formerly Vector Search
2.0). The store keeps chunk text and metadata in each Data Object, takes embeddings from the
pipeline, and maps collection names to RFC 1035 collection IDs. A collection name uses ASCII
lowercase letters, digits, and underscores, starts with a letter (unless a collection prefix is
set), ends with a letter or digit, and fits 63 characters with the prefix; each underscore becomes
a hyphen, so my_docs is the collection my-docs. Any other name returns
RagError::VectorStoreError instead of being rewritten.
= { = "3.0.0", = ["agent-retrieval"] }
use ;
async
AgentRetrievalStore::hybrid_search fuses semantic and text search, both filtered by scope,
with reciprocal rank fusion. Each chunk is stored under a Data Object ID derived from its scope
and chunk ID, because Agent Retrieval accepts only RFC 1035 labels, and create_collection
declares a data schema because the service admits no undeclared data field.
Erasing a person's chunks
RagSubjectData adapts a VectorStore to adk_core::subject::SubjectDataStore, so
SubjectRights exports and erases a person's chunks with the rest of their data: chunks tagged
with SUBJECT_METADATA_KEY (adk_subject) are deleted with delete_where
(SubjectPartition::Tagged), and a scope per user is purged with purge_scope
(SubjectPartition::ScopePerUser). See
Subject Rights.
Vertex AI RAG Engine (managed)
Instead of running your own pipeline, retrieve from managed Vertex AI RAG
Engine corpora — the platform handles chunking, embedding, and vector search.
The vertex-rag feature provides a read-only data-plane client and a
retrieval tool (corpus creation and file import stay in the Vertex AI console
or management APIs):
= { = "3.0.0", = ["vertex-rag"] }
use Arc;
use ;
async
See docs/official_docs/rag/vertex-rag-engine.md
and the vertex_rag example in adk-playground.
Choosing a Chunker
| Chunker | Best for | How it splits |
|---|---|---|
FixedSizeChunker |
General text, logs | Every N bytes with overlap, on character boundaries |
RecursiveChunker |
Articles, docs, code | Paragraphs → sentences → words (natural boundaries) |
MarkdownChunker |
Markdown files, READMEs | By headers, preserving section hierarchy in metadata |
use ;
Sizes are bytes of UTF-8, not characters, and chunks never split a character.
new normalises an invalid size pair (a zero chunk_size becomes 1 and a
chunk_overlap that is not smaller than chunk_size is ignored, with a
warning); try_new rejects it with RagError::ConfigError:
use FixedSizeChunker;
Configuration
use RagConfig;
- chunk_size — Smaller chunks are more precise but may lose context. 200–500 is a good range.
- chunk_overlap — Prevents information loss at chunk boundaries. 10–20% of chunk_size works well.
- top_k — More results give the LLM more context but increase token usage.
- similarity_threshold — Filter out low-quality matches. 0.0 returns everything, 0.3–0.7 keeps strong matches only.
Writing a Custom Reranker
The default NoOpReranker passes results through unchanged. Write your own to improve precision:
[]
= { = "3.0.0", = ["gemini"] }
= "0.1"
= { = "1", = ["full"] }
use Arc;
use ;
use async_trait;
Feature Flags
# Core only (in-memory store, all chunkers, no external deps)
= "3.0.0"
# With Gemini embeddings
= { = "3.0.0", = ["gemini"] }
# With OpenAI embeddings
= { = "3.0.0", = ["openai"] }
# With a persistent vector store
= { = "3.0.0", = ["gemini", "qdrant"] }
# Everything
= { = "3.0.0", = ["full"] }
| Feature | Enables | Extra dependency |
|---|---|---|
| (default) | Core traits, InMemoryVectorStore, all chunkers |
none |
gemini |
GeminiEmbeddingProvider |
adk-gemini |
openai |
OpenAIEmbeddingProvider |
reqwest |
onnx |
OnnxEmbeddingProvider: a sentence-transformer ONNX model (default BAAI/bge-small-en-v1.5, 384 dimensions) run in process, fetched once into the Hugging Face hub cache; ort downloads the onnxruntime binary at build time |
ort, tokenizers, hf-hub |
qdrant |
QdrantVectorStore |
qdrant-client, uuid |
lancedb |
LanceDBVectorStore |
lancedb (arrow types come from its re-exports), futures |
pgvector |
PgVectorStore |
sqlx |
agent-retrieval |
AgentRetrievalStore (Agent Retrieval, formerly Vector Search 2.0) |
adk-gcp, google-cloud-auth, reqwest, uuid |
vertex-rag |
VertexRagEngineClient, VertexAiRagRetrievalTool |
adk-gcp, google-cloud-auth, reqwest |
full |
gemini, openai, qdrant, lancedb, pgvector |
all of those |
Testing Without API Keys
For unit tests or CI where you don't have API keys, implement a deterministic mock embedder:
use async_trait;
use ;
;
This produces stable vectors so your tests are reproducible, but the similarity scores won't be meaningful. Use it for testing pipeline wiring, not search quality.
Examples
| Example | What it shows |
|---|---|
vertex_rag in adk-playground |
Vertex AI RAG Engine retrieval |
The adk-playground repository has more RAG examples, such as a custom embedder and multi-collection search.
API Reference
Core types
| Type | Fields |
|---|---|
Document |
id, text, metadata: HashMap<String, String>, source_uri: Option<String>, title: Option<String> |
Chunk |
id, text, embedding: Vec<f32>, metadata, document_id, source_uri, title |
SearchResult |
chunk: Chunk, score: f32 |
Document and Chunk are #[non_exhaustive]: build them with Document::new(id, text) and
Chunk::new(id, document_id, text) or Chunk::from_document(&document, id, text), then the
with_metadata, with_source_uri, with_title, and (for Chunk) with_embedding builders.
Provenance
A document's source_uri and title say where its text came from. Every built-in chunker
copies them onto each chunk, every vector store persists them as fields of their own and
returns them with search results, and RagTool passes them to the model. Metadata is stored
verbatim with no reserved keys, so provenance never collides with a metadata entry.
| Backend | Where provenance is stored | Existing data |
|---|---|---|
| In-memory | the stored Chunk |
— |
| pgvector | source_uri and title columns |
create_collection adds the columns in place |
| LanceDB | source_uri and title columns |
re-create the table and re-ingest; upsert into an old table fails with that guidance |
| Qdrant | source_uri and title payload fields |
old points return None until re-ingested |
| Agent Retrieval | sourceUri and title data fields |
old data objects return None until re-ingested |
Scopes
Every VectorStore operation names a Scope, and a stored chunk is identified by its
collection, scope, and chunk ID together, so tenants can share a collection: the same
document ID in two scopes keeps two sets of chunks, and a search sees only its scope's chunks.
Every backend applies the scope inside its search, before the top k are chosen, so a small
tenant keeps its recall beside a large one. The shared contract suite checks all of this on
every backend, including a scope of one chunk beside 500 nearer chunks of another scope.
| Constructor | Key |
|---|---|
Scope::new("org-7") |
The opaque key itself: 1 to 256 bytes, no control characters |
Scope::from_parts(["support", tenant_id]) |
Each part percent-encoded, joined with / |
Scope::single_tenant() |
:single-tenant, for an application with one tenant |
Pipeline methods
| Method | Does |
|---|---|
create_collection(name), delete_collection(name) |
Manage collections in the vector store |
create_collection_with_filterable(name, ["lang"]) |
Create a collection whose listed metadata keys filters may name |
scoped(scope) |
A ScopedRag that ingests into, searches, and deletes from one scope |
ScopedRag method |
Does |
|---|---|
ingest(collection, &document) |
Chunk, embed, and store one document, replacing its earlier chunks; returns its chunks |
ingest_batch(collection, &documents) |
The same for several documents |
query(collection, text) |
Embed, search the scope, rerank, and drop results below similarity_threshold |
query_with(collection, text, &options) |
The same with QueryOptions: with_top_k(3), with_filter(filter) |
count(collection), count_where(collection, &filter) |
The number of the scope's chunks, or of those the filter matches |
delete_where(collection, &filter) |
Delete the scope's chunks the filter matches; returns how many |
delete_document(collection, id) |
Delete every chunk of one document in the scope |
purge_scope(collection) |
Delete every chunk of the scope; returns how many it held |
ingest upserts the new chunks, then deletes the document's chunks in the scope that the new
version no longer has, so a shorter version leaves no stale chunks and a search never finds the
document without chunks. A document with empty text removes the document.
| Backend | Scope storage | Data stored before scopes |
|---|---|---|
| In-memory | a map per scope | — |
| pgvector | scope column, primary key (scope, id) |
create_collection migrates in place; existing rows join Scope::single_tenant() |
| LanceDB | scope column, merge-insert on scope and id |
re-create and re-ingest; upsert fails with that guidance |
| Qdrant | scope payload field, tenant index; point ID from scope and chunk ID |
re-ingest |
| Agent Retrieval | scope data field; Data Object ID from scope and chunk ID; declared data schema |
re-create and re-ingest |
Filters
A Filter is a typed predicate over a chunk's metadata, document_id, source_uri, and chunk
ID. Every backend compiles it into its own query language with bound parameters or typed
expressions and applies it with the scope, before the top k are chosen.
use ;
let filter = and;
let options = new.with_top_k.with_filter;
| Filter | Matches |
|---|---|
Filter::eq(field, value) |
The field is present and equals the value |
Filter::is_in(field, values) |
The field is present and equals one of the values (at least one) |
Filter::exists(field) |
The field is present |
Filter::and([..]), Filter::or([..]) |
Every / at least one filter matches (at least one filter) |
!filter |
The filter does not match, so !Filter::eq(field, v) matches chunks without the field |
Values are strings. A metadata key a filter names must be declared on the collection —
create_collection_with_filterable(name, keys), or CollectionSpec::with_filterable on a
VectorStore — and use ASCII letters, digits, and underscores. The pipeline refuses an
undeclared key, an empty And, Or, or In, and any shape a backend cannot express with
RagError::UnsupportedFilter before any I/O; no backend ignores a predicate or applies part of
one. Filter::matches is the reference evaluator: the in-memory store uses it, and the shared
contract compares every other backend with it on a filter catalogue and on generated filter
trees.
| Backend | Compiles to | Declared keys |
|---|---|---|
| In-memory | Filter::matches |
— |
| pgvector | WHERE conditions; keys and values are bound parameters, leaves wrapped in COALESCE(.., false) |
— |
| LanceDB | Typed DataFusion expressions, prefiltered | Nullable m_<key> columns |
| Qdrant | Nested must / should / must_not filters on metadata.<key> |
Keyword payload indexes |
| Agent Retrieval | $eq, $in, $and, $or; $ne/$nin for ! around Eq/In on the document or chunk ID |
m_<key> data fields in the schema |
Agent Retrieval refuses Exists, other negations, and nesting deeper than two levels (the
scope's $and counts as one), because its filter language cannot express them.
RagTool
RagTool::new(pipeline, default_collection) exposes the pipeline as the rag_search tool,
searching that one collection in Scope::single_tenant(). with_allowed_collections([...])
lets the model choose among further collections:
| Configuration | Arguments | A call naming another collection |
|---|---|---|
RagTool::new(pipeline, "docs") |
query (required), top_k |
Fails with tool.invalid_arguments |
.with_allowed_collections(["faq"]) |
query (required), top_k, collection (docs or faq; docs when omitted) |
Fails with tool.invalid_arguments, naming the allowed collections |
| Builder | Effect |
|---|---|
with_scope(scope) |
Every call searches scope |
with_scope_from(|ctx| ..) |
Each call's scope is resolved from its ToolContext (app, user, session, state, identity); an error fails the call before any search |
with_scope_per_user() |
Scope::from_parts([app_name, user_id]) of each call |
with_policy_filter(filter) |
filter applies to every call, AND-ed with the model's |
with_model_filterable(["section"]) |
The schema gains a filter argument mapping each listed metadata key to a string (equal) or an array of strings (one of); any other key fails with tool.invalid_arguments |
The scope and policy filter are configuration, never model arguments, so the model can narrow results but never reach another scope or widen past the policy. Keys of the policy filter and model-filterable keys must be declared filterable on the collection.
use Arc;
use ;
Each result with a source_uri is recorded as an adk_core::GroundingSource on the call's
event, so the agent binds the final answer's [title](uri) links to it and adk-guardrail's
CitationRequired can require a citation of a retrieved source.
The tool returns the results best first, each as
{"id", "document_id", "text", "metadata", "score"} plus source_uri and title when the
chunk's document had them. Embedding vectors are left out, and a
top_k override is reranked and filtered like any other query. The tool is read-only and
concurrency-safe. With one collection per tenant, build one tool per tenant from the
authenticated request.
SQLx compatibility
ADK-Rust 3.0 SQL backends use SQLx 0.9. SQLx types appear in this crate's public
API — PgVectorStore::from_pool — 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.