Skip to content

ant_ai.memory.backends.mem0

Mem0Memory pydantic-model

Bases: Memory

Long-term memory kept by the mem0 cloud service, searched by meaning.

Requires MEM0_API_KEY in the environment, or pass api_key explicitly. Memories are kept per ctx.user_id, or per ctx.session_id when there is no user.

Example
from ant_ai.agent import Agent
from ant_ai.memory.backends.mem0 import Mem0Memory

agent = Agent(memory=Mem0Memory(), ...)

The agent can now call:

- Mem0Memory_search(query="user preferences")
- Mem0Memory_add(facts=["The user prefers answers in Italian"])

Fields:

Validators:

  • _set_defaults
Source code in src/ant_ai/memory/backends/mem0.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class Mem0Memory(Memory):
    """
    Long-term memory kept by the mem0 cloud service, searched by meaning.

    Requires MEM0_API_KEY in the environment, or pass ``api_key`` explicitly.
    Memories are kept per `ctx.user_id`, or per `ctx.session_id` when there is no
    user.

    Example:
        ```python
        from ant_ai.agent import Agent
        from ant_ai.memory.backends.mem0 import Mem0Memory

        agent = Agent(memory=Mem0Memory(), ...)
        ```

        The agent can now call:

            - Mem0Memory_search(query="user preferences")
            - Mem0Memory_add(facts=["The user prefers answers in Italian"])
    """

    api_key: str | None = Field(default=None)
    top_k: int = Field(default=5, ge=1, description="Most memories one search returns.")
    _client: Any = PrivateAttr()

    @model_validator(mode="after")
    def _init_client(self) -> Mem0Memory:
        self._client: AsyncMemoryClient = (
            AsyncMemoryClient(api_key=self.api_key)
            if self.api_key
            else AsyncMemoryClient()
        )
        return self

    async def search(
        self, query: str, ctx: InvocationContext | None = None
    ) -> list[str]:
        """Search long-term memory for facts relevant to `query`. Call this
        whenever recalling something about the user or a past conversation
        would help answer the current request."""
        filters: dict[str, str] = _resolve_scope(ctx)
        options = SearchMemoryOptions(filters=filters, top_k=self.top_k)
        results: Any = await self._client.search(query, options=options)
        return [r["memory"] for r in results.get("results", []) if r.get("memory")]

    async def add(self, facts: list[str], ctx: InvocationContext | None = None) -> str:
        """Persist one or more durable facts (user preferences, personal
        details, explicit "remember this" instructions) for future
        conversations. Call this proactively as soon as you learn something
        worth keeping — do not wait to be asked, and do not wait until the
        end of the conversation."""
        facts = [f for f in facts if f]
        if not facts:
            return "Nothing to save."
        filters: dict[str, str] = _resolve_scope(ctx)
        await self._client.add(
            [{"role": "system", "content": f} for f in facts], **filters
        )
        return f"Saved {len(facts)} fact(s) to memory."

search async

search(
    query: str, ctx: InvocationContext | None = None
) -> list[str]

Search long-term memory for facts relevant to query. Call this whenever recalling something about the user or a past conversation would help answer the current request.

Source code in src/ant_ai/memory/backends/mem0.py
69
70
71
72
73
74
75
76
77
78
async def search(
    self, query: str, ctx: InvocationContext | None = None
) -> list[str]:
    """Search long-term memory for facts relevant to `query`. Call this
    whenever recalling something about the user or a past conversation
    would help answer the current request."""
    filters: dict[str, str] = _resolve_scope(ctx)
    options = SearchMemoryOptions(filters=filters, top_k=self.top_k)
    results: Any = await self._client.search(query, options=options)
    return [r["memory"] for r in results.get("results", []) if r.get("memory")]

add async

add(
    facts: list[str], ctx: InvocationContext | None = None
) -> str

Persist one or more durable facts (user preferences, personal details, explicit "remember this" instructions) for future conversations. Call this proactively as soon as you learn something worth keeping — do not wait to be asked, and do not wait until the end of the conversation.

Source code in src/ant_ai/memory/backends/mem0.py
80
81
82
83
84
85
86
87
88
89
90
91
92
93
async def add(self, facts: list[str], ctx: InvocationContext | None = None) -> str:
    """Persist one or more durable facts (user preferences, personal
    details, explicit "remember this" instructions) for future
    conversations. Call this proactively as soon as you learn something
    worth keeping — do not wait to be asked, and do not wait until the
    end of the conversation."""
    facts = [f for f in facts if f]
    if not facts:
        return "Nothing to save."
    filters: dict[str, str] = _resolve_scope(ctx)
    await self._client.add(
        [{"role": "system", "content": f} for f in facts], **filters
    )
    return f"Saved {len(facts)} fact(s) to memory."