迁移与最佳实践(3/7)

Understand how Mem0's memory system is evaluated, benchmark results, and how to run evaluations on your own data.

Why Memory Evaluation Matters

Most AI agent memory systems retrieve information by maximizing context window size. That works on benchmarks but not in production, where every token adds cost. Token efficiency means achieving high accuracy with less context per query. It is what separates benchmark performance from production viability.

Mem0's algorithm achieves competitive accuracy on LoCoMo, LongMemEval, and BEAM while averaging under 7,000 tokens per retrieval call. Full-context approaches on the same benchmarks routinely consume 25,000+ tokens per query. Unless noted otherwise, scores are reported at a top_200 retrieval budget (the 200 highest-ranked memories per query).

Evaluating a memory system at scale comes down to three parameters: accuracy (what the benchmarks measure), cost (context tokens per query), and performance (latency). Optimizing one is easy. Balancing all three at scale is the actual problem.

Some benchmarks today, particularly smaller ones like LoCoMo and LongMemEval, can be materially improved by aggressive retrieval strategies, larger context windows, or frontier models. That does not necessarily mean the underlying memory system has gotten better. We evaluate under constraints that reflect how memory systems actually run in production: limited context windows and practical token budgets.

Architecture Overview

Mem0's memory system operates across two phases, extraction (writing) and retrieval (reading), connected by a graph memory layer (entity linking) and a temporal reasoning layer (time metadata written during extraction and scored during retrieval).

Memory Extraction (Distillation)

When new conversations arrive, the extraction pipeline processes them through six stages:

  1. Store New Memories: Conversation enters the pipeline asynchronously (after the agent responds)
  2. Context Lookup: Find related existing memories to avoid duplicates
  3. Distill Memories: Single-pass LLM extraction produces ADD-only facts from input + context
  4. Deduplicate + Embed: Hash-based deduplication, then vectorize new memories
  5. Graph Memory (Entity Linking): Identify entities (proper nouns, quoted text, compound noun phrases) and link them across memories into a graph
  6. Temporal Reasoning: A separate temporal reasoning pass reads each new memory alongside the source conversation and its date, extracting temporal metadata: when the event occurred, whether it is ongoing or completed, how precise the timing is, and the memory type (event, state, plan, preference, relationship, absence). It is independent of extraction and can run asynchronously so writes stay fast; this metadata is stored with the memory and used later at retrieval.

Memories are distributed across three storage layers, each tuned for a specific retrieval pattern:

Store Contents Purpose
Vector Database Memory text, embeddings, metadata (timestamps, hash, categories, attributed_to) Primary fact storage + semantic retrieval
Graph / Entity Store Entities + embeddings + linked memory IDs Graph connections across memories + entity-based retrieval boost
SQL Database History log (ADD events) + rolling message window Audit trail + extraction dedup context

The key architectural decision is ADD-only extraction. New facts are stored alongside old ones. Nothing is overwritten or deleted. When information changes, both the old and new facts survive. This preserves temporal context and eliminates information loss from premature consolidation.

Multi-Signal Retrieval

When a query arrives, the retrieval pipeline scores candidates across multiple signals in parallel:

  1. Semantic Search: Vector similarity scoring against memory embeddings
  2. Keyword Search: Normalized term matching via BM25 with verb-form lemmatization
  3. Entity Search: Entity matching boosts memories linked to query entities
  4. Temporal Reasoning: The query's temporal intent is classified (with no extra LLM call), then each candidate is scored by how well the temporal metadata extracted at write time matches that intent.

These signals are fused via rank scoring into the final top-K set. The temporal score is additive and semantic relevance always dominates; it nudges ranking toward the correct dated instance without filtering candidates out or overriding a strong semantic match, so relevant memories are never dropped. Different query types lean on different signals:

Query Type Primary Signal Example
Conceptual Semantic "What does the user think about remote work?"
Factual/exact BM25 keyword "What meetings did I attend last week?"
Entity-centric Entity matching "What do we know about Alice?"
Temporal Temporal reasoning "When did the user first mention the project?"

