> ## 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.

# LiveKit Agents

> Memory preloading, turn and tool-call reporting, compacted history and on-demand search for LiveKit voice agents.

Give a LiveKit voice agent long-term memory across calls. Synap preloads the user's history into the `ChatContext` before the first turn, reports every committed turn and tool call during the session, sends the model Synap's compaction instead of a long call's earlier turns, and exposes search/store function tools the LLM can call mid-conversation.

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

## Overview

This guide shows how to add Synap to a LiveKit Agents application to build voice agents that:

* Start every call already aware of the user's history, no warm-up turn needed
* Report every committed turn and tool call back to Synap so memory grows with each call
* Send the model Synap's compacted history instead of every earlier turn of a long call
* Search and store memories mid-conversation when the model decides it's relevant

The Synap LiveKit Agents integration ships lifecycle helpers and two function tools.

| Export | Role | Purpose |
| - | - | - |
| `preload_synap_context` | Lifecycle (start) | Injects long-term memory into a `ChatContext` before the session begins |
| `attach_synap_recording` | Lifecycle (during) | Reports every committed turn, tool call and tool result to Synap, and installs the compacted-history replacement |
| `install_synap_history` | Lifecycle (during) | Wraps an agent's `llm_node` so the model is sent Synap's compaction; `attach_synap_recording` calls it for you |
| `splice_synap_history` | Helper | Replaces the earlier turns in a `ChatContext` with Synap's compaction, in place |
| `preload_synap_st` | Lifecycle (start) | Adds Synap's short-term context of a conversation to a `ChatContext` |
| `refresh_synap_st` | Lifecycle (per turn) | Keeps that short-term context fresh from a per-turn hook |
| `synap_search_tool` | Function tool | LLM-callable memory search |
| `synap_store_tool` | Function tool | LLM-callable memory storage |

## Setup

Install the package alongside LiveKit Agents. It also installs `maximem-synap` (0.5.3 or later) and `maximem-synap-integrations-common` (0.2.3 or later), and needs `livekit-agents` 1.0 or later:

```bash pip theme={null}
pip install maximem-synap-livekit-agents livekit-agents
```

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

> [!NOTE]
>
> The pip package is `maximem-synap-livekit-agents`, but the import drops the `maximem-` prefix and uses underscores: `from synap_livekit_agents 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
OPENAI_API_KEY=your-openai-api-key
LIVEKIT_API_KEY=your-livekit-key
LIVEKIT_API_SECRET=your-livekit-secret
```

Initialize the SDK once at the agent worker's 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 preloads memory before the session starts and attaches recording during it. The agent now opens with knowledge of the user's history and grows its memory with every committed turn:

```python theme={null}
# pip install maximem-synap-livekit-agents livekit-agents
import uuid
from maximem_synap import MaximemSynapSDK
from livekit.agents import Agent, AgentSession, JobContext
from livekit.agents.llm import ChatContext
from synap_livekit_agents import preload_synap_context, attach_synap_recording

sdk = MaximemSynapSDK()
await sdk.initialize()


async def entrypoint(ctx: JobContext):
    await ctx.connect()

    chat_ctx = ChatContext()
    await preload_synap_context(
        chat_ctx=chat_ctx,
        sdk=sdk,
        user_id="alice",
        customer_id="acme",   # optional, required for B2B instances
        max_results=8,
    )

    agent = Agent(
        instructions="You are a voice assistant with long-term memory.",
        chat_ctx=chat_ctx,
    )

    session = AgentSession(...)

    conversation_id = attach_synap_recording(
        session=session,
        sdk=sdk,
        user_id="alice",
        customer_id="acme",
        conversation_id=str(uuid.uuid4()),   # a UUID, so compaction can apply
    )

    await session.start(agent=agent, room=ctx.room)
```

**Preload failures degrade gracefully.** The session starts with empty context and logs an error. **Recording failures are also non-fatal.** A failed report is logged rather than killing the call.

For mid-conversation search and store (the model calls them when needed), add the function tools (see below).

***

## Core concepts

### preload\_synap\_context

Loads the user's long-term memories as system messages in the `ChatContext` *before* the session starts. This gives the LLM awareness of the user's history from the very first turn, with no tool call needed.

```python theme={null}
await preload_synap_context(
    chat_ctx=chat_ctx,
    sdk=sdk,
    user_id="alice",
    customer_id="acme",
    max_results=8,
    mode="fast",           # "fast" or "accurate"; the default is "accurate"
)
```

