{"record":{"id":"972e96817b2dd449","repo":"langchain-ai/langchain","slug":"the-number-of-metadatas-must-match-the-number-of-t","errorCode":null,"errorMessage":"The number of metadatas must match the number of texts.Got {len(metadatas)} metadatas and {len(texts_)} texts.","messagePattern":"The number of metadatas must match the number of texts\\.Got (.+?) metadatas and (.+?) texts\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"libs/core/langchain_core/vectorstores/base.py","lineNumber":84,"sourceCode":"            List of IDs from adding the texts into the `VectorStore`.\n\n        Raises:\n            ValueError: If the number of metadatas does not match the number of texts.\n            ValueError: If the number of IDs does not match the number of texts.\n        \"\"\"\n        if type(self).add_documents != VectorStore.add_documents:\n            # This condition is triggered if the subclass has provided\n            # an implementation of the upsert method.\n            # The existing add_texts\n            texts_: Sequence[str] = (\n                texts if isinstance(texts, (list, tuple)) else list(texts)\n            )\n            if metadatas and len(metadatas) != len(texts_):\n                msg = (\n                    \"The number of metadatas must match the number of texts.\"\n                    f\"Got {len(metadatas)} metadatas and {len(texts_)} texts.\"\n                )\n                raise ValueError(msg)\n            metadatas_ = iter(metadatas) if metadatas else cycle([{}])\n            ids_: Iterator[str | None] = iter(ids) if ids else cycle([None])\n            docs = [\n                Document(id=id_, page_content=text, metadata=metadata_)\n                for text, metadata_, id_ in zip(texts, metadatas_, ids_, strict=False)\n            ]\n            if ids is not None:\n                # For backward compatibility\n                kwargs[\"ids\"] = ids\n\n            return self.add_documents(docs, **kwargs)\n        msg = f\"`add_texts` has not been implemented for {self.__class__.__name__} \"\n        raise NotImplementedError(msg)\n\n    @property\n    def embeddings(self) -> Embeddings | None:\n        \"\"\"Access the query embedding object if available.\"\"\"\n        logger.debug(","sourceCodeStart":66,"sourceCodeEnd":102,"githubUrl":"https://github.com/langchain-ai/langchain/blob/e32fa9a52eab3b61ad7a45399bfde59b3e580fc4/libs/core/langchain_core/vectorstores/base.py#L66-L102","documentation":"Raised by the base `VectorStore.add_texts` compatibility shim when the subclass implements `add_documents`/`upsert` (so the shim converts texts+metadatas into `Document` objects) but the supplied `metadatas` list length differs from the number of `texts`. Each text must map one-to-one onto a metadata dict, otherwise `Document` construction would be ambiguous.","triggerScenarios":"Calling `vectorstore.add_texts(texts=[...n items...], metadatas=[...m items...])` with `m != n` on a store that only overrides `add_documents`. Generator inputs are materialized first, so lazy iterators with unexpected lengths also trigger it.","commonSituations":"Building metadata in a separate comprehension that skips rows (e.g. filtering empty metadata) so lengths drift; passing a single metadata dict instead of a list of dicts; chunking text without chunking metadata correspondingly.","solutions":["Make `metadatas` exactly one entry per text: `assert len(metadatas) == len(texts)` before the call and fix the producer.","If all texts share metadata, either omit `metadatas` or expand it: `metadatas=[meta] * len(texts)`.","Pair them at construction: `metadatas = [{'source': s} for s in sources]` built from the same iterable that produced `texts`."],"exampleFix":"# before\ntexts = [d.page_content for d in docs]\nmetadatas = [m for m in raw_metadata if m]  # filtered -> length mismatch\nstore.add_texts(texts, metadatas)\n\n# after\ntexts = [d.page_content for d in docs]\nmetadatas = [d.metadata for d in docs]  # 1:1 with texts\nstore.add_texts(texts, metadatas)","handlingStrategy":"validation","validationCode":"def prepare_batch(texts, metadatas):\n    if metadatas is not None and len(list(metadatas)) != len(list(texts)):\n        raise ValueError(f\"texts ({len(texts)}) and metadatas ({len(metadatas)}) must align\")\n    return texts, metadatas","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Derive `texts` and `metadatas` from the same documents list so they cannot drift.","Add an assert on lengths in ingestion helpers before calling the store.","Prefer `add_documents(docs)` over `add_texts(texts, metadatas)` — the pairing is structural."],"tags":["vector-store","validation","ingestion"],"backgroundTag":null,"analyzedSha":"e32fa9a52eab3b61ad7a45399bfde59b3e580fc4","analyzedAt":"2026-08-14T18:42:09.092Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}