{"record":{"id":"e7026d383ba4d9c6","repo":"langchain-ai/langchain","slug":"numpy-must-be-installed-to-use-max-marginal-releva","errorCode":null,"errorMessage":"numpy must be installed to use max_marginal_relevance_search pip install numpy","messagePattern":"numpy must be installed to use max_marginal_relevance_search pip install numpy","errorType":"exception","errorClass":"ImportError","httpStatus":null,"severity":"error","filePath":"libs/core/langchain_core/vectorstores/in_memory.py","lineNumber":440,"sourceCode":"        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        *,\n        filter: Callable[[Document], bool] | None = None,\n        **kwargs: Any,\n    ) -> list[Document]:\n        prefetch_hits = self._similarity_search_with_score_by_vector(\n            embedding=embedding,\n            k=fetch_k,\n            filter=filter,\n        )\n\n        if not _HAS_NUMPY:\n            msg = (\n                \"numpy must be installed to use max_marginal_relevance_search \"\n                \"pip install numpy\"\n            )\n            raise ImportError(msg)\n\n        mmr_chosen_indices = maximal_marginal_relevance(\n            np.array(embedding, dtype=np.float32),\n            [vector for _, _, vector in prefetch_hits],\n            k=k,\n            lambda_mult=lambda_mult,\n        )\n        return [prefetch_hits[idx][0] for idx in mmr_chosen_indices]\n\n    @override\n    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> list[Document]:","sourceCodeStart":422,"sourceCodeEnd":458,"githubUrl":"https://github.com/langchain-ai/langchain/blob/e32fa9a52eab3b61ad7a45399bfde59b3e580fc4/libs/core/langchain_core/vectorstores/in_memory.py#L422-L458","documentation":"InMemoryVectorStore.max_marginal_relevance_search (via its internal MMR helper) raises this ImportError when numpy is not installed in the environment. numpy is an optional dependency for langchain-core vectorstores: plain similarity_search works without it, but maximal-marginal-relevance reranking needs numpy math (via maximal_marginal_relevance), so the import flag _HAS_NUMPY gates it. The check occurs after the prefetch similarity search has already run, so k candidate hits are fetched before the error surfaces.","triggerScenarios":"Calling store.max_marginal_relevance_search(query, k=..., fetch_k=...) (or max_marginal_relevance_search_with_score) in an environment where `import numpy` failed — e.g. a minimal container or lambda image that installed langchain-core without the numpy extra. The prefetch _similarity_search_with_score_by_vector succeeds (pure Python), then _HAS_NUMPY is False and the ImportError fires.","commonSituations":"Slim Docker/lambda deployments that pip-install langchain without numpy to reduce image size; adding MMR search to code that originally only used similarity_search (which worked fine without numpy); CI environments with a trimmed dependency set where tests for MMR suddenly fail after a refactor.","solutions":["Install numpy in the environment: pip install numpy (or add numpy to the deployment's requirements).","If image size allowed the omission, install a prebuilt numpy wheel rather than excluding it; MMR reranking has no numpy-free fallback in this code path.","If numpy cannot be added, switch the call to store.similarity_search(query, k=k) which needs no numpy, accepting no diversity reranking.","Feature-detect up front (import numpy in a try/except at startup) and disable/configure MMR search off when unavailable, so the failure is explicit rather than mid-request."],"exampleFix":"// before\nresults = store.max_marginal_relevance_search(query, k=4, fetch_k=20)  # ImportError without numpy\n\n// after (option 1: install dependency)\n// pip install numpy\nresults = store.max_marginal_relevance_search(query, k=4, fetch_k=20)\n\n// after (option 2: degrade gracefully)\nfrom langchain_core.vectorstores import InMemoryVectorStore\ntry:\n    import numpy  # noqa: F401\n    results = store.max_marginal_relevance_search(query, k=4, fetch_k=20)\nexcept ImportError:\n    results = store.similarity_search(query, k=4)","handlingStrategy":"fallback","validationCode":"try:\n    import numpy  # noqa: F401\n    HAS_NUMPY = True\nexcept ImportError:\n    HAS_NUMPY = False\n\nif not HAS_NUMPY:\n    raise RuntimeError(\"max_marginal_relevance_search requires numpy; pip install numpy\")","typeGuard":"def supports_mmr() -> bool:\n    \"\"\"True when numpy is importable, i.e. MMR search is usable.\"\"\"\n    try:\n        import numpy  # noqa: F401\n    except ImportError:\n        return False\n    return True","tryCatchPattern":"try:\n    results = store.max_marginal_relevance_search(query, k=4, fetch_k=20)\nexcept ImportError as e:\n    if \"numpy\" in str(e):\n        logger.warning(\"numpy missing; falling back to similarity_search\")\n        results = store.similarity_search(query, k=4)\n    else:\n        raise","preventionTips":["Pin numpy in the deployment's dependency file whenever you use MMR search — it is not optional there.","Probe numpy availability at startup and configure search_type ('mmr' vs 'similarity') accordingly.","Include an MMR call in CI smoke tests so a trimmed environment fails at build time, not in production.","Document in the service's README/Dockerfile that MMR requires numpy."],"tags":["dependencies","numpy","vectorstore","in-memory","mmr","optional-import"],"backgroundTag":null,"analyzedSha":"e32fa9a52eab3b61ad7a45399bfde59b3e580fc4","analyzedAt":"2026-08-14T18:42:09.092Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}