linger-openai-sdk 0.1.1

Rust-native async SDK for OpenAI APIs with typed requests, streaming, uploads, retries, and pluggable transports.
Documentation
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
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
use crate::error::LingerError;
use crate::stream::{SseEvent, SseStream};
use crate::transport::BodyStream;
use crate::RequestId;
use futures_core::Stream;
use serde::ser::SerializeStruct;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;
use std::pin::Pin;
use std::task::{Context, Poll};

/// EN: Request body for `POST /v1/responses`.
/// 中文:`POST /v1/responses` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateResponseRequest {
    /// EN: Model id used to generate the response.
    /// 中文:用于生成响应的模型 ID。
    pub model: String,
    /// EN: Input text or message list.
    /// 中文:输入文本或消息列表。
    pub input: ResponseInput,
    /// EN: Optional system or developer instructions for this response.
    /// 中文:此响应可选的系统或开发者指令。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instructions: Option<String>,
    /// EN: Optional model-owned style preset to apply to this response.
    /// 中文:应用于此响应的可选模型自有风格预设。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub personality: Option<String>,
    /// EN: Optional previous response id for multi-turn conversation state.
    /// 中文:用于多轮会话状态的可选上一条响应 ID。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub previous_response_id: Option<String>,
    /// EN: Optional conversation this response should belong to.
    /// 中文:此响应应归属的可选 conversation。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub conversation: Option<ResponseConversation>,
    /// EN: Optional context management entries for this response request.
    /// 中文:此响应请求的可选上下文管理条目。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_management: Option<Vec<ResponseContextManagement>>,
    /// EN: Optional moderation configuration for this response request.
    /// 中文:此响应请求的可选 moderation 配置。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub moderation: Option<ResponseModeration>,
    /// EN: Optional tools the model may call while generating the response.
    /// 中文:模型生成响应时可以调用的可选工具列表。
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tools: Vec<Value>,
    /// EN: Optional mode controlling whether the model may call tools.
    /// 中文:控制模型是否可以调用工具的可选模式。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<ResponseToolChoice>,
    /// EN: Optional reusable prompt template reference and variables.
    /// 中文:可选的可复用 prompt 模板引用及变量。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt: Option<ResponsePrompt>,
    /// EN: Optional upper bound for generated output tokens.
    /// 中文:生成输出 token 数量的可选上限。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_output_tokens: Option<u32>,
    /// EN: Whether to store the generated response for later retrieval.
    /// 中文:是否存储生成的响应以便稍后检索。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub store: Option<bool>,
    /// EN: Whether to run the model response in the background.
    /// 中文:是否在后台运行模型响应。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub background: Option<bool>,
    /// EN: Optional maximum number of built-in tool calls for the response.
    /// 中文:响应中内置工具调用总次数的可选上限。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tool_calls: Option<u32>,
    /// EN: Optional metadata attached to the generated response.
    /// 中文:附加到生成响应的可选元数据。
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub metadata: BTreeMap<String, String>,
    /// EN: Whether to allow tool calls to run in parallel.
    /// 中文:是否允许并行运行工具调用。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parallel_tool_calls: Option<bool>,
    /// EN: Optional sampling temperature.
    /// 中文:可选的采样温度。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f64>,
    /// EN: Optional nucleus sampling value.
    /// 中文:可选的 nucleus sampling 值。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f64>,
    /// EN: Optional maximum number of top token log probabilities to return.
    /// 中文:可选的每个 token 位置返回的最高概率 token log probability 数量。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_logprobs: Option<u8>,
    /// EN: Optional reasoning configuration for reasoning-capable models.
    /// 中文:支持推理模型的可选推理配置。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<ResponseReasoning>,
    /// EN: Optional context truncation strategy for the response.
    /// 中文:响应可选的上下文截断策略。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub truncation: Option<ResponseTruncation>,
    /// EN: Optional prompt cache bucketing key for similar requests.
    /// 中文:用于相似请求提示缓存分桶的可选键。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt_cache_key: Option<String>,
    /// EN: Optional retention policy for prompt cache entries created by this request.
    /// 中文:此请求创建的提示缓存条目的可选保留策略。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt_cache_retention: Option<ResponsePromptCacheRetention>,
    /// EN: Optional stable safety identifier for abuse detection.
    /// 中文:用于滥用检测的可选稳定安全标识符。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub safety_identifier: Option<String>,
    /// EN: Optional processing tier for serving the response request.
    /// 中文:用于处理响应请求的可选服务层级。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_tier: Option<ResponseServiceTier>,
    /// EN: Optional additional output data to include in the model response.
    /// 中文:要包含在模型响应中的可选额外输出数据。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include: Option<Vec<ResponseInclude>>,
    /// EN: Optional text generation configuration.
    /// 中文:可选的文本生成配置。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<ResponseTextConfig>,
    /// EN: Optional streaming configuration used when streaming a response.
    /// 中文:流式响应时使用的可选流配置。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream_options: Option<StreamOptions>,
    /// EN: Optional stream flag set by streaming convenience methods.
    /// 中文:由流式便捷方法设置的可选 stream 标志。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,
    /// EN: Forward-compatible optional fields not yet covered by handwritten types.
    /// 中文:手写类型尚未覆盖的前向兼容可选字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl CreateResponseRequest {
    /// EN: Starts building a create-response request.
    /// 中文:开始构建创建响应请求。
    pub fn builder() -> CreateResponseRequestBuilder {
        CreateResponseRequestBuilder::default()
    }

    pub(crate) fn into_streaming(mut self) -> Self {
        self.stream = Some(true);
        self
    }
}

/// EN: Builder for create-response requests.
/// 中文:创建响应请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateResponseRequestBuilder {
    model: Option<String>,
    input: Option<ResponseInput>,
    instructions: Option<String>,
    personality: Option<String>,
    previous_response_id: Option<String>,
    conversation: Option<ResponseConversation>,
    context_management: Option<Vec<ResponseContextManagement>>,
    moderation: Option<ResponseModeration>,
    tools: Vec<Value>,
    tool_choice: Option<ResponseToolChoice>,
    prompt: Option<ResponsePrompt>,
    max_output_tokens: Option<u32>,
    store: Option<bool>,
    background: Option<bool>,
    max_tool_calls: Option<u32>,
    metadata: BTreeMap<String, String>,
    parallel_tool_calls: Option<bool>,
    temperature: Option<f64>,
    top_p: Option<f64>,
    top_logprobs: Option<u8>,
    reasoning: Option<ResponseReasoning>,
    truncation: Option<ResponseTruncation>,
    prompt_cache_key: Option<String>,
    prompt_cache_retention: Option<ResponsePromptCacheRetention>,
    safety_identifier: Option<String>,
    service_tier: Option<ResponseServiceTier>,
    include: Option<Vec<ResponseInclude>>,
    text: Option<ResponseTextConfig>,
    stream_options: Option<StreamOptions>,
    extra: BTreeMap<String, Value>,
}

impl CreateResponseRequestBuilder {
    /// EN: Sets the model id.
    /// 中文:设置模型 ID。
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// EN: Sets the request input.
    /// 中文:设置请求输入。
    pub fn input(mut self, input: impl Into<ResponseInput>) -> Self {
        self.input = Some(input.into());
        self
    }

    /// EN: Sets system or developer instructions for this response.
    /// 中文:设置此响应的系统或开发者指令。
    pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
        self.instructions = Some(instructions.into());
        self
    }

    /// EN: Sets the model-owned style preset for this response.
    /// 中文:设置此响应的模型自有风格预设。
    pub fn personality(mut self, personality: impl Into<String>) -> Self {
        self.personality = Some(personality.into());
        self
    }

    /// EN: Sets the previous response id for multi-turn conversation state.
    /// 中文:设置用于多轮会话状态的上一条响应 ID。
    pub fn previous_response_id(mut self, previous_response_id: impl Into<String>) -> Self {
        self.previous_response_id = Some(previous_response_id.into());
        self
    }

    /// EN: Sets the conversation this response should belong to.
    /// 中文:设置此响应应归属的 conversation。
    pub fn conversation(mut self, conversation: impl Into<ResponseConversation>) -> Self {
        self.conversation = Some(conversation.into());
        self
    }

    /// EN: Sets context management entries for this response request.
    /// 中文:设置此响应请求的上下文管理条目。
    pub fn context_management<I>(mut self, context_management: I) -> Self
    where
        I: IntoIterator<Item = ResponseContextManagement>,
    {
        self.context_management = Some(context_management.into_iter().collect());
        self
    }

    /// EN: Sets moderation configuration for this response request.
    /// 中文:设置此响应请求的 moderation 配置。
    pub fn moderation(mut self, moderation: ResponseModeration) -> Self {
        self.moderation = Some(moderation);
        self
    }

    /// EN: Sets the tools the model may call while generating the response.
    /// 中文:设置模型生成响应时可以调用的工具列表。
    pub fn tools<T>(mut self, tools: impl IntoIterator<Item = T>) -> Self
    where
        T: Into<ResponseTool>,
    {
        self.tools = tools
            .into_iter()
            .map(|tool| tool.into().into_value())
            .collect();
        self
    }

    /// EN: Adds one tool the model may call while generating the response.
    /// 中文:添加一个模型生成响应时可以调用的工具。
    pub fn tool(mut self, tool: impl Into<ResponseTool>) -> Self {
        self.tools.push(tool.into().into_value());
        self
    }

    /// EN: Sets how the model should select tools while generating the response.
    /// 中文:设置模型生成响应时应如何选择工具。
    pub fn tool_choice(mut self, tool_choice: ResponseToolChoice) -> Self {
        self.tool_choice = Some(tool_choice);
        self
    }

    /// EN: Sets the reusable prompt template reference for this response.
    /// 中文:设置此响应使用的可复用 prompt 模板引用。
    pub fn prompt(mut self, prompt: ResponsePrompt) -> Self {
        self.prompt = Some(prompt);
        self
    }

    /// EN: Sets the upper bound for generated output tokens.
    /// 中文:设置生成输出 token 数量的上限。
    pub fn max_output_tokens(mut self, max_output_tokens: u32) -> Self {
        self.max_output_tokens = Some(max_output_tokens);
        self
    }

    /// EN: Sets whether the generated response is stored for later retrieval.
    /// 中文:设置是否存储生成的响应以便稍后检索。
    pub fn store(mut self, store: bool) -> Self {
        self.store = Some(store);
        self
    }

    /// EN: Sets whether the response should run in the background.
    /// 中文:设置响应是否应在后台运行。
    pub fn background(mut self, background: bool) -> Self {
        self.background = Some(background);
        self
    }

    /// EN: Sets the maximum number of built-in tool calls for the response.
    /// 中文:设置响应中内置工具调用总次数上限。
    pub fn max_tool_calls(mut self, max_tool_calls: u32) -> Self {
        self.max_tool_calls = Some(max_tool_calls);
        self
    }

    /// EN: Adds a metadata key/value pair.
    /// 中文:添加一个元数据键值对。
    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// EN: Sets whether tool calls may run in parallel.
    /// 中文:设置是否允许工具调用并行运行。
    pub fn parallel_tool_calls(mut self, parallel_tool_calls: bool) -> Self {
        self.parallel_tool_calls = Some(parallel_tool_calls);
        self
    }

    /// EN: Sets the sampling temperature.
    /// 中文:设置采样温度。
    pub fn temperature(mut self, temperature: f64) -> Self {
        self.temperature = Some(temperature);
        self
    }

    /// EN: Sets the nucleus sampling value.
    /// 中文:设置 nucleus sampling 值。
    pub fn top_p(mut self, top_p: f64) -> Self {
        self.top_p = Some(top_p);
        self
    }

    /// EN: Sets the maximum number of top token log probabilities to return.
    /// 中文:设置每个 token 位置返回的最高概率 token log probability 数量。
    pub fn top_logprobs(mut self, top_logprobs: u8) -> Self {
        self.top_logprobs = Some(top_logprobs);
        self
    }

    /// EN: Sets reasoning configuration for reasoning-capable models.
    /// 中文:设置支持推理模型的推理配置。
    pub fn reasoning(mut self, reasoning: ResponseReasoning) -> Self {
        self.reasoning = Some(reasoning);
        self
    }

    /// EN: Sets the context truncation strategy for the response.
    /// 中文:设置响应的上下文截断策略。
    pub fn truncation(mut self, truncation: ResponseTruncation) -> Self {
        self.truncation = Some(truncation);
        self
    }

    /// EN: Sets the prompt cache bucketing key for similar requests.
    /// 中文:设置用于相似请求提示缓存分桶的键。
    pub fn prompt_cache_key(mut self, prompt_cache_key: impl Into<String>) -> Self {
        self.prompt_cache_key = Some(prompt_cache_key.into());
        self
    }

    /// EN: Sets the prompt cache retention policy for this request.
    /// 中文:设置此请求的提示缓存保留策略。
    pub fn prompt_cache_retention(
        mut self,
        prompt_cache_retention: ResponsePromptCacheRetention,
    ) -> Self {
        self.prompt_cache_retention = Some(prompt_cache_retention);
        self
    }

    /// EN: Sets the stable safety identifier for abuse detection.
    /// 中文:设置用于滥用检测的稳定安全标识符。
    pub fn safety_identifier(mut self, safety_identifier: impl Into<String>) -> Self {
        self.safety_identifier = Some(safety_identifier.into());
        self
    }

    /// EN: Sets the service tier used to serve the response request.
    /// 中文:设置用于处理响应请求的服务层级。
    pub fn service_tier(mut self, service_tier: ResponseServiceTier) -> Self {
        self.service_tier = Some(service_tier);
        self
    }

    /// EN: Sets additional output data to include in the model response.
    /// 中文:设置要包含在模型响应中的额外输出数据。
    pub fn include<I>(mut self, include: I) -> Self
    where
        I: IntoIterator<Item = ResponseInclude>,
    {
        self.include = Some(include.into_iter().collect());
        self
    }

    /// EN: Sets text generation configuration.
    /// 中文:设置文本生成配置。
    pub fn text(mut self, text: ResponseTextConfig) -> Self {
        self.text = Some(text);
        self
    }

    /// EN: Sets streaming options for a request that will be sent with streaming enabled.
    /// 中文:设置将在启用流式传输时发送的请求流选项。
    pub fn stream_options(mut self, stream_options: StreamOptions) -> Self {
        self.stream_options = Some(stream_options);
        self
    }

    /// EN: Adds a forward-compatible JSON field.
    /// 中文:添加前向兼容的 JSON 字段。
    pub fn extra(mut self, name: impl Into<String>, value: Value) -> Self {
        self.extra.insert(name.into(), value);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateResponseRequest, LingerError> {
        let model = self
            .model
            .filter(|value| !value.trim().is_empty())
            .ok_or_else(|| LingerError::invalid_config("model is required"))?;
        let input = self
            .input
            .ok_or_else(|| LingerError::invalid_config("input is required"))?;
        if self
            .max_output_tokens
            .is_some_and(|max_output_tokens| max_output_tokens < 16)
        {
            return Err(LingerError::invalid_config(
                "max_output_tokens must be at least 16",
            ));
        }
        if self
            .temperature
            .is_some_and(|temperature| !(0.0..=2.0).contains(&temperature))
        {
            return Err(LingerError::invalid_config(
                "temperature must be between 0.0 and 2.0",
            ));
        }
        if self
            .top_p
            .is_some_and(|top_p| !(0.0..=1.0).contains(&top_p))
        {
            return Err(LingerError::invalid_config(
                "top_p must be between 0.0 and 1.0",
            ));
        }
        if self
            .top_logprobs
            .is_some_and(|top_logprobs| top_logprobs > 20)
        {
            return Err(LingerError::invalid_config(
                "top_logprobs must be between 0 and 20",
            ));
        }
        validate_optional_string("prompt_cache_key", self.prompt_cache_key.as_deref())?;
        validate_optional_string("safety_identifier", self.safety_identifier.as_deref())?;
        validate_optional_string("personality", self.personality.as_deref())?;
        if let Some(conversation) = &self.conversation {
            validate_optional_string("conversation", Some(conversation.id()))?;
        }
        if self.previous_response_id.is_some() && self.conversation.is_some() {
            return Err(LingerError::invalid_config(
                "previous_response_id cannot be used with conversation",
            ));
        }
        if let Some(context_management) = &self.context_management {
            validate_context_management(context_management)?;
        }
        if let Some(moderation) = &self.moderation {
            validate_moderation(moderation)?;
        }
        validate_tools(&self.tools)?;
        if let Some(tool_choice) = &self.tool_choice {
            validate_tool_choice(tool_choice)?;
        }
        if let Some(prompt) = &self.prompt {
            validate_prompt(prompt)?;
        }
        if let Some(text) = &self.text {
            validate_text_config(text)?;
        }
        if self
            .personality
            .as_deref()
            .is_some_and(|value| value.chars().count() > 64)
        {
            return Err(LingerError::invalid_config(
                "personality must be at most 64 characters",
            ));
        }
        validate_metadata(&self.metadata)?;
        if self
            .safety_identifier
            .as_deref()
            .is_some_and(|value| value.chars().count() > 64)
        {
            return Err(LingerError::invalid_config(
                "safety_identifier must be at most 64 characters",
            ));
        }
        validate_extra_fields(&self.extra)?;
        Ok(CreateResponseRequest {
            model,
            input,
            instructions: self.instructions,
            personality: self.personality,
            previous_response_id: self.previous_response_id,
            conversation: self.conversation,
            context_management: self.context_management,
            moderation: self.moderation,
            tools: self.tools,
            tool_choice: self.tool_choice,
            prompt: self.prompt,
            max_output_tokens: self.max_output_tokens,
            store: self.store,
            background: self.background,
            max_tool_calls: self.max_tool_calls,
            metadata: self.metadata,
            parallel_tool_calls: self.parallel_tool_calls,
            temperature: self.temperature,
            top_p: self.top_p,
            top_logprobs: self.top_logprobs,
            reasoning: self.reasoning,
            truncation: self.truncation,
            prompt_cache_key: self.prompt_cache_key,
            prompt_cache_retention: self.prompt_cache_retention,
            safety_identifier: self.safety_identifier,
            service_tier: self.service_tier,
            include: self.include,
            text: self.text,
            stream_options: self.stream_options,
            stream: None,
            extra: self.extra,
        })
    }
}

