endpoints 0.37.0

A collection of data structures for the OpenAI-compatible endpoints.
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
//! Define types for building chat completion requests, including messages, tools, and tool choices.
//!
//! **Example 1** Create a normal chat completion request.
//! ```
//! use endpoints::chat::*;
//!
//! let mut messages = Vec::new();
//!
//! // create a system message
//! let system_message = ChatCompletionRequestMessage::System(
//!     ChatCompletionSystemMessage::new("Hello, world!", None),
//! );
//! messages.push(system_message);
//!
//! // create a user message
//! let user_message_content = ChatCompletionUserMessageContent::Parts(vec![
//!     ContentPart::Text(TextContentPart::new("what is in the picture?")),
//!     ContentPart::Image(ImageContentPart::new(Image {
//!         url: "https://example.com/image.png".to_string(),
//!         detail: None,
//!     })),
//! ]);
//! let user_message =
//!     ChatCompletionRequestMessage::new_user_message(user_message_content, None);
//! messages.push(user_message);
//!
//! // create a chat completion request
//! let request = ChatCompletionRequestBuilder::new(&messages)
//!     .with_model("model-id")
//!     .with_tool_choice(ToolChoice::None)
//!     .build();
//!
//! // serialize the request to JSON string
//! let json = serde_json::to_string(&request).unwrap();
//! assert_eq!(
//!     json,
//!     r#"{"model":"model-id","messages":[{"role":"system","content":"Hello, world!"},{"role":"user","content":[{"type":"text","text":"what is in the picture?"},{"type":"image_url","image_url":{"url":"https://example.com/image.png"}}]}],"temperature":0.8,"top_p":0.9,"n":1,"stream":false,"max_completion_tokens":2147483647,"presence_penalty":0.0,"frequency_penalty":0.0,"tool_choice":"none"}"#
//! );
//!
//! ```
//!

use crate::common::{FinishReason, Usage};
use indexmap::IndexMap;
use serde::{
    de::{self, IgnoredAny, MapAccess, Visitor},
    Deserialize, Deserializer, Serialize,
};
use serde_json::Value;
use std::{collections::HashMap, fmt};

/// Request builder for creating a new chat completion request.
pub struct ChatCompletionRequestBuilder {
    req: ChatCompletionRequest,
}
impl ChatCompletionRequestBuilder {
    /// Creates a new builder with the given messages.
    ///
    /// # Arguments
    ///
    /// * `messages` - A list of messages comprising the conversation so far.
    pub fn new(messages: &[ChatCompletionRequestMessage]) -> Self {
        Self {
            req: ChatCompletionRequest {
                messages: messages.to_vec(),
                ..Default::default()
            },
        }
    }

    /// Sets the model name to use for generating completions.
    ///
    /// # Arguments
    ///
    /// * `model` - The name of the model to use.
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.req.model = Some(model.into());
        self
    }

    /// Sets the sampling method to use.
    ///
    /// # Arguments
    ///
    /// * `sampling` - The sampling method to use.
    pub fn with_sampling(mut self, sampling: ChatCompletionRequestSampling) -> Self {
        let (temperature, top_p) = match sampling {
            ChatCompletionRequestSampling::Temperature(t) => (t, 1.0),
            ChatCompletionRequestSampling::TopP(p) => (1.0, p),
        };
        self.req.temperature = Some(temperature);
        self.req.top_p = Some(top_p);
        self
    }

    /// Sets the number of chat completion choices to generate for each input message.
    ///
    /// # Arguments
    ///
    /// * `n` - How many chat completion choices to generate for each input message. If `n` is less than 1, then sets to `1`.
    pub fn with_n_choices(mut self, n: u64) -> Self {
        let n_choice = if n < 1 { 1 } else { n };
        self.req.n_choice = Some(n_choice);
        self
    }

    /// Enables streaming reponse.
    ///
    /// # Arguments
    ///
    /// * `flag` - Whether to enable streaming response.
    pub fn enable_stream(mut self, flag: bool) -> Self {
        self.req.stream = Some(flag);
        self
    }

    /// Includes usage in streaming response.
    pub fn include_usage(mut self) -> Self {
        self.req.stream_options = Some(StreamOptions {
            include_usage: Some(true),
        });
        self
    }

    /// Sets the stop tokens.
    ///
    /// # Arguments
    ///
    /// * `stop` - A list of tokens at which to stop generation.
    pub fn with_stop(mut self, stop: Vec<String>) -> Self {
        self.req.stop = Some(stop);
        self
    }

    /// Sets the maximum number of tokens that can be generated for a completion.
    ///
    /// # Argument
    ///
    /// * `max_completion_tokens` - The maximum number of tokens that can be generated for a completion.
    pub fn with_max_completion_tokens(mut self, max_completion_tokens: i32) -> Self {
        self.req.max_completion_tokens = Some(max_completion_tokens);
        self
    }

    /// Sets the presence penalty. Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.
    ///
    /// # Arguments
    ///
    /// * `penalty` - The presence penalty.
    pub fn with_presence_penalty(mut self, penalty: f64) -> Self {
        self.req.presence_penalty = Some(penalty);
        self
    }

    /// Sets the frequency penalty. Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.
    ///
    /// # Arguments
    ///
    /// * `penalty` - The frequency penalty.
    pub fn with_frequency_penalty(mut self, penalty: f64) -> Self {
        self.req.frequency_penalty = Some(penalty);
        self
    }

    /// Sets the logit bias.
    ///
    /// # Arguments
    ///
    /// * `map` - A map of tokens to their associated bias values.
    pub fn with_logits_bias(mut self, map: HashMap<String, f64>) -> Self {
        self.req.logit_bias = Some(map);
        self
    }

    /// Sets the user.
    ///
    /// # Arguments
    ///
    /// * `user` - A unique identifier representing your end-user.
    pub fn with_user(mut self, user: impl Into<String>) -> Self {
        self.req.user = Some(user.into());
        self
    }

    /// Sets the response format.
    ///
    /// # Arguments
    ///
    /// * `response_format` - The response format to use.
    pub fn with_reponse_format(mut self, response_format: ChatResponseFormat) -> Self {
        self.req.response_format = Some(response_format);
        self
    }

    /// Sets tools.
    ///
    /// # Arguments
    ///
    /// * `tools` - A list of tools the model may call.
    pub fn with_tools(mut self, tools: Vec<Tool>) -> Self {
        self.req.tools = Some(tools);
        self
    }

    /// Sets tool choice.
    ///
    /// # Arguments
    ///
    /// * `tool_choice` - The tool choice to use.
    pub fn with_tool_choice(mut self, tool_choice: ToolChoice) -> Self {
        self.req.tool_choice = Some(tool_choice);
        self
    }

    /// Builds the chat completion request.
    pub fn build(self) -> ChatCompletionRequest {
        self.req
    }
}

/// Represents a chat completion request.
#[derive(Debug, Serialize)]
pub struct ChatCompletionRequest {
    /// The model to use for generating completions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// A list of messages comprising the conversation so far.
    pub messages: Vec<ChatCompletionRequestMessage>,
    /// Adjust the randomness of the generated text. Between 0.0 and 2.0. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
    ///
    /// We generally recommend altering this or top_p but not both.
    /// Defaults to `0.8`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f64>,
    /// An alternative to sampling with temperature. Limit the next token selection to a subset of tokens with a cumulative probability above a threshold `p`. The value should be between 0.0 and 1.0.
    ///
    /// Top-p sampling, also known as nucleus sampling, is another text generation method that selects the next token from a subset of tokens that together have a cumulative probability of at least `p`. This method provides a balance between diversity and quality by considering both the probabilities of tokens and the number of tokens to sample from. A higher value for top_p (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text.
    ///
    /// We generally recommend altering this or temperature but not both.
    /// Defaults to `0.9`. To disable top-p sampling, set it to `1.0`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f64>,
    /// How many chat completion choices to generate for each input message.
    /// Defaults to `1`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "n")]
    pub n_choice: Option<u64>,
    /// Whether to stream the results as they are generated. Useful for chatbots.
    /// Defaults to false.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,
    /// Options for streaming response. Only set this when you set `stream: true`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream_options: Option<StreamOptions>,
    /// A list of tokens at which to stop generation. If None, no stop tokens are used. Up to 4 sequences where the API will stop generating further tokens.
    /// Defaults to None
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop: Option<Vec<String>>,
    /// An upper bound for the number of tokens that can be generated for a completion. `-1` means infinity. `-2` means until context filled. Defaults to `i32::MAX`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_completion_tokens: Option<i32>,
    /// Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.
    /// Defaults to 0.0.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub presence_penalty: Option<f64>,
    /// Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.
    /// Defaults to 0.0.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frequency_penalty: Option<f64>,
    /// Modify the likelihood of specified tokens appearing in the completion.
    ///
    /// Accepts a json object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.
    /// Defaults to None.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logit_bias: Option<HashMap<String, f64>>,
    /// A unique identifier representing your end-user.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,

    /// Format that the model must output
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_format: Option<ChatResponseFormat>,
    /// A list of tools the model may call.
    ///
    /// Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<Tool>>,
    /// Controls which (if any) function is called by the model.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<ToolChoice>,
}
#[allow(deprecated)]
impl<'de> Deserialize<'de> for ChatCompletionRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ChatCompletionRequestVisitor;

        impl<'de> Visitor<'de> for ChatCompletionRequestVisitor {
            type Value = ChatCompletionRequest;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct ChatCompletionRequest")
            }

            fn visit_map<V>(self, mut map: V) -> Result<ChatCompletionRequest, V::Error>
            where
                V: MapAccess<'de>,
            {
                // Initialize all fields as None or empty
                let mut model = None;
                let mut messages = None;
                let mut temperature = None;
                let mut top_p = None;
                let mut n_choice = None;
                let mut stream = None;
                let mut stream_options = None;
                let mut stop = None;
                let mut max_completion_tokens = None;
                let mut presence_penalty = None;
                let mut frequency_penalty = None;
                let mut logit_bias = None;
                let mut user = None;
                let mut response_format = None;
                let mut tools = None;
                let mut tool_choice = None;

                while let Some(key) = map.next_key::<String>()? {
                    #[cfg(feature = "logging")]
                    debug!(target: "stdout", "key: {key}");

                    match key.as_str() {
                        "model" => model = map.next_value()?,
                        "messages" => messages = map.next_value()?,
                        "temperature" => temperature = map.next_value()?,
                        "top_p" => top_p = map.next_value()?,
                        "n" => n_choice = map.next_value()?,
                        "stream" => stream = map.next_value()?,
                        "stream_options" => stream_options = map.next_value()?,
                        "stop" => stop = map.next_value()?,
                        "max_completion_tokens" => max_completion_tokens = map.next_value()?,
                        "presence_penalty" => presence_penalty = map.next_value()?,
                        "frequency_penalty" => frequency_penalty = map.next_value()?,
                        "logit_bias" => logit_bias = map.next_value()?,
                        "user" => user = map.next_value()?,
                        "response_format" => response_format = map.next_value()?,
                        "tools" => tools = map.next_value()?,
                        "tool_choice" => tool_choice = map.next_value()?,
                        _ => {
                            // Ignore unknown fields
                            let _ = map.next_value::<IgnoredAny>()?;

                            #[cfg(feature = "logging")]
                            warn!(target: "stdout", "Not supported field: {key}");
                        }
                    }
                }

                // Ensure all required fields are initialized
                let messages = messages.ok_or_else(|| de::Error::missing_field("messages"))?;

                // Set default value for `max_completion_tokens` if not provided
                if max_completion_tokens.is_none() {
                    // max_completion_tokens = Some(-1);
                    max_completion_tokens = Some(i32::MAX);
                }

                // Check tools and tool_choice
                if tools.is_some() && tool_choice.is_none() {
                    tool_choice = Some(ToolChoice::None);
                }

                if n_choice.is_none() {
                    n_choice = Some(1);
                }

                if stream.is_none() {
                    stream = Some(false);
                }

                // Construct ChatCompletionRequest with all fields
                Ok(ChatCompletionRequest {
                    model,
                    messages,
                    temperature,
                    top_p,
                    n_choice,
                    stream,
                    stream_options,
                    stop,
                    max_completion_tokens,
                    presence_penalty,
                    frequency_penalty,
                    logit_bias,
                    user,
                    response_format,
                    tools,
                    tool_choice,
                })
            }
        }

        const FIELDS: &[&str] = &[
            "model",
            "messages",
            "temperature",
            "top_p",
            "n",
            "stream",
            "stream_options",
            "stop",
            "max_completion_tokens",
            "presence_penalty",
            "frequency_penalty",
            "logit_bias",
            "user",
            "response_format",
            "tools",
            "tool_choice",
        ];
        deserializer.deserialize_struct(
            "ChatCompletionRequest",
            FIELDS,
            ChatCompletionRequestVisitor,
        )
    }
}
#[allow(deprecated)]
impl Default for ChatCompletionRequest {
    fn default() -> Self {
        Self {
            model: None,
            messages: vec![],
            temperature: Some(0.8),
            top_p: Some(0.9),
            n_choice: Some(1),
            stream: Some(false),
            stream_options: None,
            stop: None,
            // max_completion_tokens: Some(-1),
            max_completion_tokens: Some(i32::MAX),
            presence_penalty: Some(0.0),
            frequency_penalty: Some(0.0),
            logit_bias: None,
            user: None,
            response_format: None,
            tools: None,
            tool_choice: None,
        }
    }
}
impl ChatCompletionRequest {
    /// Return the reference to the latest user message from the chat history.
    pub fn latest_user_message(&self) -> Option<&ChatCompletionUserMessage> {
        self.messages
            .iter()
            .rev()
            .find_map(|message| match message {
                ChatCompletionRequestMessage::User(user_message) => Some(user_message),
                _ => None,
            })
    }

