---
title: "Building AI Companions"
description: "Building AI companions requires more than a simple chat window; an effective companion needs to retain your preferences, personality traits, and history across multiple sessions. By integrating Mem..."
last_updated: "2026-10-11T17:38:36.505607+00:00"
canonical_url: "https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/guide/how-to-guides/building-ai-companions"
---

## Overview

Building AI companions requires more than a simple chat window; an effective companion needs to retain your preferences, personality traits, and history across multiple sessions. By integrating **Mem0** into your conversational assistant or framework, your assistant gains persistent long-term memory, semantic recall, and automatic context updates. 

This guide covers how to wire memory management into interactive frameworks so that your AI companions remember important details, respect custom memory scopes, and seamlessly adapt to users over time.

> [!NOTE]
> Persistent memory allows your AI companion to recall past decisions, personal details, and workflows without requiring you to re-explain yourself in every new conversation.

---

## Setting Up Persistent Memory for Assistants

### Understanding Authentication and Configuration

To wire memory into an interactive conversational assistant, you typically choose a framework integration or plugin and configure your authentication and scoping preferences. Every memory integration requires authentication to connect your assistant to the Mem0 platform or your self-hosted backend. Set your API key in your environment variables:

```bash
export MEM0_API_KEY="your-api-key-here"
```

If you are running a self-hosted instance rather than the cloud platform, you can configure a custom host URL instead:

```bash
export MEM0_HOST="https://your-self-hosted-mem0-instance.com"
```

### Configuring Memory Scopes

Memories are organized using namespaces to keep data cleanly separated between users, projects, and active runs. The available scope identifiers include:

| Scope Identifier | What It Controls | Example Use Case |
| :--- | :--- | :--- |
| `user_id` | Identifies the unique human user owning the memory. | Separating preferences for different users. |
| `agent_id` | Partitions memories by a specific AI agent's identity. | Giving different companions separate personalities. |
| `run_id` | Limits memories to a specific active run or conversation session. | Storing temporary state for a single working session. |
| `app_id` | Groups memories under a specific application or project. | Isolating project knowledge in a coding workspace. |

---

## Step-by-Step: Wiring Memory into Frameworks

### Framework Integration Workflow

Depending on your conversational framework, you can hook Mem0 directly into the message loop for automatic context injection and conversation extraction.

### Step 1: Initialize the Memory Store

Initialize the memory store with your credentials and default scope settings. For example, when using memory stores in backend pipelines, specify your user namespace and enable extraction:

```python
from mem0_strands import Mem0MemoryStore

# Configure semantic memory with automatic server-side extraction
store = Mem0MemoryStore(user_id="alex", writable=True, extraction=True)
```

### Step 2: Enable Auto-Recall and Auto-Capture

Most companion integrations support automated hooks that perform two key functions:
1. **Auto-Recall:** Before generating a response, the system searches stored memories for relevant facts based on your latest prompt and injects them into the system prompt.
2. **Auto-Capture:** After a conversation turn or session ends, the system passes the conversation turns to Mem0 to extract durable facts, preferences, and decisions.

```typescript
// Example configuration snippet for auto-recall and auto-capture settings
const mem0Config = {
  autoRecall: true,
  autoCapture: true,
  topK: 5,
  searchThreshold: 0.7,
};
```

### Step 3: Use Explicit Memory Tools

If your companion framework supports agent-callable tools, the assistant can proactively search, add, update, or delete memories during conversations. 

```markdown
User does X (e.g., states a preference) → System extracts durable fact → Memory stored via add_memory tool → Future queries retrieve context via search_memory tool
```

Available core tool actions typically include:
- **Search:** Recalls facts ranked by semantic relevance.
- **Add:** Stores a durable fact verbatim or via extraction.
- **Update:** Replaces the text of an outdated memory by its unique ID.
- **Delete:** Removes obsolete or forgotten memories.

---

## Examples & Configuration Options

Below is an example of configuring a chat completion wrapper with Mem0 to automatically manage memory injection and background saving:

```python
from mem0 import MemoryClient

# Initialize the client
client = MemoryClient(api_key="your-api-key")

# Add a conversation turn to memory
client.add(
    [
        {"role": "user", "content": "I prefer vegetarian recipes and live in Seattle."},
        {"role": "assistant", "content": "Got it! I'll keep your dietary preference in mind."}
    ],
    user_id="alex-user"
)

# Search relevant memories for future turns
memories = client.search(
    query="What does the user like to eat?",
    filters={"user_id": "alex-user"}
)
```

> [!TIP]
> When building multi-agent companions, use distinct `agent_id` parameters to ensure each companion maintains its own distinct conversational history and persona traits.

---

## Tips and Warnings

> [!WARNING]
> Extraction runs asynchronously on the server side in some configurations. Do not immediately search for a newly added memory in the exact same turn expecting it to be indexed instantly.

> [!CAUTION]
> Avoid passing sensitive credentials, raw secrets, or private keys into conversational prompts. Ensure your extraction filters redact sensitive tokens before writing them to long-term storage.

> [!TIP]
> For chat models using framework plugins (such as LangChain or custom orchestrators), utilize helper functions like `condenseMem0MemoryIntoHumanMessage` or system prompt injection utilities to cleanly separate reference memories from active user questions.

## Related

- [Managing Memories](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/guide/core-features/managing-memories)
- [Organizing User Memories](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/guide/how-to-guides/organizing-user-memories)


## Sitemap

See the full [sitemap](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/llms.txt) for all pages in this wiki.
