Vector-Based Memory Retrieval: Semantic Recall over Past User Statements
Swap ADK's keyword memory for vector similarity and your agent can answer 'I told you I hate cilantro' without the word 'hate' ever appearing in the query. A hands-on guide to VertexAiRagMemoryService, tool-level search_memory, and when Memory Bank is the better fit.
Published on • December 3, 2026
AI Assistant

A user tells your booking agent in session one: “I always get motion sick on ferries.” Forty sessions later they ask “can you find me a crossing to the islands?” and the agent happily books the fastest ferry. Nothing broke — the keyword matcher in InMemoryMemoryService simply had nothing to match on. The word “ferry” appeared in both, but “motion sick” and “fastest crossing” share no tokens worth scoring.
That failure mode is the whole argument for vector-based memory retrieval. Instead of matching substrings, you embed statements into a vector space and retrieve by distance, so semantically related phrasing collapses onto each other. ADK gives you two vector-backed paths — VertexAiRagMemoryService (raw transcript similarity over a Knowledge Engine corpus) and VertexAiMemoryBankService (LLM-extracted memories with semantic search) — and this post walks through wiring the first one, reaching it from a tool, and deciding when the second one is the better fit.
Prerequisites
pip install google-adkfor the core, pluspip install google-adk[gcp]— constructingVertexAiRagMemoryServiceraisesImportErrorwithout the extra.- A Google Cloud project with the Agent Platform API enabled and a Knowledge Engine (RAG) corpus already created.
- Application Default Credentials (
gcloud auth application-default login). - A
Runneryou have run at least once, and aSessionyou have pushed to memory.
1. Choose the service before you write the code
All three implementations expose the same BaseMemoryService interface — add_session_to_memory, search_memory, and the optional add_events_to_memory / add_memory — but they retrieve in fundamentally different ways:
InMemoryMemoryService | VertexAiRagMemoryService | VertexAiMemoryBankService | |
|---|---|---|---|
| Retrieval mechanism | Basic keyword matching | Vector similarity over a Knowledge Engine corpus | Semantic search over LLM-extracted memories |
| What is stored | Full conversation | Full conversation, indexed by Knowledge Engine | Consolidated memories, not raw transcript |
| Persistence | None — lost on restart | Yes — stored in Knowledge Engine | Yes — managed by Agent Platform |
| Setup complexity | None (it’s the default) | Medium — corpus + google-adk[gcp] | Low — needs an Agent Runtime ID |
| Best for | Prototyping and local testing | Retrieving raw past statements by meaning | Evolving, deduplicated user knowledge |
The middle column is the one this post builds: vector similarity recall over past user statements. If you want the agent to hear “I told you I hate cilantro” as a match for a query about “coriander,” you need embeddings between the two — not a token overlap score.
2. Construct the RAG memory service
The constructor wants the full resource name of the corpus, not a bare ID, plus two retrieval knobs:
from google.adk.memory import VertexAiRagMemoryService
memory_service = VertexAiRagMemoryService(
rag_corpus="projects/PROJECT_ID/locations/LOCATION/ragCorpora/CORPUS_ID",
similarity_top_k=5, # how many snippets come back
vector_distance_threshold=0.6, # discard anything less similar than this
)
Then hand it to the Runner alongside your session service:
from google.adk.runners import Runner
runner = Runner(
agent=root_agent,
app_name="travel_concierge",
session_service=session_service,
memory_service=memory_service,
)
similarity_top_k and vector_distance_threshold are your precision/recall dial. A generous top-k with a low threshold floods the model with near-misses; a tight threshold with top_k=1 risks returning nothing at all on paraphrased queries. Start at 5 / 0.6 and measure before you tune.
3. Ingestion is still a decision, not a side effect
Nothing reaches the corpus until you push it. The standard pattern is an after_agent_callback that flushes the completed session:
from google.adk.agents import Agent
async def remember_this_conversation(callback_context):
await callback_context.add_session_to_memory()
agent = Agent(
model="gemini-flash-latest",
name="concierge",
instruction="Answer the user's travel questions.",
after_agent_callback=remember_this_conversation,
)
Because ingestion is explicit, you control what becomes searchable. If you would rather seed specific facts than whole transcripts, add_memory accepts explicit MemoryEntry objects — but note that only some backends implement it, so confirm before you design around it.
4. Reaching the memory from the agent
Once the service is wired, the agent has three retrieval routes:
| Route | Trigger | Use when |
|---|---|---|
load_memory tool | The model decides to call it | Recall is optional and query-shaped |
preload_memory tool | Runs automatically at the start of every turn | You always want recent memories in context |
| Custom tool | Your code calls tool_context.search_memory(query) | You need to post-process, filter, or log the hits |
The custom route is just a thin wrapper over the service:
from google.adk.tools import ToolContext
async def recall_past_statements(query: str, tool_context: ToolContext) -> dict:
response = await tool_context.search_memory(query)
return {
"results": [
part.text
for entry in response.memories
for part in (entry.content.parts or [])
if part.text
]
}
Under the hood this is memory_service.search_memory(app_name, user_id, query), which returns a list of MemoryEntry objects — the tool context simply fills in the first two arguments for you. Register it like any other tool:
agent = Agent(
model="gemini-flash-latest",
name="concierge",
instruction=(
"Before answering, search past user statements with "
"recall_past_statements and prefer constraints the user already gave."
),
tools=[recall_past_statements],
)
5. When to pick Memory Bank instead
VertexAiRagMemoryService gives you verbatim transcript recall: exact what-the-user-said retrieval, at the cost of also retrieving filler. VertexAiMemoryBankService flips the tradeoff — an LLM extracts and consolidates meaningful memories, then serves them via semantic search, so you get “user prefers aisle seats and avoids early departures” rather than a paragraph where that was buried. It needs an Agent Runtime and is configured either through --memory_service_uri="agentengine://<id>" or by constructing the service directly with project, location, and agent_engine_id.
A practical rule: use RAG memory when the exact past statement matters (complaints, quotes, commitments), and Memory Bank when you want durable, deduplicated user knowledge. They are not mutually exclusive — an agent can hold more than one memory service and route between them.
Checklist
-
google-adk[gcp]is installed before anything importsVertexAiRagMemoryService. - The corpus is passed as a full
projects/.../ragCorpora/...resource name, not a bare ID. -
similarity_top_kandvector_distance_thresholdare measured, not guessed. - Ingestion is wired explicitly through
add_session_to_memory(callback or service call). - Retrieval route is chosen deliberately:
load_memory,preload_memory, or a customtool_context.search_memorytool. - The agent’s instruction tells it when to search, not just that it can.
- Raw-transcript recall (RAG) vs. consolidated knowledge (Memory Bank) matches the product requirement.
- The service instance is shared across
Runners — memory is not per-runner.
Conclusion
Keyword memory fails quietly: it returns nothing rather than raising, so the agent just seems to forget. Vector retrieval fixes the failure mode by scoring meaning instead of tokens, and ADK wires it in behind a single search_memory call. Pick VertexAiRagMemoryService when the user’s exact past words matter, VertexAiMemoryBankService when distilled knowledge matters, and keep ingestion deliberate — the best retriever in the world cannot recall a conversation you never stored.