---
title: "Python Client SDK"
description: "The Python Client SDK (MemoryClient and AsyncMemoryClient) provides a structured interface for communicating with the Mem0 Platform API, handling authentication, request routing, telemetry instrume..."
last_updated: "2026-10-11T17:37:10.294005+00:00"
canonical_url: "https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/python-core/python-client-sdk"
---

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [mem0/client/main.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/main.py)
- [integrations/hermes-plugin-mem0/__init__.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/hermes-plugin-mem0/__init__.py)
- [integrations/opencode-plugin/opencode-mem0.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/opencode-plugin/opencode-mem0.ts)
- [mem0-ts/src/client/mem0.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/client/mem0.ts)
- [integrations/mem0-strands/python/src/mem0_strands/client.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/mem0-strands/python/src/mem0_strands/client.py)
- [cli/python/src/mem0_cli/app.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/cli/python/src/mem0_cli/app.py)
- [integrations/antigravity-plugin/core/memory_cli.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/antigravity-plugin/core/memory_cli.py)
- [integrations/agent-plugin-core/python/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/python/memory_core.py)
- [integrations/agent-plugin-core/python/memory_cli.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/python/memory_cli.py)
- [mem0/client/__init__.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/__init__.py)
- [integrations/mem0-agent-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/mem0-agent-plugin/core/memory_core.py)
- [integrations/antigravity-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/antigravity-plugin/core/memory_core.py)
- [cli/python/src/mem0_cli/backend/platform.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/cli/python/src/mem0_cli/backend/platform.py)
- [mem0/memory/main.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/memory/main.py)
- [cli/python/src/mem0_cli/__main__.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/cli/python/src/mem0_cli/__main__.py)
- [integrations/kimi-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/kimi-plugin/core/memory_core.py)
- [integrations/codex-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/codex-plugin/core/memory_core.py)
- [integrations/cursor-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/cursor-plugin/core/memory_core.py)
- [mem0/client/project.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/project.py)
- [server/main.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/server/main.py)
- [mem0/__init__.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/__init__.py)
- [integrations/mem0-strands/python/src/mem0_strands/__init__.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/mem0-strands/python/src/mem0_strands/__init__.py)
- [integrations/agent-plugin-core/python/mcp_server.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/python/mcp_server.py)
- [integrations/hermes-plugin-mem0/_backend.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/hermes-plugin-mem0/_backend.py)
- [integrations/antigravity-plugin/core/mcp_server.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/antigravity-plugin/core/mcp_server.py)
- [mem0-ts/src/community/src/integrations/langchain/mem0.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts)
- [cli/python/src/mem0_cli/commands/__init__.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/cli/python/src/mem0_cli/commands/__init__.py)
- [cli/python/src/mem0_cli/backend/__init__.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/cli/python/src/mem0_cli/backend/__init__.py)
- [cli/python/src/mem0_cli/__init__.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/cli/python/src/mem0_cli/__init__.py)
- [mem0/client/types.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/types.py)
</details>

## Overview

The Python Client SDK (`MemoryClient` and `AsyncMemoryClient`) provides a structured interface for communicating with the Mem0 Platform API, handling authentication, request routing, telemetry instrumentation, and error translation. It supports synchronous and asynchronous CRUD workflows, batch operations, and search filters through Pydantic request models.