    /// Return the mutable reference to the latest user message from the chat history.
    pub fn latest_user_message_mut(&mut self) -> Option<&mut ChatCompletionUserMessage> {
        self.messages
            .iter_mut()
            .rev()
            .find_map(|message| match message {
                ChatCompletionRequestMessage::User(user_message) => Some(user_message),
                _ => None,
            })
    }

    /// Return the type of the latest message from the chat history.
    pub fn latest_message_type(&self) -> Option<String> {
        self.messages.last().map(|message| match message {
            ChatCompletionRequestMessage::User(_) => "user".to_string(),
            ChatCompletionRequestMessage::Assistant(_) => "assistant".to_string(),
            ChatCompletionRequestMessage::System(_) => "system".to_string(),
            ChatCompletionRequestMessage::Tool(_) => "tool".to_string(),
            ChatCompletionRequestMessage::Developer(_) => "developer".to_string(),
        })
    }
}

#[test]
fn test_chat_serialize_chat_request() {
    {
        let mut messages = Vec::new();
        let system_message = ChatCompletionRequestMessage::System(
            ChatCompletionSystemMessage::new("Hello, world!", None),
        );
        messages.push(system_message);
        let user_message = ChatCompletionRequestMessage::User(ChatCompletionUserMessage::new(
            ChatCompletionUserMessageContent::Text("Hello, world!".to_string()),
            None,
        ));
        messages.push(user_message);
        let assistant_message = ChatCompletionRequestMessage::Assistant(
            ChatCompletionAssistantMessage::new(Some("Hello, world!".to_string()), None, None),
        );
        messages.push(assistant_message);
        let request = ChatCompletionRequestBuilder::new(&messages)
            .with_model("model-id")
            .with_sampling(ChatCompletionRequestSampling::Temperature(0.8))
            .with_n_choices(3)
            .enable_stream(true)
            .include_usage()
            .with_stop(vec!["stop1".to_string(), "stop2".to_string()])
            .with_presence_penalty(0.5)
            .with_frequency_penalty(0.5)
            .with_reponse_format(ChatResponseFormat::default())
            .with_tool_choice(ToolChoice::Auto)
            .build();
        let json = serde_json::to_string(&request).unwrap();
        assert_eq!(
            json,
            r#"{"model":"model-id","messages":[{"role":"system","content":"Hello, world!"},{"role":"user","content":"Hello, world!"},{"role":"assistant","content":"Hello, world!"}],"temperature":0.8,"top_p":1.0,"n":3,"stream":true,"stream_options":{"include_usage":true},"stop":["stop1","stop2"],"max_completion_tokens":2147483647,"presence_penalty":0.5,"frequency_penalty":0.5,"response_format":{"type":"text"},"tool_choice":"auto"}"#
        );
    }

    {
        let mut messages = Vec::new();
        let system_message = ChatCompletionRequestMessage::System(
            ChatCompletionSystemMessage::new("Hello, world!", None),
        );
        messages.push(system_message);

        let user_message_content = ChatCompletionUserMessageContent::Parts(vec![
            ContentPart::Text(TextContentPart::new("what is in the picture?")),
            ContentPart::Image(ImageContentPart::new(Image {
                url: "https://example.com/image.png".to_string(),
                detail: None,
            })),
        ]);
        let user_message =
            ChatCompletionRequestMessage::new_user_message(user_message_content, None);
        messages.push(user_message);

        let request = ChatCompletionRequestBuilder::new(&messages)
            .with_model("model-id")
            .with_tool_choice(ToolChoice::None)
            .build();
        let json = serde_json::to_string(&request).unwrap();
        assert_eq!(
            json,
            r#"{"model":"model-id","messages":[{"role":"system","content":"Hello, world!"},{"role":"user","content":[{"type":"text","text":"what is in the picture?"},{"type":"image_url","image_url":{"url":"https://example.com/image.png"}}]}],"temperature":0.8,"top_p":0.9,"n":1,"stream":false,"max_completion_tokens":2147483647,"presence_penalty":0.0,"frequency_penalty":0.0,"tool_choice":"none"}"#
        );
    }

    {
        let mut messages = Vec::new();
        let system_message = ChatCompletionRequestMessage::System(
            ChatCompletionSystemMessage::new("Hello, world!", None),
        );
        messages.push(system_message);
        let user_message = ChatCompletionRequestMessage::User(ChatCompletionUserMessage::new(
            ChatCompletionUserMessageContent::Text("Hello, world!".to_string()),
            None,
        ));
        messages.push(user_message);
        let assistant_message = ChatCompletionRequestMessage::Assistant(
            ChatCompletionAssistantMessage::new(Some("Hello, world!".to_string()), None, None),
        );
        messages.push(assistant_message);

        let json_str = r###"{
                    "$schema": "http://json-schema.org/draft-07/schema#",
                    "definitions": {
                        "TemperatureUnit": {
                            "enum": [
                                "celsius",
                                "fahrenheit"
                            ],
                            "type": "string"
                        }
                    },
                    "properties": {
                        "api_key": {
                            "description": "the OpenWeatherMap API key to use. If not provided, the server will use the OPENWEATHERMAP_API_KEY environment variable.",
                            "type": [
                                "string",
                                "null"
                            ]
                        },
                        "location": {
                            "description": "the city to get the weather for, e.g., 'Beijing', 'New York', 'Tokyo'",
                            "type": "string"
                        },
                        "unit": {
                            "allOf": [
                                {
                                    "$ref": "#/definitions/TemperatureUnit"
                                }
                            ],
                            "description": "the unit to use for the temperature, e.g., 'celsius', 'fahrenheit'"
                        }
                    },
                    "required": [
                        "location",
                        "unit"
                    ],
                    "title": "GetWeatherRequest",
                    "type": "object"
                }"###;
        let json_schema: JsonObject = serde_json::from_str(json_str).unwrap();

        let tool = Tool {
            ty: ToolType::Function,
            function: ToolFunction {
                name: "my_function".to_string(),
                description: None,
                parameters: Some(json_schema),
            },
        };

        let request = ChatCompletionRequestBuilder::new(&messages)
            .with_model("model-id")
            .with_sampling(ChatCompletionRequestSampling::Temperature(0.8))
            .with_n_choices(3)
            .enable_stream(true)
            .include_usage()
            .with_stop(vec!["stop1".to_string(), "stop2".to_string()])
            .with_max_completion_tokens(100)
            .with_presence_penalty(0.5)
            .with_frequency_penalty(0.5)
            .with_reponse_format(ChatResponseFormat::default())
            .with_tools(vec![tool])
            .with_tool_choice(ToolChoice::Tool(ToolChoiceTool {
                ty: ToolType::Function,
                function: ToolChoiceToolFunction {
                    name: "my_function".to_string(),
                },
            }))
            .build();
        let json = serde_json::to_string(&request).unwrap();
        assert_eq!(
            json,
            r###"{"model":"model-id","messages":[{"role":"system","content":"Hello, world!"},{"role":"user","content":"Hello, world!"},{"role":"assistant","content":"Hello, world!"}],"temperature":0.8,"top_p":1.0,"n":3,"stream":true,"stream_options":{"include_usage":true},"stop":["stop1","stop2"],"max_completion_tokens":100,"presence_penalty":0.5,"frequency_penalty":0.5,"response_format":{"type":"text"},"tools":[{"type":"function","function":{"name":"my_function","parameters":{"$schema":"http://json-schema.org/draft-07/schema#","definitions":{"TemperatureUnit":{"enum":["celsius","fahrenheit"],"type":"string"}},"properties":{"api_key":{"description":"the OpenWeatherMap API key to use. If not provided, the server will use the OPENWEATHERMAP_API_KEY environment variable.","type":["string","null"]},"location":{"description":"the city to get the weather for, e.g., 'Beijing', 'New York', 'Tokyo'","type":"string"},"unit":{"allOf":[{"$ref":"#/definitions/TemperatureUnit"}],"description":"the unit to use for the temperature, e.g., 'celsius', 'fahrenheit'"}},"required":["location","unit"],"title":"GetWeatherRequest","type":"object"}}}],"tool_choice":{"type":"function","function":{"name":"my_function"}}}"###
        );
    }

    {
        let mut messages = Vec::new();
        let system_message = ChatCompletionRequestMessage::System(
            ChatCompletionSystemMessage::new("Hello, world!", None),
        );
        messages.push(system_message);
        let user_message = ChatCompletionRequestMessage::User(ChatCompletionUserMessage::new(
            ChatCompletionUserMessageContent::Text("Hello, world!".to_string()),
            None,
        ));
        messages.push(user_message);
        let assistant_message = ChatCompletionRequestMessage::Assistant(
            ChatCompletionAssistantMessage::new(Some("Hello, world!".to_string()), None, None),
        );
        messages.push(assistant_message);

        let tool = Tool {
            ty: ToolType::Function,
            function: ToolFunction {
                name: "my_function".to_string(),
                description: None,
                parameters: None,
            },
        };

        let request = ChatCompletionRequestBuilder::new(&messages)
            .with_model("model-id")
            .with_sampling(ChatCompletionRequestSampling::Temperature(0.8))
            .with_n_choices(3)
            .enable_stream(true)
            .include_usage()
            .with_stop(vec!["stop1".to_string(), "stop2".to_string()])
            .with_max_completion_tokens(100)
            .with_presence_penalty(0.5)
            .with_frequency_penalty(0.5)
            .with_reponse_format(ChatResponseFormat::default())
            .with_tools(vec![tool])
            .with_tool_choice(ToolChoice::Auto)
            .build();
        let json = serde_json::to_string(&request).unwrap();
        assert_eq!(
            json,
            r#"{"model":"model-id","messages":[{"role":"system","content":"Hello, world!"},{"role":"user","content":"Hello, world!"},{"role":"assistant","content":"Hello, world!"}],"temperature":0.8,"top_p":1.0,"n":3,"stream":true,"stream_options":{"include_usage":true},"stop":["stop1","stop2"],"max_completion_tokens":100,"presence_penalty":0.5,"frequency_penalty":0.5,"response_format":{"type":"text"},"tools":[{"type":"function","function":{"name":"my_function"}}],"tool_choice":"auto"}"#
        );
    }
}

