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
- 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))].
- 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.
- 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.
- 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
- Derive ids from the documents collection itself (same comprehension) instead of maintaining a parallel list.
- Prefer setting Document(id=...) over a separate ids argument so ids cannot drift from documents.
- When batching, slice ids with the same slice bounds as documents: docs_batch, ids_batch = documents[i:i+n], ids[i:i+n].
- Assert length equality before the call so you fail before paying for embeddings.
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
- IDs must be provided for deletion
- numpy must be installed to use max_marginal_relevance_search
- Number of columns in X and Y must be the same. X has shape {
- invalid IP address
- Failed to resolve hostname '{hostname}': {e}
AI-assisted analysis of langchain-ai/langchain@e32fa9a52e (2026-08-14).
Data as JSON: /api/errors/0d9f1faa1ff9bceb.
Report an issue: GitHub.