rig-core 0.35.0

An opinionated library for building LLM powered applications.
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
// ================================================================
//! Google Gemini Completion Integration
//! From [Gemini API Reference](https://ai.google.dev/api/generate-content)
// ================================================================
/// `gemini-3.1-flash-lite-preview` completion model
pub const GEMINI_3_1_FLASH_LITE_PREVIEW: &str = "gemini-3.1-flash-lite-preview";
/// `gemini-3-flash-preview` completion model
pub const GEMINI_3_FLASH_PREVIEW: &str = "gemini-3-flash-preview";
/// `gemini-2.5-pro-preview-06-05` completion model
pub const GEMINI_2_5_PRO_PREVIEW_06_05: &str = "gemini-2.5-pro-preview-06-05";
/// `gemini-2.5-pro-preview-05-06` completion model
pub const GEMINI_2_5_PRO_PREVIEW_05_06: &str = "gemini-2.5-pro-preview-05-06";
/// `gemini-2.5-pro-preview-03-25` completion model
pub const GEMINI_2_5_PRO_PREVIEW_03_25: &str = "gemini-2.5-pro-preview-03-25";
/// `gemini-2.5-flash-preview-04-17` completion model
pub const GEMINI_2_5_FLASH_PREVIEW_04_17: &str = "gemini-2.5-flash-preview-04-17";
/// `gemini-2.5-pro-exp-03-25` experimental completion model
pub const GEMINI_2_5_PRO_EXP_03_25: &str = "gemini-2.5-pro-exp-03-25";
/// `gemini-2.5-flash` completion model
pub const GEMINI_2_5_FLASH: &str = "gemini-2.5-flash";
/// `gemini-2.0-flash-lite` completion model
pub const GEMINI_2_0_FLASH_LITE: &str = "gemini-2.0-flash-lite";
/// `gemini-2.0-flash` completion model
pub const GEMINI_2_0_FLASH: &str = "gemini-2.0-flash";

use self::gemini_api_types::Schema;
use crate::http_client::HttpClientExt;
use crate::message::{self, MimeType, Reasoning};

use crate::providers::gemini::completion::gemini_api_types::{
    AdditionalParameters, FunctionCallingMode, ToolConfig,
};
use crate::providers::gemini::streaming::StreamingCompletionResponse;
use crate::telemetry::SpanCombinator;
use crate::{
    OneOrMany,
    completion::{self, CompletionError, CompletionRequest},
};
use gemini_api_types::{
    Content, FunctionDeclaration, GenerateContentRequest, GenerateContentResponse,
    GenerationConfig, Part, PartKind, Role, Tool,
};
use serde_json::{Map, Value};
use std::convert::TryFrom;
use tracing::{Level, enabled, info_span};
use tracing_futures::Instrument;

use super::Client;

// =================================================================
// Rig Implementation Types
// =================================================================

#[derive(Clone, Debug)]
pub struct CompletionModel<T = reqwest::Client> {
    pub(crate) client: Client<T>,
    pub model: String,
}

impl<T> CompletionModel<T> {
    pub fn new(client: Client<T>, model: impl Into<String>) -> Self {
        Self {
            client,
            model: model.into(),
        }
    }

    pub fn with_model(client: Client<T>, model: &str) -> Self {
        Self {
            client,
            model: model.into(),
        }
    }
}

impl<T> completion::CompletionModel for CompletionModel<T>
where
    T: HttpClientExt + Clone + 'static,
{
    type Response = GenerateContentResponse;
    type StreamingResponse = StreamingCompletionResponse;
    type Client = super::Client<T>;

    fn make(client: &Self::Client, model: impl Into<String>) -> Self {
        Self::new(client.clone(), model)
    }

    async fn completion(
        &self,
        completion_request: CompletionRequest,
    ) -> Result<completion::CompletionResponse<GenerateContentResponse>, CompletionError> {
        let request_model = resolve_request_model(&self.model, &completion_request);
        let span = if tracing::Span::current().is_disabled() {
            info_span!(
                target: "rig::completions",
                "generate_content",
                gen_ai.operation.name = "generate_content",
                gen_ai.provider.name = "gcp.gemini",
                gen_ai.request.model = &request_model,
                gen_ai.system_instructions = &completion_request.preamble,
                gen_ai.response.id = tracing::field::Empty,
                gen_ai.response.model = tracing::field::Empty,
                gen_ai.usage.output_tokens = tracing::field::Empty,
                gen_ai.usage.input_tokens = tracing::field::Empty,
                gen_ai.usage.cached_tokens = tracing::field::Empty,
            )
        } else {
            tracing::Span::current()
        };

        let request = create_request_body(completion_request)?;

        if enabled!(Level::TRACE) {
            tracing::trace!(
                target: "rig::completions",
                "Gemini completion request: {}",
                serde_json::to_string_pretty(&request)?
            );
        }

        let body = serde_json::to_vec(&request)?;

        let path = completion_endpoint(&request_model);

        let request = self
            .client
            .post(path.as_str())?
            .body(body)
            .map_err(|e| CompletionError::HttpError(e.into()))?;

        async move {
            let response = self.client.send::<_, Vec<u8>>(request).await?;

            if response.status().is_success() {
                let response_body = response
                    .into_body()
                    .await
                    .map_err(CompletionError::HttpError)?;

                let response_text = String::from_utf8_lossy(&response_body).to_string();

                let response: GenerateContentResponse = serde_json::from_slice(&response_body)
                    .map_err(|err| {
                        tracing::error!(
                            error = %err,
                            body = %response_text,
                            "Failed to deserialize Gemini completion response"
                        );
                        CompletionError::JsonError(err)
                    })?;

                let span = tracing::Span::current();
                span.record_response_metadata(&response);
                span.record_token_usage(&response.usage_metadata);

                if enabled!(Level::TRACE) {
                    tracing::trace!(
                        target: "rig::completions",
                        "Gemini completion response: {}",
                        serde_json::to_string_pretty(&response)?
                    );
                }

                response.try_into()
            } else {
                let text = String::from_utf8_lossy(
                    &response
                        .into_body()
                        .await
                        .map_err(CompletionError::HttpError)?,
                )
                .into();

                Err(CompletionError::ProviderError(text))
            }
        }
        .instrument(span)
        .await
    }

    async fn stream(
        &self,
        request: CompletionRequest,
    ) -> Result<
        crate::streaming::StreamingCompletionResponse<Self::StreamingResponse>,
        CompletionError,
    > {
        CompletionModel::stream(self, request).await
    }
}

pub(crate) fn create_request_body(
    completion_request: CompletionRequest,
) -> Result<GenerateContentRequest, CompletionError> {
    let documents_message = completion_request.normalized_documents();

    let CompletionRequest {
        model: _,
        preamble,
        chat_history,
        documents: _,
        tools: function_tools,
        temperature,
        max_tokens,
        tool_choice,
        mut additional_params,
        output_schema,
    } = completion_request;

    let mut full_history = Vec::new();
    if let Some(msg) = documents_message {
        full_history.push(msg);
    }
    full_history.extend(chat_history);
    let (history_system, full_history) = split_system_messages_from_history(full_history);

    let mut additional_params_payload = additional_params
        .take()
        .unwrap_or_else(|| Value::Object(Map::new()));
    let mut additional_tools =
        extract_tools_from_additional_params(&mut additional_params_payload)?;

    let AdditionalParameters {
        mut generation_config,
        additional_params,
    } = serde_json::from_value::<AdditionalParameters>(additional_params_payload)?;

    // Apply output_schema to generation_config, creating one if needed
    if let Some(schema) = output_schema {
        let cfg = generation_config.get_or_insert_with(GenerationConfig::default);
        cfg.response_mime_type = Some("application/json".to_string());
        cfg.response_json_schema = Some(schema.to_value());
    }

    generation_config = generation_config.map(|mut cfg| {
        if let Some(temp) = temperature {
            cfg.temperature = Some(temp);
        };

        if let Some(max_tokens) = max_tokens {
            cfg.max_output_tokens = Some(max_tokens);
        };

        cfg
    });

    let mut system_parts: Vec<Part> = Vec::new();
    if let Some(preamble) = preamble.filter(|preamble| !preamble.is_empty()) {
        system_parts.push(preamble.into());
    }
    for content in history_system {
        if !content.is_empty() {
            system_parts.push(content.into());
        }
    }
    let system_instruction = if system_parts.is_empty() {
        None
    } else {
        Some(Content {
            parts: system_parts,
            role: Some(Role::Model),
        })
    };

    let mut tools = if function_tools.is_empty() {
        Vec::new()
    } else {
        vec![serde_json::to_value(Tool::try_from(function_tools)?)?]
    };
    tools.append(&mut additional_tools);
    let tools = if tools.is_empty() { None } else { Some(tools) };

    let tool_config = if let Some(cfg) = tool_choice {
        Some(ToolConfig {
            function_calling_config: Some(FunctionCallingMode::try_from(cfg)?),
        })
    } else {
        None
    };

    let request = GenerateContentRequest {
        contents: full_history
            .into_iter()
            .map(|msg| {
                msg.try_into()
                    .map_err(|e| CompletionError::RequestError(Box::new(e)))
            })
            .collect::<Result<Vec<_>, _>>()?,
        generation_config,
        safety_settings: None,
        tools,
        tool_config,
        system_instruction,
        additional_params,
    };

    Ok(request)
}

fn split_system_messages_from_history(
    history: Vec<completion::Message>,
) -> (Vec<String>, Vec<completion::Message>) {
    let mut system = Vec::new();
    let mut remaining = Vec::new();

    for message in history {
        match message {
            completion::Message::System { content } => system.push(content),
            other => remaining.push(other),
        }
    }

    (system, remaining)
}

fn extract_tools_from_additional_params(
    additional_params: &mut Value,
) -> Result<Vec<Value>, CompletionError> {
    if let Some(map) = additional_params.as_object_mut()
        && let Some(raw_tools) = map.remove("tools")
    {
        return serde_json::from_value::<Vec<Value>>(raw_tools).map_err(|err| {
            CompletionError::RequestError(
                format!("Invalid Gemini `additional_params.tools` payload: {err}").into(),
            )
        });
    }

    Ok(Vec::new())
}

pub(crate) fn resolve_request_model(
    default_model: &str,
    completion_request: &CompletionRequest,
) -> String {
    completion_request
        .model
        .clone()
        .unwrap_or_else(|| default_model.to_string())
}

pub(crate) fn completion_endpoint(model: &str) -> String {
    format!("/v1beta/models/{model}:generateContent")
}

pub(crate) fn streaming_endpoint(model: &str) -> String {
    format!("/v1beta/models/{model}:streamGenerateContent")
}

impl TryFrom<completion::ToolDefinition> for Tool {
    type Error = CompletionError;

    fn try_from(tool: completion::ToolDefinition) -> Result<Self, Self::Error> {
        let parameters: Option<Schema> =
            if tool.parameters == serde_json::json!({"type": "object", "properties": {}}) {
                None
            } else {
                Some(tool.parameters.try_into()?)
            };

        Ok(Self {
            function_declarations: vec![FunctionDeclaration {
                name: tool.name,
                description: tool.description,
                parameters,
            }],
            code_execution: None,
        })
    }
}

