Skip to content

Commit 686a6b7

Browse files
CasiCodemdrxy
andauthored
fix: issue a warning if np.nan or np.inf are in _cosine_similarity argument Matrices (#31532)
- **Description**: issues a warning if inf and nan are passed as inputs to langchain_core.vectorstores.utils._cosine_similarity - **Issue**: Fixes #31496 - **Dependencies**: no external dependencies added, only warnings module imported --------- Co-authored-by: Mason Daugherty <[email protected]>
1 parent 12d370a commit 686a6b7

File tree

1 file changed

+18
-0
lines changed
  • libs/core/langchain_core/vectorstores

1 file changed

+18
-0
lines changed

libs/core/langchain_core/vectorstores/utils.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from __future__ import annotations
88

99
import logging
10+
import warnings
1011
from typing import TYPE_CHECKING, Union
1112

1213
if TYPE_CHECKING:
@@ -46,6 +47,23 @@ def _cosine_similarity(x: Matrix, y: Matrix) -> np.ndarray:
4647

4748
x = np.array(x)
4849
y = np.array(y)
50+
51+
# Check for NaN
52+
if np.any(np.isnan(x)) or np.any(np.isnan(y)):
53+
warnings.warn(
54+
"NaN found in input arrays, unexpected return might follow",
55+
category=RuntimeWarning,
56+
stacklevel=2,
57+
)
58+
59+
# Check for Inf
60+
if np.any(np.isinf(x)) or np.any(np.isinf(y)):
61+
warnings.warn(
62+
"Inf found in input arrays, unexpected return might follow",
63+
category=RuntimeWarning,
64+
stacklevel=2,
65+
)
66+
4967
if x.shape[1] != y.shape[1]:
5068
msg = (
5169
f"Number of columns in X and Y must be the same. X has shape {x.shape} "

0 commit comments

Comments
 (0)