langchain-ai/langchain · error · ImportError
maximal_marginal_relevance requires numpy to be installed. P
Error message
maximal_marginal_relevance requires numpy to be installed. Please install numpy with `pip install numpy`.
What it means
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.
Source
Thrown at libs/core/langchain_core/vectorstores/utils.py:137
Args:
query_embedding: The query embedding.
embedding_list: A list of embeddings.
lambda_mult: The lambda parameter for MMR.
k: The number of embeddings to return.
Returns:
A list of indices of the embeddings to return.
Raises:
ImportError: If numpy is not installed.
"""
if not _HAS_NUMPY:
msg = (
"maximal_marginal_relevance requires numpy to be installed. "
"Please install numpy with `pip install numpy`."
)
raise ImportError(msg)
if min(k, len(embedding_list)) <= 0:
return []
if query_embedding.ndim == 1:
query_embedding = np.expand_dims(query_embedding, axis=0)
similarity_to_query = _cosine_similarity(query_embedding, embedding_list)[0]
most_similar = int(np.argmax(similarity_to_query))
idxs = [most_similar]
selected = np.array([embedding_list[most_similar]])
while len(idxs) < min(k, len(embedding_list)):
best_score = -np.inf
idx_to_add = -1
similarity_to_selected = _cosine_similarity(embedding_list, selected)
for i, query_score in enumerate(similarity_to_query):
if i in idxs:
continue
redundant_score = max(similarity_to_selected[i])
equation_score = (View on GitHub (pinned to e32fa9a52e)
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.
Example fix
// before from langchain_core.vectorstores.utils import maximal_marginal_relevance idxs = maximal_marginal_relevance(q_emb, cand_embs, k=4) # ImportError // after // shell: pip install numpy from langchain_core.vectorstores.utils import maximal_marginal_relevance idxs = maximal_marginal_relevance(q_emb, cand_embs, k=4)
Defensive patterns
Strategy: fallback
Validate before calling
try:
import numpy # noqa: F401
HAS_NUMPY = True
except ImportError:
HAS_NUMPY = False
if not HAS_NUMPY:
raise RuntimeError("maximal_marginal_relevance requires numpy; pip install numpy") Type guard
def mmr_available() -> bool:
"""True when numpy is importable, i.e. maximal_marginal_relevance is usable."""
try:
import numpy # noqa: F401
except ImportError:
return False
return True Try / catch
try:
idxs = maximal_marginal_relevance(query_embedding, embedding_list, k=k, lambda_mult=0.5)
except ImportError as e:
if "requires numpy" in str(e):
# pure-python fallback: plain top-k by score order already present
idxs = list(range(min(k, len(embedding_list))))
else:
raise Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- numpy must be installed to use max_marginal_relevance_search
- cosine_similarity requires numpy to be installed. Please ins
- Number of columns in X and Y must be the same. X has shape {
- Could not import transformers python package. This is needed
- defusedxml is not installed. Please install it to use the de
AI-assisted analysis of langchain-ai/langchain@e32fa9a52e (2026-08-14).
Data as JSON: /api/errors/61c683044f5b6794.
Report an issue: GitHub.