-
Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathtest_use.py
More file actions
1500 lines (1276 loc) · 48.1 KB
/
test_use.py
File metadata and controls
1500 lines (1276 loc) · 48.1 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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import os
from enum import Enum
from pathlib import Path
from typing import Literal, Union
import httpx
import pytest
import respx
import replicate
from replicate.use import get_path_url
class ClientMode(str, Enum):
DEFAULT = "default"
ASYNC = "async"
# Allow use() to be called in test context
os.environ["REPLICATE_ALWAYS_ALLOW_USE"] = "1"
os.environ["REPLICATE_POLL_INTERVAL"] = "0"
def _deep_merge(base, override):
if override is None:
return base
result = base.copy()
for key, value in override.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = _deep_merge(result[key], value)
else:
result[key] = value
return result
def create_mock_version(version_overrides=None, version_id="xyz123"):
default_version = {
"id": version_id,
"created_at": "2024-01-01T00:00:00Z",
"cog_version": "0.8.0",
"openapi_schema": {
"openapi": "3.0.2",
"info": {"title": "Cog", "version": "0.1.0"},
"paths": {
"/": {
"post": {
"summary": "Make a prediction",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PredictionRequest"
}
}
}
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PredictionResponse"
}
}
}
}
},
}
}
},
"components": {
"schemas": {
"Input": {
"type": "object",
"properties": {"prompt": {"type": "string", "title": "Prompt"}},
"required": ["prompt"],
},
"Output": {"type": "string", "title": "Output"},
}
},
},
}
return _deep_merge(default_version, version_overrides)
def create_mock_prediction(
prediction_overrides=None, prediction_id="pred123", uses_versionless_api=None
):
default_prediction = {
"id": prediction_id,
"model": "acme/hotdog-detector",
"version": "hidden"
if uses_versionless_api in ("notfound", "empty")
else "xyz123",
"urls": {
"get": f"https://api.replicate.com/v1/predictions/{prediction_id}",
"cancel": f"https://api.replicate.com/v1/predictions/{prediction_id}/cancel",
},
"created_at": "2024-01-01T00:00:00Z",
"source": "api",
"status": "processing",
"input": {"prompt": "hello world"},
"output": None,
"error": None,
"logs": "Starting prediction...",
}
return _deep_merge(default_prediction, prediction_overrides)
def mock_model_endpoints(
versions=None,
*,
# This is a workaround while we have a bug in the api
uses_versionless_api: Union[Literal["notfound"], Literal["empty"], None] = None,
):
if versions is None:
versions = [create_mock_version()]
# Get the latest version (first in list) for the model endpoint
latest_version = versions[0] if versions else None
respx.get("https://api.replicate.com/v1/models/acme/hotdog-detector").mock(
return_value=httpx.Response(
200,
json={
"url": "https://replicate.com/acme/hotdog-detector",
"owner": "acme",
"name": "hotdog-detector",
"description": "A model to detect hotdogs",
"visibility": "public",
"github_url": "https://github.com/acme/hotdog-detector",
"paper_url": None,
"license_url": None,
"run_count": 42,
"cover_image_url": None,
"default_example": None,
"latest_version": latest_version,
},
)
)
versions_results = versions
if uses_versionless_api == "empty":
versions_results = []
if uses_versionless_api == "notfound":
respx.get(
"https://api.replicate.com/v1/models/acme/hotdog-detector/versions"
).mock(return_value=httpx.Response(404, json={"detail": "Not found"}))
else:
respx.get(
"https://api.replicate.com/v1/models/acme/hotdog-detector/versions"
).mock(return_value=httpx.Response(200, json={"results": versions_results}))
for version_obj in versions_results:
if uses_versionless_api == "notfound":
respx.get(
f"https://api.replicate.com/v1/models/acme/hotdog-detector/versions/{version_obj['id']}"
).mock(return_value=httpx.Response(404, json={}))
else:
respx.get(
f"https://api.replicate.com/v1/models/acme/hotdog-detector/versions/{version_obj['id']}"
).mock(return_value=httpx.Response(200, json=version_obj))
def mock_prediction_endpoints(
predictions=None,
*,
uses_versionless_api=None,
):
if predictions is None:
# Create default two-step prediction flow (processing -> succeeded)
predictions = [
create_mock_prediction(
{
"status": "processing",
"output": None,
"logs": "",
},
uses_versionless_api=uses_versionless_api,
),
create_mock_prediction(
{
"status": "succeeded",
"output": "not hotdog",
"logs": "Starting prediction...\nPrediction completed.",
},
uses_versionless_api=uses_versionless_api,
),
]
initial_prediction = predictions[0]
if uses_versionless_api in ("notfound", "empty"):
respx.post(
"https://api.replicate.com/v1/models/acme/hotdog-detector/predictions"
).mock(return_value=httpx.Response(201, json=initial_prediction))
else:
respx.post("https://api.replicate.com/v1/predictions").mock(
return_value=httpx.Response(201, json=initial_prediction)
)
prediction_id = initial_prediction["id"]
respx.get(f"https://api.replicate.com/v1/predictions/{prediction_id}").mock(
side_effect=[httpx.Response(200, json=response) for response in predictions]
)
@pytest.mark.asyncio
@pytest.mark.parametrize("client_mode", [ClientMode.DEFAULT, ClientMode.ASYNC])
@respx.mock
async def test_use(client_mode):
mock_model_endpoints()
mock_prediction_endpoints()
hotdog_detector = replicate.use(
"acme/hotdog-detector", use_async=client_mode == ClientMode.ASYNC
)
if client_mode == ClientMode.ASYNC:
output = await hotdog_detector(prompt="hello world")
else:
output = hotdog_detector(prompt="hello world")
assert output == "not hotdog"
@pytest.mark.asyncio
@pytest.mark.parametrize("client_mode", [ClientMode.DEFAULT, ClientMode.ASYNC])
@respx.mock
async def test_use_with_version_identifier(client_mode):
mock_model_endpoints()
mock_prediction_endpoints()
hotdog_detector = replicate.use(
"acme/hotdog-detector:xyz123", use_async=client_mode == ClientMode.ASYNC
)
if client_mode == ClientMode.ASYNC:
output = await hotdog_detector(prompt="hello world")
else:
output = hotdog_detector(prompt="hello world")
assert output == "not hotdog"
@pytest.mark.asyncio
@pytest.mark.parametrize("client_mode", [ClientMode.DEFAULT, ClientMode.ASYNC])
@respx.mock
async def test_use_with_function_ref(client_mode):
mock_model_endpoints()
mock_prediction_endpoints()
class HotdogDetector:
name = "acme/hotdog-detector:xyz123"
def __call__(self, prompt: str) -> str: ...
hotdog_detector = replicate.use(
HotdogDetector(), use_async=client_mode == ClientMode.ASYNC
)
if client_mode == ClientMode.ASYNC:
output = await hotdog_detector(prompt="hello world")
else:
output = hotdog_detector(prompt="hello world")
assert output == "not hotdog"
@pytest.mark.asyncio
@pytest.mark.parametrize("client_mode", [ClientMode.DEFAULT, ClientMode.ASYNC])
@respx.mock
async def test_use_versionless_empty_versions_list(client_mode):
mock_model_endpoints(uses_versionless_api="empty")
mock_prediction_endpoints(uses_versionless_api="empty")
hotdog_detector = replicate.use(
"acme/hotdog-detector", use_async=client_mode == ClientMode.ASYNC
)
if client_mode == ClientMode.ASYNC:
output = await hotdog_detector(prompt="hello world")
else:
output = hotdog_detector(prompt="hello world")
assert output == "not hotdog"
@pytest.mark.asyncio
@pytest.mark.parametrize("client_mode", [ClientMode.DEFAULT, ClientMode.ASYNC])
@respx.mock
async def test_use_versionless_404_versions_list(client_mode):
mock_model_endpoints(uses_versionless_api="notfound")
mock_prediction_endpoints(uses_versionless_api="notfound")
hotdog_detector = replicate.use(
"acme/hotdog-detector", use_async=client_mode == ClientMode.ASYNC
)
if client_mode == ClientMode.ASYNC:
output = await hotdog_detector(prompt="hello world")
else:
output = hotdog_detector(prompt="hello world")
assert output == "not hotdog"
@pytest.mark.asyncio
@pytest.mark.parametrize("client_mode", [ClientMode.DEFAULT, ClientMode.ASYNC])
@respx.mock
async def test_use_function_create_method(client_mode):
mock_model_endpoints()
mock_prediction_endpoints()
hotdog_detector = replicate.use(
"acme/hotdog-detector", use_async=client_mode == ClientMode.ASYNC
)
if client_mode == ClientMode.ASYNC:
run = await hotdog_detector.create(prompt="hello world")
else:
run = hotdog_detector.create(prompt="hello world")
from replicate.use import AsyncRun, Run
if client_mode == ClientMode.ASYNC:
assert isinstance(run, AsyncRun)
else:
assert isinstance(run, Run)
assert run._prediction.id == "pred123"
assert run._prediction.status == "processing"
assert run._prediction.input == {"prompt": "hello world"}
@pytest.mark.asyncio
@pytest.mark.parametrize("client_mode", [ClientMode.DEFAULT, ClientMode.ASYNC])
@respx.mock
async def test_use_function_openapi_schema_dereferenced(client_mode):
mock_model_endpoints(
versions=[
create_mock_version(
{
"openapi_schema": {
"components": {
"schemas": {
"Output": {"$ref": "#/components/schemas/ModelOutput"},
"ModelOutput": {
"type": "object",
"properties": {
"text": {"type": "string"},
"image": {
"type": "string",
"format": "uri",
},
"count": {"type": "integer"},
},
},
}
}
}
}
)
]
)
hotdog_detector = replicate.use(
"acme/hotdog-detector", use_async=client_mode == ClientMode.ASYNC
)
if client_mode == ClientMode.ASYNC:
schema = await hotdog_detector.openapi_schema()
else:
schema = hotdog_detector.openapi_schema()
assert schema["components"]["schemas"]["Output"] == {
"type": "object",
"properties": {
"text": {"type": "string"},
"image": {
"type": "string",
"format": "uri",
},
"count": {"type": "integer"},
},
}
assert "ModelOutput" not in schema["components"]["schemas"]
@pytest.mark.asyncio
@pytest.mark.parametrize("client_mode", [ClientMode.DEFAULT, ClientMode.ASYNC])
@respx.mock
async def test_use_concatenate_iterator_output(client_mode):
mock_model_endpoints(
versions=[
create_mock_version(
{
"openapi_schema": {
"components": {
"schemas": {
"Output": {
"type": "array",
"items": {"type": "string"},
"x-cog-array-type": "iterator",
"x-cog-array-display": "concatenate",
}
}
}
}
}
)
]
)
mock_prediction_endpoints(
predictions=[
create_mock_prediction(),
create_mock_prediction(
{"status": "succeeded", "output": ["Hello", " ", "world", "!"]}
),
]
)
hotdog_detector = replicate.use(
"acme/hotdog-detector",
use_async=client_mode == ClientMode.ASYNC,
streaming=True,
)
if client_mode == ClientMode.ASYNC:
output = await hotdog_detector(prompt="hello world")
else:
output = hotdog_detector(prompt="hello world")
from replicate.use import OutputIterator
assert isinstance(output, OutputIterator)
assert str(output) == "Hello world!"
# Also test that it's iterable
output_list = list(output)
assert output_list == ["Hello", " ", "world", "!"]
# Test that concatenate OutputIterators are stringified when passed to create()
# Set up a mock for the prediction creation to capture the request
request_body = None
def capture_request(request):
nonlocal request_body
request_body = request.read()
return httpx.Response(
201,
json={
"id": "pred456",
"model": "acme/hotdog-detector",
"version": "xyz123",
"urls": {
"get": "https://api.replicate.com/v1/predictions/pred456",
"cancel": "https://api.replicate.com/v1/predictions/pred456/cancel",
},
"created_at": "2024-01-01T00:00:00Z",
"source": "api",
"status": "processing",
"input": {"text_input": "Hello world!"},
"output": None,
"error": None,
"logs": "",
},
)
respx.post("https://api.replicate.com/v1/predictions").mock(
side_effect=capture_request
)
# Pass the OutputIterator as input to create()
if client_mode == ClientMode.ASYNC:
await hotdog_detector.create(text_input=output)
else:
hotdog_detector.create(text_input=output)
# Verify the request body contains the stringified version
assert request_body
parsed_body = json.loads(request_body)
assert parsed_body["input"]["text_input"] == "Hello world!"
@pytest.mark.asyncio
async def test_output_iterator_async_iteration():
"""Test OutputIterator async iteration capabilities."""
from replicate.use import OutputIterator
# Create mock sync and async iterators
def sync_iterator():
return iter(["Hello", " ", "world", "!"])
async def async_iterator():
for item in ["Hello", " ", "world", "!"]:
yield item
# Test concatenate iterator
concatenate_output = OutputIterator(
sync_iterator, async_iterator, {}, is_concatenate=True
)
# Test sync iteration
sync_result = list(concatenate_output)
assert sync_result == ["Hello", " ", "world", "!"]
# Test async iteration
async_result = []
async for item in concatenate_output:
async_result.append(item)
assert async_result == ["Hello", " ", "world", "!"]
# Test sync string conversion
assert str(concatenate_output) == "Hello world!"
# Test async await (should return joined string for concatenate)
async_result = await concatenate_output
assert async_result == "Hello world!"
@pytest.mark.asyncio
async def test_output_iterator_async_non_concatenate():
"""Test OutputIterator async iteration for non-concatenate iterators."""
from replicate.use import OutputIterator
# Create mock sync and async iterators for non-concatenate case
test_items = ["item1", "item2", "item3"]
def sync_iterator():
return iter(test_items)
async def async_iterator():
for item in test_items:
yield item
# Test non-concatenate iterator
regular_output = OutputIterator(
sync_iterator, async_iterator, {}, is_concatenate=False
)
# Test sync iteration
sync_result = list(regular_output)
assert sync_result == test_items
# Test async iteration
async_result = []
async for item in regular_output:
async_result.append(item)
assert async_result == test_items
# Test sync string conversion
assert str(regular_output) == str(test_items)
# Test async await (should return list for non-concatenate)
async_result = await regular_output
assert async_result == test_items
@pytest.mark.asyncio
@respx.mock
async def test_async_function_concatenate_iterator_output():
"""Test AsyncFunction with concatenate iterator output."""
mock_model_endpoints(
versions=[
create_mock_version(
{
"openapi_schema": {
"components": {
"schemas": {
"Output": {
"type": "array",
"items": {"type": "string"},
"x-cog-array-type": "iterator",
"x-cog-array-display": "concatenate",
}
}
}
}
}
)
]
)
mock_prediction_endpoints(
predictions=[
create_mock_prediction(),
create_mock_prediction(
{"status": "succeeded", "output": ["Async", " ", "Hello", " ", "World"]}
),
]
)
hotdog_detector = replicate.use(
"acme/hotdog-detector", use_async=True, streaming=True
)
run = await hotdog_detector.create(prompt="hello world")
output = await run.output()
from replicate.use import OutputIterator
assert isinstance(output, OutputIterator)
assert str(output) == "Async Hello World"
# Test async await (should return joined string for concatenate)
async_result = await output
assert async_result == "Async Hello World"
# Test async iteration
async_result = []
async for item in output:
async_result.append(item)
assert async_result == ["Async", " ", "Hello", " ", "World"]
# Also test that it's still sync iterable
sync_result = list(output)
assert sync_result == ["Async", " ", "Hello", " ", "World"]
@pytest.mark.asyncio
async def test_output_iterator_await_syntax_demo():
"""Demonstrate the clean await syntax for OutputIterator."""
from replicate.use import OutputIterator
# Create mock iterators
def sync_iterator():
return iter(["Hello", " ", "World"])
async def async_iterator():
for item in ["Hello", " ", "World"]:
yield item
# Test concatenate mode - await returns string
concatenate_output = OutputIterator(
sync_iterator, async_iterator, {}, is_concatenate=True
)
# This is the clean syntax we wanted: str(await iterator)
result = await concatenate_output
assert result == "Hello World"
assert str(result) == "Hello World" # Can use str() on the result
# Test non-concatenate mode - await returns list
regular_output = OutputIterator(
sync_iterator, async_iterator, {}, is_concatenate=False
)
result = await regular_output
assert result == ["Hello", " ", "World"]
assert str(result) == "['Hello', ' ', 'World']" # str() gives list representation
@pytest.mark.asyncio
@pytest.mark.parametrize("client_mode", [ClientMode.DEFAULT, ClientMode.ASYNC])
@respx.mock
async def test_use_concatenate_iterator_without_streaming_returns_string(client_mode):
"""Test that concatenate iterator models without streaming=True return final concatenated string."""
mock_model_endpoints(
versions=[
create_mock_version(
{
"openapi_schema": {
"components": {
"schemas": {
"Output": {
"type": "array",
"items": {"type": "string"},
"x-cog-array-type": "iterator",
"x-cog-array-display": "concatenate",
}
}
}
}
}
)
]
)
mock_prediction_endpoints(
predictions=[
create_mock_prediction(),
create_mock_prediction(
{"status": "succeeded", "output": ["Hello", " ", "world", "!"]}
),
]
)
hotdog_detector = replicate.use(
"acme/hotdog-detector", use_async=client_mode == ClientMode.ASYNC
)
if client_mode == ClientMode.ASYNC:
output = await hotdog_detector(prompt="hello world")
else:
output = hotdog_detector(prompt="hello world")
assert output == "Hello world!"
@pytest.mark.asyncio
@pytest.mark.parametrize("client_mode", [ClientMode.DEFAULT, ClientMode.ASYNC])
@respx.mock
async def test_iterator_output_returns_immediately(client_mode):
"""Test that OutputIterator is returned immediately without waiting for completion."""
mock_model_endpoints(
versions=[
create_mock_version(
{
"openapi_schema": {
"components": {
"schemas": {
"Output": {
"type": "array",
"items": {"type": "string"},
"x-cog-array-type": "iterator",
"x-cog-array-display": "concatenate",
}
}
}
}
}
)
]
)
mock_prediction_endpoints(
predictions=[
create_mock_prediction({"status": "processing", "output": []}),
create_mock_prediction({"status": "processing", "output": ["Hello"]}),
create_mock_prediction(
{"status": "succeeded", "output": ["Hello", " ", "World"]}
),
]
)
hotdog_detector = replicate.use(
"acme/hotdog-detector",
use_async=client_mode == ClientMode.ASYNC,
streaming=True,
)
# Get the output iterator - this should return immediately even though prediction is processing
if client_mode == ClientMode.ASYNC:
run = await hotdog_detector.create(prompt="hello world")
output_iterator = await run.output()
else:
run = hotdog_detector.create(prompt="hello world")
output_iterator = run.output()
from replicate.use import OutputIterator
assert isinstance(output_iterator, OutputIterator)
# Verify the prediction is still processing when we get the iterator
assert run._prediction.status == "processing"
@pytest.mark.asyncio
@pytest.mark.parametrize("client_mode", [ClientMode.DEFAULT, ClientMode.ASYNC])
@respx.mock
async def test_streaming_output_yields_incrementally(client_mode):
"""Test that OutputIterator yields results incrementally during polling."""
mock_model_endpoints(
versions=[
create_mock_version(
{
"openapi_schema": {
"components": {
"schemas": {
"Output": {
"type": "array",
"items": {"type": "string"},
"x-cog-array-type": "iterator",
"x-cog-array-display": "concatenate",
}
}
}
}
}
)
]
)
# Create a prediction that will be polled multiple times
prediction_id = "pred123"
initial_prediction = create_mock_prediction(
{"id": prediction_id, "status": "processing", "output": []},
prediction_id=prediction_id,
)
if client_mode == ClientMode.ASYNC:
respx.post("https://api.replicate.com/v1/predictions").mock(
return_value=httpx.Response(201, json=initial_prediction)
)
else:
respx.post("https://api.replicate.com/v1/predictions").mock(
return_value=httpx.Response(201, json=initial_prediction)
)
poll_responses = [
create_mock_prediction(
{"status": "processing", "output": ["Hello"]}, prediction_id=prediction_id
),
create_mock_prediction(
{"status": "processing", "output": ["Hello", " "]},
prediction_id=prediction_id,
),
create_mock_prediction(
{"status": "processing", "output": ["Hello", " ", "streaming"]},
prediction_id=prediction_id,
),
create_mock_prediction(
{"status": "processing", "output": ["Hello", " ", "streaming", " "]},
prediction_id=prediction_id,
),
create_mock_prediction(
{
"status": "succeeded",
"output": ["Hello", " ", "streaming", " ", "world!"],
},
prediction_id=prediction_id,
),
]
respx.get(f"https://api.replicate.com/v1/predictions/{prediction_id}").mock(
side_effect=[httpx.Response(200, json=resp) for resp in poll_responses]
)
hotdog_detector = replicate.use(
"acme/hotdog-detector",
use_async=client_mode == ClientMode.ASYNC,
streaming=True,
)
# Get the output iterator immediately
if client_mode == ClientMode.ASYNC:
run = await hotdog_detector.create(prompt="hello world", use_async=True)
output_iterator = await run.output()
else:
run = hotdog_detector.create(prompt="hello world")
output_iterator = run.output()
from replicate.use import OutputIterator
assert isinstance(output_iterator, OutputIterator)
# Track when we receive each item to verify incremental delivery
collected_items = []
if client_mode == ClientMode.ASYNC:
async for item in output_iterator:
collected_items.append(item)
# Break after we get some incremental results to verify polling works
if len(collected_items) >= 3:
break
else:
for item in output_iterator:
collected_items.append(item)
# Break after we get some incremental results to verify polling works
if len(collected_items) >= 3:
break
# Verify we got incremental streaming results
assert len(collected_items) >= 3
# The items should be the concatenated string parts from the incremental output
result = "".join(collected_items)
assert "Hello" in result # Should contain the first part we streamed
@pytest.mark.asyncio
@pytest.mark.parametrize("client_mode", [ClientMode.DEFAULT, ClientMode.ASYNC])
@respx.mock
async def test_non_streaming_output_waits_for_completion(client_mode):
"""Test that non-iterator outputs still wait for completion."""
mock_model_endpoints(
versions=[
create_mock_version(
{
"openapi_schema": {
"components": {
"schemas": {
"Output": {"type": "string"} # Non-iterator output
}
}
}
}
)
]
)
mock_prediction_endpoints(
predictions=[
create_mock_prediction({"status": "processing", "output": None}),
create_mock_prediction({"status": "succeeded", "output": "Final result"}),
]
)
hotdog_detector = replicate.use(
"acme/hotdog-detector", use_async=client_mode == ClientMode.ASYNC
)
# For non-iterator output, this should wait for completion
if client_mode == ClientMode.ASYNC:
run = await hotdog_detector.create(prompt="hello world")
output = await run.output()
else:
run = hotdog_detector.create(prompt="hello world")
output = run.output()
# Should get the final result directly
assert output == "Final result"
@pytest.mark.asyncio
@pytest.mark.parametrize("client_mode", [ClientMode.DEFAULT, ClientMode.ASYNC])
@respx.mock
async def test_use_list_of_strings_output(client_mode):
mock_model_endpoints(
versions=[
create_mock_version(
{
"openapi_schema": {
"components": {
"schemas": {
"Output": {
"type": "array",
"items": {"type": "string"},
}
}
}
}
}
)
]
)
mock_prediction_endpoints(
predictions=[
create_mock_prediction(),
create_mock_prediction(
{"status": "succeeded", "output": ["hello", "world", "test"]}
),
]
)
hotdog_detector = replicate.use(
"acme/hotdog-detector", use_async=client_mode == ClientMode.ASYNC
)
if client_mode == ClientMode.ASYNC:
output = await hotdog_detector(prompt="hello world")
else:
output = hotdog_detector(prompt="hello world")
assert output == ["hello", "world", "test"]
@pytest.mark.asyncio
@pytest.mark.parametrize("client_mode", [ClientMode.DEFAULT, ClientMode.ASYNC])
@respx.mock
async def test_use_iterator_of_strings_output(client_mode):
mock_model_endpoints(
versions=[
create_mock_version(
{
"openapi_schema": {
"components": {
"schemas": {
"Output": {
"type": "array",
"items": {"type": "string"},
"x-cog-array-type": "iterator",
}
}
}
}
}
)
]
)
mock_prediction_endpoints(
predictions=[
create_mock_prediction(),
create_mock_prediction(
{"status": "succeeded", "output": ["hello", "world", "test"]}
),
]
)
hotdog_detector = replicate.use(
"acme/hotdog-detector",
use_async=client_mode == ClientMode.ASYNC,
streaming=True,
)
if client_mode == ClientMode.ASYNC:
output = await hotdog_detector(prompt="hello world")
else:
output = hotdog_detector(prompt="hello world")