#[test]
fn test_chat_deserialize_chat_request() {
    {
        let json = r#"{"model":"model-id","messages":[{"role":"system","content":"Hello, world!"},{"role":"user","content":"Hello, world!"},{"role":"assistant","content":"Hello, world!"}],"temperature":0.8,"top_p":1.0,"n":3,"stream":true,"stop":["stop1","stop2"],"presence_penalty":0.5,"frequency_penalty":0.5,"response_format":{"type":"text"}}"#;
        let request: ChatCompletionRequest = serde_json::from_str(json).unwrap();
        assert_eq!(request.model, Some("model-id".to_string()));
        assert_eq!(request.messages.len(), 3);
        assert_eq!(
            request.messages[0],
            ChatCompletionRequestMessage::System(ChatCompletionSystemMessage::new(
                "Hello, world!",
                None
            ))
        );
        assert_eq!(
            request.messages[1],
            ChatCompletionRequestMessage::User(ChatCompletionUserMessage::new(
                ChatCompletionUserMessageContent::Text("Hello, world!".to_string()),
                None
            ))
        );
        assert_eq!(
            request.messages[2],
            ChatCompletionRequestMessage::Assistant(ChatCompletionAssistantMessage::new(
                Some("Hello, world!".to_string()),
                None,
                None
            ))
        );
        assert_eq!(request.temperature, Some(0.8));
        assert_eq!(request.top_p, Some(1.0));
        assert_eq!(request.n_choice, Some(3));
        assert_eq!(request.stream, Some(true));
        assert_eq!(
            request.stop,
            Some(vec!["stop1".to_string(), "stop2".to_string()])
        );
        assert_eq!(request.max_completion_tokens, Some(i32::MAX));
        assert_eq!(request.presence_penalty, Some(0.5));
        assert_eq!(request.frequency_penalty, Some(0.5));
        assert_eq!(request.tool_choice, None);
    }

    {
        let json = r#"{"model":"model-id","messages":[{"role":"system","content":"Hello, world!"},{"role":"user","content":"Hello, world!"},{"role":"assistant","content":"Hello, world!"}],"temperature":0.8,"top_p":1.0,"n":3,"stream":true,"stop":["stop1","stop2"],"max_completion_tokens":100,"presence_penalty":0.5,"frequency_penalty":0.5,"response_format":{"type":"text"},"tool_choice":"auto"}"#;
        let request: ChatCompletionRequest = serde_json::from_str(json).unwrap();
        assert_eq!(request.model, Some("model-id".to_string()));
        assert_eq!(request.messages.len(), 3);
        assert_eq!(request.temperature, Some(0.8));
        assert_eq!(request.top_p, Some(1.0));
        assert_eq!(request.n_choice, Some(3));
        assert_eq!(request.stream, Some(true));
        assert_eq!(
            request.stop,
            Some(vec!["stop1".to_string(), "stop2".to_string()])
        );
        assert_eq!(request.max_completion_tokens, Some(100));
        assert_eq!(request.presence_penalty, Some(0.5));
        assert_eq!(request.frequency_penalty, Some(0.5));
        assert_eq!(request.tool_choice, Some(ToolChoice::Auto));
    }

    {
        let json = r#"{"model":"model-id","messages":[{"role":"system","content":"Hello, world!"},{"role":"user","content":"Hello, world!"},{"role":"assistant","content":"Hello, world!"}],"temperature":0.8,"top_p":1.0,"n":3,"stream":true,"stop":["stop1","stop2"],"max_completion_tokens":100,"presence_penalty":0.5,"frequency_penalty":0.5,"response_format":{"type":"text"},"tool_choice":{"type":"function","function":{"name":"my_function"}}}"#;
        let request: ChatCompletionRequest = serde_json::from_str(json).unwrap();
        assert_eq!(request.model, Some("model-id".to_string()));
        assert_eq!(request.messages.len(), 3);
        assert_eq!(request.temperature, Some(0.8));
        assert_eq!(request.top_p, Some(1.0));
        assert_eq!(request.n_choice, Some(3));
        assert_eq!(request.stream, Some(true));
        assert_eq!(
            request.stop,
            Some(vec!["stop1".to_string(), "stop2".to_string()])
        );
        assert_eq!(request.max_completion_tokens, Some(100));
        assert_eq!(request.presence_penalty, Some(0.5));
        assert_eq!(request.frequency_penalty, Some(0.5));
        assert_eq!(
            request.tool_choice,
            Some(ToolChoice::Tool(ToolChoiceTool {
                ty: ToolType::Function,
                function: ToolChoiceToolFunction {
                    name: "my_function".to_string(),
                },
            }))
        );
    }

    {
        let json = r#"{"model":"model-id","messages":[{"role":"system","content":"Hello, world!"},{"role":"user","content":"Hello, world!"},{"role":"assistant","content":"Hello, world!"}],"temperature":0.8,"top_p":1.0,"n":3,"stream":true,"stream_options":{"include_usage":true},"stop":["stop1","stop2"],"max_completion_tokens":100,"presence_penalty":0.5,"frequency_penalty":0.5,"response_format":{"type":"text"},"tools":[{"type":"function","function":{"name":"my_function","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"]}}}]}"#;

        let request: ChatCompletionRequest = serde_json::from_str(json).unwrap();
        let tool_choice = request.tool_choice.unwrap();
        assert_eq!(tool_choice, ToolChoice::None);
    }

    {
        let json = r#"{"model":"model-id","messages":[{"role":"system","content":"Hello, world!"},{"role":"user","content":"Hello, world!"},{"role":"assistant","content":"Hello, world!"}],"temperature":0.8,"top_p":1.0,"n":3,"stream":true,"stream_options":{"include_usage":true},"stop":["stop1","stop2"],"max_completion_tokens":100,"presence_penalty":0.5,"frequency_penalty":0.5,"response_format":{"type":"text"}}"#;

        let request: ChatCompletionRequest = serde_json::from_str(json).unwrap();
        assert!(request.tool_choice.is_none());
    }

    {
        let json_str = r###"{
    "model": "Llama-3-Groq-8B",
    "messages": [
        {
            "role": "user",
            "content": "How is the weather of Beijing, China? In Celsius."
        }
    ],
    "tools": [
        {
            "type": "function",
            "function": {
                "name": "sum",
                "description": "Calculate the sum of two numbers",
                "parameters": {
                    "$schema": "http://json-schema.org/draft-07/schema#",
                    "properties": {
                        "a": {
                            "description": "the left hand side number",
                            "format": "int32",
                            "type": "integer"
                        },
                        "b": {
                            "description": "the right hand side number",
                            "format": "int32",
                            "type": "integer"
                        }
                    },
                    "required": [
                        "a",
                        "b"
                    ],
                    "title": "SumRequest",
                    "type": "object"
                }
            }
        }
    ],
    "tool_choice": "required",
    "stream": false
}"###;

        let request: ChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        assert!(request.model.is_some());
        let tools = request.tools.unwrap();
        assert!(tools.len() == 1);
        let tool = &tools[0];
        assert_eq!(tool.ty, ToolType::Function);
        assert_eq!(tool.function.name, "sum");
        assert!(tool.function.parameters.is_some());
        let params = tool.function.parameters.as_ref().unwrap();
        assert!(params.contains_key("properties"));
        let properties = params.get("properties").unwrap();
        let properties = properties.as_object().unwrap();
        assert!(properties.len() == 2);
        assert!(properties.contains_key("a"));
        assert!(properties.contains_key("b"));
        let a = properties.get("a").unwrap();
        let a = a.as_object().unwrap();
        assert!(a.contains_key("description"));
        assert_eq!(
            a.get("description").unwrap().as_str().unwrap(),
            "the left hand side number"
        );
        assert!(a.contains_key("format"));
        assert_eq!(a.get("format").unwrap().as_str().unwrap(), "int32");
        assert!(a.contains_key("type"));
        assert_eq!(a.get("type").unwrap().as_str().unwrap(), "integer");
        let b = properties.get("b").unwrap();
        let b = b.as_object().unwrap();
        assert!(b.contains_key("description"));
        assert_eq!(
            b.get("description").unwrap().as_str().unwrap(),
            "the right hand side number"
        );
        assert!(b.contains_key("format"));
        assert_eq!(b.get("format").unwrap().as_str().unwrap(), "int32");
        assert!(b.contains_key("type"));
        assert_eq!(b.get("type").unwrap().as_str().unwrap(), "integer");
    }
}

/// An object specifying the format that the model must output.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ChatResponseFormat {
    /// Must be one of `text`` or `json_object`. Defaults to `text`.
    #[serde(rename = "type")]
    pub ty: String,
}
impl Default for ChatResponseFormat {
    fn default() -> Self {
        Self {
            ty: "text".to_string(),
        }
    }
}

#[test]
fn test_chat_serialize_response_format() {
    let response_format = ChatResponseFormat {
        ty: "text".to_string(),
    };
    let json = serde_json::to_string(&response_format).unwrap();
    assert_eq!(json, r#"{"type":"text"}"#);

    let response_format = ChatResponseFormat {
        ty: "json_object".to_string(),
    };
    let json = serde_json::to_string(&response_format).unwrap();
    assert_eq!(json, r#"{"type":"json_object"}"#);
}

/// Options for streaming response. Only set this when you set stream: `true`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct StreamOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_usage: Option<bool>,
}

/// Controls which (if any) function is called by the model. Defaults to `None`.
#[derive(Debug, Default, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum ToolChoice {
    /// The model will not call a function and instead generates a message.
    #[serde(rename = "none")]
    #[default]
    None,
    /// The model can pick between generating a message or calling a function.
    #[serde(rename = "auto")]
    Auto,
    /// The model must call one or more tools.
    #[serde(rename = "required")]
    Required,
    /// Specifies a tool the model should use. Use to force the model to call a specific function.
    #[serde(untagged)]
    Tool(ToolChoiceTool),
}

#[test]
fn test_chat_serialize_tool_choice() {
    let tool_choice = ToolChoice::None;
    let json = serde_json::to_string(&tool_choice).unwrap();
    assert_eq!(json, r#""none""#);

    let tool_choice = ToolChoice::Auto;
    let json = serde_json::to_string(&tool_choice).unwrap();
    assert_eq!(json, r#""auto""#);

    let tool_choice = ToolChoice::Tool(ToolChoiceTool {
        ty: ToolType::Function,
        function: ToolChoiceToolFunction {
            name: "my_function".to_string(),
        },
    });
    let json = serde_json::to_string(&tool_choice).unwrap();
    assert_eq!(
        json,
        r#"{"type":"function","function":{"name":"my_function"}}"#
    );
}

#[test]
fn test_chat_deserialize_tool_choice() {
    let json = r#""none""#;
    let tool_choice: ToolChoice = serde_json::from_str(json).unwrap();
    assert_eq!(tool_choice, ToolChoice::None);

    let json = r#""auto""#;
    let tool_choice: ToolChoice = serde_json::from_str(json).unwrap();
    assert_eq!(tool_choice, ToolChoice::Auto);

    let json = r#"{"type":"function","function":{"name":"my_function"}}"#;
    let tool_choice: ToolChoice = serde_json::from_str(json).unwrap();
    assert_eq!(
        tool_choice,
        ToolChoice::Tool(ToolChoiceTool {
            ty: ToolType::Function,
            function: ToolChoiceToolFunction {
                name: "my_function".to_string(),
            },
        })
    );
}

/// A tool the model should use.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct ToolChoiceTool {
    /// The type of the tool. Currently, only `function` is supported.
    #[serde(rename = "type")]
    pub ty: ToolType,
    /// The function the model calls.
    pub function: ToolChoiceToolFunction,
}

/// Represents a tool the model should use.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct ToolChoiceToolFunction {
    /// The name of the function to call.
    pub name: String,
}

/// Represents a tool the model may generate JSON inputs for.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Tool {
    /// The type of the tool. Currently, only `function` is supported.
    #[serde(rename = "type")]
    pub ty: ToolType,
    /// Function the model may generate JSON inputs for.
    pub function: ToolFunction,
}
impl Tool {
    pub fn new(function: ToolFunction) -> Self {
        Self {
            ty: ToolType::Function,
            function,
        }
    }
}

#[test]
fn test_chat_serialize_tool() {
    {
        let tool = Tool {
            ty: ToolType::Function,
            function: ToolFunction {
                name: "my_function".to_string(),
                description: None,
                parameters: None,
            },
        };
        let json = serde_json::to_string(&tool).unwrap();
        assert_eq!(
            json,
            r#"{"type":"function","function":{"name":"my_function"}}"#
        );
    }

    {
        let input_schema_str = r###"{
                    "$schema": "http://json-schema.org/draft-07/schema#",
                    "properties": {
                        "a": {
                            "description": "the left hand side number",
                            "format": "int32",
                            "type": "integer"
                        },
                        "b": {
                            "description": "the right hand side number",
                            "format": "int32",
                            "type": "integer"
                        }
                    },
                    "required": [
                        "a",
                        "b"
                    ],
                    "title": "SumRequest",
                    "type": "object"
                }"###;
        let input_schema: JsonObject = serde_json::from_str(input_schema_str).unwrap();

        let tool = Tool {
            ty: ToolType::Function,
            function: ToolFunction {
                name: "sum".to_string(),
                description: Some("Calculate the sum of two numbers".to_string()),
                parameters: Some(input_schema),
            },
        };
        let json = serde_json::to_string(&tool).unwrap();
        assert_eq!(
            json,
            r###"{"type":"function","function":{"name":"sum","description":"Calculate the sum of two numbers","parameters":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{"a":{"description":"the left hand side number","format":"int32","type":"integer"},"b":{"description":"the right hand side number","format":"int32","type":"integer"}},"required":["a","b"],"title":"SumRequest","type":"object"}}}"###
        );
    }

    {
        let tool1_json_str = r###"{
            "type": "function",
            "function": {
                "name": "get_current_weather",
                "description": "Get the current weather in a given location",
                "parameters": {
                    "$schema": "http://json-schema.org/draft-07/schema#",
                    "definitions": {
                        "TemperatureUnit": {
                            "enum": [
                                "celsius",
                                "fahrenheit"
                            ],
                            "type": "string"
                        }
                    },
                    "properties": {
                        "api_key": {
                            "description": "the OpenWeatherMap API key to use. If not provided, the server will use the OPENWEATHERMAP_API_KEY environment variable.",
                            "type": [
                                "string",
                                "null"
                            ]
                        },
                        "location": {
                            "description": "the city to get the weather for, e.g., 'Beijing', 'New York', 'Tokyo'",
                            "type": "string"
                        },
                        "unit": {
                            "allOf": [
                                {
                                    "$ref": "#/definitions/TemperatureUnit"
                                }
                            ],
                            "description": "the unit to use for the temperature, e.g., 'celsius', 'fahrenheit'"
                        }
                    },
                    "required": [
                        "location",
                        "unit"
                    ],
                    "title": "GetWeatherRequest",
                    "type": "object"
                }
            }
        }"###;
        let tool_1: Tool = serde_json::from_str(tool1_json_str).unwrap();

        let tool2_json_str = r###"{
            "type": "function",
            "function": {
                "name": "sum",
                "description": "Calculate the sum of two numbers",
                "parameters": {
                    "$schema": "http://json-schema.org/draft-07/schema#",
                    "properties": {
                        "a": {
                            "description": "the left hand side number",
                            "format": "int32",
                            "type": "integer"
                        },
                        "b": {
                            "description": "the right hand side number",
                            "format": "int32",
                            "type": "integer"
                        }
                    },
                    "required": [
                        "a",
                        "b"
                    ],
                    "title": "SumRequest",
                    "type": "object"
                }
            }
        }"###;
        let tool_2: Tool = serde_json::from_str(tool2_json_str).unwrap();

        let tools = vec![tool_1, tool_2];
        let json_str = serde_json::to_string(&tools).unwrap();
        assert_eq!(
            json_str,
            r###"[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"$schema":"http://json-schema.org/draft-07/schema#","definitions":{"TemperatureUnit":{"enum":["celsius","fahrenheit"],"type":"string"}},"properties":{"api_key":{"description":"the OpenWeatherMap API key to use. If not provided, the server will use the OPENWEATHERMAP_API_KEY environment variable.","type":["string","null"]},"location":{"description":"the city to get the weather for, e.g., 'Beijing', 'New York', 'Tokyo'","type":"string"},"unit":{"allOf":[{"$ref":"#/definitions/TemperatureUnit"}],"description":"the unit to use for the temperature, e.g., 'celsius', 'fahrenheit'"}},"required":["location","unit"],"title":"GetWeatherRequest","type":"object"}}},{"type":"function","function":{"name":"sum","description":"Calculate the sum of two numbers","parameters":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{"a":{"description":"the left hand side number","format":"int32","type":"integer"},"b":{"description":"the right hand side number","format":"int32","type":"integer"}},"required":["a","b"],"title":"SumRequest","type":"object"}}}]"###
        );
    }
}