/// EN: Additional Responses API output data to include.
/// 中文:Responses API 可额外包含的输出数据。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResponseInclude {
    /// EN: File search results from file search tool calls.
    /// 中文:文件搜索工具调用的搜索结果。
    #[serde(rename = "file_search_call.results")]
    FileSearchCallResults,
    /// EN: Web search results from web search tool calls.
    /// 中文:网页搜索工具调用的搜索结果。
    #[serde(rename = "web_search_call.results")]
    WebSearchCallResults,
    /// EN: Source links for web search actions.
    /// 中文:网页搜索动作的来源链接。
    #[serde(rename = "web_search_call.action.sources")]
    WebSearchCallActionSources,
    /// EN: Image URLs from input messages.
    /// 中文:输入消息中的图像 URL。
    #[serde(rename = "message.input_image.image_url")]
    MessageInputImageImageUrl,
    /// EN: Image URLs from computer call outputs.
    /// 中文:computer call 输出中的图像 URL。
    #[serde(rename = "computer_call_output.output.image_url")]
    ComputerCallOutputOutputImageUrl,
    /// EN: Code interpreter tool call outputs.
    /// 中文:代码解释器工具调用输出。
    #[serde(rename = "code_interpreter_call.outputs")]
    CodeInterpreterCallOutputs,
    /// EN: Encrypted reasoning content for stateless multi-turn use.
    /// 中文:用于无状态多轮使用的加密推理内容。
    #[serde(rename = "reasoning.encrypted_content")]
    ReasoningEncryptedContent,
    /// EN: Log probabilities for assistant output text.
    /// 中文:assistant 输出文本的 logprobs。
    #[serde(rename = "message.output_text.logprobs")]
    MessageOutputTextLogprobs,
}

/// EN: Context truncation strategy for a Responses API request.
/// 中文:Responses API 请求的上下文截断策略。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseTruncation {
    /// EN: Automatically truncate input items from the beginning when needed.
    /// 中文:需要时自动从开头截断输入项目。
    Auto,
    /// EN: Disable truncation and let oversized inputs fail.
    /// 中文:禁用截断,让超出上下文限制的输入失败。
    Disabled,
}

/// EN: Conversation selector for a Responses API request.
/// 中文:Responses API 请求的 conversation 选择器。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(untagged)]
#[non_exhaustive]
pub enum ResponseConversation {
    /// EN: Use the conversation with this id.
    /// 中文:使用此 ID 对应的 conversation。
    Id(String),
    /// EN: Use the conversation object with this id.
    /// 中文:使用包含此 ID 的 conversation 对象。
    Object {
        /// EN: Conversation id.
        /// 中文:Conversation ID。
        id: String,
    },
}

impl ResponseConversation {
    /// EN: Creates a conversation object selector with the provided id.
    /// 中文:使用提供的 ID 创建 conversation 对象选择器。
    pub fn object(id: impl Into<String>) -> Self {
        Self::Object { id: id.into() }
    }

    fn id(&self) -> &str {
        match self {
            Self::Id(id) => id,
            Self::Object { id } => id,
        }
    }
}

impl From<String> for ResponseConversation {
    fn from(value: String) -> Self {
        Self::Id(value)
    }
}

impl From<&str> for ResponseConversation {
    fn from(value: &str) -> Self {
        Self::Id(value.to_string())
    }
}

/// EN: Reference to a reusable Responses API prompt template.
/// 中文:Responses API 可复用 prompt 模板引用。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponsePrompt {
    /// EN: Unique prompt template identifier.
    /// 中文:唯一的 prompt 模板标识符。
    pub id: String,
    /// EN: Optional prompt template version.
    /// 中文:可选的 prompt 模板版本。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    /// EN: Optional variables substituted into the prompt template.
    /// 中文:可选的 prompt 模板变量替换值。
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub variables: BTreeMap<String, Value>,
}

impl ResponsePrompt {
    /// EN: Creates a prompt template reference with the provided id.
    /// 中文:使用提供的 id 创建 prompt 模板引用。
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            version: None,
            variables: BTreeMap::new(),
        }
    }

    /// EN: Sets the prompt template version.
    /// 中文:设置 prompt 模板版本。
    pub fn version(mut self, version: impl Into<String>) -> Self {
        self.version = Some(version.into());
        self
    }

    /// EN: Adds a prompt template variable.
    /// 中文:添加 prompt 模板变量。
    pub fn variable(mut self, name: impl Into<String>, value: Value) -> Self {
        self.variables.insert(name.into(), value);
        self
    }
}

/// EN: Context management entry for a Responses API request.
/// 中文:Responses API 请求的上下文管理条目。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResponseContextManagement {
    /// EN: Context management entry type.
    /// 中文:上下文管理条目类型。
    #[serde(rename = "type")]
    pub kind: ResponseContextManagementType,
    /// EN: Optional token threshold at which compaction should run.
    /// 中文:触发压缩的可选 token 阈值。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compact_threshold: Option<u32>,
}

impl ResponseContextManagement {
    /// EN: Creates a compaction context management entry.
    /// 中文:创建 compaction 上下文管理条目。
    pub fn compaction() -> Self {
        Self {
            kind: ResponseContextManagementType::Compaction,
            compact_threshold: None,
        }
    }

    /// EN: Sets the token threshold at which compaction should run.
    /// 中文:设置触发压缩的 token 阈值。
    pub fn compact_threshold(mut self, compact_threshold: u32) -> Self {
        self.compact_threshold = Some(compact_threshold);
        self
    }
}

/// EN: Context management entry type.
/// 中文:上下文管理条目类型。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseContextManagementType {
    /// EN: Compact conversation context when configured thresholds are reached.
    /// 中文:达到配置阈值时压缩会话上下文。
    Compaction,
}

/// EN: Moderation configuration for a Responses API request.
/// 中文:Responses API 请求的 moderation 配置。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResponseModeration {
    /// EN: Moderation model id used for this response.
    /// 中文:此响应使用的 moderation 模型 ID。
    pub model: String,
}

impl ResponseModeration {
    /// EN: Creates moderation configuration with the provided model id.
    /// 中文:使用提供的模型 ID 创建 moderation 配置。
    pub fn new(model: impl Into<String>) -> Self {
        Self {
            model: model.into(),
        }
    }
}

/// EN: Tool definition accepted by a Responses API request.
/// 中文:Responses API 请求接受的工具定义。
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct ResponseTool {
    value: Value,
}

impl ResponseTool {
    /// EN: Creates a forward-compatible raw JSON tool definition.
    /// 中文:创建前向兼容的原始 JSON 工具定义。
    pub fn raw(value: Value) -> Self {
        Self { value }
    }

    /// EN: Converts the tool definition into the request JSON value.
    /// 中文:将工具定义转换为请求 JSON 值。
    pub fn into_value(self) -> Value {
        self.value
    }
}

impl From<Value> for ResponseTool {
    fn from(value: Value) -> Self {
        Self::raw(value)
    }
}

impl From<ResponseFunctionTool> for ResponseTool {
    fn from(tool: ResponseFunctionTool) -> Self {
        Self {
            value: serde_json::to_value(tool)
                .expect("serializing a response function tool should not fail"),
        }
    }
}

impl From<ResponseFileSearchTool> for ResponseTool {
    fn from(tool: ResponseFileSearchTool) -> Self {
        Self {
            value: serde_json::to_value(tool)
                .expect("serializing a response file search tool should not fail"),
        }
    }
}

impl From<ResponseComputerTool> for ResponseTool {
    fn from(tool: ResponseComputerTool) -> Self {
        Self {
            value: serde_json::to_value(tool)
                .expect("serializing a response computer tool should not fail"),
        }
    }
}

impl From<ResponseLocalShellTool> for ResponseTool {
    fn from(tool: ResponseLocalShellTool) -> Self {
        Self {
            value: serde_json::to_value(tool)
                .expect("serializing a response local shell tool should not fail"),
        }
    }
}

impl From<ResponseApplyPatchTool> for ResponseTool {
    fn from(tool: ResponseApplyPatchTool) -> Self {
        Self {
            value: serde_json::to_value(tool)
                .expect("serializing a response apply patch tool should not fail"),
        }
    }
}

impl From<ResponseCustomTool> for ResponseTool {
    fn from(tool: ResponseCustomTool) -> Self {
        Self {
            value: serde_json::to_value(tool)
                .expect("serializing a response custom tool should not fail"),
        }
    }
}

impl From<ResponseNamespaceTool> for ResponseTool {
    fn from(tool: ResponseNamespaceTool) -> Self {
        Self {
            value: serde_json::to_value(tool)
                .expect("serializing a response namespace tool should not fail"),
        }
    }
}

impl From<ResponseToolSearchTool> for ResponseTool {
    fn from(tool: ResponseToolSearchTool) -> Self {
        Self {
            value: serde_json::to_value(tool)
                .expect("serializing a response tool search tool should not fail"),
        }
    }
}

impl From<ResponseShellTool> for ResponseTool {
    fn from(tool: ResponseShellTool) -> Self {
        Self {
            value: serde_json::to_value(tool)
                .expect("serializing a response shell tool should not fail"),
        }
    }
}

impl From<ResponseCodeInterpreterTool> for ResponseTool {
    fn from(tool: ResponseCodeInterpreterTool) -> Self {
        Self {
            value: serde_json::to_value(tool)
                .expect("serializing a response code interpreter tool should not fail"),
        }
    }
}

impl From<ResponseImageGenerationTool> for ResponseTool {
    fn from(tool: ResponseImageGenerationTool) -> Self {
        Self {
            value: serde_json::to_value(tool)
                .expect("serializing a response image generation tool should not fail"),
        }
    }
}

impl From<ResponseMcpTool> for ResponseTool {
    fn from(tool: ResponseMcpTool) -> Self {
        Self {
            value: serde_json::to_value(tool)
                .expect("serializing a response MCP tool should not fail"),
        }
    }
}

impl From<ResponseWebSearchTool> for ResponseTool {
    fn from(tool: ResponseWebSearchTool) -> Self {
        Self {
            value: serde_json::to_value(tool)
                .expect("serializing a response web search tool should not fail"),
        }
    }
}

/// EN: Computer tool definition for Responses API computer-use models.
/// 中文:Responses API computer-use 模型使用的 computer 工具定义。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseComputerTool {
    #[serde(rename = "type")]
    kind: &'static str,
    /// EN: Computer environment controlled by the tool.
    /// 中文:工具控制的计算机环境。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<ResponseComputerEnvironment>,
    /// EN: Width of the virtual computer display.
    /// 中文:虚拟计算机显示器宽度。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_width: Option<u32>,
    /// EN: Height of the virtual computer display.
    /// 中文:虚拟计算机显示器高度。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_height: Option<u32>,
}

impl ResponseComputerTool {
    /// EN: Creates the basic hosted computer tool.
    /// 中文:创建基础 hosted computer 工具。
    pub fn computer() -> Self {
        Self {
            kind: "computer",
            environment: None,
            display_width: None,
            display_height: None,
        }
    }

    /// EN: Creates a computer-use preview tool for a display environment.
    /// 中文:为指定显示环境创建 computer-use preview 工具。
    pub fn computer_use_preview(
        environment: ResponseComputerEnvironment,
        display_width: u32,
        display_height: u32,
    ) -> Self {
        Self {
            kind: "computer_use_preview",
            environment: Some(environment),
            display_width: Some(display_width),
            display_height: Some(display_height),
        }
    }
}

/// EN: Environment controlled by a Responses API computer tool.
/// 中文:Responses API computer 工具控制的环境。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResponseComputerEnvironment {
    /// EN: Windows desktop environment.
    /// 中文:Windows 桌面环境。
    #[serde(rename = "windows")]
    Windows,
    /// EN: macOS desktop environment.
    /// 中文:macOS 桌面环境。
    #[serde(rename = "mac")]
    Mac,
    /// EN: Linux desktop environment.
    /// 中文:Linux 桌面环境。
    #[serde(rename = "linux")]
    Linux,
    /// EN: Ubuntu desktop environment.
    /// 中文:Ubuntu 桌面环境。
    #[serde(rename = "ubuntu")]
    Ubuntu,
    /// EN: Browser environment.
    /// 中文:浏览器环境。
    #[serde(rename = "browser")]
    Browser,
}

/// EN: Local shell tool definition for Responses API requests.
/// 中文:Responses API 请求使用的 local shell 工具定义。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResponseLocalShellTool {
    #[serde(rename = "type")]
    kind: &'static str,
}

impl ResponseLocalShellTool {
    /// EN: Creates a local shell tool.
    /// 中文:创建 local shell 工具。
    pub fn new() -> Self {
        Self {
            kind: "local_shell",
        }
    }
}

impl Default for ResponseLocalShellTool {
    fn default() -> Self {
        Self::new()
    }
}

/// EN: Apply-patch tool definition for Responses API requests.
/// 中文:Responses API 请求使用的 apply-patch 工具定义。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResponseApplyPatchTool {
    #[serde(rename = "type")]
    kind: &'static str,
}

impl ResponseApplyPatchTool {
    /// EN: Creates an apply-patch tool.
    /// 中文:创建 apply-patch 工具。
    pub fn new() -> Self {
        Self {
            kind: "apply_patch",
        }
    }
}

impl Default for ResponseApplyPatchTool {
    fn default() -> Self {
        Self::new()
    }
}

/// EN: Custom tool definition for Responses API requests.
/// 中文:Responses API 请求使用的 custom 工具定义。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseCustomTool {
    #[serde(rename = "type")]
    kind: &'static str,
    /// EN: Name used to identify this custom tool in tool calls.
    /// 中文:在工具调用中识别此 custom 工具的名称。
    pub name: String,
    /// EN: Optional description used to provide model context.
    /// 中文:用于向模型提供上下文的可选描述。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// EN: Optional input format for the custom tool.
    /// 中文:custom 工具的可选输入格式。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<ResponseCustomToolFormat>,
    /// EN: Whether this tool is deferred and loaded via tool search.
    /// 中文:此工具是否通过工具搜索延迟加载。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub defer_loading: Option<bool>,
}

impl ResponseCustomTool {
    /// EN: Creates a custom tool with the provided name.
    /// 中文:使用提供的名称创建 custom 工具。
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            kind: "custom",
            name: name.into(),
            description: None,
            format: None,
            defer_loading: None,
        }
    }

    /// EN: Sets the custom tool description.
    /// 中文:设置 custom 工具描述。
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// EN: Sets the custom tool input format.
    /// 中文:设置 custom 工具输入格式。
    pub fn format(mut self, format: ResponseCustomToolFormat) -> Self {
        self.format = Some(format);
        self
    }

    /// EN: Sets whether the custom tool is loaded via tool search.
    /// 中文:设置 custom 工具是否通过工具搜索加载。
    pub fn defer_loading(mut self, defer_loading: bool) -> Self {
        self.defer_loading = Some(defer_loading);
        self
    }
}

/// EN: Input format for a Responses API custom tool.
/// 中文:Responses API custom 工具的输入格式。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(tag = "type")]
#[non_exhaustive]
pub enum ResponseCustomToolFormat {
    /// EN: Unconstrained text input.
    /// 中文:不受约束的文本输入。
    #[serde(rename = "text")]
    Text,
    /// EN: Grammar-constrained input.
    /// 中文:受 grammar 约束的输入。
    #[serde(rename = "grammar")]
    Grammar {
        /// EN: Grammar syntax used by the definition.
        /// 中文:definition 使用的 grammar 语法。
        syntax: ResponseCustomToolGrammarSyntax,
        /// EN: Grammar definition.
        /// 中文:grammar 定义。
        definition: String,
    },
}

impl ResponseCustomToolFormat {
    /// EN: Creates an unconstrained text format.
    /// 中文:创建不受约束的 text 格式。
    pub fn text() -> Self {
        Self::Text
    }

    /// EN: Creates a grammar-constrained format.
    /// 中文:创建受 grammar 约束的格式。
    pub fn grammar(syntax: ResponseCustomToolGrammarSyntax, definition: impl Into<String>) -> Self {
        Self::Grammar {
            syntax,
            definition: definition.into(),
        }
    }
}

/// EN: Grammar syntax supported by Responses API custom tools.
/// 中文:Responses API custom 工具支持的 grammar 语法。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResponseCustomToolGrammarSyntax {
    /// EN: Lark grammar syntax.
    /// 中文:Lark grammar 语法。
    #[serde(rename = "lark")]
    Lark,
    /// EN: Regex grammar syntax.
    /// 中文:Regex grammar 语法。
    #[serde(rename = "regex")]
    Regex,
}

