-
Notifications
You must be signed in to change notification settings - Fork 841
Expand file tree
/
Copy pathtest_openai.py
More file actions
1703 lines (1425 loc) · 58.5 KB
/
test_openai.py
File metadata and controls
1703 lines (1425 loc) · 58.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 logging
import unittest.mock
import openai
import pydantic
import pytest
import strands
from strands.models.openai import OpenAIModel
from strands.types.exceptions import ContextWindowOverflowException, ModelThrottledException
@pytest.fixture
def openai_client():
with unittest.mock.patch.object(strands.models.openai.openai, "AsyncOpenAI") as mock_client_cls:
mock_client = unittest.mock.AsyncMock()
# Make the mock client work as an async context manager
mock_client.__aenter__ = unittest.mock.AsyncMock(return_value=mock_client)
mock_client.__aexit__ = unittest.mock.AsyncMock(return_value=None)
mock_client_cls.return_value = mock_client
yield mock_client
@pytest.fixture
def model_id():
return "m1"
@pytest.fixture
def model(openai_client, model_id):
_ = openai_client
return OpenAIModel(model_id=model_id, params={"max_tokens": 1})
@pytest.fixture
def messages():
return [{"role": "user", "content": [{"text": "test"}]}]
@pytest.fixture
def tool_specs():
return [
{
"name": "test_tool",
"description": "A test tool",
"inputSchema": {
"json": {
"type": "object",
"properties": {
"input": {"type": "string"},
},
"required": ["input"],
},
},
},
]
@pytest.fixture
def system_prompt():
return "s1"
@pytest.fixture
def test_output_model_cls():
class TestOutputModel(pydantic.BaseModel):
name: str
age: int
return TestOutputModel
def test__init__(model_id):
model = OpenAIModel(model_id=model_id, params={"max_tokens": 1})
tru_config = model.get_config()
exp_config = {"model_id": "m1", "params": {"max_tokens": 1}}
assert tru_config == exp_config
def test_update_config(model, model_id):
model.update_config(model_id=model_id)
tru_model_id = model.get_config().get("model_id")
exp_model_id = model_id
assert tru_model_id == exp_model_id
@pytest.mark.parametrize(
"content, exp_result",
[
# Document
(
{
"document": {
"format": "pdf",
"name": "test doc",
"source": {"bytes": b"document"},
},
},
{
"file": {
"file_data": "data:application/pdf;base64,ZG9jdW1lbnQ=",
"filename": "test doc",
},
"type": "file",
},
),
# Image
(
{
"image": {
"format": "jpg",
"source": {"bytes": b"image"},
},
},
{
"image_url": {
"detail": "auto",
"format": "image/jpeg",
"url": "data:image/jpeg;base64,aW1hZ2U=",
},
"type": "image_url",
},
),
# Text
(
{"text": "hello"},
{"type": "text", "text": "hello"},
),
],
)
def test_format_request_message_content(content, exp_result):
tru_result = OpenAIModel.format_request_message_content(content)
assert tru_result == exp_result
def test_format_request_message_content_unsupported_type():
content = {"unsupported": {}}
with pytest.raises(TypeError, match="content_type=<unsupported> | unsupported type"):
OpenAIModel.format_request_message_content(content)
def test_format_request_message_tool_call():
tool_use = {
"input": {"expression": "2+2"},
"name": "calculator",
"toolUseId": "c1",
}
tru_result = OpenAIModel.format_request_message_tool_call(tool_use)
exp_result = {
"function": {
"arguments": '{"expression": "2+2"}',
"name": "calculator",
},
"id": "c1",
"type": "function",
}
assert tru_result == exp_result
def test_format_request_tool_message():
tool_result = {
"content": [{"text": "4"}, {"json": ["4"]}],
"status": "success",
"toolUseId": "c1",
}
tru_result = OpenAIModel.format_request_tool_message(tool_result)
exp_result = {
"content": '4\n["4"]',
"role": "tool",
"tool_call_id": "c1",
}
assert tru_result == exp_result
def test_format_request_tool_message_single_text_returns_string():
"""Test that single text content is returned as string for model compatibility."""
tool_result = {
"content": [{"text": '{"result": "success"}'}],
"status": "success",
"toolUseId": "c1",
}
tru_result = OpenAIModel.format_request_tool_message(tool_result)
exp_result = {
"content": '{"result": "success"}',
"role": "tool",
"tool_call_id": "c1",
}
assert tru_result == exp_result
def test_format_request_tool_message_multi_text_returns_joined_string():
"""Test that multi-content text results are joined into a single string.
Regression test for https://github.com/strands-agents/sdk-python/issues/1696.
OpenAI-compatible endpoints (e.g., Kimi K2.5, vLLM, Ollama) only correctly
parse string content for tool messages; array format causes hallucinated results.
"""
tool_result = {
"content": [
{"text": "Temperature: 72°F"},
{"json": {"humidity": 45, "unit": "%"}},
{"text": "Wind: 5 mph"},
],
"status": "success",
"toolUseId": "c1",
}
tru_result = OpenAIModel.format_request_tool_message(tool_result)
exp_result = {
"content": 'Temperature: 72°F\n{"humidity": 45, "unit": "%"}\nWind: 5 mph',
"role": "tool",
"tool_call_id": "c1",
}
assert tru_result == exp_result
def test_format_request_tool_message_mixed_text_image_preserves_order():
"""Test that text and image content blocks preserve their original order."""
tool_result = {
"content": [
{"text": "Before image"},
{"image": {"format": "png", "source": {"bytes": b"PNG"}}},
{"text": "After image"},
],
"status": "success",
"toolUseId": "c1",
}
tru_result = OpenAIModel.format_request_tool_message(tool_result)
content = tru_result["content"]
# Array format since images are present
assert isinstance(content, list)
assert len(content) == 3
# Order preserved: text, image, text
assert content[0] == {"type": "text", "text": "Before image"}
assert content[1]["type"] == "image_url"
assert content[2] == {"type": "text", "text": "After image"}
def test_format_request_tool_message_merges_adjacent_text():
"""Test that adjacent text blocks are merged while non-text order is preserved."""
tool_result = {
"content": [
{"text": "Line 1"},
{"text": "Line 2"},
{"image": {"format": "png", "source": {"bytes": b"PNG"}}},
{"text": "Line 3"},
],
"status": "success",
"toolUseId": "c1",
}
tru_result = OpenAIModel.format_request_tool_message(tool_result)
content = tru_result["content"]
assert isinstance(content, list)
assert len(content) == 3
# Adjacent text merged, image order preserved
assert content[0] == {"type": "text", "text": "Line 1\nLine 2"}
assert content[1]["type"] == "image_url"
assert content[2] == {"type": "text", "text": "Line 3"}
def test_format_request_tool_message_image_only():
"""Test tool message with only non-text content."""
tool_result = {
"content": [
{"image": {"format": "png", "source": {"bytes": b"PNG"}}},
],
"status": "success",
"toolUseId": "c1",
}
tru_result = OpenAIModel.format_request_tool_message(tool_result)
content = tru_result["content"]
assert isinstance(content, list)
assert len(content) == 1
assert content[0]["type"] == "image_url"
def test_format_request_tool_message_document_mixed():
"""Test tool message with document content mixed with text."""
tool_result = {
"content": [
{"text": "Summary"},
{"document": {"format": "pdf", "name": "report.pdf", "source": {"bytes": b"PDF"}}},
{"text": "Footer"},
],
"status": "success",
"toolUseId": "c1",
}
tru_result = OpenAIModel.format_request_tool_message(tool_result)
content = tru_result["content"]
assert isinstance(content, list)
assert len(content) == 3
assert content[0] == {"type": "text", "text": "Summary"}
assert content[1]["type"] == "file"
assert content[2] == {"type": "text", "text": "Footer"}
def test_format_request_tool_message_empty_content():
"""Test tool message with empty content list returns empty string."""
tool_result = {
"content": [],
"status": "success",
"toolUseId": "c1",
}
tru_result = OpenAIModel.format_request_tool_message(tool_result)
assert tru_result["content"] == ""
assert tru_result["role"] == "tool"
assert tru_result["tool_call_id"] == "c1"
def test_split_tool_message_images_with_image():
"""Test that images are extracted from tool messages."""
tool_message = {
"role": "tool",
"tool_call_id": "c1",
"content": [
{"type": "text", "text": "Result"},
{
"type": "image_url",
"image_url": {"url": "data:image/png;base64,iVBORw0KGgo=", "detail": "auto", "format": "image/png"},
},
],
}
tool_clean, user_with_image = OpenAIModel._split_tool_message_images(tool_message)
# Tool message should now have the original text plus the appended informational text
assert tool_clean["role"] == "tool"
assert tool_clean["tool_call_id"] == "c1"
assert len(tool_clean["content"]) == 2
assert tool_clean["content"][0]["type"] == "text"
assert tool_clean["content"][0]["text"] == "Result"
assert "Tool successfully returned an image" in tool_clean["content"][1]["text"]
# User message should have the image
assert user_with_image is not None
assert user_with_image["role"] == "user"
assert len(user_with_image["content"]) == 1
assert user_with_image["content"][0]["type"] == "image_url"
def test_split_tool_message_images_without_image():
"""Test that tool messages without images are unchanged."""
tool_message = {"role": "tool", "tool_call_id": "c1", "content": [{"type": "text", "text": "Result"}]}
tool_clean, user_with_image = OpenAIModel._split_tool_message_images(tool_message)
assert tool_clean == tool_message
assert user_with_image is None
def test_split_tool_message_images_only_image():
"""Test tool message with only image content."""
tool_message = {
"role": "tool",
"tool_call_id": "c1",
"content": [{"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}}],
}
tool_clean, user_with_image = OpenAIModel._split_tool_message_images(tool_message)
# Tool message should have default text
assert tool_clean["role"] == "tool"
assert len(tool_clean["content"]) == 1
assert "successfully" in tool_clean["content"][0]["text"].lower()
# User message should have the image
assert user_with_image is not None
assert user_with_image["role"] == "user"
assert len(user_with_image["content"]) == 1
def test_split_tool_message_images_non_tool_role():
"""Test that messages with roles other than 'tool' are ignored."""
user_msg = {"role": "user", "content": [{"type": "text", "text": "hello"}]}
clean, extra = OpenAIModel._split_tool_message_images(user_msg)
assert clean == user_msg
assert extra is None
def test_split_tool_message_images_invalid_content_type():
"""Test that messages with non-list content are ignored."""
invalid_msg = {"role": "tool", "content": "not a list"}
clean, extra = OpenAIModel._split_tool_message_images(invalid_msg)
assert clean == invalid_msg
assert extra is None
def test_format_request_messages_with_tool_result_containing_image():
"""Test that tool results with images are properly split into tool and user messages."""
messages = [
{
"content": [{"text": "Run the tool"}],
"role": "user",
},
{
"content": [
{
"toolUse": {
"input": {},
"name": "image_tool",
"toolUseId": "t1",
},
},
],
"role": "assistant",
},
{
"content": [
{
"toolResult": {
"toolUseId": "t1",
"status": "success",
"content": [
{"text": "Image generated"},
{
"image": {
"format": "png",
"source": {"bytes": b"fake_image_data"},
}
},
],
}
}
],
"role": "user",
},
]
formatted = OpenAIModel.format_request_messages(messages)
# Find the tool message
tool_messages = [msg for msg in formatted if msg.get("role") == "tool"]
assert len(tool_messages) == 1
# Tool message should only have text content
tool_msg = tool_messages[0]
assert all(c.get("type") != "image_url" for c in tool_msg["content"])
# There should be a user message right after the tool message with the image
tool_msg_idx = formatted.index(tool_msg)
assert tool_msg_idx + 1 < len(formatted)
user_msg = formatted[tool_msg_idx + 1]
assert user_msg["role"] == "user"
assert any(c.get("type") == "image_url" for c in user_msg["content"])
def test_format_request_messages_with_multiple_images_in_tool_result():
"""Test tool result with multiple images."""
messages = [
{
"content": [
{
"toolResult": {
"toolUseId": "t1",
"status": "success",
"content": [
{"text": "Two images generated"},
{
"image": {
"format": "png",
"source": {"bytes": b"image1"},
}
},
{
"image": {
"format": "jpg",
"source": {"bytes": b"image2"},
}
},
],
}
}
],
"role": "user",
},
]
formatted = OpenAIModel.format_request_messages(messages)
# Find user message with images
user_image_msgs = [
msg
for msg in formatted
if msg.get("role") == "user" and any(c.get("type") == "image_url" for c in msg.get("content", []))
]
assert len(user_image_msgs) == 1
# Should have both images
image_contents = [c for c in user_image_msgs[0]["content"] if c.get("type") == "image_url"]
assert len(image_contents) == 2
def test_format_request_tool_choice_auto():
tool_choice = {"auto": {}}
tru_result = OpenAIModel._format_request_tool_choice(tool_choice)
exp_result = {"tool_choice": "auto"}
assert tru_result == exp_result
def test_format_request_tool_choice_any():
tool_choice = {"any": {}}
tru_result = OpenAIModel._format_request_tool_choice(tool_choice)
exp_result = {"tool_choice": "required"}
assert tru_result == exp_result
def test_format_request_tool_choice_tool():
tool_choice = {"tool": {"name": "test_tool"}}
tru_result = OpenAIModel._format_request_tool_choice(tool_choice)
exp_result = {"tool_choice": {"type": "function", "function": {"name": "test_tool"}}}
assert tru_result == exp_result
def test_format_request_messages(system_prompt):
messages = [
{
"content": [],
"role": "user",
},
{
"content": [{"text": "hello"}],
"role": "user",
},
{
"content": [
{"text": "call tool"},
{
"toolUse": {
"input": {"expression": "2+2"},
"name": "calculator",
"toolUseId": "c1",
},
},
],
"role": "assistant",
},
{
"content": [{"toolResult": {"toolUseId": "c1", "status": "success", "content": [{"text": "4"}]}}],
"role": "user",
},
]
tru_result = OpenAIModel.format_request_messages(messages, system_prompt)
exp_result = [
{
"content": system_prompt,
"role": "system",
},
{
"content": [{"text": "hello", "type": "text"}],
"role": "user",
},
{
"content": [{"text": "call tool", "type": "text"}],
"role": "assistant",
"tool_calls": [
{
"function": {
"name": "calculator",
"arguments": '{"expression": "2+2"}',
},
"id": "c1",
"type": "function",
}
],
},
{
"content": "4",
"role": "tool",
"tool_call_id": "c1",
},
]
assert tru_result == exp_result
def test_format_request(model, messages, tool_specs, system_prompt):
tru_request = model.format_request(messages, tool_specs, system_prompt)
exp_request = {
"messages": [
{
"content": system_prompt,
"role": "system",
},
{
"content": [{"text": "test", "type": "text"}],
"role": "user",
},
],
"model": "m1",
"stream": True,
"stream_options": {"include_usage": True},
"tools": [
{
"function": {
"description": "A test tool",
"name": "test_tool",
"parameters": {
"properties": {
"input": {"type": "string"},
},
"required": ["input"],
"type": "object",
},
},
"type": "function",
},
],
"max_tokens": 1,
}
assert tru_request == exp_request
def test_format_request_with_tool_choice_auto(model, messages, tool_specs, system_prompt):
tool_choice = {"auto": {}}
tru_request = model.format_request(messages, tool_specs, system_prompt, tool_choice)
exp_request = {
"messages": [
{
"content": system_prompt,
"role": "system",
},
{
"content": [{"text": "test", "type": "text"}],
"role": "user",
},
],
"model": "m1",
"stream": True,
"stream_options": {"include_usage": True},
"tools": [
{
"function": {
"description": "A test tool",
"name": "test_tool",
"parameters": {
"properties": {
"input": {"type": "string"},
},
"required": ["input"],
"type": "object",
},
},
"type": "function",
},
],
"tool_choice": "auto",
"max_tokens": 1,
}
assert tru_request == exp_request
def test_format_request_with_tool_choice_any(model, messages, tool_specs, system_prompt):
tool_choice = {"any": {}}
tru_request = model.format_request(messages, tool_specs, system_prompt, tool_choice)
exp_request = {
"messages": [
{
"content": system_prompt,
"role": "system",
},
{
"content": [{"text": "test", "type": "text"}],
"role": "user",
},
],
"model": "m1",
"stream": True,
"stream_options": {"include_usage": True},
"tools": [
{
"function": {
"description": "A test tool",
"name": "test_tool",
"parameters": {
"properties": {
"input": {"type": "string"},
},
"required": ["input"],
"type": "object",
},
},
"type": "function",
},
],
"tool_choice": "required",
"max_tokens": 1,
}
assert tru_request == exp_request
def test_format_request_with_tool_choice_tool(model, messages, tool_specs, system_prompt):
tool_choice = {"tool": {"name": "test_tool"}}
tru_request = model.format_request(messages, tool_specs, system_prompt, tool_choice)
exp_request = {
"messages": [
{
"content": system_prompt,
"role": "system",
},
{
"content": [{"text": "test", "type": "text"}],
"role": "user",
},
],
"model": "m1",
"stream": True,
"stream_options": {"include_usage": True},
"tools": [
{
"function": {
"description": "A test tool",
"name": "test_tool",
"parameters": {
"properties": {
"input": {"type": "string"},
},
"required": ["input"],
"type": "object",
},
},
"type": "function",
},
],
"tool_choice": {"type": "function", "function": {"name": "test_tool"}},
"max_tokens": 1,
}
assert tru_request == exp_request
@pytest.mark.parametrize(
("event", "exp_chunk"),
[
# Message start
(
{"chunk_type": "message_start"},
{"messageStart": {"role": "assistant"}},
),
# Content Start - Tool Use
(
{
"chunk_type": "content_start",
"data_type": "tool",
"data": unittest.mock.Mock(**{"function.name": "calculator", "id": "c1"}),
},
{"contentBlockStart": {"start": {"toolUse": {"name": "calculator", "toolUseId": "c1"}}}},
),
# Content Start - Text
(
{"chunk_type": "content_start", "data_type": "text"},
{"contentBlockStart": {"start": {}}},
),
# Content Delta - Tool Use
(
{
"chunk_type": "content_delta",
"data_type": "tool",
"data": unittest.mock.Mock(function=unittest.mock.Mock(arguments='{"expression": "2+2"}')),
},
{"contentBlockDelta": {"delta": {"toolUse": {"input": '{"expression": "2+2"}'}}}},
),
# Content Delta - Tool Use - None
(
{
"chunk_type": "content_delta",
"data_type": "tool",
"data": unittest.mock.Mock(function=unittest.mock.Mock(arguments=None)),
},
{"contentBlockDelta": {"delta": {"toolUse": {"input": ""}}}},
),
# Content Delta - Reasoning Text
(
{"chunk_type": "content_delta", "data_type": "reasoning_content", "data": "I'm thinking"},
{"contentBlockDelta": {"delta": {"reasoningContent": {"text": "I'm thinking"}}}},
),
# Content Delta - Text
(
{"chunk_type": "content_delta", "data_type": "text", "data": "hello"},
{"contentBlockDelta": {"delta": {"text": "hello"}}},
),
# Content Stop
(
{"chunk_type": "content_stop"},
{"contentBlockStop": {}},
),
# Message Stop - Tool Use
(
{"chunk_type": "message_stop", "data": "tool_calls"},
{"messageStop": {"stopReason": "tool_use"}},
),
# Message Stop - Max Tokens
(
{"chunk_type": "message_stop", "data": "length"},
{"messageStop": {"stopReason": "max_tokens"}},
),
# Message Stop - End Turn
(
{"chunk_type": "message_stop", "data": "stop"},
{"messageStop": {"stopReason": "end_turn"}},
),
# Metadata
(
{
"chunk_type": "metadata",
"data": unittest.mock.Mock(
prompt_tokens=100,
completion_tokens=50,
total_tokens=150,
prompt_tokens_details=None,
),
},
{
"metadata": {
"usage": {
"inputTokens": 100,
"outputTokens": 50,
"totalTokens": 150,
},
"metrics": {
"latencyMs": 0,
},
},
},
),
],
)
def test_format_chunk(event, exp_chunk, model):
tru_chunk = model.format_chunk(event)
assert tru_chunk == exp_chunk
def test_format_chunk_unknown_type(model):
event = {"chunk_type": "unknown"}
with pytest.raises(RuntimeError, match="chunk_type=<unknown> | unknown type"):
model.format_chunk(event)
def test_format_chunk_metadata_with_cache_tokens(model):
"""Test format_chunk for metadata with cache tokens present."""
mock_usage = unittest.mock.Mock()
mock_usage.prompt_tokens = 100
mock_usage.completion_tokens = 50
mock_usage.total_tokens = 150
mock_tokens_details = unittest.mock.Mock()
mock_tokens_details.cached_tokens = 25
mock_usage.prompt_tokens_details = mock_tokens_details
event = {"chunk_type": "metadata", "data": mock_usage}
result = model.format_chunk(event)
assert result["metadata"]["usage"]["inputTokens"] == 100
assert result["metadata"]["usage"]["outputTokens"] == 50
assert result["metadata"]["usage"]["totalTokens"] == 150
assert result["metadata"]["usage"]["cacheReadInputTokens"] == 25
def test_format_chunk_metadata_with_zero_cached_tokens(model):
"""Test format_chunk for metadata when cached_tokens is 0."""
mock_usage = unittest.mock.Mock()
mock_usage.prompt_tokens = 100
mock_usage.completion_tokens = 50
mock_usage.total_tokens = 150
mock_tokens_details = unittest.mock.Mock()
mock_tokens_details.cached_tokens = 0
mock_usage.prompt_tokens_details = mock_tokens_details
event = {"chunk_type": "metadata", "data": mock_usage}
result = model.format_chunk(event)
assert "cacheReadInputTokens" not in result["metadata"]["usage"]
@pytest.mark.asyncio
async def test_stream(openai_client, model_id, model, agenerator, alist):
mock_tool_call_1_part_1 = unittest.mock.Mock(index=0)
mock_tool_call_2_part_1 = unittest.mock.Mock(index=1)
mock_delta_1 = unittest.mock.Mock(
reasoning_content="",
content=None,
tool_calls=None,
)
mock_delta_2 = unittest.mock.Mock(
reasoning_content="\nI'm thinking",
content=None,
tool_calls=None,
)
mock_delta_3 = unittest.mock.Mock(
content="I'll calculate", tool_calls=[mock_tool_call_1_part_1, mock_tool_call_2_part_1], reasoning_content=None
)
mock_tool_call_1_part_2 = unittest.mock.Mock(index=0)
mock_tool_call_2_part_2 = unittest.mock.Mock(index=1)
mock_delta_4 = unittest.mock.Mock(
content="that for you", tool_calls=[mock_tool_call_1_part_2, mock_tool_call_2_part_2], reasoning_content=None
)
mock_delta_5 = unittest.mock.Mock(content="", tool_calls=None, reasoning_content=None)
mock_event_1 = unittest.mock.Mock(choices=[unittest.mock.Mock(finish_reason=None, delta=mock_delta_1)])
mock_event_2 = unittest.mock.Mock(choices=[unittest.mock.Mock(finish_reason=None, delta=mock_delta_2)])
mock_event_3 = unittest.mock.Mock(choices=[unittest.mock.Mock(finish_reason=None, delta=mock_delta_3)])
mock_event_4 = unittest.mock.Mock(choices=[unittest.mock.Mock(finish_reason=None, delta=mock_delta_4)])
mock_event_5 = unittest.mock.Mock(choices=[unittest.mock.Mock(finish_reason="tool_calls", delta=mock_delta_5)])
mock_event_6 = unittest.mock.Mock()
openai_client.chat.completions.create = unittest.mock.AsyncMock(
return_value=agenerator([mock_event_1, mock_event_2, mock_event_3, mock_event_4, mock_event_5, mock_event_6])
)
messages = [{"role": "user", "content": [{"text": "calculate 2+2"}]}]
response = model.stream(messages)
tru_events = await alist(response)
exp_events = [
{"messageStart": {"role": "assistant"}},
{"contentBlockStart": {"start": {}}}, # reasoning_content starts
{"contentBlockDelta": {"delta": {"reasoningContent": {"text": "\nI'm thinking"}}}},
{"contentBlockStop": {}}, # reasoning_content ends
{"contentBlockStart": {"start": {}}}, # text starts
{"contentBlockDelta": {"delta": {"text": "I'll calculate"}}},
{"contentBlockDelta": {"delta": {"text": "that for you"}}},
{"contentBlockStop": {}}, # text ends
{
"contentBlockStart": {
"start": {
"toolUse": {"toolUseId": mock_tool_call_1_part_1.id, "name": mock_tool_call_1_part_1.function.name}
}
}
},
{"contentBlockDelta": {"delta": {"toolUse": {"input": mock_tool_call_1_part_1.function.arguments}}}},
{"contentBlockDelta": {"delta": {"toolUse": {"input": mock_tool_call_1_part_2.function.arguments}}}},
{"contentBlockStop": {}},
{
"contentBlockStart": {
"start": {
"toolUse": {"toolUseId": mock_tool_call_2_part_1.id, "name": mock_tool_call_2_part_1.function.name}
}
}
},
{"contentBlockDelta": {"delta": {"toolUse": {"input": mock_tool_call_2_part_1.function.arguments}}}},
{"contentBlockDelta": {"delta": {"toolUse": {"input": mock_tool_call_2_part_2.function.arguments}}}},
{"contentBlockStop": {}},
{"messageStop": {"stopReason": "tool_use"}},
{
"metadata": {
"usage": {
"inputTokens": mock_event_6.usage.prompt_tokens,
"outputTokens": mock_event_6.usage.completion_tokens,
"totalTokens": mock_event_6.usage.total_tokens,
},
"metrics": {"latencyMs": 0},
}
},
]
assert len(tru_events) == len(exp_events)
# Verify that format_request was called with the correct arguments
expected_request = {
"max_tokens": 1,
"model": model_id,
"messages": [{"role": "user", "content": [{"text": "calculate 2+2", "type": "text"}]}],
"stream": True,
"stream_options": {"include_usage": True},
"tools": [],
}
openai_client.chat.completions.create.assert_called_once_with(**expected_request)
@pytest.mark.asyncio
async def test_stream_empty(openai_client, model_id, model, agenerator, alist):
mock_delta = unittest.mock.Mock(content=None, tool_calls=None, reasoning_content=None)
mock_event_1 = unittest.mock.Mock(choices=[unittest.mock.Mock(finish_reason=None, delta=mock_delta)])
mock_event_2 = unittest.mock.Mock(choices=[unittest.mock.Mock(finish_reason="stop", delta=mock_delta)])
mock_event_3 = unittest.mock.Mock()
mock_event_4 = unittest.mock.Mock(usage=None)
openai_client.chat.completions.create = unittest.mock.AsyncMock(
return_value=agenerator([mock_event_1, mock_event_2, mock_event_3, mock_event_4]),
)