#[test]
fn test_chat_deserialize_tool() {
    use std::any::{Any, TypeId};

    let json = r###"{
    "type": "function",
    "function": {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
            "$schema": "http://json-schema.org/draft-07/schema#",
            "definitions": {
                "TemperatureUnit": {
                    "enum": [
                        "celsius",
                        "fahrenheit"
                    ],
                    "type": "string"
                }
            },
            "properties": {
                "api_key": {
                    "description": "the OpenWeatherMap API key to use. If not provided, the server will use the OPENWEATHERMAP_API_KEY environment variable.",
                    "type": [
                        "string",
                        "null"
                    ]
                },
                "location": {
                    "description": "the city to get the weather for, e.g., 'Beijing', 'New York', 'Tokyo'",
                    "type": "string"
                },
                "unit": {
                    "allOf": [
                        {
                            "$ref": "#/definitions/TemperatureUnit"
                        }
                    ],
                    "description": "the unit to use for the temperature, e.g., 'celsius', 'fahrenheit'"
                }
            },
            "required": [
                "location",
                "unit"
            ],
            "title": "GetWeatherRequest",
            "type": "object"
        }
    }
}"###;
    let tool: Tool = serde_json::from_str(json).unwrap();
    assert_eq!(tool.ty, ToolType::Function);
    assert_eq!(tool.function.name, "get_current_weather");
    assert!(tool.function.description.is_some());
    assert!(tool.function.parameters.is_some());
    let params = tool.function.parameters.as_ref().unwrap();
    assert_eq!(params.type_id(), TypeId::of::<JsonObject>());
    assert!(params.contains_key("$schema"));
    assert!(params.contains_key("definitions"));
    let definitions = params.get("definitions").unwrap();
    let definitions = definitions.as_object().unwrap();
    assert_eq!(definitions.len(), 1);
    assert!(definitions.contains_key("TemperatureUnit"));
    let temperature_unit = definitions.get("TemperatureUnit").unwrap();
    let temperature_unit = temperature_unit.as_object().unwrap();
    assert_eq!(temperature_unit.len(), 2);
    assert!(temperature_unit.contains_key("enum"));
    let enum_values = temperature_unit.get("enum").unwrap();
    let enum_values = enum_values.as_array().unwrap();
    assert_eq!(enum_values.len(), 2);
    assert_eq!(enum_values[0].as_str().unwrap(), "celsius");
    assert_eq!(enum_values[1].as_str().unwrap(), "fahrenheit");
    assert!(params.contains_key("properties"));
    let properties = params.get("properties").unwrap();
    let properties = properties.as_object().unwrap();
    assert_eq!(properties.len(), 3);
    assert!(properties.contains_key("unit"));
    assert!(properties.contains_key("location"));
    assert!(properties.contains_key("api_key"));
    let unit = properties.get("unit").unwrap();
    let unit = unit.as_object().unwrap();
    assert!(unit.contains_key("allOf"));
    let all_of = unit.get("allOf").unwrap();
    let all_of = all_of.as_array().unwrap();
    assert_eq!(all_of.len(), 1);
    let all_of_0 = all_of[0].as_object().unwrap();
    assert!(all_of_0.contains_key("$ref"));
    assert_eq!(
        all_of_0.get("$ref").unwrap().as_str().unwrap(),
        "#/definitions/TemperatureUnit"
    );
    let location = properties.get("location").unwrap();
    let location = location.as_object().unwrap();
    assert_eq!(location.len(), 2);
    assert!(location.contains_key("description"));
    assert_eq!(
        location.get("description").unwrap().as_str().unwrap(),
        "the city to get the weather for, e.g., 'Beijing', 'New York', 'Tokyo'"
    );
    assert!(location.contains_key("type"));
    assert_eq!(location.get("type").unwrap().as_str().unwrap(), "string");
    assert!(params.contains_key("required"));
    let required = params.get("required").unwrap();
    let required = required.as_array().unwrap();
    assert_eq!(required.len(), 2);
    assert_eq!(required[0].as_str().unwrap(), "location");
    assert_eq!(required[1].as_str().unwrap(), "unit");
}

/// Function the model may generate JSON inputs for.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ToolFunction {
    /// The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.
    pub name: String,
    /// A description of what the function does, used by the model to choose when and how to call the function.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The parameters the functions accepts, described as a JSON Schema object.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<JsonObject>,
}

pub type JsonObject<F = Value> = serde_json::Map<String, F>;

#[test]
fn test_chat_serialize_tool_function() {
    let parameters_str = r###"{
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "TemperatureUnit": {
            "enum": [
              "celsius",
              "fahrenheit"
            ],
            "type": "string"
          }
        },
        "properties": {
          "api_key": {
            "description": "the OpenWeatherMap API key to use. If not provided, the server will use the OPENWEATHERMAP_API_KEY environment variable.",
            "type": [
              "string",
              "null"
            ]
          },
          "location": {
            "description": "the city to get the weather for, e.g., 'Beijing', 'New York', 'Tokyo'",
            "type": "string"
          },
          "unit": {
            "allOf": [
              {
                "$ref": "#/definitions/TemperatureUnit"
              }
            ],
            "description": "the unit to use for the temperature, e.g., 'celsius', 'fahrenheit'"
          }
        },
        "required": [
          "location",
          "unit"
        ],
        "title": "GetWeatherRequest",
        "type": "object"
      }"###;
    let parameters: JsonObject = serde_json::from_str(parameters_str).unwrap();

    let func = ToolFunction {
        name: "get_current_weather".to_string(),
        description: Some("Get the current weather in a given location".to_string()),
        parameters: Some(parameters),
    };

    let json_str = serde_json::to_string(&func).unwrap();
    assert_eq!(
        json_str,
        r###"{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"$schema":"http://json-schema.org/draft-07/schema#","definitions":{"TemperatureUnit":{"enum":["celsius","fahrenheit"],"type":"string"}},"properties":{"api_key":{"description":"the OpenWeatherMap API key to use. If not provided, the server will use the OPENWEATHERMAP_API_KEY environment variable.","type":["string","null"]},"location":{"description":"the city to get the weather for, e.g., 'Beijing', 'New York', 'Tokyo'","type":"string"},"unit":{"allOf":[{"$ref":"#/definitions/TemperatureUnit"}],"description":"the unit to use for the temperature, e.g., 'celsius', 'fahrenheit'"}},"required":["location","unit"],"title":"GetWeatherRequest","type":"object"}}"###
    );
}

/// The parameters the functions accepts, described as a JSON Schema object.
///
/// See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format.
///
/// To describe a function that accepts no parameters, provide the value
/// `{"type": "object", "properties": {}}`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ToolFunctionParameters {
    #[serde(rename = "type")]
    pub schema_type: JSONSchemaType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<IndexMap<String, Box<JSONSchemaDefine>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<Vec<String>>,
}

#[test]
fn test_chat_serialize_tool_function_params() {
    {
        let params = ToolFunctionParameters {
            schema_type: JSONSchemaType::Object,
            properties: Some(
                vec![
                    (
                        "location".to_string(),
                        Box::new(JSONSchemaDefine {
                            schema_type: Some(JSONSchemaType::String),
                            description: Some(
                                "The city and state, e.g. San Francisco, CA".to_string(),
                            ),
                            enum_values: None,
                            properties: None,
                            required: None,
                            items: None,
                            default: None,
                            maximum: None,
                            minimum: None,
                            title: None,
                            examples: None,
                        }),
                    ),
                    (
                        "unit".to_string(),
                        Box::new(JSONSchemaDefine {
                            schema_type: Some(JSONSchemaType::String),
                            description: None,
                            enum_values: Some(vec![
                                "celsius".to_string(),
                                "fahrenheit".to_string(),
                            ]),
                            properties: None,
                            required: None,
                            items: None,
                            default: None,
                            maximum: None,
                            minimum: None,
                            title: None,
                            examples: None,
                        }),
                    ),
                ]
                .into_iter()
                .collect(),
            ),
            required: Some(vec!["location".to_string()]),
        };

        let json = serde_json::to_string(&params).unwrap();
        assert_eq!(
            json,
            r#"{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}"#
        );
    }
}

#[test]
fn test_chat_deserialize_tool_function_params() {
    {
        let json = r###"
    {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The city and state, e.g. San Francisco, CA"
          },
          "unit": {
            "type": "string",
            "enum": ["celsius", "fahrenheit"]
          }
        },
        "required": ["location"]
    }"###;
        let params: ToolFunctionParameters = serde_json::from_str(json).unwrap();
        assert_eq!(params.schema_type, JSONSchemaType::Object);
        let properties = params.properties.as_ref().unwrap();
        assert_eq!(properties.len(), 2);
        assert!(properties.contains_key("unit"));
        assert!(properties.contains_key("location"));
        let unit = properties.get("unit").unwrap();
        assert_eq!(unit.schema_type, Some(JSONSchemaType::String));
        assert_eq!(
            unit.enum_values,
            Some(vec!["celsius".to_string(), "fahrenheit".to_string()])
        );
        let location = properties.get("location").unwrap();
        assert_eq!(location.schema_type, Some(JSONSchemaType::String));
        assert_eq!(
            location.description,
            Some("The city and state, e.g. San Francisco, CA".to_string())
        );
        let required = params.required.as_ref().unwrap();
        assert_eq!(required.len(), 1);
        assert_eq!(required[0], "location");
    }

    {
        let json = r###"{
            "properties": {
                "include_spam_trash": {
                    "default": false,
                    "description": "Include messages from SPAM and TRASH in the results.",
                    "title": "Include Spam Trash",
                    "type": "boolean"
                },
                "add_label_ids": {
                    "default": [],
                    "description": "A list of IDs of labels to add to this thread.",
                    "items": {
                        "type": "string"
                    },
                    "title": "Add Label Ids",
                    "type": "array"
                },
                "max_results": {
                    "default": 10,
                    "description": "Maximum number of messages to return.",
                    "examples": [
                        10,
                        50,
                        100
                    ],
                    "maximum": 500,
                    "minimum": 1,
                    "title": "Max Results",
                    "type": "integer"
                },
                "query": {
                    "default": null,
                    "description": "Only return threads matching the specified query.",
                    "examples": [
                        "is:unread",
                        "from:john.doe@example.com"
                    ],
                    "title": "Query",
                    "type": "string"
                }
            },
            "title": "FetchEmailsRequest",
            "type": "object"
        }"###;

        let params: ToolFunctionParameters = serde_json::from_str(json).unwrap();
        assert_eq!(params.schema_type, JSONSchemaType::Object);
        let properties = params.properties.as_ref().unwrap();
        assert_eq!(properties.len(), 4);
        // println!("{:?}", properties);
        assert!(properties.contains_key("include_spam_trash"));
        assert!(properties.contains_key("add_label_ids"));
        assert!(properties.contains_key("max_results"));
        assert!(properties.contains_key("query"));

        let include_spam_trash = properties.get("include_spam_trash").unwrap();
        assert_eq!(
            include_spam_trash.schema_type,
            Some(JSONSchemaType::Boolean)
        );
        assert_eq!(
            include_spam_trash.description,
            Some("Include messages from SPAM and TRASH in the results.".to_string())
        );
        assert_eq!(
            include_spam_trash.title,
            Some("Include Spam Trash".to_string())
        );
        assert_eq!(
            include_spam_trash.default,
            Some(serde_json::Value::Bool(false))
        );

        let add_label_ids = properties.get("add_label_ids").unwrap();
        assert_eq!(add_label_ids.schema_type, Some(JSONSchemaType::Array));
        assert_eq!(
            add_label_ids.description,
            Some("A list of IDs of labels to add to this thread.".to_string())
        );
        assert_eq!(add_label_ids.title, Some("Add Label Ids".to_string()));
        assert_eq!(
            add_label_ids.default,
            Some(serde_json::Value::Array(vec![]))
        );
        let items = add_label_ids.items.as_ref().unwrap();
        assert_eq!(items.schema_type, Some(JSONSchemaType::String));

        let max_results = properties.get("max_results").unwrap();
        assert_eq!(max_results.schema_type, Some(JSONSchemaType::Integer));
        assert_eq!(
            max_results.description,
            Some("Maximum number of messages to return.".to_string())
        );
        assert_eq!(
            max_results.examples,
            Some(vec![
                Value::Number(serde_json::Number::from(10)),
                Value::Number(serde_json::Number::from(50)),
                Value::Number(serde_json::Number::from(100))
            ])
        );
        assert_eq!(
            max_results.maximum,
            Some(Value::Number(serde_json::Number::from(500)))
        );
        assert_eq!(
            max_results.minimum,
            Some(Value::Number(serde_json::Number::from(1)))
        );
        assert_eq!(max_results.title, Some("Max Results".to_string()));
        assert_eq!(
            max_results.default,
            Some(serde_json::Value::Number(10.into()))
        );

        let query = properties.get("query").unwrap();
        assert_eq!(query.schema_type, Some(JSONSchemaType::String));
        assert_eq!(
            query.description,
            Some("Only return threads matching the specified query.".to_string())
        );
        assert_eq!(
            query.examples,
            Some(vec![
                Value::String("is:unread".to_string()),
                Value::String("from:john.doe@example.com".to_string())
            ])
        );
        assert_eq!(query.title, Some("Query".to_string()));
        assert_eq!(query.default, None);
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct McpTool {
    /// The type of the tool.
    #[serde(rename = "type")]
    pub ty: ToolType,
    /// The label of the server..
    #[serde(rename = "server_label")]
    pub server_label: String,
    /// The URL of the server.
    #[serde(rename = "server_url")]
    pub server_url: String,
    /// The transport type to use for the server.
    #[serde(rename = "transport")]
    pub transport: McpTransport,
    /// The tools allowed to be called by the model.
    #[serde(rename = "allowed_tools", skip_serializing_if = "Option::is_none")]
    pub allowed_tools: Option<Vec<String>>,
    /// The headers to send to the server.
    #[serde(rename = "headers", skip_serializing_if = "Option::is_none")]
    pub headers: Option<HashMap<String, String>>,
}
impl McpTool {
    pub fn new(server_label: String, server_url: String, transport: McpTransport) -> Self {
        Self {
            ty: ToolType::Mcp,
            server_label,
            server_url,
            transport,
            allowed_tools: None,
            headers: None,
        }
    }
}