/// EN: Namespace tool definition for grouping function and custom tools.
/// 中文:用于分组 function 和 custom 工具的 namespace 工具定义。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseNamespaceTool {
    #[serde(rename = "type")]
    kind: &'static str,
    /// EN: Namespace name used in tool calls.
    /// 中文:工具调用中使用的 namespace 名称。
    pub name: String,
    /// EN: Description shown to the model.
    /// 中文:展示给模型的描述。
    pub description: String,
    /// EN: Function or custom tools inside this namespace.
    /// 中文:此 namespace 内的 function 或 custom 工具。
    pub tools: Vec<Value>,
}

impl ResponseNamespaceTool {
    /// EN: Creates an empty namespace tool that must receive nested tools before build.
    /// 中文:创建空 namespace 工具,build 前必须加入嵌套工具。
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            kind: "namespace",
            name: name.into(),
            description: description.into(),
            tools: Vec::new(),
        }
    }

    /// EN: Adds a function or custom tool to this namespace.
    /// 中文:向此 namespace 添加 function 或 custom 工具。
    pub fn tool<T>(mut self, tool: T) -> Self
    where
        T: Into<ResponseTool>,
    {
        self.tools.push(tool.into().into_value());
        self
    }

    /// EN: Replaces the nested tool list for this namespace.
    /// 中文:替换此 namespace 的嵌套工具列表。
    pub fn tools<I, T>(mut self, tools: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<ResponseTool>,
    {
        self.tools = tools
            .into_iter()
            .map(|tool| tool.into().into_value())
            .collect();
        self
    }
}

/// EN: Tool-search tool definition for deferred Responses API tools.
/// 中文:用于延迟 Responses API 工具的 tool-search 工具定义。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseToolSearchTool {
    #[serde(rename = "type")]
    kind: &'static str,
    /// EN: Whether tool search is executed by the server or client.
    /// 中文:工具搜索由服务器还是客户端执行。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution: Option<ResponseToolSearchExecution>,
    /// EN: Optional description shown to the model.
    /// 中文:展示给模型的可选描述。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// EN: Optional parameter schema for client-executed tool search.
    /// 中文:客户端执行工具搜索时使用的可选参数 schema。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<Value>,
}

impl ResponseToolSearchTool {
    /// EN: Creates a tool-search tool without an execution hint.
    /// 中文:创建不带执行位置提示的 tool-search 工具。
    pub fn new() -> Self {
        Self {
            kind: "tool_search",
            execution: None,
            description: None,
            parameters: None,
        }
    }

    /// EN: Creates a server-executed tool-search tool.
    /// 中文:创建由服务器执行的 tool-search 工具。
    pub fn server() -> Self {
        Self::new().execution(ResponseToolSearchExecution::Server)
    }

    /// EN: Creates a client-executed tool-search tool.
    /// 中文:创建由客户端执行的 tool-search 工具。
    pub fn client() -> Self {
        Self::new().execution(ResponseToolSearchExecution::Client)
    }

    /// EN: Sets the tool-search execution location.
    /// 中文:设置 tool-search 的执行位置。
    pub fn execution(mut self, execution: ResponseToolSearchExecution) -> Self {
        self.execution = Some(execution);
        self
    }

    /// EN: Sets the description shown to the model.
    /// 中文:设置展示给模型的描述。
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// EN: Sets the parameter schema for client-executed tool search.
    /// 中文:设置客户端执行工具搜索时使用的参数 schema。
    pub fn parameters(mut self, parameters: Value) -> Self {
        self.parameters = Some(parameters);
        self
    }
}

impl Default for ResponseToolSearchTool {
    fn default() -> Self {
        Self::new()
    }
}

/// EN: Execution location for Responses API tool search.
/// 中文:Responses API tool search 的执行位置。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResponseToolSearchExecution {
    /// EN: Execute tool search on the server.
    /// 中文:在服务器执行工具搜索。
    #[serde(rename = "server")]
    Server,
    /// EN: Execute tool search on the client.
    /// 中文:在客户端执行工具搜索。
    #[serde(rename = "client")]
    Client,
}

/// EN: Shell tool definition for Responses API requests.
/// 中文:Responses API 请求使用的 shell 工具定义。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseShellTool {
    #[serde(rename = "type")]
    kind: &'static str,
    /// EN: Optional shell execution environment.
    /// 中文:可选 shell 执行环境。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<Value>,
}

impl ResponseShellTool {
    /// EN: Creates a shell tool without an environment hint.
    /// 中文:创建不带环境提示的 shell 工具。
    pub fn new() -> Self {
        Self {
            kind: "shell",
            environment: None,
        }
    }

    /// EN: Creates a shell tool that uses a local environment.
    /// 中文:创建使用 local 环境的 shell 工具。
    pub fn local() -> Self {
        Self::new().environment(shell_environment_type("local"))
    }

    /// EN: Creates a shell tool that automatically creates a container.
    /// 中文:创建自动创建 container 的 shell 工具。
    pub fn container_auto() -> Self {
        Self::new().environment(shell_environment_type("container_auto"))
    }

    /// EN: Creates a shell tool that references an existing container.
    /// 中文:创建引用现有 container 的 shell 工具。
    pub fn container_reference(container_id: impl Into<String>) -> Self {
        let mut environment = serde_json::Map::new();
        environment.insert(
            "type".to_string(),
            Value::String("container_reference".to_string()),
        );
        environment.insert(
            "container_id".to_string(),
            Value::String(container_id.into()),
        );
        Self::new().environment(Value::Object(environment))
    }

    /// EN: Sets a raw shell environment object for forward compatibility.
    /// 中文:设置原始 shell environment 对象以保持前向兼容。
    pub fn environment(mut self, environment: Value) -> Self {
        self.environment = Some(environment);
        self
    }
}

impl Default for ResponseShellTool {
    fn default() -> Self {
        Self::new()
    }
}

fn shell_environment_type(kind: &'static str) -> Value {
    let mut environment = serde_json::Map::new();
    environment.insert("type".to_string(), Value::String(kind.to_string()));
    Value::Object(environment)
}

/// EN: Function tool definition for Responses API tool calling.
/// 中文:Responses API 工具调用使用的 function 工具定义。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseFunctionTool {
    #[serde(rename = "type")]
    kind: &'static str,
    /// EN: Function name the model may call.
    /// 中文:模型可以调用的函数名称。
    pub name: String,
    /// EN: Optional function description used by the model.
    /// 中文:供模型使用的可选函数描述。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// EN: JSON schema describing function parameters.
    /// 中文:描述函数参数的 JSON schema。
    pub parameters: Value,
    /// EN: Whether to enforce strict parameter validation.
    /// 中文:是否强制严格参数校验。
    pub strict: bool,
    /// EN: Whether this function is deferred and loaded via tool search.
    /// 中文:此函数是否通过工具搜索延迟加载。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub defer_loading: Option<bool>,
}

impl ResponseFunctionTool {
    /// EN: Creates a function tool with default strict parameter validation.
    /// 中文:创建默认启用严格参数校验的 function 工具。
    pub fn new(name: impl Into<String>, parameters: Value) -> Self {
        Self {
            kind: "function",
            name: name.into(),
            description: None,
            parameters,
            strict: true,
            defer_loading: None,
        }
    }

    /// EN: Sets the function description used by the model.
    /// 中文:设置供模型使用的函数描述。
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// EN: Sets whether strict parameter validation is enforced.
    /// 中文:设置是否强制严格参数校验。
    pub fn strict(mut self, strict: bool) -> Self {
        self.strict = strict;
        self
    }

    /// EN: Sets whether the function is deferred and loaded via tool search.
    /// 中文:设置函数是否通过工具搜索延迟加载。
    pub fn defer_loading(mut self, defer_loading: bool) -> Self {
        self.defer_loading = Some(defer_loading);
        self
    }
}

/// EN: File search tool definition for Responses API built-in file search.
/// 中文:Responses API 内置文件搜索使用的 file_search 工具定义。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseFileSearchTool {
    #[serde(rename = "type")]
    kind: &'static str,
    /// EN: Vector store ids the tool searches.
    /// 中文:工具要搜索的 vector store ID 列表。
    pub vector_store_ids: Vec<String>,
    /// EN: Optional maximum number of search results to return.
    /// 中文:可选的最大搜索结果数量。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_num_results: Option<u8>,
    /// EN: Optional ranking options object.
    /// 中文:可选的排序选项对象。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ranking_options: Option<Value>,
    /// EN: Optional filter object to apply.
    /// 中文:可选的过滤器对象。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<Value>,
}

impl ResponseFileSearchTool {
    /// EN: Creates a file search tool for the provided vector store ids.
    /// 中文:使用提供的 vector store ID 创建 file_search 工具。
    pub fn new<I, S>(vector_store_ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            kind: "file_search",
            vector_store_ids: vector_store_ids.into_iter().map(Into::into).collect(),
            max_num_results: None,
            ranking_options: None,
            filters: None,
        }
    }

    /// EN: Sets the maximum number of search results to return.
    /// 中文:设置最大搜索结果数量。
    pub fn max_num_results(mut self, max_num_results: u8) -> Self {
        self.max_num_results = Some(max_num_results);
        self
    }

    /// EN: Sets ranking options for file search.
    /// 中文:设置文件搜索排序选项。
    pub fn ranking_options(mut self, ranking_options: Value) -> Self {
        self.ranking_options = Some(ranking_options);
        self
    }

    /// EN: Sets a filter for file search.
    /// 中文:设置文件搜索过滤器。
    pub fn filters(mut self, filters: Value) -> Self {
        self.filters = Some(filters);
        self
    }
}

/// EN: Code interpreter tool definition for Responses API built-in Python execution.
/// 中文:Responses API 内置 Python 执行使用的 code_interpreter 工具定义。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseCodeInterpreterTool {
    #[serde(rename = "type")]
    kind: &'static str,
    /// EN: Code interpreter container id or auto container configuration.
    /// 中文:code interpreter 容器 ID 或自动容器配置。
    pub container: ResponseCodeInterpreterContainer,
}

impl ResponseCodeInterpreterTool {
    /// EN: Creates a code interpreter tool that reuses an existing container id.
    /// 中文:创建复用已有容器 ID 的 code_interpreter 工具。
    pub fn container_id(container_id: impl Into<String>) -> Self {
        Self {
            kind: "code_interpreter",
            container: ResponseCodeInterpreterContainer::Id(container_id.into()),
        }
    }

    /// EN: Creates a code interpreter tool with an automatically managed container.
    /// 中文:创建使用自动托管容器的 code_interpreter 工具。
    pub fn auto() -> Self {
        Self::auto_container(ResponseCodeInterpreterAutoContainer::new())
    }

    /// EN: Creates a code interpreter tool from an auto container configuration.
    /// 中文:使用自动容器配置创建 code_interpreter 工具。
    pub fn auto_container(container: ResponseCodeInterpreterAutoContainer) -> Self {
        Self {
            kind: "code_interpreter",
            container: ResponseCodeInterpreterContainer::Auto(container),
        }
    }

    /// EN: Sets uploaded file ids for the auto container.
    /// 中文:设置自动容器可访问的上传文件 ID。
    pub fn file_ids<I, S>(mut self, file_ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        if let ResponseCodeInterpreterContainer::Auto(container) = &mut self.container {
            container.file_ids = file_ids.into_iter().map(Into::into).collect();
        }
        self
    }

    /// EN: Sets the memory limit for the auto container.
    /// 中文:设置自动容器的内存限制。
    pub fn memory_limit(mut self, memory_limit: ResponseCodeInterpreterMemoryLimit) -> Self {
        if let ResponseCodeInterpreterContainer::Auto(container) = &mut self.container {
            container.memory_limit = Some(memory_limit);
        }
        self
    }

    /// EN: Sets raw network policy configuration for the auto container.
    /// 中文:设置自动容器的原始网络策略配置。
    pub fn network_policy(mut self, network_policy: Value) -> Self {
        if let ResponseCodeInterpreterContainer::Auto(container) = &mut self.container {
            container.network_policy = Some(network_policy);
        }
        self
    }
}

/// EN: Code interpreter container selector.
/// 中文:code interpreter 容器选择器。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[serde(untagged)]
#[non_exhaustive]
pub enum ResponseCodeInterpreterContainer {
    /// EN: Existing container id.
    /// 中文:已有容器 ID。
    Id(String),
    /// EN: Automatically managed container configuration.
    /// 中文:自动托管容器配置。
    Auto(ResponseCodeInterpreterAutoContainer),
}

/// EN: Auto container configuration for a code interpreter tool.
/// 中文:code interpreter 工具的自动容器配置。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseCodeInterpreterAutoContainer {
    #[serde(rename = "type")]
    kind: &'static str,
    /// EN: Uploaded file ids to make available to Python code.
    /// 中文:提供给 Python 代码使用的上传文件 ID。
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub file_ids: Vec<String>,
    /// EN: Optional memory limit for the container.
    /// 中文:容器的可选内存限制。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_limit: Option<ResponseCodeInterpreterMemoryLimit>,
    /// EN: Optional raw network policy for the container.
    /// 中文:容器的可选原始网络策略。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub network_policy: Option<Value>,
}

impl ResponseCodeInterpreterAutoContainer {
    /// EN: Creates an empty auto container configuration.
    /// 中文:创建空的自动容器配置。
    pub fn new() -> Self {
        Self {
            kind: "auto",
            file_ids: Vec::new(),
            memory_limit: None,
            network_policy: None,
        }
    }

    /// EN: Sets uploaded file ids for the auto container.
    /// 中文:设置自动容器可访问的上传文件 ID。
    pub fn file_ids<I, S>(mut self, file_ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.file_ids = file_ids.into_iter().map(Into::into).collect();
        self
    }

    /// EN: Sets the memory limit for the auto container.
    /// 中文:设置自动容器的内存限制。
    pub fn memory_limit(mut self, memory_limit: ResponseCodeInterpreterMemoryLimit) -> Self {
        self.memory_limit = Some(memory_limit);
        self
    }

    /// EN: Sets raw network policy configuration for the auto container.
    /// 中文:设置自动容器的原始网络策略配置。
    pub fn network_policy(mut self, network_policy: Value) -> Self {
        self.network_policy = Some(network_policy);
        self
    }
}

impl Default for ResponseCodeInterpreterAutoContainer {
    fn default() -> Self {
        Self::new()
    }
}

/// EN: Memory limit for a code interpreter auto container.
/// 中文:code interpreter 自动容器的内存限制。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResponseCodeInterpreterMemoryLimit {
    /// EN: One gigabyte memory limit.
    /// 中文:1GB 内存限制。
    #[serde(rename = "1g")]
    OneGigabyte,
    /// EN: Four gigabyte memory limit.
    /// 中文:4GB 内存限制。
    #[serde(rename = "4g")]
    FourGigabytes,
    /// EN: Sixteen gigabyte memory limit.
    /// 中文:16GB 内存限制。
    #[serde(rename = "16g")]
    SixteenGigabytes,
    /// EN: Sixty-four gigabyte memory limit.
    /// 中文:64GB 内存限制。
    #[serde(rename = "64g")]
    SixtyFourGigabytes,
}

/// EN: Image generation tool definition for Responses API built-in image creation.
/// 中文:Responses API 内置图像创建使用的 image_generation 工具定义。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseImageGenerationTool {
    #[serde(rename = "type")]
    kind: &'static str,
    /// EN: Optional image generation model id.
    /// 中文:可选的图像生成模型 ID。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// EN: Optional generated image quality.
    /// 中文:可选的生成图像质量。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quality: Option<ResponseImageGenerationQuality>,
    /// EN: Optional generated image size.
    /// 中文:可选的生成图像尺寸。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<String>,
    /// EN: Optional output image format.
    /// 中文:可选的输出图像格式。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_format: Option<ResponseImageGenerationOutputFormat>,
    /// EN: Optional output image compression percentage.
    /// 中文:可选的输出图像压缩百分比。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_compression: Option<u8>,
    /// EN: Optional image moderation level.
    /// 中文:可选的图像审核级别。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub moderation: Option<ResponseImageGenerationModeration>,
    /// EN: Optional generated image background.
    /// 中文:可选的生成图像背景。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub background: Option<ResponseImageGenerationBackground>,
    /// EN: Optional input image fidelity for edit actions.
    /// 中文:编辑动作的可选输入图像保真度。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_fidelity: Option<ResponseImageGenerationInputFidelity>,
    /// EN: Optional mask for inpainting edits.
    /// 中文:修补编辑使用的可选遮罩。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_image_mask: Option<ResponseImageGenerationMask>,
    /// EN: Optional number of partial images to stream.
    /// 中文:可选的流式部分图像数量。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub partial_images: Option<u8>,
    /// EN: Optional image generation action.
    /// 中文:可选的图像生成动作。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<ResponseImageGenerationAction>,
}

impl ResponseImageGenerationTool {
    /// EN: Creates an image generation tool with default server-side options.
    /// 中文:创建使用服务端默认选项的 image_generation 工具。
    pub fn new() -> Self {
        Self {
            kind: "image_generation",
            model: None,
            quality: None,
            size: None,
            output_format: None,
            output_compression: None,
            moderation: None,
            background: None,
            input_fidelity: None,
            input_image_mask: None,
            partial_images: None,
            action: None,
        }
    }