The combined score outperformed every individual signal across every category tested.

Benchmarks

LoCoMo

LoCoMo tests single-hop, multi-hop, open-domain, and temporal memory recall across conversational sessions.

Category Score
Overall 92.5
Single-hop 91.2
Multi-hop 91.3
Open-domain 72.7
Temporal 92.0

Mean tokens: 6,956.

Temporal reasoning is on by default and helps most on temporal (92.0) and multi-hop (91.3) questions, where the system has to identify which dated instance applies, while open-domain (72.7) does not benefit and is actively being tuned.

LongMemEval

LongMemEval evaluates memory across single-session and multi-session contexts, including knowledge updates and temporal reasoning.

Category Score
Overall 94.4
Single-session (user) 98.6
Single-session (assistant) 98.2
Single-session (preference) 96.7
Knowledge update 93.6
Temporal reasoning 97.0
Multi-session 88.0

Mean tokens: 6,787.

Temporal reasoning is the standout at a top_200 budget, reaching 97.0 on the temporal-reasoning category, with single-session user and assistant both near-saturated (98.6 and 98.2). Knowledge update (93.6) remains the hardest category for an additive, ADD-only architecture: older facts are preserved rather than overwritten, so semantically similar prior facts can still surface alongside newer ones.

BEAM

BEAM evaluates memory systems at 1M and 10M token scales across ten task categories. It is the only public benchmark that operates at context volumes production AI agents actually encounter.

Category 1M 10M
Overall 64.1 48.6
preference_following 88.3 90.4
instruction_following 85.2 82.5
information_extraction 70.0 56.3
knowledge_update 65.0 75.0
multi_session_reasoning 65.2 26.1
summarization 63.5 46.9
temporal_reasoning 61.8 16.3
event_ordering 53.6 20.2
abstention 52.5 40.0
contradiction_resolution 35.7 32.5

Mean tokens (1M): 6,719. Mean tokens (10M): 6,914.

BEAM is the most relevant benchmark here. It operates at 1M and 10M token scales and cannot be solved by simply expanding the context window. The results at 10M reflect where memory systems actually stand at production context volumes. The system holds up well on preference following, instruction following, and knowledge updates at both scales. Weaker categories at 10M (temporal reasoning, event ordering, multi-session reasoning) are open problems across the field. They require higher-order representations of how events relate to each other across time, which is a primary focus of our ongoing research.

Performance Summary

All results use a single-pass retrieval setup (one retrieval call, one answer, no agentic loops) at a top_200 retrieval budget.

Benchmark Score Average tokens / query
LoCoMo 92.5 6,956
LongMemEval 94.4 6,787
BEAM (1M) 64.1 6,719
BEAM (10M) 48.6 6,914

Scores reflect Mem0's managed platform, which includes proprietary optimizations not available in the open-source SDK. Open-source users should expect directionally similar gains but not identical numbers.

All benchmarks run on the same production-representative model stack. Scores carry a ±1 point confidence interval due to judge inconsistency.

Running Evaluations

The full evaluation framework is open-sourced so anyone can reproduce the numbers independently. It supports both Mem0 Cloud and self-hosted OSS backends.

Setup

git clone https://github.com/mem0ai/memory-benchmarks.git
cd memory-benchmarks
pip install -r requirements.txt

# Set your API keys
export MEM0_API_KEY=m0-your-key
export OPENAI_API_KEY=sk-your-key
git clone https://github.com/mem0ai/memory-benchmarks.git
cd memory-benchmarks
pip install -r requirements.txt

# Copy and configure environment
cp .env.example .env
# Edit .env to add OPENAI_API_KEY

# Start local Mem0 server + Qdrant
docker compose up -d
# Mem0 server: http://localhost:8888
# Qdrant:      http://localhost:6333

Running a Benchmark

Each benchmark is a Python module with its own runner (source code). All share common CLI options:

Option Default Description
--project-name (required) Run identifier for tracking results
--backend oss oss (self-hosted) or cloud (Mem0 Platform)
--mem0-api-key N/A Mem0 API key (required for cloud backend)
--mem0-host http://localhost:8888 Mem0 server URL (for oss backend)
--top-k 200 Number of memories to retrieve per query
--top-k-cutoffs 10,20,50,200 Evaluate accuracy at multiple retrieval depths (BEAM default: 100)
--answerer-model (varies) LLM for generating answers from retrieved memories
--judge-model (varies) LLM for judging answer correctness
--provider openai LLM provider: openai, anthropic, azure
--judge-provider (same as --provider) Override provider for the judge model
--max-workers 10 Parallel workers for evaluation
--predict-only N/A Stop after search, skip answer + judge phases
--evaluate-only N/A Skip ingest + search, evaluate existing results
--resume N/A Resume from checkpoint (BEAM and LongMemEval; on by default for LongMemEval)
# ~300 questions across 10 conversations (fastest benchmark)
python -m benchmarks.locomo.run \
  --project-name my-eval \
  --backend cloud \
  --mem0-api-key $MEM0_API_KEY \
  --top-k 200

# Self-hosted
python -m benchmarks.locomo.run \
  --project-name my-eval \
  --top-k 200
# 500 questions across 6 categories
python -m benchmarks.longmemeval.run \
  --project-name my-eval \
  --backend cloud \
  --mem0-api-key $MEM0_API_KEY \
  --all-questions \
  --top-k 200

# Self-hosted
python -m benchmarks.longmemeval.run \
  --project-name my-eval \
  --all-questions \
  --top-k 200
# 1M token scale (100 conversations)
python -m benchmarks.beam.run \
  --project-name my-eval \
  --backend cloud \
  --mem0-api-key $MEM0_API_KEY \
  --chat-sizes 1M \
  --conversations 0-99 \
  --top-k 200

# 10M token scale
python -m benchmarks.beam.run \
  --project-name my-eval \
  --backend cloud \
  --mem0-api-key $MEM0_API_KEY \
  --chat-sizes 10M \
  --conversations 0-99 \
  --top-k 200

Custom Model Configuration

To run evaluations with custom models (Azure OpenAI, Ollama, etc.), copy one of the provided configs:

# Available configs: openai.yaml, azure-openai.yaml, ollama.yaml
cp configs/azure-openai.yaml mem0-config.yaml
# Edit mem0-config.yaml with your model details

# Uncomment the volume mount in docker-compose.yml, then restart:
docker compose down && docker compose up -d

Viewing Results

Results are saved to results/[benchmark]/ and can be explored through the built-in web UI:

npm install
npm run dev -- -p 3001
# Open http://localhost:3001

The UI lets you browse per-question results, inspect retrieval details, and compare multiple runs.

Result Format

Each evaluated question produces a structured result:

{
  "id": "locomo_q_001",
  "group": "temporal",
  "question": "When did the user first mention moving?",
  "ground_truth": "During the March 3rd conversation",
  "retrieval": {
    "search_query": "when did user mention moving",
    "search_results": ["..."],
    "search_latency_ms": 123.4,
    "total_results": 42
  },
  "generation": {
    "generated_answer": "The user first mentioned moving on March 3rd",
    "model": "<answerer-model>",
    "prompt_tokens": 500,
    "completion_tokens": 100
  },
  "judgment": {
    "judgment": "CORRECT",
    "score": 0.85,
    "reason": "Answer correctly identifies the date",
    "model": "<judge-model>"
  },
  "cutoff_results": {
    "top_10": { "score": 0.75, "judgment": "CORRECT" },
    "top_50": { "score": 0.85, "judgment": "CORRECT" },
    "top_200": { "score": 0.90, "judgment": "CORRECT" }
  }
}

Interpreting Results

