langchain-ai/langchain · error · ValueError

ids must be the same length as texts. Got {len(ids)} ids and

Error message

ids must be the same length as texts. Got {len(ids)} ids and {len(texts)} texts.

What it means

Thrown by InMemoryVectorStore.add_documents when the optional ids list is supplied but its length does not match the number of documents being added. The store requires a one-to-one mapping between documents and ids so each vector can be keyed correctly in self.store. The check runs after embedding, so the embed_documents call still executes (and may cost an API call) before the ValueError is raised.

Source

Thrown at libs/core/langchain_core/vectorstores/in_memory.py:202

    async def adelete(self, ids: Sequence[str] | None = None, **kwargs: Any) -> None:
        self.delete(ids)

    @override
    def add_documents(
        self,
        documents: list[Document],
        ids: list[str] | None = None,
        **kwargs: Any,
    ) -> list[str]:
        texts = [doc.page_content for doc in documents]
        vectors = self.embedding.embed_documents(texts)

        if ids and len(ids) != len(texts):
            msg = (
                f"ids must be the same length as texts. "
                f"Got {len(ids)} ids and {len(texts)} texts."
            )
            raise ValueError(msg)

        id_iterator: Iterator[str | None] = (
            iter(ids) if ids else iter(doc.id for doc in documents)
        )

        ids_ = []

        for doc, vector in zip(documents, vectors, strict=False):
            doc_id = next(id_iterator)
            doc_id_ = doc_id or str(uuid.uuid4())
            ids_.append(doc_id_)
            self.store[doc_id_] = {
                "id": doc_id_,
                "vector": vector,
                "text": doc.page_content,
                "metadata": doc.metadata,
            }

View on GitHub (pinned to e32fa9a52e)

Solutions

  1. Make ids match the batch exactly: build ids in the same comprehension/loop that builds documents, e.g. ids = [f'doc-{i}' for i in range(len(documents))].
  2. If you want automatic id generation, pass ids=None (or omit it) so the store falls back to doc.id or a generated uuid4 per document.
  3. Set an explicit id on each Document (Document(page_content=..., id=...)) instead of passing a separate ids list, keeping ids and documents coupled by construction.
  4. Add an assertion before the call: assert ids is None or len(ids) == len(documents), to fail before the embedding step rather than after it.

Example fix

// before
ids = ["a", "b", "c"]
store.add_documents(docs_of_length_5, ids=ids)  # ValueError

// after
ids = [f"doc-{i}" for i in range(len(docs))]
store.add_documents(docs, ids=ids)
Defensive patterns

Strategy: validation

Validate before calling

def validate_add_documents(documents: list, ids: list[str] | None) -> None:
    if ids is not None and len(ids) != len(documents):
        msg = f"ids length {len(ids)} != documents length {len(documents)}"
        raise ValueError(msg)

Type guard

from typing import TypeGuard
from langchain_core.documents import Document

def has_matching_ids(documents: list[Document], ids: object) -> TypeGuard[list[str]]:
    return isinstance(ids, list) and len(ids) == len(documents) and all(isinstance(i, str) for i in ids)

Try / catch

try:
    store.add_documents(documents, ids=ids)
except ValueError as e:
    if "ids must be the same length as texts" in str(e):
        logger.error("ids/documents length mismatch: %s vs %s", len(ids or []), len(documents))
        ids = None  # fall back to doc.id / uuid generation
        store.add_documents(documents, ids=ids)
    else:
        raise

Prevention

When it happens

Trigger: Calling add_documents(documents, ids=[...]) where len(ids) != len(documents). Note the guard is `if ids and len(ids) != len(texts)`: passing an empty list ([]) is treated as falsy and falls back to document ids/uuids, so the error only fires for a non-empty ids list of the wrong length. Also reachable via add_texts-style wrappers or VectorStore.from_documents-style helpers that forward a mismatched ids argument.

Common situations: Appending new documents to an existing ids list but forgetting to extend it; batching documents into chunks (e.g. via chunking or parallel loops) while reusing the full-length ids list per batch; off-by-one when constructing ids with list comprehension ranges; refactoring from add_texts (where ids aligned with strings) to add_documents without resizing ids.

Related errors


AI-assisted analysis of langchain-ai/langchain@e32fa9a52e (2026-08-14). Data as JSON: /api/errors/0d9f1faa1ff9bceb. Report an issue: GitHub.