    /// EN: Sets the image generation model id.
    /// 中文:设置图像生成模型 ID。
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// EN: Sets generated image quality.
    /// 中文:设置生成图像质量。
    pub fn quality(mut self, quality: ResponseImageGenerationQuality) -> Self {
        self.quality = Some(quality);
        self
    }

    /// EN: Sets generated image size.
    /// 中文:设置生成图像尺寸。
    pub fn size(mut self, size: impl Into<String>) -> Self {
        self.size = Some(size.into());
        self
    }

    /// EN: Sets output image format.
    /// 中文:设置输出图像格式。
    pub fn output_format(mut self, output_format: ResponseImageGenerationOutputFormat) -> Self {
        self.output_format = Some(output_format);
        self
    }

    /// EN: Sets output image compression percentage.
    /// 中文:设置输出图像压缩百分比。
    pub fn output_compression(mut self, output_compression: u8) -> Self {
        self.output_compression = Some(output_compression);
        self
    }

    /// EN: Sets image moderation level.
    /// 中文:设置图像审核级别。
    pub fn moderation(mut self, moderation: ResponseImageGenerationModeration) -> Self {
        self.moderation = Some(moderation);
        self
    }

    /// EN: Sets generated image background.
    /// 中文:设置生成图像背景。
    pub fn background(mut self, background: ResponseImageGenerationBackground) -> Self {
        self.background = Some(background);
        self
    }

    /// EN: Sets input image fidelity for edit actions.
    /// 中文:设置编辑动作的输入图像保真度。
    pub fn input_fidelity(mut self, input_fidelity: ResponseImageGenerationInputFidelity) -> Self {
        self.input_fidelity = Some(input_fidelity);
        self
    }

    /// EN: Sets the mask for inpainting edits.
    /// 中文:设置修补编辑使用的遮罩。
    pub fn input_image_mask(mut self, input_image_mask: ResponseImageGenerationMask) -> Self {
        self.input_image_mask = Some(input_image_mask);
        self
    }

    /// EN: Sets the number of partial images to stream.
    /// 中文:设置要流式返回的部分图像数量。
    pub fn partial_images(mut self, partial_images: u8) -> Self {
        self.partial_images = Some(partial_images);
        self
    }

    /// EN: Sets image generation action.
    /// 中文:设置图像生成动作。
    pub fn action(mut self, action: ResponseImageGenerationAction) -> Self {
        self.action = Some(action);
        self
    }
}

impl Default for ResponseImageGenerationTool {
    fn default() -> Self {
        Self::new()
    }
}

/// EN: Image generation mask for inpainting edits.
/// 中文:修补编辑使用的图像生成遮罩。
#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResponseImageGenerationMask {
    /// EN: Base64 data URL mask image.
    /// 中文:base64 data URL 遮罩图像。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_url: Option<String>,
    /// EN: Uploaded file id for the mask image.
    /// 中文:遮罩图像的已上传文件 ID。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_id: Option<String>,
}

impl ResponseImageGenerationMask {
    /// EN: Creates a mask from a base64 data URL image.
    /// 中文:使用 base64 data URL 图像创建遮罩。
    pub fn image_url(image_url: impl Into<String>) -> Self {
        Self {
            image_url: Some(image_url.into()),
            file_id: None,
        }
    }

    /// EN: Creates a mask from an uploaded file id.
    /// 中文:使用已上传文件 ID 创建遮罩。
    pub fn file_id(file_id: impl Into<String>) -> Self {
        Self {
            image_url: None,
            file_id: Some(file_id.into()),
        }
    }
}

/// EN: Image generation quality.
/// 中文:图像生成质量。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseImageGenerationQuality {
    /// EN: Low image quality.
    /// 中文:低图像质量。
    Low,
    /// EN: Medium image quality.
    /// 中文:中等图像质量。
    Medium,
    /// EN: High image quality.
    /// 中文:高图像质量。
    High,
    /// EN: Let the API choose image quality automatically.
    /// 中文:让 API 自动选择图像质量。
    Auto,
}

/// EN: Image generation output format.
/// 中文:图像生成输出格式。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseImageGenerationOutputFormat {
    /// EN: PNG output.
    /// 中文:PNG 输出。
    Png,
    /// EN: WebP output.
    /// 中文:WebP 输出。
    Webp,
    /// EN: JPEG output.
    /// 中文:JPEG 输出。
    Jpeg,
}

/// EN: Image generation moderation level.
/// 中文:图像生成审核级别。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseImageGenerationModeration {
    /// EN: Let the API choose moderation automatically.
    /// 中文:让 API 自动选择审核级别。
    Auto,
    /// EN: Use the low moderation level.
    /// 中文:使用低审核级别。
    Low,
}

/// EN: Image generation background mode.
/// 中文:图像生成背景模式。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseImageGenerationBackground {
    /// EN: Transparent background.
    /// 中文:透明背景。
    Transparent,
    /// EN: Opaque background.
    /// 中文:不透明背景。
    Opaque,
    /// EN: Let the API choose the background automatically.
    /// 中文:让 API 自动选择背景。
    Auto,
}

/// EN: Input image fidelity for image generation edits.
/// 中文:图像生成编辑的输入图像保真度。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseImageGenerationInputFidelity {
    /// EN: High input image fidelity.
    /// 中文:高输入图像保真度。
    High,
    /// EN: Low input image fidelity.
    /// 中文:低输入图像保真度。
    Low,
}

/// EN: Image generation action.
/// 中文:图像生成动作。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseImageGenerationAction {
    /// EN: Generate a new image.
    /// 中文:生成新图像。
    Generate,
    /// EN: Edit an existing image.
    /// 中文:编辑已有图像。
    Edit,
    /// EN: Let the API choose the action automatically.
    /// 中文:让 API 自动选择动作。
    Auto,
}

/// EN: MCP tool definition for Responses API remote MCP servers and connectors.
/// 中文:Responses API 远程 MCP 服务器和连接器使用的 MCP 工具定义。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResponseMcpTool {
    #[serde(rename = "type")]
    kind: &'static str,
    /// EN: Label used to identify this MCP server in tool calls.
    /// 中文:在工具调用中标识此 MCP 服务器的标签。
    pub server_label: String,
    /// EN: URL for a custom remote MCP server.
    /// 中文:自定义远程 MCP 服务器 URL。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub server_url: Option<String>,
    /// EN: Built-in service connector identifier.
    /// 中文:内置服务连接器标识。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_id: Option<ResponseMcpConnector>,
    /// EN: Optional OAuth access token for the MCP server or connector.
    /// 中文:MCP 服务器或连接器使用的可选 OAuth access token。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authorization: Option<String>,
    /// EN: Optional MCP server description.
    /// 中文:可选的 MCP 服务器描述。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub server_description: Option<String>,
    /// EN: Optional HTTP headers to send to the MCP server.
    /// 中文:发送给 MCP 服务器的可选 HTTP header。
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub headers: BTreeMap<String, String>,
    /// EN: Optional allowed tool names or filter object.
    /// 中文:可选的允许工具名称列表或过滤器对象。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_tools: Option<ResponseMcpAllowedTools>,
    /// EN: Optional approval policy for MCP tools.
    /// 中文:MCP 工具的可选审批策略。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub require_approval: Option<ResponseMcpRequireApproval>,
    /// EN: Whether this MCP tool is deferred and discovered via tool search.
    /// 中文:此 MCP 工具是否延迟并通过工具搜索发现。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub defer_loading: Option<bool>,
}

impl ResponseMcpTool {
    /// EN: Creates an MCP tool backed by a custom remote MCP server URL.
    /// 中文:创建由自定义远程 MCP 服务器 URL 支持的 MCP 工具。
    pub fn server_url(server_label: impl Into<String>, server_url: impl Into<String>) -> Self {
        Self {
            kind: "mcp",
            server_label: server_label.into(),
            server_url: Some(server_url.into()),
            connector_id: None,
            authorization: None,
            server_description: None,
            headers: BTreeMap::new(),
            allowed_tools: None,
            require_approval: None,
            defer_loading: None,
        }
    }

    /// EN: Creates an MCP tool backed by a built-in service connector.
    /// 中文:创建由内置服务连接器支持的 MCP 工具。
    pub fn connector(server_label: impl Into<String>, connector: ResponseMcpConnector) -> Self {
        Self {
            kind: "mcp",
            server_label: server_label.into(),
            server_url: None,
            connector_id: Some(connector),
            authorization: None,
            server_description: None,
            headers: BTreeMap::new(),
            allowed_tools: None,
            require_approval: None,
            defer_loading: None,
        }
    }

    /// EN: Sets an OAuth access token for the MCP server or connector.
    /// 中文:设置 MCP 服务器或连接器使用的 OAuth access token。
    pub fn authorization(mut self, authorization: impl Into<String>) -> Self {
        self.authorization = Some(authorization.into());
        self
    }

    /// EN: Sets an optional MCP server description.
    /// 中文:设置可选的 MCP 服务器描述。
    pub fn server_description(mut self, server_description: impl Into<String>) -> Self {
        self.server_description = Some(server_description.into());
        self
    }

    /// EN: Adds an HTTP header sent to the MCP server.
    /// 中文:添加发送给 MCP 服务器的 HTTP header。
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(name.into(), value.into());
        self
    }

    /// EN: Restricts MCP calls to the provided tool names.
    /// 中文:将 MCP 调用限制为提供的工具名称。
    pub fn allowed_tools<I, S>(mut self, tool_names: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.allowed_tools = Some(ResponseMcpAllowedTools::Names(
            tool_names.into_iter().map(Into::into).collect(),
        ));
        self
    }

    /// EN: Restricts MCP calls using a filter object.
    /// 中文:使用过滤器对象限制 MCP 调用。
    pub fn allowed_tool_filter(mut self, filter: ResponseMcpToolFilter) -> Self {
        self.allowed_tools = Some(ResponseMcpAllowedTools::Filter(filter));
        self
    }

    /// EN: Sets the MCP tool approval policy.
    /// 中文:设置 MCP 工具审批策略。
    pub fn require_approval(mut self, require_approval: ResponseMcpRequireApproval) -> Self {
        self.require_approval = Some(require_approval);
        self
    }

    /// EN: Sets whether this MCP tool is deferred and discovered via tool search.
    /// 中文:设置此 MCP 工具是否延迟并通过工具搜索发现。
    pub fn defer_loading(mut self, defer_loading: bool) -> Self {
        self.defer_loading = Some(defer_loading);
        self
    }
}

/// EN: Built-in MCP service connector identifiers.
/// 中文:内置 MCP 服务连接器标识。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResponseMcpConnector {
    /// EN: Dropbox connector.
    /// 中文:Dropbox 连接器。
    #[serde(rename = "connector_dropbox")]
    Dropbox,
    /// EN: Gmail connector.
    /// 中文:Gmail 连接器。
    #[serde(rename = "connector_gmail")]
    Gmail,
    /// EN: Google Calendar connector.
    /// 中文:Google Calendar 连接器。
    #[serde(rename = "connector_googlecalendar")]
    GoogleCalendar,
    /// EN: Google Drive connector.
    /// 中文:Google Drive 连接器。
    #[serde(rename = "connector_googledrive")]
    GoogleDrive,
    /// EN: Microsoft Teams connector.
    /// 中文:Microsoft Teams 连接器。
    #[serde(rename = "connector_microsoftteams")]
    MicrosoftTeams,
    /// EN: Outlook Calendar connector.
    /// 中文:Outlook Calendar 连接器。
    #[serde(rename = "connector_outlookcalendar")]
    OutlookCalendar,
    /// EN: Outlook Email connector.
    /// 中文:Outlook Email 连接器。
    #[serde(rename = "connector_outlookemail")]
    OutlookEmail,
    /// EN: SharePoint connector.
    /// 中文:SharePoint 连接器。
    #[serde(rename = "connector_sharepoint")]
    SharePoint,
}

/// EN: MCP allowed tools selector.
/// 中文:MCP 允许工具选择器。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[serde(untagged)]
#[non_exhaustive]
pub enum ResponseMcpAllowedTools {
    /// EN: Explicit allowed tool names.
    /// 中文:显式允许的工具名称。
    Names(Vec<String>),
    /// EN: Filter-based allowed tools.
    /// 中文:基于过滤器的允许工具。
    Filter(ResponseMcpToolFilter),
}

/// EN: MCP tool filter by names and read-only annotation.
/// 中文:按名称和只读标注过滤 MCP 工具。
#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResponseMcpToolFilter {
    /// EN: Optional tool names to match.
    /// 中文:可选的匹配工具名称。
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tool_names: Vec<String>,
    /// EN: Optional read-only filter.
    /// 中文:可选的只读过滤器。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub read_only: Option<bool>,
}

impl ResponseMcpToolFilter {
    /// EN: Creates an empty MCP tool filter.
    /// 中文:创建空的 MCP 工具过滤器。
    pub fn new() -> Self {
        Self::default()
    }

    /// EN: Sets the tool names matched by this filter.
    /// 中文:设置此过滤器匹配的工具名称。
    pub fn tool_names<I, S>(mut self, tool_names: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.tool_names = tool_names.into_iter().map(Into::into).collect();
        self
    }

    /// EN: Sets the read-only filter.
    /// 中文:设置只读过滤器。
    pub fn read_only(mut self, read_only: bool) -> Self {
        self.read_only = Some(read_only);
        self
    }
}

/// EN: MCP approval policy.
/// 中文:MCP 审批策略。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[serde(untagged)]
#[non_exhaustive]
pub enum ResponseMcpRequireApproval {
    /// EN: A single approval mode for all tools.
    /// 中文:应用于全部工具的单一审批模式。
    Mode(ResponseMcpApprovalMode),
    /// EN: Filtered approval policy.
    /// 中文:基于过滤器的审批策略。
    Filter(ResponseMcpApprovalFilter),
}

/// EN: MCP approval mode for all tools.
/// 中文:全部 MCP 工具的审批模式。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseMcpApprovalMode {
    /// EN: Always require approval.
    /// 中文:始终要求审批。
    Always,
    /// EN: Never require approval.
    /// 中文:从不要求审批。
    Never,
}

/// EN: MCP approval filters for always and never approval sets.
/// 中文:MCP always 和 never 审批集合的过滤器。
#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResponseMcpApprovalFilter {
    /// EN: Tools that always require approval.
    /// 中文:始终需要审批的工具。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub always: Option<ResponseMcpToolFilter>,
    /// EN: Tools that never require approval.
    /// 中文:从不需要审批的工具。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub never: Option<ResponseMcpToolFilter>,
}

impl ResponseMcpApprovalFilter {
    /// EN: Creates an empty MCP approval filter.
    /// 中文:创建空的 MCP 审批过滤器。
    pub fn new() -> Self {
        Self::default()
    }

    /// EN: Sets tools that always require approval.
    /// 中文:设置始终需要审批的工具。
    pub fn always(mut self, filter: ResponseMcpToolFilter) -> Self {
        self.always = Some(filter);
        self
    }

    /// EN: Sets tools that never require approval.
    /// 中文:设置从不需要审批的工具。
    pub fn never(mut self, filter: ResponseMcpToolFilter) -> Self {
        self.never = Some(filter);
        self
    }
}

/// EN: Web search tool definition for Responses API built-in web search.
/// 中文:Responses API 内置网页搜索使用的 web search 工具定义。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseWebSearchTool {
    #[serde(rename = "type")]
    kind: ResponseWebSearchToolType,
    /// EN: Optional filters for web search.
    /// 中文:可选的网页搜索过滤器。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<Value>,
    /// EN: Optional approximate user location object.
    /// 中文:可选的用户大致位置对象。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_location: Option<Value>,
    /// EN: Optional search context size guidance.
    /// 中文:可选的搜索上下文大小提示。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search_context_size: Option<ResponseWebSearchContextSize>,
    /// EN: Optional preview search content types.
    /// 中文:可选的 preview 搜索内容类型。
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub search_content_types: Vec<String>,
}

impl ResponseWebSearchTool {
    /// EN: Creates the current web search tool.
    /// 中文:创建当前 web_search 工具。
    pub fn web_search() -> Self {
        Self::new(ResponseWebSearchToolType::WebSearch)
    }

    /// EN: Creates the versioned 2025-08-26 web search tool.
    /// 中文:创建 2025-08-26 版本的 web_search 工具。
    pub fn web_search_2025_08_26() -> Self {
        Self::new(ResponseWebSearchToolType::WebSearch20250826)
    }

    /// EN: Creates the current web search preview tool.
    /// 中文:创建当前 web_search_preview 工具。
    pub fn web_search_preview() -> Self {
        Self::new(ResponseWebSearchToolType::WebSearchPreview)
    }

    /// EN: Creates the versioned 2025-03-11 web search preview tool.
    /// 中文:创建 2025-03-11 版本的 web_search_preview 工具。
    pub fn web_search_preview_2025_03_11() -> Self {
        Self::new(ResponseWebSearchToolType::WebSearchPreview20250311)
    }

    fn new(kind: ResponseWebSearchToolType) -> Self {
        Self {
            kind,
            filters: None,
            user_location: None,
            search_context_size: None,
            search_content_types: Vec::new(),
        }
    }

    /// EN: Sets web search filters.
    /// 中文:设置网页搜索过滤器。
    pub fn filters(mut self, filters: Value) -> Self {
        self.filters = Some(filters);
        self
    }

