mem0ai/mem0 · error · ValueError

Gemini embed_batch() returned {len(all_embeddings)} embeddin

Error message

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

What it means

GeminiEmbedding.embed_batch chunks texts into batches of 100, calls models.embed_content via the google-genai SDK, and extends all_embeddings from response.embeddings. A final count check requires one embedding per input text; a mismatch raises this ValueError naming the model. In practice the usual cause is batch_items_per_request / API limits causing the SDK to return fewer embedding entries, or empty input strings being dropped.

Source

Thrown at mem0/embeddings/gemini.py:52

        config = types.EmbedContentConfig(output_dimensionality=self.config.embedding_dims)

        # Call the embed_content method with the correct parameters
        response = self.client.models.embed_content(model=self.config.model, contents=text, config=config)

        return response.embeddings[0].values

    def embed_batch(self, texts, memory_action="add"):
        if not texts:
            return []
        config = types.EmbedContentConfig(output_dimensionality=self.config.embedding_dims)
        MAX_BATCH = 100
        all_embeddings = []
        for i in range(0, len(texts), MAX_BATCH):
            chunk = [t.replace("\n", " ") for t in texts[i : i + MAX_BATCH]]
            response = self.client.models.embed_content(model=self.config.model, contents=chunk, config=config)
            all_embeddings.extend(e.values for e in response.embeddings)
        if len(all_embeddings) != len(texts):
            raise ValueError(
                f"Gemini embed_batch() returned {len(all_embeddings)} embeddings for {len(texts)} texts "
                f"using model '{self.config.model}'"
            )
        return all_embeddings

View on GitHub (pinned to 001c235229)

Solutions

  1. Filter empty/whitespace strings from the batch before calling embed_batch
  2. Lower MAX_BATCH / split your input list into smaller chunks (e.g. ≤ 100 texts or fewer tokens per chunk)
  3. Log the failing chunk boundaries and retry just that chunk to identify the problematic input

Example fix

# before
texts = ["", "hello", "   "]
embedding.embed_batch(texts)

# after
texts = [t for t in texts if t.strip()]
embedding.embed_batch(texts)
Defensive patterns

Strategy: validation

Validate before calling

clean = [t for t in texts if t and t.strip()]
if not clean:
    raise ValueError("nothing to embed")
# chunk defensively below API batch limits
chunks = [clean[i:i+50] for i in range(0, len(clean), 50)]

Type guard

def is_embeddable_batch(xs: list[str]) -> bool:
    return 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):
        vecs = [embedding.embed(t) for t in texts]  # fall back to per-item calls
    else:
        raise

Prevention

When it happens

Trigger: Passing a list containing empty strings (the API may return no vector for them); a chunk larger than the model's per-request item or token budget returning partial results; model output_dimensionality misconfigured so some entries are omitted.

Common situations: Batching user memories where some cleaned to ''; using gemini-embedding-001 with batch sizes near API limits; version differences in the google-genai SDK silently truncating large responses.

Related errors


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