mem0ai/mem0 · error · ValueError

HuggingFace embed_batch() returned {len(result)} embeddings

Error message

HuggingFace embed_batch() returned {len(result)} embeddings for {len(texts)} texts using model '{self.config.model}'

What it means

The second raise in HuggingFaceEmbedding.embed_batch covers the local path: no huggingface_base_url, so sentence-transformers model.encode(texts) runs locally. If the numpy result converted to lists does not have exactly one vector per input text, this ValueError fires. Local encode virtually always returns the right count, so hitting it usually indicates an upstream transformation bug (e.g. texts accidentally nested or an ndarray squeeze) rather than model behavior.

Source

Thrown at mem0/embeddings/huggingface.py:62

            return self.model.encode(text, convert_to_numpy=True).tolist()

    def embed_batch(self, texts, memory_action="add"):
        if not texts:
            return []
        if self.config.huggingface_base_url:
            response = self.client.embeddings.create(input=texts, model=self.config.model, **self.config.model_kwargs)
            sorted_data = sorted(response.data, key=lambda x: x.index)
            embeddings = [item.embedding for item in sorted_data]
            if len(embeddings) != len(texts):
                raise ValueError(
                    f"HuggingFace embed_batch() returned {len(embeddings)} embeddings for {len(texts)} texts"
                    f" using model '{self.config.model}'"
                )
            return embeddings
        else:
            result = self.model.encode(texts, convert_to_numpy=True).tolist()
            if len(result) != len(texts):
                raise ValueError(
                    f"HuggingFace embed_batch() returned {len(result)} embeddings for {len(texts)} texts"
                    f" using model '{self.config.model}'"
                )
            return result

View on GitHub (pinned to 001c235229)

Solutions

  1. Ensure texts is a flat list[str] before the call: assert all(isinstance(t, str) for t in texts)
  2. Log len(texts) and the texts themselves right before embed_batch to catch nesting introduced upstream
  3. If it persists, reproduce with model.encode directly outside mem0 to isolate the transformation at fault

Example fix

# before
texts = [["memory one", "memory two"]]
embed_batch(texts)

# after
texts = ["memory one", "memory two"]
embed_batch(texts)
Defensive patterns

Strategy: validation

Validate before calling

def is_flat_str_list(xs) -> bool:
    return isinstance(xs, list) and all(isinstance(x, str) for x in xs)

if not is_flat_str_list(texts):
    texts = [x for sub in texts for x in sub] if all(isinstance(x, list) for x in texts) else list(texts)

Type guard

def is_flat_str_list(xs: object) -> bool:
    return isinstance(xs, list) and bool(xs) and all(isinstance(x, str) and x.strip() for x in xs)

Try / catch

try:
    vecs = embedding.embed_batch(texts)
except ValueError as e:
    if "embed_batch() returned" in str(e):
        raise DataError("texts must be a flat list[str]; got nested or non-str items") from e
    raise

Prevention

When it happens

Trigger: Passing a list whose elements are themselves lists (encode flattens or errors differently); post-processing code that reshapes the result before the check; passing a pandas Series whose values behave unexpectedly; extremely long sequences truncated by model max_seq_length with return_dict semantics.

Common situations: Feeding unvalidated batch payloads from a queue; wrapping texts in extra brackets ([["a", "b"]]); mixing str and non-str inputs.

Related errors


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