    /// EN: Sets the approximate user location object.
    /// 中文:设置用户大致位置对象。
    pub fn user_location(mut self, user_location: Value) -> Self {
        self.user_location = Some(user_location);
        self
    }

    /// EN: Sets search context size guidance.
    /// 中文:设置搜索上下文大小提示。
    pub fn search_context_size(
        mut self,
        search_context_size: ResponseWebSearchContextSize,
    ) -> Self {
        self.search_context_size = Some(search_context_size);
        self
    }

    /// EN: Sets preview search content types.
    /// 中文:设置 preview 搜索内容类型。
    pub fn search_content_types<I, S>(mut self, search_content_types: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.search_content_types = search_content_types.into_iter().map(Into::into).collect();
        self
    }
}

/// EN: Web search tool wire type.
/// 中文:网页搜索工具的传输类型。
#[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResponseWebSearchToolType {
    /// EN: Current web search tool.
    /// 中文:当前 web_search 工具。
    #[serde(rename = "web_search")]
    WebSearch,
    /// EN: Versioned 2025-08-26 web search tool.
    /// 中文:2025-08-26 版本的 web_search 工具。
    #[serde(rename = "web_search_2025_08_26")]
    WebSearch20250826,
    /// EN: Current web search preview tool.
    /// 中文:当前 web_search_preview 工具。
    #[serde(rename = "web_search_preview")]
    WebSearchPreview,
    /// EN: Versioned 2025-03-11 web search preview tool.
    /// 中文:2025-03-11 版本的 web_search_preview 工具。
    #[serde(rename = "web_search_preview_2025_03_11")]
    WebSearchPreview20250311,
}

/// EN: Search context size guidance for web search tools.
/// 中文:网页搜索工具的搜索上下文大小提示。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseWebSearchContextSize {
    /// EN: Use a small search context.
    /// 中文:使用较小的搜索上下文。
    Low,
    /// EN: Use the default medium search context.
    /// 中文:使用默认的中等搜索上下文。
    Medium,
    /// EN: Use a larger search context.
    /// 中文:使用较大的搜索上下文。
    High,
}

/// EN: Tool selection mode or specific tool for a Responses API request.
/// 中文:Responses API 请求的工具选择模式或指定工具。
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResponseToolChoice {
    /// EN: The model must not call tools and should generate a message.
    /// 中文:模型不得调用工具,应直接生成消息。
    None,
    /// EN: The model may choose between generating a message and calling tools.
    /// 中文:模型可以在生成消息和调用工具之间自动选择。
    Auto,
    /// EN: The model must call one or more tools.
    /// 中文:模型必须调用一个或多个工具。
    Required,
    /// EN: Force the model to call a built-in hosted tool.
    /// 中文:强制模型调用一个内置托管工具。
    HostedTool {
        /// EN: Hosted tool type to call.
        /// 中文:要调用的托管工具类型。
        tool_type: ResponseHostedToolChoice,
    },
    /// EN: Force the model to call a named function tool.
    /// 中文:强制模型调用指定名称的 function 工具。
    Function {
        /// EN: Function name to call.
        /// 中文:要调用的 function 名称。
        name: String,
    },
    /// EN: Force the model to call a named custom tool.
    /// 中文:强制模型调用指定名称的 custom 工具。
    Custom {
        /// EN: Custom tool name to call.
        /// 中文:要调用的 custom 工具名称。
        name: String,
    },
    /// EN: Force the model to call a tool on a remote MCP server.
    /// 中文:强制模型调用远程 MCP 服务器上的工具。
    Mcp {
        /// EN: MCP server label to use.
        /// 中文:要使用的 MCP 服务器标签。
        server_label: String,
        /// EN: Optional tool name to call on the MCP server.
        /// 中文:要在 MCP 服务器上调用的可选工具名称。
        name: Option<String>,
    },
    /// EN: Force the model to call the apply_patch tool.
    /// 中文:强制模型调用 apply_patch 工具。
    ApplyPatch,
    /// EN: Force the model to call the shell tool.
    /// 中文:强制模型调用 shell 工具。
    Shell,
    /// EN: Constrain the model to a pre-defined set of allowed tools.
    /// 中文:将模型限制为只能从预定义的允许工具集合中选择。
    AllowedTools {
        /// EN: Selection mode within the allowed tools set.
        /// 中文:允许工具集合内的选择模式。
        mode: ResponseAllowedToolsMode,
        /// EN: Tool definitions the model may call.
        /// 中文:模型可以调用的工具定义。
        tools: Vec<Value>,
    },
}

impl ResponseToolChoice {
    /// EN: Creates a hosted tool choice for the provided built-in tool type.
    /// 中文:为提供的内置工具类型创建 hosted tool 选择。
    pub fn hosted_tool(tool_type: ResponseHostedToolChoice) -> Self {
        Self::HostedTool { tool_type }
    }

    /// EN: Creates a function tool choice for the provided function name.
    /// 中文:为提供的 function 名称创建工具选择。
    pub fn function(name: impl Into<String>) -> Self {
        Self::Function { name: name.into() }
    }

    /// EN: Creates a custom tool choice for the provided custom tool name.
    /// 中文:为提供的 custom 工具名称创建工具选择。
    pub fn custom(name: impl Into<String>) -> Self {
        Self::Custom { name: name.into() }
    }

    /// EN: Creates an MCP server tool choice for the provided server label.
    /// 中文:为提供的服务器标签创建 MCP 工具选择。
    pub fn mcp(server_label: impl Into<String>) -> Self {
        Self::Mcp {
            server_label: server_label.into(),
            name: None,
        }
    }

    /// EN: Creates an MCP tool choice for a named tool on the provided server.
    /// 中文:为提供的服务器和工具名称创建 MCP 工具选择。
    pub fn mcp_tool(server_label: impl Into<String>, name: impl Into<String>) -> Self {
        Self::Mcp {
            server_label: server_label.into(),
            name: Some(name.into()),
        }
    }

    /// EN: Creates an allowed-tools choice with the provided mode and tool definitions.
    /// 中文:使用提供的模式和工具定义创建 allowed-tools 选择。
    pub fn allowed_tools<I>(mode: ResponseAllowedToolsMode, tools: I) -> Self
    where
        I: IntoIterator<Item = Value>,
    {
        Self::AllowedTools {
            mode,
            tools: tools.into_iter().collect(),
        }
    }
}

impl Serialize for ResponseToolChoice {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Self::None => serializer.serialize_str("none"),
            Self::Auto => serializer.serialize_str("auto"),
            Self::Required => serializer.serialize_str("required"),
            Self::HostedTool { tool_type } => {
                let mut state = serializer.serialize_struct("ResponseToolChoiceHostedTool", 1)?;
                state.serialize_field("type", tool_type)?;
                state.end()
            }
            Self::Function { name } => {
                let mut state = serializer.serialize_struct("ResponseToolChoiceFunction", 2)?;
                state.serialize_field("type", "function")?;
                state.serialize_field("name", name)?;
                state.end()
            }
            Self::Custom { name } => {
                let mut state = serializer.serialize_struct("ResponseToolChoiceCustom", 2)?;
                state.serialize_field("type", "custom")?;
                state.serialize_field("name", name)?;
                state.end()
            }
            Self::Mcp { server_label, name } => {
                let mut state = serializer
                    .serialize_struct("ResponseToolChoiceMcp", 2 + usize::from(name.is_some()))?;
                state.serialize_field("type", "mcp")?;
                state.serialize_field("server_label", server_label)?;
                if let Some(name) = name {
                    state.serialize_field("name", name)?;
                }
                state.end()
            }
            Self::ApplyPatch => {
                let mut state = serializer.serialize_struct("ResponseToolChoiceApplyPatch", 1)?;
                state.serialize_field("type", "apply_patch")?;
                state.end()
            }
            Self::Shell => {
                let mut state = serializer.serialize_struct("ResponseToolChoiceShell", 1)?;
                state.serialize_field("type", "shell")?;
                state.end()
            }
            Self::AllowedTools { mode, tools } => {
                let mut state = serializer.serialize_struct("ResponseToolChoiceAllowedTools", 3)?;
                state.serialize_field("type", "allowed_tools")?;
                state.serialize_field("mode", mode)?;
                state.serialize_field("tools", tools)?;
                state.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for ResponseToolChoice {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct ObjectToolChoice {
            #[serde(rename = "type")]
            tool_type: String,
            name: Option<String>,
            server_label: Option<String>,
            mode: Option<ResponseAllowedToolsMode>,
            tools: Option<Vec<Value>>,
        }

        let value = Value::deserialize(deserializer)?;
        if let Some(value) = value.as_str() {
            return match value {
                "none" => Ok(Self::None),
                "auto" => Ok(Self::Auto),
                "required" => Ok(Self::Required),
                other => Err(serde::de::Error::unknown_variant(
                    other,
                    &["none", "auto", "required"],
                )),
            };
        }
        let object = ObjectToolChoice::deserialize(value).map_err(serde::de::Error::custom)?;
        if object.tool_type == "function" {
            let name = object
                .name
                .ok_or_else(|| serde::de::Error::missing_field("name"))?;
            return Ok(Self::Function { name });
        }
        if object.tool_type == "custom" {
            let name = object
                .name
                .ok_or_else(|| serde::de::Error::missing_field("name"))?;
            return Ok(Self::Custom { name });
        }
        if object.tool_type == "mcp" {
            let server_label = object
                .server_label
                .ok_or_else(|| serde::de::Error::missing_field("server_label"))?;
            return Ok(Self::Mcp {
                server_label,
                name: object.name,
            });
        }
        if object.tool_type == "apply_patch" {
            return Ok(Self::ApplyPatch);
        }
        if object.tool_type == "shell" {
            return Ok(Self::Shell);
        }
        if object.tool_type == "allowed_tools" {
            let mode = object
                .mode
                .ok_or_else(|| serde::de::Error::missing_field("mode"))?;
            let tools = object
                .tools
                .ok_or_else(|| serde::de::Error::missing_field("tools"))?;
            return Ok(Self::AllowedTools { mode, tools });
        }
        if let Some(tool_type) = ResponseHostedToolChoice::from_wire_type(&object.tool_type) {
            return Ok(Self::HostedTool { tool_type });
        }
        Err(serde::de::Error::unknown_variant(
            &object.tool_type,
            &[
                "none",
                "auto",
                "required",
                "file_search",
                "web_search_preview",
                "computer",
                "computer_use_preview",
                "computer_use",
                "web_search_preview_2025_03_11",
                "image_generation",
                "code_interpreter",
                "function",
                "custom",
                "mcp",
                "apply_patch",
                "shell",
                "allowed_tools",
            ],
        ))
    }
}

/// EN: Selection mode for an allowed tools Responses API tool choice.
/// 中文:Responses API allowed tools 工具选择的选择模式。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseAllowedToolsMode {
    /// EN: Allow the model to choose among allowed tools or generate a message.
    /// 中文:允许模型在允许工具中选择,或生成普通消息。
    Auto,
    /// EN: Require the model to call one or more allowed tools.
    /// 中文:要求模型调用一个或多个允许工具。
    Required,
}

/// EN: Built-in hosted tool type for a Responses API tool choice.
/// 中文:Responses API 工具选择使用的内置托管工具类型。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResponseHostedToolChoice {
    /// EN: File search hosted tool.
    /// 中文:文件搜索托管工具。
    #[serde(rename = "file_search")]
    FileSearch,
    /// EN: Web search preview hosted tool.
    /// 中文:网页搜索预览托管工具。
    #[serde(rename = "web_search_preview")]
    WebSearchPreview,
    /// EN: Computer hosted tool.
    /// 中文:计算机托管工具。
    #[serde(rename = "computer")]
    Computer,
    /// EN: Computer use preview hosted tool.
    /// 中文:计算机使用预览托管工具。
    #[serde(rename = "computer_use_preview")]
    ComputerUsePreview,
    /// EN: Computer use hosted tool.
    /// 中文:计算机使用托管工具。
    #[serde(rename = "computer_use")]
    ComputerUse,
    /// EN: Versioned web search preview hosted tool.
    /// 中文:带版本的网页搜索预览托管工具。
    #[serde(rename = "web_search_preview_2025_03_11")]
    WebSearchPreview2025_03_11,
    /// EN: Image generation hosted tool.
    /// 中文:图像生成托管工具。
    #[serde(rename = "image_generation")]
    ImageGeneration,
    /// EN: Code interpreter hosted tool.
    /// 中文:代码解释器托管工具。
    #[serde(rename = "code_interpreter")]
    CodeInterpreter,
}

impl ResponseHostedToolChoice {
    fn from_wire_type(value: &str) -> Option<Self> {
        match value {
            "file_search" => Some(Self::FileSearch),
            "web_search_preview" => Some(Self::WebSearchPreview),
            "computer" => Some(Self::Computer),
            "computer_use_preview" => Some(Self::ComputerUsePreview),
            "computer_use" => Some(Self::ComputerUse),
            "web_search_preview_2025_03_11" => Some(Self::WebSearchPreview2025_03_11),
            "image_generation" => Some(Self::ImageGeneration),
            "code_interpreter" => Some(Self::CodeInterpreter),
            _ => None,
        }
    }
}

/// EN: Reasoning configuration for reasoning-capable Responses API models.
/// 中文:Responses API 中支持推理模型的推理配置。
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResponseReasoning {
    /// EN: Optional effort level for reasoning tokens.
    /// 中文:推理 token 的可选努力等级。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effort: Option<ResponseReasoningEffort>,
    /// EN: Optional summary mode for the model's reasoning.
    /// 中文:模型推理过程的可选摘要模式。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<ResponseReasoningSummary>,
}

impl ResponseReasoning {
    /// EN: Starts building reasoning configuration.
    /// 中文:开始构建推理配置。
    pub fn builder() -> ResponseReasoningBuilder {
        ResponseReasoningBuilder::default()
    }
}

/// EN: Builder for Responses API reasoning configuration.
/// 中文:Responses API 推理配置的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct ResponseReasoningBuilder {
    effort: Option<ResponseReasoningEffort>,
    summary: Option<ResponseReasoningSummary>,
}

impl ResponseReasoningBuilder {
    /// EN: Sets the reasoning effort level.
    /// 中文:设置推理努力等级。
    pub fn effort(mut self, effort: ResponseReasoningEffort) -> Self {
        self.effort = Some(effort);
        self
    }

    /// EN: Sets the reasoning summary mode.
    /// 中文:设置推理摘要模式。
    pub fn summary(mut self, summary: ResponseReasoningSummary) -> Self {
        self.summary = Some(summary);
        self
    }

    /// EN: Builds the reasoning configuration.
    /// 中文:构建推理配置。
    pub fn build(self) -> ResponseReasoning {
        ResponseReasoning {
            effort: self.effort,
            summary: self.summary,
        }
    }
}

/// EN: Effort level for reasoning-capable models.
/// 中文:支持推理模型的努力等级。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseReasoningEffort {
    /// EN: Disable reasoning when the selected model supports it.
    /// 中文:在所选模型支持时禁用推理。
    None,
    /// EN: Use minimal reasoning effort.
    /// 中文:使用最小推理努力。
    Minimal,
    /// EN: Use low reasoning effort.
    /// 中文:使用低推理努力。
    Low,
    /// EN: Use medium reasoning effort.
    /// 中文:使用中等推理努力。
    Medium,
    /// EN: Use high reasoning effort.
    /// 中文:使用高推理努力。
    High,
    /// EN: Use extra-high reasoning effort when supported.
    /// 中文:在支持时使用超高推理努力。
    #[serde(rename = "xhigh")]
    XHigh,
}

/// EN: Summary mode for reasoning output.
/// 中文:推理输出的摘要模式。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseReasoningSummary {
    /// EN: Let the API choose the reasoning summary mode.
    /// 中文:让 API 选择推理摘要模式。
    Auto,
    /// EN: Request a concise reasoning summary.
    /// 中文:请求简洁的推理摘要。
    Concise,
    /// EN: Request a detailed reasoning summary.
    /// 中文:请求详细的推理摘要。
    Detailed,
}

/// EN: Service tier used to serve a Responses API request.
/// 中文:用于处理 Responses API 请求的服务层级。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseServiceTier {
    /// EN: Use the project-configured service tier, defaulting to standard processing.
    /// 中文:使用项目配置的服务层级,默认使用标准处理。
    Auto,
    /// EN: Use standard pricing and performance for the selected model.
    /// 中文:对所选模型使用标准价格和性能。
    Default,
    /// EN: Use flex processing when available for the request.
    /// 中文:在请求可用时使用 flex 处理。
    Flex,
    /// EN: Use priority processing when available for the request.
    /// 中文:在请求可用时使用 priority 处理。
    Priority,
}

/// EN: Retention policy for prompt cache entries created by a Responses API request.
/// 中文:Responses API 请求创建的提示缓存条目的保留策略。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResponsePromptCacheRetention {
    /// EN: Keep the cached prefix in memory only.
    /// 中文:仅在内存中保留缓存前缀。
    #[serde(rename = "in_memory")]
    InMemory,
    /// EN: Keep cached prefixes active for up to 24 hours where supported.
    /// 中文:在支持时让缓存前缀最多保持 24 小时活跃。
    #[serde(rename = "24h")]
    TwentyFourHours,
}

