---
title: "MongoDB Vector Search for voice agents: build persistent memory in Python"
date: "2026-06-03"
authors: "Jesse Hall"
tags: "guide"
---

# MongoDB Vector Search for voice agents: build persistent memory in Python

A voice agent that forgets you between calls starts every conversation from zero. It can't greet you by name, recall what you asked last time, or pick up where you left off. Personalization, retrieval-augmented generation over a knowledge base, and memory that carries across sessions all need somewhere durable to live. [MongoDB Atlas](https://www.mongodb.com/docs/vector-search/) gives you one home for all three. Flexible schemas hold profiles and session reports, an aggregation pipeline does the heavy lifting, and [`$vectorSearch`](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage/) runs next to the rest of your data.

This guide walks through five integration patterns for wiring Atlas into a [LiveKit voice agent](https://docs.livekit.io/agents/logic/external-data/). Every snippet is taken from a working [starter kit](https://github.com/livekit-examples/mongodb-hacker-starter) you can clone.

## Why persistent state matters in voice

Voice runs on a tighter latency budget than chat. A two-second pause that reads as "thinking" in a chat window reads as "broken" out loud, so anything you ask the agent to remember or look up has to fit inside one user-stops-speaking to agent-starts-speaking round trip. A bloated system prompt loses to a focused one every time.

Three jobs in particular benefit from moving out of the prompt and into a database.

- **Personalization.** The agent should know who is on the call before it says hello.
- **Knowledge.** The agent should answer questions about your product or domain without memorizing everything.
- **Memory.** The agent should remember what was said last time, last week, last quarter.

Atlas fits all of this because the document model maps cleanly to profiles and transcripts, and vector search lives right beside that data.

## The five integration points

LiveKit Agents exposes a small set of [hooks and lifecycle callbacks](https://docs.livekit.io/agents/logic/nodes/) that map one-to-one onto database operations. Mix and match.

| Pattern                   | LiveKit hook                         | MongoDB feature                         |
| ------------------------- | ------------------------------------ | --------------------------------------- |
| 1. RAG as a function tool | `@function_tool`                     | `$vectorSearch` aggregation             |
| 2. Agentic memory         | `@function_tool`                     | `$vectorSearch` with filter fields      |
| 3. Identify + pre-load    | Agent dispatch metadata + entrypoint | `find_one_and_update` upsert on `users` |
| 4. Function-tool CRUD     | `@function_tool`                     | Any PyMongo async op                    |
| 5. Session persistence    | `on_session_end` callback            | `insert_one` on `sessions`              |

The starter puts all five in a single `MongoAgent` class.

## Setting up the project

Both halves are bootstrapped from official LiveKit templates.

```bash
lk agent init agent --template agent-starter-python
lk agent init frontend --template agent-starter-react
```

The agent template adds `pymongo>=4.13` for the async client and `voyageai` for embeddings. No provider plugins for STT, LLM, or TTS are needed because LiveKit Inference handles those through your LiveKit credentials.

Five environment variables, three LiveKit credentials, the MongoDB connection string, and a Voyage API key.

```text
LIVEKIT_URL=
LIVEKIT_API_KEY=
LIVEKIT_API_SECRET=
MONGODB_URI=
VOYAGE_API_KEY=
```

## The voice pipeline

Before we get to MongoDB, here is the agent's pipeline. Everything is configured through `inference.STT`, `inference.LLM`, and `inference.TTS`, so you swap providers by changing a string.

```python
session = AgentSession(
    stt=inference.STT(model="deepgram/nova-3", language="multi"),
    llm=inference.LLM(model="openai/gpt-5.3-chat-latest"),
    tts=inference.TTS(
        model="cartesia/sonic-3", voice="9626c31c-bec5-4cca-baa8-f8ba9e84c8bc"
    ),
    vad=ctx.proc.userdata["vad"],
    turn_handling=TurnHandlingOptions(
        turn_detection=MultilingualModel(),
        preemptive_generation={"enabled": True},
    ),
)
```

None of that is MongoDB-specific, but it sets the timing budget the database work has to live within. The agent class is registered with the [`AgentServer`](https://docs.livekit.io/agents/logic/sessions/) under a name the frontend dispatches to, with an `on_session_end` callback that Pattern 5 covers.

## Pattern 1: RAG as a function tool

The LLM knows when it needs facts. Small talk, confirmations, and greetings don't need a knowledge-base lookup, and running a vector search on every turn burns embedding calls you didn't need. A function tool lets the model decide.

The tradeoff is latency. A tool call adds a hop on top of the vector search, and in voice that hop is dead air. To hide it, borrow a tiny pattern from LiveKit's user feedback guide. Schedule a verbal status update on a short delay, then cancel it if the search finishes first.

The vector search itself lives in a small helper.

```python
async def _vector_search_knowledge(
    db: AsyncDatabase, query: str, limit: int = 3
) -> list[dict]:
    """Run the knowledge vector search and return {title, content} docs."""
    query_embedding = await embed_text(query, input_type="query")
    pipeline = [
        {
            "$vectorSearch": {
                "index": "knowledge_embedding_index",
                "path": "embedding",
                "queryVector": query_embedding,
                "numCandidates": 100,
                "limit": limit,
            }
        },
        {"$project": {"title": 1, "content": 1, "_id": 0}},
    ]
    cursor = await db.knowledge.aggregate(pipeline)
    return await cursor.to_list(length=limit)
```

`$vectorSearch` takes a pre-computed query vector, so we embed the query through Voyage first. The [PyMongo async API](https://www.mongodb.com/docs/languages/python/pymongo-driver/current/reference/migration/) treats `aggregate()` as a coroutine that returns an `AsyncCursor`, so the helper awaits both `db.knowledge.aggregate(pipeline)` and `cursor.to_list(length=limit)`.

The tool itself is dominated by the status-update pattern, not the database call.

```python
@function_tool()
async def search_knowledge(
    self, context: RunContext, query: str
) -> str:
    """Search the shared knowledge base for facts the user asks about."""

    async def _speak_status_update(delay: float = 0.5) -> None:
        await asyncio.sleep(delay)
        await context.session.generate_reply(
            instructions=(
                f"You are searching the knowledge base for '{query}' "
                "but it is taking a moment. Give the user a brief, "
                "one-sentence update that you are looking it up."
            )
        )

    status_task = asyncio.create_task(_speak_status_update(0.5))
    try:
        db = await get_db()
        results = await _vector_search_knowledge(db, query, limit=3)
    finally:
        status_task.cancel()
    return json.dumps({"results": results})
```

The timer fires only if the search takes longer than 500ms. On a fast path the task is cancelled in the `finally` block before `asyncio.sleep` resolves, so the user never hears a filler phrase. On a slow path the model says something like "just a moment, looking that up" and then answers normally once `search_knowledge` returns.

The vector index is created once on Atlas with `SearchIndexModel`.

```python
SearchIndexModel(
    definition={
        "fields": [
            {
                "type": "vector",
                "path": "embedding",
                "numDimensions": EMBEDDING_DIMENSIONS,
                "similarity": "cosine",
            },
            {"type": "filter", "path": "user_id"},
            {"type": "filter", "path": "tenant_id"},
        ]
    },
    name=name,
    type="vectorSearch",
)
```

Filter fields matter. `$vectorSearch` lets you pre-filter candidates with a `filter` clause, but only on fields declared in the index. Pattern 2 uses those filters to keep one user's memories out of another user's recall.

## Pattern 2: agentic memory as tools

RAG handles knowledge that exists ahead of time. Memory handles knowledge the agent picks up during conversation. The pattern that works best for voice is to expose memory as tools and let the LLM decide what to persist. Five tools cover most cases. `remember_detail(memory_type, content)` stores or replaces a slot, `recall_detail(memory_type)` returns it, `forget_detail(memory_type)` deletes it, `search_memories(query)` runs hybrid vector and text search, and `list_user_memories()` returns every slot for this user.

Identity-like fields (name, email, preferred language, timezone) belong on the user's profile document in `users`, not in free-form memory slots, so Pattern 3 can load them at session start without iterating memories. A sixth tool, `update_profile(field, value)`, writes an allow-listed set of profile fields directly to `users`.

Memory is modeled as **slots**. Each `(user_id, tenant_id, memory_type)` triple holds at most one value, so writing the same label twice replaces the previous entry. That matches how voice agents actually use memory (the user's *current* favorite color, not a log of every color).

```python
async def remember(
    db: AsyncDatabase,
    user_id: str,
    tenant_id: str,
    memory_type: str,
    content: str,
) -> str:
    embedding = await embed_text(
        f"{memory_type}: {content}", input_type="document"
    )
    now = _now()
    await db.memories.update_one(
        {**_scope(user_id, tenant_id), "memory_type": memory_type},
        {
            "$set": {
                "content": content,
                "embedding": embedding,
                "updated_at": now,
            },
            "$setOnInsert": {"created_at": now},
        },
        upsert=True,
    )
    return f"Remembered ({memory_type}): {content}"
```

The embedding covers `"{memory_type}: {content}"` rather than `content` alone, so a short slot like `{memory_type: "name", content: "Jesse"}` still encodes that "Jesse" is a name. A unique compound index on `(user_id, tenant_id, memory_type)` enforces the one-value-per-slot rule under concurrent writes.

### Hybrid retrieval with `$rankFusion`

Exact-label recall only works when the LLM knows which label it used. Ask "what's my favorite color?" and the fact might be stored as `color_preference`, `favorite_color`, or `user_color`. The fix is hybrid retrieval. [`$rankFusion`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/rankFusion/) (MongoDB 8.0+) runs `$vectorSearch` and `$search` text pipelines in parallel, then merges them with Reciprocal Rank Fusion.

```python
pipeline = [
    {
        "$rankFusion": {
            "input": {
                "pipelines": {
                    "vectorSearch": [
                        {
                            "$vectorSearch": {
                                "index": "memories_embedding_index",
                                "path": "embedding",
                                "queryVector": query_embedding,
                                "numCandidates": 100,
                                "limit": 30,
                                "filter": scope,
                            }
                        }
                    ],
                    "textSearch": [
                        {
                            "$search": {
                                "index": "memories_text_index",
                                "compound": {
                                    "should": [
                                        {"text": {"query": query, "path": "memory_type", "fuzzy": {}}},
                                        {"text": {"query": query, "path": "content", "fuzzy": {}}},
                                    ]
                                },
                            }
                        },
                        {"$match": scope},
                        {"$limit": 30},
                    ],
                }
            },
            "combination": {"weights": {"vectorSearch": 0.7, "textSearch": 0.3}},
        }
    },
    {"$limit": limit},
    {"$project": {"_id": 0, "memory_type": 1, "content": 1}},
]
```

The 0.7 / 0.3 weighting biases toward semantic match while keeping lexical precision for direct hits. Results come back as `{memory_type, content}` pairs so the LLM can follow up with `recall_detail` or `forget_detail`. Both indexes are declared in `db/indexes.py`. `$rankFusion` is an 8.0 stage, so the starter needs MongoDB 8.0+ (M10+ runs 8.0 by default).

## Pattern 3: identify the user, then pre-load their context

Before we can load a profile we need a stable id, and it has to reach the agent before it speaks.

LiveKit gives you three places for that data. [Job metadata](https://docs.livekit.io/agents/server/job/) is the right one for session-start identity because `ctx.job.metadata` is available before `ctx.connect()`, and the [external data docs](https://docs.livekit.io/agents/logic/external-data/) say to do any network calls in the entrypoint before `ctx.connect()` so the frontend doesn't render an agent participant that isn't listening yet. [Participant attributes](https://docs.livekit.io/transport/data/state/participant-attributes/) don't resolve until after connect, so reach for them when identity changes mid-call.

### Server: one httpOnly cookie

The token route owns identity. On first visit it reads `lk_mongo_user_cookie`, mints a UUID if nothing is there, stamps the id onto the agent dispatch entry, and sends the cookie back.

```typescript
// app/api/token/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { AccessToken, type AccessTokenOptions, type VideoGrant } from 'livekit-server-sdk';
import { RoomAgentDispatch, RoomConfiguration } from '@livekit/protocol';

const COOKIE_NAME = 'lk_mongo_user_cookie';
const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
const AGENT_NAME = process.env.AGENT_NAME;

export async function POST(req: NextRequest) {
  let userId = req.cookies.get(COOKIE_NAME)?.value;
  const isNewCookie = !userId;
  if (!userId) userId = crypto.randomUUID();

  const metadata = JSON.stringify({ user_id: userId, tenant_id: 'default' });
  const roomConfig = AGENT_NAME
    ? new RoomConfiguration({
        agents: [new RoomAgentDispatch({ agentName: AGENT_NAME, metadata })],
      })
    : new RoomConfiguration();

  const participantToken = await createParticipantToken(
    { identity: `voice_assistant_user_${Math.floor(Math.random() * 10_000)}`, name: 'user' },
    `voice_assistant_room_${Math.floor(Math.random() * 10_000)}`,
    roomConfig,
  );

  const res = NextResponse.json({ serverUrl: LIVEKIT_URL, roomName, participantName: 'user', participantToken });
  if (isNewCookie) {
    res.cookies.set({
      name: COOKIE_NAME,
      value: userId,
      httpOnly: true,
      sameSite: 'lax',
      secure: process.env.NODE_ENV === 'production',
      path: '/',
      maxAge: COOKIE_MAX_AGE,
    });
  }
  return res;
}
```

The cookie is `httpOnly`, so JavaScript on the page can't read or forge it. Same-origin `fetch` [attaches cookies by default](https://developer.mozilla.org/en-US/docs/Web/API/fetch#credentials), so `TokenSource.endpoint('/api/token')` ships the cookie on every token request without extra config. Any `room_config` the client sends in the body is ignored. The server builds its own `RoomConfiguration` and stamps the verified id onto `agents[0].metadata` via `RoomAgentDispatch`, matching the [custom-auth Node.js example](https://docs.livekit.io/frontends/build/authentication/custom/).

### Read metadata on the agent

Parse `ctx.job.metadata` before `ctx.connect()` so `preload_user` runs in parallel with the connection handshake.

```python
@server.rtc_session(agent_name="my-agent", on_session_end=on_session_end)
async def my_agent(ctx: JobContext) -> None:
    meta: dict[str, str] = {}
    if ctx.job.metadata:
        try:
            meta = json.loads(ctx.job.metadata)
        except json.JSONDecodeError:
            logger.warning("ctx.job.metadata was not valid JSON; using defaults")

    user_id = meta.get("user_id", DEFAULT_USER_ID)
    tenant_id = meta.get("tenant_id", DEFAULT_TENANT_ID)
    ctx.proc.userdata["user_id"] = user_id
    ctx.proc.userdata["tenant_id"] = tenant_id

    initial_ctx = await preload_user(user_id, tenant_id)
    # ... build session, start it, connect
```

`DEFAULT_USER_ID` is the fallback for console mode (`lk agent console`), where there is no frontend. Stashing the id on `ctx.proc.userdata` gives `on_session_end` a place to find it on hangup without threading it through as a parameter.

### Pre-load the profile

`preload_user` does two things. It upserts the `users` row so every visitor has a stable profile document, and it reads back the document plus all memory slots for this `(user_id, tenant_id)` scope. Both land in the `ChatContext` as assistant messages before the LLM speaks.

```python
async def preload_user(user_id: str, tenant_id: str) -> ChatContext:
    """Pattern 3: upsert the user row, then seed the chat context."""
    db = await get_db()
    now = _now()
    user = await db.users.find_one_and_update(
        {"user_id": user_id},
        {
            "$set": {"last_seen_at": now},
            "$setOnInsert": {"user_id": user_id, "created_at": now},
        },
        upsert=True,
        return_document=ReturnDocument.AFTER,
    )

    chat_ctx = ChatContext()
    name = user.get("name")
    email = user.get("email")
    prefs = user.get("preferences", {})
    if name or email or prefs:
        chat_ctx.add_message(
            role="assistant",
            content=(
                f"User profile: name={name or 'unknown'}, "
                f"email={email or 'unknown'}, preferences={prefs}."
            ),
        )
    else:
        chat_ctx.add_message(
            role="assistant",
            content=(
                f"No stored profile fields yet for user_id {user_id}. "
                "Greet them as a new user."
            ),
        )

    memories = await list_memories(db, user_id, tenant_id)
    if memories:
        lines = "\n".join(
            f"- {m['memory_type']}: {m['content']}" for m in memories
        )
        chat_ctx.add_message(
            role="assistant",
            content=f"Remembered facts from prior sessions:\n{lines}",
        )
    return chat_ctx
```

`find_one_and_update` with `upsert=True` creates the document if missing, stamps `last_seen_at`, and returns the post-write state in one round trip. The memory pass closes the loop with Pattern 2. A slot the agent wrote last Tuesday is in context on Wednesday without any extra tool calls.

The agent's `on_enter` calls `self.session.generate_reply` with an instruction to greet by name if the profile or remembered facts contain one. All of this has to finish before the agent speaks, with on the order of a few hundred milliseconds of headroom on top of TTS warmup.

### This is not authentication

The server owns the id, but it's still anonymous. Some things to keep in mind.

- **Clearing the cookie resets identity.** Different browser, private window, or manual delete produces a fresh id and a fresh profile.
- **Production swap is one file.** Replace the cookie read in `/api/token/route.ts` with your session lookup (Better-Auth, Clerk, Supabase) and fall through to the cookie only for guests. The starter ships with a `NODE_ENV !== 'development'` throw at the top of the route as a tripwire to delete on the same edit.
- **Migrating guests to logins.** One `updateMany({ user_id: cookieId }, { $set: { user_id: authedId } })` across `users`, `memories`, and `sessions` merges the history onto the real account.
- **The agent doesn't care.** `ctx.job.metadata` reads the same either way.

## Pattern 4: function-tool CRUD

For data the agent reads or writes on demand, [`@function_tool`](https://docs.livekit.io/agents/logic/tools/definition/) is the right surface. The example here looks up an order by ID.

```python
@function_tool()
async def lookup_order(self, context: RunContext, order_id: str) -> str:
    """Look up an order by its ID. Returns items, total, and status."""
    db = await get_db()
    order = await db.orders.find_one({"order_id": order_id})
    if not order:
        raise ToolError(f"Order {order_id} not found.")
    return json.dumps(
        {
            "order_id": order["order_id"],
            "items": order["items"],
            "total": order["total"],
            "status": order["status"],
        }
    )
```

`ToolError` signals a recoverable failure to the LLM. The message is fed back into the model so it can apologize and ask for a different ID instead of crashing the call. For tools that *mutate* data, call `context.disallow_interruptions()` and return a confirmation string the model can read back.

## Pattern 5: session persistence with on\_session\_end

When a call ends, [`on_session_end`](https://docs.livekit.io/testing/observability/data/) hands you a `JobContext` to call `ctx.make_session_report()` and write the result somewhere durable. Here it lands in a `sessions` collection.

```python
async def on_session_end(ctx: JobContext) -> None:
    """Pattern 5: persist a session report to MongoDB on hangup."""
    try:
        report = ctx.make_session_report()
        db = await get_db()
        user_id = ctx.proc.userdata.get("user_id", DEFAULT_USER_ID)
        tenant_id = ctx.proc.userdata.get("tenant_id", DEFAULT_TENANT_ID)
        await db.sessions.insert_one(
            {
                "session_id": ctx.room.name,
                "user_id": user_id,
                "tenant_id": tenant_id,
                "room_name": ctx.room.name,
                "report": report.to_dict(),
            }
        )
        logger.info("Persisted session report for %s", ctx.room.name)
    except Exception:
        logger.exception("Failed to persist session report")
    finally:
        await aclose()
```

`user_id` and `tenant_id` come from `ctx.proc.userdata`, where Pattern 3 stashed them. Hangup-time code reads the same id that preload set.

`report.to_dict()` returns a JSON-friendly snapshot you can drop into MongoDB without custom serialization. A few hundred of those gives you a corpus you can aggregate right in place.

## Putting the database in front of the agent

The starter's `db/client.py` is short on purpose.

```python
from pymongo import AsyncMongoClient
from pymongo.asynchronous.database import AsyncDatabase

_client: AsyncMongoClient | None = None

async def get_mongo_client() -> AsyncMongoClient:
    global _client
    if _client is None:
        uri = os.getenv("MONGODB_URI")
        if not uri:
            raise RuntimeError("MONGODB_URI environment variable is not set.")
        _client = AsyncMongoClient(uri)
    return _client

async def get_db(db_name: str | None = None) -> AsyncDatabase:
    client = await get_mongo_client()
    return client[db_name or os.getenv("MONGODB_DB", DEFAULT_DB_NAME)]
```

A single `AsyncMongoClient` per process. PyMongo handles pooling under the hood. For explicit lifecycle ownership, construct the client in `prewarm` on `server.setup_fnc` instead. LiveKit forks a process per job, so size your Atlas connection ceiling against `replicas × concurrent jobs × maxPoolSize`.

## Running the starter kit

The agent side needs deps synced, an env file, the one-time model download, and the two MongoDB init scripts.

```bash
cd agent
uv sync
cp .env.example .env.local
# fill in MONGODB_URI, VOYAGE_API_KEY, LIVEKIT_* in .env.local
uv run -m db.indexes                 # collections and vector indexes
uv run -m db.seed                    # sample users, orders, knowledge
lk agent console
```

Vector indexes need a minute or two to become queryable on Atlas after creation, so retry if a search returns nothing immediately.

### What's in the frontend

The frontend is a sibling Next.js App Router project from `agent-starter-react`. It mints tokens server-side (Pattern 3) and runs the LiveKit client that joins the room and plays audio.

```text
frontend/
├── app/
│   ├── api/token/route.ts   # mints tokens, owns the user cookie
│   ├── layout.tsx
│   └── page.tsx             # renders <App appConfig={APP_CONFIG_DEFAULTS} />
├── components/
│   ├── app/
│   │   ├── app.tsx              # TokenSource + useSession + provider
│   │   └── view-controller.tsx  # welcome <-> active session
│   ├── agents-ui/
│   │   ├── agent-session-provider.tsx  # SessionProvider + RoomAudioRenderer
│   │   ├── start-audio-button.tsx      # browser autoplay gate
│   │   └── blocks/agent-session-view-01/  # tiles, transcript, controls
│   └── ui/                              # shadcn primitives
├── lib/utils.ts             # shared client helpers
├── hooks/                   # useDebug, useAgentErrors
└── app-config.ts            # feature toggles + agentName dispatch
```

Connection wiring lives in `components/app/app.tsx`. `TokenSource.endpoint('/api/token')` and `useSession(tokenSource, { agentName })` from `@livekit/components-react` own the room lifecycle. The `agentName` in `app-config.ts` has to match the `agent_name` on the Python side for dispatch to reach the agent. `AgentSessionProvider` wraps `SessionProvider` with `RoomAudioRenderer`, which plays the agent's TTS through the page.

Browser autoplay policies block playback until a user gesture, so the kit ships a `StartAudioButton` calling `useStartAudio()` on first click.

```bash
cd ../frontend
pnpm install
cp .env.example .env.local    # fill in LIVEKIT_* (same values as the agent)
pnpm dev
```

Both apps share LiveKit credentials. A root `package.json` exposes `pnpm setup`, `pnpm db:init`, `pnpm db:seed`, and `pnpm dev` for a single-command runbook.

## Where to go from here

We kept the starter intentionally minimal. A few directions worth exploring.

- Swap `users`, `orders`, and `knowledge` for collections that match your domain, and rewrite the seed script.
- Add or remove `@function_tool` methods on `MongoAgent` to expose your own database operations to the LLM.
- Try `voyage-3-large` for higher-quality embeddings or `voyage-multilingual-2` for non-English content. For latency-sensitive flows, `voyage-3.5-lite` at 512 dimensions is faster than 1024.
- Read about [agent handoffs](https://docs.livekit.io/agents/logic/agents-handoffs/) to split the agent into multiple specialists.

Clone the [starter](https://github.com/livekit-examples/mongodb-hacker-starter), point it at an Atlas cluster, and you should be talking to a memory-equipped agent in under ten minutes.

## Resources

- [LiveKit Agents docs](https://docs.livekit.io/agents/logic/external-data/)
- [MongoDB Atlas Vector Search](https://www.mongodb.com/docs/vector-search/)
- [`$vectorSearch` aggregation stage](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage/)
- [Voyage AI embeddings](https://docs.voyageai.com/docs/embeddings)