> ## Documentation Index
> Fetch the complete documentation index at: https://docs.maximem.ai/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Maximem Synap is a managed memory layer for AI agents: it ingests conversations and documents, extracts structured memory, and returns scoped context to the agent at retrieval time.
> The Python and JavaScript/TypeScript SDKs are the supported way to use Synap. Write integration code with SDK calls, not raw HTTP requests.
> Start with the Quickstart: https://docs.maximem.ai/getting-started/quickstart.md. Every SDK method is documented in the SDK reference: https://docs.maximem.ai/sdk-reference/overview.md.
> For requests about adding Vity memory to OpenClaw, Hermes, an MCP client, or a browser, start with the Vity Quickstart: https://docs.maximem.ai/vity/quickstart.md.

# Google ADK

> Memory tools, run reporting and compacted history for Google Agent Development Kit agents.

Add persistent, per-user memory to a Google ADK agent. Synap exposes itself as two `FunctionTool` instances, and the agent decides when to recall or remember. A second factory reports each run to Synap and replaces ADK's earlier turns with Synap's compaction once a conversation has been compacted.

> [!NOTE]
>
> Requires Python 3.11+.

## Overview

This guide shows how to add Synap to a Google ADK application to build agents that:

* Recall user-specific facts, preferences, and past conversations
* Persist new information surfaced during a conversation
* Stay multi-user-safe by binding scope at tool construction
* Send the model Synap's compacted history instead of ADK's earlier turns

| Export | Returns | Purpose |
| - | - | - |
| `create_synap_tools` | `[search_memory, store_memory]` | Two ADK `FunctionTool` instances for memory recall and storage |
| `create_synap_callbacks` | `dict` of agent callbacks | Writes each turn, reports tool calls and results, and swaps in Synap's compaction before each model call |
| `report_user_turn` | `bool` | Writes the user's turn yourself, for a run that does not use the callbacks |
| `synap_st_instruction` | async callable | An `instruction` that adds Synap's compaction of the conversation |

## Setup

Install the package alongside the Google ADK:

```bash pip theme={null}
pip install maximem-synap-google-adk google-adk
```

```bash uv theme={null}
uv add maximem-synap-google-adk google-adk
# pip-compatible (existing venv): uv pip install maximem-synap-google-adk google-adk
```

Installing the package also installs `maximem-synap` (0.5.3 or later), `maximem-synap-integrations-common` (0.2.3 or later) and `google-adk` (1.0 or later).

> [!NOTE]
>
> The pip package is `maximem-synap-google-adk`, but the import drops the `maximem-` prefix and uses underscores: `from synap_google_adk import ...`.