/// EN: Request body for `POST /v1/responses/input_tokens`.
/// 中文:`POST /v1/responses/input_tokens` 的请求体。
#[derive(Clone, Debug, Default, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateResponseInputTokensRequest {
    /// EN: Optional model id used for token accounting.
    /// 中文:用于 token 计数的可选模型 ID。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// EN: Optional response input to count.
    /// 中文:要计数的可选响应输入。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input: Option<ResponseInput>,
    /// EN: Optional system or developer instructions.
    /// 中文:可选的系统或开发者指令。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instructions: Option<String>,
    /// EN: Optional previous response id for conversation state.
    /// 中文:用于会话状态的可选上一条响应 ID。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub previous_response_id: Option<String>,
    /// EN: Optional text configuration used for token accounting.
    /// 中文:用于 token 计数的可选文本配置。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<ResponseTextConfig>,
    /// EN: Forward-compatible optional fields not yet covered by handwritten types.
    /// 中文:手写类型尚未覆盖的前向兼容可选字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl CreateResponseInputTokensRequest {
    /// EN: Starts building an input-token count request.
    /// 中文:开始构建输入 token 计数请求。
    pub fn builder() -> CreateResponseInputTokensRequestBuilder {
        CreateResponseInputTokensRequestBuilder::default()
    }
}

/// EN: Builder for input-token count requests.
/// 中文:输入 token 计数请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateResponseInputTokensRequestBuilder {
    model: Option<String>,
    input: Option<ResponseInput>,
    instructions: Option<String>,
    previous_response_id: Option<String>,
    text: Option<ResponseTextConfig>,
    extra: BTreeMap<String, Value>,
}

impl CreateResponseInputTokensRequestBuilder {
    /// EN: Sets the optional model id.
    /// 中文:设置可选模型 ID。
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// EN: Sets the optional input value.
    /// 中文:设置可选输入值。
    pub fn input(mut self, input: impl Into<ResponseInput>) -> Self {
        self.input = Some(input.into());
        self
    }

    /// EN: Sets optional system or developer instructions.
    /// 中文:设置可选系统或开发者指令。
    pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
        self.instructions = Some(instructions.into());
        self
    }

    /// EN: Sets the optional previous response id.
    /// 中文:设置可选上一条响应 ID。
    pub fn previous_response_id(mut self, previous_response_id: impl Into<String>) -> Self {
        self.previous_response_id = Some(previous_response_id.into());
        self
    }

    /// EN: Sets optional text configuration.
    /// 中文:设置可选文本配置。
    pub fn text(mut self, text: ResponseTextConfig) -> Self {
        self.text = Some(text);
        self
    }

    /// EN: Adds a forward-compatible JSON field.
    /// 中文:添加前向兼容的 JSON 字段。
    pub fn extra(mut self, name: impl Into<String>, value: Value) -> Self {
        self.extra.insert(name.into(), value);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateResponseInputTokensRequest, LingerError> {
        validate_optional_string("model", self.model.as_deref())?;
        validate_optional_string("instructions", self.instructions.as_deref())?;
        validate_optional_string("previous_response_id", self.previous_response_id.as_deref())?;
        if self.input.is_none() && self.extra.is_empty() {
            return Err(LingerError::invalid_config("input is required"));
        }
        if let Some(text) = &self.text {
            validate_text_config(text)?;
        }
        validate_extra_fields(&self.extra)?;
        Ok(CreateResponseInputTokensRequest {
            model: self.model,
            input: self.input,
            instructions: self.instructions,
            previous_response_id: self.previous_response_id,
            text: self.text,
            extra: self.extra,
        })
    }
}

/// EN: Request body for `POST /v1/responses/compact`.
/// 中文:`POST /v1/responses/compact` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CompactResponseRequest {
    /// EN: Model id used for compaction.
    /// 中文:用于压缩上下文的模型 ID。
    pub model: String,
    /// EN: Optional input to compact.
    /// 中文:要压缩的可选输入。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input: Option<ResponseInput>,
    /// EN: Optional system or developer instructions.
    /// 中文:可选的系统或开发者指令。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instructions: Option<String>,
    /// EN: Optional previous response id for conversation state.
    /// 中文:用于会话状态的可选上一条响应 ID。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub previous_response_id: Option<String>,
    /// EN: Forward-compatible optional fields not yet covered by handwritten types.
    /// 中文:手写类型尚未覆盖的前向兼容可选字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl CompactResponseRequest {
    /// EN: Starts building a response compaction request.
    /// 中文:开始构建响应压缩请求。
    pub fn builder() -> CompactResponseRequestBuilder {
        CompactResponseRequestBuilder::default()
    }
}

/// EN: Builder for response compaction requests.
/// 中文:响应压缩请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CompactResponseRequestBuilder {
    model: Option<String>,
    input: Option<ResponseInput>,
    instructions: Option<String>,
    previous_response_id: Option<String>,
    extra: BTreeMap<String, Value>,
}

impl CompactResponseRequestBuilder {
    /// EN: Sets the model id.
    /// 中文:设置模型 ID。
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// EN: Sets optional input.
    /// 中文:设置可选输入。
    pub fn input(mut self, input: impl Into<ResponseInput>) -> Self {
        self.input = Some(input.into());
        self
    }

    /// EN: Sets optional system or developer instructions.
    /// 中文:设置可选系统或开发者指令。
    pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
        self.instructions = Some(instructions.into());
        self
    }

    /// EN: Sets the optional previous response id.
    /// 中文:设置可选上一条响应 ID。
    pub fn previous_response_id(mut self, previous_response_id: impl Into<String>) -> Self {
        self.previous_response_id = Some(previous_response_id.into());
        self
    }

    /// EN: Adds a forward-compatible JSON field.
    /// 中文:添加前向兼容的 JSON 字段。
    pub fn extra(mut self, name: impl Into<String>, value: Value) -> Self {
        self.extra.insert(name.into(), value);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CompactResponseRequest, LingerError> {
        let model = self
            .model
            .filter(|value| !value.trim().is_empty())
            .ok_or_else(|| LingerError::invalid_config("model is required"))?;
        validate_optional_string("instructions", self.instructions.as_deref())?;
        validate_optional_string("previous_response_id", self.previous_response_id.as_deref())?;
        validate_extra_fields(&self.extra)?;
        Ok(CompactResponseRequest {
            model,
            input: self.input,
            instructions: self.instructions,
            previous_response_id: self.previous_response_id,
            extra: self.extra,
        })
    }
}

/// EN: Responses API input value.
/// 中文:Responses API 输入值。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[serde(untagged)]
#[non_exhaustive]
pub enum ResponseInput {
    /// EN: Plain text input.
    /// 中文:纯文本输入。
    Text(String),
    /// EN: Structured input messages.
    /// 中文:结构化输入消息。
    Messages(Vec<ResponseInputMessage>),
}

impl From<&str> for ResponseInput {
    fn from(value: &str) -> Self {
        Self::Text(value.to_string())
    }
}

impl From<String> for ResponseInput {
    fn from(value: String) -> Self {
        Self::Text(value)
    }
}

impl From<Vec<ResponseInputMessage>> for ResponseInput {
    fn from(value: Vec<ResponseInputMessage>) -> Self {
        Self::Messages(value)
    }
}

/// EN: Structured input message.
/// 中文:结构化输入消息。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseInputMessage {
    /// EN: Message role.
    /// 中文:消息角色。
    pub role: String,
    /// EN: Message content.
    /// 中文:消息内容。
    pub content: Vec<ResponseInputMessageContent>,
}

/// EN: Structured input message content.
/// 中文:结构化输入消息内容。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[serde(tag = "type")]
#[non_exhaustive]
pub enum ResponseInputMessageContent {
    /// EN: Input text content.
    /// 中文:输入文本内容。
    #[serde(rename = "input_text")]
    InputText {
        /// EN: Text content.
        /// 中文:文本内容。
        text: String,
    },
}

/// EN: Text output configuration.
/// 中文:文本输出配置。
#[derive(Clone, Debug, Default, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseTextConfig {
    /// EN: Optional text format configuration.
    /// 中文:可选的文本格式配置。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<ResponseTextFormat>,
    /// EN: Optional output verbosity.
    /// 中文:可选的输出详细程度。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verbosity: Option<ResponseTextVerbosity>,
}

impl ResponseTextConfig {
    /// EN: Sets the text output format.
    /// 中文:设置文本输出格式。
    pub fn format(mut self, format: impl Into<ResponseTextFormat>) -> Self {
        self.format = Some(format.into());
        self
    }

    /// EN: Sets the text output verbosity.
    /// 中文:设置文本输出详细程度。
    pub fn verbosity(mut self, verbosity: ResponseTextVerbosity) -> Self {
        self.verbosity = Some(verbosity);
        self
    }
}

/// EN: Text output format configuration.
/// 中文:文本输出格式配置。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[serde(tag = "type")]
#[non_exhaustive]
pub enum ResponseTextFormat {
    /// EN: Plain text output.
    /// 中文:纯文本输出。
    #[serde(rename = "text")]
    Text,
    /// EN: JSON object output.
    /// 中文:JSON 对象输出。
    #[serde(rename = "json_object")]
    JsonObject,
    /// EN: JSON Schema structured output.
    /// 中文:JSON Schema 结构化输出。
    #[serde(rename = "json_schema")]
    JsonSchema {
        /// EN: Response format name.
        /// 中文:响应格式名称。
        name: String,
        /// EN: JSON schema the model output should match.
        /// 中文:模型输出应匹配的 JSON schema。
        schema: Value,
        /// EN: Optional schema description.
        /// 中文:可选的 schema 描述。
        #[serde(skip_serializing_if = "Option::is_none")]
        description: Option<String>,
        /// EN: Whether to enable strict schema adherence.
        /// 中文:是否启用严格 schema 遵循。
        #[serde(skip_serializing_if = "Option::is_none")]
        strict: Option<bool>,
    },
}

impl ResponseTextFormat {
    /// EN: Starts a JSON Schema text format configuration.
    /// 中文:开始构建 JSON Schema 文本格式配置。
    pub fn json_schema(name: impl Into<String>, schema: Value) -> ResponseTextJsonSchemaFormat {
        ResponseTextJsonSchemaFormat::new(name, schema)
    }
}

/// EN: Builder value for JSON Schema structured text output.
/// 中文:JSON Schema 结构化文本输出的构建值。
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct ResponseTextJsonSchemaFormat {
    /// EN: Response format name.
    /// 中文:响应格式名称。
    pub name: String,
    /// EN: JSON schema the model output should match.
    /// 中文:模型输出应匹配的 JSON schema。
    pub schema: Value,
    /// EN: Optional schema description.
    /// 中文:可选的 schema 描述。
    pub description: Option<String>,
    /// EN: Whether to enable strict schema adherence.
    /// 中文:是否启用严格 schema 遵循。
    pub strict: Option<bool>,
}

impl ResponseTextJsonSchemaFormat {
    /// EN: Creates a JSON Schema text format configuration.
    /// 中文:创建 JSON Schema 文本格式配置。
    pub fn new(name: impl Into<String>, schema: Value) -> Self {
        Self {
            name: name.into(),
            schema,
            description: None,
            strict: None,
        }
    }

    /// EN: Sets the schema description.
    /// 中文:设置 schema 描述。
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// EN: Sets strict schema adherence.
    /// 中文:设置严格 schema 遵循。
    pub fn strict(mut self, strict: bool) -> Self {
        self.strict = Some(strict);
        self
    }
}

impl From<ResponseTextJsonSchemaFormat> for ResponseTextFormat {
    fn from(format: ResponseTextJsonSchemaFormat) -> Self {
        Self::JsonSchema {
            name: format.name,
            schema: format.schema,
            description: format.description,
            strict: format.strict,
        }
    }
}

/// EN: Text output verbosity.
/// 中文:文本输出详细程度。
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseTextVerbosity {
    /// EN: Low verbosity.
    /// 中文:低详细程度。
    Low,
    /// EN: Medium verbosity.
    /// 中文:中等详细程度。
    Medium,
    /// EN: High verbosity.
    /// 中文:高详细程度。
    High,
}

/// EN: Options for streaming Responses API requests.
/// 中文:Responses API 流式请求的选项。
#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct StreamOptions {
    /// EN: Whether to include obfuscation padding fields in streaming delta events.
    /// 中文:是否在流式增量事件中包含混淆填充字段。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_obfuscation: Option<bool>,
}

impl StreamOptions {
    /// EN: Starts building stream options.
    /// 中文:开始构建流选项。
    pub fn builder() -> StreamOptionsBuilder {
        StreamOptionsBuilder::default()
    }
}

/// EN: Builder for Responses API stream options.
/// 中文:Responses API 流选项的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct StreamOptionsBuilder {
    include_obfuscation: Option<bool>,
}

impl StreamOptionsBuilder {
    /// EN: Sets whether streaming delta events include obfuscation padding fields.
    /// 中文:设置流式增量事件是否包含混淆填充字段。
    pub fn include_obfuscation(mut self, include_obfuscation: bool) -> Self {
        self.include_obfuscation = Some(include_obfuscation);
        self
    }

    /// EN: Builds the stream options.
    /// 中文:构建流选项。
    pub fn build(self) -> StreamOptions {
        StreamOptions {
            include_obfuscation: self.include_obfuscation,
        }
    }
}

/// EN: Response object returned by the Responses API.
/// 中文:Responses API 返回的响应对象。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct Response {
    /// EN: Response id.
    /// 中文:响应 ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Model that produced the response.
    /// 中文:生成响应的模型。
    pub model: String,
    /// EN: Output items returned by the model.
    /// 中文:模型返回的输出项。
    #[serde(default)]
    pub output: Vec<ResponseOutput>,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl Response {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }

    /// EN: Concatenates text from `output_text` content items.
    /// 中文:拼接 `output_text` 内容项中的文本。
    pub fn output_text(&self) -> String {
        let mut text = String::new();
        for item in &self.output {
            if let ResponseOutput::Message(message) = item {
                for content in &message.content {
                    if let ResponseContent::OutputText { text: value, .. } = content {
                        text.push_str(value);
                    }
                }
            }
        }
        text
    }
}

