langchain-ai/langchain · error · ImportError

cosine_similarity requires numpy to be installed. Please ins

Error message

cosine_similarity requires numpy to be installed. Please install numpy with `pip install numpy`.

What it means

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.

Source

Thrown at libs/core/langchain_core/vectorstores/utils.py:59

    Args:
        x: A matrix of shape `(n, m)`.
        y: A matrix of shape `(k, m)`.

    Returns:
        A matrix of shape `(n, k)` where each element `(i, j)` is the cosine similarity
            between the `i`th row of `x` and the `j`th row of `y`.

    Raises:
        ValueError: If the number of columns in `x` and `y` are not the same.
        ImportError: If numpy is not installed.
    """
    if not _HAS_NUMPY:
        msg = (
            "cosine_similarity requires numpy to be installed. "
            "Please install numpy with `pip install numpy`."
        )
        raise ImportError(msg)

    if len(x) == 0 or len(y) == 0:
        return np.array([[]])

    x = np.array(x)
    y = np.array(y)

    # Check for NaN
    if np.any(np.isnan(x)) or np.any(np.isnan(y)):
        warnings.warn(
            "NaN found in input arrays, unexpected return might follow",
            category=RuntimeWarning,
            stacklevel=2,
        )

    # Check for Inf
    if np.any(np.isinf(x)) or np.any(np.isinf(y)):
        warnings.warn(

View on GitHub (pinned to e32fa9a52e)

Solutions

  1. Install numpy: pip install numpy — it is required for this utility, not optional.
  2. If you installed only langchain-core, prefer installing the broader langchain package or explicitly add numpy to your project dependencies so environments stay reproducible.
  3. 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.
  4. For performance-sensitive deployments, also consider pip install simsimd so the function uses the faster simsimd path once numpy is present.

Example fix

// before
from langchain_core.vectorstores.utils import cosine_similarity
sim = cosine_similarity(query_embs, doc_embs)  # ImportError without numpy

// after
// shell: pip install numpy
from langchain_core.vectorstores.utils import cosine_similarity
sim = cosine_similarity(query_embs, doc_embs)
Defensive patterns

Strategy: validation

Validate before calling

def ensure_numpy() -> None:
    try:
        import numpy  # noqa: F401
    except ImportError as exc:
        msg = "cosine_similarity requires numpy; install it with `pip install numpy`"
        raise RuntimeError(msg) from exc

Type guard

def can_compute_cosine() -> bool:
    """True when numpy is importable and cosine_similarity will work."""
    try:
        import numpy  # noqa: F401
    except ImportError:
        return False
    return True

Try / catch

try:
        sim = cosine_similarity(x, y)
except ImportError as e:
    if "requires numpy" in str(e):
        # e.g. fall back to a pure-python dot product or skip scoring
        raise RuntimeError("environment missing numpy; cannot score candidates") from e
    raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of langchain-ai/langchain@e32fa9a52e (2026-08-14). Data as JSON: /api/errors/e822c01c02656301. Report an issue: GitHub.