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
- 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.
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
- 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.
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
- maximal_marginal_relevance requires numpy to be installed. P
- numpy must be installed to use max_marginal_relevance_search
- Number of columns in X and Y must be the same. X has shape {
- NaN values found, please remove the NaN values and try again
- Could not import transformers python package. This is needed
AI-assisted analysis of langchain-ai/langchain@e32fa9a52e (2026-08-14).
Data as JSON: /api/errors/e822c01c02656301.
Report an issue: GitHub.