Sources: [mem0/client/main.py:1-32](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/main.py#L1-L32), [mem0/__init__.py:1-6](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/__init__.py#L1-L6), [mem0/client/types.py:1-12](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/types.py#L1-L12)

## Client Initialization and Configuration

### Client Setup and Header Management

The Mem0 Python client SDK provides public client classes (`MemoryClient` and `AsyncMemoryClient`) designed to interface with the Mem0 Platform API. During initialization, the client configures host routing, validates credentials, and constructs custom HTTP headers for request tracing.

The header composition mechanism relies on a set-once and append-only contract to preserve caller identity across wrapped execution layers. Headers such as `X-Mem0-Source` and `X-Application` follow a set-once rule where outer layers retain their values, whereas `X-Mem0-Client` accumulates client stack entries up to bounded character and entry limits.

```python
MAX_STACK_ENTRIES = 4
MAX_STACK_CHARS = 200
```
Sources: [mem0/client/main.py:152-153](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/main.py#L152-L153)

> [!NOTE]
> The `_bounded_stack` function limits client trace entries by dropping whole entries rather than slicing strings in the middle, ensuring that partial identifiers do not corrupt client stack parsing.
Sources: [mem0/client/main.py:156-175](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/main.py#L156-L175)

### Configuration and Telemetry Constants

Client initialization automatically invokes setup routines and reads runtime variables to govern telemetry behavior and identifier aliasing. The following table outlines core configuration parameters and routing paths defined in the client module.

| Constant Name | Value / Type | Purpose |
| :--- | :--- | :--- |
| `ENTITY_PARAMS` | `frozenset` (`"user_id"`, `"agent_id"`, `"app_id"`, `"run_id"`) | Entity parameters that must be passed via filters rather than top-level arguments. |
| `PROFILE_JOBS_PATH` | `"/v2/profiles/jobs/"` | API endpoint path for profile generation jobs. |
| `PROFILE_SETTINGS_PATH` | `"/v2/profiles/settings/"` | API endpoint path for profile settings synchronization. |
| `MAX_STACK_ENTRIES` | `4` | Maximum number of entries permitted in the `X-Mem0-Client` tracking stack. |
| `MAX_STACK_CHARS` | `200` | Maximum character length allocated for the `X-Mem0-Client` header string. |

Sources: [mem0/client/main.py:41-45](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/main.py#L41-L45), [mem0/client/main.py:152-153](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/main.py#L152-L153)

> [!WARNING]
> Sending `schema` or `custom_instructions` flat in profile settings payloads is rejected by the API with an `Unsupported settings` error; they must be nested under entities.
Sources: [mem0/client/main.py:51-78](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/main.py#L51-L78)

## Remote Memory Operations

### CRUD Workflows and Pydantic Request Models

The client SDK supports comprehensive synchronous and asynchronous CRUD workflows for managing memory records through Pydantic request models defined in `mem0/client/types.py`. Operations such as `add`, `search`, `get_all`, `delete_all`, and `update` accept structured option classes (`AddMemoryOptions`, `SearchMemoryOptions`, `GetAllMemoryOptions`, `DeleteAllMemoryOptions`, and `UpdateMemoryOptions`) alongside arbitrary keyword arguments to ensure runtime validation and IDE autocompletion.

> [!IMPORTANT]
> Identity parameters such as `user_id`, `agent_id`, `app_id`, and `run_id` must be encapsulated within the `filters` dictionary across remote memory operations. Transmitting them at the top level is rejected by the API.
Sources: [mem0/client/types.py:6-99](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/types.py#L6-L99)

### Memory Option Parameters Reference

The following table details the primary Pydantic options models and parameters used across remote memory operations to constrain, filter, and structure payloads.

| Model Name | Parameter Field | Type | Description |
| :--- | :--- | :--- | :--- |
| `AddMemoryOptions` | `filters` | `Optional[Dict[str, Any]]` | Filters containing entity IDs (e.g. `{'user_id': '...'}`). |
| `AddMemoryOptions` | `infer` | `Optional[bool]` | Whether to infer memories from the input. |
| `SearchMemoryOptions` | `top_k` | `Optional[int]` | Number of results to return during search retrieval. |
| `SearchMemoryOptions` | `threshold` | `Optional[float]` | Minimum similarity score threshold for search results. |
| `GetAllMemoryOptions` | `page` | `Optional[int]` | Page number for paginated retrieval. |
| `GetAllMemoryOptions` | `page_size` | `Optional[int]` | Number of items per page for retrieval. |
| `UpdateMemoryOptions` | `text` | `Optional[str]` | New text content for updating an existing memory. |
| `UpdateMemoryOptions` | `expiration_date` | `Optional[str]` | Expiration date in `YYYY-MM-DD` format, or `None` to clear. |

Sources: [mem0/client/types.py:15-107](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/types.py#L15-L107)

### Query Validation and Payload Serialization

Prior to executing remote requests, search queries undergo strict validation and trimming via helper functions in `mem0/client/main.py`. The `_validate_and_trim_search_query` function checks that incoming queries are non-empty strings and strips leading or trailing whitespace, raising a `ValueError` if validation fails. Path segments are encoded safely using `_encode_path_segment`.

```python
def _validate_and_trim_search_query(query: str) -> str:
    if not isinstance(query, str):
        raise ValueError("Invalid query: must be a non-empty string.")
    trimmed = query.strip()
    if not trimmed:
        raise ValueError("Invalid query: cannot be empty or whitespace-only.")
    return trimmed


def _encode_path_segment(value: Any) -> str:
    return quote(str(value), safe="")
```
Sources: [mem0/client/main.py:81-91](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/main.py#L81-L91)

> [!CAUTION]
> Passing non-string or whitespace-only query strings to search operations triggers an immediate `ValueError` before any HTTP request is dispatched to the backend platform.
Sources: [mem0/client/main.py:81-87](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/main.py#L81-L87)

## Project and Organization Scoping

### Project Configuration and Base Interfaces

Multi-tenant project bindings within the Python client SDK are governed by the `ProjectConfig` Pydantic model and the `BaseProject` abstract base class defined in `mem0/client/project.py`. `ProjectConfig` handles configuration validation for project management operations with `extra="forbid"` and assignment validation enabled, encapsulating organization identifiers, project identifiers, and user emails.

```python
class ProjectConfig(BaseModel):
    """
    Configuration for project management operations.
    """

    org_id: Optional[str] = Field(default=None, description="Organization ID")
    project_id: Optional[str] = Field(default=None, description="Project ID")
    user_email: Optional[str] = Field(default=None, description="User email")

    model_config = ConfigDict(validate_assignment=True, extra="forbid")


class BaseProject(ABC):
    """
    Abstract base class for project management operations.
    """

    def __init__(
        self,
        client: Any,
        config: Optional[ProjectConfig] = None,
        org_id: Optional[str] = None,
        project_id: Optional[str] = None,
        user_email: Optional[str] = None,
    ):
```
Sources: [mem0/client/project.py:16-40](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/project.py#L16-L40)

> [!WARNING]
> Initializing `ProjectConfig` with unrecognized extra fields triggers an immediate validation error because `extra="forbid"` is strictly enforced on the configuration model.
Sources: [mem0/client/project.py:16-26](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/project.py#L16-L26)

### Project Configuration Fields Reference

The following table summarizes the configuration fields and types accepted by `ProjectConfig` for project and organization scoping.

| Field Name | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `org_id` | `Optional[str]` | `None` | Organization ID for multi-tenant isolation. |
| `project_id` | `Optional[str]` | `None` | Project ID for scoping memory records. |
| `user_email` | `Optional[str]` | `None` | User email associated with the project scope. |

Sources: [mem0/client/project.py:16-26](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/project.py#L16-L26)

## Client-Side Request Models and Typing

### Pydantic Request Parameter Structures

Type enforcement and runtime validation across SDK request endpoints are implemented through Pydantic base models defined in `mem0/client/types.py`. These models structure payloads for memory addition, retrieval, search, updating, and project configuration adjustments, offering IDE autocompletion and type safety while supporting `**kwargs` fallback for backward compatibility.

> [!NOTE]
> Identity fields including `user_id`, `agent_id`, `app_id`, and `run_id` must be encapsulated within the `filters` dictionary parameter rather than passed at the top level of request options, complying with v2 and v3 API specifications.
Sources: [mem0/client/types.py:6-8](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/types.py#L6-L8)

### Request Options Reference

The following table details the Pydantic request models, parameter fields, types, and descriptions implemented for client-side type enforcement across SDK methods.

| Model Name | Parameter Field | Type | Description |
| :--- | :--- | :--- | :--- |
| `AddMemoryOptions` | `filters` | `Optional[Dict[str, Any]]` | Filters containing entity IDs (e.g. `{'user_id': '...'}`). |
| `AddMemoryOptions` | `metadata` | `Optional[Dict[str, Any]]` | Additional metadata for the memory. |
| `AddMemoryOptions` | `infer` | `Optional[bool]` | Whether to infer memories from the input. |
| `AddMemoryOptions` | `custom_categories` | `Optional[List[Dict[str, Any]]]` | Custom categories for memory classification. |
| `AddMemoryOptions` | `custom_instructions` | `Optional[str]` | Custom instructions for fact extraction. |
| `AddMemoryOptions` | `timestamp` | `Optional[int]` | Unix timestamp for the memory. |
| `AddMemoryOptions` | `expiration_date` | `Optional[str]` | Expiration date in `YYYY-MM-DD` format. |
| `SearchMemoryOptions` | `top_k` | `Optional[int]` | Number of results to return during search. |
| `SearchMemoryOptions` | `rerank` | `Optional[bool]` | Whether to rerank search results. |
| `SearchMemoryOptions` | `threshold` | `Optional[float]` | Minimum similarity score threshold. |
| `SearchMemoryOptions` | `show_expired` | `Optional[bool]` | Whether to include expired memories. |
| `SearchMemoryOptions` | `latest_only` | `Optional[bool]` | Whether to only return the latest memory version. |
| `GetAllMemoryOptions` | `page` | `Optional[int]` | Page number for pagination. |
| `GetAllMemoryOptions` | `page_size` | `Optional[int]` | Number of items per page. |
| `GetAllMemoryOptions` | `start_date` | `Optional[str]` | Filter memories created on or after this date (ISO 8601). |
| `UpdateMemoryOptions` | `text` | `Optional[str]` | New text content for the memory. |
| `UpdateMemoryOptions` | `timestamp` | `Optional[Union[int, float, str]]` | Updated timestamp value. |
| `ProjectUpdateOptions` | `memory_depth` | `Optional[str]` | Memory depth configuration setting. |
| `ProjectUpdateOptions` | `multilingual` | `Optional[bool]` | Whether to enable multilingual support. |

Sources: [mem0/client/types.py:15-121](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/types.py#L15-L121)

## Error Handling and Telemetry Capture

### Exception Wrappers and Status Translation

SDK request execution relies on API error handlers and status translators to catch HTTP failures and convert responses into structured Python exceptions. When requests encounter validation errors, payload rejections, or server faults, the underlying client utility decorators parse response status codes and bodies to raise descriptive client-side exceptions.

```python
def _validate_and_trim_search_query(query: str) -> str:
    if not isinstance(query, str):
        raise ValueError("Invalid query: must be a non-empty string.")
    trimmed = query.strip()
    if not trimmed:
        raise ValueError("Invalid query: cannot be empty or whitespace-only.")
    return trimmed

```
```python
def _validate_and_trim_search_query(query: str) -> str:
    if not isinstance(query, str):
        raise ValueError("Invalid query: must be a non-empty string.")
    trimmed = query.strip()
    if not trimmed:
        raise ValueError("Invalid query: cannot be empty or whitespace-only.")
    return trimmed
```
Sources: [mem0/client/main.py:81-88](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/main.py#L81-L88)

### Telemetry Instrumentation and User Alias Tracking

Client instrumentation monitors operational events, version properties, and user identity mapping through PostHog telemetry hooks. The client captures anonymous IDs and maps them to authenticated email addresses when user sessions are initialized, operating in a best-effort, failure-tolerant mode that prevents telemetry errors from disrupting core memory operations.

```python
def _maybe_alias_anon_to_email(user_email):
    """Fire $identify per prior anon ID so PostHog merges them into email.

    Idempotent via telemetry.aliased_pairs: only writes markers when
    telemetry is actually enabled, so disabling/re-enabling MEM0_TELEMETRY still works.
    Best-effort: never raises.
    """
    if client_telemetry.posthog is None:
        return
    if not user_email or "@" not in user_email:
        return
    try:
        anon_ids = read_anon_ids()
        seen = set()
        for anon_id in (anon_ids.get("oss"), anon_ids.get("cli")):
            if not anon_id or anon_id == user_email or anon_id in seen:
                continue
            seen.add(anon_id)
            if is_aliased(anon_id, user_email):
                continue
            if client_telemetry.capture_identify(anon_id, user_email):
                mark_aliased(anon_id, user_email)
    except Exception as e:
        logger.debug("Failed to alias anon telemetry to %r: %s", user_email, e)

```
```python
def _maybe_alias_anon_to_email(user_email):
    """Fire $identify per prior anon ID so PostHog merges them into email.

    Idempotent via telemetry.aliased_pairs: only writes markers when
    telemetry is actually enabled, so disabling/re-enabling MEM0_TELEMETRY still works.
    Best-effort: never raises.
    """
    if client_telemetry.posthog is None:
        return
    if not user_email or "@" not in user_email:
        return
    try:
        anon_ids = read_anon_ids()
        seen = set()
        for anon_id in (anon_ids.get("oss"), anon_ids.get("cli")):
            if not anon_id or anon_id == user_email or anon_id in seen:
                continue
            seen.add(anon_id)
            if is_aliased(anon_id, user_email):
                continue
            if client_telemetry.capture_identify(anon_id, user_email):
                mark_aliased(anon_id, user_email)
    except Exception as e:
        logger.debug("Failed to alias anon telemetry to %r: %s", user_email, e)
```
Sources: [mem0/client/main.py:94-118](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/main.py#L94-L118)

> [!TIP]
> Telemetry aliasing relies on `telemetry.aliased_pairs` tracking markers to maintain idempotency across sessions, ensuring `$identify` events are dispatched exactly once per unique anonymous identifier without duplicating tracking overhead.
Sources: [mem0/client/main.py:94-98](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/client/main.py#L94-L98)

## Related

- [FastAPI Application](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/server-dashboard/fastapi-application)
- [Typescript Core](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/typescript-core/typescript-core)


## Sitemap

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