#[test]
fn test_chat_serialize_mcp_tool() {
    let tool = McpTool::new(
        "test".to_string(),
        "https://test.com".to_string(),
        McpTransport::Sse,
    );
    let json = serde_json::to_string(&tool).unwrap();
    assert_eq!(
        json,
        r#"{"type":"mcp","server_label":"test","server_url":"https://test.com","transport":"sse"}"#
    );

    let tool = McpTool {
        ty: ToolType::Mcp,
        server_label: "test".to_string(),
        server_url: "https://test.com".to_string(),
        transport: McpTransport::Sse,
        allowed_tools: Some(vec!["test".to_string()]),
        headers: Some(HashMap::new()),
    };
    let json = serde_json::to_string(&tool).unwrap();
    assert_eq!(
        json,
        r#"{"type":"mcp","server_label":"test","server_url":"https://test.com","transport":"sse","allowed_tools":["test"],"headers":{}}"#
    );

    let tool = McpTool {
        ty: ToolType::Mcp,
        server_label: "test".to_string(),
        server_url: "https://test.com".to_string(),
        transport: McpTransport::StreamHttp,
        allowed_tools: Some(vec!["test".to_string()]),
        headers: Some(HashMap::from([(
            "Authorization".to_string(),
            "Bearer token".to_string(),
        )])),
    };
    let json = serde_json::to_string(&tool).unwrap();
    assert_eq!(
        json,
        r#"{"type":"mcp","server_label":"test","server_url":"https://test.com","transport":"stream-http","allowed_tools":["test"],"headers":{"Authorization":"Bearer token"}}"#
    );
}

#[test]
fn test_chat_deserialize_mcp_tool() {
    let json =
        r#"{"type":"mcp","server_label":"test","server_url":"https://test.com","transport":"sse"}"#;
    let tool: McpTool = serde_json::from_str(json).unwrap();
    assert_eq!(tool.ty, ToolType::Mcp);
    assert_eq!(tool.server_label, "test");
    assert_eq!(tool.server_url, "https://test.com");
    assert_eq!(tool.transport, McpTransport::Sse);
    assert_eq!(tool.allowed_tools, None);
    assert_eq!(tool.headers, None);

    let json = r#"{"type":"mcp","server_label":"test","server_url":"https://test.com","transport":"stream-http","allowed_tools":["test"],"headers":{"Authorization":"Bearer token"}}"#;
    let tool: McpTool = serde_json::from_str(json).unwrap();
    assert_eq!(tool.ty, ToolType::Mcp);
    assert_eq!(tool.server_label, "test");
    assert_eq!(tool.server_url, "https://test.com");
    assert_eq!(tool.transport, McpTransport::StreamHttp);
    assert_eq!(tool.allowed_tools, Some(vec!["test".to_string()]));
    assert_eq!(
        tool.headers,
        Some(HashMap::from([(
            "Authorization".to_string(),
            "Bearer token".to_string()
        )]))
    );
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum ToolType {
    #[serde(rename = "function")]
    Function,
    #[serde(rename = "mcp")]
    Mcp,
}

#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
pub enum McpTransport {
    #[serde(rename = "sse")]
    Sse,
    #[serde(rename = "stream-http")]
    StreamHttp,
    #[serde(rename = "stdio")]
    Stdio,
}
impl fmt::Display for McpTransport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            McpTransport::Sse => write!(f, "sse"),
            McpTransport::StreamHttp => write!(f, "stream-http"),
            McpTransport::Stdio => write!(f, "stdio"),
        }
    }
}

/// Message for comprising the conversation.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(tag = "role", rename_all = "lowercase")]
pub enum ChatCompletionRequestMessage {
    System(ChatCompletionSystemMessage),
    Developer(ChatCompletionDeveloperMessage),
    User(ChatCompletionUserMessage),
    Assistant(ChatCompletionAssistantMessage),
    Tool(ChatCompletionToolMessage),
}
impl ChatCompletionRequestMessage {
    /// Creates a new system message.
    ///
    /// # Arguments
    ///
    /// * `content` - The contents of the system message.
    ///
    /// * `name` - An optional name for the participant. Provides the model information to differentiate between participants of the same role.
    pub fn new_system_message(content: impl Into<String>, name: Option<String>) -> Self {
        ChatCompletionRequestMessage::System(ChatCompletionSystemMessage::new(content, name))
    }

    /// Creates a new developer message.
    ///
    /// # Arguments
    ///
    /// * `content` - The contents of the developer message.
    ///
    /// * `name` - An optional name for the participant. Provides the model information to differentiate between participants of the same role.
    pub fn new_developer_message(content: impl Into<String>, name: Option<String>) -> Self {
        ChatCompletionRequestMessage::Developer(ChatCompletionDeveloperMessage::new(content, name))
    }

    /// Creates a new user message.
    ///
    /// # Arguments
    ///
    /// * `content` - The contents of the user message.
    ///
    /// * `name` - An optional name for the participant. Provides the model information to differentiate between participants of the same role.
    pub fn new_user_message(
        content: ChatCompletionUserMessageContent,
        name: Option<String>,
    ) -> Self {
        ChatCompletionRequestMessage::User(ChatCompletionUserMessage::new(content, name))
    }

    /// Creates a new assistant message.
    ///
    /// # Arguments
    ///
    /// * `content` - The contents of the assistant message. Required unless `tool_calls` is specified.
    ///
    /// * `name` - An optional name for the participant. Provides the model information to differentiate between participants of the same role.
    ///
    /// * `tool_calls` - The tool calls generated by the model.
    pub fn new_assistant_message(
        content: Option<String>,
        name: Option<String>,
        tool_calls: Option<Vec<ToolCall>>,
    ) -> Self {
        ChatCompletionRequestMessage::Assistant(ChatCompletionAssistantMessage::new(
            content, name, tool_calls,
        ))
    }

    /// Creates a new tool message.
    pub fn new_tool_message(content: impl Into<String>, tool_call_id: impl Into<String>) -> Self {
        ChatCompletionRequestMessage::Tool(ChatCompletionToolMessage::new(content, tool_call_id))
    }

    /// The role of the messages author.
    pub fn role(&self) -> ChatCompletionRole {
        match self {
            ChatCompletionRequestMessage::System(_) => ChatCompletionRole::System,
            ChatCompletionRequestMessage::User(_) => ChatCompletionRole::User,
            ChatCompletionRequestMessage::Assistant(_) => ChatCompletionRole::Assistant,
            ChatCompletionRequestMessage::Tool(_) => ChatCompletionRole::Tool,
            ChatCompletionRequestMessage::Developer(_) => ChatCompletionRole::Developer,
        }
    }

    /// The name of the participant. Provides the model information to differentiate between participants of the same role.
    pub fn name(&self) -> Option<&String> {
        match self {
            ChatCompletionRequestMessage::System(message) => message.name(),
            ChatCompletionRequestMessage::User(message) => message.name(),
            ChatCompletionRequestMessage::Assistant(message) => message.name(),
            ChatCompletionRequestMessage::Tool(_) => None,
            ChatCompletionRequestMessage::Developer(message) => message.name(),
        }
    }
}

#[test]
fn test_chat_serialize_request_message() {
    let message = ChatCompletionRequestMessage::System(ChatCompletionSystemMessage::new(
        "Hello, world!",
        None,
    ));
    let json = serde_json::to_string(&message).unwrap();
    assert_eq!(json, r#"{"role":"system","content":"Hello, world!"}"#);

    let message = ChatCompletionRequestMessage::User(ChatCompletionUserMessage::new(
        ChatCompletionUserMessageContent::Text("Hello, world!".to_string()),
        None,
    ));
    let json = serde_json::to_string(&message).unwrap();
    assert_eq!(json, r#"{"role":"user","content":"Hello, world!"}"#);

    let message = ChatCompletionRequestMessage::Assistant(ChatCompletionAssistantMessage::new(
        Some("Hello, world!".to_string()),
        None,
        None,
    ));
    let json = serde_json::to_string(&message).unwrap();
    assert_eq!(json, r#"{"role":"assistant","content":"Hello, world!"}"#);

    let message = ChatCompletionRequestMessage::Tool(ChatCompletionToolMessage::new(
        "Hello, world!",
        "tool-call-id",
    ));
    let json = serde_json::to_string(&message).unwrap();
    assert_eq!(
        json,
        r#"{"role":"tool","content":"Hello, world!","tool_call_id":"tool-call-id"}"#
    );
}

#[test]
fn test_chat_deserialize_request_message() {
    let json = r#"{"content":"Hello, world!","role":"assistant"}"#;
    let message: ChatCompletionRequestMessage = serde_json::from_str(json).unwrap();
    assert_eq!(message.role(), ChatCompletionRole::Assistant);

    let json = r#"{"content":"Hello, world!","role":"system"}"#;
    let message: ChatCompletionRequestMessage = serde_json::from_str(json).unwrap();
    assert_eq!(message.role(), ChatCompletionRole::System);

    let json = r#"{"content":"Hello, world!","role":"user"}"#;
    let message: ChatCompletionRequestMessage = serde_json::from_str(json).unwrap();
    assert_eq!(message.role(), ChatCompletionRole::User);

    let json = r#"{"role":"tool","content":"Hello, world!","tool_call_id":"tool-call-id"}"#;
    let message: ChatCompletionRequestMessage = serde_json::from_str(json).unwrap();
    assert_eq!(message.role(), ChatCompletionRole::Tool);
}

/// Defines the content of a system message.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct ChatCompletionSystemMessage {
    /// The contents of the system message.
    content: String,
    /// An optional name for the participant. Provides the model information to differentiate between participants of the same role.
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,
}
impl ChatCompletionSystemMessage {
    /// Creates a new system message.
    ///
    /// # Arguments
    ///
    /// * `content` - The contents of the system message.
    ///
    /// * `name` - An optional name for the participant. Provides the model information to differentiate between participants of the same role.
    pub fn new(content: impl Into<String>, name: Option<String>) -> Self {
        Self {
            content: content.into(),
            name,
        }
    }

    pub fn role(&self) -> ChatCompletionRole {
        ChatCompletionRole::System
    }

    pub fn content(&self) -> &str {
        &self.content
    }

    pub fn name(&self) -> Option<&String> {
        self.name.as_ref()
    }
}

/// Defines the content of a developer message.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct ChatCompletionDeveloperMessage {
    /// The contents of the developer message.
    content: String,
    /// An optional name for the participant. Provides the model information to differentiate between participants of the same role.
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,
}
impl ChatCompletionDeveloperMessage {
    /// Creates a new developer message.
    ///
    /// # Arguments
    ///
    /// * `content` - The contents of the developer message.
    ///
    /// * `name` - An optional name for the participant. Provides the model information to differentiate between participants of the same role.
    pub fn new(content: impl Into<String>, name: Option<String>) -> Self {
        Self {
            content: content.into(),
            name,
        }
    }

    pub fn role(&self) -> ChatCompletionRole {
        ChatCompletionRole::Developer
    }

    pub fn content(&self) -> &str {
        &self.content
    }

    pub fn name(&self) -> Option<&String> {
        self.name.as_ref()
    }
}

/// Defines the content of a user message.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct ChatCompletionUserMessage {
    /// The contents of the user message.
    content: ChatCompletionUserMessageContent,
    /// An optional name for the participant. Provides the model information to differentiate between participants of the same role.
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,
}
impl ChatCompletionUserMessage {
    /// Creates a new user message.
    ///
    /// # Arguments
    ///
    /// * `content` - The contents of the user message.
    ///
    /// * `name` - An optional name for the participant. Provides the model information to differentiate between participants of the same role.
    pub fn new(content: ChatCompletionUserMessageContent, name: Option<String>) -> Self {
        Self { content, name }
    }

