---
title: "Memory Bank Integration: Preloading User Profiles with PreloadMemoryTool"
date: "2026-12-03T08:32:05+07:00"
description: "Wire VertexAiMemoryBankService into an ADK agent and use the preload_memory tool to inject the user's stored profile at the start of every turn — plus the auto-save callback that keeps memories growing."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-memory-bank-preload-memory-tool.jpg"
alt: "A user profile card being loaded into an agent's context at the start of a conversation turn"
tags: ['google-adk', 'memory-bank', 'preload-memory', 'vertex-ai', 'agent-memory']
---

An agent that greets a returning customer with "How can I help you today?" has technically failed — the user told it their shipping preference, their project name, and their timezone in three previous conversations. The information is not lost; it is sitting in your memory store. The failure is in the *retrieval path*: `load_memory` only helps if the model decides to call it, and a model that does not know a fact exists never searches for it.

Google ADK closes that gap with the `preload_memory` tool: it runs automatically at the beginning of every turn and hands the model whatever relevant memories exist *before* the model ever formulates a response. Combined with `VertexAiMemoryBankService` — Google's managed Memory Bank — you get a profile-aware agent with about twenty lines of wiring. This tutorial builds that wiring end to end.

## Prerequisites

- `google-adk` installed (`pip install google-adk`) and an agent you have run with a `Runner`.
- A Google Cloud project with the **Agent Platform API** enabled.
- An **Agent Runtime** resource on Agent Platform (you do not need to deploy your agent to it — you only need its ID).
- Authentication and environment:

```bash
gcloud auth application-default login
export GOOGLE_CLOUD_PROJECT="your-gcp-project-id"
export GOOGLE_CLOUD_LOCATION="your-gcp-location"
```

- Familiarity with `MemoryService` concepts (session ingestion vs. search) helps, but is not required.

## 1. Choosing the memory service

ADK ships three `MemoryService` implementations. `preload_memory` works with any of them, but the quality of what gets preloaded depends entirely on the extraction step:

| Feature | `InMemoryMemoryService` | `VertexAiMemoryBankService` | `VertexAiRagMemoryService` |
| --- | --- | --- | --- |
| Persistence | None — lost on restart | Managed by Agent Platform | Stored in Knowledge Engine |
| Memory extraction | Stores full conversation | LLM extracts meaningful memories | Stores full conversation |
| Search capability | Basic keyword matching | Advanced semantic search | Vector similarity |
| Setup complexity | None — it's the default | Low — needs an Agent Runtime | Medium — needs a RAG corpus |
| Best for | Prototyping | Evolving user profiles from conversations | Raw transcript retrieval / existing RAG |

For a *user profile* use case — durable facts like preferences, roles, and project context — Memory Bank is the right column: it distills conversations into discrete, searchable memories instead of replaying transcripts.

## 2. Constructing the service

There are two equivalent ways to connect Memory Bank.

**Route A — the CLI flag** (simplest for `adk web` and `adk api_server`):

```bash
adk web path/to/your/agents_dir --memory_service_uri="agentengine://1234567890"
```

**Route B — construct the service and pass it to the `Runner`** (required for programmatic embedding):

```python
from google.adk.memory import VertexAiMemoryBankService

memory_service = VertexAiMemoryBankService(
    project="your-gcp-project-id",
    location="your-gcp-location",
    agent_engine_id="1234567890",
)

runner = Runner(
    agent=root_agent,
    app_name="profile_assistant",
    session_service=session_service,
    memory_service=memory_service,   # <-- shared across runners
)
```

> **Rule:** services must be shared across `Runner` instances to share state and memory. A second `Runner` with a fresh service sees nothing.

## 3. Preloading vs. on-demand retrieval

ADK provides two pre-built retrieval tools, and they encode a genuine design choice:

| | `preload_memory` | `load_memory` |
| --- | --- | --- |
| When it runs | Automatically, at the start of each turn | Only when the model decides to call it |
| Cost per turn | One memory search always | Zero if the model never calls it |
| Best for | User profiles, always-relevant context | Occasional lookups ("what did we decide about X?") |
| Failure mode | Wasted search if memory is empty | Missed recall if the model doesn't know to search |

