How to Give Your AI Agent Memory with Mem0 and Ollama

Every local AI agent has the same flaw: restart the session and it has no idea who you are. Your coding preferences, your project conventions, the facts you shared last week — all gone, because everything the agent "knows" lives inside a context window that gets wiped on restart. The fix is not a bigger model. It is a memory layer that lives outside the context window, on your own disk, and hands the agent only the facts that matter for the current question.

Mem0 is the open-source project that does exactly that. It sits between your agent and the language model, extracts facts from conversations, stores them as vectors, and retrieves the relevant ones before each reply. It has more than 68,000 stars on GitHub, it is licensed under Apache 2.0, and — the part that matters for this guide — it can run entirely on local models through Ollama. No OpenAI key, no cloud service, no data leaving your machine. Here is how to set it up in about 30 minutes.

Source: Mem0 — how a memory layer retrieves facts before the LLM replies and stores new ones after.

What Mem0 Actually Does

When your agent finishes a conversation turn, Mem0 sends the exchange to a language model that pulls out discrete facts: "the user prefers pytest over unittest" or "the user works in the Europe/Berlin timezone." Each fact is converted into a vector embedding and stored in a vector database, alongside the raw text. When a new message arrives, Mem0 searches that store by meaning, not keywords, and injects the matching facts into the prompt before the model replies.

That is the whole idea, and it solves three problems that simpler approaches cannot. A preferences file loaded into the system prompt grows stale and eats context. A chat-history buffer gets truncated. A summary written at the end of a session is only as good as the last summarization. Mem0 keeps facts structured, searchable, and updateable: when you change a preference, it can replace the old fact instead of piling up contradictions. Recent versions of the library extract facts in a single pass and accumulate memories rather than rewriting them, which keeps write latency low enough to run after every turn.

How Memory Flows Through an Agent

The pattern is the same whether your agent answers in text or by voice. Before the language model is called, the memory layer retrieves relevant facts. After the response is generated, new facts from the exchange are stored asynchronously, so the user never waits on a write. The retrieval step is what turns a stateless model into something that feels like it knows you; the storage step is what makes that feeling survive a restart.



Source: Inngest — the memory reader and writer sit beside the agent orchestrator, not inside the prompt.

If you already built a local RAG system with Ollama and Qdrant, this will feel familiar — RAG retrieves documents, Mem0 retrieves facts about the user. The two complement each other: documents answer questions about the world, memory answers questions about you.

What You Need

  • Python 3.10 or newer
  • Docker, for running Qdrant
  • Ollama installed and running, with about 8 GB of VRAM or enough RAM to run an 8B model on CPU
  • Roughly 30 minutes

Step 1: Pull the Models

Mem0 needs two models: one language model to extract facts from conversations, and one embedding model to turn those facts into vectors. Qwen3 8B handles extraction well and fits comfortably in 8 GB of VRAM; nomic-embed-text is a compact embedding model that works well for this job.

ollama pull qwen3:8b
ollama pull nomic-embed-text

Step 2: Start Qdrant

Qdrant is the vector database where memories live. One Docker command starts it, with its data stored in a folder next to your project so it survives container restarts.

docker run -d --name qdrant-local -p 6333:6333 \
  -v $(pwd)/qdrant_storage:/qdrant/storage qdrant/qdrant

Check it is up with curl http://localhost:6333/ — you should get a JSON response with a version number. If the port is already in use, stop the other container or change the host port, and update the config in the next step to match.

Step 3: Install Mem0

python -m venv venv
source venv/bin/activate
pip install mem0ai

Out of the box, Mem0 points at OpenAI for both the language model and embeddings. That is fine if you have an API key, but this guide replaces both with Ollama, so skip the key entirely.

Step 4: Point Mem0 at Ollama

Create a file called memory.py. The config has three blocks: the language model, the embedder, and the vector store. The one number that trips people up is embedding_model_dims — it must match the embedding model exactly. Nomic-embed-text produces 768-dimensional vectors.

from mem0 import Memory

config = {
    "llm": {
        "provider": "ollama",
        "config": {
            "model": "qwen3:8b",
            "ollama_base_url": "http://localhost:11434"
        },
    },
    "embedder": {
        "provider": "ollama",
        "config": {
            "model": "nomic-embed-text",
            "ollama_base_url": "http://localhost:11434"
        },
    },
    "vector_store": {
        "provider": "qdrant",
        "config": {
            "collection_name": "agent_memory",
            "host": "localhost",
            "port": 6333,
            "embedding_model_dims": 768,
        },
    },
}