/// EN: Input-token count returned by `POST /v1/responses/input_tokens`.
/// 中文:`POST /v1/responses/input_tokens` 返回的输入 token 计数。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResponseInputTokens {
    /// EN: API object type, normally `response.input_tokens`.
    /// 中文:API 对象类型,通常为 `response.input_tokens`。
    pub object: String,
    /// EN: Count of input tokens.
    /// 中文:输入 token 数量。
    pub input_tokens: u64,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl ResponseInputTokens {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Compacted response object returned by `POST /v1/responses/compact`.
/// 中文:`POST /v1/responses/compact` 返回的压缩响应对象。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseCompaction {
    /// EN: Compacted response id.
    /// 中文:压缩响应 ID。
    pub id: String,
    /// EN: API object type, normally `response.compaction`.
    /// 中文:API 对象类型,通常为 `response.compaction`。
    pub object: String,
    /// EN: Unix timestamp when the compacted response was created.
    /// 中文:压缩响应创建时的 Unix 时间戳。
    pub created_at: u64,
    /// EN: Compacted output items preserved as JSON for forward compatibility.
    /// 中文:以 JSON 形式保留的压缩输出项,用于前向兼容。
    #[serde(default)]
    pub output: Vec<Value>,
    /// EN: Token usage for the compaction pass.
    /// 中文:压缩过程的 token 用量。
    pub usage: ResponseUsage,
    /// EN: Additional fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl ResponseCompaction {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Token usage returned by Responses endpoints.
/// 中文:Responses 端点返回的 token 用量。
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResponseUsage {
    /// EN: Input token count.
    /// 中文:输入 token 数量。
    pub input_tokens: u64,
    /// EN: Output token count.
    /// 中文:输出 token 数量。
    pub output_tokens: u64,
    /// EN: Total token count.
    /// 中文:总 token 数量。
    pub total_tokens: u64,
    /// EN: Input token detail fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的输入 token 详情字段。
    #[serde(default)]
    pub input_tokens_details: BTreeMap<String, Value>,
    /// EN: Output token detail fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的输出 token 详情字段。
    #[serde(default)]
    pub output_tokens_details: BTreeMap<String, Value>,
    /// EN: Additional usage fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外用量字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

/// EN: Deletion result returned by the Responses API.
/// 中文:Responses API 返回的删除结果。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResponseDeletion {
    /// EN: Deleted response id.
    /// 中文:已删除的响应 ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Whether the response was deleted.
    /// 中文:响应是否已删除。
    pub deleted: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl ResponseDeletion {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Paginated input items returned by the Responses API.
/// 中文:Responses API 返回的分页输入项。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseInputItemsPage {
    /// EN: API list object type.
    /// 中文:API 列表对象类型。
    pub object: String,
    /// EN: Input items on this page.
    /// 中文:本页输入项。
    #[serde(default)]
    pub data: Vec<ResponseInputItem>,
    /// EN: First item id on this page.
    /// 中文:本页第一个项目 ID。
    #[serde(default)]
    pub first_id: Option<String>,
    /// EN: Last item id on this page.
    /// 中文:本页最后一个项目 ID。
    #[serde(default)]
    pub last_id: Option<String>,
    /// EN: Whether more items are available.
    /// 中文:是否还有更多项目。
    pub has_more: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl ResponseInputItemsPage {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Response input item.
/// 中文:响应输入项。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(tag = "type")]
#[non_exhaustive]
pub enum ResponseInputItem {
    /// EN: Message input item.
    /// 中文:消息输入项。
    #[serde(rename = "message")]
    Message(ResponseInputItemMessage),
    /// EN: Forward-compatible unknown input item.
    /// 中文:前向兼容的未知输入项。
    #[serde(other)]
    Unknown,
}

/// EN: Message input item returned by the Responses API.
/// 中文:Responses API 返回的消息输入项。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseInputItemMessage {
    /// EN: Input item id.
    /// 中文:输入项 ID。
    pub id: String,
    /// EN: Message role.
    /// 中文:消息角色。
    pub role: String,
    /// EN: Message content.
    /// 中文:消息内容。
    #[serde(default)]
    pub content: Vec<ResponseInputItemContent>,
}

impl ResponseInputItemMessage {
    /// EN: Concatenates `input_text` content.
    /// 中文:拼接 `input_text` 内容。
    pub fn input_text(&self) -> String {
        let mut text = String::new();
        for content in &self.content {
            if let ResponseInputItemContent::InputText { text: value, .. } = content {
                text.push_str(value);
            }
        }
        text
    }
}

/// EN: Input item message content.
/// 中文:输入项消息内容。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(tag = "type")]
#[non_exhaustive]
pub enum ResponseInputItemContent {
    /// EN: Input text content.
    /// 中文:输入文本内容。
    #[serde(rename = "input_text")]
    InputText {
        /// EN: Text content.
        /// 中文:文本内容。
        text: String,
        /// EN: Additional fields preserved for forward compatibility.
        /// 中文:为前向兼容保留的额外字段。
        #[serde(flatten)]
        extra: BTreeMap<String, Value>,
    },
    /// EN: Forward-compatible unknown content item.
    /// 中文:前向兼容的未知内容项。
    #[serde(other)]
    Unknown,
}

/// EN: Response output item.
/// 中文:响应输出项。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(tag = "type")]
#[non_exhaustive]
pub enum ResponseOutput {
    /// EN: Assistant message output.
    /// 中文:助手消息输出。
    #[serde(rename = "message")]
    Message(ResponseOutputMessage),
    /// EN: Forward-compatible unknown output item.
    /// 中文:前向兼容的未知输出项。
    #[serde(other)]
    Unknown,
}

/// EN: Assistant message output item.
/// 中文:助手消息输出项。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ResponseOutputMessage {
    /// EN: Output item id.
    /// 中文:输出项 ID。
    pub id: String,
    /// EN: Message role.
    /// 中文:消息角色。
    pub role: String,
    /// EN: Message content.
    /// 中文:消息内容。
    #[serde(default)]
    pub content: Vec<ResponseContent>,
}

/// EN: Response message content.
/// 中文:响应消息内容。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(tag = "type")]
#[non_exhaustive]
pub enum ResponseContent {
    /// EN: Output text content.
    /// 中文:输出文本内容。
    #[serde(rename = "output_text")]
    OutputText {
        /// EN: Text content.
        /// 中文:文本内容。
        text: String,
        /// EN: Additional fields preserved for forward compatibility.
        /// 中文:为前向兼容保留的额外字段。
        #[serde(flatten)]
        extra: BTreeMap<String, Value>,
    },
    /// EN: Forward-compatible unknown content item.
    /// 中文:前向兼容的未知内容项。
    #[serde(other)]
    Unknown,
}

/// EN: Typed Responses streaming event.
/// 中文:类型化的 Responses 流式事件。
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum ResponseStreamEvent {
    /// EN: Incremental output text delta.
    /// 中文:增量输出文本片段。
    OutputTextDelta {
        /// EN: Delta text.
        /// 中文:文本增量。
        delta: String,
    },
    /// EN: Completed response event.
    /// 中文:响应完成事件。
    Completed {
        /// EN: Completed response.
        /// 中文:已完成的响应。
        response: Response,
    },
    /// EN: Forward-compatible unknown event.
    /// 中文:前向兼容的未知事件。
    Unknown {
        /// EN: Event type.
        /// 中文:事件类型。
        event_type: String,
        /// EN: Raw JSON data.
        /// 中文:原始 JSON 数据。
        data: Value,
    },
}

/// EN: Streaming item with typed and raw event access.
/// 中文:同时提供类型化和原始事件访问的流式项。
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct ResponseStreamItem {
    /// EN: Typed event.
    /// 中文:类型化事件。
    pub event: ResponseStreamEvent,
    /// EN: Raw SSE frame.
    /// 中文:原始 SSE 帧。
    pub raw: SseEvent,
}

impl ResponseStreamItem {
    /// EN: Returns the event type.
    /// 中文:返回事件类型。
    pub fn event_type(&self) -> &str {
        self.raw.event_type.as_deref().unwrap_or("")
    }

    /// EN: Returns output text delta when this is a delta event.
    /// 中文:当事件为文本增量时返回输出文本增量。
    pub fn output_text_delta(&self) -> Option<&str> {
        match &self.event {
            ResponseStreamEvent::OutputTextDelta { delta } => Some(delta),
            _ => None,
        }
    }
}

/// EN: Incremental Responses stream.
/// 中文:增量 Responses 流。
pub struct ResponseStream {
    inner: SseStream,
}

impl ResponseStream {
    /// EN: Creates a response stream from an HTTP body stream.
    /// 中文:通过 HTTP 响应体流创建响应流。
    pub fn new(body: BodyStream) -> Self {
        Self {
            inner: SseStream::new(body),
        }
    }
}

impl Stream for ResponseStream {
    type Item = Result<ResponseStreamItem, LingerError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        match Pin::new(&mut this.inner).poll_next(cx) {
            Poll::Ready(Some(Ok(raw))) => Poll::Ready(Some(parse_response_event(raw))),
            Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))),
            Poll::Ready(None) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }
}

fn parse_response_event(raw: SseEvent) -> Result<ResponseStreamItem, LingerError> {
    let event_type = raw.event_type.clone().unwrap_or_default();
    let value: Value = serde_json::from_str(&raw.data).map_err(|error| {
        LingerError::streaming(format!("invalid response stream JSON: {error}"))
    })?;
    let event = match event_type.as_str() {
        "response.output_text.delta" => {
            let delta = value
                .get("delta")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_string();
            ResponseStreamEvent::OutputTextDelta { delta }
        }
        "response.completed" => {
            let response = value.get("response").cloned().ok_or_else(|| {
                LingerError::streaming("response.completed event is missing response")
            })?;
            let response = serde_json::from_value(response).map_err(|error| {
                LingerError::streaming(format!("invalid completed response: {error}"))
            })?;
            ResponseStreamEvent::Completed { response }
        }
        _ => ResponseStreamEvent::Unknown {
            event_type,
            data: value,
        },
    };
    Ok(ResponseStreamItem { event, raw })
}

fn validate_optional_string(name: &str, value: Option<&str>) -> Result<(), LingerError> {
    if value.is_some_and(|value| value.trim().is_empty()) {
        return Err(LingerError::invalid_config(format!(
            "{name} must not be empty"
        )));
    }
    Ok(())
}

fn validate_metadata(metadata: &BTreeMap<String, String>) -> Result<(), LingerError> {
    if metadata.len() > 16 {
        return Err(LingerError::invalid_config(
            "metadata must contain at most 16 entries",
        ));
    }
    for (key, value) in metadata {
        if key.trim().is_empty() {
            return Err(LingerError::invalid_config(
                "metadata keys must not be empty",
            ));
        }
        if key.chars().count() > 64 {
            return Err(LingerError::invalid_config(
                "metadata keys must be at most 64 characters",
            ));
        }
        if value.chars().count() > 512 {
            return Err(LingerError::invalid_config(
                "metadata values must be at most 512 characters",
            ));
        }
    }
    Ok(())
}

fn validate_json_items(name: &str, values: &[Value]) -> Result<(), LingerError> {
    if values.iter().any(Value::is_null) {
        return Err(LingerError::invalid_config(format!(
            "{name} must not contain null"
        )));
    }
    Ok(())
}

fn validate_tools(tools: &[Value]) -> Result<(), LingerError> {
    validate_json_items("tools", tools)?;
    for tool in tools {
        let Some(object) = tool.as_object() else {
            continue;
        };
        match object.get("type").and_then(Value::as_str) {
            Some("function") => validate_function_tool(object)?,
            Some("custom") => validate_custom_tool(object)?,
            Some("namespace") => validate_namespace_tool(object)?,
            Some("tool_search") => validate_tool_search_tool(object)?,
            Some("shell") => validate_shell_tool(object)?,
            Some("file_search") => validate_file_search_tool(object)?,
            Some("computer_use_preview") => validate_computer_use_preview_tool(object)?,
            Some("code_interpreter") => validate_code_interpreter_tool(object)?,
            Some("image_generation") => validate_image_generation_tool(object)?,
            Some("mcp") => validate_mcp_tool(object)?,
            Some(
                "web_search"
                | "web_search_2025_08_26"
                | "web_search_preview"
                | "web_search_preview_2025_03_11",
            ) => validate_web_search_tool(object)?,
            _ => {}
        }
    }
    Ok(())
}

fn validate_custom_tool(object: &serde_json::Map<String, Value>) -> Result<(), LingerError> {
    let name = object
        .get("name")
        .and_then(Value::as_str)
        .unwrap_or_default();
    validate_optional_string("custom tool name", Some(name))?;
    validate_optional_string(
        "custom tool description",
        object.get("description").and_then(Value::as_str),
    )?;
    if let Some(description) = object.get("description") {
        if !description.is_string() {
            return Err(LingerError::invalid_config(
                "custom tool description must be a string",
            ));
        }
    }
    if let Some(defer_loading) = object.get("defer_loading") {
        if !defer_loading.is_boolean() {
            return Err(LingerError::invalid_config(
                "custom tool defer_loading must be a boolean",
            ));
        }
    }
    if let Some(format) = object.get("format") {
        validate_custom_tool_format(format)?;
    }
    Ok(())
}

fn validate_custom_tool_format(format: &Value) -> Result<(), LingerError> {
    let Some(format) = format.as_object() else {
        return Err(LingerError::invalid_config(
            "custom tool format must be a JSON object",
        ));
    };
    match format.get("type").and_then(Value::as_str) {
        Some("text") => Ok(()),
        Some("grammar") => {
            let syntax = format
                .get("syntax")
                .and_then(Value::as_str)
                .ok_or_else(|| {
                    LingerError::invalid_config("custom tool grammar format must include syntax")
                })?;
            if !matches!(syntax, "lark" | "regex") {
                return Err(LingerError::invalid_config(
                    "custom tool grammar syntax has an unsupported value",
                ));
            }
            let definition = format
                .get("definition")
                .and_then(Value::as_str)
                .unwrap_or_default();
            validate_optional_string("custom tool grammar definition", Some(definition))
        }
        _ => Err(LingerError::invalid_config(
            "custom tool format type has an unsupported value",
        )),
    }
}

fn validate_tool_search_tool(object: &serde_json::Map<String, Value>) -> Result<(), LingerError> {
    if let Some(execution) = object.get("execution") {
        let Some(execution) = execution.as_str() else {
            return Err(LingerError::invalid_config(
                "tool_search execution must be a string",
            ));
        };
        if !matches!(execution, "server" | "client") {
            return Err(LingerError::invalid_config(
                "tool_search execution has an unsupported value",
            ));
        }
    }
    if let Some(description) = object.get("description") {
        if !(description.is_string() || description.is_null()) {
            return Err(LingerError::invalid_config(
                "tool_search description must be a string or null",
            ));
        }
        if let Some(description) = description.as_str() {
            validate_optional_string("tool_search description", Some(description))?;
        }
    }
    if let Some(parameters) = object.get("parameters") {
        if !(parameters.is_object() || parameters.is_null()) {
            return Err(LingerError::invalid_config(
                "tool_search parameters must be a JSON object or null",
            ));
        }
    }
    Ok(())
}

fn validate_shell_tool(object: &serde_json::Map<String, Value>) -> Result<(), LingerError> {
    let Some(environment) = object.get("environment") else {
        return Ok(());
    };
    if environment.is_null() {
        return Ok(());
    }
    let Some(environment) = environment.as_object() else {
        return Err(LingerError::invalid_config(
            "shell environment must be a JSON object or null",
        ));
    };
    match environment.get("type").and_then(Value::as_str) {
        Some("local" | "container_auto") => Ok(()),
        Some("container_reference") => {
            let container_id = environment
                .get("container_id")
                .and_then(Value::as_str)
                .unwrap_or_default();
            validate_optional_string("shell container_id", Some(container_id))
        }
        _ => Err(LingerError::invalid_config(
            "shell environment type has an unsupported value",
        )),
    }
}

fn validate_namespace_tool(object: &serde_json::Map<String, Value>) -> Result<(), LingerError> {
    let name = object
        .get("name")
        .and_then(Value::as_str)
        .unwrap_or_default();
    validate_optional_string("namespace tool name", Some(name))?;
    let description = object
        .get("description")
        .and_then(Value::as_str)
        .unwrap_or_default();
    validate_optional_string("namespace tool description", Some(description))?;
    let tools = object
        .get("tools")
        .and_then(Value::as_array)
        .ok_or_else(|| LingerError::invalid_config("namespace tools must include tools"))?;
    if tools.is_empty() {
        return Err(LingerError::invalid_config(
            "namespace tools must not be empty",
        ));
    }
    for tool in tools {
        let Some(tool) = tool.as_object() else {
            return Err(LingerError::invalid_config(
                "namespace tools must contain objects",
            ));
        };
        match tool.get("type").and_then(Value::as_str) {
            Some("function") => validate_namespace_function_tool(tool)?,
            Some("custom") => validate_custom_tool(tool)?,
            _ => {
                return Err(LingerError::invalid_config(
                    "namespace tools may only contain function or custom tools",
                ));
            }
        }
    }
    Ok(())
}

fn validate_namespace_function_tool(
    object: &serde_json::Map<String, Value>,
) -> Result<(), LingerError> {
    let name = object
        .get("name")
        .and_then(Value::as_str)
        .unwrap_or_default();
    validate_optional_string("namespace function tool name", Some(name))?;
    if let Some(description) = object.get("description") {
        if !(description.is_string() || description.is_null()) {
            return Err(LingerError::invalid_config(
                "namespace function tool description must be a string or null",
            ));
        }
    }
    if let Some(parameters) = object.get("parameters") {
        if !(parameters.is_object() || parameters.is_null()) {
            return Err(LingerError::invalid_config(
                "namespace function tool parameters must be a JSON object or null",
            ));
        }
    }
    if let Some(strict) = object.get("strict") {
        if !(strict.is_boolean() || strict.is_null()) {
            return Err(LingerError::invalid_config(
                "namespace function tool strict must be a boolean or null",
            ));
        }
    }
    if let Some(defer_loading) = object.get("defer_loading") {
        if !defer_loading.is_boolean() {
            return Err(LingerError::invalid_config(
                "namespace function tool defer_loading must be a boolean",
            ));
        }
    }
    Ok(())
}

fn validate_computer_use_preview_tool(
    object: &serde_json::Map<String, Value>,
) -> Result<(), LingerError> {
    let environment = object
        .get("environment")
        .and_then(Value::as_str)
        .ok_or_else(|| {
            LingerError::invalid_config("computer_use_preview tools must include environment")
        })?;
    if !matches!(
        environment,
        "windows" | "mac" | "linux" | "ubuntu" | "browser"
    ) {
        return Err(LingerError::invalid_config(
            "computer_use_preview environment has an unsupported value",
        ));
    }

    for field in ["display_width", "display_height"] {
        let value = object.get(field).and_then(Value::as_u64).ok_or_else(|| {
            LingerError::invalid_config(format!(
                "computer_use_preview tools must include integer {field}"
            ))
        })?;
        if value == 0 {
            return Err(LingerError::invalid_config(format!(
                "computer_use_preview {field} must be greater than 0"
            )));
        }
    }
    Ok(())
}

fn validate_function_tool(object: &serde_json::Map<String, Value>) -> Result<(), LingerError> {
    let name = object
        .get("name")
        .and_then(Value::as_str)
        .unwrap_or_default();
    validate_optional_string("tools[].name", Some(name))?;
    let parameters = object
        .get("parameters")
        .ok_or_else(|| LingerError::invalid_config("function tools must include parameters"))?;
    if parameters.is_null() {
        return Err(LingerError::invalid_config(
            "function tool parameters must not be null",
        ));
    }
    if !parameters.is_object() {
        return Err(LingerError::invalid_config(
            "function tool parameters must be a JSON object",
        ));
    }
    if !object.get("strict").is_some_and(Value::is_boolean) {
        return Err(LingerError::invalid_config(
            "function tools must include boolean strict",
        ));
    }
    Ok(())
}

