-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtest_errors.py
More file actions
1363 lines (1178 loc) · 42.5 KB
/
test_errors.py
File metadata and controls
1363 lines (1178 loc) · 42.5 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
from typing import Any, AsyncIterable, AsyncIterator, Callable
from unittest.mock import patch
import httpx
import pytest
import respx
from openai.types.responses.response import Response
from openai.types.responses.response_in_progress_event import (
ResponseInProgressEvent,
)
from respx.types import SideEffectTypes
from aidial_adapter_openai.configuration.app_config import ApplicationConfig
from aidial_adapter_openai.configuration.deployment_type import (
ChatCompletionDeploymentType,
)
from tests.conftest import create_test_client
from tests.integration_tests.constants import (
IMAGE_RESOURCE,
PDF_DOCUMENT_RESOURCE,
)
from tests.utils.dictionary import exclude_keys
from tests.utils.openai import (
user_with_file_content_part,
user_with_image_content_part,
)
from tests.utils.stream import (
OpenAIStream,
create_choice,
many_choices_chunk,
single_choice_chunk,
)
_API_VERSION = "api-version=2023-03-15-preview"
_UPSTREAM_ENDPOINT = (
"http://localhost:5001/openai/deployments/gpt-4/chat/completions"
)
@pytest.fixture(autouse=True)
def mock_azure_ad_token():
with patch(
"aidial_adapter_openai.utils.auth.get_api_key",
return_value="test-azure-ad-token",
):
yield
def assert_equal(actual: Any, expected: Any):
assert actual == expected
def assert_equal_no_dynamic_fields(actual: Any, expected: Any):
if isinstance(actual, dict) and isinstance(expected, dict):
keys = {"id", "created"}
assert exclude_keys(actual, keys) == exclude_keys(expected, keys)
else:
assert actual == expected
def mock_response(
status_code: int,
content_type: str,
content: str,
*,
check_request: Callable[[httpx.Request], None] = lambda _: None,
extra_headers: dict[str, str] = {},
) -> SideEffectTypes:
def side_effect(request: httpx.Request):
check_request(request)
return httpx.Response(
status_code=status_code,
headers={
"content-type": content_type,
**extra_headers,
},
content=content,
)
return side_effect
@respx.mock
async def test_single_chunk_token_counting(test_app: httpx.AsyncClient):
# The adapter tolerates top-level extra fields
# and passes it further to the upstream endpoint.
mock_stream = OpenAIStream(
single_choice_chunk(
delta={"role": "assistant", "content": "5"}, finish_reason="stop"
),
)
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).respond(
status_code=200,
content_type="text/event-stream",
content=mock_stream.to_content(),
)
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={
"messages": [{"role": "user", "content": "Test content"}],
"stream": True,
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 200
mock_stream.assert_response_content(
response,
assert_equal,
usages={
0: {
"prompt_tokens": 9,
"completion_tokens": 1,
"total_tokens": 10,
}
},
)
@respx.mock
async def test_top_level_extra_field(test_app: httpx.AsyncClient):
# The adapter tolerates top-level extra fields
# and passes it further to the upstream endpoint.
mock_stream = OpenAIStream(
{"error": {"message": "whatever", "code": "500"}}
)
def check_request(request: httpx.Request):
assert json.loads(request.content)["extra_field"] == 1
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).mock(
side_effect=mock_response(
status_code=200,
content_type="text/event-stream",
content=mock_stream.to_content(),
check_request=check_request,
),
)
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={
"messages": [{"role": "user", "content": "Test content"}],
"stream": True,
"extra_field": 1,
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 500
assert response.json() == {"error": {"message": "whatever", "code": "500"}}
@respx.mock
async def test_nested_extra_field(test_app: httpx.AsyncClient):
# The adapter tolerates nested extra fields
# and passes it further to the upstream endpoint.
mock_stream = OpenAIStream(
{"error": {"message": "whatever", "code": "500"}}
)
def check_request(request: httpx.Request):
assert json.loads(request.content)["messages"][0]["extra_field"] == 1
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).mock(
side_effect=mock_response(
status_code=200,
content_type="text/event-stream",
content=mock_stream.to_content(),
check_request=check_request,
),
)
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={
"messages": [
{"role": "user", "content": "2+3=?", "extra_field": 1}
],
"stream": True,
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 500
assert response.json() == {"error": {"message": "whatever", "code": "500"}}
@respx.mock
async def test_missing_api_version(test_app: httpx.AsyncClient):
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions",
json={
"messages": [{"role": "user", "content": "Test content"}],
"stream": True,
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 400
assert response.json() == {
"error": {
"code": "400",
"message": "api-version is a required query parameter",
"type": "invalid_request_error",
}
}
@respx.mock
async def test_error_during_streaming_stopped(test_app: httpx.AsyncClient):
mock_stream = OpenAIStream(
single_choice_chunk(finish_reason="stop", delta={"role": "assistant"}),
{
"error": {
"message": "Error test",
"type": "runtime_error",
"code": "500",
"extra_error_field": "extra_error_value",
}
},
)
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).respond(
status_code=200,
content_type="text/event-stream",
content=mock_stream.to_content(),
)
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={
"messages": [{"role": "user", "content": "Test content"}],
"stream": True,
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 200
mock_stream.assert_response_content(
response,
assert_equal,
usages={
0: {
"prompt_tokens": 9,
"completion_tokens": 0,
"total_tokens": 9,
}
},
)
@respx.mock
async def test_error_during_streaming_unfinished(test_app: httpx.AsyncClient):
mock_stream = OpenAIStream(
single_choice_chunk(delta={"role": "assistant", "content": "hello "}),
{
"error": {
"message": "Error test",
"type": "runtime_error",
"code": "500",
"extra_error_field": "extra_error_value",
}
},
)
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).respond(
status_code=200,
content_type="text/event-stream",
content=mock_stream.to_content(),
)
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={
"messages": [{"role": "user", "content": "Test content"}],
"stream": True,
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 200
mock_stream.assert_response_content(
response,
assert_equal,
usages={
0: {
"completion_tokens": 2,
"prompt_tokens": 9,
"total_tokens": 11,
}
},
)
@respx.mock
async def test_interrupted_stream_single_choice(test_app: httpx.AsyncClient):
mock_stream = OpenAIStream(
single_choice_chunk(delta={"role": "assistant", "content": "hello"}),
)
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).respond(
status_code=200,
content_type="text/event-stream",
content=mock_stream.to_content(),
)
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={
"messages": [{"role": "user", "content": "Test content"}],
"stream": True,
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 200
expected_stream = OpenAIStream(
single_choice_chunk(
delta={"role": "assistant", "content": "hello"},
finish_reason="length",
usage={
"completion_tokens": 1,
"prompt_tokens": 9,
"total_tokens": 10,
},
)
)
expected_stream.assert_response_content(response, assert_equal)
@respx.mock
async def test_interrupted_stream_many_choices(test_app: httpx.AsyncClient):
mock_stream = OpenAIStream(
single_choice_chunk(
delta={"role": "assistant", "content": "hello1"}, choice_index=0
),
single_choice_chunk(
delta={"role": "assistant", "content": "hello2"}, choice_index=1
),
)
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).respond(
status_code=200,
content_type="text/event-stream",
content=mock_stream.to_content(),
)
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={
"messages": [{"role": "user", "content": "Test content"}],
"stream": True,
"n": 3,
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 200
expected_stream = OpenAIStream(
single_choice_chunk(
choice_index=0,
delta={"role": "assistant", "content": "hello1"},
),
many_choices_chunk(
choices=[
create_choice(
index=1,
delta={"role": "assistant", "content": "hello2"},
finish_reason="length",
),
create_choice(index=0, finish_reason="length"),
create_choice(index=2, finish_reason="length"),
],
usage={
"completion_tokens": 4,
"prompt_tokens": 9,
"total_tokens": 13,
},
),
)
expected_stream.assert_response_content(response, assert_equal)
@respx.mock
async def test_zero_chunk_stream(test_app: httpx.AsyncClient):
mock_stream = OpenAIStream()
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).respond(
status_code=200,
content_type="text/event-stream",
content=mock_stream.to_content(),
)
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={
"messages": [{"role": "user", "content": "Test content"}],
"stream": True,
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 200
expected_final_chunk = single_choice_chunk(
delta={},
finish_reason="length",
usage={"prompt_tokens": 9, "completion_tokens": 0, "total_tokens": 9},
)
expected_stream = OpenAIStream(expected_final_chunk)
expected_stream.assert_response_content(
response, assert_equal_no_dynamic_fields
)
@respx.mock
async def test_incorrect_upstream_url(test_app: httpx.AsyncClient):
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={"messages": [{"role": "user", "content": "Test content"}]},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
# upstream endpoint should contain the full path
"X-UPSTREAM-ENDPOINT": "http://localhost:5001",
},
)
assert response.status_code == 502
assert response.json() == {
"error": {
"message": "Invalid upstream endpoint format",
"type": "internal_server_error",
"code": "502",
}
}
@respx.mock
async def test_no_request_response_validation(test_app: httpx.AsyncClient):
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).respond(
status_code=200, json={"messages": "string", "extra_response": "string"}
)
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={
"messages": [
{
"role": "user",
"content": "Test content",
"extra_mesage": "string",
}
],
"extra_request": "string",
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
"Content-Type": "application/pdf",
},
)
assert response.status_code == 200
assert response.json() == {
"messages": "string",
"extra_response": "string",
}
@respx.mock
async def test_status_error_from_upstream(test_app: httpx.AsyncClient):
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).respond(status_code=400, content="Bad request")
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={"messages": [{"role": "user", "content": "Test content"}]},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 400
assert response.text == "Bad request"
@respx.mock
async def test_status_error_from_upstream_with_headers(
test_app: httpx.AsyncClient,
):
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).respond(
status_code=429,
content="Too many requests",
headers={"Retry-After": "42"},
)
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={"messages": [{"role": "user", "content": "Test content"}]},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 429
assert response.text == "Too many requests"
assert response.headers["Retry-After"] == "42"
@respx.mock
async def test_timeout_error_from_upstream(test_app: httpx.AsyncClient):
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).mock(side_effect=httpx.ReadTimeout("Timeout error"))
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={"messages": [{"role": "user", "content": "Test content"}]},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 504
assert response.json() == {
"error": {
"message": "Request timed out",
"type": "timeout",
"code": "504",
"display_message": "Request timed out. Please try again later.",
}
}
@respx.mock
async def test_connection_error_from_upstream_non_streaming(
test_app: httpx.AsyncClient,
):
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).mock(side_effect=httpx.ConnectError("Connection error"))
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={"messages": [{"role": "user", "content": "Test content"}]},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 502
assert response.json() == {
"error": {
"message": "Error communicating with OpenAI",
"type": "connection",
"code": "502",
"display_message": "OpenAI server is not responsive. Please try again later.",
}
}
@respx.mock
async def test_content_length_of_response_error(test_app: httpx.AsyncClient):
upstream_response = """
{
"error": {
"message": "Bad request",
"code": "400"
}
}
"""
upstream_response_content_length = str(len(upstream_response))
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).mock(
side_effect=mock_response(
400,
"application/json",
upstream_response,
extra_headers={"content-length": upstream_response_content_length},
)
)
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={"messages": [{"role": "user", "content": "Test content"}]},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
expected_response = json.dumps(
json.loads(upstream_response), separators=(",", ":")
)
expected_content_length = str(len(expected_response))
assert response.status_code == 400
assert response.text == expected_response
assert response.headers["content-length"] == expected_content_length
assert upstream_response_content_length != expected_content_length
@respx.mock
async def test_connection_error_from_upstream_streaming(
test_app: httpx.AsyncClient,
):
async def mock_stream() -> AsyncIterable[bytes]:
yield b'data: {"message": "first chunk"}\n\n'
yield b'data: {"message": "second chunk"}\n\n'
raise httpx.ConnectError("Connection error")
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).respond(
status_code=200,
content_type="text/event-stream",
content=mock_stream(),
)
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={
"stream": True,
"messages": [{"role": "user", "content": "Test content"}],
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 200
assert response.text == "\n\n".join(
[
'data: {"message":"first chunk"}',
'data: {"message":"second chunk"}',
'data: {"error":{"message":"Connection error","type":"internal_server_error","code":"500"}}',
"data: [DONE]",
"",
]
)
@respx.mock
async def test_adapter_internal_error(
test_app: httpx.AsyncClient,
):
async def mock_generate_stream(stream: AsyncIterator[dict], **kwargs):
yield await stream.__anext__()
raise ValueError("failed generating the stream")
with patch(
"aidial_adapter_openai.chat_completions.gpt.generate_stream",
side_effect=mock_generate_stream,
):
async def mock_stream() -> AsyncIterable[bytes]:
yield b'data: {"message": "first chunk"}\n\n'
yield b'data: {"message": "second chunk"}\n\n'
yield b"data: [DONE]"
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).respond(
status_code=200,
content_type="text/event-stream",
content=mock_stream(),
)
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={
"stream": True,
"messages": [{"role": "user", "content": "Test content"}],
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 200
assert response.text == "\n\n".join(
[
'data: {"message":"first chunk"}',
'data: {"error":{"message":"failed generating the stream","type":"internal_server_error","code":"500"}}',
"data: [DONE]",
"",
]
)
@respx.mock
async def test_invalid_chunk_stream_from_upstream(
test_app: httpx.AsyncClient,
):
async def mock_stream() -> AsyncIterable[bytes]:
yield b"data: chunk1\n\n"
yield b"data: chunk2\n\n"
yield b"data: [DONE]\n\n"
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).respond(
status_code=200,
content_type="text/event-stream",
content=mock_stream(),
)
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={
"stream": True,
"messages": [{"role": "user", "content": "Test content"}],
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
assert response.status_code == 500
assert response.json() == {
"error": {
"message": "Expecting value: line 1 column 1 (char 0)",
"type": "internal_server_error",
"code": "500",
}
}
@respx.mock
async def test_unexpected_multi_modal_input_streaming(
test_app: httpx.AsyncClient, caplog
):
mock_stream = OpenAIStream(
single_choice_chunk(delta={"role": "assistant"}),
single_choice_chunk(delta={"content": "Test response"}),
single_choice_chunk(delta={}, finish_reason="stop"),
)
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).respond(
status_code=200,
content=mock_stream.to_content(),
content_type="text/event-stream",
)
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={
"stream": True,
"messages": [
user_with_image_content_part("image1", IMAGE_RESOURCE),
user_with_image_content_part("image2", IMAGE_RESOURCE),
user_with_file_content_part(
"file1", "file1", PDF_DOCUMENT_RESOURCE
),
],
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
file_not_supported = (
"Content part type 'file' is not supported by the tokenizer. "
"Tokens for this content part will be ignored."
)
image_not_supported = (
"Image content detected, however, the image tokenization algorithm is not known for this deployment. "
"Tokens for the image will be ignored. "
"Declare the deployment in either GPT4O_DEPLOYMENTS or GPT4O_MINI_DEPLOYMENTS "
"to specify the image tokenization algorithm."
)
log_messages = [record.message for record in caplog.records]
assert file_not_supported in log_messages
assert image_not_supported in log_messages
assert response.status_code == 200
mock_stream.assert_response_content(
response,
assert_equal_no_dynamic_fields,
usages={
2: {
"prompt_tokens": 21,
"completion_tokens": 2,
"total_tokens": 23,
}
},
)
@respx.mock
async def test_invalid_image_url_streaming_catch_all(
test_app: httpx.AsyncClient,
):
mock_stream = OpenAIStream(
single_choice_chunk(delta={"role": "assistant"}),
single_choice_chunk(delta={"content": "Test response"}),
single_choice_chunk(delta={}, finish_reason="stop"),
)
respx.post(
"http://localhost:5001/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview"
).respond(
status_code=200,
content=mock_stream.to_content(),
content_type="text/event-stream",
)
image_url = "http://xyz.com/image.png"
respx.get(image_url).respond(status_code=404, content="Not Found")
response = await test_app.post(
"/openai/deployments/gpt-4/chat/completions?api-version=2023-03-15-preview",
json={
"stream": True,
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": image_url,
"detail": "auto",
},
}
],
}
],
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/gpt-4/chat/completions",
},
)
error_message = f"The following files failed to process:\n1. {image_url}: failed to download the image content part"
response_stream = OpenAIStream(
{
"error": {
"code": "400",
"type": "invalid_request_error",
"message": error_message,
"display_message": error_message,
}
},
)
assert response.status_code == 400
response_stream.assert_response_content(
response, assert_equal_no_dynamic_fields
)
@respx.mock
async def test_invalid_image_url_streaming_gpt4o():
app_config = (
ApplicationConfig()
.add_deployment("app", ChatCompletionDeploymentType.GPT4O)
.map_to_tiktoken_model("app", "gpt-4")
)
async with create_test_client(app_config) as test_app:
mock_stream = OpenAIStream(
single_choice_chunk(delta={"role": "assistant"}),
single_choice_chunk(delta={"content": "Test response"}),
single_choice_chunk(delta={}, finish_reason="stop"),
)
respx.post(
"http://localhost:5001/openai/deployments/upstream-model/chat/completions?api-version=2023-03-15-preview"
).respond(
status_code=200,
content=mock_stream.to_content(),
content_type="text/event-stream",
)
image_url = "http://xyz.com/image.png"
respx.get(image_url).respond(status_code=404, content="Not Found")
response = await test_app.post(
"/openai/deployments/app/chat/completions?api-version=2023-03-15-preview",
json={
"stream": True,
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": image_url,
"detail": "auto",
},
}
],
}
],
},
headers={
"X-UPSTREAM-KEY": "TEST_API_KEY",
"X-UPSTREAM-ENDPOINT": "http://localhost:5001/openai/deployments/upstream-model/chat/completions",
},
)
error_message = f"The following files failed to process:\n1. {image_url}: failed to download the image content part"
response_stream = OpenAIStream(
{
"error": {
"code": "400",
"type": "invalid_request_error",
"message": error_message,
"display_message": error_message,
}
},
)
assert response.status_code == 400
response_stream.assert_response_content(
response, assert_equal_no_dynamic_fields
)