When evaluating memory systems, keep these considerations in mind:

  • Saturating a small benchmark is not the same as building a memory system that works at scale. Small benchmarks can be brute-forced with aggressive retrieval and frontier models.
  • Token efficiency matters as much as accuracy. A system that scores 95% using 25K tokens per query isn't comparable to one scoring 90% using 7K tokens. Report mean tokens per query alongside scores.
  • Compare at equal constraints. Always compare systems using the same retrieval budget, the same model, and the same latency budget. A frontier model at maximum recall is not comparable to a smaller production-grade model at production-realistic retrieval depth.
  • Watch for score ceiling effects. Categories like "single-session user" are already near-saturated (97%+). Improvements in these categories are less meaningful than gains in harder categories like temporal reasoning or multi-session.
  • BEAM at 10M is the real test. Any system can look good at small scale. The 10M-token BEAM benchmark reveals whether the retrieval system actually scales.

FAQ

<AccordionGroup>

The judge model is configurable via `--judge-model` and `--judge-provider` flags. See the [evaluation repository](https://github.com/mem0ai/memory-benchmarks) for the current defaults. Scores carry a ±1 point confidence interval due to judge inconsistency.



Yes. For self-hosted, configure the extraction model in your `mem0-config.yaml` (see the `configs/` directory of the evaluation repo for provider-specific examples). For Mem0 Cloud, extraction uses the platform's default. Using a frontier model will likely produce higher scores but at higher cost and latency.



BEAM operates at 1M and 10M token scales, orders of magnitude larger than LoCoMo or LongMemEval. At these scales, similar content appears multiple times across the window, and the memory system must surface the exact correct memory over many close matches. The scores reflect the genuine difficulty of the task, not a regression in the algorithm.



Open a pull request to the [memory-benchmarks repository](https://github.com/mem0ai/memory-benchmarks) with your benchmark implementation. See the repository README for the expected interface and format.

</AccordionGroup>

Resources

Open-source evaluation framework for reproducing all benchmark results



Published research papers and technical reports



Detailed writeup of the new algorithm design and results



Guide for migrating your Platform integration

Pair the OpenAI Agents SDK with Mem0 to build a voice assistant that remembers.

Works with: Mem0 Platform (MemoryClient)

This guide demonstrates how to combine OpenAI's Agents SDK for voice applications with Mem0's memory capabilities to create a voice assistant that remembers user preferences and past interactions.

Prerequisites

Before you begin, make sure you have:

  1. Installed OpenAI Agents SDK with voice dependencies:
pip install 'openai-agents[voice]'
  1. Installed Mem0 SDK:
pip install mem0ai
  1. Installed other required dependencies:
pip install numpy sounddevice pydantic
  1. Set up your API keys:
  2. OpenAI API key for the Agents SDK
  3. Mem0 API key from the Mem0 Platform

Code Breakdown

Let's break down the key components of this implementation:

1. Setting Up Dependencies and Environment

# OpenAI Agents SDK imports
from agents import (
    Agent,
    function_tool
)
from agents.voice import (
    AudioInput,
    SingleAgentVoiceWorkflow,
    VoicePipeline
)
from agents.extensions.handoff_prompt import prompt_with_handoff_instructions

# Mem0 imports
from mem0 import AsyncMemoryClient

# Set up API keys (replace with your actual keys)
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"

# Define a global user ID for simplicity
USER_ID = "voice_user"

# Initialize Mem0 client
mem0_client = AsyncMemoryClient()

This section handles:

  • Importing required modules from OpenAI Agents SDK and Mem0
  • Setting up environment variables for API keys
  • Defining a simple user identification system (using a global variable)
  • Initializing the Mem0 client that will handle memory operations

2. Memory Tools with Function Decorators

The @function_tool decorator transforms Python functions into callable tools for the OpenAI agent. Here are the key memory tools:

Storing User Memories

import logging

# Set up logging at the top of your file
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    force=True
)
logger = logging.getLogger("memory_voice_agent")

# Then use logger in your function tools
@function_tool
async def save_memories(
    memory: str
) -> str:
    """Store a user memory in memory."""
    # This will be visible in your console
    logger.debug(f"Saving memory: {memory} for user {USER_ID}")

    # Store the preference in Mem0
    memory_content = f"User memory - {memory}"
    await mem0_client.add(
        memory_content,
        user_id=USER_ID,
    )

    return f"I've saved your memory: {memory}"

This function:

  • Takes a memory string
  • Creates a formatted memory string
  • Stores it in Mem0 using the add() method
  • Includes metadata to categorize the memory for easier retrieval
  • Returns a confirmation message that the agent will speak

Finding Relevant Memories

@function_tool
async def search_memories(
    query: str
) -> str:
    """
    Find memories relevant to the current conversation.
    Args:
        query: The search query to find relevant memories
    """
    print(f"Finding memories related to: {query}")
    results = await mem0_client.search(
        query,
        filters={"user_id": USER_ID},
        top_k=5,
        threshold=0.7,  # Higher threshold for more relevant results
    )

    # Format and return the results
    if not results.get('results', []):
        return "I don't have any relevant memories about this topic."

    memories = [f"• {result['memory']}" for result in results.get('results', [])]
    return "Here's what I remember that might be relevant:\n" + "\n".join(memories)

This tool:

  • Takes a search query string
  • Passes it to Mem0's semantic search to find related memories
  • Sets a threshold for relevance to ensure quality results
  • Returns a formatted list of relevant memories or a default message

3. Creating the Voice Agent

def create_memory_voice_agent():
    # Create the agent with memory-enabled tools
    agent = Agent(
        name="Memory Assistant",
        instructions=prompt_with_handoff_instructions(
            """You're speaking to a human, so be polite and concise.
            Always respond in clear, natural English.
            You have the ability to remember information about the user.
            Use the save_memories tool when the user shares important information worth remembering.
            Use the search_memories tool when you need context from past conversations or user asks you to recall something.
            """,
        ),
        model="gpt-5-mini",
        tools=[save_memories, search_memories],
    )

    return agent

This function:

  • Creates an OpenAI Agent with specific instructions
  • Configures it to use gpt-4.1-nano (you can use other models)
  • Registers the memory-related tools with the agent
  • Uses prompt_with_handoff_instructions to include standard voice agent behaviors

4. Microphone Recording Functionality

async def record_from_microphone(duration=5, samplerate=24000):
    """Record audio from the microphone for a specified duration."""
    print(f"Recording for {duration} seconds...")

    # Create a buffer to store the recorded audio
    frames = []

    # Callback function to store audio data
    def callback(indata, frames_count, time_info, status):
        frames.append(indata.copy())

    # Start recording
    with sd.InputStream(samplerate=samplerate, channels=1, callback=callback, dtype=np.int16):
        await asyncio.sleep(duration)

    # Combine all frames into a single numpy array
    audio_data = np.concatenate(frames)
    return audio_data

This function:

  • Creates a simple asynchronous microphone recording function
  • Uses the sounddevice library to capture audio input
  • Stores frames in a buffer during recording
  • Combines frames into a single numpy array when complete
  • Returns the audio data for processing

5. Main Loop and Voice Processing

async def main():
    # Create the agent
    agent = create_memory_voice_agent()

    # Set up the voice pipeline
    pipeline = VoicePipeline(
        workflow=SingleAgentVoiceWorkflow(agent)
    )

    # Configure TTS settings
    pipeline.config.tts_settings.voice = "alloy"
    pipeline.config.tts_settings.speed = 1.0

    try:
        while True:
            # Get user input
            print("\nPress Enter to start recording (or 'q' to quit)...")
            user_input = input()
            if user_input.lower() == 'q':
                break

            # Record and process audio
            audio_data = await record_from_microphone(duration=5)
            audio_input = AudioInput(buffer=audio_data)
            result = await pipeline.run(audio_input)

            # Play response and handle events
            player = sd.OutputStream(samplerate=24000, channels=1, dtype=np.int16)
            player.start()

            agent_response = ""
            print("\nAgent response:")

            async for event in result.stream():
                if event.type == "voice_stream_event_audio":
                    player.write(event.data)
                elif event.type == "voice_stream_event_content":
                    content = event.data
                    agent_response += content
                    print(content, end="", flush=True)

            # Save the agent's response to memory
            if agent_response:
                try:
                    await mem0_client.add(
                        f"Agent response: {agent_response}",
                        user_id=USER_ID,
                        metadata={"type": "agent_response"}
                    )
                except Exception as e:
                    print(f"Failed to store memory: {e}")

    except KeyboardInterrupt:
        print("\nExiting...")

This main function orchestrates the entire process:

  1. Creates the memory-enabled voice agent
  2. Sets up the voice pipeline with TTS settings
  3. Implements an interactive loop for recording and processing voice input
  4. Handles streaming of response events (both audio and text)
  5. Automatically saves the agent's responses to memory
  6. Includes proper error handling and exit mechanisms

Create a Memory-Enabled Voice Agent

Now that we've explained each component, here's the complete implementation that combines OpenAI Agents SDK for voice with Mem0's memory capabilities:

import asyncio
import os
import logging
from typing import Optional, List, Dict, Any
import numpy as np
import sounddevice as sd
from pydantic import BaseModel

# OpenAI Agents SDK imports
from agents import (
    Agent,
    function_tool
)
from agents.voice import (
    AudioInput,
    SingleAgentVoiceWorkflow,
    VoicePipeline
)
from agents.extensions.handoff_prompt import prompt_with_handoff_instructions

# Mem0 imports
from mem0 import AsyncMemoryClient

# Set up API keys (replace with your actual keys)
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"

# Define a global user ID for simplicity
USER_ID = "voice_user"

# Initialize Mem0 client
mem0_client = AsyncMemoryClient()

# Create tools that utilize Mem0's memory
@function_tool
async def save_memories(
    memory: str
) -> str:
    """
    Store a user memory in memory.
    Args:
        memory: The memory to save
    """
    print(f"Saving memory: {memory} for user {USER_ID}")

    # Store the preference in Mem0
    memory_content = f"User memory - {memory}"
    await mem0_client.add(
        memory_content,
        user_id=USER_ID,
    )

    return f"I've saved your memory: {memory}"

@function_tool
async def search_memories(
    query: str
) -> str:
    """
    Find memories relevant to the current conversation.
    Args:
        query: The search query to find relevant memories
    """
    print(f"Finding memories related to: {query}")
    results = await mem0_client.search(
        query,
        filters={"user_id": USER_ID},
        top_k=5,
        threshold=0.7,  # Higher threshold for more relevant results
    )

    # Format and return the results
    if not results.get('results', []):
        return "I don't have any relevant memories about this topic."

    memories = [f"• {result['memory']}" for result in results.get('results', [])]
    return "Here's what I remember that might be relevant:\n" + "\n".join(memories)

# Create the agent with memory-enabled tools
def create_memory_voice_agent():
    # Create the agent with memory-enabled tools
    agent = Agent(
        name="Memory Assistant",
        instructions=prompt_with_handoff_instructions(
            """You're speaking to a human, so be polite and concise.
            Always respond in clear, natural English.
            You have the ability to remember information about the user.
            Use the save_memories tool when the user shares important information worth remembering.
            Use the search_memories tool when you need context from past conversations or user asks you to recall something.
            """,
        ),
        model="gpt-5-mini",
        tools=[save_memories, search_memories],
    )

    return agent

async def record_from_microphone(duration=5, samplerate=24000):
    """Record audio from the microphone for a specified duration."""
    print(f"Recording for {duration} seconds...")

    # Create a buffer to store the recorded audio
    frames = []

    # Callback function to store audio data
    def callback(indata, frames_count, time_info, status):
        frames.append(indata.copy())

    # Start recording
    with sd.InputStream(samplerate=samplerate, channels=1, callback=callback, dtype=np.int16):
        await asyncio.sleep(duration)

    # Combine all frames into a single numpy array
    audio_data = np.concatenate(frames)
    return audio_data

async def main():
    print("Starting Memory Voice Agent")

    # Create the agent and context
    agent = create_memory_voice_agent()

    # Set up the voice pipeline
    pipeline = VoicePipeline(
        workflow=SingleAgentVoiceWorkflow(agent)
    )

    # Configure TTS settings
    pipeline.config.tts_settings.voice = "alloy"
    pipeline.config.tts_settings.speed = 1.0

    try:
        while True:
            # Get user input
            print("\nPress Enter to start recording (or 'q' to quit)...")
            user_input = input()
            if user_input.lower() == 'q':
                break

            # Record and process audio
            audio_data = await record_from_microphone(duration=5)
            audio_input = AudioInput(buffer=audio_data)

            print("Processing your request...")

            # Process the audio input
            result = await pipeline.run(audio_input)

            # Create an audio player
            player = sd.OutputStream(samplerate=24000, channels=1, dtype=np.int16)
            player.start()

            # Store the agent's response for adding to memory
            agent_response = ""

            print("\nAgent response:")
            # Play the audio stream as it comes in
            async for event in result.stream():
                if event.type == "voice_stream_event_audio":
                    player.write(event.data)
                elif event.type == "voice_stream_event_content":
                    # Accumulate and print the text response
                    content = event.data
                    agent_response += content
                    print(content, end="", flush=True)

            print("\n")

            # Example of saving the conversation to Mem0 after completion
            if agent_response:
                try:
                    await mem0_client.add(
                        f"Agent response: {agent_response}",
                        user_id=USER_ID,
                        metadata={"type": "agent_response"}
                    )
                except Exception as e:
                    print(f"Failed to store memory: {e}")

    except KeyboardInterrupt:
        print("\nExiting...")

if __name__ == "__main__":
    asyncio.run(main())

Key Features of This Implementation

This implementation offers several key features:

  1. Simplified User Management: Uses a global USER_ID variable for simplicity, but can be extended to manage multiple users.

  2. Real Microphone Input: Includes a record_from_microphone() function that captures actual voice input from your microphone.

  3. Interactive Voice Loop: Implements a continuous interaction loop, allowing for multiple back-and-forth exchanges.

  4. Memory Management Tools:

  5. save_memories: Stores user memories in Mem0
  6. search_memories: Searches for relevant past information

  7. Voice Configuration: Demonstrates how to configure TTS settings for the voice response.

Running the Example

To run this example:

  1. Replace the placeholder API keys with your actual keys
  2. Make sure your microphone is properly connected
  3. Run the script with Python 3.8 or newer
  4. Press Enter to start recording, then speak your request
  5. Press 'q' to quit the application

The agent will listen to your request, process it through the OpenAI model, utilize Mem0 for memory operations as needed, and respond both through text output and voice speech.

Best Practices for Voice Agents with Memory

  1. Optimizing Memory for Voice: Keep memories concise and relevant for voice responses.

  2. Forgetting Mechanism: Implement a way to delete or expire memories that are no longer relevant.

  3. Context Preservation: Store enough context with each memory to make retrieval effective.

  4. Error Handling: Implement robust error handling for memory operations, as voice interactions should continue smoothly even if memory operations fail.

Conclusion

By combining OpenAI's Agents SDK with Mem0's memory capabilities, you can create voice agents that maintain persistent memory of user preferences and past interactions. This significantly enhances the user experience by making conversations more natural and personalized.

As you build your voice application, experiment with different memory strategies and filtering approaches to find the optimal balance between comprehensive memory and efficient retrieval for your specific use case.

Debugging Function Tools

When working with the OpenAI Agents SDK, you might notice that regular print() statements inside @function_tool decorated functions don't appear in your console output. This is because the Agents SDK captures and redirects standard output when executing these functions.

To effectively debug your function tools, use Python's logging module instead:

import logging

# Set up logging at the top of your file
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    force=True
)
logger = logging.getLogger("memory_voice_agent")

# Then use logger in your function tools
@function_tool
async def save_memories(
    memory: str
) -> str:
    """Store a user memory in memory."""
    # This will be visible in your console
    logger.debug(f"Saving memory: {memory} for user {USER_ID}")

    # Rest of your function...

Learn how to add vision and audio memory alongside voice interactions.



Master the core patterns for building memory-powered companions.

<Snippet />