Skip to content

Commit fde2983

Browse files
Merge branch '0.6.0' into feat/rerun-060-notebooks
2 parents bba3163 + bbfab82 commit fde2983

File tree

13 files changed

+175
-31
lines changed

13 files changed

+175
-31
lines changed

redisvl/cli/index.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from redisvl.redis.utils import convert_bytes, make_dict
99
from redisvl.schema.schema import IndexSchema
1010
from redisvl.utils.log import get_logger
11+
from redisvl.utils.utils import lazy_import
1112

1213
logger = get_logger("[RedisVL]")
1314

redisvl/cli/stats.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from redisvl.index import SearchIndex
77
from redisvl.schema.schema import IndexSchema
88
from redisvl.utils.log import get_logger
9+
from redisvl.utils.utils import lazy_import
910

1011
logger = get_logger("[RedisVL]")
1112

@@ -85,6 +86,8 @@ def _connect_to_index(self, args: Namespace) -> SearchIndex:
8586

8687

8788
def _display_stats(index_info, output_format="rounded_outline"):
89+
tabulate = lazy_import("tabulate")
90+
8891
# Extracting the statistics
8992
stats_data = [(key, str(index_info.get(key))) for key in STATS_KEYS]
9093

redisvl/query/aggregate.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@
55
from redisvl.query.filter import FilterExpression
66
from redisvl.redis.utils import array_to_buffer
77
from redisvl.utils.token_escaper import TokenEscaper
8+
from redisvl.utils.utils import lazy_import
9+
10+
nltk = lazy_import("nltk")
11+
nltk_stopwords = lazy_import("nltk.corpus.stopwords")
812

913