    pub fn role(&self) -> ChatCompletionRole {
        ChatCompletionRole::User
    }

    pub fn content(&self) -> &ChatCompletionUserMessageContent {
        &self.content
    }

    pub fn name(&self) -> Option<&String> {
        self.name.as_ref()
    }
}

#[test]
fn test_chat_serialize_user_message() {
    let message = ChatCompletionUserMessage::new(
        ChatCompletionUserMessageContent::Text("Hello, world!".to_string()),
        None,
    );
    let json = serde_json::to_string(&message).unwrap();
    assert_eq!(json, r#"{"content":"Hello, world!"}"#);

    let message = ChatCompletionUserMessage::new(
        ChatCompletionUserMessageContent::Parts(vec![
            ContentPart::Text(TextContentPart::new("Hello, world!")),
            ContentPart::Image(ImageContentPart::new(Image {
                url: "https://example.com/image.png".to_string(),
                detail: Some("auto".to_string()),
            })),
        ]),
        None,
    );
    let json = serde_json::to_string(&message).unwrap();
    assert_eq!(
        json,
        r#"{"content":[{"type":"text","text":"Hello, world!"},{"type":"image_url","image_url":{"url":"https://example.com/image.png","detail":"auto"}}]}"#
    );
}

#[test]
fn test_chat_deserialize_user_message() {
    let json = r#"{"content":"Hello, world!","role":"user"}"#;
    let message: ChatCompletionUserMessage = serde_json::from_str(json).unwrap();
    assert_eq!(message.content().ty(), "text");

    let json = r#"{"content":[{"type":"text","text":"Hello, world!"},{"type":"image_url","image_url":{"url":"https://example.com/image.png","detail":"auto"}}],"role":"user"}"#;
    let message: ChatCompletionUserMessage = serde_json::from_str(json).unwrap();
    assert_eq!(message.content().ty(), "parts");
}

/// Defines the content of an assistant message.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct ChatCompletionAssistantMessage {
    /// The contents of the assistant message. Required unless `tool_calls` is specified.
    #[serde(skip_serializing_if = "Option::is_none")]
    content: Option<String>,
    /// An optional name for the participant. Provides the model information to differentiate between participants of the same role.
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,
    /// The tool calls generated by the model.
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_calls: Option<Vec<ToolCall>>,
}
impl ChatCompletionAssistantMessage {
    /// Creates a new assistant message.
    ///
    /// # Arguments
    ///
    /// * `content` - The contents of the assistant message. Required unless `tool_calls` is specified.
    ///
    /// * `name` - An optional name for the participant. Provides the model information to differentiate between participants of the same role.
    ///
    /// * `tool_calls` - The tool calls generated by the model.
    pub fn new(
        content: Option<String>,
        name: Option<String>,
        tool_calls: Option<Vec<ToolCall>>,
    ) -> Self {
        match tool_calls.is_some() {
            true => Self {
                content,
                name,
                tool_calls,
            },
            false => Self {
                content,
                name,
                tool_calls: None,
            },
        }
    }

    /// The role of the messages author, in this case `assistant`.
    pub fn role(&self) -> ChatCompletionRole {
        ChatCompletionRole::Assistant
    }

    /// The contents of the assistant message. If `tool_calls` is specified, then `content` is None.
    pub fn content(&self) -> Option<&String> {
        self.content.as_ref()
    }

    /// An optional name for the participant.
    pub fn name(&self) -> Option<&String> {
        self.name.as_ref()
    }

    /// The tool calls generated by the model.
    pub fn tool_calls(&self) -> Option<&Vec<ToolCall>> {
        self.tool_calls.as_ref()
    }
}

#[test]
fn test_chat_serialize_assistant_message() {
    let message =
        ChatCompletionAssistantMessage::new(Some("Hello, world!".to_string()), None, None);
    let json = serde_json::to_string(&message).unwrap();
    assert_eq!(json, r#"{"content":"Hello, world!"}"#);
}

#[test]
fn test_chat_deserialize_assistant_message() {
    let json = r#"{"content":"Hello, world!","role":"assistant"}"#;
    let message: ChatCompletionAssistantMessage = serde_json::from_str(json).unwrap();
    assert_eq!(message.role(), ChatCompletionRole::Assistant);
    assert_eq!(message.content().unwrap().as_str(), "Hello, world!");
}

/// Defines the content of a tool message.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct ChatCompletionToolMessage {
    /// The contents of the tool message.
    content: String,
    /// Tool call that this message is responding to.
    tool_call_id: String,
}
impl ChatCompletionToolMessage {
    /// Creates a new tool message.
    ///
    /// # Arguments
    ///
    /// * `content` - The contents of the tool message.
    ///
    /// * `tool_call_id` - Tool call that this message is responding to.
    pub fn new(content: impl Into<String>, tool_call_id: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            tool_call_id: tool_call_id.into(),
        }
    }

    /// The role of the messages author, in this case `tool`.
    pub fn role(&self) -> ChatCompletionRole {
        ChatCompletionRole::Tool
    }

    /// The contents of the tool message.
    pub fn content(&self) -> &str {
        &self.content
    }

    /// Tool call that this message is responding to.
    pub fn tool_call_id(&self) -> &str {
        &self.tool_call_id
    }
}

/// Represents a tool call generated by the model.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct ToolCall {
    /// The ID of the tool call.
    pub id: String,
    /// The type of the tool. Currently, only function is supported.
    #[serde(rename = "type")]
    pub ty: String,
    /// The function that the model called.
    pub function: Function,
}
impl From<ToolCallForChunk> for ToolCall {
    fn from(value: ToolCallForChunk) -> Self {
        Self {
            id: value.id,
            ty: value.ty,
            function: Function {
                name: value.function.name,
                arguments: value.function.arguments,
            },
        }
    }
}

#[test]
fn test_deserialize_tool_call() {
    let json = r#"{"id":"tool-call-id","type":"function","function":{"name":"my_function","arguments":"{\"location\":\"San Francisco, CA\"}"}}"#;
    let tool_call: ToolCall = serde_json::from_str(json).unwrap();
    assert_eq!(tool_call.id, "tool-call-id");
    assert_eq!(tool_call.ty, "function");
    assert_eq!(
        tool_call.function,
        Function {
            name: "my_function".to_string(),
            arguments: r#"{"location":"San Francisco, CA"}"#.to_string()
        }
    );
}

/// Represents a tool call generated by the model.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct ToolCallForChunk {
    pub index: usize,
    /// The ID of the tool call.
    pub id: String,
    /// The type of the tool. Currently, only function is supported.
    #[serde(rename = "type")]
    pub ty: String,
    /// The function that the model called.
    pub function: Function,
}

#[test]
fn test_deserialize_tool_call_for_chunk() {
    let json = r#"{"index":0, "id":"tool-call-id","type":"function","function":{"name":"my_function","arguments":"{\"location\":\"San Francisco, CA\"}"}}"#;
    let tool_call: ToolCallForChunk = serde_json::from_str(json).unwrap();
    assert_eq!(tool_call.index, 0);
    assert_eq!(tool_call.id, "tool-call-id");
    assert_eq!(tool_call.ty, "function");
    assert_eq!(
        tool_call.function,
        Function {
            name: "my_function".to_string(),
            arguments: r#"{"location":"San Francisco, CA"}"#.to_string()
        }
    );
}

/// The function that the model called.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct Function {
    /// The name of the function that the model called.
    pub name: String,
    /// The arguments that the model called the function with.
    pub arguments: String,
}

/// Defines the types of a user message content.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum ChatCompletionUserMessageContent {
    /// The text contents of the message.
    Text(String),
    /// An array of content parts with a defined type, each can be of type `text` or `image_url` when passing in images.
    /// It is required that there must be one content part of type `text` at least. Multiple images are allowed by adding multiple image_url content parts.
    Parts(Vec<ContentPart>),
}
impl ChatCompletionUserMessageContent {
    pub fn ty(&self) -> &str {
        match self {
            ChatCompletionUserMessageContent::Text(_) => "text",
            ChatCompletionUserMessageContent::Parts(_) => "parts",
        }
    }
}

