{"record":{"id":"61c683044f5b6794","repo":"langchain-ai/langchain","slug":"maximal-marginal-relevance-requires-numpy-to-be-in","errorCode":null,"errorMessage":"maximal_marginal_relevance requires numpy to be installed. Please install numpy with `pip install numpy`.","messagePattern":"maximal_marginal_relevance requires numpy to be installed\\. Please install numpy with `pip install numpy`\\.","errorType":"exception","errorClass":"ImportError","httpStatus":null,"severity":"error","filePath":"libs/core/langchain_core/vectorstores/utils.py","lineNumber":137,"sourceCode":"\n    Args:\n        query_embedding: The query embedding.\n        embedding_list: A list of embeddings.\n        lambda_mult: The lambda parameter for MMR.\n        k: The number of embeddings to return.\n\n    Returns:\n        A list of indices of the embeddings to return.\n\n    Raises:\n        ImportError: If numpy is not installed.\n    \"\"\"\n    if not _HAS_NUMPY:\n        msg = (\n            \"maximal_marginal_relevance requires numpy to be installed. \"\n            \"Please install numpy with `pip install numpy`.\"\n        )\n        raise ImportError(msg)\n\n    if min(k, len(embedding_list)) <= 0:\n        return []\n    if query_embedding.ndim == 1:\n        query_embedding = np.expand_dims(query_embedding, axis=0)\n    similarity_to_query = _cosine_similarity(query_embedding, embedding_list)[0]\n    most_similar = int(np.argmax(similarity_to_query))\n    idxs = [most_similar]\n    selected = np.array([embedding_list[most_similar]])\n    while len(idxs) < min(k, len(embedding_list)):\n        best_score = -np.inf\n        idx_to_add = -1\n        similarity_to_selected = _cosine_similarity(embedding_list, selected)\n        for i, query_score in enumerate(similarity_to_query):\n            if i in idxs:\n                continue\n            redundant_score = max(similarity_to_selected[i])\n            equation_score = (","sourceCodeStart":119,"sourceCodeEnd":155,"githubUrl":"https://github.com/langchain-ai/langchain/blob/e32fa9a52eab3b61ad7a45399bfde59b3e580fc4/libs/core/langchain_core/vectorstores/utils.py#L119-L155","documentation":"langchain_core.vectorstores.utils.maximal_marginal_relevance raises this ImportError when numpy is not installed. MMR alternates between cosine-similarity and diversity computations implemented with numpy (argmax, array arithmetic), so the _HAS_NUMPY guard at the top of the function aborts immediately. This is the underlying dependency behind InMemoryVectorStore.max_marginal_relevance_search raising the equivalent error (error 462), so the two surface together in numpy-less environments.","triggerScenarios":"Calling maximal_marginal_relevance(query_embedding, embedding_list, k, lambda_mult) directly (custom retriever/reranker code), or indirectly through any vectorstore's max_marginal_relevance_search, in an environment where numpy failed to import. The call fails on the first line of the function regardless of arguments.","commonSituations":"Custom retrievers that hand-roll MMR reranking over fetched candidates; environments slimmed to exclude numpy (serverless, Alpine-based images) where similarity_search worked but switching the retriever's search_type to 'mmr' broke; local dev on a managed interpreter without build tools where numpy was silently never installed.","solutions":["Install numpy: pip install numpy (add it to the project's pinned dependencies so every environment gets it).","If you use the simsimd fast path too, install simsimd as well — but numpy alone satisfies this guard.","If numpy is intentionally absent, replace MMR selection with plain top-k selection (sort by cosine similarity) — no numpy needed — accepting less diverse results.","At startup, probe availability (try: import numpy) and configure search_type='similarity' instead of 'mmr' when it is missing."],"exampleFix":"// before\nfrom langchain_core.vectorstores.utils import maximal_marginal_relevance\nidxs = maximal_marginal_relevance(q_emb, cand_embs, k=4)  # ImportError\n\n// after\n// shell: pip install numpy\nfrom langchain_core.vectorstores.utils import maximal_marginal_relevance\nidxs = maximal_marginal_relevance(q_emb, cand_embs, 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(\"maximal_marginal_relevance requires numpy; pip install numpy\")","typeGuard":"def mmr_available() -> bool:\n    \"\"\"True when numpy is importable, i.e. maximal_marginal_relevance is usable.\"\"\"\n    try:\n        import numpy  # noqa: F401\n    except ImportError:\n        return False\n    return True","tryCatchPattern":"try:\n    idxs = maximal_marginal_relevance(query_embedding, embedding_list, k=k, lambda_mult=0.5)\nexcept ImportError as e:\n    if \"requires numpy\" in str(e):\n        # pure-python fallback: plain top-k by score order already present\n        idxs = list(range(min(k, len(embedding_list))))\n    else:\n        raise","preventionTips":["Declare numpy as a hard dependency in projects using MMR utilities or search_type='mmr'.","Feature-detect numpy at startup and choose the reranking strategy based on it.","Cover the MMR code path in CI with the production dependency set installed.","Keep a pure-python top-k fallback implemented and tested in case numpy is unavailable."],"tags":["dependencies","numpy","mmr","vectorstore","utils","optional-import"],"backgroundTag":null,"analyzedSha":"e32fa9a52eab3b61ad7a45399bfde59b3e580fc4","analyzedAt":"2026-08-14T18:42:09.092Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}