{"record":{"id":"e822c01c02656301","repo":"langchain-ai/langchain","slug":"cosine-similarity-requires-numpy-to-be-installed","errorCode":null,"errorMessage":"cosine_similarity requires numpy to be installed. Please install numpy with `pip install numpy`.","messagePattern":"cosine_similarity 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":59,"sourceCode":"\n    Args:\n        x: A matrix of shape `(n, m)`.\n        y: A matrix of shape `(k, m)`.\n\n    Returns:\n        A matrix of shape `(n, k)` where each element `(i, j)` is the cosine similarity\n            between the `i`th row of `x` and the `j`th row of `y`.\n\n    Raises:\n        ValueError: If the number of columns in `x` and `y` are not the same.\n        ImportError: If numpy is not installed.\n    \"\"\"\n    if not _HAS_NUMPY:\n        msg = (\n            \"cosine_similarity requires numpy to be installed. \"\n            \"Please install numpy with `pip install numpy`.\"\n        )\n        raise ImportError(msg)\n\n    if len(x) == 0 or len(y) == 0:\n        return np.array([[]])\n\n    x = np.array(x)\n    y = np.array(y)\n\n    # Check for NaN\n    if np.any(np.isnan(x)) or np.any(np.isnan(y)):\n        warnings.warn(\n            \"NaN found in input arrays, unexpected return might follow\",\n            category=RuntimeWarning,\n            stacklevel=2,\n        )\n\n    # Check for Inf\n    if np.any(np.isinf(x)) or np.any(np.isinf(y)):\n        warnings.warn(","sourceCodeStart":41,"sourceCodeEnd":77,"githubUrl":"https://github.com/langchain-ai/langchain/blob/e32fa9a52eab3b61ad7a45399bfde59b3e580fc4/libs/core/langchain_core/vectorstores/utils.py#L41-L77","documentation":"langchain_core.vectorstores.utils.cosine_similarity raises this ImportError when numpy is unavailable, because the entire function is implemented on top of numpy arrays (or the optional simsimd backend). It is a hard gate at the top of the function: no partial computation happens. Many higher-level helpers (relevance scoring, some retriever rerankers, utils used by partner vectorstores) call this function, so the error can appear far from your own code.","triggerScenarios":"Importing and calling cosine_similarity(x, y) (directly or through a helper such as maximal_marginal_relevance or a custom retriever's score fusion) in an environment where numpy is not installed. Any non-empty input triggers it; even cosine_similarity([], []) is rejected because the numpy check precedes the empty-input early return.","commonSituations":"Running langchain-core in minimal environments (slim containers, serverless runtimes, embedded interpreters) where numpy was deliberately left out; scripts that worked under the full langchain package (which pulls numpy transitively) breaking after migrating to bare langchain-core; unit tests failing in CI matrix jobs that install a reduced extras set.","solutions":["Install numpy: pip install numpy — it is required for this utility, not optional.","If you installed only langchain-core, prefer installing the broader langchain package or explicitly add numpy to your project dependencies so environments stay reproducible.","Avoid calling cosine_similarity entirely when you just need top-k neighbors: use a vectorstore's similarity_search_with_score, which does not require numpy for the InMemory backend.","For performance-sensitive deployments, also consider pip install simsimd so the function uses the faster simsimd path once numpy is present."],"exampleFix":"// before\nfrom langchain_core.vectorstores.utils import cosine_similarity\nsim = cosine_similarity(query_embs, doc_embs)  # ImportError without numpy\n\n// after\n// shell: pip install numpy\nfrom langchain_core.vectorstores.utils import cosine_similarity\nsim = cosine_similarity(query_embs, doc_embs)","handlingStrategy":"validation","validationCode":"def ensure_numpy() -> None:\n    try:\n        import numpy  # noqa: F401\n    except ImportError as exc:\n        msg = \"cosine_similarity requires numpy; install it with `pip install numpy`\"\n        raise RuntimeError(msg) from exc","typeGuard":"def can_compute_cosine() -> bool:\n    \"\"\"True when numpy is importable and cosine_similarity will work.\"\"\"\n    try:\n        import numpy  # noqa: F401\n    except ImportError:\n        return False\n    return True","tryCatchPattern":"try:\n        sim = cosine_similarity(x, y)\nexcept ImportError as e:\n    if \"requires numpy\" in str(e):\n        # e.g. fall back to a pure-python dot product or skip scoring\n        raise RuntimeError(\"environment missing numpy; cannot score candidates\") from e\n    raise","preventionTips":["Treat numpy as a required dependency in any project importing langchain_core.vectorstores.utils.","Use the same dependency set in CI, Docker, and local dev so numpy presence does not drift between environments.","Prefer higher-level APIs (similarity_search_with_score) that do not require numpy when you do not need raw matrices.","Add an import-time smoke check in the app entrypoint that fails fast on missing numpy."],"tags":["dependencies","numpy","cosine-similarity","vectorstore","utils","optional-import"],"backgroundTag":null,"analyzedSha":"e32fa9a52eab3b61ad7a45399bfde59b3e580fc4","analyzedAt":"2026-08-14T18:42:09.092Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}