Skip to main content
doc0blade47/mem0documentation home
Sign in

Python Client SDK

Last updated Oct 11, 2026100% grounded
Relevant source files

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

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, mem0/init.py:1-6, mem0/client/types.py:1-12

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.

MAX_STACK_ENTRIES = 4
MAX_STACK_CHARS = 200

Sources: mem0/client/main.py:152-153

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

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 NameValue / TypePurpose
ENTITY_PARAMSfrozenset ("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_ENTRIES4Maximum number of entries permitted in the X-Mem0-Client tracking stack.
MAX_STACK_CHARS200Maximum character length allocated for the X-Mem0-Client header string.

Sources: mem0/client/main.py:41-45, mem0/client/main.py:152-153

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

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

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 NameParameter FieldTypeDescription
AddMemoryOptionsfiltersOptional[Dict[str, Any]]Filters containing entity IDs (e.g. {'user_id': '...'}).
AddMemoryOptionsinferOptional[bool]Whether to infer memories from the input.
SearchMemoryOptionstop_kOptional[int]Number of results to return during search retrieval.
SearchMemoryOptionsthresholdOptional[float]Minimum similarity score threshold for search results.
GetAllMemoryOptionspageOptional[int]Page number for paginated retrieval.
GetAllMemoryOptionspage_sizeOptional[int]Number of items per page for retrieval.
UpdateMemoryOptionstextOptional[str]New text content for updating an existing memory.
UpdateMemoryOptionsexpiration_dateOptional[str]Expiration date in YYYY-MM-DD format, or None to clear.

Sources: mem0/client/types.py:15-107

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.

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

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

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.

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

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

Project Configuration Fields Reference

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

Field NameTypeDefaultDescription
org_idOptional[str]NoneOrganization ID for multi-tenant isolation.
project_idOptional[str]NoneProject ID for scoping memory records.
user_emailOptional[str]NoneUser email associated with the project scope.

Sources: mem0/client/project.py:16-26

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

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 NameParameter FieldTypeDescription
AddMemoryOptionsfiltersOptional[Dict[str, Any]]Filters containing entity IDs (e.g. {'user_id': '...'}).
AddMemoryOptionsmetadataOptional[Dict[str, Any]]Additional metadata for the memory.
AddMemoryOptionsinferOptional[bool]Whether to infer memories from the input.
AddMemoryOptionscustom_categoriesOptional[List[Dict[str, Any]]]Custom categories for memory classification.
AddMemoryOptionscustom_instructionsOptional[str]Custom instructions for fact extraction.
AddMemoryOptionstimestampOptional[int]Unix timestamp for the memory.
AddMemoryOptionsexpiration_dateOptional[str]Expiration date in YYYY-MM-DD format.
SearchMemoryOptionstop_kOptional[int]Number of results to return during search.
SearchMemoryOptionsrerankOptional[bool]Whether to rerank search results.
SearchMemoryOptionsthresholdOptional[float]Minimum similarity score threshold.
SearchMemoryOptionsshow_expiredOptional[bool]Whether to include expired memories.
SearchMemoryOptionslatest_onlyOptional[bool]Whether to only return the latest memory version.
GetAllMemoryOptionspageOptional[int]Page number for pagination.
GetAllMemoryOptionspage_sizeOptional[int]Number of items per page.
GetAllMemoryOptionsstart_dateOptional[str]Filter memories created on or after this date (ISO 8601).
UpdateMemoryOptionstextOptional[str]New text content for the memory.
UpdateMemoryOptionstimestampOptional[Union[int, float, str]]Updated timestamp value.
ProjectUpdateOptionsmemory_depthOptional[str]Memory depth configuration setting.
ProjectUpdateOptionsmultilingualOptional[bool]Whether to enable multilingual support.

Sources: mem0/client/types.py:15-121

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.

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 _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

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.

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)
 
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

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

Was this page helpful?