impl TryFrom<Vec<completion::ToolDefinition>> for Tool {
    type Error = CompletionError;

    fn try_from(tools: Vec<completion::ToolDefinition>) -> Result<Self, Self::Error> {
        let mut function_declarations = Vec::new();

        for tool in tools {
            let parameters =
                if tool.parameters == serde_json::json!({"type": "object", "properties": {}}) {
                    None
                } else {
                    match tool.parameters.try_into() {
                        Ok(schema) => Some(schema),
                        Err(e) => {
                            let emsg = format!(
                                "Tool '{}' could not be converted to a schema: {:?}",
                                tool.name, e,
                            );
                            return Err(CompletionError::ProviderError(emsg));
                        }
                    }
                };

            function_declarations.push(FunctionDeclaration {
                name: tool.name,
                description: tool.description,
                parameters,
            });
        }

        Ok(Self {
            function_declarations,
            code_execution: None,
        })
    }
}

impl TryFrom<GenerateContentResponse> for completion::CompletionResponse<GenerateContentResponse> {
    type Error = CompletionError;

    fn try_from(response: GenerateContentResponse) -> Result<Self, Self::Error> {
        let candidate = response.candidates.first().ok_or_else(|| {
            CompletionError::ResponseError("No response candidates in response".into())
        })?;

        let content = candidate
            .content
            .as_ref()
            .ok_or_else(|| {
                let reason = candidate
                    .finish_reason
                    .as_ref()
                    .map(|r| format!("finish_reason={r:?}"))
                    .unwrap_or_else(|| "finish_reason=<unknown>".to_string());
                let message = candidate
                    .finish_message
                    .as_deref()
                    .unwrap_or("no finish message provided");
                CompletionError::ResponseError(format!(
                    "Gemini candidate missing content ({reason}, finish_message={message})"
                ))
            })?
            .parts
            .iter()
            .map(
                |Part {
                     thought,
                     thought_signature,
                     part,
                     ..
                 }| {
                    Ok(match part {
                        PartKind::Text(text) => {
                            if let Some(thought) = thought
                                && *thought
                            {
                                completion::AssistantContent::Reasoning(
                                    Reasoning::new_with_signature(text, thought_signature.clone()),
                                )
                            } else {
                                completion::AssistantContent::text(text)
                            }
                        }
                        PartKind::InlineData(inline_data) => {
                            let mime_type =
                                message::MediaType::from_mime_type(&inline_data.mime_type);

                            match mime_type {
                                Some(message::MediaType::Image(media_type)) => {
                                    message::AssistantContent::image_base64(
                                        &inline_data.data,
                                        Some(media_type),
                                        Some(message::ImageDetail::default()),
                                    )
                                }
                                _ => {
                                    return Err(CompletionError::ResponseError(format!(
                                        "Unsupported media type {mime_type:?}"
                                    )));
                                }
                            }
                        }
                        PartKind::FunctionCall(function_call) => {
                            completion::AssistantContent::ToolCall(
                                message::ToolCall::new(
                                    function_call.name.clone(),
                                    message::ToolFunction::new(
                                        function_call.name.clone(),
                                        function_call.args.clone(),
                                    ),
                                )
                                .with_signature(thought_signature.clone()),
                            )
                        }
                        _ => {
                            return Err(CompletionError::ResponseError(
                                "Response did not contain a message or tool call".into(),
                            ));
                        }
                    })
                },
            )
            .collect::<Result<Vec<_>, _>>()?;

        let choice = OneOrMany::many(content).map_err(|_| {
            CompletionError::ResponseError(
                "Response contained no message or tool call (empty)".to_owned(),
            )
        })?;

        let usage = response
            .usage_metadata
            .as_ref()
            .map(|usage| completion::Usage {
                input_tokens: usage.prompt_token_count as u64,
                output_tokens: usage.candidates_token_count.unwrap_or(0) as u64,
                total_tokens: usage.total_token_count as u64,
                cached_input_tokens: 0,
                cache_creation_input_tokens: 0,
            })
            .unwrap_or_default();

        Ok(completion::CompletionResponse {
            choice,
            usage,
            raw_response: response,
            message_id: None,
        })
    }
}

pub mod gemini_api_types {
    use crate::telemetry::ProviderResponseExt;
    use std::{collections::HashMap, convert::Infallible, str::FromStr};

    // =================================================================
    // Gemini API Types
    // =================================================================
    use serde::{Deserialize, Serialize};
    use serde_json::{Value, json};

    use crate::completion::GetTokenUsage;
    use crate::message::{DocumentSourceKind, ImageMediaType, MessageError, MimeType};
    use crate::{
        completion::CompletionError,
        message::{self},
        providers::gemini::gemini_api_types::{CodeExecutionResult, ExecutableCode},
    };

    #[derive(Debug, Deserialize, Serialize, Default)]
    #[serde(rename_all = "camelCase")]
    pub struct AdditionalParameters {
        /// Change your Gemini request configuration.
        pub generation_config: Option<GenerationConfig>,
        /// Any additional parameters that you want.
        #[serde(flatten, skip_serializing_if = "Option::is_none")]
        pub additional_params: Option<serde_json::Value>,
    }

    impl AdditionalParameters {
        pub fn with_config(mut self, cfg: GenerationConfig) -> Self {
            self.generation_config = Some(cfg);
            self
        }

        pub fn with_params(mut self, params: serde_json::Value) -> Self {
            self.additional_params = Some(params);
            self
        }
    }

