mem0ai/mem0 · error · Exception

Insert failed for document {doc.get('id')}: {doc}

Error message

Insert failed for document {doc.get('id')}: {doc}

What it means

Raised by AzureAISearch.insert after search_client.upload_documents returns: the code inspects each IndexedDocument and raises when the response indicates the document was not uploaded with status 201. Typical causes are stale index schema (dimension/field mismatch), throttling (207/429), auth issues, or a payload field that violates the index definition. Note the guard 'not hasattr(doc, "status_code") and doc.get(...) != 201' only fires for dict-like responses lacking the attribute, so some real failures can be silently swallowed — treat any raise here as a genuine server-side rejection.

Source

Thrown at mem0/vector_stores/azure_ai_search.py:189

    # Note: Explicit "insert" calls may later be decoupled from memory management decisions.
    def insert(self, vectors, payloads=None, ids=None):
        """
        Insert vectors into the index.

        Args:
            vectors (List[List[float]]): List of vectors to insert.
            payloads (List[Dict], optional): List of payloads corresponding to vectors.
            ids (List[str], optional): List of IDs corresponding to vectors.
        """
        logger.info(f"Inserting {len(vectors)} vectors into index {self.index_name}")
        documents = [
            self._generate_document(vector, payload, id) for id, vector, payload in zip(ids, vectors, payloads)
        ]
        response = self.search_client.upload_documents(documents)
        for doc in response:
            if not hasattr(doc, "status_code") and doc.get("status_code") != 201:
                raise Exception(f"Insert failed for document {doc.get('id')}: {doc}")
        return response

    def _sanitize_key(self, key: str) -> str:
        return re.sub(r"[^\w]", "", key)

    def _build_filter_expression(self, filters):
        filter_conditions = []
        for key, value in filters.items():
            safe_key = self._sanitize_key(key)
            if isinstance(value, str):
                safe_value = value.replace("'", "''")
                condition = f"{safe_key} eq '{safe_value}'"
            elif isinstance(value, bool):
                condition = f"{safe_key} eq {str(value).lower()}"
            elif isinstance(value, (int, float)):
                condition = f"{safe_key} eq {value}"
            else:
                raise ValueError(

View on GitHub (pinned to 001c235229)

Solutions

  1. Inspect the doc dict in the exception: status_code 400 → schema mismatch, 429 → throttling, 403 → auth
  2. If dimensions changed, delete and recreate the index (drop the collection_name or create a new one) so create_col rebuilds it
  3. For 429: reduce batch size / add retry with exponential backoff around memory.add()
  4. Verify service_name and api_key in vector_store config and that the index exists in the portal

Example fix

# before
memory.add("...", user_id="u1")  # Insert failed for document ...

# after (dimension changed): recreate index with the new dims
cfg = {
  "vector_store": {"provider": "azure_ai_search", "config": {
    "service_name": "svc", "collection_name": "mem0_idx_v2",
    "api_key": key, "embedding_model_dims": 1536}}
}
memory = Memory.from_config(cfg)
Defensive patterns

Strategy: retry

Validate before calling

# before add(): confirm index dims match the embedder
emb_dims = 1536  # from your embedder
# AzureAISearch stores embedding_model_dims at init; recreate index if it differs
if existing_index_dim is not None and existing_index_dim != emb_dims:
    raise ConfigError(f'dimension drift: index={existing_index_dim}, embedder={emb_dims}; recreate index')

Try / catch

import time
for attempt in range(5):
    try:
        memory.add(msg, user_id=uid)
        break
    except Exception as e:
        if 'Insert failed for document' in str(e) and attempt < 4:
            time.sleep(2 ** attempt)
            continue
        raise

Prevention

When it happens

Trigger: Calling memory.add() with azure_ai_search configured after switching embedding models so vector dimensions no longer match the existing index's vector field; uploading documents whose payload JSON exceeds field constraints; hitting Azure throttling limits on bulk adds; index deleted/recreated with different schema while the client cached the old one.

Common situations: Changing embedder model (e.g. text-embedding-3-small 1536 → another dim) without recreating the Azure index; bursty workloads exceeding the service's QPS; service name/api key misconfigured; index field 'payload' redefined as non-collection(Edm.String).

Related errors


AI-assisted analysis of mem0ai/mem0@001c235229 (2026-08-15). Data as JSON: /api/errors/137e17f3559795bd. Report an issue: GitHub.