{"record":{"id":"4d39f42d35e9a880","repo":"mem0ai/mem0","slug":"huggingface-embed-batch-returned-len-result-e","errorCode":null,"errorMessage":"HuggingFace embed_batch() returned {len(result)} embeddings for {len(texts)} texts using model '{self.config.model}'","messagePattern":"HuggingFace embed_batch\\(\\) returned (.+?) embeddings for (.+?) texts using model '(.+?)'","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"mem0/embeddings/huggingface.py","lineNumber":62,"sourceCode":"            return self.model.encode(text, convert_to_numpy=True).tolist()\n\n    def embed_batch(self, texts, memory_action=\"add\"):\n        if not texts:\n            return []\n        if self.config.huggingface_base_url:\n            response = self.client.embeddings.create(input=texts, model=self.config.model, **self.config.model_kwargs)\n            sorted_data = sorted(response.data, key=lambda x: x.index)\n            embeddings = [item.embedding for item in sorted_data]\n            if len(embeddings) != len(texts):\n                raise ValueError(\n                    f\"HuggingFace embed_batch() returned {len(embeddings)} embeddings for {len(texts)} texts\"\n                    f\" using model '{self.config.model}'\"\n                )\n            return embeddings\n        else:\n            result = self.model.encode(texts, convert_to_numpy=True).tolist()\n            if len(result) != len(texts):\n                raise ValueError(\n                    f\"HuggingFace embed_batch() returned {len(result)} embeddings for {len(texts)} texts\"\n                    f\" using model '{self.config.model}'\"\n                )\n            return result\n","sourceCodeStart":44,"sourceCodeEnd":67,"githubUrl":"https://github.com/mem0ai/mem0/blob/001c235229be8795e3834520467bd0d661ed8f34/mem0/embeddings/huggingface.py#L44-L67","documentation":"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.","triggerScenarios":"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.","commonSituations":"Feeding unvalidated batch payloads from a queue; wrapping texts in extra brackets ([[\"a\", \"b\"]]); mixing str and non-str inputs.","solutions":["Ensure texts is a flat list[str] before the call: assert all(isinstance(t, str) for t in texts)","Log len(texts) and the texts themselves right before embed_batch to catch nesting introduced upstream","If it persists, reproduce with model.encode directly outside mem0 to isolate the transformation at fault"],"exampleFix":"# before\ntexts = [[\"memory one\", \"memory two\"]]\nembed_batch(texts)\n\n# after\ntexts = [\"memory one\", \"memory two\"]\nembed_batch(texts)","handlingStrategy":"validation","validationCode":"def is_flat_str_list(xs) -> bool:\n    return isinstance(xs, list) and all(isinstance(x, str) for x in xs)\n\nif not is_flat_str_list(texts):\n    texts = [x for sub in texts for x in sub] if all(isinstance(x, list) for x in texts) else list(texts)","typeGuard":"def is_flat_str_list(xs: object) -> bool:\n    return isinstance(xs, list) and bool(xs) and all(isinstance(x, str) and x.strip() for x in xs)","tryCatchPattern":"try:\n    vecs = embedding.embed_batch(texts)\nexcept ValueError as e:\n    if \"embed_batch() returned\" in str(e):\n        raise DataError(\"texts must be a flat list[str]; got nested or non-str items\") from e\n    raise","preventionTips":["Assert flat list[str] inputs at the boundary where batches enter your code","Convert pandas/numpy iterables to plain lists of str before embedding"],"tags":["huggingface","sentence-transformers","embeddings","batch","data-integrity"],"backgroundTag":null,"analyzedSha":"001c235229be8795e3834520467bd0d661ed8f34","analyzedAt":"2026-08-15T01:55:42.685Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}