    /// Response from the model supporting multiple candidate responses.
    /// Safety ratings and content filtering are reported for both prompt in GenerateContentResponse.prompt_feedback
    /// and for each candidate in finishReason and in safetyRatings.
    /// The API:
    ///     - Returns either all requested candidates or none of them
    ///     - Returns no candidates at all only if there was something wrong with the prompt (check promptFeedback)
    ///     - Reports feedback on each candidate in finishReason and safetyRatings.
    #[derive(Debug, Deserialize, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct GenerateContentResponse {
        pub response_id: String,
        /// Candidate responses from the model.
        pub candidates: Vec<ContentCandidate>,
        /// Returns the prompt's feedback related to the content filters.
        pub prompt_feedback: Option<PromptFeedback>,
        /// Output only. Metadata on the generation requests' token usage.
        pub usage_metadata: Option<UsageMetadata>,
        pub model_version: Option<String>,
    }

    impl ProviderResponseExt for GenerateContentResponse {
        type OutputMessage = ContentCandidate;
        type Usage = UsageMetadata;

        fn get_response_id(&self) -> Option<String> {
            Some(self.response_id.clone())
        }

        fn get_response_model_name(&self) -> Option<String> {
            None
        }

        fn get_output_messages(&self) -> Vec<Self::OutputMessage> {
            self.candidates.clone()
        }

        fn get_text_response(&self) -> Option<String> {
            let str = self
                .candidates
                .iter()
                .filter_map(|x| {
                    let content = x.content.as_ref()?;
                    if content.role.as_ref().is_none_or(|y| y != &Role::Model) {
                        return None;
                    }

                    let res = content
                        .parts
                        .iter()
                        .filter_map(|part| {
                            if let PartKind::Text(ref str) = part.part {
                                Some(str.to_owned())
                            } else {
                                None
                            }
                        })
                        .collect::<Vec<String>>()
                        .join("\n");

                    Some(res)
                })
                .collect::<Vec<String>>()
                .join("\n");

            if str.is_empty() { None } else { Some(str) }
        }

        fn get_usage(&self) -> Option<Self::Usage> {
            self.usage_metadata.clone()
        }
    }

    /// A response candidate generated from the model.
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct ContentCandidate {
        /// Output only. Generated content returned from the model.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub content: Option<Content>,
        /// Optional. Output only. The reason why the model stopped generating tokens.
        /// If empty, the model has not stopped generating tokens.
        pub finish_reason: Option<FinishReason>,
        /// List of ratings for the safety of a response candidate.
        /// There is at most one rating per category.
        pub safety_ratings: Option<Vec<SafetyRating>>,
        /// Output only. Citation information for model-generated candidate.
        /// This field may be populated with recitation information for any text included in the content.
        /// These are passages that are "recited" from copyrighted material in the foundational LLM's training data.
        pub citation_metadata: Option<CitationMetadata>,
        /// Output only. Token count for this candidate.
        pub token_count: Option<i32>,
        /// Output only.
        pub avg_logprobs: Option<f64>,
        /// Output only. Log-likelihood scores for the response tokens and top tokens
        pub logprobs_result: Option<LogprobsResult>,
        /// Output only. Index of the candidate in the list of response candidates.
        pub index: Option<i32>,
        /// Output only. Additional information about why the model stopped generating tokens.
        pub finish_message: Option<String>,
    }

    #[derive(Clone, Debug, Deserialize, Serialize)]
    pub struct Content {
        /// Ordered Parts that constitute a single message. Parts may have different MIME types.
        #[serde(default)]
        pub parts: Vec<Part>,
        /// The producer of the content. Must be either 'user' or 'model'.
        /// Useful to set for multi-turn conversations, otherwise can be left blank or unset.
        pub role: Option<Role>,
    }

    impl TryFrom<message::Message> for Content {
        type Error = message::MessageError;

        fn try_from(msg: message::Message) -> Result<Self, Self::Error> {
            Ok(match msg {
                message::Message::System { content } => Content {
                    parts: vec![content.into()],
                    role: Some(Role::User),
                },
                message::Message::User { content } => Content {
                    parts: content
                        .into_iter()
                        .map(|c| c.try_into())
                        .collect::<Result<Vec<_>, _>>()?,
                    role: Some(Role::User),
                },
                message::Message::Assistant { content, .. } => Content {
                    role: Some(Role::Model),
                    parts: content
                        .into_iter()
                        .map(|content| content.try_into())
                        .collect::<Result<Vec<_>, _>>()?,
                },
            })
        }
    }

    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
    #[serde(rename_all = "lowercase")]
    pub enum Role {
        User,
        Model,
    }

    #[derive(Debug, Default, Deserialize, Serialize, Clone, PartialEq)]
    #[serde(rename_all = "camelCase")]
    pub struct Part {
        /// whether or not the part is a reasoning/thinking text or not
        #[serde(skip_serializing_if = "Option::is_none")]
        pub thought: Option<bool>,
        /// an opaque sig for the thought so it can be reused - is a base64 string
        #[serde(skip_serializing_if = "Option::is_none")]
        pub thought_signature: Option<String>,
        #[serde(flatten)]
        pub part: PartKind,
        #[serde(flatten, skip_serializing_if = "Option::is_none")]
        pub additional_params: Option<Value>,
    }

    /// A datatype containing media that is part of a multi-part [Content] message.
    /// A Part consists of data which has an associated datatype. A Part can only contain one of the accepted types in Part.data.
    /// A Part must have a fixed IANA MIME type identifying the type and subtype of the media if the inlineData field is filled with raw bytes.
    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
    #[serde(rename_all = "camelCase")]
    pub enum PartKind {
        Text(String),
        InlineData(Blob),
        FunctionCall(FunctionCall),
        FunctionResponse(FunctionResponse),
        FileData(FileData),
        ExecutableCode(ExecutableCode),
        CodeExecutionResult(CodeExecutionResult),
    }

    // This default instance is primarily so we can easily fill in the optional fields of `Part`
    // So this instance for `PartKind` (and the allocation it would cause) should be optimized away
    impl Default for PartKind {
        fn default() -> Self {
            Self::Text(String::new())
        }
    }

    impl From<String> for Part {
        fn from(text: String) -> Self {
            Self {
                thought: Some(false),
                thought_signature: None,
                part: PartKind::Text(text),
                additional_params: None,
            }
        }
    }

    impl From<&str> for Part {
        fn from(text: &str) -> Self {
            Self::from(text.to_string())
        }
    }

    impl FromStr for Part {
        type Err = Infallible;

        fn from_str(s: &str) -> Result<Self, Self::Err> {
            Ok(s.into())
        }
    }

    impl TryFrom<(ImageMediaType, DocumentSourceKind)> for PartKind {
        type Error = message::MessageError;
        fn try_from(
            (mime_type, doc_src): (ImageMediaType, DocumentSourceKind),
        ) -> Result<Self, Self::Error> {
            let mime_type = mime_type.to_mime_type().to_string();
            let part = match doc_src {
                DocumentSourceKind::Url(url) => PartKind::FileData(FileData {
                    mime_type: Some(mime_type),
                    file_uri: url,
                }),
                DocumentSourceKind::Base64(data) | DocumentSourceKind::String(data) => {
                    PartKind::InlineData(Blob { mime_type, data })
                }
                DocumentSourceKind::Raw(_) => {
                    return Err(message::MessageError::ConversionError(
                        "Raw files not supported, encode as base64 first".into(),
                    ));
                }
                DocumentSourceKind::Unknown => {
                    return Err(message::MessageError::ConversionError(
                        "Can't convert an unknown document source".to_string(),
                    ));
                }
            };

            Ok(part)
        }
    }

    impl TryFrom<message::UserContent> for Part {
        type Error = message::MessageError;

        fn try_from(content: message::UserContent) -> Result<Self, Self::Error> {
            match content {
                message::UserContent::Text(message::Text { text }) => Ok(Part {
                    thought: Some(false),
                    thought_signature: None,
                    part: PartKind::Text(text),
                    additional_params: None,
                }),
                message::UserContent::ToolResult(message::ToolResult { id, content, .. }) => {
                    let mut response_json: Option<serde_json::Value> = None;
                    let mut parts: Vec<FunctionResponsePart> = Vec::new();

                    for item in content.iter() {
                        match item {
                            message::ToolResultContent::Text(text) => {
                                let result: serde_json::Value =
                                    serde_json::from_str(&text.text).unwrap_or_else(|error| {
                                        tracing::trace!(
                                            ?error,
                                            "Tool result is not a valid JSON, treat it as normal string"
                                        );
                                        json!(&text.text)
                                    });

                                response_json = Some(match response_json {
                                    Some(mut existing) => {
                                        if let serde_json::Value::Object(ref mut map) = existing {
                                            map.insert("text".to_string(), result);
                                        }
                                        existing
                                    }
                                    None => json!({ "result": result }),
                                });
                            }
                            message::ToolResultContent::Image(image) => {
                                let part = match &image.data {
                                    DocumentSourceKind::Base64(b64) => {
                                        let mime_type = image
                                            .media_type
                                            .as_ref()
                                            .ok_or(message::MessageError::ConversionError(
                                                "Image media type is required for Gemini tool results".to_string(),
                                            ))?
                                            .to_mime_type();

                                        FunctionResponsePart {
                                            inline_data: Some(FunctionResponseInlineData {
                                                mime_type: mime_type.to_string(),
                                                data: b64.clone(),
                                                display_name: None,
                                            }),
                                            file_data: None,
                                        }
                                    }
                                    DocumentSourceKind::Url(url) => {
                                        let mime_type = image
                                            .media_type
                                            .as_ref()
                                            .map(|mt| mt.to_mime_type().to_string());

                                        FunctionResponsePart {
                                            inline_data: None,
                                            file_data: Some(FileData {
                                                mime_type,
                                                file_uri: url.clone(),
                                            }),
                                        }
                                    }
                                    _ => {
                                        return Err(message::MessageError::ConversionError(
                                            "Unsupported image source kind for tool results"
                                                .to_string(),
                                        ));
                                    }
                                };
                                parts.push(part);
                            }
                        }
                    }

                    Ok(Part {
                        thought: Some(false),
                        thought_signature: None,
                        part: PartKind::FunctionResponse(FunctionResponse {
                            name: id,
                            response: response_json,
                            parts: if parts.is_empty() { None } else { Some(parts) },
                        }),
                        additional_params: None,
                    })
                }
                message::UserContent::Image(message::Image {
                    data, media_type, ..
                }) => match media_type {
                    Some(media_type) => match media_type {
                        message::ImageMediaType::JPEG
                        | message::ImageMediaType::PNG
                        | message::ImageMediaType::WEBP
                        | message::ImageMediaType::HEIC
                        | message::ImageMediaType::HEIF => {
                            let part = PartKind::try_from((media_type, data))?;
                            Ok(Part {
                                thought: Some(false),
                                thought_signature: None,
                                part,
                                additional_params: None,
                            })
                        }
                        _ => Err(message::MessageError::ConversionError(format!(
                            "Unsupported image media type {media_type:?}"
                        ))),
                    },
                    None => Err(message::MessageError::ConversionError(
                        "Media type for image is required for Gemini".to_string(),
                    )),
                },
                message::UserContent::Document(message::Document {
                    data, media_type, ..
                }) => {
                    let Some(media_type) = media_type else {
                        return Err(MessageError::ConversionError(
                            "A mime type is required for document inputs to Gemini".to_string(),
                        ));
                    };

                    // For text-like documents (RAG context), convert inline content to plain text.
                    // URL-backed files should stay as file_data references so Gemini can fetch them.
                    if matches!(
                        media_type,
                        message::DocumentMediaType::TXT
                            | message::DocumentMediaType::RTF
                            | message::DocumentMediaType::HTML
                            | message::DocumentMediaType::CSS
                            | message::DocumentMediaType::MARKDOWN
                            | message::DocumentMediaType::CSV
                            | message::DocumentMediaType::XML
                            | message::DocumentMediaType::Javascript
                            | message::DocumentMediaType::Python
                    ) {
                        use base64::Engine;
                        let part = match data {
                            DocumentSourceKind::String(text) => PartKind::Text(text),
                            DocumentSourceKind::Base64(data) => {
                                // Decode base64 text payloads.
                                let text = String::from_utf8(
                                    base64::engine::general_purpose::STANDARD
                                        .decode(&data)
                                        .map_err(|e| {
                                            MessageError::ConversionError(format!(
                                                "Failed to decode base64: {e}"
                                            ))
                                        })?,
                                )
                                .map_err(|e| {
                                    MessageError::ConversionError(format!(
                                        "Invalid UTF-8 in document: {e}"
                                    ))
                                })?;
                                PartKind::Text(text)
                            }
                            DocumentSourceKind::Url(file_uri) => PartKind::FileData(FileData {
                                mime_type: Some(media_type.to_mime_type().to_string()),
                                file_uri,
                            }),
                            DocumentSourceKind::Raw(_) => {
                                return Err(MessageError::ConversionError(
                                    "Raw files not supported, encode as base64 first".to_string(),
                                ));
                            }
                            DocumentSourceKind::Unknown => {
                                return Err(MessageError::ConversionError(
                                    "Document has no body".to_string(),
                                ));
                            }
                        };

                        Ok(Part {
                            thought: Some(false),
                            part,
                            ..Default::default()
                        })
                    } else if !media_type.is_code() {
                        let mime_type = media_type.to_mime_type().to_string();

                        let part = match data {
                            DocumentSourceKind::Url(file_uri) => PartKind::FileData(FileData {
                                mime_type: Some(mime_type),
                                file_uri,
                            }),
                            DocumentSourceKind::Base64(data) | DocumentSourceKind::String(data) => {
                                PartKind::InlineData(Blob { mime_type, data })
                            }
                            DocumentSourceKind::Raw(_) => {
                                return Err(message::MessageError::ConversionError(
                                    "Raw files not supported, encode as base64 first".into(),
                                ));
                            }
                            _ => {
                                return Err(message::MessageError::ConversionError(
                                    "Document has no body".to_string(),
                                ));
                            }
                        };

                        Ok(Part {
                            thought: Some(false),
                            part,
                            ..Default::default()
                        })
                    } else {
                        Err(message::MessageError::ConversionError(format!(
                            "Unsupported document media type {media_type:?}"
                        )))
                    }
                }

                message::UserContent::Audio(message::Audio {
                    data, media_type, ..
                }) => {
                    let Some(media_type) = media_type else {
                        return Err(MessageError::ConversionError(
                            "A mime type is required for audio inputs to Gemini".to_string(),
                        ));
                    };

                    let mime_type = media_type.to_mime_type().to_string();

                    let part = match data {
                        DocumentSourceKind::Base64(data) => {
                            PartKind::InlineData(Blob { data, mime_type })
                        }

                        DocumentSourceKind::Url(file_uri) => PartKind::FileData(FileData {
                            mime_type: Some(mime_type),
                            file_uri,
                        }),
                        DocumentSourceKind::String(_) => {
                            return Err(message::MessageError::ConversionError(
                                "Strings cannot be used as audio files!".into(),
                            ));
                        }
                        DocumentSourceKind::Raw(_) => {
                            return Err(message::MessageError::ConversionError(
                                "Raw files not supported, encode as base64 first".into(),
                            ));
                        }
                        DocumentSourceKind::Unknown => {
                            return Err(message::MessageError::ConversionError(
                                "Content has no body".to_string(),
                            ));
                        }
                    };

                    Ok(Part {
                        thought: Some(false),
                        part,
                        ..Default::default()
                    })
                }
                message::UserContent::Video(message::Video {
                    data,
                    media_type,
                    additional_params,
                    ..
                }) => {
                    let mime_type = media_type.map(|media_ty| media_ty.to_mime_type().to_string());

                    let part = match data {
                        DocumentSourceKind::Url(file_uri) => {
                            if file_uri.starts_with("https://www.youtube.com") {
                                PartKind::FileData(FileData {
                                    mime_type,
                                    file_uri,
                                })
                            } else {
                                if mime_type.is_none() {
                                    return Err(MessageError::ConversionError(
                                        "A mime type is required for non-Youtube video file inputs to Gemini"
                                            .to_string(),
                                    ));
                                }

                                PartKind::FileData(FileData {
                                    mime_type,
                                    file_uri,
                                })
                            }
                        }
                        DocumentSourceKind::Base64(data) => {
                            let Some(mime_type) = mime_type else {
                                return Err(MessageError::ConversionError(
                                    "A media type is expected for base64 encoded strings"
                                        .to_string(),
                                ));
                            };
                            PartKind::InlineData(Blob { mime_type, data })
                        }
                        DocumentSourceKind::String(_) => {
                            return Err(message::MessageError::ConversionError(
                                "Strings cannot be used as audio files!".into(),
                            ));
                        }
                        DocumentSourceKind::Raw(_) => {
                            return Err(message::MessageError::ConversionError(
                                "Raw file data not supported, encode as base64 first".into(),
                            ));
                        }
                        DocumentSourceKind::Unknown => {
                            return Err(message::MessageError::ConversionError(
                                "Media type for video is required for Gemini".to_string(),
                            ));
                        }
                    };

                    Ok(Part {
                        thought: Some(false),
                        thought_signature: None,
                        part,
                        additional_params,
                    })
                }
            }
        }
    }

    impl TryFrom<message::AssistantContent> for Part {
        type Error = message::MessageError;

        fn try_from(content: message::AssistantContent) -> Result<Self, Self::Error> {
            match content {
                message::AssistantContent::Text(message::Text { text }) => Ok(text.into()),
                message::AssistantContent::Image(message::Image {
                    data, media_type, ..
                }) => match media_type {
                    Some(media_type) => match media_type {
                        message::ImageMediaType::JPEG
                        | message::ImageMediaType::PNG
                        | message::ImageMediaType::WEBP
                        | message::ImageMediaType::HEIC
                        | message::ImageMediaType::HEIF => {
                            let part = PartKind::try_from((media_type, data))?;
                            Ok(Part {
                                thought: Some(false),
                                thought_signature: None,
                                part,
                                additional_params: None,
                            })
                        }
                        _ => Err(message::MessageError::ConversionError(format!(
                            "Unsupported image media type {media_type:?}"
                        ))),
                    },
                    None => Err(message::MessageError::ConversionError(
                        "Media type for image is required for Gemini".to_string(),
                    )),
                },
                message::AssistantContent::ToolCall(tool_call) => Ok(tool_call.into()),
                message::AssistantContent::Reasoning(reasoning) => Ok(Part {
                    thought: Some(true),
                    thought_signature: reasoning.first_signature().map(str::to_owned),
                    part: PartKind::Text(reasoning.display_text()),
                    additional_params: None,
                }),
            }
        }
    }

    impl From<message::ToolCall> for Part {
        fn from(tool_call: message::ToolCall) -> Self {
            Self {
                thought: Some(false),
                thought_signature: tool_call.signature,
                part: PartKind::FunctionCall(FunctionCall {
                    name: tool_call.function.name,
                    args: tool_call.function.arguments,
                }),
                additional_params: None,
            }
        }
    }

    /// Raw media bytes.
    /// Text should not be sent as raw bytes, use the 'text' field.
    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
    #[serde(rename_all = "camelCase")]
    pub struct Blob {
        /// The IANA standard MIME type of the source data. Examples: - image/png - image/jpeg
        /// If an unsupported MIME type is provided, an error will be returned.
        pub mime_type: String,
        /// Raw bytes for media formats. A base64-encoded string.
        pub data: String,
    }

    /// A predicted FunctionCall returned from the model that contains a string representing the
    /// FunctionDeclaration.name with the arguments and their values.
    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
    pub struct FunctionCall {
        /// Required. The name of the function to call. Must be a-z, A-Z, 0-9, or contain underscores
        /// and dashes, with a maximum length of 63.
        pub name: String,
        /// Optional. The function parameters and values in JSON object format.
        pub args: serde_json::Value,
    }

    impl From<message::ToolCall> for FunctionCall {
        fn from(tool_call: message::ToolCall) -> Self {
            Self {
                name: tool_call.function.name,
                args: tool_call.function.arguments,
            }
        }
    }

    /// The result output from a FunctionCall that contains a string representing the FunctionDeclaration.name
    /// and a structured JSON object containing any output from the function is used as context to the model.
    /// This should contain the result of aFunctionCall made based on model prediction.
    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
    pub struct FunctionResponse {
        /// The name of the function to call. Must be a-z, A-Z, 0-9, or contain underscores and dashes,
        /// with a maximum length of 63.
        pub name: String,
        /// The function response in JSON object format.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub response: Option<serde_json::Value>,
        /// Multimodal parts for the function response (e.g., images).
        #[serde(skip_serializing_if = "Option::is_none")]
        pub parts: Option<Vec<FunctionResponsePart>>,
    }

    /// A part of a multimodal function response.
    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
    #[serde(rename_all = "camelCase")]
    pub struct FunctionResponsePart {
        /// Inline data containing base64-encoded media content.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub inline_data: Option<FunctionResponseInlineData>,
        /// File data containing a URI reference.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub file_data: Option<FileData>,
    }

    /// Inline data for function response parts.
    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
    #[serde(rename_all = "camelCase")]
    pub struct FunctionResponseInlineData {
        /// The IANA standard MIME type of the source data.
        pub mime_type: String,
        /// Raw bytes for media formats. A base64-encoded string.
        pub data: String,
        /// Optional display name for the content.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub display_name: Option<String>,
    }

    /// URI based data.
    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
    #[serde(rename_all = "camelCase")]
    pub struct FileData {
        /// Optional. The IANA standard MIME type of the source data.
        pub mime_type: Option<String>,
        /// Required. URI.
        pub file_uri: String,
    }

    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
    pub struct SafetyRating {
        pub category: HarmCategory,
        pub probability: HarmProbability,
    }

    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
    #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
    pub enum HarmProbability {
        HarmProbabilityUnspecified,
        Negligible,
        Low,
        Medium,
        High,
    }

    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
    #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
    pub enum HarmCategory {
        HarmCategoryUnspecified,
        HarmCategoryDerogatory,
        HarmCategoryToxicity,
        HarmCategoryViolence,
        HarmCategorySexually,
        HarmCategoryMedical,
        HarmCategoryDangerous,
        HarmCategoryHarassment,
        HarmCategoryHateSpeech,
        HarmCategorySexuallyExplicit,
        HarmCategoryDangerousContent,
        HarmCategoryCivicIntegrity,
    }

    #[derive(Debug, Deserialize, Clone, Default, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct UsageMetadata {
        #[serde(default)]
        pub prompt_token_count: i32,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub cached_content_token_count: Option<i32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub candidates_token_count: Option<i32>,
        pub total_token_count: i32,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub thoughts_token_count: Option<i32>,
    }

    impl std::fmt::Display for UsageMetadata {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(
                f,
                "Prompt token count: {}\nCached content token count: {}\nCandidates token count: {}\nTotal token count: {}",
                self.prompt_token_count,
                match self.cached_content_token_count {
                    Some(count) => count.to_string(),
                    None => "n/a".to_string(),
                },
                match self.candidates_token_count {
                    Some(count) => count.to_string(),
                    None => "n/a".to_string(),
                },
                self.total_token_count
            )
        }
    }

    impl GetTokenUsage for UsageMetadata {
        fn token_usage(&self) -> Option<crate::completion::Usage> {
            let mut usage = crate::completion::Usage::new();

            usage.input_tokens = self.prompt_token_count as u64;
            usage.output_tokens = (self.cached_content_token_count.unwrap_or_default()
                + self.candidates_token_count.unwrap_or_default()
                + self.thoughts_token_count.unwrap_or_default())
                as u64;
            usage.total_tokens = usage.input_tokens + usage.output_tokens;

            Some(usage)
        }
    }

    /// A set of the feedback metadata the prompt specified in [GenerateContentRequest.contents](GenerateContentRequest).
    #[derive(Debug, Deserialize, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct PromptFeedback {
        /// Optional. If set, the prompt was blocked and no candidates are returned. Rephrase the prompt.
        pub block_reason: Option<BlockReason>,
        /// Ratings for safety of the prompt. There is at most one rating per category.
        pub safety_ratings: Option<Vec<SafetyRating>>,
    }

    /// Reason why a prompt was blocked by the model
    #[derive(Debug, Deserialize, Serialize)]
    #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
    pub enum BlockReason {
        /// Default value. This value is unused.
        BlockReasonUnspecified,
        /// Prompt was blocked due to safety reasons. Inspect safetyRatings to understand which safety category blocked it.
        Safety,
        /// Prompt was blocked due to unknown reasons.
        Other,
        /// Prompt was blocked due to the terms which are included from the terminology blocklist.
        Blocklist,
        /// Prompt was blocked due to prohibited content.
        ProhibitedContent,
    }

    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
    pub enum FinishReason {
        /// Default value. This value is unused.
        FinishReasonUnspecified,
        /// Natural stop point of the model or provided stop sequence.
        Stop,
        /// The maximum number of tokens as specified in the request was reached.
        MaxTokens,
        /// The response candidate content was flagged for safety reasons.
        Safety,
        /// The response candidate content was flagged for recitation reasons.
        Recitation,
        /// The response candidate content was flagged for using an unsupported language.
        Language,
        /// Unknown reason.
        Other,
        /// Token generation stopped because the content contains forbidden terms.
        Blocklist,
        /// Token generation stopped for potentially containing prohibited content.
        ProhibitedContent,
        /// Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).
        Spii,
        /// The function call generated by the model is invalid.
        MalformedFunctionCall,
    }

    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct CitationMetadata {
        pub citation_sources: Vec<CitationSource>,
    }

    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct CitationSource {
        #[serde(skip_serializing_if = "Option::is_none")]
        pub uri: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub start_index: Option<i32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub end_index: Option<i32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub license: Option<String>,
    }

    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct LogprobsResult {
        pub top_candidate: Vec<TopCandidate>,
        pub chosen_candidate: Vec<LogProbCandidate>,
    }

    #[derive(Clone, Debug, Deserialize, Serialize)]
    pub struct TopCandidate {
        pub candidates: Vec<LogProbCandidate>,
    }

    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct LogProbCandidate {
        pub token: String,
        pub token_id: String,
        pub log_probability: f64,
    }

    /// Gemini API Configuration options for model generation and outputs. Not all parameters are
    /// configurable for every model. From [Gemini API Reference](https://ai.google.dev/api/generate-content#generationconfig)
    /// ### Rig Note:
    /// Can be used to construct a typesafe `additional_params` in rig::[AgentBuilder](crate::agent::AgentBuilder).
    #[derive(Debug, Deserialize, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct GenerationConfig {
        /// The set of character sequences (up to 5) that will stop output generation. If specified, the API will stop
        /// at the first appearance of a stop_sequence. The stop sequence will not be included as part of the response.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub stop_sequences: Option<Vec<String>>,
        /// MIME type of the generated candidate text. Supported MIME types are:
        ///     - text/plain:  (default) Text output
        ///     - application/json: JSON response in the response candidates.
        ///     - text/x.enum: ENUM as a string response in the response candidates.
        /// Refer to the docs for a list of all supported text MIME types
        #[serde(skip_serializing_if = "Option::is_none")]
        pub response_mime_type: Option<String>,
        /// Output schema of the generated candidate text. Schemas must be a subset of the OpenAPI schema and can be
        /// objects, primitives or arrays. If set, a compatible responseMimeType must also  be set. Compatible MIME
        /// types: application/json: Schema for JSON response. Refer to the JSON text generation guide for more details.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub response_schema: Option<Schema>,
        /// Optional. The output schema of the generated response.
        /// This is an alternative to responseSchema that accepts a standard JSON Schema.
        /// If this is set, responseSchema must be omitted.
        /// Compatible MIME type: application/json.
        /// Supported properties: $id, $defs, $ref, type, properties, etc.
        #[serde(
            skip_serializing_if = "Option::is_none",
            rename = "_responseJsonSchema"
        )]
        pub _response_json_schema: Option<Value>,
        /// Internal or alternative representation for `response_json_schema`.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub response_json_schema: Option<Value>,
        /// Number of generated responses to return. Currently, this value can only be set to 1. If
        /// unset, this will default to 1.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub candidate_count: Option<i32>,
        /// The maximum number of tokens to include in a response candidate. Note: The default value varies by model, see
        /// the Model.output_token_limit attribute of the Model returned from the getModel function.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub max_output_tokens: Option<u64>,
        /// Controls the randomness of the output. Note: The default value varies by model, see the Model.temperature
        /// attribute of the Model returned from the getModel function. Values can range from [0.0, 2.0].
        #[serde(skip_serializing_if = "Option::is_none")]
        pub temperature: Option<f64>,
        /// The maximum cumulative probability of tokens to consider when sampling. The model uses combined Top-k and
        /// Top-p (nucleus) sampling. Tokens are sorted based on their assigned probabilities so that only the most
        /// likely tokens are considered. Top-k sampling directly limits the maximum number of tokens to consider, while
        /// Nucleus sampling limits the number of tokens based on the cumulative probability. Note: The default value
        /// varies by Model and is specified by theModel.top_p attribute returned from the getModel function. An empty
        /// topK attribute indicates that the model doesn't apply top-k sampling and doesn't allow setting topK on requests.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub top_p: Option<f64>,
        /// The maximum number of tokens to consider when sampling. Gemini models use Top-p (nucleus) sampling or a
        /// combination of Top-k and nucleus sampling. Top-k sampling considers the set of topK most probable tokens.
        /// Models running with nucleus sampling don't allow topK setting. Note: The default value varies by Model and is
        /// specified by theModel.top_p attribute returned from the getModel function. An empty topK attribute indicates
        /// that the model doesn't apply top-k sampling and doesn't allow setting topK on requests.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub top_k: Option<i32>,
        /// Presence penalty applied to the next token's logprobs if the token has already been seen in the response.
        /// This penalty is binary on/off and not dependent on the number of times the token is used (after the first).
        /// Use frequencyPenalty for a penalty that increases with each use. A positive penalty will discourage the use
        /// of tokens that have already been used in the response, increasing the vocabulary. A negative penalty will
        /// encourage the use of tokens that have already been used in the response, decreasing the vocabulary.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub presence_penalty: Option<f64>,
        /// Frequency penalty applied to the next token's logprobs, multiplied by the number of times each token has been
        /// seen in the response so far. A positive penalty will discourage the use of tokens that have already been
        /// used, proportional to the number of times the token has been used: The more a token is used, the more
        /// difficult it is for the  model to use that token again increasing the vocabulary of responses. Caution: A
        /// negative penalty will encourage the model to reuse tokens proportional to the number of times the token has
        /// been used. Small negative values will reduce the vocabulary of a response. Larger negative values will cause
        /// the model to  repeating a common token until it hits the maxOutputTokens limit: "...the the the the the...".
        #[serde(skip_serializing_if = "Option::is_none")]
        pub frequency_penalty: Option<f64>,
        /// If true, export the logprobs results in response.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub response_logprobs: Option<bool>,
        /// Only valid if responseLogprobs=True. This sets the number of top logprobs to return at each decoding step in
        /// [Candidate.logprobs_result].
        #[serde(skip_serializing_if = "Option::is_none")]
        pub logprobs: Option<i32>,
        /// Configuration for thinking/reasoning.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub thinking_config: Option<ThinkingConfig>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub image_config: Option<ImageConfig>,
    }

    impl Default for GenerationConfig {
        fn default() -> Self {
            Self {
                temperature: Some(1.0),
                max_output_tokens: Some(4096),
                stop_sequences: None,
                response_mime_type: None,
                response_schema: None,
                _response_json_schema: None,
                response_json_schema: None,
                candidate_count: None,
                top_p: None,
                top_k: None,
                presence_penalty: None,
                frequency_penalty: None,
                response_logprobs: None,
                logprobs: None,
                thinking_config: None,
                image_config: None,
            }
        }
    }

    /// Thinking depth level for Gemini 3 models.
    #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
    #[serde(rename_all = "snake_case")]
    pub enum ThinkingLevel {
        Minimal,
        Low,
        Medium,
        High,
    }

    /// Configuration for the model's thinking/reasoning process.
    /// Note: `thinking_budget` (Gemini 2.5) and `thinking_level` (Gemini 3) are mutually exclusive
    /// and cannot be set in the same request.
    #[derive(Debug, Deserialize, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct ThinkingConfig {
        /// Token budget for thinking. Used by Gemini 2.5 models. Range: 0 to 32768.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub thinking_budget: Option<u32>,
        /// Thinking depth level. Used by Gemini 3 models.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub thinking_level: Option<ThinkingLevel>,
        /// When true, includes summarized versions of the model's reasoning in the response.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub include_thoughts: Option<bool>,
    }

    #[derive(Debug, Deserialize, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct ImageConfig {
        #[serde(skip_serializing_if = "Option::is_none")]
        pub aspect_ratio: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub image_size: Option<String>,
    }

    /// The Schema object allows the definition of input and output data types. These types can be objects, but also
    /// primitives and arrays. Represents a select subset of an OpenAPI 3.0 schema object.
    /// From [Gemini API Reference](https://ai.google.dev/api/caching#Schema)
    #[derive(Debug, Deserialize, Serialize, Clone)]
    pub struct Schema {
        pub r#type: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub format: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub description: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub nullable: Option<bool>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub r#enum: Option<Vec<String>>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub max_items: Option<i32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub min_items: Option<i32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub properties: Option<HashMap<String, Schema>>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub required: Option<Vec<String>>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub items: Option<Box<Schema>>,
    }

    /// Flattens a JSON schema by resolving all `$ref` references inline.
    /// It takes a JSON schema that may contain `$ref` references to definitions
    /// in `$defs` or `definitions` sections and returns a new schema with all references
    /// resolved and inlined. This is necessary for APIs like Gemini that don't support
    /// schema references.
    pub fn flatten_schema(mut schema: Value) -> Result<Value, CompletionError> {
        // extracting $defs if they exist
        let defs = if let Some(obj) = schema.as_object() {
            obj.get("$defs").or_else(|| obj.get("definitions")).cloned()
        } else {
            None
        };

        let Some(defs_value) = defs else {
            return Ok(schema);
        };

        let Some(defs_obj) = defs_value.as_object() else {
            return Err(CompletionError::ResponseError(
                "$defs must be an object".into(),
            ));
        };

        resolve_refs(&mut schema, defs_obj)?;

        // removing $defs from the final schema because we have inlined everything
        if let Some(obj) = schema.as_object_mut() {
            obj.remove("$defs");
            obj.remove("definitions");
        }

        Ok(schema)
    }

    /// Recursively resolves all `$ref` references in a JSON value by
    /// replacing them with their definitions.
    fn resolve_refs(
        value: &mut Value,
        defs: &serde_json::Map<String, Value>,
    ) -> Result<(), CompletionError> {
        match value {
            Value::Object(obj) => {
                if let Some(ref_value) = obj.get("$ref")
                    && let Some(ref_str) = ref_value.as_str()
                {
                    // "#/$defs/Person" -> "Person"
                    let def_name = parse_ref_path(ref_str)?;

                    let def = defs.get(&def_name).ok_or_else(|| {
                        CompletionError::ResponseError(format!("Reference not found: {}", ref_str))
                    })?;

                    let mut resolved = def.clone();
                    resolve_refs(&mut resolved, defs)?;
                    *value = resolved;
                    return Ok(());
                }

                for (_, v) in obj.iter_mut() {
                    resolve_refs(v, defs)?;
                }
            }
            Value::Array(arr) => {
                for item in arr.iter_mut() {
                    resolve_refs(item, defs)?;
                }
            }
            _ => {}
        }

        Ok(())
    }

    /// Parses a JSON Schema `$ref` path to extract the definition name.
    ///
    /// JSON Schema references use URI fragment syntax to point to definitions within
    /// the same document. This function extracts the definition name from common
    /// reference patterns used in JSON Schema.
    fn parse_ref_path(ref_str: &str) -> Result<String, CompletionError> {
        if let Some(fragment) = ref_str.strip_prefix('#') {
            if let Some(name) = fragment.strip_prefix("/$defs/") {
                Ok(name.to_string())
            } else if let Some(name) = fragment.strip_prefix("/definitions/") {
                Ok(name.to_string())
            } else {
                Err(CompletionError::ResponseError(format!(
                    "Unsupported reference format: {}",
                    ref_str
                )))
            }
        } else {
            Err(CompletionError::ResponseError(format!(
                "Only fragment references (#/...) are supported: {}",
                ref_str
            )))
        }
    }

    /// Helper function to extract the type string from a JSON value.
    /// Handles both direct string types and array types (returns the first element).
    fn extract_type(type_value: &Value) -> Option<String> {
        if type_value.is_string() {
            type_value.as_str().map(String::from)
        } else if type_value.is_array() {
            type_value
                .as_array()
                .and_then(|arr| arr.first())
                .and_then(|v| v.as_str().map(String::from))
        } else {
            None
        }
    }

    /// Helper function to extract type from anyOf, oneOf, or allOf schemas.
    /// Returns the type of the first non-null schema found.
    fn extract_type_from_composition(composition: &Value) -> Option<String> {
        composition.as_array().and_then(|arr| {
            arr.iter().find_map(|schema| {
                if let Some(obj) = schema.as_object() {
                    // Skip null types
                    if let Some(type_val) = obj.get("type")
                        && let Some(type_str) = type_val.as_str()
                        && type_str == "null"
                    {
                        return None;
                    }
                    // Extract type from this schema
                    obj.get("type").and_then(extract_type).or_else(|| {
                        if obj.contains_key("properties") {
                            Some("object".to_string())
                        } else if obj.contains_key("enum") {
                            // Enum schemas without explicit type are string-backed
                            Some("string".to_string())
                        } else {
                            None
                        }
                    })
                } else {
                    None
                }
            })
        })
    }

    /// Helper function to extract the first non-null schema from anyOf, oneOf, or allOf.
    /// Returns the schema object that should be used for properties, required, etc.
    fn extract_schema_from_composition(
        composition: &Value,
    ) -> Option<serde_json::Map<String, Value>> {
        composition.as_array().and_then(|arr| {
            arr.iter().find_map(|schema| {
                if let Some(obj) = schema.as_object()
                    && let Some(type_val) = obj.get("type")
                    && let Some(type_str) = type_val.as_str()
                {
                    if type_str == "null" {
                        return None;
                    }
                    Some(obj.clone())
                } else {
                    None
                }
            })
        })
    }

    /// Helper function to infer the type of a schema object.
    /// Checks for explicit type, then anyOf/oneOf/allOf, then infers from properties.
    fn infer_type(obj: &serde_json::Map<String, Value>) -> String {
        // First, try direct type field
        if let Some(type_val) = obj.get("type")
            && let Some(type_str) = extract_type(type_val)
        {
            return type_str;
        }

        // Then try anyOf, oneOf, allOf (in that order)
        if let Some(any_of) = obj.get("anyOf")
            && let Some(type_str) = extract_type_from_composition(any_of)
        {
            return type_str;
        }

        if let Some(one_of) = obj.get("oneOf")
            && let Some(type_str) = extract_type_from_composition(one_of)
        {
            return type_str;
        }

        if let Some(all_of) = obj.get("allOf")
            && let Some(type_str) = extract_type_from_composition(all_of)
        {
            return type_str;
        }

        // Finally, infer object type if properties are present
        if obj.contains_key("properties") {
            "object".to_string()
        } else {
            String::new()
        }
    }

    impl TryFrom<Value> for Schema {
        type Error = CompletionError;

        fn try_from(value: Value) -> Result<Self, Self::Error> {
            let flattened_val = flatten_schema(value)?;
            if let Some(obj) = flattened_val.as_object() {
                // Determine which object to use for extracting properties and required fields.
                // If this object has anyOf/oneOf/allOf, we need to extract properties from the composition.
                let props_source = if obj.get("properties").is_none() {
                    if let Some(any_of) = obj.get("anyOf") {
                        extract_schema_from_composition(any_of)
                    } else if let Some(one_of) = obj.get("oneOf") {
                        extract_schema_from_composition(one_of)
                    } else if let Some(all_of) = obj.get("allOf") {
                        extract_schema_from_composition(all_of)
                    } else {
                        None
                    }
                    .unwrap_or(obj.clone())
                } else {
                    obj.clone()
                };

                let schema_type = infer_type(obj);
                let items = obj
                    .get("items")
                    .and_then(|v| v.clone().try_into().ok())
                    .map(Box::new);

                // Gemini requires `items` on array-typed schemas; default to
                // string items when the source schema omits it.
                let items = if schema_type == "array" && items.is_none() {
                    Some(Box::new(Schema {
                        r#type: "string".to_string(),
                        format: None,
                        description: None,
                        nullable: None,
                        r#enum: None,
                        max_items: None,
                        min_items: None,
                        properties: None,
                        required: None,
                        items: None,
                    }))
                } else {
                    items
                };

                Ok(Schema {
                    r#type: schema_type,
                    format: obj.get("format").and_then(|v| v.as_str()).map(String::from),
                    description: obj
                        .get("description")
                        .and_then(|v| v.as_str())
                        .map(String::from),
                    nullable: obj.get("nullable").and_then(|v| v.as_bool()),
                    r#enum: obj.get("enum").and_then(|v| v.as_array()).map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect()
                    }),
                    max_items: obj
                        .get("maxItems")
                        .and_then(|v| v.as_i64())
                        .map(|v| v as i32),
                    min_items: obj
                        .get("minItems")
                        .and_then(|v| v.as_i64())
                        .map(|v| v as i32),
                    properties: props_source
                        .get("properties")
                        .and_then(|v| v.as_object())
                        .map(|map| {
                            map.iter()
                                .filter_map(|(k, v)| {
                                    v.clone().try_into().ok().map(|schema| (k.clone(), schema))
                                })
                                .collect()
                        }),
                    required: props_source
                        .get("required")
                        .and_then(|v| v.as_array())
                        .map(|arr| {
                            arr.iter()
                                .filter_map(|v| v.as_str().map(String::from))
                                .collect()
                        }),
                    items,
                })
            } else {
                Err(CompletionError::ResponseError(
                    "Expected a JSON object for Schema".into(),
                ))
            }
        }
    }

    #[derive(Debug, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct GenerateContentRequest {
        pub contents: Vec<Content>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub tools: Option<Vec<Value>>,
        pub tool_config: Option<ToolConfig>,
        /// Optional. Configuration options for model generation and outputs.
        pub generation_config: Option<GenerationConfig>,
        /// Optional. A list of unique SafetySetting instances for blocking unsafe content. This will be enforced on the
        /// [GenerateContentRequest.contents] and [GenerateContentResponse.candidates]. There should not be more than one
        /// setting for each SafetyCategory type. The API will block any contents and responses that fail to meet the
        /// thresholds set by these settings. This list overrides the default settings for each SafetyCategory specified
        /// in the safetySettings. If there is no SafetySetting for a given SafetyCategory provided in the list, the API
        /// will use the default safety setting for that category. Harm categories:
        ///     - HARM_CATEGORY_HATE_SPEECH,
        ///     - HARM_CATEGORY_SEXUALLY_EXPLICIT
        ///     - HARM_CATEGORY_DANGEROUS_CONTENT
        ///     - HARM_CATEGORY_HARASSMENT
        /// are supported.
        /// Refer to the guide for detailed information on available safety settings. Also refer to the Safety guidance
        /// to learn how to incorporate safety considerations in your AI applications.
        pub safety_settings: Option<Vec<SafetySetting>>,
        /// Optional. Developer set system instruction(s). Currently, text only.
        /// From [Gemini API Reference](https://ai.google.dev/gemini-api/docs/system-instructions?lang=rest)
        pub system_instruction: Option<Content>,
        // cachedContent: Optional<String>
        /// Additional parameters.
        #[serde(flatten, skip_serializing_if = "Option::is_none")]
        pub additional_params: Option<serde_json::Value>,
    }

    #[derive(Debug, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct Tool {
        pub function_declarations: Vec<FunctionDeclaration>,
        pub code_execution: Option<CodeExecution>,
    }

    #[derive(Debug, Serialize, Clone)]
    #[serde(rename_all = "camelCase")]
    pub struct FunctionDeclaration {
        pub name: String,
        pub description: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub parameters: Option<Schema>,
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct ToolConfig {
        pub function_calling_config: Option<FunctionCallingMode>,
    }

    #[derive(Debug, Serialize, Deserialize, Default)]
    #[serde(tag = "mode", rename_all = "UPPERCASE")]
    pub enum FunctionCallingMode {
        #[default]
        Auto,
        None,
        Any {
            #[serde(skip_serializing_if = "Option::is_none")]
            allowed_function_names: Option<Vec<String>>,
        },
    }

    impl TryFrom<message::ToolChoice> for FunctionCallingMode {
        type Error = CompletionError;
        fn try_from(value: message::ToolChoice) -> Result<Self, Self::Error> {
            let res = match value {
                message::ToolChoice::Auto => Self::Auto,
                message::ToolChoice::None => Self::None,
                message::ToolChoice::Required => Self::Any {
                    allowed_function_names: None,
                },
                message::ToolChoice::Specific { function_names } => Self::Any {
                    allowed_function_names: Some(function_names),
                },
            };

            Ok(res)
        }
    }

    #[derive(Debug, Serialize)]
    pub struct CodeExecution {}

    #[derive(Debug, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct SafetySetting {
        pub category: HarmCategory,
        pub threshold: HarmBlockThreshold,
    }

    #[derive(Debug, Serialize)]
    #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
    pub enum HarmBlockThreshold {
        HarmBlockThresholdUnspecified,
        BlockLowAndAbove,
        BlockMediumAndAbove,
        BlockOnlyHigh,
        BlockNone,
        Off,
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        message,
        providers::gemini::completion::gemini_api_types::{
            ContentCandidate, FinishReason, flatten_schema,
        },
    };

    use super::*;
    use serde_json::json;

    #[test]
    fn test_resolve_request_model_uses_override() {
        let request = CompletionRequest {
            model: Some("gemini-2.5-flash".to_string()),
            preamble: None,
            chat_history: crate::OneOrMany::one("Hello".into()),
            documents: vec![],
            tools: vec![],
            temperature: None,
            max_tokens: None,
            tool_choice: None,
            additional_params: None,
            output_schema: None,
        };

        let request_model = resolve_request_model("gemini-2.0-flash", &request);
        assert_eq!(request_model, "gemini-2.5-flash");
        assert_eq!(
            completion_endpoint(&request_model),
            "/v1beta/models/gemini-2.5-flash:generateContent"
        );
        assert_eq!(
            streaming_endpoint(&request_model),
            "/v1beta/models/gemini-2.5-flash:streamGenerateContent"
        );
    }

    #[test]
    fn test_resolve_request_model_uses_default_when_unset() {
        let request = CompletionRequest {
            model: None,
            preamble: None,
            chat_history: crate::OneOrMany::one("Hello".into()),
            documents: vec![],
            tools: vec![],
            temperature: None,
            max_tokens: None,
            tool_choice: None,
            additional_params: None,
            output_schema: None,
        };

        assert_eq!(
            resolve_request_model("gemini-2.0-flash", &request),
            "gemini-2.0-flash"
        );
    }

    #[test]
    fn test_deserialize_message_user() {
        let raw_message = r#"{
            "parts": [
                {"text": "Hello, world!"},
                {"inlineData": {"mimeType": "image/png", "data": "base64encodeddata"}},
                {"functionCall": {"name": "test_function", "args": {"arg1": "value1"}}},
                {"functionResponse": {"name": "test_function", "response": {"result": "success"}}},
                {"fileData": {"mimeType": "application/pdf", "fileUri": "http://example.com/file.pdf"}},
                {"executableCode": {"code": "print('Hello, world!')", "language": "PYTHON"}},
                {"codeExecutionResult": {"output": "Hello, world!", "outcome": "OUTCOME_OK"}}
            ],
            "role": "user"
        }"#;

        let content: Content = {
            let jd = &mut serde_json::Deserializer::from_str(raw_message);
            serde_path_to_error::deserialize(jd).unwrap_or_else(|err| {
                panic!("Deserialization error at {}: {}", err.path(), err);
            })
        };
        assert_eq!(content.role, Some(Role::User));
        assert_eq!(content.parts.len(), 7);

        let parts: Vec<Part> = content.parts.into_iter().collect();

        if let Part {
            part: PartKind::Text(text),
            ..
        } = &parts[0]
        {
            assert_eq!(text, "Hello, world!");
        } else {
            panic!("Expected text part");
        }

        if let Part {
            part: PartKind::InlineData(inline_data),
            ..
        } = &parts[1]
        {
            assert_eq!(inline_data.mime_type, "image/png");
            assert_eq!(inline_data.data, "base64encodeddata");
        } else {
            panic!("Expected inline data part");
        }

        if let Part {
            part: PartKind::FunctionCall(function_call),
            ..
        } = &parts[2]
        {
            assert_eq!(function_call.name, "test_function");
            assert_eq!(
                function_call.args.as_object().unwrap().get("arg1").unwrap(),
                "value1"
            );
        } else {
            panic!("Expected function call part");
        }

        if let Part {
            part: PartKind::FunctionResponse(function_response),
            ..
        } = &parts[3]
        {
            assert_eq!(function_response.name, "test_function");
            assert_eq!(
                function_response
                    .response
                    .as_ref()
                    .unwrap()
                    .get("result")
                    .unwrap(),
                "success"
            );
        } else {
            panic!("Expected function response part");
        }

        if let Part {
            part: PartKind::FileData(file_data),
            ..
        } = &parts[4]
        {
            assert_eq!(file_data.mime_type.as_ref().unwrap(), "application/pdf");
            assert_eq!(file_data.file_uri, "http://example.com/file.pdf");
        } else {
            panic!("Expected file data part");
        }

        if let Part {
            part: PartKind::ExecutableCode(executable_code),
            ..
        } = &parts[5]
        {
            assert_eq!(executable_code.code, "print('Hello, world!')");
        } else {
            panic!("Expected executable code part");
        }

        if let Part {
            part: PartKind::CodeExecutionResult(code_execution_result),
            ..
        } = &parts[6]
        {
            assert_eq!(
                code_execution_result.clone().output.unwrap(),
                "Hello, world!"
            );
        } else {
            panic!("Expected code execution result part");
        }
    }

    #[test]
    fn test_deserialize_message_model() {
        let json_data = json!({
            "parts": [{"text": "Hello, user!"}],
            "role": "model"
        });

        let content: Content = serde_json::from_value(json_data).unwrap();
        assert_eq!(content.role, Some(Role::Model));
        assert_eq!(content.parts.len(), 1);
        if let Some(Part {
            part: PartKind::Text(text),
            ..
        }) = content.parts.first()
        {
            assert_eq!(text, "Hello, user!");
        } else {
            panic!("Expected text part");
        }
    }

    #[test]
    fn test_message_conversion_user() {
        let msg = message::Message::user("Hello, world!");
        let content: Content = msg.try_into().unwrap();
        assert_eq!(content.role, Some(Role::User));
        assert_eq!(content.parts.len(), 1);
        if let Some(Part {
            part: PartKind::Text(text),
            ..
        }) = &content.parts.first()
        {
            assert_eq!(text, "Hello, world!");
        } else {
            panic!("Expected text part");
        }
    }

    #[test]
    fn test_message_conversion_model() {
        let msg = message::Message::assistant("Hello, user!");

        let content: Content = msg.try_into().unwrap();
        assert_eq!(content.role, Some(Role::Model));
        assert_eq!(content.parts.len(), 1);
        if let Some(Part {
            part: PartKind::Text(text),
            ..
        }) = &content.parts.first()
        {
            assert_eq!(text, "Hello, user!");
        } else {
            panic!("Expected text part");
        }
    }

    #[test]
    fn test_thought_signature_is_preserved_from_response_reasoning_part() {
        let response = GenerateContentResponse {
            response_id: "resp_1".to_string(),
            candidates: vec![ContentCandidate {
                content: Some(Content {
                    parts: vec![Part {
                        thought: Some(true),
                        thought_signature: Some("thought_sig_123".to_string()),
                        part: PartKind::Text("thinking text".to_string()),
                        additional_params: None,
                    }],
                    role: Some(Role::Model),
                }),
                finish_reason: Some(FinishReason::Stop),
                safety_ratings: None,
                citation_metadata: None,
                token_count: None,
                avg_logprobs: None,
                logprobs_result: None,
                index: Some(0),
                finish_message: None,
            }],
            prompt_feedback: None,
            usage_metadata: None,
            model_version: None,
        };

        let converted: crate::completion::CompletionResponse<GenerateContentResponse> =
            response.try_into().expect("convert response");
        let first = converted.choice.first();
        assert!(matches!(
            first,
            message::AssistantContent::Reasoning(message::Reasoning { content, .. })
                if matches!(
                    content.first(),
                    Some(message::ReasoningContent::Text {
                        text,
                        signature: Some(signature)
                    }) if text == "thinking text" && signature == "thought_sig_123"
                )
        ));
    }

    #[test]
    fn test_reasoning_signature_is_emitted_in_gemini_part() {
        let msg = message::Message::Assistant {
            id: None,
            content: OneOrMany::one(message::AssistantContent::Reasoning(
                message::Reasoning::new_with_signature(
                    "structured thought",
                    Some("reuse_sig_456".to_string()),
                ),
            )),
        };

        let converted: Content = msg.try_into().expect("convert message");
        let first = converted.parts.first().expect("reasoning part");
        assert_eq!(first.thought, Some(true));
        assert_eq!(first.thought_signature.as_deref(), Some("reuse_sig_456"));
        assert!(matches!(
            &first.part,
            PartKind::Text(text) if text == "structured thought"
        ));
    }

    #[test]
    fn test_message_conversion_tool_call() {
        let tool_call = message::ToolCall {
            id: "test_tool".to_string(),
            call_id: None,
            function: message::ToolFunction {
                name: "test_function".to_string(),
                arguments: json!({"arg1": "value1"}),
            },
            signature: None,
            additional_params: None,
        };

        let msg = message::Message::Assistant {
            id: None,
            content: OneOrMany::one(message::AssistantContent::ToolCall(tool_call)),
        };

        let content: Content = msg.try_into().unwrap();
        assert_eq!(content.role, Some(Role::Model));
        assert_eq!(content.parts.len(), 1);
        if let Some(Part {
            part: PartKind::FunctionCall(function_call),
            ..
        }) = content.parts.first()
        {
            assert_eq!(function_call.name, "test_function");
            assert_eq!(
                function_call.args.as_object().unwrap().get("arg1").unwrap(),
                "value1"
            );
        } else {
            panic!("Expected function call part");
        }
    }

    #[test]
    fn test_vec_schema_conversion() {
        let schema_with_ref = json!({
            "type": "array",
            "items": {
                "$ref": "#/$defs/Person"
            },
            "$defs": {
                "Person": {
                    "type": "object",
                    "properties": {
                        "first_name": {
                            "type": ["string", "null"],
                            "description": "The person's first name, if provided (null otherwise)"
                        },
                        "last_name": {
                            "type": ["string", "null"],
                            "description": "The person's last name, if provided (null otherwise)"
                        },
                        "job": {
                            "type": ["string", "null"],
                            "description": "The person's job, if provided (null otherwise)"
                        }
                    },
                    "required": []
                }
            }
        });

        let result: Result<Schema, _> = schema_with_ref.try_into();

        match result {
            Ok(schema) => {
                assert_eq!(schema.r#type, "array");

                if let Some(items) = schema.items {
                    println!("item types: {}", items.r#type);

                    assert_ne!(items.r#type, "", "Items type should not be empty string!");
                    assert_eq!(items.r#type, "object", "Items should be object type");
                } else {
                    panic!("Schema should have items field for array type");
                }
            }
            Err(e) => println!("Schema conversion failed: {:?}", e),
        }
    }

    #[test]
    fn test_object_schema() {
        let simple_schema = json!({
            "type": "object",
            "properties": {
                "name": {
                    "type": "string"
                }
            }
        });

        let schema: Schema = simple_schema.try_into().unwrap();
        assert_eq!(schema.r#type, "object");
        assert!(schema.properties.is_some());
    }

    #[test]
    fn test_array_with_inline_items() {
        let inline_schema = json!({
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string"
                    }
                }
            }
        });

        let schema: Schema = inline_schema.try_into().unwrap();
        assert_eq!(schema.r#type, "array");

        if let Some(items) = schema.items {
            assert_eq!(items.r#type, "object");
            assert!(items.properties.is_some());
        } else {
            panic!("Schema should have items field");
        }
    }
    #[test]
    fn test_flattened_schema() {
        let ref_schema = json!({
            "type": "array",
            "items": {
                "$ref": "#/$defs/Person"
            },
            "$defs": {
                "Person": {
                    "type": "object",
                    "properties": {
                        "name": { "type": "string" }
                    }
                }
            }
        });

        let flattened = flatten_schema(ref_schema).unwrap();
        let schema: Schema = flattened.try_into().unwrap();

        assert_eq!(schema.r#type, "array");

        if let Some(items) = schema.items {
            println!("Flattened items type: '{}'", items.r#type);

            assert_eq!(items.r#type, "object");
            assert!(items.properties.is_some());
        }
    }

    #[test]
    fn test_array_without_items_gets_default() {
        let schema_json = json!({
            "type": "object",
            "properties": {
                "service_ids": {
                    "type": "array",
                    "description": "A list of service IDs"
                }
            }
        });

        let schema: Schema = schema_json.try_into().unwrap();
        let props = schema.properties.unwrap();
        let service_ids = props.get("service_ids").unwrap();
        assert_eq!(service_ids.r#type, "array");
        let items = service_ids
            .items
            .as_ref()
            .expect("array schema missing items should get a default");
        assert_eq!(items.r#type, "string");
    }

    #[test]
    fn test_txt_document_conversion_to_text_part() {
        // Test that TXT documents are converted to plain text parts, not inline data
        use crate::message::{DocumentMediaType, UserContent};

        let doc = UserContent::document(
            "Note: test.md\nPath: /test.md\nContent: Hello World!",
            Some(DocumentMediaType::TXT),
        );

        let content: Content = message::Message::User {
            content: crate::OneOrMany::one(doc),
        }
        .try_into()
        .unwrap();

        if let Part {
            part: PartKind::Text(text),
            ..
        } = &content.parts[0]
        {
            assert!(text.contains("Note: test.md"));
            assert!(text.contains("Hello World!"));
        } else {
            panic!(
                "Expected text part for TXT document, got: {:?}",
                content.parts[0]
            );
        }
    }

    #[test]
    fn test_tool_result_with_image_content() {
        // Test that a ToolResult with image content converts correctly to Gemini's Part format
        use crate::OneOrMany;
        use crate::message::{
            DocumentSourceKind, Image, ImageMediaType, ToolResult, ToolResultContent,
        };

        // Create a tool result with both text and image content
        let tool_result = ToolResult {
            id: "test_tool".to_string(),
            call_id: None,
            content: OneOrMany::many(vec![
                ToolResultContent::Text(message::Text {
                    text: r#"{"status": "success"}"#.to_string(),
                }),
                ToolResultContent::Image(Image {
                    data: DocumentSourceKind::Base64("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==".to_string()),
                    media_type: Some(ImageMediaType::PNG),
                    detail: None,
                    additional_params: None,
                }),
            ]).expect("Should create OneOrMany with multiple items"),
        };

        let user_content = message::UserContent::ToolResult(tool_result);
        let msg = message::Message::User {
            content: OneOrMany::one(user_content),
        };

        // Convert to Gemini Content
        let content: Content = msg.try_into().expect("Should convert to Gemini Content");
        assert_eq!(content.role, Some(Role::User));
        assert_eq!(content.parts.len(), 1);

        // Verify the part is a FunctionResponse with both response and parts
        if let Some(Part {
            part: PartKind::FunctionResponse(function_response),
            ..
        }) = content.parts.first()
        {
            assert_eq!(function_response.name, "test_tool");

            // Check that response JSON is present
            assert!(function_response.response.is_some());
            let response = function_response.response.as_ref().unwrap();
            assert!(response.get("result").is_some());

            // Check that parts with image data are present
            assert!(function_response.parts.is_some());
            let parts = function_response.parts.as_ref().unwrap();
            assert_eq!(parts.len(), 1);

            let image_part = &parts[0];
            assert!(image_part.inline_data.is_some());
            let inline_data = image_part.inline_data.as_ref().unwrap();
            assert_eq!(inline_data.mime_type, "image/png");
            assert!(!inline_data.data.is_empty());
        } else {
            panic!("Expected FunctionResponse part");
        }
    }

    #[test]
    fn test_markdown_document_conversion_to_text_part() {
        // Test that MARKDOWN documents are converted to plain text parts
        use crate::message::{DocumentMediaType, UserContent};

        let doc = UserContent::document(
            "# Heading\n\n* List item",
            Some(DocumentMediaType::MARKDOWN),
        );

        let content: Content = message::Message::User {
            content: crate::OneOrMany::one(doc),
        }
        .try_into()
        .unwrap();

        if let Part {
            part: PartKind::Text(text),
            ..
        } = &content.parts[0]
        {
            assert_eq!(text, "# Heading\n\n* List item");
        } else {
            panic!(
                "Expected text part for MARKDOWN document, got: {:?}",
                content.parts[0]
            );
        }
    }

    #[test]
    fn test_markdown_url_document_conversion_to_file_data_part() {
        // URL-backed MARKDOWN documents should be represented as file_data.
        use crate::message::{DocumentMediaType, DocumentSourceKind, UserContent};

        let doc = UserContent::Document(message::Document {
            data: DocumentSourceKind::Url(
                "https://generativelanguage.googleapis.com/v1beta/files/test-markdown".to_string(),
            ),
            media_type: Some(DocumentMediaType::MARKDOWN),
            additional_params: None,
        });

        let content: Content = message::Message::User {
            content: crate::OneOrMany::one(doc),
        }
        .try_into()
        .unwrap();

        if let Part {
            part: PartKind::FileData(file_data),
            ..
        } = &content.parts[0]
        {
            assert_eq!(
                file_data.file_uri,
                "https://generativelanguage.googleapis.com/v1beta/files/test-markdown"
            );
            assert_eq!(file_data.mime_type.as_deref(), Some("text/markdown"));
        } else {
            panic!(
                "Expected file_data part for URL MARKDOWN document, got: {:?}",
                content.parts[0]
            );
        }
    }

    #[test]
    fn test_tool_result_with_url_image() {
        // Test that a ToolResult with a URL-based image converts to file_data
        use crate::OneOrMany;
        use crate::message::{
            DocumentSourceKind, Image, ImageMediaType, ToolResult, ToolResultContent,
        };

        let tool_result = ToolResult {
            id: "screenshot_tool".to_string(),
            call_id: None,
            content: OneOrMany::one(ToolResultContent::Image(Image {
                data: DocumentSourceKind::Url("https://example.com/image.png".to_string()),
                media_type: Some(ImageMediaType::PNG),
                detail: None,
                additional_params: None,
            })),
        };

        let user_content = message::UserContent::ToolResult(tool_result);
        let msg = message::Message::User {
            content: OneOrMany::one(user_content),
        };

        let content: Content = msg.try_into().expect("Should convert to Gemini Content");
        assert_eq!(content.role, Some(Role::User));
        assert_eq!(content.parts.len(), 1);

        if let Some(Part {
            part: PartKind::FunctionResponse(function_response),
            ..
        }) = content.parts.first()
        {
            assert_eq!(function_response.name, "screenshot_tool");

            // URL images should have parts with file_data
            assert!(function_response.parts.is_some());
            let parts = function_response.parts.as_ref().unwrap();
            assert_eq!(parts.len(), 1);

            let image_part = &parts[0];
            assert!(image_part.file_data.is_some());
            let file_data = image_part.file_data.as_ref().unwrap();
            assert_eq!(file_data.file_uri, "https://example.com/image.png");
            assert_eq!(file_data.mime_type.as_ref().unwrap(), "image/png");
        } else {
            panic!("Expected FunctionResponse part");
        }
    }

    #[test]
    fn test_create_request_body_with_documents() {
        // Test that documents are injected into chat history
        use crate::OneOrMany;
        use crate::completion::request::{CompletionRequest, Document};
        use crate::message::Message;

        let documents = vec![
            Document {
                id: "doc1".to_string(),
                text: "Note: first.md\nContent: First note".to_string(),
                additional_props: std::collections::HashMap::new(),
            },
            Document {
                id: "doc2".to_string(),
                text: "Note: second.md\nContent: Second note".to_string(),
                additional_props: std::collections::HashMap::new(),
            },
        ];

        let completion_request = CompletionRequest {
            preamble: Some("You are a helpful assistant".to_string()),
            chat_history: OneOrMany::one(Message::user("What are my notes about?")),
            documents: documents.clone(),
            tools: vec![],
            temperature: None,
            model: None,
            output_schema: None,
            max_tokens: None,
            tool_choice: None,
            additional_params: None,
        };

        let request = create_request_body(completion_request).unwrap();

        // Should have 2 contents: 1 for documents, 1 for user message
        assert_eq!(
            request.contents.len(),
            2,
            "Expected 2 contents (documents + user message)"
        );

        // First content should be documents with role User
        assert_eq!(request.contents[0].role, Some(Role::User));
        assert_eq!(
            request.contents[0].parts.len(),
            2,
            "Expected 2 document parts"
        );

        // Check that documents are text parts
        for part in &request.contents[0].parts {
            if let Part {
                part: PartKind::Text(text),
                ..
            } = part
            {
                assert!(
                    text.contains("Note:") && text.contains("Content:"),
                    "Document should contain note metadata"
                );
            } else {
                panic!("Document parts should be text, not {:?}", part);
            }
        }

        // Second content should be the user message
        assert_eq!(request.contents[1].role, Some(Role::User));
        if let Part {
            part: PartKind::Text(text),
            ..
        } = &request.contents[1].parts[0]
        {
            assert_eq!(text, "What are my notes about?");
        } else {
            panic!("Expected user message to be text");
        }
    }

    #[test]
    fn test_create_request_body_without_documents() {
        // Test backward compatibility: requests without documents work as before
        use crate::OneOrMany;
        use crate::completion::request::CompletionRequest;
        use crate::message::Message;

        let completion_request = CompletionRequest {
            preamble: Some("You are a helpful assistant".to_string()),
            chat_history: OneOrMany::one(Message::user("Hello")),
            documents: vec![], // No documents
            tools: vec![],
            temperature: None,
            max_tokens: None,
            tool_choice: None,
            model: None,
            output_schema: None,
            additional_params: None,
        };

        let request = create_request_body(completion_request).unwrap();

        // Should have only 1 content (the user message)
        assert_eq!(request.contents.len(), 1, "Expected only user message");
        assert_eq!(request.contents[0].role, Some(Role::User));

        if let Part {
            part: PartKind::Text(text),
            ..
        } = &request.contents[0].parts[0]
        {
            assert_eq!(text, "Hello");
        } else {
            panic!("Expected user message to be text");
        }
    }

    #[test]
    fn test_from_tool_output_parses_image_json() {
        // Test the ToolResultContent::from_tool_output helper with image JSON
        use crate::message::{DocumentSourceKind, ToolResultContent};

        // Test simple image JSON format
        let image_json = r#"{"type": "image", "data": "base64data==", "mimeType": "image/jpeg"}"#;
        let result = ToolResultContent::from_tool_output(image_json);

        assert_eq!(result.len(), 1);
        if let ToolResultContent::Image(img) = result.first() {
            assert!(matches!(img.data, DocumentSourceKind::Base64(_)));
            if let DocumentSourceKind::Base64(data) = &img.data {
                assert_eq!(data, "base64data==");
            }
            assert_eq!(img.media_type, Some(crate::message::ImageMediaType::JPEG));
        } else {
            panic!("Expected Image content");
        }
    }

    #[test]
    fn test_from_tool_output_parses_hybrid_json() {
        // Test the ToolResultContent::from_tool_output helper with hybrid response/parts format
        use crate::message::{DocumentSourceKind, ToolResultContent};

        let hybrid_json = r#"{
            "response": {"status": "ok", "count": 42},
            "parts": [
                {"type": "image", "data": "imgdata1==", "mimeType": "image/png"},
                {"type": "image", "data": "https://example.com/img.jpg", "mimeType": "image/jpeg"}
            ]
        }"#;

        let result = ToolResultContent::from_tool_output(hybrid_json);

        // Should have 3 items: 1 text (response) + 2 images (parts)
        assert_eq!(result.len(), 3);

        let items: Vec<_> = result.iter().collect();

        // First should be text with the response JSON
        if let ToolResultContent::Text(text) = &items[0] {
            assert!(text.text.contains("status"));
            assert!(text.text.contains("ok"));
        } else {
            panic!("Expected Text content first");
        }

        // Second should be base64 image
        if let ToolResultContent::Image(img) = &items[1] {
            assert!(matches!(img.data, DocumentSourceKind::Base64(_)));
        } else {
            panic!("Expected Image content second");
        }

        // Third should be URL image
        if let ToolResultContent::Image(img) = &items[2] {
            assert!(matches!(img.data, DocumentSourceKind::Url(_)));
        } else {
            panic!("Expected Image content third");
        }
    }

    /// E2E test that verifies Gemini can process tool results containing images.
    /// This test creates an agent with a tool that returns an image, invokes it,
    /// and verifies that Gemini can interpret the image in the tool result.
    #[tokio::test]
    #[ignore = "requires GEMINI_API_KEY environment variable"]
    async fn test_gemini_agent_with_image_tool_result_e2e() {
        use crate::completion::{Prompt, ToolDefinition};
        use crate::prelude::*;
        use crate::providers::gemini;
        use crate::tool::Tool;
        use serde::{Deserialize, Serialize};

        /// A tool that returns a small red 1x1 pixel PNG image
        #[derive(Debug, Serialize, Deserialize)]
        struct ImageGeneratorTool;

        #[derive(Debug, thiserror::Error)]
        #[error("Image generation error")]
        struct ImageToolError;

        impl Tool for ImageGeneratorTool {
            const NAME: &'static str = "generate_test_image";
            type Error = ImageToolError;
            type Args = serde_json::Value;
            // Return the image in the format that from_tool_output expects
            type Output = String;

            async fn definition(&self, _prompt: String) -> ToolDefinition {
                ToolDefinition {
                    name: "generate_test_image".to_string(),
                    description: "Generates a small test image (a 1x1 red pixel). Call this tool when asked to generate or show an image.".to_string(),
                    parameters: json!({
                        "type": "object",
                        "properties": {},
                        "required": []
                    }),
                }
            }

            async fn call(&self, _args: Self::Args) -> Result<Self::Output, Self::Error> {
                // Return a JSON object that from_tool_output will parse as an image
                // This is a 1x1 red PNG pixel
                Ok(json!({
                    "type": "image",
                    "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==",
                    "mimeType": "image/png"
                }).to_string())
            }
        }

        let client = gemini::Client::from_env();

        let agent = client
            .agent("gemini-3-flash-preview")
            .preamble("You are a helpful assistant. When asked about images, use the generate_test_image tool to create one, then describe what you see in the image.")
            .tool(ImageGeneratorTool)
            .build();

        // This prompt should trigger the tool, which returns an image that Gemini should process
        let response = agent
            .prompt("Please generate a test image and tell me what color the pixel is.")
            .await;

        // The test passes if Gemini successfully processes the request without errors.
        // The image is a 1x1 red pixel, so Gemini should be able to describe it.
        assert!(
            response.is_ok(),
            "Gemini should successfully process tool result with image: {:?}",
            response.err()
        );

        let response_text = response.unwrap();
        println!("Response: {response_text}");
        // Gemini should have been able to see the image and potentially describe its color
        assert!(!response_text.is_empty(), "Response should not be empty");
    }
}