1014
class AggregationQuery(AggregateRequest):
@@ -162,17 +166,13 @@ def _set_stopwords(self, stopwords: Optional[Union[str, Set[str]]] = "english"):
162166
if not stopwords:
163167
self._stopwords = set()
164168
elif isinstance(stopwords, str):
165-
# Lazy import because nltk is an optional dependency
166169
try:
167-
import nltk
168-
from nltk.corpus import stopwords as nltk_stopwords
170+
nltk.download("stopwords", quiet=True)
171+
self._stopwords = set(nltk_stopwords.words(stopwords))
169172
except ImportError:
170173
raise ValueError(
171174
f"Loading stopwords for {stopwords} failed: nltk is not installed."
172175
)
173-
try:
174-
nltk.download("stopwords", quiet=True)
175-
self._stopwords = set(nltk_stopwords.words(stopwords))
176176
except Exception as e:
177177
raise ValueError(f"Error trying to load {stopwords} from nltk. {e}")
178178
elif isinstance(stopwords, (Set, List, Tuple)) and all( # type: ignore

redisvl/query/query.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@
66
from redisvl.query.filter import FilterExpression
77
from redisvl.redis.utils import array_to_buffer
88
from redisvl.utils.token_escaper import TokenEscaper
9-
from redisvl.utils.utils import denorm_cosine_distance
9+
from redisvl.utils.utils import denorm_cosine_distance, lazy_import
10+
11+
nltk = lazy_import("nltk")
12+
nltk_stopwords = lazy_import("nltk.corpus.stopwords")
1013

1114

1215
class BaseQuery(RedisQuery):
@@ -893,17 +896,13 @@ def _set_stopwords(self, stopwords: Optional[Union[str, Set[str]]] = "english"):
893896
if not stopwords:
894897
self._stopwords = set()
895898
elif isinstance(stopwords, str):
896-
# Lazy import because nltk is an optional dependency
897899
try:
898-
import nltk
899-
from nltk.corpus import stopwords as nltk_stopwords
900+
nltk.download("stopwords", quiet=True)
901+
self._stopwords = set(nltk_stopwords.words(stopwords))
900902
except ImportError:
901903
raise ValueError(
902904
f"Loading stopwords for {stopwords} failed: nltk is not installed."
903905
)
904-
try:
905-
nltk.download("stopwords", quiet=True)
906-
self._stopwords = set(nltk_stopwords.words(stopwords))
907906
except Exception as e:
908907
raise ValueError(f"Error trying to load {stopwords} from nltk. {e}")
909908
elif isinstance(stopwords, (Set, List, Tuple)) and all( # type: ignore

redisvl/redis/utils.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import hashlib
22
from typing import Any, Dict, List, Optional
33

4-
import numpy as np
5-
from ml_dtypes import bfloat16
4+
from redisvl.utils.utils import lazy_import
5+
6+
# Lazy import numpy
7+
np = lazy_import("numpy")
68

79
from redisvl.schema.fields import VectorDataType
810

@@ -41,6 +43,13 @@ def array_to_buffer(array: List[float], dtype: str) -> bytes:
4143
raise ValueError(
4244
f"Invalid data type: {dtype}. Supported types are: {[t.lower() for t in VectorDataType]}"
4345
)
46+
47+
# Special handling for bfloat16 which requires explicit import from ml_dtypes
48+
if dtype.lower() == "bfloat16":
49+
from ml_dtypes import bfloat16
50+
51+
return np.array(array, dtype=bfloat16).tobytes()
52+
4453
return np.array(array, dtype=dtype.lower()).tobytes()
4554

4655

@@ -52,6 +61,14 @@ def buffer_to_array(buffer: bytes, dtype: str) -> List[Any]:
5261
raise ValueError(
5362
f"Invalid data type: {dtype}. Supported types are: {[t.lower() for t in VectorDataType]}"
5463
)
64+
65+
# Special handling for bfloat16 which requires explicit import from ml_dtypes
66+
# because otherwise the (lazily imported) numpy is unaware of the type
67+
if dtype.lower() == "bfloat16":
68+
from ml_dtypes import bfloat16
69+
70+
return np.frombuffer(buffer, dtype=bfloat16).tolist() # type: ignore[return-value]
71+
5572
return np.frombuffer(buffer, dtype=dtype.lower()).tolist() # type: ignore[return-value]
5673

5774

redisvl/utils/optimize/cache.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from typing import Any, Callable, Dict, List
22

3-
import numpy as np
3+
from redisvl.utils.utils import lazy_import
4+
5+
np = lazy_import("numpy")
46
from ranx import Qrels, Run, evaluate
57

68
from redisvl.extensions.cache.llm.semantic import SemanticCache

redisvl/utils/optimize/router.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import random
22
from typing import Any, Callable, Dict, List
33

4-
import numpy as np
4+
from redisvl.utils.utils import lazy_import
5+
6+
np = lazy_import("numpy")
57
from ranx import Qrels, Run, evaluate
68

79
from redisvl.extensions.router.semantic import SemanticRouter

redisvl/utils/optimize/utils.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from typing import List
22

3-
import numpy as np
3+
from redisvl.utils.utils import lazy_import
4+
5+
np = lazy_import("numpy")
46
from ranx import Qrels
57

68
from redisvl.utils.optimize.schema import LabeledData

redisvl/utils/utils.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -321,15 +321,17 @@ def __getattr__(self, name: str) -> Any:
321321
else:
322322
# This means we couldn't find the attribute in the module path
323323
raise AttributeError(
324-
f"{self._parts[0]} has no attribute '{self._parts[1]}'"
324+
f"module '{self._parts[0]}' has no attribute '{self._parts[1]}'"
325325
)
326326

327327
# If we have a module, get the requested attribute
328328
if hasattr(self._module, name):
329329
return getattr(self._module, name)
330330

331331
# If the attribute doesn't exist, raise AttributeError
332-
raise AttributeError(f"{self._module_path} has no attribute '{name}'")
332+
raise AttributeError(
333+
f"module '{self._module_path}' has no attribute '{name}'"
334+
)
333335

334336
def __call__(self, *args: Any, **kwargs: Any) -> Any:
335337
# Import the module if it hasn't been imported yet

schemas/semantic_router.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
name: test-router-01JSHK4MJ79HH51PS6WEK6M9MF
1+
name: test-router
22
routes:
33
- name: greeting
44
references:

0 commit comments

Comments
 (0)