-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathtest_vectorizers.py
More file actions
808 lines (645 loc) · 26.3 KB
/
test_vectorizers.py
File metadata and controls
808 lines (645 loc) · 26.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
import os
import warnings
import numpy as np
import pytest
from redisvl.extensions.cache.embeddings.embeddings import EmbeddingsCache
from redisvl.utils.utils import create_ulid
from redisvl.utils.vectorize import (
AzureOpenAITextVectorizer,
BedrockVectorizer,
CohereTextVectorizer,
CustomVectorizer,
HFTextVectorizer,
MistralAITextVectorizer,
OpenAITextVectorizer,
VertexAIVectorizer,
VoyageAIVectorizer,
)
# Constants for testing
TEST_TEXT = "This is a test sentence."
TEST_TEXTS = ["This is the first test sentence.", "This is the second test sentence."]
TEST_VECTOR = [1.1, 2.2, 3.3, 4.4]
@pytest.fixture
def embeddings_cache(client):
"""Create a real EmbeddingsCache for testing with a unique namespace."""
# Use a unique prefix for this test run to avoid conflicts
unique_prefix = f"test_cache_{create_ulid()}"
# Create the cache with a short TTL
cache = EmbeddingsCache(name=unique_prefix, ttl=10, redis_client=client)
yield cache
cache.clear()
@pytest.fixture(
params=[
HFTextVectorizer,
OpenAITextVectorizer,
VertexAIVectorizer,
CohereTextVectorizer,
AzureOpenAITextVectorizer,
BedrockVectorizer,
MistralAITextVectorizer,
CustomVectorizer,
VoyageAIVectorizer,
]
)
def vectorizer(request):
if request.param == HFTextVectorizer:
return request.param()
elif request.param == OpenAITextVectorizer:
return request.param()
elif request.param == VertexAIVectorizer:
return request.param()
elif request.param == CohereTextVectorizer:
return request.param()
elif request.param == MistralAITextVectorizer:
return request.param()
elif request.param == VoyageAIVectorizer:
return request.param(model="voyage-large-2")
elif request.param == AzureOpenAITextVectorizer:
return request.param(
model=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME", "text-embedding-ada-002")
)
elif request.param == BedrockVectorizer:
return request.param(
model=os.getenv("BEDROCK_MODEL_ID", "amazon.titan-embed-text-v2:0")
)
elif request.param == CustomVectorizer:
def embed(content):
return TEST_VECTOR
def embed_many(contents):
return [TEST_VECTOR] * len(contents)
async def aembed_func(content):
return TEST_VECTOR
async def aembed_many_func(contents):
return [TEST_VECTOR] * len(contents)
return request.param(embed=embed, embed_many=embed_many)
@pytest.fixture
def cached_vectorizer(embeddings_cache):
"""Create a simple custom vectorizer for testing."""
def embed(content):
return TEST_VECTOR
def embed_many(contents):
return [TEST_VECTOR] * len(contents)
async def aembed(content):
return TEST_VECTOR
async def aembed_many(contents):
return [TEST_VECTOR] * len(contents)
return CustomVectorizer(
embed=embed,
embed_many=embed_many,
aembed=aembed,
aembed_many=aembed_many,
cache=embeddings_cache,
)
@pytest.fixture
def custom_embed_func():
def embed(content: str):
return TEST_VECTOR
return embed
@pytest.fixture
def custom_embed_class():
class MyEmbedder:
def embed(self, content: str):
return TEST_VECTOR
def embed_with_args(self, content: str, max_len=None):
return TEST_VECTOR[0:max_len]
def embed_many(self, contents):
return [[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]
def embed_many_with_args(self, contents, param=True):
if param:
return [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
else:
return [[6.0, 5.0, 4.0], [3.0, 2.0, 1.0]]
return MyEmbedder
@pytest.mark.requires_api_keys
def test_vectorizer_embed(vectorizer):
text = TEST_TEXT
if isinstance(vectorizer, CohereTextVectorizer):
embedding = vectorizer.embed(text, input_type="search_document")
elif isinstance(vectorizer, VoyageAIVectorizer):
embedding = vectorizer.embed(text, input_type="document")
else:
embedding = vectorizer.embed(text)
assert isinstance(embedding, list)
assert len(embedding) == vectorizer.dims
@pytest.mark.requires_api_keys
def test_vectorizer_embed_many(vectorizer):
texts = TEST_TEXTS
if isinstance(vectorizer, CohereTextVectorizer):
embeddings = vectorizer.embed_many(texts, input_type="search_document")
elif isinstance(vectorizer, VoyageAIVectorizer):
embeddings = vectorizer.embed_many(texts, input_type="document")
else:
embeddings = vectorizer.embed_many(texts)
assert isinstance(embeddings, list)
assert len(embeddings) == len(texts)
assert all(
isinstance(emb, list) and len(emb) == vectorizer.dims for emb in embeddings
)
def test_vectorizer_with_cache(cached_vectorizer):
"""Test the complete cache flow - miss, store, hit."""
# First call - should be a cache miss
first_result = cached_vectorizer.embed(TEST_TEXT)
assert first_result == TEST_VECTOR
# Second call - should be a cache hit
second_result = cached_vectorizer.embed(TEST_TEXT)
assert second_result == TEST_VECTOR
# Verify it's actually using the cache by checking the cached value exists
cached_entry = cached_vectorizer.cache.get(
content=TEST_TEXT, model_name=cached_vectorizer.model
)
assert cached_entry is not None
assert cached_entry["embedding"] == TEST_VECTOR
def test_vectorizer_with_cache_skip(cached_vectorizer):
"""Test embedding with skip_cache=True."""
# Store a value in the cache
cached_vectorizer.embed(TEST_TEXT)
# Call embed with skip_cache=True - should bypass cache
cached_vectorizer.cache.drop(content=TEST_TEXT, model_name=cached_vectorizer.model)
# Store a deliberately different value in the cache
cached_vectorizer.cache.set(
content=TEST_TEXT,
model_name=cached_vectorizer.model,
embedding=[9.9, 8.8, 7.7, 6.6],
)
# Now call with skip_cache=True
result = cached_vectorizer.embed(TEST_TEXT, skip_cache=True)
# Should generate fresh result, not use cached value
assert result == TEST_VECTOR
# Cache should still have the original value
cached_entry = cached_vectorizer.cache.get(
content=TEST_TEXT, model_name=cached_vectorizer.model
)
assert cached_entry["embedding"] == [9.9, 8.8, 7.7, 6.6]
def test_vectorizer_with_cache_many(cached_vectorizer):
"""Test embedding many texts with partial cache hits/misses."""
# Store an embedding for the first text only
cached_vectorizer.cache.set(
content=TEST_TEXTS[0],
model_name=cached_vectorizer.model,
embedding=[0.1, 0.2, 0.3, 0.4],
)
# Call embed_many - should hit cache for first text, miss for second
results = cached_vectorizer.embed_many(TEST_TEXTS)
# Verify results
assert results[0] == [0.1, 0.2, 0.3, 0.4] # From cache
assert results[1] == TEST_VECTOR # Generated
# Both should now be in cache
for text in TEST_TEXTS:
assert cached_vectorizer.cache.exists(
content=text, model_name=cached_vectorizer.model
)
def test_vectorizer_with_cached_metadata(cached_vectorizer):
"""Test passing metadata through to the cache."""
# Call embed with metadata
test_metadata = {"source": "test", "importance": "high"}
cached_vectorizer.embed(TEST_TEXT, metadata=test_metadata)
# Verify metadata was stored in cache
cached_entry = cached_vectorizer.cache.get(
content=TEST_TEXT, model_name=cached_vectorizer.model
)
assert cached_entry["metadata"] == test_metadata
@pytest.mark.asyncio
async def test_vectorizer_with_cache_async(cached_vectorizer):
"""Test async embedding with cache."""
# First call - should be a cache miss
first_result = await cached_vectorizer.aembed(TEST_TEXT)
assert first_result == TEST_VECTOR
# Second call - should be a cache hit
second_result = await cached_vectorizer.aembed(TEST_TEXT)
assert second_result == TEST_VECTOR
# Verify it's actually using the cache
cached_entry = await cached_vectorizer.cache.aget(
content=TEST_TEXT, model_name=cached_vectorizer.model
)
assert cached_entry is not None
assert cached_entry["embedding"] == TEST_VECTOR
@pytest.mark.asyncio
async def test_vectorizer_with_cache_async_many(cached_vectorizer):
"""Test async embedding many texts with partial cache hits/misses."""
# Store an embedding for the first text only
await cached_vectorizer.cache.aset(
content=TEST_TEXTS[0],
model_name=cached_vectorizer.model,
embedding=[0.1, 0.2, 0.3, 0.4],
)
# Call aembed_many - should hit cache for first text, miss for second
results = await cached_vectorizer.aembed_many(TEST_TEXTS)
# Verify results
assert results[0] == [0.1, 0.2, 0.3, 0.4] # From cache
assert results[1] == TEST_VECTOR # Generated
# Both should now be in cache
for text in TEST_TEXTS:
assert await cached_vectorizer.cache.aexists(
content=text, model_name=cached_vectorizer.model
)
@pytest.mark.requires_api_keys
def test_bedrock_bad_credentials():
with pytest.raises(ValueError):
BedrockVectorizer(
api_config={
"aws_access_key_id": "invalid",
"aws_secret_access_key": "invalid",
}
)
@pytest.mark.requires_api_keys
def test_bedrock_invalid_model():
with pytest.raises(ValueError):
bedrock = BedrockVectorizer(model="invalid-model")
bedrock.embed("test")
def test_custom_vectorizer_embed(custom_embed_class, custom_embed_func):
custom_wrapper = CustomVectorizer(embed=custom_embed_func)
embedding = custom_wrapper.embed("This is a test sentence.")
assert embedding == TEST_VECTOR
custom_wrapper = CustomVectorizer(embed=custom_embed_class().embed)
embedding = custom_wrapper.embed("This is a test sentence.")
assert embedding == TEST_VECTOR
custom_wrapper = CustomVectorizer(embed=custom_embed_class().embed_with_args)
embedding = custom_wrapper.embed("This is a test sentence.", max_len=4)
assert embedding == TEST_VECTOR
embedding = custom_wrapper.embed("This is a test sentence.", max_len=2)
assert embedding == [1.1, 2.2]
with pytest.raises(ValueError):
invalid_vectorizer = CustomVectorizer(embed="hello")
with pytest.raises(ValueError):
invalid_vectorizer = CustomVectorizer(embed=42)
with pytest.raises(ValueError):
invalid_vectorizer = CustomVectorizer(embed={"foo": "bar"})
def bad_arg_type(value: int):
return [value]
with pytest.raises(ValueError):
invalid_vectorizer = CustomVectorizer(embed=bad_arg_type)
def bad_return_type(text: str) -> str:
return text
with pytest.raises(ValueError):
invalid_vectorizer = CustomVectorizer(embed=bad_return_type)
def test_custom_vectorizer_embed_many(custom_embed_class, custom_embed_func):
custom_wrapper = CustomVectorizer(
custom_embed_func, embed_many=custom_embed_class().embed_many
)
embeddings = custom_wrapper.embed_many(["test one.", "test two"])
assert embeddings == [[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]
custom_wrapper = CustomVectorizer(
custom_embed_func, embed_many=custom_embed_class().embed_many
)
embeddings = custom_wrapper.embed_many(["test one.", "test two"])
assert embeddings == [[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]
custom_wrapper = CustomVectorizer(
custom_embed_func, embed_many=custom_embed_class().embed_many_with_args
)
embeddings = custom_wrapper.embed_many(["test one.", "test two"], param=True)
assert embeddings == [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
embeddings = custom_wrapper.embed_many(["test one.", "test two"], param=False)
assert embeddings == [[6.0, 5.0, 4.0], [3.0, 2.0, 1.0]]
with pytest.raises(ValueError):
invalid_vectorizer = CustomVectorizer(custom_embed_func, embed_many="hello")
with pytest.raises(ValueError):
invalid_vectorizer = CustomVectorizer(custom_embed_func, embed_many=42)
with pytest.raises(ValueError):
invalid_vectorizer = CustomVectorizer(
custom_embed_func, embed_many={"foo": "bar"}
)
def bad_arg_type(value: int):
return [value]
with pytest.raises(ValueError):
invalid_vectorizer = CustomVectorizer(
custom_embed_func, embed_many=bad_arg_type
)
def bad_return_type(text: str) -> str:
return text
with pytest.raises(ValueError):
invalid_vectorizer = CustomVectorizer(
custom_embed_func, embed_many=bad_return_type
)
@pytest.mark.requires_api_keys
@pytest.mark.parametrize(
"vectorizer_",
[
AzureOpenAITextVectorizer,
BedrockVectorizer,
CohereTextVectorizer,
CustomVectorizer,
HFTextVectorizer,
MistralAITextVectorizer,
OpenAITextVectorizer,
VertexAIVectorizer,
VoyageAIVectorizer,
],
)
def test_default_dtype(vectorizer_):
# test dtype defaults to float32
if issubclass(vectorizer_, CustomVectorizer):
vectorizer = vectorizer_(embed=lambda x, input_type=None: [1.0, 2.0, 3.0])
elif issubclass(vectorizer_, AzureOpenAITextVectorizer):
vectorizer = vectorizer_(
model=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME", "text-embedding-ada-002")
)
else:
vectorizer = vectorizer_()
assert vectorizer.dtype == "float32"
@pytest.mark.requires_api_keys
@pytest.mark.parametrize(
"vectorizer_",
[
AzureOpenAITextVectorizer,
BedrockVectorizer,
CohereTextVectorizer,
CustomVectorizer,
HFTextVectorizer,
MistralAITextVectorizer,
OpenAITextVectorizer,
VertexAIVectorizer,
VoyageAIVectorizer,
],
)
def test_vectorizer_dtype_assignment(vectorizer_):
# test initializing dtype in constructor
for dtype in ["float16", "float32", "float64", "bfloat16", "int8", "uint8"]:
if issubclass(vectorizer_, CustomVectorizer):
vectorizer = vectorizer_(embed=lambda x: [1.0, 2.0, 3.0], dtype=dtype)
elif issubclass(vectorizer_, AzureOpenAITextVectorizer):
vectorizer = vectorizer_(
model=os.getenv(
"AZURE_OPENAI_DEPLOYMENT_NAME", "text-embedding-ada-002"
),
dtype=dtype,
)
else:
vectorizer = vectorizer_(dtype=dtype)
assert vectorizer.dtype == dtype
@pytest.mark.requires_api_keys
@pytest.mark.parametrize(
"vectorizer_",
[
AzureOpenAITextVectorizer,
BedrockVectorizer,
CohereTextVectorizer,
HFTextVectorizer,
MistralAITextVectorizer,
OpenAITextVectorizer,
VertexAIVectorizer,
VoyageAIVectorizer,
],
)
def test_non_supported_dtypes(vectorizer_):
with pytest.raises(ValueError):
vectorizer_(dtype="float25")
with pytest.raises(ValueError):
vectorizer_(dtype=7)
with pytest.raises(ValueError):
vectorizer_(dtype=None)
@pytest.mark.requires_api_keys
@pytest.mark.asyncio
async def test_vectorizer_aembed(vectorizer):
text = TEST_TEXT
if isinstance(vectorizer, CohereTextVectorizer):
embedding = await vectorizer.aembed(text, input_type="search_document")
elif isinstance(vectorizer, VoyageAIVectorizer):
embedding = await vectorizer.aembed(text, input_type="document")
else:
embedding = await vectorizer.aembed(text)
assert isinstance(embedding, list)
assert len(embedding) == vectorizer.dims
@pytest.mark.requires_api_keys
@pytest.mark.asyncio
async def test_vectorizer_aembed_many(vectorizer):
texts = TEST_TEXTS
if isinstance(vectorizer, CohereTextVectorizer):
embeddings = await vectorizer.aembed_many(texts, input_type="search_document")
elif isinstance(vectorizer, VoyageAIVectorizer):
embeddings = await vectorizer.aembed_many(texts, input_type="document")
else:
embeddings = await vectorizer.aembed_many(texts)
assert isinstance(embeddings, list)
assert len(embeddings) == len(texts)
assert all(
isinstance(emb, list) and len(emb) == vectorizer.dims for emb in embeddings
)
@pytest.mark.requires_api_keys
@pytest.mark.parametrize(
"dtype,expected_type",
[
("float32", float), # Float dtype should return floats
("int8", int), # Int8 dtype should return ints
("uint8", int), # Uint8 dtype should return ints
],
)
def test_cohere_dtype_support(dtype, expected_type):
"""Test that CohereTextVectorizer properly handles different dtypes for embeddings."""
text = TEST_TEXT
texts = TEST_TEXTS
# Create vectorizer with specified dtype
vectorizer = CohereTextVectorizer(dtype=dtype)
# Verify the correct mapping of dtype to Cohere embedding_types
if dtype == "int8":
assert vectorizer._get_cohere_embedding_type(dtype) == ["int8"]
elif dtype == "uint8":
assert vectorizer._get_cohere_embedding_type(dtype) == ["uint8"]
else:
# All other dtypes should map to float
assert vectorizer._get_cohere_embedding_type(dtype) == ["float"]
# Test single embedding
embedding = vectorizer.embed(text, input_type="search_document")
assert isinstance(embedding, list)
assert len(embedding) == vectorizer.dims
# Check that all elements are of the expected type
assert all(
isinstance(val, expected_type) for val in embedding
), f"Expected all elements to be {expected_type.__name__} for dtype {dtype}"
# Test multiple embeddings
embeddings = vectorizer.embed_many(texts, input_type="search_document")
assert isinstance(embeddings, list)
assert len(embeddings) == len(texts)
assert all(
isinstance(emb, list) and len(emb) == vectorizer.dims for emb in embeddings
)
# Check that all elements in all embeddings are of the expected type
for emb in embeddings:
assert all(
isinstance(val, expected_type) for val in emb
), f"Expected all elements to be {expected_type.__name__} for dtype {dtype}"
# Test as_buffer output format
embedding_buffer = vectorizer.embed(
text, input_type="search_document", as_buffer=True
)
assert isinstance(embedding_buffer, bytes)
# Test embed_many with as_buffer=True
buffer_embeddings = vectorizer.embed_many(
texts, input_type="search_document", as_buffer=True
)
assert all(isinstance(emb, bytes) for emb in buffer_embeddings)
# Compare dimensions between buffer and list formats
assert len(np.frombuffer(embedding_buffer, dtype=dtype)) == len(embedding)
@pytest.mark.requires_api_keys
def test_cohere_embedding_types_warning():
"""Test that a warning is raised when embedding_types parameter is passed."""
text = TEST_TEXT
texts = TEST_TEXTS
vectorizer = CohereTextVectorizer()
# Test warning for single embedding
with pytest.warns(UserWarning, match="embedding_types.*not supported"):
embedding = vectorizer.embed(
text,
input_type="search_document",
embedding_types=["uint8"], # explicitly testing the anti-pattern here
)
assert isinstance(embedding, list)
assert len(embedding) == vectorizer.dims
# Test warning for multiple embeddings
with pytest.warns(UserWarning, match="embedding_types.*not supported"):
embeddings = vectorizer.embed_many(
texts, input_type="search_document", embedding_types=["uint8"]
)
assert isinstance(embeddings, list)
assert len(embeddings) == len(texts)
def test_deprecated_text_parameter_warning():
"""Test that using deprecated 'text' and 'texts' parameters emits deprecation warnings."""
vectorizer = HFTextVectorizer(model="sentence-transformers/all-MiniLM-L6-v2")
# Test single embed with deprecated 'text' parameter emits warning
with pytest.warns(DeprecationWarning, match="Argument text is deprecated"):
embedding = vectorizer.embed(text=TEST_TEXT)
assert isinstance(embedding, list)
assert len(embedding) == vectorizer.dims
# Test embed_many with deprecated 'texts' parameter emits warning
with pytest.warns(DeprecationWarning, match="Argument texts is deprecated"):
embeddings = vectorizer.embed_many(texts=TEST_TEXTS)
assert isinstance(embeddings, list)
assert len(embeddings) == len(TEST_TEXTS)
# VoyageAI-specific tests for token counting and context model detection
@pytest.mark.requires_api_keys
def test_voyageai_count_tokens():
"""Test VoyageAI token counting functionality."""
vectorizer = VoyageAIVectorizer(model="voyage-3.5")
texts = ["Hello world", "This is a longer test sentence."]
token_counts = vectorizer.count_tokens(texts)
assert isinstance(token_counts, list)
assert len(token_counts) == len(texts)
assert all(isinstance(count, int) and count > 0 for count in token_counts)
# Empty list should return empty list
assert vectorizer.count_tokens([]) == []
@pytest.mark.requires_api_keys
@pytest.mark.asyncio
async def test_voyageai_acount_tokens():
"""Test VoyageAI async token counting functionality."""
vectorizer = VoyageAIVectorizer(model="voyage-3.5")
texts = ["Hello world", "This is a longer test sentence."]
token_counts = await vectorizer.acount_tokens(texts)
assert isinstance(token_counts, list)
assert len(token_counts) == len(texts)
assert all(isinstance(count, int) and count > 0 for count in token_counts)
# Empty list should return empty list
assert await vectorizer.acount_tokens([]) == []
def test_voyageai_token_limits():
"""Test VoyageAI token limit constants."""
from redisvl.utils.vectorize.voyageai import VOYAGE_TOTAL_TOKEN_LIMITS
# Verify token limits are defined correctly
assert VOYAGE_TOTAL_TOKEN_LIMITS.get("voyage-context-3") == 32_000
assert VOYAGE_TOTAL_TOKEN_LIMITS.get("voyage-3.5-lite") == 1_000_000
assert VOYAGE_TOTAL_TOKEN_LIMITS.get("voyage-3.5") == 320_000
assert VOYAGE_TOTAL_TOKEN_LIMITS.get("voyage-multimodal-3") == 32_000
assert VOYAGE_TOTAL_TOKEN_LIMITS.get("voyage-multimodal-3.5") == 32_000
# Default for unknown models
assert VOYAGE_TOTAL_TOKEN_LIMITS.get("unknown-model", 120_000) == 120_000
def test_voyageai_context_model_detection():
"""Test detection of contextualized embedding models."""
# Test the context model detection logic directly
# The method checks if "context" is in the model name
assert "context" not in "voyage-3.5"
assert "context" in "voyage-context-3"
assert "context" not in "voyage-multimodal-3.5"
# Verify the detection would work correctly for known models
test_cases = [
("voyage-3.5", False),
("voyage-context-3", True),
("voyage-multimodal-3.5", False),
("voyage-3-large", False),
]
for model_name, expected in test_cases:
# The _is_context_model method simply checks: "context" in self.model
assert ("context" in model_name) == expected, f"Failed for {model_name}"
@pytest.mark.requires_api_keys
def test_voyageai_multimodal_text_only():
"""Test VoyageAI multimodal vectorizer with text-only input."""
vectorizer = VoyageAIVectorizer(model="voyage-multimodal-3")
# Test single text embedding via embed()
embedding = vectorizer.embed("A red apple on a wooden table")
assert isinstance(embedding, list)
assert len(embedding) > 0
assert all(isinstance(x, float) for x in embedding)
# Test another text embedding to verify consistency
embedding2 = vectorizer.embed("A cat sleeping on a couch")
assert isinstance(embedding2, list)
assert len(embedding2) == len(embedding)
@pytest.mark.requires_api_keys
def test_voyageai_multimodal_image():
"""Test VoyageAI multimodal vectorizer with image input."""
import os
import tempfile
from PIL import Image
vectorizer = VoyageAIVectorizer(model="voyage-multimodal-3")
# Create a simple test image
img = Image.new("RGB", (100, 100), color="red")
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
img.save(f, format="PNG")
temp_path = f.name
try:
# Test embed_image
embedding = vectorizer.embed_image(temp_path)
assert isinstance(embedding, list)
assert len(embedding) > 0
assert all(isinstance(x, float) for x in embedding)
finally:
os.unlink(temp_path)
@pytest.mark.requires_api_keys
def test_voyageai_multimodal_video():
"""Test VoyageAI multimodal vectorizer with video input."""
import os
import subprocess
import tempfile
from PIL import Image
vectorizer = VoyageAIVectorizer(model="voyage-multimodal-3.5")
# Create a minimal test video using ffmpeg
with tempfile.TemporaryDirectory() as tmpdir:
# Create 3 frames
for i in range(3):
img = Image.new("RGB", (64, 64), color=(i * 80, 100, 150))
img.save(os.path.join(tmpdir, f"frame_{i:03d}.png"))
video_path = os.path.join(tmpdir, "test_video.mp4")
# Create video from frames
result = subprocess.run(
[
"ffmpeg",
"-y",
"-framerate",
"1",
"-i",
os.path.join(tmpdir, "frame_%03d.png"),
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-t",
"3",
video_path,
],
capture_output=True,
)
if result.returncode != 0:
pytest.skip("ffmpeg not available or failed to create test video")
# Test embed_video
embedding = vectorizer.embed_video(video_path)
assert isinstance(embedding, list)
assert len(embedding) > 0
assert all(isinstance(x, float) for x in embedding)
@pytest.mark.requires_api_keys
@pytest.mark.asyncio
async def test_voyageai_multimodal_async():
"""Test VoyageAI multimodal vectorizer async methods."""
vectorizer = VoyageAIVectorizer(model="voyage-multimodal-3")
# Test async text embedding
embedding = await vectorizer.aembed("A beautiful sunset over mountains")
assert isinstance(embedding, list)
assert len(embedding) > 0
# Test async batch
texts = ["Ocean waves", "Forest trees"]
embeddings = await vectorizer.aembed_many(texts)
assert len(embeddings) == 2