#[test]
fn test_chat_serialize_user_message_content() {
    let content = ChatCompletionUserMessageContent::Text("Hello, world!".to_string());
    let json = serde_json::to_string(&content).unwrap();
    assert_eq!(json, r#""Hello, world!""#);

    let content = ChatCompletionUserMessageContent::Parts(vec![
        ContentPart::Text(TextContentPart::new("Hello, world!")),
        ContentPart::Image(ImageContentPart::new(Image {
            url: "https://example.com/image.png".to_string(),
            detail: Some("auto".to_string()),
        })),
    ]);
    let json = serde_json::to_string(&content).unwrap();
    assert_eq!(
        json,
        r#"[{"type":"text","text":"Hello, world!"},{"type":"image_url","image_url":{"url":"https://example.com/image.png","detail":"auto"}}]"#
    );
}

#[test]
fn test_chat_deserialize_user_message_content() {
    let json = r#"[{"type":"text","text":"Hello, world!"},{"type":"image_url","image_url":{"url":"https://example.com/image.png","detail":"auto"}}]"#;
    let content: ChatCompletionUserMessageContent = serde_json::from_str(json).unwrap();
    assert_eq!(content.ty(), "parts");
    if let ChatCompletionUserMessageContent::Parts(parts) = content {
        assert_eq!(parts.len(), 2);
        assert_eq!(parts[0].ty(), "text");
        assert_eq!(parts[1].ty(), "image_url");
    }
}

/// Define the content part of a user message.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "lowercase")]
// #[serde(untagged)]
pub enum ContentPart {
    #[serde(rename = "text")]
    Text(TextContentPart),
    #[serde(rename = "image_url")]
    Image(ImageContentPart),
    #[serde(rename = "input_audio")]
    Audio(AudioContentPart),
}
impl ContentPart {
    pub fn ty(&self) -> &str {
        match self {
            ContentPart::Text(_) => "text",
            ContentPart::Image(_) => "image_url",
            ContentPart::Audio(_) => "input_audio",
        }
    }
}

#[test]
fn test_chat_serialize_content_part() {
    let text_content_part = TextContentPart::new("Hello, world!");
    let content_part = ContentPart::Text(text_content_part);
    let json = serde_json::to_string(&content_part).unwrap();
    assert_eq!(json, r#"{"type":"text","text":"Hello, world!"}"#);

    let image_content_part = ImageContentPart::new(Image {
        url: "https://example.com/image.png".to_string(),
        detail: Some("auto".to_string()),
    });
    let content_part = ContentPart::Image(image_content_part);
    let json = serde_json::to_string(&content_part).unwrap();
    assert_eq!(
        json,
        r#"{"type":"image_url","image_url":{"url":"https://example.com/image.png","detail":"auto"}}"#
    );

    let audio_content_part = AudioContentPart::new(Audio {
        data: "dummy-base64-encodings".to_string(),
        format: AudioFormat::Wav,
    });
    let content_part = ContentPart::Audio(audio_content_part);
    let json = serde_json::to_string(&content_part).unwrap();
    assert_eq!(
        json,
        r#"{"type":"input_audio","input_audio":{"data":"dummy-base64-encodings","format":"wav"}}"#
    );
}

#[test]
fn test_chat_deserialize_content_part() {
    let json = r#"{"type":"text","text":"Hello, world!"}"#;
    let content_part: ContentPart = serde_json::from_str(json).unwrap();
    assert_eq!(content_part.ty(), "text");

    let json = r#"{"type":"image_url","image_url":{"url":"https://example.com/image.png","detail":"auto"}}"#;
    let content_part: ContentPart = serde_json::from_str(json).unwrap();
    assert_eq!(content_part.ty(), "image_url");

    let json =
        r#"{"type":"input_audio","input_audio":{"data":"dummy-base64-encodings","format":"wav"}}"#;
    let content_part: ContentPart = serde_json::from_str(json).unwrap();
    assert_eq!(content_part.ty(), "input_audio");
}

/// Represents the text part of a user message content.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct TextContentPart {
    /// The text content.
    text: String,
}
impl TextContentPart {
    pub fn new(text: impl Into<String>) -> Self {
        Self { text: text.into() }
    }

    /// The text content.
    pub fn text(&self) -> &str {
        &self.text
    }
}

#[test]
fn test_chat_serialize_text_content_part() {
    let text_content_part = TextContentPart::new("Hello, world!");
    let json = serde_json::to_string(&text_content_part).unwrap();
    assert_eq!(json, r#"{"text":"Hello, world!"}"#);
}

#[test]
fn test_chat_deserialize_text_content_part() {
    let json = r#"{"type":"text","text":"Hello, world!"}"#;
    let text_content_part: TextContentPart = serde_json::from_str(json).unwrap();
    assert_eq!(text_content_part.text, "Hello, world!");
}

/// Represents the image part of a user message content.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct ImageContentPart {
    #[serde(rename = "image_url")]
    image: Image,
}
impl ImageContentPart {
    pub fn new(image: Image) -> Self {
        Self { image }
    }

    /// The image URL.
    pub fn image(&self) -> &Image {
        &self.image
    }
}

#[test]
fn test_chat_serialize_image_content_part() {
    let image_content_part = ImageContentPart::new(Image {
        url: "https://example.com/image.png".to_string(),
        detail: Some("auto".to_string()),
    });
    let json = serde_json::to_string(&image_content_part).unwrap();
    assert_eq!(
        json,
        r#"{"image_url":{"url":"https://example.com/image.png","detail":"auto"}}"#
    );

    let image_content_part = ImageContentPart::new(Image {
        url: "https://example.com/image.png".to_string(),
        detail: None,
    });
    let json = serde_json::to_string(&image_content_part).unwrap();
    assert_eq!(
        json,
        r#"{"image_url":{"url":"https://example.com/image.png"}}"#
    );

    let image_content_part = ImageContentPart::new(Image {
        url: "base64".to_string(),
        detail: Some("auto".to_string()),
    });
    let json = serde_json::to_string(&image_content_part).unwrap();
    assert_eq!(json, r#"{"image_url":{"url":"base64","detail":"auto"}}"#);

    let image_content_part = ImageContentPart::new(Image {
        url: "base64".to_string(),
        detail: None,
    });
    let json = serde_json::to_string(&image_content_part).unwrap();
    assert_eq!(json, r#"{"image_url":{"url":"base64"}}"#);
}

#[test]
fn test_chat_deserialize_image_content_part() {
    let json = r#"{"type":"image_url","image_url":{"url":"https://example.com/image.png","detail":"auto"}}"#;
    let image_content_part: ImageContentPart = serde_json::from_str(json).unwrap();
    // assert_eq!(image_content_part.ty, "image_url");
    assert_eq!(
        image_content_part.image.url,
        "https://example.com/image.png"
    );
    assert_eq!(image_content_part.image.detail, Some("auto".to_string()));
}

/// JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib)
/// PNG 1/2/4/8/16-bit-per-channel
///
/// TGA (not sure what subset, if a subset)
/// BMP non-1bpp, non-RLE
/// PSD (composited view only, no extra channels, 8/16 bit-per-channel)
///
/// GIF (*comp always reports as 4-channel)
/// HDR (radiance rgbE format)
/// PIC (Softimage PIC)
/// PNM (PPM and PGM binary only)
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
pub struct Image {
    /// Either a URL of the image or the base64 encoded image data.
    pub url: String,
    /// Specifies the detail level of the image. Defaults to auto.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}
impl Image {
    pub fn is_url(&self) -> bool {
        url::Url::parse(&self.url).is_ok()
    }
}

#[test]
fn test_chat_serialize_image() {
    let image = Image {
        url: "https://example.com/image.png".to_string(),
        detail: Some("auto".to_string()),
    };
    let json = serde_json::to_string(&image).unwrap();
    assert_eq!(
        json,
        r#"{"url":"https://example.com/image.png","detail":"auto"}"#
    );

    let image = Image {
        url: "https://example.com/image.png".to_string(),
        detail: None,
    };
    let json = serde_json::to_string(&image).unwrap();
    assert_eq!(json, r#"{"url":"https://example.com/image.png"}"#);

    let image = Image {
        url: "base64".to_string(),
        detail: Some("auto".to_string()),
    };
    let json = serde_json::to_string(&image).unwrap();
    assert_eq!(json, r#"{"url":"base64","detail":"auto"}"#);

    let image = Image {
        url: "base64".to_string(),
        detail: None,
    };
    let json = serde_json::to_string(&image).unwrap();
    assert_eq!(json, r#"{"url":"base64"}"#);
}

#[test]
fn test_chat_deserialize_image() {
    let json = r#"{"url":"https://example.com/image.png","detail":"auto"}"#;
    let image: Image = serde_json::from_str(json).unwrap();
    assert_eq!(image.url, "https://example.com/image.png");
    assert_eq!(image.detail, Some("auto".to_string()));

    let json = r#"{"url":"https://example.com/image.png"}"#;
    let image: Image = serde_json::from_str(json).unwrap();
    assert_eq!(image.url, "https://example.com/image.png");
    assert_eq!(image.detail, None);

    let json = r#"{"url":"base64","detail":"auto"}"#;
    let image: Image = serde_json::from_str(json).unwrap();
    assert_eq!(image.url, "base64");
    assert_eq!(image.detail, Some("auto".to_string()));

    let json = r#"{"url":"base64"}"#;
    let image: Image = serde_json::from_str(json).unwrap();
    assert_eq!(image.url, "base64");
    assert_eq!(image.detail, None);
}

/// Represents the audio part of a user message content.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
pub struct AudioContentPart {
    #[serde(rename = "input_audio")]
    audio: Audio,
}
impl AudioContentPart {
    pub fn new(audio: Audio) -> Self {
        Self { audio }
    }

    /// The audio data.
    pub fn audio(&self) -> &Audio {
        &self.audio
    }
}

#[test]
fn test_chat_serialize_audio_content_part() {
    let audio_content_part = AudioContentPart {
        audio: Audio {
            data: "dummy-base64-encodings".to_string(),
            format: AudioFormat::Wav,
        },
    };
    let json = serde_json::to_string(&audio_content_part).unwrap();
    assert_eq!(
        json,
        r#"{"input_audio":{"data":"dummy-base64-encodings","format":"wav"}}"#
    );

    let audio_content_part = AudioContentPart {
        audio: Audio {
            data: "dummy-base64-encodings".to_string(),
            format: AudioFormat::Mp3,
        },
    };
    let json = serde_json::to_string(&audio_content_part).unwrap();
    assert_eq!(
        json,
        r#"{"input_audio":{"data":"dummy-base64-encodings","format":"mp3"}}"#
    );
}

#[test]
fn test_chat_deserialize_audio_content_part() {
    let json = r#"{"input_audio":{"data":"dummy-base64-encodings","format":"wav"}}"#;
    let audio_content_part: AudioContentPart = serde_json::from_str(json).unwrap();
    assert_eq!(audio_content_part.audio.data, "dummy-base64-encodings");
    assert_eq!(audio_content_part.audio.format, AudioFormat::Wav);

    let json = r#"{"input_audio":{"data":"dummy-base64-encodings","format":"mp3"}}"#;
    let audio_content_part: AudioContentPart = serde_json::from_str(json).unwrap();
    assert_eq!(audio_content_part.audio.data, "dummy-base64-encodings");
    assert_eq!(audio_content_part.audio.format, AudioFormat::Mp3);
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
pub struct Audio {
    /// Base64 encoded audio data.
    pub data: String,
    /// The format of the encoded audio data.
    pub format: AudioFormat,
}

/// The format of the encoded audio data.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum AudioFormat {
    Wav,
    Mp3,
}

#[test]
fn test_chat_serialize_audio() {
    let audio = Audio {
        data: "dummy-base64-encodings".to_string(),
        format: AudioFormat::Wav,
    };
    let json = serde_json::to_string(&audio).unwrap();
    assert_eq!(json, r#"{"data":"dummy-base64-encodings","format":"wav"}"#);

    let audio = Audio {
        data: "dummy-base64-encodings".to_string(),
        format: AudioFormat::Mp3,
    };
    let json = serde_json::to_string(&audio).unwrap();
    assert_eq!(json, r#"{"data":"dummy-base64-encodings","format":"mp3"}"#);
}

#[test]
fn test_chat_deserialize_audio() {
    let json = r#"{"data":"dummy-base64-encodings","format":"wav"}"#;
    let audio: Audio = serde_json::from_str(json).unwrap();
    assert_eq!(audio.data, "dummy-base64-encodings");
    assert_eq!(audio.format, AudioFormat::Wav);

    let json = r#"{"data":"dummy-base64-encodings","format":"mp3"}"#;
    let audio: Audio = serde_json::from_str(json).unwrap();
    assert_eq!(audio.data, "dummy-base64-encodings");
    assert_eq!(audio.format, AudioFormat::Mp3);
}

/// Sampling methods used for chat completion requests.
#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq)]
pub enum ChatCompletionRequestSampling {
    /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
    Temperature(f64),
    /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.
    TopP(f64),
}

/// The role of the messages author.
#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ChatCompletionRole {
    System,
    Developer,
    User,
    Assistant,
    /// **Deprecated since 0.10.0.** Use [ChatCompletionRole::Tool] instead.
    Function,
    Tool,
}
impl std::fmt::Display for ChatCompletionRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ChatCompletionRole::System => write!(f, "system"),
            ChatCompletionRole::Developer => write!(f, "developer"),
            ChatCompletionRole::User => write!(f, "user"),
            ChatCompletionRole::Assistant => write!(f, "assistant"),
            ChatCompletionRole::Function => write!(f, "function"),
            ChatCompletionRole::Tool => write!(f, "tool"),
        }
    }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct ChatCompletionRequestFunction {
    name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    parameters: ChatCompletionRequestFunctionParameters,
}

/// The parameters the functions accepts, described as a JSON Schema object.
///
/// See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format.
///
/// To describe a function that accepts no parameters, provide the value
/// `{"type": "object", "properties": {}}`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ChatCompletionRequestFunctionParameters {
    #[serde(rename = "type")]
    pub schema_type: JSONSchemaType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<HashMap<String, Box<JSONSchemaDefine>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<Vec<String>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum JSONSchemaType {
    Object,
    Number,
    Integer,
    String,
    Array,
    Null,
    Boolean,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JSONSchemaDefine {
    #[serde(rename = "type")]
    pub schema_type: Option<JSONSchemaType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
    pub enum_values: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<HashMap<String, Box<JSONSchemaDefine>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub items: Option<Box<JSONSchemaDefine>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub maximum: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub minimum: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub examples: Option<Vec<Value>>,
}

/// Represents a chat completion response returned by model, based on the provided input.
#[derive(Debug, Deserialize, Serialize)]
pub struct ChatCompletionObject {
    /// A unique identifier for the chat completion.
    pub id: String,
    /// The object type, which is always `chat.completion`.
    pub object: String,
    /// The Unix timestamp (in seconds) of when the chat completion was created.
    pub created: u64,
    /// The model used for the chat completion.
    pub model: String,
    /// A list of chat completion choices. Can be more than one if `n_choice` is greater than 1.
    pub choices: Vec<ChatCompletionObjectChoice>,
    /// Usage statistics for the completion request.
    pub usage: Usage,
}

#[test]
fn test_deserialize_chat_completion_object() {
    let json = r#"{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1699896916,
  "model": "gpt-3.5-turbo-0125",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_abc123",
            "type": "function",
            "function": {
              "name": "get_current_weather",
              "arguments": "{\n\"location\": \"Boston, MA\"\n}"
            }
          }
        ]
      },
      "logprobs": null,
      "finish_reason": "tool_calls"
    }
  ],
  "usage": {
    "prompt_tokens": 82,
    "completion_tokens": 17,
    "total_tokens": 99
  }
}"#;

    let chatcmp_object: ChatCompletionObject = serde_json::from_str(json).unwrap();
    assert_eq!(chatcmp_object.id, "chatcmpl-abc123");
    assert_eq!(chatcmp_object.object, "chat.completion");
    assert_eq!(chatcmp_object.created, 1699896916);
    assert_eq!(chatcmp_object.model, "gpt-3.5-turbo-0125");
    assert_eq!(chatcmp_object.choices.len(), 1);
    assert_eq!(chatcmp_object.choices[0].index, 0);
    assert_eq!(
        chatcmp_object.choices[0].finish_reason,
        FinishReason::tool_calls
    );
    assert_eq!(chatcmp_object.choices[0].message.tool_calls.len(), 1);
    assert_eq!(
        chatcmp_object.choices[0].message.tool_calls[0].id,
        "call_abc123"
    );
    assert_eq!(
        chatcmp_object.choices[0].message.tool_calls[0].ty,
        "function"
    );
    assert_eq!(
        chatcmp_object.choices[0].message.tool_calls[0]
            .function
            .name,
        "get_current_weather"
    );
    assert_eq!(
        chatcmp_object.choices[0].message.tool_calls[0]
            .function
            .arguments,
        "{\n\"location\": \"Boston, MA\"\n}"
    );
    assert_eq!(chatcmp_object.usage.prompt_tokens, 82);
    assert_eq!(chatcmp_object.usage.completion_tokens, 17);
    assert_eq!(chatcmp_object.usage.total_tokens, 99);
}

/// Represents a chat completion choice returned by model.
#[derive(Debug, Deserialize, Serialize)]
pub struct ChatCompletionObjectChoice {
    /// The index of the choice in the list of choices.
    pub index: u32,
    /// A chat completion message generated by the model.
    pub message: ChatCompletionObjectMessage,
    /// The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, or `function_call` if the model called a function.
    pub finish_reason: FinishReason,
    /// Log probability information for the choice.
    pub logprobs: Option<LogProbs>,
}

#[test]
fn test_serialize_chat_completion_object_choice() {
    let tool = ToolCall {
        id: "call_abc123".to_string(),
        ty: "function".to_string(),
        function: Function {
            name: "get_current_weather".to_string(),
            arguments: "{\"location\": \"Boston, MA\"}".to_string(),
        },
    };
    let message = ChatCompletionObjectMessage {
        content: None,
        tool_calls: vec![tool],
        role: ChatCompletionRole::Assistant,
        function_call: None,
    };
    let choice = ChatCompletionObjectChoice {
        index: 0,
        message,
        finish_reason: FinishReason::tool_calls,
        logprobs: None,
    };
    let json = serde_json::to_string(&choice).unwrap();
    assert_eq!(
        json,
        r#"{"index":0,"message":{"content":null,"tool_calls":[{"id":"call_abc123","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"Boston, MA\"}"}}],"role":"assistant"},"finish_reason":"tool_calls","logprobs":null}"#
    );
}

/// Log probability information for the choice.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct LogProbs {
    pub content: Vec<LogProb>,
    pub refusal: Vec<LogProb>,
}