Attach `preload_memory` the same way you attach any tool:

```python
from google.adk.agents import Agent
from google.adk.tools import preload_memory

agent = Agent(
    model="gemini-2.5-flash",
    name="profile_assistant",
    instruction=(
        "You are a personal assistant. A summary of what you already know "
        "about this user is provided at the start of every turn — use it "
        "naturally, and never ask for information you have already been given."
    ),
    tools=[preload_memory],
)
```

The tool's result lands in the model's context before it drafts a reply, which is exactly the "profile preloading" behavior we want. For selective recall, add `load_memory` alongside it — the agent gets both the automatic head start and the ability to dig deeper.

## 4. Keeping memory fresh: the auto-save callback

Preloading is the read side. Without a write side, the profile is frozen at whatever was ingested once. The standard pattern is an `after_agent_callback` that persists the completed session:

```python
from google.adk.agents import Agent
from google.adk.tools import preload_memory

async def auto_save_session_to_memory_callback(callback_context):
    await callback_context.add_session_to_memory()

agent = Agent(
    model="gemini-2.5-flash",
    name="profile_assistant",
    instruction="Answer the user's questions.",
    tools=[preload_memory],
    after_agent_callback=auto_save_session_to_memory_callback,
)
```

Memory ingestion is a **decision, not a side effect** — nothing is remembered until you push it. This callback makes that decision every turn, so the next turn's `preload_memory` call has something new to work with.

## 5. Searching memory inside a custom tool

When you need control over *what* gets searched (a user-supplied query, a filtered subset), reach for `tool_context.search_memory`:

```python
from google.adk.tools import ToolContext

async def search_past_conversations(
    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
        ]
    }
```

This is the escape hatch for logic that neither built-in tool expresses: date-windowed searches, multi-query fan-out, or post-filtering results before the model sees them.

## 6. Direct ingestion for curated facts

Not every memory should come from conversation mining. `VertexAiMemoryBankService.add_memory` accepts explicit `MemoryEntry` objects — useful for facts from a signup form, a CRM, or an admin console:

```python
from google.adk.memory.memory_entry import MemoryEntry
from google.genai.types import Content, Part

await memory_service.add_memory(
    app_name="profile_assistant",
    user_id="user-123",
    memories=[
        MemoryEntry(content=Content(parts=[Part(
            text="The user is a backend engineer on the payments team."
        )]))
    ],
)
```

By default this calls `memories.create`, storing each entry as a distinct item. Pass `custom_metadata={"enable_consolidation": True}` to switch to `memories.generate`, which merges the new fact with related existing memories instead of accumulating near-duplicates — the subject of our companion article on consolidation.

## Checklist

- [ ] An Agent Runtime exists and `gcloud auth application-default login` has been run.
- [ ] `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` are exported.
- [ ] Memory Bank is wired via `--memory_service_uri="agentengine://<id>"` or a constructed `VertexAiMemoryBankService` passed to `Runner`.
- [ ] The same service instance is shared across every `Runner` that must see the same memory.
- [ ] `preload_memory` is in `tools` for always-relevant profile context.
- [ ] `load_memory` is available for on-demand deep recall.
- [ ] An `after_agent_callback` calls `callback_context.add_session_to_memory()` so memories accumulate.
- [ ] Curated non-conversation facts use `add_memory` with `MemoryEntry`, with `enable_consolidation` set deliberately.
- [ ] Custom search needs use `tool_context.search_memory(query)` rather than a reimplemented store.

## Conclusion

A profile-aware agent is not a bigger prompt — it is a retrieval path that runs before the model can fail to use it. `VertexAiMemoryBankService` supplies distilled, semantic memories; `preload_memory` guarantees they arrive at the start of every turn; and the auto-save callback ensures the next turn has more to preload than the last. Wire those three together and the user's third conversation starts where the second one ended, instead of from scratch.

## References

- https://adk.dev/sessions/memory/
- https://adk.dev/sessions/state/
- https://adk.dev/sessions/session/
