forked from MacPaw/OpenAI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenAITestsDecoder.swift
More file actions
951 lines (856 loc) · 33.2 KB
/
OpenAITestsDecoder.swift
File metadata and controls
951 lines (856 loc) · 33.2 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
//
// OpenAITestsDecoder.swift
//
//
// Created by Aled Samuel on 10/04/2023.
//
import XCTest
@testable import OpenAI
class OpenAITestsDecoder: XCTestCase {
override func setUp() {
super.setUp()
}
private func decode<T: Decodable & Equatable>(_ jsonString: String, _ expectedValue: T, file: StaticString = #filePath, line: UInt = #line) throws {
let data = jsonString.data(using: .utf8)!
let decoded = try JSONDecoder().decode(T.self, from: data)
XCTAssertEqual(decoded, expectedValue, file: file, line: line)
}
private func encode<T: Encodable & Equatable>(_ expectedValue: T, _ jsonString: String, file: StaticString = #filePath, line: UInt = #line) throws {
// To compare serialized JSONs we first convert them both into NSDictionary which are comparable (unlike native swift dictionaries)
let expectedValueAsDict = try jsonDataAsNSDictionary(JSONEncoder().encode(expectedValue))
let jsonStringAsDict = try jsonDataAsNSDictionary(jsonString.data(using: .utf8)!)
XCTAssertEqual(jsonStringAsDict, expectedValueAsDict, file: file, line: line)
}
func jsonDataAsNSDictionary(_ data: Data) throws -> NSDictionary {
return NSDictionary(dictionary: try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any])
}
func testImages() async throws {
let data = """
{
"created": 1589478378,
"data": [
{
"url": "https://foo.bar"
},
{
"url": "https://bar.foo"
},
{
"b64_json": "test"
}
]
}
"""
let expectedValue = ImagesResult(created: 1589478378, data: [
.init(b64Json: nil, revisedPrompt: nil, url: "https://foo.bar"),
.init(b64Json: nil, revisedPrompt: nil, url: "https://bar.foo"),
.init(b64Json: "test", revisedPrompt: nil, url: nil)
])
try decode(data, expectedValue)
}
func testChatCompletion() async throws {
let data = ChatResult.mockJsonString
let expectedValue = ChatResult(
id: "chatcmpl-123", created: 1677652288, model: .gpt4, object: "chat.completion", serviceTier: nil, systemFingerprint: "fp_fc9f1d7035",
choices: [
.init(
index: 0,
logprobs: nil,
message: .init(content: "Hello, world!", refusal: nil, role: "assistant", annotations: [], audio: nil, toolCalls: [], _reasoning: nil, _reasoningContent: nil),
finishReason: "stop"
)
],
usage: .init(completionTokens: 12, promptTokens: 9, totalTokens: 21, promptTokensDetails: nil),
citations: nil
)
try decode(data, expectedValue)
}
func testImageQuery() async throws {
let imageQuery = ImagesQuery(
prompt: "test",
model: .dall_e_2,
n: 1,
responseFormat: .b64_json,
size: ._512,
style: .vivid,
user: "user"
)
let expectedValue = """
{
"model": "dall-e-2",
"prompt": "test",
"n": 1,
"size": "512x512",
"style": "vivid",
"user": "user",
"response_format": "b64_json"
}
"""
try encode(imageQuery, expectedValue)
}
func testChatQueryWithVision() async throws {
let chatQuery = ChatQuery(
messages: [
.user(.init(content: .contentParts([
.text(.init(text: "What's in this image?")),
.image(.init(imageUrl: .init(url: "https://some.url/image.jpeg", detail: .auto)))
])))
],
model: Model.gpt4_o,
maxCompletionTokens: 300
)
let expectedValue = """
{
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "What's in this image?"
},
{
"type": "image_url",
"image_url": {
"url": "https://some.url/image.jpeg",
"detail": "auto"
}
}
]
}
],
"max_completion_tokens": 300,
"stream": false
}
"""
// To compare serialized JSONs we first convert them both into NSDictionary which are comparable (unline native swift dictionaries)
let chatQueryAsDict = try jsonDataAsNSDictionary(JSONEncoder().encode(chatQuery))
let expectedValueAsDict = try jsonDataAsNSDictionary(expectedValue.data(using: .utf8)!)
XCTAssertEqual(chatQueryAsDict, expectedValueAsDict)
}
func testChatQueryWithStreamOptions() async throws {
let chatQuery = ChatQuery(messages: [
.init(role: .user, content: "Who are you?")!
], model: .gpt4, stream: true, streamOptions: .init(includeUsage: true))
let expectedValue = """
{
"model": "gpt-4",
"messages": [
{
"role": "user",
"content": "Who are you?"
}
],
"stream": true,
"stream_options": {
"include_usage" : true
}
}
"""
let chatQueryAsDict = try jsonDataAsNSDictionary(JSONEncoder().encode(chatQuery))
let expectedValueAsDict = try jsonDataAsNSDictionary(expectedValue.data(using: .utf8)!)
XCTAssertEqual(chatQueryAsDict, expectedValueAsDict)
}
func testChatQueryWithoutStreamOptions() async throws {
let chatQuery = ChatQuery(messages: [
.init(role: .user, content: "Who are you?")!
], model: .gpt4, stream: true)
let expectedValue = """
{
"model": "gpt-4",
"messages": [
{
"role": "user",
"content": "Who are you?"
}
],
"stream": true
}
"""
let chatQueryAsDict = try jsonDataAsNSDictionary(JSONEncoder().encode(chatQuery))
let expectedValueAsDict = try jsonDataAsNSDictionary(expectedValue.data(using: .utf8)!)
XCTAssertEqual(chatQueryAsDict, expectedValueAsDict)
}
func testChatQueryWithFunctionCall() async throws {
let chatQuery = ChatQuery(
messages: [
.user(.init(content: .string("What's the weather like in Boston?")))
],
model: .gpt3_5Turbo,
responseFormat: ChatQuery.ResponseFormat.jsonObject,
toolChoice: .function("get_current_weather"),
tools: [
.makeWeatherMock()
]
)
let expectedValue = """
{
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": "What's the weather like in Boston?"
}
],
"response_format": {
"type": "json_object"
},
"tools": [
{
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": { "type": "string", "enum": ["celsius", "fahrenheit"] }
},
"required": ["location"]
}
},
"type": "function"
}
],
"tool_choice": {
"type": "function",
"function": {
"name": "get_current_weather"
}
},
"stream": false
}
"""
try encode(chatQuery, expectedValue)
}
func testChatCompletionWithFunctionCall() async throws {
let data = """
{
"id": "chatcmpl-1234",
"object": "chat.completion",
"created": 1677652288,
"model": "gpt-3.5-turbo",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"annotations": [],
"tool_calls": [
{
"type": "function",
"id": "chatcmpl-1234",
"function": {
"name": "get_current_weather",
"arguments": ""
}
}
]
},
"finish_reason": "tool_calls",
"logprobs": null
}
],
"usage": {
"prompt_tokens": 82,
"completion_tokens": 18,
"total_tokens": 100
},
"system_fingerprint": "fp_fc9f1d7035"
}
"""
let expectedValue = ChatResult(
id: "chatcmpl-1234",
created: 1677652288,
model: .gpt3_5Turbo,
object: "chat.completion",
serviceTier: nil,
systemFingerprint: "fp_fc9f1d7035",
choices: [
.init(
index: 0,
logprobs: nil,
message: .init(
content: nil,
refusal: nil,
role: "assistant",
annotations: [],
audio: nil,
toolCalls: [.init(id: "chatcmpl-1234", function: .init(arguments: "", name: "get_current_weather"))],
_reasoning: nil,
_reasoningContent: nil
),
finishReason: "tool_calls"
)
],
usage: .init(completionTokens: 18, promptTokens: 82, totalTokens: 100, promptTokensDetails: nil),
citations: nil
)
try decode(data, expectedValue)
}
func testChatQueryWithReasoningEffort() throws {
let chatQuery = ChatQuery(
messages: [
.init(role: .user, content: "Who are you?")!
],
model: .gpt4,
reasoningEffort: .low
)
let expectedValue = """
{
"model": "gpt-4",
"messages": [
{
"role": "user",
"content": "Who are you?"
}
],
"reasoning_effort": "low",
"stream": false
}
"""
let chatQueryAsDict = try jsonDataAsNSDictionary(JSONEncoder().encode(chatQuery))
let expectedValueAsDict = try jsonDataAsNSDictionary(expectedValue.data(using: .utf8)!)
XCTAssertEqual(chatQueryAsDict, expectedValueAsDict)
}
func testChatQueryWithReasoningEffortMinimal() throws {
let chatQuery = ChatQuery(
messages: [
.init(role: .user, content: "Who are you?")!
],
model: .gpt4,
reasoningEffort: .minimal
)
let expectedValue = """
{
"model": "gpt-4",
"messages": [
{
"role": "user",
"content": "Who are you?"
}
],
"reasoning_effort": "minimal",
"stream": false
}
"""
let chatQueryAsDict = try jsonDataAsNSDictionary(JSONEncoder().encode(chatQuery))
let expectedValueAsDict = try jsonDataAsNSDictionary(expectedValue.data(using: .utf8)!)
XCTAssertEqual(chatQueryAsDict, expectedValueAsDict)
}
func testReasoningEffortDecodingMinimal() throws {
let json = """
{ "effort": "minimal" }
"""
let data = json.data(using: .utf8)!
let decoded = try JSONDecoder().decode(Components.Schemas.Reasoning.self, from: data)
XCTAssertEqual(decoded.effort, .minimal)
}
func testVerbosityDecoding() throws {
// Test decoding "low"
let jsonLow = """
{ "format": { "type": "text" }, "verbosity": "low" }
"""
let dataLow = jsonLow.data(using: .utf8)!
let decodedLow = try JSONDecoder().decode(CreateModelResponseQuery.TextResponseConfigurationOptions.self, from: dataLow)
XCTAssertEqual(decodedLow.verbosity, .low)
// Test decoding "medium"
let jsonMedium = """
{ "format": { "type": "text" }, "verbosity": "medium" }
"""
let dataMedium = jsonMedium.data(using: .utf8)!
let decodedMedium = try JSONDecoder().decode(CreateModelResponseQuery.TextResponseConfigurationOptions.self, from: dataMedium)
XCTAssertEqual(decodedMedium.verbosity, .medium)
// Test decoding "high"
let jsonHigh = """
{ "format": { "type": "text" }, "verbosity": "high" }
"""
let dataHigh = jsonHigh.data(using: .utf8)!
let decodedHigh = try JSONDecoder().decode(CreateModelResponseQuery.TextResponseConfigurationOptions.self, from: dataHigh)
XCTAssertEqual(decodedHigh.verbosity, .high)
// Test decoding without verbosity (should be nil)
let jsonNil = """
{ "format": { "type": "text" } }
"""
let dataNil = jsonNil.data(using: .utf8)!
let decodedNil = try JSONDecoder().decode(CreateModelResponseQuery.TextResponseConfigurationOptions.self, from: dataNil)
XCTAssertNil(decodedNil.verbosity)
}
func testChatQueryWithReasoningEffortNone() throws {
let chatQuery = ChatQuery(
messages: [
.init(role: .user, content: "Who are you?")!
],
model: .gpt5_1,
reasoningEffort: ChatQuery.ReasoningEffort.none
)
let expectedValue = """
{
"model": "gpt-5.1",
"messages": [
{
"role": "user",
"content": "Who are you?"
}
],
"reasoning_effort": "none",
"stream": false
}
"""
let chatQueryAsDict = try jsonDataAsNSDictionary(JSONEncoder().encode(chatQuery))
let expectedValueAsDict = try jsonDataAsNSDictionary(expectedValue.data(using: .utf8)!)
XCTAssertEqual(chatQueryAsDict, expectedValueAsDict)
}
func testReasoningEffortDecodingNone() throws {
let json = """
{ "effort": "none" }
"""
let data = json.data(using: .utf8)!
let decoded = try JSONDecoder().decode(Components.Schemas.Reasoning.self, from: data)
XCTAssertEqual(decoded.effort, Components.Schemas.ReasoningEffort.none)
}
func testEmbeddings() async throws {
let data = """
{
"object": "list",
"data": [
{
"object": "embedding",
"embedding": [
0.0023064255,
-0.009327292,
-0.0028842222,
],
"index": 0
}
],
"model": "text-embedding-ada-002",
"usage": {
"prompt_tokens": 8,
"total_tokens": 8
}
}
"""
let expectedValue = EmbeddingsResult(data: [
.init(object: "embedding", embedding: [0.0023064255, -0.009327292, -0.0028842222], index: 0)
], model: .textEmbeddingAda, usage: .init(promptTokens: 8, totalTokens: 8), object: "list")
try decode(data, expectedValue)
}
func testModels() async throws {
let data = """
{
"data": [
{
"id": "gpt-3.5-turbo",
"created": 222,
"object": "model",
"owned_by": "organization-owner"
},
{
"id": "dall-e-2",
"created": 111,
"object": "model",
"owned_by": "organization-owner"
},
{
"id": "whisper-1",
"created": 333,
"object": "model",
"owned_by": "openai"
}
],
"object": "list"
}
"""
let expectedValue = ModelsResult(data: [
.init(id: .gpt3_5Turbo, created: 222, object: "model", ownedBy: "organization-owner"),
.init(id: .dall_e_2, created: 111, object: "model", ownedBy: "organization-owner"),
.init(id: .whisper_1, created: 333, object: "model", ownedBy: "openai")
], object: "list")
try decode(data, expectedValue)
}
func testModelType() async throws {
let data = """
{
"id": "whisper-1",
"created": 555,
"object": "model",
"owned_by": "openai"
}
"""
let expectedValue = ModelResult(id: .whisper_1, created: 555, object: "model", ownedBy: "openai")
try decode(data, expectedValue)
}
func testModerations() async throws {
let data = """
{
"id": "modr-5MWoLO",
"model": "text-moderation-007",
"results": [
{
"categories": {
"harassment": false,
"harassment/threatening": false,
"hate": false,
"hate/threatening": true,
"self-harm": false,
"self-harm/intent": false,
"self-harm/instructions": false,
"sexual": false,
"sexual/minors": false,
"violence": true,
"violence/graphic": false
},
"category_scores": {
"harassment": 0.0431830403405153,
"harassment/threatening": 0.1229622494034651,
"hate": 0.22714105248451233,
"hate/threatening": 0.4132447838783264,
"self-harm": 0.00523239187896251,
"self-harm/intent": 0.307237106114835,
"self-harm/instructions": 0.42189350703096,
"sexual": 0.01407341007143259,
"sexual/minors": 0.0038522258400917053,
"violence": 0.9223177433013916,
"violence/graphic": 0.036865197122097015
},
"flagged": true
}
]
}
"""
let expectedValue = ModerationsResult(id: "modr-5MWoLO", model: .moderation, results: [
.init(categories: .init(harassment: false, harassmentThreatening: false, hate: false, hateThreatening: true, selfHarm: false, selfHarmIntent: false, selfHarmInstructions: false, sexual: false, sexualMinors: false, violence: true, violenceGraphic: false),
categoryScores: .init(harassment: 0.0431830403405153, harassmentThreatening: 0.1229622494034651, hate: 0.22714105248451233, hateThreatening: 0.4132447838783264, selfHarm: 0.00523239187896251, selfHarmIntent: 0.307237106114835, selfHarmInstructions: 0.42189350703096, sexual: 0.01407341007143259, sexualMinors: 0.0038522258400917053, violence: 0.9223177433013916, violenceGraphic: 0.036865197122097015),
flagged: true)
])
try decode(data, expectedValue)
}
func testAudioTranscriptions() async throws {
let data = """
{
"text": "Hello, world!"
}
"""
let expectedValue = AudioTranscriptionResult(text: "Hello, world!")
try decode(data, expectedValue)
}
func testAudioAudioTranslationResults() async throws {
let data = """
{
"text": "Hello, world!"
}
"""
let expectedValue = AudioTranslationResult(text: "Hello, world!")
try decode(data, expectedValue)
}
func testAssistantResult() async throws {
let data = """
{
"id": "asst_abc123",
"object": "assistant",
"created_at": 1698984975,
"name": "Math Tutor",
"description": null,
"model": "gpt-4",
"instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.",
"tools": [
{
"type": "code_interpreter"
}
],
"file_ids": [],
"metadata": {}
}
"""
let expectedValue = AssistantResult(id: "asst_abc123", name: "Math Tutor", description: nil, instructions: "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", tools: [.codeInterpreter], toolResources: nil)
try decode(data, expectedValue)
}
func testAssistantsQuery() async throws {
let assistantsQuery = AssistantsQuery(
model: .gpt4,
name: "Math Tutor",
description: nil,
instructions: "You are a personal math tutor. When asked a question, write and run Python code to answer the question.",
tools: [.codeInterpreter],
toolResources: nil
)
let expectedValue = """
{
"instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.",
"name": "Math Tutor",
"tools": [
{"type": "code_interpreter"}
],
"model": "gpt-4"
}
"""
try encode(assistantsQuery, expectedValue)
}
func testAssistantsResult() async throws {
let data = """
{
"object": "list",
"data": [
{
"id": "asst_abc123",
"object": "assistant",
"created_at": 1698982736,
"name": "Coding Tutor",
"description": null,
"model": "gpt-4",
"instructions": "You are a helpful assistant designed to make me better at coding!",
"tools": [],
"file_ids": [],
"metadata": {}
},
{
"id": "asst_abc456",
"object": "assistant",
"created_at": 1698982718,
"name": "My Assistant",
"description": null,
"model": "gpt-4",
"instructions": "You are a helpful assistant designed to teach me about AI!",
"tools": [],
"file_ids": [],
"metadata": {}
}
],
"first_id": "asst_abc123",
"last_id": "asst_abc789",
"has_more": false
}
"""
let expectedValue = AssistantsResult(
data: [
.init(id: "asst_abc123", name: "Coding Tutor", description: nil, instructions: "You are a helpful assistant designed to make me better at coding!", tools: [], toolResources: nil),
.init(id: "asst_abc456", name: "My Assistant", description: nil, instructions: "You are a helpful assistant designed to teach me about AI!", tools: [], toolResources: nil),
],
firstId: "asst_abc123",
lastId: "asst_abc789",
hasMore: false
)
try decode(data, expectedValue)
}
func testMessageQuery() async throws {
let messageQuery = MessageQuery(
role: .user,
content: "How does AI work? Explain it in simple terms.",
fileIds: ["file_abc123"]
)
let expectedValue = """
{
"role": "user",
"content": "How does AI work? Explain it in simple terms.",
"file_ids": ["file_abc123"]
}
"""
try encode(messageQuery, expectedValue)
}
func testRunResult() async throws {
let data = """
{
"id": "run_1a",
"thread_id": "thread_2b",
"status": "requires_action",
"required_action": {
"type": "submit_tool_outputs",
"submit_tool_outputs": {
"tool_calls": [
{
"id": "tool_abc890",
"type": "function",
"function": {
"name": "print",
"arguments": "{\\"text\\": \\"hello\\"}"
}
}
]
}
}
}
"""
let expectedValue = RunResult(
id: "run_1a",
threadId: "thread_2b",
status: .requiresAction,
requiredAction: .init(
submitToolOutputs: .init(toolCalls: [.init(id: "tool_abc890", type: "function", function: .init(name: "print", arguments: "{\"text\": \"hello\"}"))])
)
)
try decode(data, expectedValue)
}
func testRunToolOutputsQuery() async throws {
let runToolOutputsQuery = RunToolOutputsQuery(
toolOutputs: [
.init(toolCallId: "call_abc0", output: "success")
]
)
let expectedValue = """
{
"tool_outputs": [
{
"tool_call_id": "call_abc0",
"output": "success"
}
]
}
"""
try encode(runToolOutputsQuery, expectedValue)
}
func testThreadRunQuery() async throws {
let threadRunQuery = ThreadRunQuery(
assistantId: "asst_abc123",
thread: .init(
messages: [.init(role: .user, content: "Explain deep learning to a 5 year old.")!]
)
)
let expectedValue = """
{
"assistant_id": "asst_abc123",
"thread": {
"messages": [
{"role": "user", "content": "Explain deep learning to a 5 year old."}
]
}
}
"""
try encode(threadRunQuery, expectedValue)
}
func testChatQueryWithStructuredOutputDerivedSchema() throws {
let query = ChatQuery(
messages: [.system(.init(content: .textContent("Return a structured response.")))],
model: .gpt4_o,
responseFormat: .jsonSchema(
.init(
name: "movie-info",
description: "dezg",
schema: .derivedJsonSchema(MovieInfo.self),
strict: true
)
)
)
let data = try JSONEncoder().encode(query)
try testEncodedChatQueryWithStructuredOutput(data)
}
func testChatQueryWithStructuredOutputJsonSchema() throws {
let query = ChatQuery(
messages: [.system(.init(content: .textContent("Return a structured response.")))],
model: .gpt4_o,
responseFormat: .jsonSchema(.init(
name: "movie-info",
description: "dezg",
schema: .jsonSchema(.init(
fields: [
.type(.object),
.properties([
"title": .init(fields: [
.type(.string)
])
])
])),
strict: true
))
)
let data = try JSONEncoder().encode(query)
try testEncodedChatQueryWithStructuredOutput(data)
}
func testCreateResponseQueryWithStructuredOutputDerivedSchema() throws {
let query = CreateModelResponseQuery(
input: .textInput("Return a structured response."),
model: .gpt4_o,
text: .init(format: .jsonSchema(
.init(
name: "movie-info",
schema: .derivedJsonSchema(MovieInfo.self),
description: "dezg",
strict: true
)
))
)
let data = try JSONEncoder().encode(query)
try testEncodedCreateResponseQueryWithStructuredOutput(data)
}
func testCreateResponseQueryWithStructuredOutputJsonSchema() throws {
let query = CreateModelResponseQuery(
input: .textInput("Return a structured response."),
model: .gpt4_o,
text: .init(
format: .jsonSchema(
.init(
name: "movie-info",
schema: .jsonSchema(.init(
fields: [
.type(.object),
.properties([
"title": .init(fields: [
.type(.string)
])
])
])),
description: "dezg",
strict: true
)
)
)
)
let data = try JSONEncoder().encode(query)
try testEncodedCreateResponseQueryWithStructuredOutput(data)
}
func testCreateResponseQueryWithVerbosity() throws {
let query = CreateModelResponseQuery(
input: .textInput("Return a low verbosity response."),
model: .gpt5,
text: .init(format: .text, verbosity: .low)
)
let data = try JSONEncoder().encode(query)
try testEncodedCreateResponseQueryWithVerbosity(data)
}
private func testEncodedChatQueryWithStructuredOutput(_ data: Data) throws {
let dict = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
XCTAssertEqual(try XCTUnwrap(dict["model"] as? String), "gpt-4o")
XCTAssertEqual(try XCTUnwrap(dict["stream"] as? Bool), false)
let responseFormat = try XCTUnwrap(dict["response_format"] as? [String: Any])
XCTAssertEqual(try XCTUnwrap(responseFormat["type"] as? String), "json_schema")
let configOptions = try XCTUnwrap(responseFormat["json_schema"] as? [String: Any])
XCTAssertEqual(try XCTUnwrap(configOptions["name"] as? String), "movie-info")
XCTAssertEqual(try XCTUnwrap(configOptions["description"] as? String), "dezg")
XCTAssertEqual(try XCTUnwrap(configOptions["strict"] as? Bool), true)
let jsonSchema = try XCTUnwrap(configOptions["schema"] as? [String: Any])
XCTAssertEqual(try XCTUnwrap(jsonSchema["type"] as? String), "object")
let properties = try XCTUnwrap(jsonSchema["properties"] as? [String: [String: Any]])
let titleSchema = try XCTUnwrap(properties["title"])
XCTAssertEqual(titleSchema.count, 1)
XCTAssertEqual(try XCTUnwrap(titleSchema["type"] as? String), "string")
}
private func testEncodedCreateResponseQueryWithStructuredOutput(_ data: Data) throws {
let dict = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
XCTAssertEqual(try XCTUnwrap(dict["model"] as? String), "gpt-4o")
let textResponseConfigurationOptions = try XCTUnwrap(dict["text"] as? [String: Any])
let outputFormat = try XCTUnwrap(textResponseConfigurationOptions["format"] as? [String: Any])
XCTAssertEqual(try XCTUnwrap(outputFormat["type"] as? String), "json_schema")
XCTAssertEqual(try XCTUnwrap(outputFormat["name"] as? String), "movie-info")
XCTAssertEqual(try XCTUnwrap(outputFormat["description"] as? String), "dezg")
XCTAssertEqual(try XCTUnwrap(outputFormat["strict"] as? Bool), true)
let jsonSchema = try XCTUnwrap(outputFormat["schema"] as? [String: Any])
XCTAssertEqual(try XCTUnwrap(jsonSchema["type"] as? String), "object")
let properties = try XCTUnwrap(jsonSchema["properties"] as? [String: [String: Any]])
let titleSchema = try XCTUnwrap(properties["title"])
XCTAssertEqual(titleSchema.count, 1)
XCTAssertEqual(try XCTUnwrap(titleSchema["type"] as? String), "string")
}
private func testEncodedCreateResponseQueryWithVerbosity(_ data: Data) throws {
let dict = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
XCTAssertEqual(try XCTUnwrap(dict["model"] as? String), "gpt-5")
let textResponseConfigurationOptions = try XCTUnwrap(dict["text"] as? [String: Any])
let outputFormat = try XCTUnwrap(textResponseConfigurationOptions["format"] as? [String: Any])
let outputVerbosity = try XCTUnwrap(textResponseConfigurationOptions["verbosity"] as? String)
XCTAssertEqual(try XCTUnwrap(outputFormat["type"] as? String), "text")
XCTAssertNotNil(CreateModelResponseQuery.TextResponseConfigurationOptions.Verbosity(rawValue: outputVerbosity))
}
}