/// Log probability information for the choice.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct LogProb {
    /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token.
    pub bytes: Option<Vec<u8>>,
    /// The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0`` is used to signify that the token is very unlikely.
    pub logprob: f64,
    /// The token.
    pub token: String,
    /// List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned.
    pub top_logprobs: Vec<TopLogProb>,
}

/// Represents the top log probabilities for tokens.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TopLogProb {
    /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token.
    pub bytes: Option<Vec<u8>>,
    /// The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely.
    pub logprob: f64,
    /// The token.
    pub token: String,
}

/// Represents a chat completion message generated by the model.
#[derive(Debug, Serialize)]
pub struct ChatCompletionObjectMessage {
    /// The contents of the message.
    pub content: Option<String>,
    /// The tool calls generated by the model, such as function calls.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tool_calls: Vec<ToolCall>,
    /// The role of the author of this message.
    pub role: ChatCompletionRole,
    /// Deprecated. The name and arguments of a function that should be called, as generated by the model.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub function_call: Option<ChatMessageFunctionCall>,
}
impl<'de> Deserialize<'de> for ChatCompletionObjectMessage {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ChatCompletionObjectMessageVisitor;

        impl<'de> Visitor<'de> for ChatCompletionObjectMessageVisitor {
            type Value = ChatCompletionObjectMessage;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct ChatCompletionObjectMessage")
            }

            fn visit_map<V>(self, mut map: V) -> Result<ChatCompletionObjectMessage, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut content = None;
                let mut tool_calls = None;
                let mut role = None;
                let mut function_call = None;

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "content" => content = map.next_value()?,
                        "tool_calls" => tool_calls = map.next_value()?,
                        "role" => role = map.next_value()?,
                        "function_call" => function_call = map.next_value()?,
                        _ => {
                            // Ignore unknown fields
                            let _ = map.next_value::<IgnoredAny>()?;

                            #[cfg(feature = "logging")]
                            warn!(target: "stdout", "Not supported field: {key}");
                        }
                    }
                }

                let content = content;
                let tool_calls = tool_calls.unwrap_or_default();
                let role = role.ok_or_else(|| de::Error::missing_field("role"))?;
                let function_call = function_call;

                Ok(ChatCompletionObjectMessage {
                    content,
                    tool_calls,
                    role,
                    function_call,
                })
            }
        }

        const FIELDS: &[&str] = &["content", "tool_calls", "role", "function_call"];
        deserializer.deserialize_struct(
            "ChatCompletionObjectMessage",
            FIELDS,
            ChatCompletionObjectMessageVisitor,
        )
    }
}

#[test]
fn test_serialize_chat_completion_object_message() {
    let tool = ToolCall {
        id: "call_abc123".to_string(),
        ty: "function".to_string(),
        function: Function {
            name: "get_current_weather".to_string(),
            arguments: "{\"location\": \"Boston, MA\"}".to_string(),
        },
    };
    let message = ChatCompletionObjectMessage {
        content: None,
        tool_calls: vec![tool],
        role: ChatCompletionRole::Assistant,
        function_call: None,
    };
    let json = serde_json::to_string(&message).unwrap();
    assert_eq!(
        json,
        r#"{"content":null,"tool_calls":[{"id":"call_abc123","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"Boston, MA\"}"}}],"role":"assistant"}"#
    );
}

#[test]
fn test_deserialize_chat_completion_object_message() {
    {
        let json = r#"{"content":null,"tool_calls":[{"id":"call_abc123","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"Boston, MA\"}"}}],"role":"assistant"}"#;
        let message: ChatCompletionObjectMessage = serde_json::from_str(json).unwrap();
        assert_eq!(message.content, None);
        assert_eq!(message.tool_calls.len(), 1);
        assert_eq!(message.role, ChatCompletionRole::Assistant);
    }

    {
        let json = r#"{"content":null,"role":"assistant"}"#;
        let message: ChatCompletionObjectMessage = serde_json::from_str(json).unwrap();
        assert_eq!(message.content, None);
        assert!(message.tool_calls.is_empty());
        assert_eq!(message.role, ChatCompletionRole::Assistant);
    }
}

/// The name and arguments of a function that should be called, as generated by the model.
#[derive(Debug, Deserialize, Serialize)]
pub struct ChatMessageFunctionCall {
    /// The name of the function to call.
    pub name: String,

    /// The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.
    pub arguments: String,
}

/// Represents a streamed chunk of a chat completion response returned by model, based on the provided input.
#[derive(Debug, Deserialize, Serialize)]
pub struct ChatCompletionChunk {
    /// A unique identifier for the chat completion.
    pub id: String,
    /// A list of chat completion choices. Can be more than one if `n_choice` is greater than 1.
    pub choices: Vec<ChatCompletionChunkChoice>,
    /// The Unix timestamp (in seconds) of when the chat completion was created.
    pub created: u64,
    /// The model used for the chat completion.
    pub model: String,
    /// This fingerprint represents the backend configuration that the model runs with. Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.
    pub system_fingerprint: String,
    /// The object type, which is always `chat.completion.chunk`.
    pub object: String,
    /// Usage statistics for the completion request.
    ///
    /// An optional field that will only be present when you set stream_options: {"include_usage": true} in your request. When present, it contains a null value except for the last chunk which contains the token usage statistics for the entire request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<Usage>,
}

#[test]
fn test_serialize_chat_completion_chunk() {
    let chunk = ChatCompletionChunk {
        id: "chatcmpl-1d0ff773-e8ab-4254-a222-96e97e3c295a".to_string(),
        choices: vec![ChatCompletionChunkChoice {
            index: 0,
            delta: ChatCompletionChunkChoiceDelta {
                content: Some(".".to_owned()),
                tool_calls: vec![],
                role: ChatCompletionRole::Assistant,
            },
            logprobs: None,
            finish_reason: None,
        }],
        created: 1722433423,
        model: "default".to_string(),
        system_fingerprint: "fp_44709d6fcb".to_string(),
        object: "chat.completion.chunk".to_string(),
        usage: None,
    };

    let json = serde_json::to_string(&chunk).unwrap();
    assert_eq!(
        json,
        r#"{"id":"chatcmpl-1d0ff773-e8ab-4254-a222-96e97e3c295a","choices":[{"index":0,"delta":{"content":".","role":"assistant"},"logprobs":null,"finish_reason":null}],"created":1722433423,"model":"default","system_fingerprint":"fp_44709d6fcb","object":"chat.completion.chunk"}"#
    );
}

#[test]
fn test_deserialize_chat_completion_chunk() {
    {
        let json = r#"{"id":"chatcmpl-1d0ff773-e8ab-4254-a222-96e97e3c295a","choices":[{"index":0,"delta":{"content":".","role":"assistant"},"logprobs":null,"finish_reason":null}],"created":1722433423,"model":"default","system_fingerprint":"fp_44709d6fcb","object":"chat.completion.chunk"}"#;

        let chunk: ChatCompletionChunk = serde_json::from_str(json).unwrap();
        assert_eq!(chunk.id, "chatcmpl-1d0ff773-e8ab-4254-a222-96e97e3c295a");
        assert_eq!(chunk.choices.len(), 1);
        assert_eq!(chunk.choices[0].index, 0);
        assert_eq!(chunk.choices[0].delta.content, Some(".".to_owned()));
        assert!(chunk.choices[0].delta.tool_calls.is_empty());
        assert_eq!(chunk.choices[0].delta.role, ChatCompletionRole::Assistant);
        assert_eq!(chunk.created, 1722433423);
        assert_eq!(chunk.model, "default");
        assert_eq!(chunk.system_fingerprint, "fp_44709d6fcb");
        assert_eq!(chunk.object, "chat.completion.chunk");
    }

    {
        let json_str = r#"{"id":"chatcmpl-5b20a5a9-80e0-4cc4-9d33-7ab504dac9ca","choices":[{"index":0,"delta":{"content":null,"tool_calls":[{"index":0,"id":"call_abc123","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\":\"Beijing\",\"unit\":\"celsius\"}"}}],"role":"assistant"},"logprobs":null,"finish_reason":null}],"created":1744028716,"model":"Llama-3-Groq-8B","system_fingerprint":"fp_44709d6fcb","object":"chat.completion.chunk"}"#;

        let chunk: ChatCompletionChunk = serde_json::from_str(json_str).unwrap();
        assert_eq!(chunk.id, "chatcmpl-5b20a5a9-80e0-4cc4-9d33-7ab504dac9ca");
        assert_eq!(chunk.choices.len(), 1);
        assert_eq!(chunk.choices[0].index, 0);
        assert_eq!(chunk.choices[0].delta.content, None);
        assert_eq!(chunk.choices[0].delta.tool_calls.len(), 1);
    }
}

/// Represents a chat completion choice in a streamed chunk of a chat completion response.
#[derive(Debug, Deserialize, Serialize)]
pub struct ChatCompletionChunkChoice {
    /// The index of the choice in the list of choices.
    pub index: u32,
    /// A chat completion delta generated by streamed model responses.
    pub delta: ChatCompletionChunkChoiceDelta,
    /// Log probability information for the choice.
    pub logprobs: Option<LogProbs>,
    /// The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, or `function_call` if the model called a function.
    pub finish_reason: Option<FinishReason>,
}

/// Represents a chat completion delta generated by streamed model responses.
#[derive(Debug, Serialize)]
pub struct ChatCompletionChunkChoiceDelta {
    /// The contents of the chunk message.
    pub content: Option<String>,
    /// The name and arguments of a function that should be called, as generated by the model.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tool_calls: Vec<ToolCallForChunk>,
    /// The role of the author of this message.
    pub role: ChatCompletionRole,
}
impl<'de> Deserialize<'de> for ChatCompletionChunkChoiceDelta {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ChatCompletionChunkChoiceDeltaVisitor;

        impl<'de> Visitor<'de> for ChatCompletionChunkChoiceDeltaVisitor {
            type Value = ChatCompletionChunkChoiceDelta;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct ChatCompletionChunkChoiceDelta")
            }

            fn visit_map<V>(self, mut map: V) -> Result<ChatCompletionChunkChoiceDelta, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut content = None;
                let mut tool_calls = None;
                let mut role = None;

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "content" => content = map.next_value()?,
                        "tool_calls" => tool_calls = map.next_value()?,
                        "role" => role = map.next_value()?,
                        _ => {
                            // Ignore unknown fields
                            let _ = map.next_value::<IgnoredAny>()?;

                            #[cfg(feature = "logging")]
                            warn!(target: "stdout", "Not supported field: {key}");
                        }
                    }
                }

                let content = content;
                let tool_calls = tool_calls.unwrap_or_default();
                let role = role.ok_or_else(|| de::Error::missing_field("role"))?;
                Ok(ChatCompletionChunkChoiceDelta {
                    content,
                    tool_calls,
                    role,
                })
            }
        }

        const FIELDS: &[&str] = &["content", "tool_calls", "role"];
        deserializer.deserialize_struct(
            "ChatCompletionChunkChoiceDelta",
            FIELDS,
            ChatCompletionChunkChoiceDeltaVisitor,
        )
    }
}