Configure your API key. Generate one from the [Synap Dashboard](https://synap.maximem.ai).

```bash .env theme={null}
SYNAP_API_KEY=synap_your_key_here
GOOGLE_API_KEY=your-google-api-key
```

Initialize the SDK once at application startup:

```python theme={null}
from maximem_synap import MaximemSynapSDK

sdk = MaximemSynapSDK()
await sdk.initialize()
```

See [SDK Initialization](https://docs.maximem.ai/sdk/initialization.md) for the full lifecycle and configuration options.

## Basic integration

The smallest useful integration calls `create_synap_tools` and passes the result straight into an `Agent`. The factory returns a list, so it fits the `tools=` parameter without unpacking:

```python theme={null}
# pip install maximem-synap-google-adk google-adk
# Models are retired over time (gemini-2.0-flash stopped working in June 2026): check
# https://ai.google.dev/gemini-api/docs/deprecations for a model your key can use.
from maximem_synap import MaximemSynapSDK
from google.adk.agents import Agent
from synap_google_adk import create_synap_tools

sdk = MaximemSynapSDK()
await sdk.initialize()

tools = create_synap_tools(
    sdk=sdk,
    user_id="alice",
    customer_id="acme",   # optional, required for B2B instances
)

agent = Agent(
    name="MemoryAgent",
    model="gemini-2.5-flash",
    instruction=(
        "Use the search_memory tool to recall context about the user. "
        "Use store_memory to remember new facts."
    ),
    tools=tools,
)
```

The factory binds `user_id` and `customer_id` into the closures it returns. The model only ever sees `query` and `content`, never the user identity. This prevents prompt-injection attempts from spoofing scope.

***

## Core concepts

### create\_synap\_tools

`create_synap_tools` returns a two-element list: `[search_memory, store_memory]`. Both are ADK `FunctionTool` instances and can be passed directly to `Agent(tools=...)`:

```python theme={null}
from synap_google_adk import create_synap_tools

tools = create_synap_tools(
    sdk=sdk,
    user_id="alice",
    customer_id="acme",
)
# tools[0] = search_memory
# tools[1] = store_memory
```

### search\_memory

Tool signature exposed to the model:

```text theme={null}
search_memory(query: str) -> str
```

Runs an accurate-mode fetch scoped to the bound user and customer, and returns the formatted context as one string. When nothing matches it returns `"No relevant memories found."`.

**Search failures surface**: an SDK error is logged and raised as `SynapIntegrationError`, so a failed search is never mistaken for an empty memory.

### store\_memory

Tool signature exposed to the model:

```text theme={null}
store_memory(content: str) -> str
```

Returns `"Memory stored (ingestion_id: ...)"` on success. **Store failures surface explicitly**: the tool raises `SynapIntegrationError` so the agent (and you) know if persistence failed.

***

## Complete example: per-user memory agent

In a multi-user service, build a fresh tool set per request. Each agent run gets a scope-bound tool list, so two concurrent users cannot see each other's memories:

```python theme={null}
from google.adk.agents import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
from synap_google_adk import create_synap_tools

APP_NAME = "memory-agent"
session_service = InMemorySessionService()


def build_agent_for_user(sdk, user_id: str, customer_id: str | None = None) -> Agent:
    tools = create_synap_tools(sdk=sdk, user_id=user_id, customer_id=customer_id)

    return Agent(
        name="MemoryAgent",
        model="gemini-2.5-flash",
        instruction=(
            "You are a personal assistant with long-term memory.\n"
            "1. Always call search_memory FIRST for any question about the user.\n"
            "2. When the user shares a fact, preference, or decision, "
            "call store_memory before responding.\n"
            "3. If search_memory returns nothing, say so honestly."
        ),
        tools=tools,
    )


async def handle_request(sdk, user_id: str, message: str) -> str:
    agent = build_agent_for_user(sdk, user_id=user_id, customer_id="acme")

    # ADK's Runner needs an app name and a session service; run_async takes
    # keyword args and a structured Content message, and yields events.
    # It is not `run_async(message)`. See ADK's runtime docs for the full loop.
    runner = Runner(app_name=APP_NAME, agent=agent, session_service=session_service)
    session = await session_service.create_session(app_name=APP_NAME, user_id=user_id)
    content = types.Content(role="user", parts=[types.Part.from_text(text=message)])

    async for event in runner.run_async(
        user_id=user_id, session_id=session.id, new_message=content
    ):
        # A failed model call (an unknown or retired model, quota, auth) arrives as a
        # final event with error_code set and no content, so check for it first.
        if event.error_code:
            raise RuntimeError(f"ADK run failed: {event.error_code}: {event.error_message}")
        if event.is_final_response() and event.content and event.content.parts:
            return event.content.parts[0].text or ""
    return ""


# Usage
await handle_request(sdk, user_id="alice", message="I just upgraded to the Pro plan.")
# Later:
reply = await handle_request(sdk, user_id="alice", message="What plan am I on?")
# → "You're on the Pro plan."
```

Three things to notice in this pattern:

1. **Per-request agent construction is the safety pattern.** Each request gets its own scope-bound tool list, so no shared state can leak between users.
2. **The instruction is the policy.** Telling the model to always call `search_memory` first is what produces recall behavior; the tools are just plumbing.
3. **Failures are never silent.** Both tools raise `SynapIntegrationError` when the SDK call fails, so a failed store cannot pass for a stored one and a failed search cannot pass for an empty memory.

***

## Advanced patterns

### Multi-tenant scoping

`create_synap_tools` accepts the standard scoping triple: `user_id` (required), `customer_id` (B2B instances only), optional `conversation_id`. `customer_id` is required on B2B Synap instances and **not accepted** on B2C (single-tenant) ones, where a call carrying it is rejected with HTTP 400. See [Memory Scopes](https://docs.maximem.ai/concepts/memory-scopes.md).

```python theme={null}
# User-scoped only
tools = create_synap_tools(sdk=sdk, user_id="alice")

# Organization-scoped (user sees org-shared memories too)
tools = create_synap_tools(sdk=sdk, user_id="alice", customer_id="acme-corp")
```

### Report the run and use Synap's compaction

`create_synap_callbacks` returns the keyword arguments an agent takes for its callbacks. Splat the dict into the agent next to the tools:

```python theme={null}
import uuid
from google.adk.agents import Agent
from synap_google_adk import create_synap_callbacks, create_synap_tools

# A UUID, reused for every turn of this conversation.
conversation_id = str(uuid.uuid4())

agent = Agent(
    name="MemoryAgent",
    model="gemini-2.5-flash",
    instruction="You are a personal assistant with long-term memory.",
    tools=create_synap_tools(sdk=sdk, user_id="alice", customer_id="acme"),
    **create_synap_callbacks(
        sdk,
        user_id="alice",
        customer_id="acme",
        conversation_id=conversation_id,
    ),
)
```

The dict holds four callbacks: `before_model_callback`, `after_model_callback`, `before_tool_callback` and `after_tool_callback`.

* **Turns.** The user's message is written once per invocation, and the model's final reply is written when it arrives. A reply that calls a tool, a partial streamed chunk and a reasoning part are not turns, so they are not written.
* **Tool calls and results.** Each tool call and its result are reported to Synap, so anticipation sees what the agent did, not only what it said. Pass `report_tool_results=False` to keep results out; a tool result is usually your own customer's data, and it leaves your process.
* **Compaction.** Once Synap has compacted the conversation, every turn before the current one is replaced by Synap's compaction block, placed in the system instruction, followed by the turns after the compaction. The current turn is untouched. Before the first compaction, or if Synap cannot answer, ADK's own contents are sent as they are. ADK's own compaction stays installed as the fallback.

Pass `conversation_id`, and make it a UUID: Synap rejects any other value when it reads the compacted conversation. The replacement only happens for a known conversation, and the REST fallback cannot write a turn without one.

The first callback opens the real-time stream for you, so you do not call `listen()`. If the stream cannot open, each turn is written over REST instead, never both; tool calls and results exist only on the stream and are dropped in that case. Set `SYNAP_AUTO_LISTEN=false` to stay on REST, or open the stream yourself and the integration uses it as is. See [gRPC vs REST](https://docs.maximem.ai/concepts/grpc-vs-rest.md#framework-integrations).

`create_synap_callbacks` takes the `before_model_callback` slot. If you have your own, pass a list after the splat:

```python theme={null}
callbacks = create_synap_callbacks(sdk, user_id="alice", conversation_id=conversation_id)
callbacks["before_model_callback"] = [callbacks["before_model_callback"], my_before_model]

agent = Agent(name="MemoryAgent", model="gemini-2.5-flash", **callbacks)
```

If a run does not use the callbacks, `report_user_turn(sdk, content, conversation_id=..., user_id=...)` writes the user's turn yourself. When you use both, the turn is written once.

### Add the compaction to the instruction

`synap_st_instruction` is the lighter option when you only want the compaction in the prompt. It returns an async callable that ADK runs before each model call:

```python theme={null}
import uuid
from google.adk.agents import Agent
from synap_google_adk import synap_st_instruction

conversation_id = str(uuid.uuid4())

agent = Agent(
    name="support",
    model="gemini-2.5-flash",
    instruction=synap_st_instruction(
        sdk,
        conversation_id=conversation_id,
        instruction="You are a polite support agent.",
    ),
)
```

It prepends Synap's compaction of the conversation, inside `<synap_short_term_context>` tags, to your instruction. Before the first compaction it adds nothing, because ADK already sends the recent turns. `conversation_id` is required and must be a UUID.

### Multi-agent setups

Each `Agent` can carry its own tool list. Give a "memory-keeper" agent both tools and a "consumer" agent only `search_memory` to keep the write surface small:

```python theme={null}
[search, _store] = create_synap_tools(sdk=sdk, user_id="alice", customer_id="acme")
reader_only = Agent(name="Reader", model="gemini-2.5-flash", tools=[search])
```

### Failure semantics

The two parts of the integration fail differently:

* **The tools raise.** `search_memory` and `store_memory` log the error and raise `SynapIntegrationError`, with the original exception as `__cause__`.
* **The callbacks never raise.** They run inside ADK's own loop, so every failure is logged and swallowed, and each callback returns `None` so ADK never treats it as an override of the model or tool result.
* **`synap_st_instruction` falls back by default.** On an SDK error it returns your static instruction unchanged. Pass `on_error="raise"` to get `SynapIntegrationError` instead.

Silent write failures would let the memory drift away from reality, so the tools make them visible. Telemetry must not end a user-facing run, so the callbacks stay quiet.

***

## Going further

* [Patterns overview](https://docs.maximem.ai/patterns/overview.md): reusable memory patterns across frameworks.
* [Cookbook overview](https://docs.maximem.ai/cookbook/overview.md): end-to-end worked examples.

***

## Next steps

> [card] [Haystack](https://docs.maximem.ai/integrations/haystack.md)
>
> Pipeline components for Haystack.

> [card] [Agno](https://docs.maximem.ai/integrations/agno.md)
>
> `InMemoryDb` replacement for Agno agents.

> [card] [Context Fetch](https://docs.maximem.ai/sdk/context-fetch.md)
>
> The retrieval API behind `search_memory`: modes, scopes, and response shapes.

> [card] [Memory Scopes](https://docs.maximem.ai/concepts/memory-scopes.md)
>
> How `user_id` and `customer_id` interact across reads and writes.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.