memory = Memory.from_config(config)

Step 5: Store and Recall a Memory

Two calls are the whole API surface you need most days: add() stores a memory for a user, search() retrieves the relevant ones. Try it in a Python shell:

memory.add("I always use type hints and pytest", user_id="dev")

results = memory.search("write a utility function", user_id="dev")
for r in results["results"]:
    print(r["memory"])

Notice the search query says nothing about testing frameworks, yet the pytest preference comes back. That is semantic search doing its job: it matches by meaning, not by shared words. If the search returns nothing, check that Qdrant is running and that embedding_model_dims is 768 — a mismatch fails inserts silently, and it is the most common reason a fresh setup looks like it is working while storing nothing.

Step 6: Wire It Into Your Agent Loop

A memory layer only earns its keep when it runs on every turn. The pattern is two lines around your normal model call: search before you reply, add after you reply.

def chat(user_id, message):
    # 1. Recall: fetch relevant memories before answering
    recalled = memory.search(message, user_id=user_id)
    context = "\n".join(r["memory"] for r in recalled["results"])

    # 2. Answer with the memories in the prompt
    reply = llm_reply(message, context)

    # 3. Remember: store the exchange for next time
    memory.add(
        [
            {"role": "user", "content": message},
            {"role": "assistant", "content": reply},
        ],
        user_id=user_id,
    )
    return reply

Pass messages as a list when you store a full exchange, so Mem0 can extract facts from both sides of the conversation. Always scope memories with a user_id — without it, facts from different users bleed into each other, and in a multi-user agent that is a privacy bug, not a feature.

This loop drops into any framework. If you built your agent with LangGraph, add the search call to the node that prepares the prompt and the add call to the node that runs after the response; our LangGraph agent guide shows where those nodes live. If your agent calls tools, the same loop applies — and our guide to giving a local LLM tools with Ollama covers the tool-calling side.

Step 7: Prove It Survives a Restart

Do not trust the setup until you have tested the exact failure it exists to prevent. Kill the Python process, stop and start the Qdrant container, then run a fresh shell and search again:

docker stop qdrant-local
docker start qdrant-local
python -c "from memory import memory; print(memory.search('testing preferences', user_id='dev')['results'])"

If your pytest preference comes back, the memory is durable. That is the whole point of the exercise: the agent now remembers you across restarts, without a single API call leaving your machine.

Troubleshooting

  • Memories never come back. The embedding dimension in your config does not match the model. Nomic-embed-text is 768; if you switch to another embedding model later, update embedding_model_dims to match it or inserts fail silently.
  • Connection refused on port 6333. Qdrant is not running. Start it with the Docker command in Step 2 and confirm it answers at http://localhost:6333/.
  • Connection refused on port 11434. Ollama is not running. Run ollama serve in a separate terminal, or start the Ollama app.
  • Mem0 tries to call OpenAI. You created the memory with Memory() instead of Memory.from_config(config). The default config uses OpenAI; only from_config applies your Ollama settings.
  • Extracted facts look garbled with qwen3. Qwen3 wraps its reasoning in <think> blocks, which can leak into extraction. If you see that, switch the LLM model in the config to llama3.1:8b and pull it with Ollama first.

When Self-Hosting Is Not the Right Call

The setup above is the right default for a personal agent or a small team: it is free beyond electricity, your data stays on your disk, and Qdrant plus Ollama are easy to back up by copying two folders. It is not the right call if you need memory shared across many machines, access controls per user, or a managed graph-memory variant — Mem0 also offers a hosted platform and a self-hosted OpenMemory server that exposes the same memory over MCP, which plugs into Claude Desktop, Cursor, or OpenClaw without writing any integration code. Start local, and move up only when the single-machine setup actually limits you.

Local agents feel like toys because they forget. A memory layer is the cheapest upgrade that changes that: thirty minutes of setup, two models you already know how to run, and an agent that still knows your preferences next week. Build it once, and every agent you write after it starts from a memory instead of a blank slate.

Comments

Popular posts from this blog

Open-Source AI Weekly: Bonsai, GigaChat 4 Lead

Claude Claims Proof of Riemann Hypothesis After 167 Years

How to Build an AI Agent with LangGraph in 30 Minutes