Voice latency is tight, so pass `mode="fast"` when the opening turn cannot wait; the default is `"accurate"` and `max_results` defaults to 20. **Failures degrade gracefully.** The session starts with empty context rather than raising.

### attach\_synap\_recording

Subscribes to the `AgentSession`'s events and reports the whole call to Synap. Returns the `conversation_id` for the session:

```python theme={null}
import uuid

conversation_id = attach_synap_recording(
    session=session,
    sdk=sdk,
    user_id="alice",
    customer_id="acme",
    conversation_id=str(uuid.uuid4()),   # recommended; see below
)
```

It reports:

* **Turns.** Each committed user and assistant message. An assistant item that only carries a tool call is not a turn.
* **Tool calls and results.** The call is reported the moment the tool is dispatched, which is the caller's dead air, and the result when the tool finishes.
* **The end of the call.** When the session closes, the conversation's Synap session is closed too, so it is not left to expire.

You do not call `listen()`. The first report opens the real-time stream, and the turns go out on it. 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).

Reporting happens out of band: it never blocks the audio path, and a failed report is logged and swallowed. Call `attach_synap_recording` before `session.start(...)`.

Left out, `conversation_id` is a new random UUID for each session (0.2.4 or later; earlier versions generated an id that was not a UUID, which Synap rejected for reads and REST writes). Pass your own UUID to continue one conversation across sessions.

### Compacted history

A LiveKit `ChatContext` only grows, so a long call re-sends every turn on every LLM request. `attach_synap_recording` installs `install_synap_history` on the session's agent, which wraps the agent's `llm_node`. Once Synap has compacted the conversation, each LLM request is sent Synap's compaction block (in `<synap_conversation_history>` tags) and the turns after it, in place of every turn before the current one. The current turn, including tool calls and their outputs, is untouched. The replacement changes what the model reads for that request and not the history the agent keeps.

Before the first compaction, or when Synap cannot answer, the history is sent as LiveKit built it. A voice turn cannot wait on a slow read: if Synap takes longer than 1.5 seconds, that request goes through unchanged and the read is not tried again for 30 seconds. The wrapper follows the agent through a handoff, because the session's current agent is wrapped on each event.

> [!NOTE]
>
> This does not apply to a session that uses a realtime model. There the provider holds the history, and the agent's `llm_node` is not called.

To wrap an agent yourself, call `install_synap_history(agent, sdk, conversation_id=...)`. To replace the turns in a `ChatContext` directly, `await splice_synap_history(chat_ctx, sdk, conversation_id=...)` does it in place and returns whether it changed anything.

### Short-term context

`preload_synap_st` and `refresh_synap_st` add Synap's short-term context of a conversation to the `ChatContext`: `preload_synap_st` once before `session.start(...)`, and `refresh_synap_st` from a per-turn hook such as `Agent.on_user_turn_completed`, where it replaces the message it added last time.

```python theme={null}
from synap_livekit_agents import preload_synap_st, refresh_synap_st

await preload_synap_st(chat_ctx, sdk, conversation_id=conversation_id)
```

Once Synap has compacted the conversation, both replace the context's earlier turns with the compaction and the turns after it. Before that, the block they add leaves out the turns the context already holds, so nothing is sent twice. `conversation_id` is required and must be a UUID. On an SDK error they leave the context untouched; pass `on_error="raise"` to get `SynapIntegrationError`.

### Function tools

For mid-conversation lookups or saves, expose the search and store tools to the LLM. The `synap_search_tool` / `synap_store_tool` factories return LiveKit `@function_tool`s, so the LiveKit LLM bridge picks them up as function calls automatically:

```python theme={null}
from synap_livekit_agents import synap_search_tool, synap_store_tool

agent = Agent(
    instructions="You are a voice assistant with long-term memory.",
    chat_ctx=chat_ctx,
    tools=[
        synap_search_tool(sdk=sdk, user_id="alice", max_results=5),
        synap_store_tool(sdk=sdk, user_id="alice"),
    ],
)
```

The scoping is bound at tool construction: the model only ever sees the `query` parameter of the search tool and the `content` and `category` parameters of the store tool, never `user_id`. The search tool defaults to `mode="accurate"` and `max_results=10`.

***

## Complete example: voice agent with full memory loop

The pattern below assembles the main exports into a single entrypoint. The agent preloads context, reports turns and tool calls, and can search or store memories mid-call:

```python theme={null}
import uuid
from livekit.agents import Agent, AgentSession, JobContext, WorkerOptions, cli
from livekit.agents.llm import ChatContext
from synap_livekit_agents import (
    preload_synap_context,
    attach_synap_recording,
    synap_search_tool,
    synap_store_tool,
)


async def entrypoint(ctx: JobContext):
    await ctx.connect()

    # Identify the caller (e.g. from a JWT claim on ctx.room)
    user_id = ctx.room.metadata.get("user_id", "anonymous")
    customer_id = ctx.room.metadata.get("customer_id")

    # 1. Preload long-term memory before the session begins
    chat_ctx = ChatContext()
    await preload_synap_context(
        chat_ctx=chat_ctx,
        sdk=sdk,
        user_id=user_id,
        customer_id=customer_id,
        max_results=8,
    )

    # 2. Build the agent with on-demand search/store tools
    agent = Agent(
        instructions=(
            "You are a voice assistant with long-term memory. "
            "Use synap_search for any question about the caller's history. "
            "Use synap_store when the caller shares a new fact or decision."
        ),
        chat_ctx=chat_ctx,
        tools=[
            synap_search_tool(sdk=sdk, user_id=user_id, customer_id=customer_id, max_results=5),
            synap_store_tool(sdk=sdk, user_id=user_id, customer_id=customer_id),
        ],
    )

    # 3. Attach turn recording so every committed turn enters Synap
    session = AgentSession(...)
    attach_synap_recording(
        session=session,
        sdk=sdk,
        user_id=user_id,
        customer_id=customer_id,
        conversation_id=str(uuid.uuid4()),
    )

    await session.start(agent=agent, room=ctx.room)


if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
```

Three things to notice in this pattern:

1. **Preload + record + tools form the loop.** Preload reads memory in, record writes turns and tool calls out, and tools let the model do explicit lookups in between.
2. **Scope is per-call.** `user_id` and `customer_id` are pulled from room metadata, so each call has its own memory scope without any global state.
3. **Failure modes are voice-friendly.** Memory operations never block the audio path; they degrade silently so the caller hears no glitch.

***

## Advanced patterns

### Multi-tenant scoping

The helpers and tools take `user_id` (required) and `customer_id` (B2B instances only); `attach_synap_recording` also takes an optional `conversation_id`, and the short-term helpers require one. `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}
await preload_synap_context(
    chat_ctx=chat_ctx,
    sdk=sdk,
    user_id="alice",
    customer_id="acme",
)
```

For multi-tenant call centers, pull `user_id` / `customer_id` from room metadata or JWT claims at entrypoint time, never hardcode them.

### Choosing preload vs. tools

* **Preload only:** the LLM sees the most relevant memories from turn one. Best when memory is small and you want zero per-turn latency overhead.
* **Tools only:** the LLM searches on demand. Best when memory is large and only a few queries need recall.
* **Both:** production setups where the opening greeting can reference long-term context AND the model can dig deeper mid-call.

### Failure semantics

The integration follows the Synap-wide contract, adapted for voice latency:

* **`preload_synap_context` degrades gracefully:** empty context on failure, error logged.
* **`attach_synap_recording` never raises into the call:** a turn goes on the stream, or over REST when the stream cannot carry it; a failed report is logged and swallowed.
* **The compacted-history replacement leaves the history alone** whenever Synap has no compaction, is slow or errors.
* **`synap_search_tool` degrades gracefully:** on failure it logs and returns the text `"Synap memory is temporarily unavailable."`, and when nothing matches it returns `"No relevant long-term memory found for this query."`.
* **`synap_store_tool` surfaces failures:** raises `SynapIntegrationError` so the model (and you) know if persistence failed.

This is by design: a voice call should never break because of a transient memory glitch, but explicit write failures must be visible.

***

## Going further

* [Voice agent pattern](https://docs.maximem.ai/patterns/voice-agent-livekit.md): the reference architecture for memory-backed voice agents.
* [Voice concierge cookbook](https://docs.maximem.ai/cookbook/voice-concierge.md): an end-to-end worked voice example.

***

## Next steps

> [card] [Pipecat](https://docs.maximem.ai/integrations/pipecat.md)
>
> Frame processors for Pipecat voice pipelines.

> [card] [Claude Agent SDK](https://docs.maximem.ai/integrations/claude-agent.md)
>
> Hooks and MCP server for the Claude Agent SDK.

> [card] [Context Fetch](https://docs.maximem.ai/sdk/context-fetch.md)
>
> The retrieval API behind `preload_synap_context` and `synap_search_tool`.

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


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