fn validate_file_search_tool(object: &serde_json::Map<String, Value>) -> Result<(), LingerError> {
    let vector_store_ids = object
        .get("vector_store_ids")
        .and_then(Value::as_array)
        .ok_or_else(|| {
            LingerError::invalid_config("file_search tools must include vector_store_ids")
        })?;
    if vector_store_ids.is_empty() {
        return Err(LingerError::invalid_config(
            "file_search vector_store_ids must not be empty",
        ));
    }
    for vector_store_id in vector_store_ids {
        let Some(vector_store_id) = vector_store_id.as_str() else {
            return Err(LingerError::invalid_config(
                "file_search vector_store_ids must contain strings",
            ));
        };
        validate_optional_string("file_search vector_store_ids", Some(vector_store_id))?;
    }
    if let Some(max_num_results) = object.get("max_num_results") {
        let max_num_results = max_num_results.as_u64().ok_or_else(|| {
            LingerError::invalid_config("file_search max_num_results must be an integer")
        })?;
        if !(1..=50).contains(&max_num_results) {
            return Err(LingerError::invalid_config(
                "file_search max_num_results must be between 1 and 50",
            ));
        }
    }
    for field in ["ranking_options", "filters"] {
        if object.get(field).is_some_and(Value::is_null) {
            return Err(LingerError::invalid_config(format!(
                "file_search {field} must not be null"
            )));
        }
    }
    Ok(())
}

fn validate_code_interpreter_tool(
    object: &serde_json::Map<String, Value>,
) -> Result<(), LingerError> {
    let container = object.get("container").ok_or_else(|| {
        LingerError::invalid_config("code_interpreter tools must include container")
    })?;
    if container.is_null() {
        return Err(LingerError::invalid_config(
            "code_interpreter container must not be null",
        ));
    }
    if let Some(container_id) = container.as_str() {
        validate_optional_string("code_interpreter container", Some(container_id))?;
        return Ok(());
    }
    let container = container.as_object().ok_or_else(|| {
        LingerError::invalid_config("code_interpreter container must be a string or object")
    })?;
    let container_type = container
        .get("type")
        .and_then(Value::as_str)
        .unwrap_or_default();
    if container_type != "auto" {
        return Err(LingerError::invalid_config(
            "code_interpreter auto container type must be auto",
        ));
    }
    if let Some(file_ids) = container.get("file_ids") {
        let file_ids = file_ids.as_array().ok_or_else(|| {
            LingerError::invalid_config("code_interpreter file_ids must be an array")
        })?;
        if file_ids.len() > 50 {
            return Err(LingerError::invalid_config(
                "code_interpreter file_ids must contain at most 50 entries",
            ));
        }
        for file_id in file_ids {
            let Some(file_id) = file_id.as_str() else {
                return Err(LingerError::invalid_config(
                    "code_interpreter file_ids must contain strings",
                ));
            };
            validate_optional_string("code_interpreter file_ids", Some(file_id))?;
        }
    }
    if let Some(memory_limit) = container.get("memory_limit") {
        if !memory_limit.is_null() {
            let Some(memory_limit) = memory_limit.as_str() else {
                return Err(LingerError::invalid_config(
                    "code_interpreter memory_limit must be a string",
                ));
            };
            if !matches!(memory_limit, "1g" | "4g" | "16g" | "64g") {
                return Err(LingerError::invalid_config(
                    "code_interpreter memory_limit must be one of 1g, 4g, 16g, or 64g",
                ));
            }
        }
    }
    if let Some(network_policy) = container.get("network_policy") {
        validate_code_interpreter_network_policy(network_policy)?;
    }
    Ok(())
}

fn validate_code_interpreter_network_policy(network_policy: &Value) -> Result<(), LingerError> {
    if network_policy.is_null() {
        return Err(LingerError::invalid_config(
            "code_interpreter network_policy must not be null",
        ));
    }
    let policy = network_policy.as_object().ok_or_else(|| {
        LingerError::invalid_config("code_interpreter network_policy must be a JSON object")
    })?;
    match policy.get("type").and_then(Value::as_str) {
        Some("disabled") => Ok(()),
        Some("allowlist") => {
            if let Some(domains) = policy.get("allowed_domains") {
                let domains = domains.as_array().ok_or_else(|| {
                    LingerError::invalid_config("code_interpreter allowed_domains must be an array")
                })?;
                if domains.is_empty() {
                    return Err(LingerError::invalid_config(
                        "code_interpreter allowed_domains must not be empty",
                    ));
                }
                for domain in domains {
                    let Some(domain) = domain.as_str() else {
                        return Err(LingerError::invalid_config(
                            "code_interpreter allowed_domains must contain strings",
                        ));
                    };
                    validate_optional_string("code_interpreter allowed_domains", Some(domain))?;
                }
            }
            Ok(())
        }
        _ => Err(LingerError::invalid_config(
            "code_interpreter network_policy type must be disabled or allowlist",
        )),
    }
}

fn validate_image_generation_tool(
    object: &serde_json::Map<String, Value>,
) -> Result<(), LingerError> {
    for field in ["model", "size"] {
        if let Some(value) = object.get(field) {
            let Some(value) = value.as_str() else {
                return Err(LingerError::invalid_config(format!(
                    "image_generation {field} must be a string"
                )));
            };
            validate_optional_string(&format!("image_generation {field}"), Some(value))?;
        }
    }
    validate_image_generation_enum(object, "quality", &["low", "medium", "high", "auto"])?;
    validate_image_generation_enum(object, "output_format", &["png", "webp", "jpeg"])?;
    validate_image_generation_enum(object, "moderation", &["auto", "low"])?;
    validate_image_generation_enum(object, "background", &["transparent", "opaque", "auto"])?;
    validate_image_generation_enum(object, "input_fidelity", &["high", "low"])?;
    validate_image_generation_enum(object, "action", &["generate", "edit", "auto"])?;
    if let Some(output_compression) = object.get("output_compression") {
        let output_compression = output_compression.as_u64().ok_or_else(|| {
            LingerError::invalid_config("image_generation output_compression must be an integer")
        })?;
        if output_compression > 100 {
            return Err(LingerError::invalid_config(
                "image_generation output_compression must be between 0 and 100",
            ));
        }
    }
    if let Some(partial_images) = object.get("partial_images") {
        let partial_images = partial_images.as_u64().ok_or_else(|| {
            LingerError::invalid_config("image_generation partial_images must be an integer")
        })?;
        if partial_images > 3 {
            return Err(LingerError::invalid_config(
                "image_generation partial_images must be between 0 and 3",
            ));
        }
    }
    if let Some(input_image_mask) = object.get("input_image_mask") {
        validate_image_generation_mask(input_image_mask)?;
    }
    Ok(())
}

fn validate_image_generation_enum(
    object: &serde_json::Map<String, Value>,
    field: &str,
    allowed: &[&str],
) -> Result<(), LingerError> {
    if let Some(value) = object.get(field) {
        let Some(value) = value.as_str() else {
            return Err(LingerError::invalid_config(format!(
                "image_generation {field} must be a string"
            )));
        };
        validate_optional_string(&format!("image_generation {field}"), Some(value))?;
        if !allowed.contains(&value) {
            return Err(LingerError::invalid_config(format!(
                "image_generation {field} has an unsupported value"
            )));
        }
    }
    Ok(())
}

fn validate_image_generation_mask(input_image_mask: &Value) -> Result<(), LingerError> {
    if input_image_mask.is_null() {
        return Err(LingerError::invalid_config(
            "image_generation input_image_mask must not be null",
        ));
    }
    let mask = input_image_mask.as_object().ok_or_else(|| {
        LingerError::invalid_config("image_generation input_image_mask must be a JSON object")
    })?;
    let image_url = mask.get("image_url").and_then(Value::as_str);
    let file_id = mask.get("file_id").and_then(Value::as_str);
    match (image_url, file_id) {
        (Some(image_url), None) => validate_optional_string(
            "image_generation input_image_mask.image_url",
            Some(image_url),
        ),
        (None, Some(file_id)) => {
            validate_optional_string("image_generation input_image_mask.file_id", Some(file_id))
        }
        (None, None) => Err(LingerError::invalid_config(
            "image_generation input_image_mask must include image_url or file_id",
        )),
        (Some(_), Some(_)) => Err(LingerError::invalid_config(
            "image_generation input_image_mask must not include both image_url and file_id",
        )),
    }
}

fn validate_mcp_tool(object: &serde_json::Map<String, Value>) -> Result<(), LingerError> {
    let server_label = object
        .get("server_label")
        .and_then(Value::as_str)
        .unwrap_or_default();
    validate_optional_string("mcp server_label", Some(server_label))?;

    let server_url = validate_mcp_optional_string(object, "server_url")?;
    let connector_id = validate_mcp_optional_string(object, "connector_id")?;
    match (server_url, connector_id) {
        (Some(_), Some(_)) => {
            return Err(LingerError::invalid_config(
                "mcp tools must include only one of server_url or connector_id",
            ));
        }
        (None, None) => {
            return Err(LingerError::invalid_config(
                "mcp tools must include server_url or connector_id",
            ));
        }
        (Some(_), None) => {}
        (None, Some(connector_id)) => validate_mcp_connector_id(connector_id)?,
    }

    validate_mcp_optional_string(object, "authorization")?;
    validate_mcp_optional_string(object, "server_description")?;

    if let Some(headers) = object.get("headers") {
        validate_mcp_headers(headers)?;
    }
    if let Some(allowed_tools) = object.get("allowed_tools") {
        validate_mcp_allowed_tools(allowed_tools)?;
    }
    if let Some(require_approval) = object.get("require_approval") {
        validate_mcp_require_approval(require_approval)?;
    }
    if let Some(defer_loading) = object.get("defer_loading") {
        if !defer_loading.is_boolean() {
            return Err(LingerError::invalid_config(
                "mcp defer_loading must be a boolean",
            ));
        }
    }

    Ok(())
}

fn validate_mcp_optional_string<'a>(
    object: &'a serde_json::Map<String, Value>,
    field: &str,
) -> Result<Option<&'a str>, LingerError> {
    let Some(value) = object.get(field) else {
        return Ok(None);
    };
    let Some(value) = value.as_str() else {
        return Err(LingerError::invalid_config(format!(
            "mcp {field} must be a string"
        )));
    };
    validate_optional_string(&format!("mcp {field}"), Some(value))?;
    Ok(Some(value))
}

fn validate_mcp_connector_id(connector_id: &str) -> Result<(), LingerError> {
    if matches!(
        connector_id,
        "connector_dropbox"
            | "connector_gmail"
            | "connector_googlecalendar"
            | "connector_googledrive"
            | "connector_microsoftteams"
            | "connector_outlookcalendar"
            | "connector_outlookemail"
            | "connector_sharepoint"
    ) {
        Ok(())
    } else {
        Err(LingerError::invalid_config(
            "mcp connector_id has an unsupported value",
        ))
    }
}

fn validate_mcp_headers(headers: &Value) -> Result<(), LingerError> {
    if headers.is_null() {
        return Err(LingerError::invalid_config("mcp headers must not be null"));
    }
    let headers = headers
        .as_object()
        .ok_or_else(|| LingerError::invalid_config("mcp headers must be a JSON object"))?;
    for (name, value) in headers {
        if name.trim().is_empty() {
            return Err(LingerError::invalid_config(
                "mcp header names must not be empty",
            ));
        }
        if !value.is_string() {
            return Err(LingerError::invalid_config(
                "mcp header values must be strings",
            ));
        }
    }
    Ok(())
}

fn validate_mcp_allowed_tools(allowed_tools: &Value) -> Result<(), LingerError> {
    if allowed_tools.is_null() {
        return Err(LingerError::invalid_config(
            "mcp allowed_tools must not be null",
        ));
    }
    if let Some(tool_names) = allowed_tools.as_array() {
        return validate_mcp_tool_names("mcp allowed_tools", tool_names);
    }
    validate_mcp_tool_filter("mcp allowed_tools", allowed_tools)
}

fn validate_mcp_require_approval(require_approval: &Value) -> Result<(), LingerError> {
    if require_approval.is_null() {
        return Err(LingerError::invalid_config(
            "mcp require_approval must not be null",
        ));
    }
    if let Some(mode) = require_approval.as_str() {
        if matches!(mode, "always" | "never") {
            return Ok(());
        }
        return Err(LingerError::invalid_config(
            "mcp require_approval must be always, never, or a filter object",
        ));
    }
    let approval = require_approval.as_object().ok_or_else(|| {
        LingerError::invalid_config("mcp require_approval must be a string or object")
    })?;
    for field in ["always", "never"] {
        if let Some(filter) = approval.get(field) {
            validate_mcp_tool_filter(&format!("mcp require_approval.{field}"), filter)?;
        }
    }
    for field in approval.keys() {
        if !matches!(field.as_str(), "always" | "never") {
            return Err(LingerError::invalid_config(
                "mcp require_approval only supports always and never filters",
            ));
        }
    }
    Ok(())
}

fn validate_mcp_tool_filter(name: &str, filter: &Value) -> Result<(), LingerError> {
    if filter.is_null() {
        return Err(LingerError::invalid_config(format!(
            "{name} must not be null"
        )));
    }
    let filter = filter
        .as_object()
        .ok_or_else(|| LingerError::invalid_config(format!("{name} must be a JSON object")))?;
    if let Some(tool_names) = filter.get("tool_names") {
        let tool_names = tool_names.as_array().ok_or_else(|| {
            LingerError::invalid_config(format!("{name}.tool_names must be an array"))
        })?;
        validate_mcp_tool_names(&format!("{name}.tool_names"), tool_names)?;
    }
    if let Some(read_only) = filter.get("read_only") {
        if !read_only.is_boolean() {
            return Err(LingerError::invalid_config(format!(
                "{name}.read_only must be a boolean"
            )));
        }
    }
    for field in filter.keys() {
        if !matches!(field.as_str(), "tool_names" | "read_only") {
            return Err(LingerError::invalid_config(format!(
                "{name} only supports tool_names and read_only"
            )));
        }
    }
    Ok(())
}

fn validate_mcp_tool_names(name: &str, tool_names: &[Value]) -> Result<(), LingerError> {
    for tool_name in tool_names {
        let Some(tool_name) = tool_name.as_str() else {
            return Err(LingerError::invalid_config(format!(
                "{name} must contain strings"
            )));
        };
        validate_optional_string(name, Some(tool_name))?;
    }
    Ok(())
}

fn validate_web_search_tool(object: &serde_json::Map<String, Value>) -> Result<(), LingerError> {
    for field in ["filters", "user_location"] {
        if let Some(value) = object.get(field) {
            if value.is_null() {
                return Err(LingerError::invalid_config(format!(
                    "web_search {field} must not be null"
                )));
            }
            if !value.is_object() {
                return Err(LingerError::invalid_config(format!(
                    "web_search {field} must be a JSON object"
                )));
            }
        }
    }
    if let Some(content_types) = object.get("search_content_types") {
        let content_types = content_types.as_array().ok_or_else(|| {
            LingerError::invalid_config("web_search search_content_types must be an array")
        })?;
        for content_type in content_types {
            let Some(content_type) = content_type.as_str() else {
                return Err(LingerError::invalid_config(
                    "web_search search_content_types must contain strings",
                ));
            };
            validate_optional_string("web_search search_content_types", Some(content_type))?;
        }
    }
    Ok(())
}

fn validate_tool_choice(tool_choice: &ResponseToolChoice) -> Result<(), LingerError> {
    if let ResponseToolChoice::AllowedTools { tools, .. } = tool_choice {
        validate_json_items("tool_choice.tools", tools)?;
    }
    Ok(())
}

fn validate_prompt(prompt: &ResponsePrompt) -> Result<(), LingerError> {
    validate_optional_string("prompt.id", Some(&prompt.id))?;
    validate_optional_string("prompt.version", prompt.version.as_deref())?;
    for (name, value) in &prompt.variables {
        if name.trim().is_empty() {
            return Err(LingerError::invalid_config(
                "prompt variable names must not be empty",
            ));
        }
        if value.is_null() {
            return Err(LingerError::invalid_config(
                "prompt variable values must not be null",
            ));
        }
    }
    Ok(())
}

fn validate_text_config(text: &ResponseTextConfig) -> Result<(), LingerError> {
    if let Some(ResponseTextFormat::JsonSchema { name, schema, .. }) = &text.format {
        validate_optional_string("text.format.name", Some(name))?;
        if name.chars().count() > 64 {
            return Err(LingerError::invalid_config(
                "text.format.name must be at most 64 characters",
            ));
        }
        if !name
            .chars()
            .all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-')
        {
            return Err(LingerError::invalid_config(
                "text.format.name must contain only ASCII letters, digits, underscores, or dashes",
            ));
        }
        if schema.is_null() {
            return Err(LingerError::invalid_config(
                "text.format.schema must not be null",
            ));
        }
    }
    Ok(())
}

fn validate_context_management(
    context_management: &[ResponseContextManagement],
) -> Result<(), LingerError> {
    if context_management.is_empty() {
        return Err(LingerError::invalid_config(
            "context_management must contain at least one entry",
        ));
    }
    if context_management.iter().any(|entry| {
        entry
            .compact_threshold
            .is_some_and(|compact_threshold| compact_threshold < 1000)
    }) {
        return Err(LingerError::invalid_config(
            "context_management compact_threshold must be at least 1000",
        ));
    }
    Ok(())
}

fn validate_moderation(moderation: &ResponseModeration) -> Result<(), LingerError> {
    if moderation.model.trim().is_empty() {
        return Err(LingerError::invalid_config(
            "moderation model must not be empty",
        ));
    }
    Ok(())
}

fn validate_extra_fields(extra: &BTreeMap<String, Value>) -> Result<(), LingerError> {
    for (key, value) in extra {
        if key.trim().is_empty() {
            return Err(LingerError::invalid_config(
                "extra field names must not be empty",
            ));
        }
        if value.is_null() {
            return Err(LingerError::invalid_config(format!(
                "extra field {key} must not be null"
            )));
        }
    }
    Ok(())
}