---
title: "Search Memories"
description: "When interacting with an AI assistant, it's crucial for the AI to remember past conversations, preferences, and important details to provide a personalized and consistent experience. The \"Search Me..."
last_updated: "2026-05-07T04:49:20.295103+00:00"
canonical_url: "https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/guide/section-2/search-memories"
---

When interacting with an AI assistant, it's crucial for the AI to remember past conversations, preferences, and important details to provide a personalized and consistent experience. The "Search Memories" feature allows your AI to retrieve relevant information from its long-term memory based on the current conversation or user query.

This capability ensures that the AI doesn't "forget" previous interactions, enabling it to adapt to individual user needs, recall specific facts, or continue a conversation with full context. By searching memories, your AI can access stored information about a user's history, preferences, or specific topics discussed, making its responses much more accurate and helpful.

<Steps>
<Step>
### Instantiate the Memory Object
Before you can search for memories, you need to initialize the `Memory` object. This object manages all memory operations.

```python
from mem0 import Memory

# Initialize the memory object
memory = Memory()
```
</Step>

<Step>
### Search for Relevant Memories
To find memories, you'll use the `search` method of your `Memory` object. You need to provide a `query` and a `user_id`. Optionally, you can specify a `limit` to control how many memories are returned.

```python
# Define your search parameters
user_query = "What did we talk about regarding my favorite color?"
user_identifier = "default_user" # Or a specific user ID for your application
number_of_results = 3

# Perform the search
relevant_memories = memory.search(
    query=user_query,
    user_id=user_identifier,
    limit=number_of_results
)
```

<Callout variant="info" title="Understanding Search Parameters">
*   **`query`**: This is the text or question you want to use to find relevant memories. It could be the user's current input, a summary of the conversation, or a specific topic.
*   **`user_id`**: This identifier ensures that the search is performed within the context of a specific user's memories. It helps in retrieving personalized information.
*   **`limit` (Optional)**: This specifies the maximum number of relevant memories to retrieve. If not provided, a default number of memories will be returned.
</Callout>
</Step>

<Step>
### Process the Search Results
The `search` method returns a dictionary containing the results. The actual memory entries are typically found under the `results` key, where each entry is a dictionary that includes the `memory` content.

```python
# Check if any memories were found
if relevant_memories and relevant_memories.get("results"):
    print(f"Found {len(relevant_memories['results'])} relevant memories:")
    for entry in relevant_memories["results"]:
        print(f"- {entry['memory']}")
else:
    print("No relevant memories found.")

# Example of how to format memories for an AI prompt
memories_str = "\n".join(f"- {entry['memory']}" for entry in relevant_memories["results"])
print("\nFormatted memories for AI prompt:")
print(memories_str)
```

<Callout variant="success" title="Using Memories in AI Prompts">
Once you retrieve relevant memories, you can incorporate them directly into your AI's system prompt or user messages. This provides the AI with the necessary context to generate informed and personalized responses, as shown in the example below.
</Callout>
</Step>
</Steps>

### Example: Integrating Memory Search into a Chatbot

Here's a complete example demonstrating how to search for memories and use them to enhance an AI's response in a simple chatbot.

```python
from openai import OpenAI
from mem0 import Memory

# Initialize OpenAI client and Memory
openai_client = OpenAI()
memory = Memory()

def chat_with_memories(message: str, user_id: str = "default_user") -> str:
    # 1. Retrieve relevant memories based on the current message
    relevant_memories = memory.search(query=message, user_id=user_id, limit=3)
    
    # Format the retrieved memories into a string for the AI prompt
    memories_str = "\n".join(f"- {entry['memory']}" for entry in relevant_memories["results"])

    # 2. Generate Assistant response using the memories
    # The system prompt includes the retrieved memories for context
    system_prompt = f"You are a helpful AI. Answer the question based on query and memories.\nUser Memories:\n{memories_str}"
    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": message}
    ]
    
    response = openai_client.chat.completions.create(
        model="gpt-4.1-nano-2025-04-14", # Replace with your preferred LLM
        messages=messages
    )
    assistant_response = response.choices[0].message.content

    # 3. Create new memories from the conversation (optional, but good practice)
    # This adds the current interaction to the memory for future searches
    messages.append({"role": "assistant", "content": assistant_response})
    memory.add(messages, user_id=user_id)

    return assistant_response

def main():
    print("Chat with AI (type 'exit' to quit)")
    while True:
        user_input = input("You: ").strip()
        if user_input.lower() == 'exit':
            print("Goodbye!")
            break
        print(f"AI: {chat_with_memories(user_input)}")

if __name__ == "__main__":
    main()
```

In this example, the `chat_with_memories` function first searches for memories related to the `user_input`. It then uses these `relevant_memories` to construct a `system_prompt` for the AI model, ensuring the AI has the necessary context to provide a well-informed answer. Finally, the conversation turn is added back to memory, continuously enriching the AI's knowledge base.

## Sitemap

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