adk-model 3.0.0

LLM model integrations for Rust Agent Development Kit (ADK-Rust) (Gemini, OpenAI, Claude, DeepSeek, etc.)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
use crate::attachment;
use crate::retry::{RetryConfig, execute_with_retry, is_retryable_model_error};
use adk_core::{
    CacheCapable, CitationMetadata, CitationSource, Content, ErrorCategory, ErrorComponent,
    FinishReason, Llm, LlmRequest, LlmResponse, LlmResponseStream, Part, Result, SchemaAdapter,
    SchemaCache, UsageMetadata,
};
use adk_gemini::Gemini;
use adk_gemini::schema_adapter::GeminiSchemaAdapter;
use async_trait::async_trait;
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
use futures::TryStreamExt;

#[cfg(feature = "gemini-interactions")]
use super::interactions_target::InteractionTarget;

/// Which Gemini wire API a [`GeminiModel`] uses.
///
/// Defaults to [`GeminiTransport::GenerateContent`], the classic
/// `models/{model}:generateContent` endpoint. Selecting
/// [`GeminiTransport::Interactions`] (via [`GeminiModel::use_interactions_api`])
/// routes requests through the Interactions API (Beta): a stateful, step-based
/// transport that drives the same [`adk_core::Llm`] contract.
///
/// Only compiled when the `gemini-interactions` feature is enabled.
#[cfg(feature = "gemini-interactions")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GeminiTransport {
    /// The classic `models/{model}:generateContent` API (default).
    #[default]
    GenerateContent,
    /// The Interactions API (Beta): stateful, step-based.
    Interactions,
}

/// Background-execution policy for the Interactions transport.
///
/// Controls whether interactions run with `background=true`. The default,
/// [`BackgroundMode::AgentTargetsOnly`], keeps low-latency chat turns
/// foreground while letting long-running agent targets (e.g. Deep Research)
/// run in the background.
///
/// Only compiled when the `gemini-interactions` feature is enabled.
#[cfg(feature = "gemini-interactions")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BackgroundMode {
    /// `background=true` for agent targets, `false` for model targets
    /// (default). Keeps chat turns low-latency while letting Deep Research and
    /// other long-running agents run in the background.
    #[default]
    AgentTargetsOnly,
    /// Always run interactions with `background=true`.
    Always,
    /// Never run interactions in the background.
    Never,
}

/// Faithful-to-API options for the Interactions transport.
///
/// The defaults mirror the Interactions API's intended posture: interactions
/// are stored (`store = true`), stateful continuation via
/// `previous_interaction_id` is enabled (`stateful = true`), background
/// execution applies to agent targets only
/// ([`BackgroundMode::AgentTargetsOnly`]), and background interactions are
/// polled once per second.
///
/// Only compiled when the `gemini-interactions` feature is enabled.
#[cfg(feature = "gemini-interactions")]
#[derive(Debug, Clone)]
pub struct InteractionOptions {
    /// Whether interactions are stored server-side. Default: `true`.
    pub store: bool,
    /// Whether to continue conversations statefully via
    /// `previous_interaction_id`. Default: `true`.
    pub stateful: bool,
    /// Background-execution policy. Default: [`BackgroundMode::AgentTargetsOnly`].
    pub background: BackgroundMode,
    /// Poll interval for background interactions. Default: 1 second.
    pub poll_interval: std::time::Duration,
}

#[cfg(feature = "gemini-interactions")]
impl Default for InteractionOptions {
    fn default() -> Self {
        Self {
            store: true,
            stateful: true,
            background: BackgroundMode::AgentTargetsOnly,
            poll_interval: std::time::Duration::from_secs(1),
        }
    }
}

/// A file uploaded through the Gemini File API.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct GeminiFile {
    /// The resource name, `files/<id>`.
    pub name: String,
    /// The URI a `Part::FileData` names.
    pub uri: String,
    /// The MIME type Gemini recorded.
    pub mime_type: Option<String>,
    /// The size in bytes.
    pub size_bytes: Option<u64>,
    /// Whether Gemini has processed it.
    pub state: GeminiFileState,
}

impl GeminiFile {
    fn from_wire(file: &adk_gemini::File) -> Result<Self> {
        let uri = file.uri.as_ref().map(ToString::to_string).ok_or_else(|| {
            adk_core::AdkError::model(format!("the File API returned {} without a URI", file.name))
        })?;
        Ok(Self {
            name: file.name.clone(),
            uri,
            mime_type: file.mime_type.clone(),
            size_bytes: file.size_bytes.and_then(|n| u64::try_from(n).ok()),
            state: match file.state {
                Some(adk_gemini::FileState::Active) => GeminiFileState::Active,
                Some(adk_gemini::FileState::Processing) => GeminiFileState::Processing,
                Some(adk_gemini::FileState::Failed) => GeminiFileState::Failed,
                _ => GeminiFileState::Unknown,
            },
        })
    }
}

/// Where Gemini is in processing an uploaded file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum GeminiFileState {
    /// Being processed; a video is not usable yet.
    Processing,
    /// Ready to use.
    Active,
    /// Processing failed.
    Failed,
    /// Not reported, or deleted.
    Unknown,
}

/// `true` for a URI Gemini fetches itself: a File API, Cloud Storage or HTTP(S) URI.
fn is_fetchable_uri(uri: &str) -> bool {
    let scheme = uri.split_once("://").map(|(s, _)| s.to_ascii_lowercase());
    matches!(scheme.as_deref(), Some("https" | "http" | "gs"))
}

/// Gemini model client wrapping the `adk-gemini` crate for the `Llm` trait.
pub struct GeminiModel {
    client: Gemini,
    model_name: String,
    retry_config: RetryConfig,
    /// Default thinking configuration applied to every request.
    ///
    /// Controls the model's reasoning effort. For Gemini 3 series, use
    /// `ThinkingLevel` (Low/Medium/High). For Gemini 2.5 series, use
    /// `thinking_budget` (token count).
    thinking_config: Option<adk_gemini::ThinkingConfig>,
    /// Selected wire transport. Defaults to
    /// [`GeminiTransport::GenerateContent`]; set to
    /// [`GeminiTransport::Interactions`] via [`GeminiModel::use_interactions_api`].
    #[cfg(feature = "gemini-interactions")]
    transport: GeminiTransport,
    /// The validated Interactions destination, populated when the Interactions
    /// transport is enabled. `None` for the generateContent transport.
    #[cfg(feature = "gemini-interactions")]
    interaction_target: Option<InteractionTarget>,
    /// Faithful-to-API options for the Interactions transport.
    #[cfg(feature = "gemini-interactions")]
    interaction_options: InteractionOptions,
    /// Server-side RAG grounding declaration attached to every request.
    /// Vertex AI backend only; see [`GeminiModel::with_vertex_rag_store`].
    #[cfg(feature = "gemini-vertex")]
    vertex_rag_store: Option<adk_gemini::VertexRagStore>,
    /// Whether the wrapped client targets the Vertex AI backend (as opposed
    /// to AI Studio). Set by the `new_google_cloud*` constructors.
    #[cfg(feature = "gemini-vertex")]
    vertex_backend: bool,
}

/// Built-in tool uses observed across the responses of one Gemini call.
///
/// Search is counted per distinct `webSearchQueries` entry, Maps once per grounded
/// response and code execution per `executableCode` part.
#[derive(Debug, Default)]
struct GeminiBuiltinToolUses {
    search_queries: std::collections::BTreeSet<String>,
    maps_grounded: bool,
    code_executions: u32,
}

impl GeminiBuiltinToolUses {
    fn observe(&mut self, response: &adk_gemini::GenerationResponse) {
        let Some(candidate) = response.candidates.first() else {
            return;
        };
        if let Some(grounding) = &candidate.grounding_metadata {
            self.search_queries.extend(grounding.web_search_queries.iter().flatten().cloned());
            self.maps_grounded |=
                grounding.grounding_chunks.iter().flatten().any(|chunk| chunk.maps.is_some());
        }
        let executions = candidate
            .content
            .parts
            .iter()
            .flatten()
            .filter(|part| matches!(part, adk_gemini::Part::ExecutableCode { .. }))
            .count();
        self.code_executions =
            self.code_executions.saturating_add(u32::try_from(executions).unwrap_or(u32::MAX));
    }

    fn uses(&self) -> Vec<adk_core::BuiltinToolUse> {
        let searches = u32::try_from(self.search_queries.len()).unwrap_or(u32::MAX);
        [
            ("code_execution", self.code_executions),
            ("google_maps", u32::from(self.maps_grounded)),
            ("google_search", searches),
        ]
        .into_iter()
        .filter(|(_, count)| *count > 0)
        .map(|(kind, count)| adk_core::BuiltinToolUse::new(kind, count))
        .collect()
    }
}

/// Converts a Gemini client error into an [`adk_core::AdkError`] for both the AI Studio
/// and Vertex AI backends.
///
/// The category comes from the HTTP status the transport reported, or, without one,
/// from the RPC status code or the typed transport failure; error text never decides
/// it. 500, 502, 503 and other 5xx statuses are `Unavailable` and 504 is `Timeout`, so
/// all are retried; 403 is `Forbidden`. The provider's own code is kept in
/// `details.metadata["provider_error_code"]`: the first `ErrorInfo.reason`, then the
/// error object's string `code`, then its `status`.
pub(crate) fn gemini_error_to_adk(e: &adk_gemini::ClientError) -> adk_core::AdkError {
    fn format_error_chain(e: &dyn std::error::Error) -> String {
        let mut msg = e.to_string();
        let mut source = e.source();
        while let Some(s) = source {
            msg.push_str(": ");
            msg.push_str(&s.to_string());
            source = s.source();
        }
        msg
    }

    // A response body can echo the request, so the message quotes a bounded excerpt.
    let message = format_error_chain(e);
    let message = adk_core::upstream_excerpt(&message);

    // Response text can mention a different status; only the transport may
    // establish an upstream HTTP status.
    let status_code = match e {
        adk_gemini::ClientError::BadResponse { code, .. } => Some(*code),
        #[cfg(feature = "gemini-vertex")]
        adk_gemini::ClientError::GoogleCloudRequest { source } => source.http_status_code(),
        _ => None,
    };
    // An error object inside a successful response reports its own status; the
    // transport status stays unset.
    let reported_status = match e {
        adk_gemini::ClientError::ErrorInResponse { code, .. } => *code,
        _ => None,
    };
    let (category, code) = match status_code.or(reported_status) {
        Some(401) => (ErrorCategory::Unauthorized, "model.gemini.unauthorized"),
        Some(403) => (ErrorCategory::Forbidden, "model.gemini.forbidden"),
        Some(404) => (ErrorCategory::NotFound, "model.gemini.not_found"),
        Some(408 | 504) => (ErrorCategory::Timeout, "model.gemini.timeout"),
        Some(429) => (ErrorCategory::RateLimited, "model.gemini.rate_limited"),
        Some(529) => (ErrorCategory::Unavailable, "model.gemini.overloaded"),
        Some(400..=499) => (ErrorCategory::InvalidInput, "model.gemini.bad_request"),
        Some(500..=599) => (ErrorCategory::Unavailable, "model.gemini.unavailable"),
        _ => error_without_status(e),
    };

    let mut err = adk_core::AdkError::new(ErrorComponent::Model, category, code, message)
        .with_provider("gemini");
    if let Some(status_code) = status_code {
        err = err.with_upstream_status(status_code);
    }
    // One rule for every backend: the first `ErrorInfo.reason`, then the error
    // object's string `code`, then its `status`.
    let provider_code = match e {
        adk_gemini::ClientError::BadResponse { description: Some(body), .. }
        | adk_gemini::ClientError::ErrorInResponse { description: body, .. } => {
            crate::error_metadata::code_from_body(body)
        }
        #[cfg(feature = "gemini-vertex")]
        adk_gemini::ClientError::GoogleCloudRequest { source } => {
            let status = source.status();
            let reason = status.into_iter().flat_map(|status| &status.details).find_map(|detail| {
                let detail = serde_json::to_value(detail).ok()?;
                if !detail["@type"].as_str().is_some_and(crate::error_metadata::is_error_info) {
                    return None;
                }
                detail["reason"].as_str().filter(|reason| !reason.is_empty()).map(str::to_owned)
            });
            reason
                .or_else(|| {
                    let body = std::str::from_utf8(source.http_payload()?).ok()?;
                    crate::error_metadata::code_from_body(body)
                })
                .or_else(|| {
                    status
                        .map(|status| status.code.name())
                        .filter(|name| *name != "OK")
                        .map(str::to_owned)
                })
        }
        _ => None,
    };
    let err = crate::error_metadata::with_code(err, provider_code.as_deref());
    let header = match e {
        adk_gemini::ClientError::BadResponse { retry_after: Some(header), .. } => {
            crate::retry::parse_retry_after(header)
        }
        _ => None,
    };
    crate::retry::with_retry_after(err, header.or_else(|| retry_info_delay(e)))
}

/// The delay a `google.rpc.RetryInfo` detail of the error asks for: the Gemini API reports
/// the wait a quota needs there (`"retryDelay": "37s"`), not in a `Retry-After` header.
fn retry_info_delay(error: &adk_gemini::ClientError) -> Option<std::time::Duration> {
    let details: Vec<serde_json::Value> = match error {
        adk_gemini::ClientError::BadResponse { description: Some(body), .. }
        | adk_gemini::ClientError::ErrorInResponse { description: body, .. } => {
            if body.len() > crate::error_metadata::MAX_BODY_LEN {
                return None;
            }
            let body: serde_json::Value = serde_json::from_str(body).ok()?;
            let error =
                body.get("error").or_else(|| body.get(0).and_then(|item| item.get("error")))?;
            error.get("details")?.as_array()?.clone()
        }
        #[cfg(feature = "gemini-vertex")]
        adk_gemini::ClientError::GoogleCloudRequest { source } => source
            .status()?
            .details
            .iter()
            .filter_map(|detail| serde_json::to_value(detail).ok())
            .collect(),
        _ => return None,
    };
    details
        .iter()
        .filter(|detail| {
            detail["@type"].as_str().is_some_and(|kind| kind.ends_with("google.rpc.RetryInfo"))
        })
        .find_map(|detail| parse_rpc_duration(detail["retryDelay"].as_str()?))
}

/// Parses a protobuf `Duration` in its JSON form (`"12s"`, `"1.5s"`), rounded up to whole
/// milliseconds so a retry never starts early. Negative or malformed values are `None`.
fn parse_rpc_duration(value: &str) -> Option<std::time::Duration> {
    let value = value.strip_suffix('s')?;
    let (seconds, fraction) = value.split_once('.').unwrap_or((value, ""));
    let digits = |text: &str| text.bytes().all(|byte| byte.is_ascii_digit());
    if seconds.is_empty() || !digits(seconds) || fraction.len() > 9 || !digits(fraction) {
        return None;
    }
    let nanos: u32 = format!("{fraction:0<9}").parse().ok()?;
    let delay = std::time::Duration::new(seconds.parse().ok()?, nanos);
    let millis = u64::try_from(delay.as_nanos().div_ceil(1_000_000)).ok()?;
    Some(std::time::Duration::from_millis(millis))
}

/// Whether a google-cloud-gax error without a status is a failed connection or
/// transport. gax's `is_connect`/`is_transport` are hidden and outside its semver
/// guarantee, so this reads the prefixes its `Display` writes for those kinds.
#[cfg(feature = "gemini-vertex")]
fn is_gax_connection_failure(message: &str) -> bool {
    message.starts_with("cannot connect to endpoint")
        || message.starts_with("the transport reports an error")
}

/// Classify failures with no HTTP response without inventing an upstream status.
fn error_without_status(error: &adk_gemini::ClientError) -> (ErrorCategory, &'static str) {
    if let Some(error) = error.request_error() {
        let category = crate::http_timeouts::transport_category(error);
        let code = if category == ErrorCategory::Timeout {
            "model.gemini.timeout"
        } else {
            "model.gemini.unavailable"
        };
        return (category, code);
    }
    match error {
        adk_gemini::ClientError::InvalidGenerationConfig { .. } => {
            (ErrorCategory::InvalidInput, "model.gemini.invalid_config")
        }
        adk_gemini::ClientError::Validation { .. } => {
            (ErrorCategory::InvalidInput, "model.gemini.bad_request")
        }
        adk_gemini::ClientError::InvalidApiKey { .. } => {
            (ErrorCategory::Unauthorized, "model.gemini.unauthorized")
        }
        #[cfg(feature = "gemini-vertex")]
        adk_gemini::ClientError::GoogleCloudRequest { source } if source.is_timeout() => {
            (ErrorCategory::Timeout, "model.gemini.timeout")
        }
        #[cfg(feature = "gemini-vertex")]
        adk_gemini::ClientError::GoogleCloudRequest { source } => {
            if let Some(status) = source.status() {
                category_for_rpc_status(status.code.name())
            } else if is_gax_connection_failure(&source.to_string()) {
                (ErrorCategory::Unavailable, "model.gemini.unavailable")
            } else {
                (ErrorCategory::Internal, "model.gemini.internal")
            }
        }
        adk_gemini::ClientError::ErrorInResponse { status: Some(status), .. } => {
            category_for_rpc_status(status)
        }
        _ => (ErrorCategory::Internal, "model.gemini.internal"),
    }
}

/// Classifies a Google RPC status name such as `UNAVAILABLE`.
fn category_for_rpc_status(name: &str) -> (ErrorCategory, &'static str) {
    match name {
        "RESOURCE_EXHAUSTED" => (ErrorCategory::RateLimited, "model.gemini.rate_limited"),
        "UNAVAILABLE" => (ErrorCategory::Unavailable, "model.gemini.unavailable"),
        "DEADLINE_EXCEEDED" => (ErrorCategory::Timeout, "model.gemini.timeout"),
        "UNAUTHENTICATED" => (ErrorCategory::Unauthorized, "model.gemini.unauthorized"),
        "PERMISSION_DENIED" => (ErrorCategory::Forbidden, "model.gemini.forbidden"),
        "NOT_FOUND" => (ErrorCategory::NotFound, "model.gemini.not_found"),
        "INVALID_ARGUMENT" => (ErrorCategory::InvalidInput, "model.gemini.bad_request"),
        _ => (ErrorCategory::Internal, "model.gemini.internal"),
    }
}

/// Maps a terminal [`InteractionStatus`](adk_gemini::interactions::InteractionStatus)
/// to a `Result`, surfacing the API's failure states as errors.
///
/// The Interactions API can terminate an interaction in `failed` or
/// `budget_exceeded` (Requirements 7.7 / 9.2). This helper converts those two
/// states into an [`adk_core::AdkError`] (provider `"gemini"`, category
/// [`ErrorCategory::Internal`]) and treats every other status as success — the
/// caller has already decided to read the interaction's content for non-failure
/// states. Factored out as a free function so the terminal-status mapping is
/// unit-testable without a network round-trip.
#[cfg(feature = "gemini-interactions")]
fn interaction_status_to_result(status: adk_gemini::interactions::InteractionStatus) -> Result<()> {
    use adk_gemini::interactions::InteractionStatus;
    match status {
        InteractionStatus::Failed => Err(interaction_terminal_error(
            "model.gemini.interactions.failed",
            "the Gemini interaction terminated with status `failed`",
        )),
        InteractionStatus::BudgetExceeded => Err(interaction_terminal_error(
            "model.gemini.interactions.budget_exceeded",
            "the Gemini interaction terminated with status `budget_exceeded`",
        )),
        InteractionStatus::RequiresContinuation => {
            tracing::warn!(
                "gemini interaction stopped at its per-request output cap with token budget left; \
                 no continuation request is sent, so the turn ends with finish reason MaxTokens"
            );
            Ok(())
        }
        InteractionStatus::InProgress
        | InteractionStatus::RequiresAction
        | InteractionStatus::Completed
        | InteractionStatus::Cancelled
        | InteractionStatus::Incomplete
        | InteractionStatus::Unknown => Ok(()),
        _ => Ok(()),
    }
}

/// Builds the [`adk_core::AdkError`] for a terminal Interactions failure status.
#[cfg(feature = "gemini-interactions")]
fn interaction_terminal_error(code: &'static str, message: &str) -> adk_core::AdkError {
    adk_core::AdkError::new(
        ErrorComponent::Model,
        ErrorCategory::Internal,
        code,
        message.to_string(),
    )
    .with_provider("gemini")
}

/// Returns the value of the environment variable `name` when it is set and
/// non-empty (after trimming whitespace).
fn env_non_empty(name: &str) -> Option<String> {
    std::env::var(name).ok().filter(|v| !v.trim().is_empty())
}

/// Returns `true` when an opt-in flag value selects the Vertex AI backend:
/// `1` or a case-insensitive `true`.
fn env_flag_truthy(value: &str) -> bool {
    let v = value.trim();
    v == "1" || v.eq_ignore_ascii_case("true")
}

/// Reports whether the environment opts in to the Vertex AI backend.
///
/// Consults `GOOGLE_GENAI_USE_ENTERPRISE` first and, when that variable is
/// unset or empty, the deprecated `GOOGLE_GENAI_USE_VERTEXAI`. A flag is
/// truthy when its value is `1` or a case-insensitive `true`.
/// `GOOGLE_GENAI_USE_ENTERPRISE` takes precedence when both are set.
///
/// # Example
///
/// ```rust,no_run
/// if adk_model::gemini::vertex_env_requested() {
///     // route Gemini traffic through Vertex AI
/// }
/// ```
pub fn vertex_env_requested() -> bool {
    // `GOOGLE_GENAI_USE_VERTEXAI` is the deprecated name adk-python still
    // honors. Deliberately no deprecation warning for it —
    // google/adk-python#6168 documents the churn such a warning caused.
    if let Some(v) = env_non_empty("GOOGLE_GENAI_USE_ENTERPRISE") {
        return env_flag_truthy(&v);
    }
    env_non_empty("GOOGLE_GENAI_USE_VERTEXAI").is_some_and(|v| env_flag_truthy(&v))
}

/// Reads `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`, erroring with a
/// message that names whichever variable is missing.
#[cfg(feature = "gemini-vertex")]
fn vertex_target_from_env() -> Result<(String, String)> {
    let project = env_non_empty("GOOGLE_CLOUD_PROJECT");
    let location = env_non_empty("GOOGLE_CLOUD_LOCATION");
    if let (Some(project), Some(location)) = (&project, &location) {
        return Ok((project.clone(), location.clone()));
    }
    let mut missing = Vec::new();
    if project.is_none() {
        missing.push("GOOGLE_CLOUD_PROJECT");
    }
    if location.is_none() {
        missing.push("GOOGLE_CLOUD_LOCATION");
    }
    Err(adk_core::AdkError::new(
        ErrorComponent::Model,
        ErrorCategory::InvalidInput,
        "model.gemini.vertex_env_incomplete",
        format!(
            "Vertex AI backend selected via GOOGLE_GENAI_USE_ENTERPRISE/GOOGLE_GENAI_USE_VERTEXAI, but {} not set. Set the missing variable(s) to your Google Cloud project ID and region (e.g. us-central1).",
            missing.join(" and ")
        ),
    )
    .with_provider("gemini"))
}

impl GeminiModel {
    /// The thinking configuration of one request (spec 3.1 §7.23, §10 C4): the request's
    /// `effort` becomes the `thinking_level` for this call on Gemini 3 and later, or on any
    /// model configured with a level, replacing a configured token budget; elsewhere it is
    /// logged and ignored.
    fn request_thinking_config(&self, req: &LlmRequest) -> Option<adk_gemini::ThinkingConfig> {
        let configured = self.thinking_config.clone();
        let Some(level) = req.config.as_ref().and_then(|config| config.effort) else {
            return configured;
        };
        let configured_level =
            configured.as_ref().is_some_and(|config| config.thinking_level.is_some());
        let generation = self.model_name.find("gemini-").and_then(|start| {
            let version = &self.model_name[start + "gemini-".len()..];
            let end = version.find(|c: char| !c.is_ascii_digit()).unwrap_or(version.len());
            version[..end].parse::<u32>().ok()
        });
        if !configured_level && generation.is_none_or(|major| major < 3) {
            tracing::debug!(
                model.name = %self.model_name,
                effort = %level,
                "model takes no thinking level; the request's effort is ignored"
            );
            return configured;
        }
        let mut config = configured.unwrap_or_default();
        config.thinking_budget = None;
        config.thinking_level = Some(level.into());
        Some(config)
    }

    fn gemini_part_thought_signature(value: &serde_json::Value) -> Option<String> {
        value.get("thoughtSignature").and_then(serde_json::Value::as_str).map(str::to_string)
    }

    /// The Gemini part a stored server-tool payload replays as: a `toolCall`, `toolResponse`,
    /// `executableCode` or `codeExecutionResult` part, or the code-execution shape the Vertex
    /// AI session service restores (`vertexExecutableCode`, `vertexCodeExecutionResult`), with
    /// its thought signature. `None` for any other payload.
    fn native_server_part(payload: &serde_json::Value) -> Option<adk_gemini::Part> {
        let thought_signature = Self::gemini_part_thought_signature(payload);
        if let Some(executable_code) = payload.get("vertexExecutableCode") {
            return Some(adk_gemini::Part::ExecutableCode {
                executable_code: executable_code.clone(),
                thought_signature,
            });
        }
        if let Some(code_execution_result) = payload.get("vertexCodeExecutionResult") {
            return Some(adk_gemini::Part::CodeExecutionResult {
                code_execution_result: code_execution_result.clone(),
                thought_signature,
            });
        }
        match serde_json::from_value::<adk_gemini::Part>(payload.clone()).ok()? {
            part @ (adk_gemini::Part::ToolCall { .. }
            | adk_gemini::Part::ToolResponse { .. }
            | adk_gemini::Part::ExecutableCode { .. }
            | adk_gemini::Part::CodeExecutionResult { .. }) => Some(part),
            adk_gemini::Part::Text { .. }
            | adk_gemini::Part::InlineData { .. }
            | adk_gemini::Part::FileData { .. }
            | adk_gemini::Part::FunctionCall { .. }
            | adk_gemini::Part::FunctionResponse { .. } => None,
        }
    }

    fn validate_request_contract(&self, req: &LlmRequest, stream: bool) -> Result<()> {
        // Server-side RAG grounding is a Vertex AI capability; reject it on
        // the AI Studio backend before any network IO (mirrors the request-
        // time gating the Vertex backend applies to Studio-only fields).
        #[cfg(feature = "gemini-vertex")]
        if self.vertex_rag_store.is_some() && !self.vertex_backend {
            return Err(adk_core::AdkError::new(
                ErrorComponent::Model,
                ErrorCategory::Unsupported,
                "model.gemini.rag_store_requires_vertex",
                "Vertex RAG store grounding requires the Vertex AI backend. Construct the model with new_google_cloud/new_google_cloud_adc (or set GOOGLE_GENAI_USE_VERTEXAI with GOOGLE_CLOUD_PROJECT/GOOGLE_CLOUD_LOCATION) instead of an AI Studio API key.",
            )
            .with_provider("gemini"));
        }

        let model = self.model_name.strip_prefix("models/").unwrap_or(&self.model_name);
        let gemini_4 = !self.supports_explicit_cache();
        if !gemini_4
            && !matches!(model, "gemini-3.6-flash" | "gemini-3.7-flash" | "gemini-3.8-flash")
        {
            return Ok(());
        }

        if let Some(config) = &req.config
            && (config.temperature.is_some() || config.top_p.is_some() || config.top_k.is_some())
        {
            return Err(adk_core::AdkError::new(
                ErrorComponent::Model,
                ErrorCategory::InvalidInput,
                "model.gemini.sampling_unsupported",
                format!(
                    "{model} does not accept temperature, top_p, or top_k; remove explicit sampling parameters"
                ),
            )
            .with_provider("gemini"));
        }
        if !gemini_4 {
            if self.thinking_config.as_ref().is_some_and(|config| config.thinking_budget.is_some())
            {
                return Err(adk_core::AdkError::new(
                    ErrorComponent::Model,
                    ErrorCategory::InvalidInput,
                    "model.gemini.thinking_budget_unsupported",
                    format!(
                        "{model} uses thinking levels instead of token budgets; set thinking_level and clear thinking_budget"
                    ),
                )
                .with_provider("gemini"));
            }
            return Ok(());
        }

        // Gemini 4 (https://aistudio.google.com/docs/whats-new-gemini-4-hydrogen and the Neon,
        // Carbon and Argon pages): a token budget maps to the nearest level, so only levels
        // are checked.
        let carbon_or_argon = matches!(model, "gemini-4-carbon" | "gemini-4-argon");
        let refused_level = match self.request_thinking_config(req).and_then(|c| c.thinking_level) {
            Some(adk_gemini::ThinkingLevel::Minimal) => Some("minimal"),
            Some(adk_gemini::ThinkingLevel::XHigh) if carbon_or_argon => Some("xhigh"),
            _ => None,
        };
        if let Some(level) = refused_level {
            return Err(adk_core::AdkError::new(
                ErrorComponent::Model,
                ErrorCategory::InvalidInput,
                "model.gemini.thinking_level_unsupported",
                format!(
                    "{model} does not accept thinking level {level}; set low, medium or high \
                     (xhigh runs on gemini-4-neon and gemini-4-hydrogen)"
                ),
            )
            .with_provider("gemini"));
        }
        if req.config.as_ref().is_some_and(|config| config.cached_content.is_some()) {
            return Err(adk_core::AdkError::new(
                ErrorComponent::Model,
                ErrorCategory::Unsupported,
                "model.gemini.explicit_cache_unsupported",
                format!(
                    "{model} does not support explicit context caching; remove cached_content \
                     (implicit caching applies to prompts of at least 4,096 tokens)"
                ),
            )
            .with_provider("gemini"));
        }
        // https://aistudio.google.com/docs/long-decode: a direct non-streaming generateContent
        // call to Carbon or Argon returns at most 32,768 tokens and refuses a larger cap.
        #[cfg(feature = "gemini-interactions")]
        let interactions = self.transport == GeminiTransport::Interactions;
        #[cfg(not(feature = "gemini-interactions"))]
        let interactions = false;
        if carbon_or_argon
            && !stream
            && !interactions
            && req
                .config
                .as_ref()
                .and_then(|config| config.max_output_tokens)
                .is_some_and(|max| max > 32_768)
        {
            return Err(adk_core::AdkError::new(
                ErrorComponent::Model,
                ErrorCategory::InvalidInput,
                "model.gemini.output_cap_exceeded",
                format!(
                    "{model} returns at most 32,768 output tokens on a non-streaming call; set \
                     max_output_tokens to 32768 or less, or stream the request"
                ),
            )
            .with_provider("gemini"));
        }
        Ok(())
    }

    /// Whether the model supports explicit context caching
    /// ([`create_cached_content`](Self::create_cached_content) and `cached_content` on a
    /// request). The Gemini 4 models do not: they cache implicitly
    /// (<https://aistudio.google.com/docs/whats-new-gemini-4-hydrogen>).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use adk_model::GeminiModel;
    ///
    /// let model = GeminiModel::new("api-key", "gemini-4-hydrogen")?;
    /// assert!(!model.supports_explicit_cache());
    /// # Ok::<(), adk_core::AdkError>(())
    /// ```
    pub fn supports_explicit_cache(&self) -> bool {
        let model = self.model_name.strip_prefix("models/").unwrap_or(&self.model_name);
        !matches!(
            model,
            "gemini-4-carbon" | "gemini-4-argon" | "gemini-4-neon" | "gemini-4-hydrogen"
        )
    }

    /// Builds a `GeminiModel` from a constructed client and model name with all
    /// configurable fields defaulted.
    ///
    /// Centralizing struct construction here keeps the cfg-gated Interactions
    /// fields out of every public constructor's `Self { .. }` literal.
    pub(crate) fn from_client(client: Gemini, model_name: String) -> Self {
        Self {
            client,
            model_name,
            retry_config: RetryConfig::default(),
            thinking_config: None,
            #[cfg(feature = "gemini-interactions")]
            transport: GeminiTransport::GenerateContent,
            #[cfg(feature = "gemini-interactions")]
            interaction_target: None,
            #[cfg(feature = "gemini-interactions")]
            interaction_options: InteractionOptions::default(),
            #[cfg(feature = "gemini-vertex")]
            vertex_rag_store: None,
            #[cfg(feature = "gemini-vertex")]
            vertex_backend: false,
        }
    }

    /// Create a new Gemini model client with an API key and model name.
    pub fn new(api_key: impl Into<String>, model: impl Into<String>) -> Result<Self> {
        let model_name = model.into();
        crate::catalog::warn_if_obsolete("gemini", &model_name);
        let client = Gemini::with_model(api_key.into(), model_name.clone())
            .map_err(|e| adk_core::AdkError::model(e.to_string()))?;

        Ok(Self::from_client(client, model_name))
    }

    /// Create an API-key model using an explicit REST base URL.
    ///
    /// The base URL includes the API version and ends with a slash. No environment
    /// variable is read.
    ///
    /// # Errors
    ///
    /// Returns an error when `base_url` is not a valid URL or the client cannot be built.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_model::GeminiModel;
    ///
    /// let model = GeminiModel::new_with_base_url(
    ///     "api-key",
    ///     "gemini-3.8-flash",
    ///     "https://gateway.example.com/v1beta/",
    /// )?;
    /// # Ok::<(), adk_core::AdkError>(())
    /// ```
    pub fn new_with_base_url(
        api_key: impl Into<String>,
        model: impl Into<String>,
        base_url: impl AsRef<str>,
    ) -> Result<Self> {
        let model_name = model.into();
        let base_url = base_url
            .as_ref()
            .parse()
            .map_err(|_| adk_core::AdkError::model("Invalid Gemini base URL"))?;
        let client = Gemini::with_model_and_base_url(api_key.into(), model_name.clone(), base_url)
            .map_err(|e| adk_core::AdkError::model(e.to_string()))?;
        Ok(Self::from_client(client, model_name))
    }

    /// Create an API-key model with explicit connect and byte-idle timeouts.
    ///
    /// The other API-key constructors apply [`HttpTimeouts::default`](crate::HttpTimeouts),
    /// the SDK's own defaults. This constructor uses the same SDK builder and adds no
    /// response-level or total-request timer.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_model::{GeminiModel, HttpTimeouts};
    /// use std::time::Duration;
    ///
    /// let model = GeminiModel::new_with_base_url_and_timeouts(
    ///     "api-key", "gemini-3.8-flash", "https://gateway.example.com/v1beta/",
    ///     HttpTimeouts::new(Duration::from_secs(30), Duration::from_secs(300)),
    /// )?;
    /// # Ok::<(), adk_core::AdkError>(())
    /// ```
    pub fn new_with_base_url_and_timeouts(
        api_key: impl Into<String>,
        model: impl Into<String>,
        base_url: impl AsRef<str>,
        timeouts: crate::HttpTimeouts,
    ) -> Result<Self> {
        let model_name = model.into();
        let base_url = base_url
            .as_ref()
            .parse()
            .map_err(|_| adk_core::AdkError::model("Invalid Gemini base URL"))?;
        let client = adk_gemini::GeminiBuilder::new(api_key.into())
            .with_model(model_name.clone())
            .with_base_url(base_url)
            .with_http_client(timeouts.apply(reqwest::Client::builder()))
            .build()
            .map_err(|error| gemini_error_to_adk(&error))?;
        Ok(Self::from_client(client, model_name))
    }

    /// Create a Gemini model via Vertex AI with API key auth.
    ///
    /// Requires `gemini-vertex` feature.
    #[cfg(feature = "gemini-vertex")]
    pub fn new_google_cloud(
        api_key: impl Into<String>,
        project_id: impl AsRef<str>,
        location: impl AsRef<str>,
        model: impl Into<String>,
    ) -> Result<Self> {
        let model_name = model.into();
        let client = Gemini::with_google_cloud_model(
            api_key.into(),
            project_id,
            location,
            model_name.clone(),
        )
        .map_err(|e| adk_core::AdkError::model(e.to_string()))?;

        let mut model = Self::from_client(client, model_name);
        model.vertex_backend = true;
        Ok(model)
    }

    /// Use an explicit Vertex endpoint and either a supplied key or execution-host ADC.
    ///
    /// Requires `gemini-vertex` feature.
    ///
    /// # Errors
    ///
    /// Returns an error when Application Default Credentials are requested
    /// (`api_key` is `None`) but unavailable, or when the client cannot be built.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use adk_model::GeminiModel;
    ///
    /// let model = GeminiModel::new_google_cloud_endpoint(
    ///     None,
    ///     "my-project",
    ///     "us-central1",
    ///     "gemini-3.8-flash",
    ///     "https://us-central1-aiplatform.googleapis.com",
    /// )?;
    /// # Ok::<(), adk_core::AdkError>(())
    /// ```
    #[cfg(feature = "gemini-vertex")]
    pub fn new_google_cloud_endpoint(
        api_key: Option<&str>,
        project: &str,
        location: &str,
        model_name: &str,
        endpoint: &str,
    ) -> Result<Self> {
        let mut builder = adk_gemini::GeminiBuilder::new(api_key.unwrap_or_default())
            .with_model(model_name.to_owned())
            .with_google_cloud(project, location)
            .with_google_cloud_endpoint(endpoint);
        if api_key.is_none() {
            builder = builder.with_google_cloud_adc().map_err(|e| gemini_error_to_adk(&e))?;
        }
        let client = builder.build().map_err(|e| gemini_error_to_adk(&e))?;
        let mut model = Self::from_client(client, model_name.to_owned());
        model.vertex_backend = true;
        Ok(model)
    }

    /// Create a Gemini model via Vertex AI with service account JSON.
    ///
    /// Requires `gemini-vertex` feature.
    #[cfg(feature = "gemini-vertex")]
    pub fn new_google_cloud_service_account(
        service_account_json: &str,
        project_id: impl AsRef<str>,
        location: impl AsRef<str>,
        model: impl Into<String>,
    ) -> Result<Self> {
        let model_name = model.into();
        let client = Gemini::with_google_cloud_service_account_json(
            service_account_json,
            project_id.as_ref(),
            location.as_ref(),
            model_name.clone(),
        )
        .map_err(|e| adk_core::AdkError::model(e.to_string()))?;

        let mut model = Self::from_client(client, model_name);
        model.vertex_backend = true;
        Ok(model)
    }

    /// Create a Gemini model via Vertex AI with Application Default Credentials.
    ///
    /// Requires `gemini-vertex` feature.
    #[cfg(feature = "gemini-vertex")]
    pub fn new_google_cloud_adc(
        project_id: impl AsRef<str>,
        location: impl AsRef<str>,
        model: impl Into<String>,
    ) -> Result<Self> {
        let model_name = model.into();
        let client = Gemini::with_google_cloud_adc_model(
            project_id.as_ref(),
            location.as_ref(),
            model_name.clone(),
        )
        .map_err(|e| adk_core::AdkError::model(e.to_string()))?;

        let mut model = Self::from_client(client, model_name);
        model.vertex_backend = true;
        Ok(model)
    }

    /// Create a Gemini model via Vertex AI with Workload Identity Federation.
    ///
    /// Requires `gemini-vertex` feature.
    #[cfg(feature = "gemini-vertex")]
    pub fn new_google_cloud_wif(
        wif_json: &str,
        project_id: impl AsRef<str>,
        location: impl AsRef<str>,
        model: impl Into<String>,
    ) -> Result<Self> {
        let model_name = model.into();
        let client = Gemini::with_google_cloud_wif_json(
            wif_json,
            project_id.as_ref(),
            location.as_ref(),
            model_name.clone(),
        )
        .map_err(|e| adk_core::AdkError::model(e.to_string()))?;

        let mut model = Self::from_client(client, model_name);
        model.vertex_backend = true;
        Ok(model)
    }

    /// Create a Gemini model from environment variables.
    ///
    /// When `GOOGLE_GENAI_USE_ENTERPRISE` or `GOOGLE_GENAI_USE_VERTEXAI` is
    /// truthy (`1` or a case-insensitive `true`), builds a Vertex AI client
    /// with Application Default Credentials from `GOOGLE_CLOUD_PROJECT` and
    /// `GOOGLE_CLOUD_LOCATION` — this path requires the `gemini-vertex`
    /// feature. Otherwise builds a Gemini API (AI Studio) client from
    /// `GOOGLE_API_KEY` or `GEMINI_API_KEY`.
    ///
    /// `GOOGLE_GENAI_USE_ENTERPRISE` takes precedence when both flags are set.
    ///
    /// The Vertex path builds Application Default Credentials, which requires
    /// a Tokio runtime to be current — call from async code or under
    /// `#[tokio::main]`.
    ///
    /// # Errors
    ///
    /// - A Vertex flag is truthy but `GOOGLE_CLOUD_PROJECT` or
    ///   `GOOGLE_CLOUD_LOCATION` is not set.
    /// - A Vertex flag is truthy but the `gemini-vertex` feature is not
    ///   compiled.
    /// - No Vertex flag is truthy and neither `GOOGLE_API_KEY` nor
    ///   `GEMINI_API_KEY` is set.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use adk_model::gemini::GeminiModel;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> adk_core::Result<()> {
    /// let model = GeminiModel::from_env("gemini-3.8-flash")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_env(model: &str) -> Result<Self> {
        if vertex_env_requested() {
            #[cfg(feature = "gemini-vertex")]
            {
                let (project, location) = vertex_target_from_env()?;
                return Self::new_google_cloud_adc(project, location, model);
            }
            #[cfg(not(feature = "gemini-vertex"))]
            {
                return Err(adk_core::AdkError::new(
                    ErrorComponent::Model,
                    ErrorCategory::Unsupported,
                    "model.gemini.vertex_feature_missing",
                    "Vertex AI backend selected via GOOGLE_GENAI_USE_ENTERPRISE/GOOGLE_GENAI_USE_VERTEXAI, but the `gemini-vertex` feature is not compiled. Enable the `gemini-vertex` feature (or `gemini-agent-platform` on the adk-rust umbrella crate) to route Gemini traffic through Vertex AI.",
                )
                .with_provider("gemini"));
            }
        }

        let Some(api_key) =
            env_non_empty("GOOGLE_API_KEY").or_else(|| env_non_empty("GEMINI_API_KEY"))
        else {
            return Err(adk_core::AdkError::new(
                ErrorComponent::Model,
                ErrorCategory::InvalidInput,
                "model.gemini.api_key_missing",
                "No Gemini API key found. Set GOOGLE_API_KEY or GEMINI_API_KEY, or set GOOGLE_GENAI_USE_ENTERPRISE=true with GOOGLE_CLOUD_PROJECT/GOOGLE_CLOUD_LOCATION for Vertex AI.",
            )
            .with_provider("gemini"));
        };
        Self::new(api_key, model)
    }

    /// Set the retry configuration (builder pattern).
    #[must_use]
    pub fn with_retry_config(mut self, retry_config: RetryConfig) -> Self {
        self.retry_config = retry_config;
        self
    }

    /// Set the retry configuration (mutable reference).
    pub fn set_retry_config(&mut self, retry_config: RetryConfig) {
        self.retry_config = retry_config;
    }

    /// Returns the current retry configuration.
    pub fn retry_config(&self) -> &RetryConfig {
        &self.retry_config
    }

    /// Set the default thinking configuration applied to every request.
    ///
    /// Controls the model's reasoning effort. For Gemini 3 series models,
    /// use `ThinkingLevel` (Low/Medium/High). For Gemini 2.5 series, use
    /// `thinking_budget` (token count).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_gemini::{ThinkingConfig, ThinkingLevel};
    ///
    /// // Gemini 3 — level-based thinking
    /// let model = GeminiModel::new(api_key, "gemini-3.1-pro-preview")?
    ///     .with_thinking_config(
    ///         ThinkingConfig::new().with_thinking_level(ThinkingLevel::Low)
    ///     );
    ///
    /// // Gemini 2.5 — budget-based thinking
    /// let model = GeminiModel::new(api_key, "gemini-3.8-flash")?
    ///     .with_thinking_config(
    ///         ThinkingConfig::new().with_thinking_budget(2048)
    ///     );
    /// ```
    #[must_use]
    pub fn with_thinking_config(mut self, thinking_config: adk_gemini::ThinkingConfig) -> Self {
        self.thinking_config = Some(thinking_config);
        self
    }

    /// Set the thinking configuration (mutable reference variant).
    pub fn set_thinking_config(&mut self, thinking_config: adk_gemini::ThinkingConfig) {
        self.thinking_config = Some(thinking_config);
    }

    /// Returns the current thinking configuration, if set.
    pub fn thinking_config(&self) -> Option<&adk_gemini::ThinkingConfig> {
        self.thinking_config.as_ref()
    }

    /// Ground every request in a Vertex AI RAG store (server-side retrieval).
    ///
    /// Declares a `retrieval` tool on each outgoing `generateContent` request
    /// so Vertex AI retrieves grounding context from the referenced RAG
    /// corpora before generating. Requires a Vertex AI backend — requests on
    /// an AI Studio model fail with the structured error
    /// `model.gemini.rag_store_requires_vertex` before any network IO.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use adk_gemini::VertexRagStore;
    /// use adk_model::gemini::GeminiModel;
    ///
    /// # fn main() -> adk_core::Result<()> {
    /// let store = VertexRagStore::corpus("projects/p/locations/us-central1/ragCorpora/123")
    ///     .with_top_k(5);
    /// let model =
    ///     GeminiModel::new_google_cloud("api-key", "p", "us-central1", "gemini-3.8-flash")?
    ///         .with_vertex_rag_store(store);
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "gemini-vertex")]
    #[must_use]
    pub fn with_vertex_rag_store(mut self, store: adk_gemini::VertexRagStore) -> Self {
        self.vertex_rag_store = Some(store);
        self
    }

    /// Returns the configured Vertex RAG store, if set.
    #[cfg(feature = "gemini-vertex")]
    pub fn vertex_rag_store(&self) -> Option<&adk_gemini::VertexRagStore> {
        self.vertex_rag_store.as_ref()
    }

    /// Enable (or disable) the Interactions API transport.
    ///
    /// When enabling, the model's configured model id is validated against the
    /// Interactions allowlist via [`InteractionTarget::parse`]. On success the
    /// transport switches to [`GeminiTransport::Interactions`] and the
    /// validated target is stored. Disabling reverts to
    /// [`GeminiTransport::GenerateContent`] and clears the stored target.
    ///
    /// Requires the `gemini-interactions` feature.
    ///
    /// # Errors
    ///
    /// Returns an [`adk_core::AdkError`] with category `InvalidInput` when
    /// enabling the transport for a model id outside the Interactions
    /// allowlist (Requirement 2.4). The error message names the supported
    /// model and agent targets.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let model = GeminiModel::new(api_key, "gemini-3.8-flash")?
    ///     .use_interactions_api(true)?;
    /// ```
    #[cfg(feature = "gemini-interactions")]
    pub fn use_interactions_api(mut self, enabled: bool) -> Result<Self> {
        if enabled {
            let target = InteractionTarget::parse(&self.model_name)?;
            self.transport = GeminiTransport::Interactions;
            self.interaction_target = Some(target);
        } else {
            self.transport = GeminiTransport::GenerateContent;
            self.interaction_target = None;
        }
        Ok(self)
    }

    /// Override the Interactions transport options (store, stateful, background
    /// mode, poll interval).
    ///
    /// Requires the `gemini-interactions` feature. The defaults (see
    /// [`InteractionOptions::default`]) mirror the Interactions API's intended
    /// posture; override only when a different behavior is required.
    #[cfg(feature = "gemini-interactions")]
    #[must_use]
    pub fn interaction_options(mut self, opts: InteractionOptions) -> Self {
        self.interaction_options = opts;
        self
    }

    /// Returns the currently selected wire transport.
    ///
    /// Requires the `gemini-interactions` feature.
    #[cfg(feature = "gemini-interactions")]
    pub fn transport(&self) -> GeminiTransport {
        self.transport
    }

    /// Returns the configured Interactions options.
    ///
    /// Requires the `gemini-interactions` feature.
    #[cfg(feature = "gemini-interactions")]
    pub fn interaction_options_ref(&self) -> &InteractionOptions {
        &self.interaction_options
    }

    /// Resolves whether background execution should be used for the configured
    /// Interactions target, honoring [`BackgroundMode`].
    ///
    /// Returns `true` when the mode is [`BackgroundMode::Always`], `false` when
    /// [`BackgroundMode::Never`], and (for [`BackgroundMode::AgentTargetsOnly`])
    /// `true` only when the configured target is an agent target. When no
    /// Interactions target is configured, agent-targets-only resolves to
    /// `false`.
    ///
    /// Used by the non-streaming/background Interactions path (task 7.3); kept
    /// here so the transport state and its policy resolution live together.
    #[cfg(feature = "gemini-interactions")]
    fn resolve_background(&self) -> bool {
        match self.interaction_options.background {
            BackgroundMode::Always => true,
            BackgroundMode::Never => false,
            BackgroundMode::AgentTargetsOnly => {
                self.interaction_target.as_ref().is_some_and(InteractionTarget::is_agent)
            }
        }
    }

    fn convert_response(resp: &adk_gemini::GenerationResponse) -> Result<LlmResponse> {
        let mut converted_parts: Vec<Part> = Vec::new();

        // Convert content parts
        if let Some(parts) = resp.candidates.first().and_then(|c| c.content.parts.as_ref()) {
            for p in parts {
                match p {
                    adk_gemini::Part::Text { text, thought, thought_signature } => {
                        if thought == &Some(true) {
                            converted_parts.push(Part::Thinking {
                                thinking: text.clone(),
                                signature: thought_signature.clone(),
                            });
                        } else {
                            converted_parts.push(Part::Text { text: text.clone() });
                        }
                    }
                    adk_gemini::Part::InlineData { inline_data, .. } => {
                        let decoded =
                            BASE64_STANDARD.decode(&inline_data.data).map_err(|error| {
                                adk_core::AdkError::model(format!(
                                    "failed to decode inline data from gemini response: {error}"
                                ))
                            })?;
                        converted_parts.push(Part::InlineData {
                            mime_type: inline_data.mime_type.clone(),
                            data: decoded,
                            uri: None,
                            annotations: None,
                        });
                    }
                    adk_gemini::Part::FunctionCall { function_call, thought_signature } => {
                        converted_parts.push(Part::FunctionCall {
                            name: function_call.name.clone(),
                            args: function_call.args.clone(),
                            id: function_call.id.clone(),
                            thought_signature: thought_signature.clone(),
                        });
                    }
                    adk_gemini::Part::FunctionResponse { function_response, .. } => {
                        converted_parts.push(Part::FunctionResponse {
                            function_response: adk_core::FunctionResponseData::new(
                                function_response.name.clone(),
                                function_response
                                    .response
                                    .clone()
                                    .unwrap_or(serde_json::Value::Null),
                            ),
                            id: None,
                            annotations: None,
                        });
                    }
                    adk_gemini::Part::ToolCall { .. } | adk_gemini::Part::ExecutableCode { .. } => {
                        if let Ok(value) = serde_json::to_value(p) {
                            converted_parts.push(Part::ServerToolCall { server_tool_call: value });
                        }
                    }
                    adk_gemini::Part::ToolResponse { .. }
                    | adk_gemini::Part::CodeExecutionResult { .. } => {
                        let value = serde_json::to_value(p).unwrap_or(serde_json::Value::Null);
                        converted_parts
                            .push(Part::ServerToolResponse { server_tool_response: value });
                    }
                    adk_gemini::Part::FileData { file_data, .. } => {
                        converted_parts.push(Part::FileData {
                            mime_type: file_data.mime_type.clone(),
                            file_uri: file_data.file_uri.clone(),
                            annotations: None,
                        });
                    }
                }
            }
        }

        let content = if converted_parts.is_empty() {
            None
        } else {
            Some(Content { role: "model".to_string(), parts: converted_parts })
        };
        let tool_call_turn = content.as_ref().is_some_and(Content::has_function_calls);

        let usage_metadata = resp.usage_metadata.as_ref().map(|u| {
            let prompt = u.prompt_token_count.unwrap_or(0);
            // Gemini's candidate count excludes the separately reported thoughts.
            let candidates = u
                .candidates_token_count
                .unwrap_or(0)
                .saturating_add(u.thoughts_token_count.unwrap_or(0));
            UsageMetadata {
                prompt_token_count: prompt,
                candidates_token_count: candidates,
                // An unreported total is at least the parts that were reported.
                total_token_count: u
                    .total_token_count
                    .unwrap_or_else(|| prompt.saturating_add(candidates)),
                thinking_token_count: u.thoughts_token_count,
                cache_read_input_token_count: u.cached_content_token_count,
                // As received, so fields such as `toolUsePromptTokenCount` survive.
                provider_usage: u.raw.clone().or_else(|| serde_json::to_value(u).ok()),
                builtin_tool_uses: {
                    let mut uses = GeminiBuiltinToolUses::default();
                    uses.observe(resp);
                    uses.uses()
                },
                ..Default::default()
            }
        });

        let finish_reason =
            resp.candidates.first().and_then(|c| c.finish_reason.as_ref()).map(|fr| match fr {
                adk_gemini::FinishReason::Stop => FinishReason::Stop,
                // A long-decode hop stops at the per-request cap; no continuation request is
                // sent, so the response is cut short.
                adk_gemini::FinishReason::MaxTokens | adk_gemini::FinishReason::Continuation => {
                    FinishReason::MaxTokens
                }
                adk_gemini::FinishReason::Safety
                | adk_gemini::FinishReason::Blocklist
                | adk_gemini::FinishReason::ProhibitedContent
                | adk_gemini::FinishReason::Spii
                | adk_gemini::FinishReason::ImageSafety
                | adk_gemini::FinishReason::ModelArmor => FinishReason::Safety,
                adk_gemini::FinishReason::Recitation => FinishReason::Recitation,
                // https://ai.google.dev/api/generate-content#FinishReason: the function call is
                // invalid, or names a tool when no tools were enabled.
                adk_gemini::FinishReason::MalformedFunctionCall
                | adk_gemini::FinishReason::UnexpectedToolCall => FinishReason::MalformedToolCall,
                adk_gemini::FinishReason::FinishReasonUnspecified
                | adk_gemini::FinishReason::Language
                | adk_gemini::FinishReason::Other
                | adk_gemini::FinishReason::TooManyToolCalls
                | adk_gemini::FinishReason::MissingThoughtSignature
                | adk_gemini::FinishReason::MalformedResponse => FinishReason::Other,
                _ => FinishReason::Other,
            });
        // A blocked prompt has no candidates: it ends the turn as a safety stop, and
        // `error_code` marks it as a failure rather than an empty answer.
        let block_reason = resp
            .prompt_feedback
            .as_ref()
            .and_then(|feedback| feedback.block_reason.as_ref())
            .and_then(|reason| match reason {
                adk_gemini::BlockReason::BlockReasonUnspecified => None,
                adk_gemini::BlockReason::Safety => Some("SAFETY"),
                adk_gemini::BlockReason::Other => Some("OTHER"),
                adk_gemini::BlockReason::Blocklist => Some("BLOCKLIST"),
                adk_gemini::BlockReason::ProhibitedContent => Some("PROHIBITED_CONTENT"),
                adk_gemini::BlockReason::ModelArmor => Some("MODEL_ARMOR"),
                adk_gemini::BlockReason::Jailbreak => Some("JAILBREAK"),
                adk_gemini::BlockReason::ImageSafety => Some("IMAGE_SAFETY"),
            });
        let finish_reason =
            if block_reason.is_some() { Some(FinishReason::Safety) } else { finish_reason };

        let citation_metadata =
            resp.candidates.first().and_then(|c| c.citation_metadata.as_ref()).map(|meta| {
                CitationMetadata {
                    citation_sources: meta
                        .citation_sources
                        .iter()
                        .map(|source| CitationSource {
                            uri: source.uri.clone(),
                            title: source.title.clone(),
                            start_index: source.start_index,
                            end_index: source.end_index,
                            license: source.license.clone(),
                            publication_date: source.publication_date.map(|d| d.to_string()),
                        })
                        .collect(),
                }
            });

        // Serialize grounding metadata into provider_metadata so consumers
        // can display search queries and sources without changing the answer.
        let mut provider_metadata = resp
            .candidates
            .first()
            .and_then(|c| c.grounding_metadata.as_ref())
            .and_then(|g| serde_json::to_value(g).ok());
        // Requested through `GenerateContentConfig::top_logprobs`; kept as Gemini sent them.
        if let Some(logprobs) = resp
            .candidates
            .first()
            .and_then(|c| c.logprobs_result.as_ref())
            .and_then(|result| serde_json::to_value(result).ok())
            && let serde_json::Value::Object(metadata) =
                provider_metadata.get_or_insert_with(|| serde_json::json!({}))
        {
            metadata.insert("logprobs".to_string(), logprobs);
        }

        Ok(LlmResponse {
            content,
            usage_metadata,
            finish_reason,
            citation_metadata,
            partial: false,
            turn_complete: !tool_call_turn,
            interrupted: false,
            error_code: block_reason.map(str::to_owned),
            error_message: block_reason
                .map(|reason| format!("Gemini blocked the prompt (blockReason {reason})")),
            provider_metadata,
            interaction_id: None,
            model: resp.model_version.clone().filter(|version| !version.is_empty()),
            provider: None,
        })
    }

    fn gemini_function_response_payload(response: serde_json::Value) -> serde_json::Value {
        match response {
            // Gemini functionResponse.response must be a JSON object.
            serde_json::Value::Object(_) => response,
            other => serde_json::json!({ "result": other }),
        }
    }

    fn merge_object_value(
        target: &mut serde_json::Map<String, serde_json::Value>,
        value: serde_json::Value,
    ) {
        if let serde_json::Value::Object(object) = value {
            for (key, value) in object {
                target.insert(key, value);
            }
        }
    }

    fn build_gemini_tools(
        tools: &adk_core::ToolDeclarations,
        adapter: &dyn SchemaAdapter,
        cache: &SchemaCache,
    ) -> Result<(Vec<adk_gemini::Tool>, adk_gemini::ToolConfig)> {
        let mut gemini_tools = Vec::new();
        let mut function_declarations = Vec::new();
        let mut has_provider_native_tools = false;
        let mut tool_config_json = serde_json::Map::new();

        for (name, tool_decl) in tools {
            if let Some(provider_tool) = tool_decl.get("x-adk-gemini-tool") {
                let tool = serde_json::from_value::<adk_gemini::Tool>(provider_tool.clone())
                    .map_err(|error| {
                        adk_core::AdkError::model(format!(
                            "failed to deserialize Gemini native tool '{name}': {error}"
                        ))
                    })?;
                has_provider_native_tools = true;
                gemini_tools.push(tool);
            } else {
                // Normalize tool name via the schema adapter
                let normalized_name = adapter.normalize_tool_name(name);

                // Get the parameters schema from the declaration, or use the
                // adapter's empty_schema fallback when none is provided.
                let schema =
                    tool_decl.get("parameters").cloned().unwrap_or_else(|| adapter.empty_schema());
                let normalized_schema = cache.normalize(&schema);

                // Build the FunctionDeclaration with normalized values
                let description =
                    tool_decl.get("description").and_then(|v| v.as_str()).unwrap_or("").to_string();

                let mut func_decl_json = serde_json::json!({
                    "name": normalized_name.as_ref(),
                    "description": description,
                    "parameters": normalized_schema,
                });

                // Preserve response schema if present (normalized like parameters)
                if let Some(response) = tool_decl.get("response") {
                    func_decl_json["response"] = cache.normalize(response);
                }

                // Preserve behavior if present
                if let Some(behavior) = tool_decl.get("behavior") {
                    func_decl_json["behavior"] = behavior.clone();
                }

                let func_decl =
                    serde_json::from_value::<adk_gemini::FunctionDeclaration>(func_decl_json)
                        .map_err(|error| {
                            adk_core::AdkError::model(format!(
                                "failed to build Gemini function declaration for '{name}': {error}"
                            ))
                        })?;
                function_declarations.push(func_decl);
            }

            if let Some(tool_config) = tool_decl.get("x-adk-gemini-tool-config") {
                Self::merge_object_value(&mut tool_config_json, tool_config.clone());
            }
        }

        let has_function_declarations = !function_declarations.is_empty();
        if has_function_declarations {
            gemini_tools.push(adk_gemini::Tool::with_functions(function_declarations));
        }

        if has_provider_native_tools {
            tool_config_json.insert(
                "includeServerSideToolInvocations".to_string(),
                serde_json::Value::Bool(true),
            );
        }

        let tool_config = if tool_config_json.is_empty() {
            adk_gemini::ToolConfig::default()
        } else {
            serde_json::from_value::<adk_gemini::ToolConfig>(serde_json::Value::Object(
                tool_config_json,
            ))
            .map_err(|error| {
                adk_core::AdkError::model(format!(
                    "failed to deserialize Gemini tool configuration: {error}"
                ))
            })?
        };

        Ok((gemini_tools, tool_config))
    }

    /// Splits one streamed Gemini response into the chunks the stream yields.
    ///
    /// A response without `finishReason` is a partial chunk. Its function calls go to
    /// `deferred_calls` and reach the stream once, ahead of the final chunk's own parts:
    /// the agent repeats every partial chunk's content in the terminal event it persists,
    /// so a call yielded mid-stream would appear twice to anything counting calls over
    /// events (spec 3.1 §7.13).
    fn stream_chunks_from_response(
        mut response: LlmResponse,
        saw_partial_chunk: bool,
        deferred_calls: &mut Vec<Part>,
    ) -> (Vec<LlmResponse>, bool) {
        let is_final = response.finish_reason.is_some();

        if !is_final {
            response.partial = true;
            response.turn_complete = false;
            if let Some(content) = response.content.as_mut() {
                let (calls, rest): (Vec<Part>, Vec<Part>) = std::mem::take(&mut content.parts)
                    .into_iter()
                    .partition(|part| matches!(part, Part::FunctionCall { .. }));
                deferred_calls.extend(calls);
                content.parts = rest;
            }
            if response.content.as_ref().is_some_and(|content| content.parts.is_empty()) {
                response.content = None;
            }
            return (vec![response], true);
        }

        response.partial = false;
        if !deferred_calls.is_empty() {
            let content = response
                .content
                .get_or_insert_with(|| Content { role: "model".to_string(), parts: Vec::new() });
            let mut parts = std::mem::take(deferred_calls);
            parts.append(&mut content.parts);
            content.parts = parts;
        }
        response.turn_complete =
            response.content.as_ref().is_none_or(|content| !content.has_function_calls());

        if saw_partial_chunk {
            return (vec![response], true);
        }

        let synthetic_partial = LlmResponse {
            content: None,
            usage_metadata: None,
            finish_reason: None,
            citation_metadata: None,
            partial: true,
            turn_complete: false,
            interrupted: false,
            error_code: None,
            error_message: None,
            provider_metadata: None,
            interaction_id: None,
            model: None,
            provider: None,
        };

        (vec![synthetic_partial, response], true)
    }

    async fn generate_content_internal(
        &self,
        req: LlmRequest,
        stream: bool,
    ) -> Result<LlmResponseStream> {
        let mut builder = self.client.generate_content();
        let thinking_config = self.request_thinking_config(&req);

        // Build a map of function_name → thought_signature from FunctionCall parts
        // in model content. Gemini 3.x requires thought_signature on FunctionResponse
        // parts when thinking is active, but adk_core::Part::FunctionResponse doesn't
        // carry it (it's Gemini-specific). We recover it here at the provider boundary.
        let mut fn_call_signatures: std::collections::HashMap<String, String> =
            std::collections::HashMap::new();
        for content in &req.contents {
            if content.role == "model" {
                for part in &content.parts {
                    if let Part::FunctionCall { name, thought_signature: Some(sig), .. } = part {
                        fn_call_signatures.insert(name.clone(), sig.clone());
                    }
                }
            }
        }

        // System contents become Gemini's `systemInstruction`, as adk-python and adk-go send
        // the agent's instruction. A request on a context cache keeps them as leading user
        // turns: the cache already carries a system instruction, and Gemini takes only one.
        let on_cache = req.config.as_ref().is_some_and(|config| config.cached_content.is_some());
        if !on_cache {
            let instruction: Vec<&str> = req
                .contents
                .iter()
                .filter(|content| content.role == "system")
                .flat_map(|content| content.parts.iter().filter_map(Part::text))
                .filter(|text| !text.trim().is_empty())
                .collect();
            if !instruction.is_empty() {
                builder = builder.with_system_instruction(instruction.join("\n\n"));
            }
        }

        // Add contents using proper builder methods
        for content in &join_function_responses(&req.contents) {
            match content.role.as_str() {
                "system" if !on_cache => {}
                "user" | "system" => {
                    // For user messages, build gemini Content with potentially multiple parts
                    let mut gemini_parts = Vec::new();
                    for part in &content.parts {
                        match part {
                            Part::Text { text } => {
                                gemini_parts.push(adk_gemini::Part::Text {
                                    text: text.clone(),
                                    thought: None,
                                    thought_signature: None,
                                });
                            }
                            Part::InlineData { data, mime_type, annotations, .. } => {
                                let encoded = attachment::encode_base64(data);
                                gemini_parts.push(adk_gemini::Part::InlineData {
                                    inline_data: adk_gemini::Blob {
                                        mime_type: mime_type.clone(),
                                        data: encoded,
                                    },
                                    video_metadata: super::options::video_metadata(
                                        annotations.as_ref(),
                                    ),
                                });
                            }
                            // Gemini fetches File API, Cloud Storage and HTTP(S) URIs itself;
                            // any other scheme (`artifact://`, `file://`) would fail the
                            // request, so it stays a text reference.
                            Part::FileData { mime_type, file_uri, annotations }
                                if is_fetchable_uri(file_uri) =>
                            {
                                gemini_parts.push(adk_gemini::Part::FileData {
                                    file_data: adk_gemini::FileDataRef {
                                        mime_type: mime_type.clone(),
                                        file_uri: file_uri.clone(),
                                    },
                                    video_metadata: super::options::video_metadata(
                                        annotations.as_ref(),
                                    ),
                                });
                            }
                            Part::FileData { mime_type, file_uri, .. } => {
                                gemini_parts.push(adk_gemini::Part::Text {
                                    text: attachment::file_attachment_to_text(mime_type, file_uri),
                                    thought: None,
                                    thought_signature: None,
                                });
                            }
                            _ => {}
                        }
                    }
                    if !gemini_parts.is_empty() {
                        let user_content = adk_gemini::Content {
                            role: Some(adk_gemini::Role::User),
                            parts: Some(gemini_parts),
                        };
                        builder = builder.with_message(adk_gemini::Message {
                            content: user_content,
                            role: adk_gemini::Role::User,
                        });
                    }
                }
                "model" => {
                    // For model messages, build gemini Content
                    let mut gemini_parts = Vec::new();
                    for part in &content.parts {
                        match part {
                            Part::Text { text } => {
                                gemini_parts.push(adk_gemini::Part::Text {
                                    text: text.clone(),
                                    thought: None,
                                    thought_signature: None,
                                });
                            }
                            Part::Thinking { thinking, signature } => {
                                gemini_parts.push(adk_gemini::Part::Text {
                                    text: thinking.clone(),
                                    thought: Some(true),
                                    thought_signature: signature.clone(),
                                });
                            }
                            Part::FunctionCall { name, args, thought_signature, id } => {
                                gemini_parts.push(adk_gemini::Part::FunctionCall {
                                    function_call: adk_gemini::FunctionCall {
                                        name: name.clone(),
                                        args: args.clone(),
                                        id: id.clone(),
                                        thought_signature: None,
                                    },
                                    thought_signature: thought_signature.clone(),
                                });
                            }
                            // Only a payload that is a Gemini part replays: another
                            // provider's payload (Anthropic's preserved message holds its
                            // thinking) never reaches Gemini.
                            Part::ServerToolCall { server_tool_call: payload }
                            | Part::ServerToolResponse { server_tool_response: payload } => {
                                match Self::native_server_part(payload) {
                                    Some(native_part) => gemini_parts.push(native_part),
                                    None => tracing::debug!(
                                        "server tool payload is not a gemini part; left out"
                                    ),
                                }
                            }
                            _ => {}
                        }
                    }
                    if !gemini_parts.is_empty() {
                        let model_content = adk_gemini::Content {
                            role: Some(adk_gemini::Role::Model),
                            parts: Some(gemini_parts),
                        };
                        builder = builder.with_message(adk_gemini::Message {
                            content: model_content,
                            role: adk_gemini::Role::Model,
                        });
                    }
                }
                "function" => {
                    // For function responses, build content directly to attach thought_signature
                    // recovered from the preceding FunctionCall (Gemini 3.x requirement)
                    let mut gemini_parts = Vec::new();
                    for part in &content.parts {
                        if let Part::FunctionResponse { function_response, id, .. } = part {
                            let sig = fn_call_signatures.get(&function_response.name).cloned();

                            // Build nested FunctionResponsePart entries for multimodal data
                            let mut fr_parts = Vec::new();
                            for inline in &function_response.inline_data {
                                let encoded = attachment::encode_base64(&inline.data);
                                fr_parts.push(adk_gemini::FunctionResponsePart::InlineData {
                                    inline_data: adk_gemini::Blob {
                                        mime_type: inline.mime_type.clone(),
                                        data: encoded,
                                    },
                                });
                            }
                            for file in &function_response.file_data {
                                fr_parts.push(adk_gemini::FunctionResponsePart::FileData {
                                    file_data: adk_gemini::FileDataRef {
                                        mime_type: file.mime_type.clone(),
                                        file_uri: file.file_uri.clone(),
                                    },
                                });
                            }

                            let mut gemini_fr = adk_gemini::tools::FunctionResponse::new(
                                &function_response.name,
                                Self::gemini_function_response_payload(
                                    function_response.response.clone(),
                                ),
                            );
                            gemini_fr.parts = fr_parts;
                            // Echo the call id so Gemini 3.x strict response matching
                            // (id + name + count) can correlate this response.
                            gemini_fr.id = id.clone();

                            gemini_parts.push(adk_gemini::Part::FunctionResponse {
                                function_response: gemini_fr,
                                thought_signature: sig,
                            });
                        }
                    }
                    if !gemini_parts.is_empty() {
                        let fn_content = adk_gemini::Content {
                            role: Some(adk_gemini::Role::User),
                            parts: Some(gemini_parts),
                        };
                        builder = builder.with_message(adk_gemini::Message {
                            content: fn_content,
                            role: adk_gemini::Role::User,
                        });
                    }
                }
                _ => {}
            }
        }

        // Add generation config
        if let Some(config) = req.config {
            let has_schema = config.response_schema.is_some();
            let options = super::options::GeminiRequestOptions::from_config(&config);
            let gen_config = adk_gemini::GenerationConfig {
                temperature: config.temperature,
                top_p: config.top_p,
                top_k: config.top_k,
                max_output_tokens: config.max_output_tokens,
                stop_sequences: (!config.stop_sequences.is_empty())
                    .then_some(config.stop_sequences),
                seed: config.seed,
                presence_penalty: config.presence_penalty,
                frequency_penalty: config.frequency_penalty,
                response_logprobs: config.top_logprobs.map(|_| true),
                logprobs: config.top_logprobs.map(i32::from),
                // The response schema takes the same OpenAPI subset as tool parameters:
                // Gemini rejects `additionalProperties` and the other JSON Schema
                // keywords there with HTTP 400.
                response_schema: config
                    .response_schema
                    .map(|schema| self.schema_adapter().normalize_schema(schema)),
                response_modalities: config.response_modalities,
                response_mime_type: if has_schema {
                    Some("application/json".to_string())
                } else {
                    None
                },
                thinking_config: thinking_config.clone(),
                media_resolution: options.media_resolution,
                ..Default::default()
            };
            builder = builder.with_generation_config(gen_config);

            // Attach cached content reference if provided
            if let Some(ref name) = config.cached_content {
                let handle = self.client.get_cached_content(name);
                builder = builder.with_cached_content(&handle);
            }
        } else if thinking_config.is_some() {
            // No generation config from the request, but we have a default
            // thinking config — apply it in an otherwise-default gen config.
            let gen_config = adk_gemini::GenerationConfig {
                thinking_config: thinking_config.clone(),
                ..Default::default()
            };
            builder = builder.with_generation_config(gen_config);
        }

        // Add tools
        if !req.tools.is_empty() {
            let adapter = self.schema_adapter();
            use std::sync::LazyLock;
            static SCHEMA_CACHE: LazyLock<SchemaCache> = LazyLock::new(|| {
                SchemaCache::for_adapter(std::sync::Arc::new(GeminiSchemaAdapter::new()))
            });
            let (gemini_tools, tool_config) =
                Self::build_gemini_tools(&req.tools, adapter, &SCHEMA_CACHE)?;
            for tool in gemini_tools {
                builder = builder.with_tool(tool);
            }
            if tool_config != adk_gemini::ToolConfig::default() {
                builder = builder.with_tool_config(tool_config);
            }
        }

        // Declare server-side RAG grounding; the Vertex backend injects it
        // as a `retrieval` tool at send time (validate_request_contract has
        // already rejected the Studio backend at this point).
        #[cfg(feature = "gemini-vertex")]
        if let Some(store) = &self.vertex_rag_store {
            builder = builder.with_vertex_rag_store(store.clone());
        }

        if stream {
            adk_telemetry::debug!("Executing streaming request");
            let response_stream = builder.execute_stream().await.map_err(|e| {
                let error = gemini_error_to_adk(&e);
                adk_telemetry::error!(error = %error.diagnostics(), "model request failed");
                error
            })?;

            let mapped_stream = async_stream::stream! {
                let mut stream = response_stream;
                let mut saw_partial_chunk = false;
                // Function calls from partial chunks, yielded once on the final chunk.
                let mut deferred_calls: Vec<Part> = Vec::new();
                // Only a chunk with `finishReason` (or a prompt block) ends a Gemini turn.
                let mut finished = false;
                // Gemini reports usage cumulatively per chunk; built-in tool uses follow suit.
                let mut builtin_uses = GeminiBuiltinToolUses::default();
                while let Some(result) = stream.try_next().await.transpose() {
                    match result {
                        Ok(resp) => {
                            builtin_uses.observe(&resp);
                            match Self::convert_response(&resp) {
                                Ok(mut llm_resp) => {
                                    if let Some(usage) = llm_resp.usage_metadata.as_mut() {
                                        usage.builtin_tool_uses = builtin_uses.uses();
                                    }
                                    finished |= llm_resp.finish_reason.is_some();
                                    let (chunks, next_saw_partial) =
                                        Self::stream_chunks_from_response(
                                            llm_resp,
                                            saw_partial_chunk,
                                            &mut deferred_calls,
                                        );
                                    saw_partial_chunk = next_saw_partial;
                                    for chunk in chunks {
                                        yield Ok(chunk);
                                    }
                                }
                                Err(e) => {
                                    adk_telemetry::error!(error = %e.diagnostics(), "failed to convert response");
                                    yield Err(e);
                                    return;
                                }
                            }
                        }
                        Err(e) => {
                            if finished && matches!(&e,
                                adk_gemini::ClientError::PerformRequestNew { .. }
                                | adk_gemini::ClientError::PerformRequest { .. }
                                | adk_gemini::ClientError::BadPart { .. }
                                | adk_gemini::ClientError::Deserialize { .. }
                                | adk_gemini::ClientError::DecodeResponse { .. }
                                | adk_gemini::ClientError::Io { .. }
                            ) {
                                return;
                            }
                            let error = gemini_error_to_adk(&e);
                            adk_telemetry::error!(error = %error.diagnostics(), "stream error");
                            yield Err(error);
                            return;
                        }
                    }
                }
                if !finished {
                    yield Err(adk_core::AdkError::new(
                        ErrorComponent::Model,
                        ErrorCategory::Unavailable,
                        "model.gemini.unfinished_stream",
                        "Gemini stream ended before any chunk carried a finish reason",
                    )
                    .with_provider("gemini"));
                }
            };

            Ok(crate::usage_tracking::with_terminal_usage(Box::pin(mapped_stream)))
        } else {
            adk_telemetry::debug!("Executing blocking request");
            let response = builder.execute().await.map_err(|e| {
                let error = gemini_error_to_adk(&e);
                adk_telemetry::error!(error = %error.diagnostics(), "model request failed");
                error
            })?;

            let llm_response = Self::convert_response(&response)?;

            let stream = async_stream::stream! {
                yield Ok(llm_response);
            };

            Ok(Box::pin(stream))
        }
    }

    /// Create a cached content resource with the given system instruction, tools, and TTL.
    ///
    /// Returns the cache name (e.g., "cachedContents/abc123") on success.
    /// The cache is created using the model configured on this `GeminiModel` instance.
    ///
    /// # Errors
    ///
    /// Returns `model.gemini.explicit_cache_unsupported` for a model without explicit caching
    /// (see [`supports_explicit_cache`](Self::supports_explicit_cache)), and an error when the
    /// cache cannot be created.
    pub async fn create_cached_content(
        &self,
        system_instruction: &str,
        tools: &adk_core::ToolDeclarations,
        ttl_seconds: u32,
    ) -> Result<String> {
        if !self.supports_explicit_cache() {
            return Err(adk_core::AdkError::new(
                ErrorComponent::Model,
                ErrorCategory::Unsupported,
                "model.gemini.explicit_cache_unsupported",
                format!(
                    "{} does not support explicit context caching; it caches prompts of at least \
                     4,096 tokens implicitly",
                    self.model_name
                ),
            )
            .with_provider("gemini"));
        }
        let mut cache_builder = self
            .client
            .create_cache()
            .with_system_instruction(system_instruction)
            .with_ttl(std::time::Duration::from_secs(u64::from(ttl_seconds)));

        let adapter = self.schema_adapter();
        use std::sync::LazyLock;
        static SCHEMA_CACHE: LazyLock<SchemaCache> = LazyLock::new(|| {
            SchemaCache::for_adapter(std::sync::Arc::new(GeminiSchemaAdapter::new()))
        });
        let (gemini_tools, tool_config) = Self::build_gemini_tools(tools, adapter, &SCHEMA_CACHE)?;
        if !gemini_tools.is_empty() {
            cache_builder = cache_builder.with_tools(gemini_tools);
        }
        if tool_config != adk_gemini::ToolConfig::default() {
            cache_builder = cache_builder.with_tool_config(tool_config);
        }

        let handle = cache_builder
            .execute()
            .await
            .map_err(|e| adk_core::AdkError::model(format!("cache creation failed: {e}")))?;

        Ok(handle.name().to_string())
    }

    /// Delete a cached content resource by name.
    pub async fn delete_cached_content(&self, name: &str) -> Result<()> {
        let handle = self.client.get_cached_content(name);
        handle
            .delete()
            .await
            .map_err(|(_, e)| adk_core::AdkError::model(format!("cache deletion failed: {e}")))?;
        Ok(())
    }

    /// Uploads `bytes` through the Gemini File API, for media above the 20 MB a request may
    /// carry inline; a `Part::FileData` naming the returned [`GeminiFile::uri`] then goes
    /// out as native `fileData`. A video is usable once its state is
    /// [`GeminiFileState::Active`] ([`wait_for_file`](Self::wait_for_file)). Files expire
    /// after 48 hours. AI Studio only: Vertex AI reads Cloud Storage URIs instead.
    ///
    /// # Errors
    ///
    /// An invalid MIME type, the upload's failure, or an answer without a file URI.
    pub async fn upload_file(
        &self,
        bytes: Vec<u8>,
        mime_type: &str,
        display_name: Option<&str>,
    ) -> Result<GeminiFile> {
        let parsed: mime::Mime = mime_type.parse().map_err(|_| {
            adk_core::AdkError::model(format!("`{mime_type}` is not a valid MIME type"))
        })?;
        let mut builder = self.client.create_file(bytes).with_mime_type(parsed);
        if let Some(name) = display_name {
            builder = builder.display_name(name);
        }
        let handle = builder
            .upload()
            .await
            .map_err(|e| adk_core::AdkError::model(format!("file upload failed: {e}")))?;
        GeminiFile::from_wire(handle.get_file_meta())
    }

    /// The File API's current view of an uploaded file.
    ///
    /// # Errors
    ///
    /// The lookup's failure, or an answer without a file URI.
    pub async fn get_file(&self, name: &str) -> Result<GeminiFile> {
        let handle = self
            .client
            .get_file(name)
            .await
            .map_err(|e| adk_core::AdkError::model(format!("file lookup failed: {e}")))?;
        GeminiFile::from_wire(handle.get_file_meta())
    }

    /// Polls an uploaded file every `interval` until Gemini has processed it.
    ///
    /// # Errors
    ///
    /// A file whose processing failed, one still processing after `timeout`, and the
    /// lookup's failure.
    pub async fn wait_for_file(
        &self,
        name: &str,
        interval: std::time::Duration,
        timeout: std::time::Duration,
    ) -> Result<GeminiFile> {
        let started = std::time::Instant::now();
        loop {
            let file = self.get_file(name).await?;
            match file.state {
                GeminiFileState::Active => return Ok(file),
                GeminiFileState::Failed => {
                    return Err(adk_core::AdkError::model(format!(
                        "Gemini could not process file {name}; check that it is a supported format"
                    )));
                }
                GeminiFileState::Processing | GeminiFileState::Unknown => {}
            }
            if started.elapsed() >= timeout {
                return Err(adk_core::AdkError::new(
                    adk_core::ErrorComponent::Model,
                    adk_core::ErrorCategory::Timeout,
                    "model.gemini.file_processing_timeout",
                    format!("file {name} was still processing after {timeout:?}"),
                ));
            }
            tokio::time::sleep(interval).await;
        }
    }

    /// Deletes an uploaded file.
    ///
    /// # Errors
    ///
    /// The deletion's failure.
    pub async fn delete_file(&self, name: &str) -> Result<()> {
        let handle = self
            .client
            .get_file(name)
            .await
            .map_err(|e| adk_core::AdkError::model(format!("file lookup failed: {e}")))?;
        handle
            .delete()
            .await
            .map_err(|(_, e)| adk_core::AdkError::model(format!("file deletion failed: {e}")))
    }

    /// Drives a single turn through the Interactions API (Beta), non-streaming.
    ///
    /// This is the Interactions counterpart to
    /// [`generate_content_internal`](Self::generate_content_internal). It builds
    /// a [`CreateInteractionRequest`](adk_gemini::interactions::CreateInteractionRequest)
    /// from `req` via [`interactions_convert::build_request`], sends it, polls to
    /// completion when running in the background, maps terminal failure statuses
    /// to errors, and converts the final interaction into a single
    /// [`LlmResponse`].
    ///
    /// Behavior of note:
    ///
    /// - **Background completion (Requirement 7.5).** When `background` is set
    ///   and the first response is neither terminal nor awaiting a tool result,
    ///   the interaction is polled via
    ///   [`get_interaction`](adk_gemini::Gemini::get_interaction) every
    ///   `poll_interval` until it reaches a terminal or `requires_action` state.
    /// - **Stale continuation fallback (Requirement 4.4).** If the initial send
    ///   fails with a `NotFound` error *and* the request carried a
    ///   `previous_response_id`, the request is transparently rebuilt without
    ///   stateful continuation (full transcript, no `previous_interaction_id`)
    ///   and re-sent once. The original `NotFound` is not surfaced.
    /// - **Terminal failure (Requirements 7.7 / 9.2).** A final `failed` /
    ///   `budget_exceeded` status becomes an [`adk_core::AdkError`].
    ///
    /// The streaming counterpart is
    /// [`generate_interactions_stream`](Self::generate_interactions_stream).
    #[cfg(feature = "gemini-interactions")]
    async fn generate_interactions_once(&self, req: LlmRequest) -> Result<LlmResponse> {
        use super::interactions_convert;

        // The Interactions target is always populated when the transport is
        // active (set by `use_interactions_api`); guard defensively.
        let target = self.interaction_target.as_ref().ok_or_else(|| {
            adk_core::AdkError::new(
                ErrorComponent::Model,
                ErrorCategory::InvalidInput,
                "model.gemini.interactions.missing_target",
                "the Interactions transport is active but no validated target is configured",
            )
            .with_provider("gemini")
        })?;

        // Resolve the thinking level (Gemini 3 level-based reasoning). Budget-only
        // configs (Gemini 2.5) carry no level, so this stays `None` for them.
        let thinking_level = self.request_thinking_config(&req).and_then(|c| c.thinking_level);

        let stateful = self.interaction_options.stateful;
        let store = self.interaction_options.store;
        let background = self.resolve_background();

        // Build the request and stamp the background flag.
        let mut request =
            interactions_convert::build_request(&req, target, thinking_level, stateful, store)?;
        request.background = Some(background);

        // Send, with a transparent transcript fallback for a stale continuation id.
        let interaction = match self.client.send_interaction(request.clone()).await {
            Ok(interaction) => interaction,
            Err(error) => {
                let mapped = gemini_error_to_adk(&error);
                // Requirement 4.4: a rejected `previous_interaction_id` (retention
                // expiry) maps to NotFound. Rebuild statelessly (full transcript,
                // no continuation id) and retry once, without surfacing the error.
                if mapped.category == ErrorCategory::NotFound && req.previous_response_id.is_some()
                {
                    let mut fallback = interactions_convert::build_request(
                        &req,
                        target,
                        thinking_level,
                        /* stateful */ false,
                        store,
                    )?;
                    fallback.background = Some(background);
                    self.client
                        .send_interaction(fallback)
                        .await
                        .map_err(|e| gemini_error_to_adk(&e))?
                } else {
                    return Err(mapped);
                }
            }
        };

        // Background completion: poll until terminal or awaiting a tool result.
        let final_interaction = if background {
            self.poll_interaction_to_completion(interaction).await?
        } else {
            interaction
        };

        // Requirements 7.7 / 9.2: surface terminal failure statuses as errors.
        interaction_status_to_result(final_interaction.status)?;

        Ok(interactions_convert::to_llm_response(&final_interaction))
    }

    /// Polls a background interaction until it reaches a terminal or
    /// `requires_action` state, honoring the configured `poll_interval`
    /// (Requirement 7.5).
    ///
    /// Returns immediately when the interaction is already terminal or awaiting
    /// a tool result. Otherwise it sleeps for `poll_interval` and re-fetches via
    /// [`get_interaction`](adk_gemini::Gemini::get_interaction) (with
    /// `include_input = false`) until one of those states is reached, or until a
    /// bounded safeguard (`MAX_POLL_ATTEMPTS`) trips.
    ///
    /// ## Cancellation (Requirement 7.6)
    ///
    /// True invocation-driven cancellation (calling
    /// [`cancel_interaction`](adk_gemini::Gemini::cancel_interaction) when the
    /// caller cancels) is **not reachable from this layer**: the [`Llm`] trait's
    /// [`generate_content`](Llm::generate_content) signature receives only an
    /// [`LlmRequest`] and a `stream` flag — it has no `InvocationContext` or
    /// cancellation token. Cancellation is handled by the runner at the
    /// event-stream boundary: when a run is cancelled the runner stops consuming
    /// the agent's event stream, which drops this future and cancels its
    /// `await` points (the in-flight `sleep` / `get_interaction`) cooperatively.
    /// The polled interaction is left running server-side; reviving it to issue
    /// an explicit `cancel_interaction` would require threading the cancellation
    /// token through the trait, which is intentionally out of scope here (the
    /// trait is transport-only and shared by every provider).
    ///
    /// The `MAX_POLL_ATTEMPTS` bound is a safeguard against an interaction that
    /// never reaches a terminal/`requires_action` state (e.g. a server-side
    /// stall): rather than looping forever it returns a [`ErrorCategory::Timeout`]
    /// error so the call fails fast instead of hanging.
    #[cfg(feature = "gemini-interactions")]
    async fn poll_interaction_to_completion(
        &self,
        interaction: adk_gemini::interactions::Interaction,
    ) -> Result<adk_gemini::interactions::Interaction> {
        /// Upper bound on poll iterations before giving up, guarding against an
        /// interaction that never settles. With the default 1s `poll_interval`
        /// this is ~10 minutes; shorter intervals trade latency for a tighter
        /// wall-clock cap. Deep Research agents complete well within this.
        const MAX_POLL_ATTEMPTS: u32 = 600;

        let mut current = interaction;
        let mut attempts: u32 = 0;
        while !current.status.is_terminal() && !current.status.requires_action() {
            if attempts >= MAX_POLL_ATTEMPTS {
                return Err(adk_core::AdkError::new(
                    ErrorComponent::Model,
                    ErrorCategory::Timeout,
                    "model.gemini.interactions.poll_timeout",
                    format!(
                        "the Gemini interaction did not reach a terminal or requires_action \
                         state after {MAX_POLL_ATTEMPTS} poll attempts"
                    ),
                )
                .with_provider("gemini"));
            }
            attempts += 1;
            tokio::time::sleep(self.interaction_options.poll_interval).await;
            current = self
                .client
                .get_interaction(&current.id, false)
                .await
                .map_err(|e| gemini_error_to_adk(&e))?;
        }
        Ok(current)
    }

    /// Drives a single turn through the Interactions API (Beta) as an SSE
    /// stream, yielding partial→final [`LlmResponse`] chunks (Requirement 7.4).
    ///
    /// This is the streaming counterpart to
    /// [`generate_interactions_once`](Self::generate_interactions_once). It
    /// builds the request the same way, forces non-background completion
    /// (streaming and background polling are mutually exclusive completion
    /// modes — SSE delivers the turn incrementally, so `background` is set to
    /// `false`), opens the SSE stream via
    /// [`send_interaction_stream`](adk_gemini::Gemini::send_interaction_stream),
    /// and folds each [`InteractionSseEvent`](adk_gemini::interactions::InteractionSseEvent)
    /// into chunks via [`interactions_convert::sse_event_to_chunk`].
    ///
    /// Stream setup (target resolution, request building, opening the SSE
    /// connection) is fallible and returns `Err` synchronously, so
    /// `execute_with_retry` (which wraps this in `generate_content`) can retry
    /// transient setup failures. Errors that occur *after* the stream starts
    /// are yielded into the stream and not retried, mirroring the
    /// generateContent streaming path. The stream fails when it ends before
    /// `interaction.completed`, and when the interaction reaches `failed` or
    /// `budget_exceeded`.
    ///
    /// The stale-continuation fallback used by the non-streaming path is not
    /// applied here: a `NotFound` on stream setup surfaces as a normal error
    /// (the streaming path is opt-in and lower-level; callers that need
    /// transparent retention fallback use the default non-streaming path).
    #[cfg(feature = "gemini-interactions")]
    async fn generate_interactions_stream(&self, req: LlmRequest) -> Result<LlmResponseStream> {
        use super::interactions_convert::{self, SseAccumulator, sse_event_to_chunk};

        let target = self.interaction_target.as_ref().ok_or_else(|| {
            adk_core::AdkError::new(
                ErrorComponent::Model,
                ErrorCategory::InvalidInput,
                "model.gemini.interactions.missing_target",
                "the Interactions transport is active but no validated target is configured",
            )
            .with_provider("gemini")
        })?;

        let thinking_level = self.request_thinking_config(&req).and_then(|c| c.thinking_level);
        let stateful = self.interaction_options.stateful;
        let store = self.interaction_options.store;

        let mut request =
            interactions_convert::build_request(&req, target, thinking_level, stateful, store)?;
        // Streaming uses SSE for incremental completion, not background polling;
        // the two are distinct completion modes (Requirement 7.4 vs 7.5). Force
        // foreground so the server streams the turn rather than returning a
        // background handle.
        request.background = Some(false);

        let sse_stream = self
            .client
            .send_interaction_stream(request)
            .await
            .map_err(|e| gemini_error_to_adk(&e))?;

        let mapped = async_stream::stream! {
            use adk_gemini::interactions::{InteractionSseEvent, InteractionStatus};

            let mut sse_stream = sse_stream;
            let mut acc = SseAccumulator::new();
            while let Some(result) = sse_stream.try_next().await.transpose() {
                match result {
                    Ok(event) => {
                        // A terminal failure status fails the turn, whether it arrives on
                        // `interaction.completed` or as a status update.
                        let (status, completed) = match &event {
                            InteractionSseEvent::InteractionCompleted { interaction, .. } => {
                                (Some(interaction.status), true)
                            }
                            InteractionSseEvent::InteractionStatusUpdate {
                                status:
                                    status @ (InteractionStatus::Failed
                                    | InteractionStatus::BudgetExceeded),
                                ..
                            } => (Some(*status), false),
                            _ => (None, false),
                        };
                        if let Some(Err(error)) = status.map(interaction_status_to_result) {
                            yield Err(error);
                            return;
                        }
                        match sse_event_to_chunk(event, &mut acc) {
                            Some(Err(error)) => {
                                yield Err(error);
                                return;
                            }
                            Some(Ok(chunk)) => yield Ok(chunk),
                            None => {}
                        }
                        if completed {
                            return;
                        }
                    }
                    Err(e) => {
                        let error = gemini_error_to_adk(&e);
                        adk_telemetry::error!(error = %error.diagnostics(), "interaction stream error");
                        yield Err(error);
                        return;
                    }
                }
            }
            yield Err(adk_core::AdkError::new(
                ErrorComponent::Model,
                ErrorCategory::Unavailable,
                "model.gemini.interactions.unfinished_stream",
                "Gemini interaction stream ended before interaction.completed",
            )
            .with_provider("gemini"));
        };

        Ok(Box::pin(mapped))
    }
}

#[async_trait]
impl Llm for GeminiModel {
    // The request's `maxOutputTokens`, thinking included, or the model's output limit.
    fn max_cost_micro_usd(&self, request: &adk_core::LlmRequest) -> Option<u64> {
        crate::pricing::PricingCatalog::standard().max_cost_micro_usd(
            Some("gemini"),
            self.name(),
            request,
            crate::pricing::request_output_cap(request),
        )
    }

    fn context_window(&self) -> Option<u64> {
        crate::pricing::PricingCatalog::standard().context_window(Some("gemini"), self.name())
    }

    // AI Studio, a custom base URL, or the Vertex AI endpoint of the configured location.
    fn data_destinations(&self) -> Vec<adk_core::DataDestination> {
        self.client
            .endpoint()
            .map(|url| adk_core::DataDestination::of_url("gemini", url))
            .into_iter()
            .collect()
    }

    fn name(&self) -> &str {
        &self.model_name
    }

    fn schema_adapter(&self) -> &dyn SchemaAdapter {
        use std::sync::LazyLock;
        static ADAPTER: LazyLock<GeminiSchemaAdapter> = LazyLock::new(GeminiSchemaAdapter::new);
        &*ADAPTER
    }

    #[cfg(feature = "gemini-interactions")]
    fn uses_interactions_api(&self) -> bool {
        self.transport == GeminiTransport::Interactions
    }

    // generateContent serves `google_search` beside function tools on both backends, with
    // no domain allowlist; the Interactions transport refuses that mix (spec 3.1 §7.20).
    fn native_web_search(&self) -> Option<adk_core::NativeWebSearch> {
        #[cfg(feature = "gemini-interactions")]
        if self.transport == GeminiTransport::Interactions {
            return None;
        }
        Some(adk_core::NativeWebSearch::new(
            "gemini",
            adk_core::NativeWebSearchTool::GoogleSearch,
            false,
        ))
    }

    // Named distinctly from the agent layer's `call_llm` span (which carries
    // the gcp.vertex.agent.* attributes and is what trace exporters capture):
    // this is the model-transport layer, so traces show one `call_llm` per
    // LLM call instead of an identical nested pair.
    #[adk_telemetry::instrument(
        name = "model.generate_content",
        skip(self, req),
        fields(
            model.name = %self.model_name,
            stream = %stream,
            request.contents_count = %req.contents.len(),
            request.tools_count = %req.tools.len()
        )
    )]
    async fn generate_content(
        &self,
        mut req: LlmRequest,
        stream: bool,
    ) -> Result<LlmResponseStream> {
        // Native items reach this provider only from the turns its own origin marks.
        adk_core::history::retain_replayable(
            &mut req.contents,
            &adk_core::history::ProviderOrigin::new("gemini", &self.model_name),
        );
        adk_telemetry::info!("Generating content");
        self.validate_request_contract(&req, stream)?;
        #[cfg(feature = "gemini-vertex")]
        let provider = if self.vertex_backend { "gemini-vertex" } else { "gemini" };
        #[cfg(not(feature = "gemini-vertex"))]
        let provider = "gemini";
        let usage_span = crate::telemetry::inference_span(provider, &self.model_name, stream, &req);

        // Dispatch on the configured transport. The default `GenerateContent`
        // path is unchanged; the Interactions path (task 7.3/7.4) is only
        // reachable when `use_interactions_api` switched the transport.
        //
        // Retries only cover request setup/execution. Stream failures after the
        // stream starts are yielded to the caller and are not replayed
        // automatically.
        #[cfg(feature = "gemini-interactions")]
        if self.transport == GeminiTransport::Interactions {
            // Streaming and non-streaming are distinct completion modes. The
            // streaming path consumes the Interactions SSE stream and yields
            // partial→final chunks; the non-streaming path sends a single
            // request and (optionally) polls a background interaction to
            // completion. `execute_with_retry` wraps only request *setup* in
            // both cases — once a stream starts, its mid-flight errors are
            // surfaced to the caller rather than replayed (mirroring the
            // generateContent streaming path).
            if stream {
                let mapped =
                    execute_with_retry(&self.retry_config, is_retryable_model_error, || {
                        self.generate_interactions_stream(req.clone())
                    })
                    .await?;
                return Ok(crate::usage_tracking::with_priced_usage_tracking(
                    mapped,
                    usage_span,
                    "gemini",
                    &self.model_name,
                ));
            }
            let response = execute_with_retry(&self.retry_config, is_retryable_model_error, || {
                self.generate_interactions_once(req.clone())
            })
            .await?;
            let single = async_stream::stream! {
                yield Ok(response);
            };
            return Ok(crate::usage_tracking::with_priced_usage_tracking(
                Box::pin(single),
                usage_span,
                "gemini",
                &self.model_name,
            ));
        }

        let result = execute_with_retry(&self.retry_config, is_retryable_model_error, || {
            self.generate_content_internal(req.clone(), stream)
        })
        .await?;
        Ok(crate::usage_tracking::with_priced_usage_tracking(
            result,
            usage_span,
            "gemini",
            &self.model_name,
        ))
    }
}

#[cfg(test)]
mod native_tool_tests {
    use super::*;

    fn test_adapter() -> GeminiSchemaAdapter {
        GeminiSchemaAdapter::new()
    }

    fn test_cache() -> SchemaCache {
        SchemaCache::for_adapter(std::sync::Arc::new(GeminiSchemaAdapter::new()))
    }

    #[test]
    fn test_build_gemini_tools_supports_native_tool_metadata() {
        let mut tools = adk_core::ToolDeclarations::new();
        tools.insert(
            "google_search".to_string(),
            serde_json::json!({
                "x-adk-gemini-tool": {
                    "google_search": {}
                }
            }),
        );
        tools.insert(
            "lookup_weather".to_string(),
            serde_json::json!({
                "name": "lookup_weather",
                "description": "lookup weather",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "city": { "type": "string" }
                    }
                }
            }),
        );

        let adapter = test_adapter();
        let cache = test_cache();
        let (gemini_tools, tool_config) = GeminiModel::build_gemini_tools(&tools, &adapter, &cache)
            .expect("tool conversion should succeed");

        assert_eq!(gemini_tools.len(), 2);
        assert_eq!(tool_config.include_server_side_tool_invocations, Some(true));
    }

    #[test]
    fn test_build_gemini_tools_sets_flag_for_builtin_only() {
        let mut tools = adk_core::ToolDeclarations::new();
        tools.insert(
            "google_search".to_string(),
            serde_json::json!({
                "x-adk-gemini-tool": {
                    "google_search": {}
                }
            }),
        );

        let adapter = test_adapter();
        let cache = test_cache();
        let (_gemini_tools, tool_config) =
            GeminiModel::build_gemini_tools(&tools, &adapter, &cache)
                .expect("tool conversion should succeed");

        assert_eq!(
            tool_config.include_server_side_tool_invocations,
            Some(true),
            "includeServerSideToolInvocations should be set even with only built-in tools"
        );
    }

    #[test]
    fn test_build_gemini_tools_no_flag_for_function_only() {
        let mut tools = adk_core::ToolDeclarations::new();
        tools.insert(
            "lookup_weather".to_string(),
            serde_json::json!({
                "name": "lookup_weather",
                "description": "lookup weather",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "city": { "type": "string" }
                    }
                }
            }),
        );

        let adapter = test_adapter();
        let cache = test_cache();
        let (_gemini_tools, tool_config) =
            GeminiModel::build_gemini_tools(&tools, &adapter, &cache)
                .expect("tool conversion should succeed");

        assert_eq!(
            tool_config.include_server_side_tool_invocations, None,
            "includeServerSideToolInvocations should NOT be set for function-only tools"
        );
    }

    #[test]
    fn test_build_gemini_tools_merges_native_tool_config() {
        let mut tools = adk_core::ToolDeclarations::new();
        tools.insert(
            "google_maps".to_string(),
            serde_json::json!({
                "x-adk-gemini-tool": {
                    "google_maps": {
                        "enable_widget": true
                    }
                },
                "x-adk-gemini-tool-config": {
                    "retrievalConfig": {
                        "latLng": {
                            "latitude": 1.23,
                            "longitude": 4.56
                        }
                    }
                }
            }),
        );

        let adapter = test_adapter();
        let cache = test_cache();
        let (_gemini_tools, tool_config) =
            GeminiModel::build_gemini_tools(&tools, &adapter, &cache)
                .expect("tool conversion should succeed");

        assert_eq!(
            tool_config.retrieval_config,
            Some(serde_json::json!({
                "latLng": {
                    "latitude": 1.23,
                    "longitude": 4.56
                }
            }))
        );
    }

    #[test]
    fn test_response_schema_is_normalized_like_parameters() {
        // Regression test: MCP tools provide an output_schema that becomes the
        // `response` field in the tool declaration. Gemini rejects JSON-Schema
        // dialect fields ($schema, additionalProperties) in the response schema.
        // This test verifies that the response schema is normalized the same way
        // parameters are — stripping unsupported keywords.
        let mut tools = adk_core::ToolDeclarations::new();
        tools.insert(
            "read_file".to_string(),
            serde_json::json!({
                "name": "read_file",
                "description": "Read a file from the filesystem",
                "parameters": {
                    "$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "properties": {
                        "path": { "type": "string", "description": "File path" }
                    },
                    "required": ["path"],
                    "additionalProperties": false
                },
                "response": {
                    "$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "properties": {
                        "content": { "type": "string", "description": "File contents" }
                    },
                    "required": ["content"],
                    "additionalProperties": false
                }
            }),
        );

        let adapter = test_adapter();
        let cache = test_cache();
        let (gemini_tools, _) = GeminiModel::build_gemini_tools(&tools, &adapter, &cache)
            .expect("tool conversion should succeed");

        // Find the function declaration
        let func_tool = gemini_tools
            .iter()
            .find(|t| matches!(t, adk_gemini::Tool::Function { .. }))
            .expect("should have function declarations");

        let decls = match func_tool {
            adk_gemini::Tool::Function { function_declarations } => function_declarations,
            _ => panic!("expected Function tool"),
        };

        let decl = &decls[0];
        let decl_json = serde_json::to_value(decl).unwrap();

        // Parameters should be normalized (no $schema, no additionalProperties)
        let params = &decl_json["parameters"];
        assert!(params.get("$schema").is_none(), "parameters.$schema should be stripped");
        assert!(
            params.get("additionalProperties").is_none(),
            "parameters.additionalProperties should be stripped"
        );

        // Response should ALSO be normalized (this was the bug)
        let response = &decl_json["response"];
        assert!(
            response.get("$schema").is_none(),
            "response.$schema should be stripped (was the bug: copied raw)"
        );
        assert!(
            response.get("additionalProperties").is_none(),
            "response.additionalProperties should be stripped (was the bug: copied raw)"
        );
    }
}

#[async_trait]
impl CacheCapable for GeminiModel {
    async fn create_cache(
        &self,
        system_instruction: &str,
        tools: &adk_core::ToolDeclarations,
        ttl_seconds: u32,
    ) -> Result<String> {
        self.create_cached_content(system_instruction, tools, ttl_seconds).await
    }

    async fn delete_cache(&self, name: &str) -> Result<()> {
        self.delete_cached_content(name).await
    }
}

/// Joins adjacent `function` contents into one. Gemini expects the responses to a turn of
/// parallel calls in a single content, one function response per call, as adk-python and
/// adk-go send them; the history holds one content per tool result.
fn join_function_responses(contents: &[Content]) -> Vec<Content> {
    let mut joined: Vec<Content> = Vec::with_capacity(contents.len());
    for content in contents {
        if content.role == "function"
            && let Some(last) = joined.last_mut()
            && last.role == "function"
        {
            last.parts.extend(content.parts.iter().cloned());
            continue;
        }
        joined.push(content.clone());
    }
    joined
}

#[cfg(test)]
mod tests {

    #[test]
    fn parallel_function_responses_travel_in_one_content() {
        let response = |id: &str| Part::FunctionResponse {
            function_response: adk_core::FunctionResponseData::new(
                "tool",
                serde_json::json!({"ok": id}),
            ),
            id: Some(id.to_string()),
            annotations: None,
        };
        let contents = vec![
            Content::new("user").with_text("both"),
            Content { role: "function".to_string(), parts: vec![response("c1")] },
            Content { role: "function".to_string(), parts: vec![response("c2")] },
            Content::new("model").with_text("done"),
            Content { role: "function".to_string(), parts: vec![response("c3")] },
        ];
        let joined = join_function_responses(&contents);
        let shape: Vec<(&str, usize)> =
            joined.iter().map(|content| (content.role.as_str(), content.parts.len())).collect();
        assert_eq!(shape, vec![("user", 1), ("function", 2), ("model", 1), ("function", 1)]);
    }
    use super::*;
    use adk_core::AdkError;
    use std::{
        sync::{
            Arc,
            atomic::{AtomicU32, Ordering},
        },
        time::Duration,
    };

    #[test]
    fn response_status_ignores_misleading_text() {
        for (status, category, code) in [
            (400, ErrorCategory::InvalidInput, "model.gemini.bad_request"),
            (401, ErrorCategory::Unauthorized, "model.gemini.unauthorized"),
            (403, ErrorCategory::Forbidden, "model.gemini.forbidden"),
            (404, ErrorCategory::NotFound, "model.gemini.not_found"),
            (408, ErrorCategory::Timeout, "model.gemini.timeout"),
            (429, ErrorCategory::RateLimited, "model.gemini.rate_limited"),
            (500, ErrorCategory::Unavailable, "model.gemini.unavailable"),
            (504, ErrorCategory::Timeout, "model.gemini.timeout"),
            (529, ErrorCategory::Unavailable, "model.gemini.overloaded"),
        ] {
            let error = gemini_error_to_adk(&adk_gemini::ClientError::BadResponse {
                retry_after: None,
                code: status,
                description: Some(
                    serde_json::json!({"error": {
                        "code": "unsupported_capability",
                        "message": "code 400; code 401; code 429; rate limit; UNAVAILABLE; TIMEOUT"
                    }})
                    .to_string(),
                ),
            });
            assert_eq!(error.category, category);
            assert_eq!(error.code, code);
            assert_eq!(error.details.upstream_status_code, Some(status));
            assert_eq!(error.details.metadata["provider_error_code"], "unsupported_capability");
        }
    }

    #[test]
    fn provider_codes_require_bounded_json_fields() {
        for (body, expected) in [
            (
                serde_json::json!({"error":{"code":"unsupported_capability"}}).to_string(),
                Some("unsupported_capability"),
            ),
            (
                serde_json::json!({"error":{"code":400,"status":"INVALID_ARGUMENT"}})
                    .to_string(),
                Some("INVALID_ARGUMENT"),
            ),
            (
                serde_json::json!({"error":{"code":"", "status":"INVALID_ARGUMENT"}})
                    .to_string(),
                Some("INVALID_ARGUMENT"),
            ),
            ("unsupported_capability".to_string(), None),
            (serde_json::json!({"error":{"code":"unsupported capability"}}).to_string(), None),
            (serde_json::json!({"error":{"code":"x".repeat(129)}}).to_string(), None),
            (
                serde_json::json!({"error":{"code":"unsupported_capability", "message":"x".repeat(64 * 1024)}}).to_string(),
                None,
            ),
        ] {
            let error = gemini_error_to_adk(&adk_gemini::ClientError::BadResponse {
                retry_after: None,
                code: 400,
                description: Some(body),
            });
            let actual = error
                .details
                .metadata
                .get("provider_error_code")
                .and_then(serde_json::Value::as_str);
            assert_eq!(actual, expected);
        }
    }

    #[test]
    fn studio_body_prefers_error_info_reason_over_status() {
        let body = serde_json::json!({"error": {
            "code": 429,
            "message": "Resource has been exhausted",
            "status": "RESOURCE_EXHAUSTED",
            "details": [{
                "@type": "type.googleapis.com/google.rpc.ErrorInfo",
                "reason": "RATE_LIMIT_EXCEEDED",
                "domain": "googleapis.com"
            }]
        }});
        let error = gemini_error_to_adk(&adk_gemini::ClientError::BadResponse {
            retry_after: None,
            code: 429,
            description: Some(body.to_string()),
        });
        assert_eq!(error.details.metadata["provider_error_code"], "RATE_LIMIT_EXCEEDED");

        let without_reason = serde_json::json!({"error": {
            "code": 429,
            "status": "RESOURCE_EXHAUSTED"
        }});
        let error = gemini_error_to_adk(&adk_gemini::ClientError::BadResponse {
            retry_after: None,
            code: 429,
            description: Some(without_reason.to_string()),
        });
        assert_eq!(error.details.metadata["provider_error_code"], "RESOURCE_EXHAUSTED");
    }

    fn quota_body(retry_delay: &str) -> String {
        serde_json::json!({"error": {
            "code": 429,
            "message": "You exceeded your current quota.",
            "status": "RESOURCE_EXHAUSTED",
            "details": [
                {"@type": "type.googleapis.com/google.rpc.QuotaFailure", "violations": []},
                {"@type": "type.googleapis.com/google.rpc.RetryInfo", "retryDelay": retry_delay}
            ]
        }})
        .to_string()
    }

    #[test]
    fn retry_info_delay_is_the_retry_hint() {
        for (delay, expected) in [
            ("12s", Some(Duration::from_secs(12))),
            ("1.5s", Some(Duration::from_millis(1500))),
            ("0.000001s", Some(Duration::from_millis(1))),
            ("0s", Some(Duration::ZERO)),
            ("-1s", None),
            ("12", None),
            ("1.5.0s", None),
            ("1.0000000001s", None),
            ("s", None),
            ("soon", None),
        ] {
            let error = gemini_error_to_adk(&adk_gemini::ClientError::BadResponse {
                retry_after: None,
                code: 429,
                description: Some(quota_body(delay)),
            });
            assert_eq!(error.retry.retry_after(), expected, "{delay}");
        }

        // The header is the server's explicit answer; the body is the fallback.
        let error = gemini_error_to_adk(&adk_gemini::ClientError::BadResponse {
            retry_after: Some("3".into()),
            code: 429,
            description: Some(quota_body("40s")),
        });
        assert_eq!(error.retry.retry_after(), Some(Duration::from_secs(3)));

        // An error object inside a successful response carries the same detail.
        let error = gemini_error_to_adk(&adk_gemini::ClientError::ErrorInResponse {
            code: Some(429),
            status: Some("RESOURCE_EXHAUSTED".into()),
            message: None,
            description: quota_body("7s"),
        });
        assert_eq!(error.retry.retry_after(), Some(Duration::from_secs(7)));

        // A non-retryable error carries no hint.
        let error = gemini_error_to_adk(&adk_gemini::ClientError::BadResponse {
            retry_after: None,
            code: 400,
            description: Some(quota_body("12s")),
        });
        assert_eq!(error.retry.retry_after(), None);
    }

    #[test]
    fn local_config_error_has_no_upstream_status() {
        let error = gemini_error_to_adk(&adk_gemini::ClientError::InvalidGenerationConfig {
            message: "code 429; RESOURCE_EXHAUSTED".to_string(),
        });
        assert_eq!(error.category, ErrorCategory::InvalidInput);
        assert_eq!(error.code, "model.gemini.invalid_config");
        assert_eq!(error.details.upstream_status_code, None);
        assert!(error.details.metadata.is_empty());
    }

    #[test]
    fn env_flag_truthy_accepts_one_and_case_insensitive_true() {
        for truthy in ["1", "true", "TRUE", "True", " true ", "tRuE"] {
            assert!(env_flag_truthy(truthy), "expected {truthy:?} to be truthy");
        }
        for falsy in ["0", "false", "FALSE", "yes", "on", "", "2", "vertex"] {
            assert!(!env_flag_truthy(falsy), "expected {falsy:?} to be falsy");
        }
    }

    #[test]
    fn constructor_is_backward_compatible_and_sync() {
        fn accepts_sync_constructor<F>(_f: F)
        where
            F: Fn(&str, &str) -> Result<GeminiModel>,
        {
        }

        accepts_sync_constructor(|api_key, model| GeminiModel::new(api_key, model));
    }

    #[test]
    fn stream_chunks_from_response_injects_partial_before_lone_final_chunk() {
        let response = LlmResponse {
            content: Some(Content::new("model").with_text("hello")),
            usage_metadata: None,
            finish_reason: Some(FinishReason::Stop),
            citation_metadata: None,
            partial: false,
            turn_complete: true,
            interrupted: false,
            error_code: None,
            error_message: None,
            provider_metadata: None,
            interaction_id: None,
            model: None,
            provider: None,
        };

        let (chunks, saw_partial) =
            GeminiModel::stream_chunks_from_response(response, false, &mut Vec::new());
        assert!(saw_partial);
        assert_eq!(chunks.len(), 2);
        assert!(chunks[0].partial);
        assert!(!chunks[0].turn_complete);
        assert!(chunks[0].content.is_none());
        assert!(!chunks[1].partial);
        assert!(chunks[1].turn_complete);
    }

    #[test]
    fn stream_chunks_from_response_keeps_final_only_when_partial_already_seen() {
        let response = LlmResponse {
            content: Some(Content::new("model").with_text("done")),
            usage_metadata: None,
            finish_reason: Some(FinishReason::Stop),
            citation_metadata: None,
            partial: false,
            turn_complete: true,
            interrupted: false,
            error_code: None,
            error_message: None,
            provider_metadata: None,
            interaction_id: None,
            model: None,
            provider: None,
        };

        let (chunks, saw_partial) =
            GeminiModel::stream_chunks_from_response(response, true, &mut Vec::new());
        assert!(saw_partial);
        assert_eq!(chunks.len(), 1);
        assert!(!chunks[0].partial);
        assert!(chunks[0].turn_complete);
    }

    #[test]
    fn stream_chunks_from_response_keeps_tool_call_turn_open() {
        let response = LlmResponse {
            content: Some(Content {
                role: "model".to_string(),
                parts: vec![Part::FunctionCall {
                    name: "get_weather".to_string(),
                    args: serde_json::json!({"city": "Boston"}),
                    id: Some("call-1".to_string()),
                    thought_signature: None,
                }],
            }),
            finish_reason: Some(FinishReason::Stop),
            turn_complete: true,
            ..Default::default()
        };

        let (chunks, _) = GeminiModel::stream_chunks_from_response(response, true, &mut Vec::new());

        assert_eq!(chunks.len(), 1);
        assert!(!chunks[0].partial);
        assert!(!chunks[0].turn_complete);
    }

    #[test]
    fn stream_chunks_from_response_yields_a_partial_chunks_function_calls_on_the_final_chunk() {
        let call = |id: &str| Part::FunctionCall {
            name: "read_file".to_string(),
            args: serde_json::json!({ "path": id }),
            id: Some(id.to_string()),
            thought_signature: Some(format!("sig-{id}")),
        };
        let partial = LlmResponse {
            content: Some(Content {
                role: "model".to_string(),
                parts: vec![Part::Text { text: "Reading".to_string() }, call("a")],
            }),
            ..Default::default()
        };
        let last = LlmResponse {
            content: Some(Content { role: "model".to_string(), parts: vec![call("b")] }),
            finish_reason: Some(FinishReason::Stop),
            ..Default::default()
        };

        let mut deferred = Vec::new();
        let (first, saw_partial) =
            GeminiModel::stream_chunks_from_response(partial, false, &mut deferred);
        assert!(saw_partial);
        assert_eq!(first.len(), 1);
        assert!(first[0].partial);
        assert_eq!(
            serde_json::to_value(&first[0].content).unwrap(),
            serde_json::to_value(Some(Content {
                role: "model".to_string(),
                parts: vec![Part::Text { text: "Reading".to_string() }],
            }))
            .unwrap(),
            "the partial chunk keeps its text and loses its call"
        );
        assert_eq!(deferred.len(), 1);

        let (chunks, _) =
            GeminiModel::stream_chunks_from_response(last, saw_partial, &mut deferred);
        assert!(deferred.is_empty());
        assert_eq!(chunks.len(), 1);
        assert!(!chunks[0].partial);
        assert!(!chunks[0].turn_complete);
        assert_eq!(
            serde_json::to_value(&chunks[0].content).unwrap(),
            serde_json::to_value(Some(Content {
                role: "model".to_string(),
                parts: vec![call("a"), call("b")],
            }))
            .unwrap(),
            "the final chunk carries every call once, in stream order, with its signature"
        );
    }

    #[tokio::test]
    async fn execute_with_retry_retries_retryable_errors() {
        let retry_config = RetryConfig::default()
            .with_max_retries(2)
            .with_initial_delay(Duration::from_millis(0))
            .with_max_delay(Duration::from_millis(0));
        let attempts = Arc::new(AtomicU32::new(0));

        let result = execute_with_retry(&retry_config, is_retryable_model_error, || {
            let attempts = Arc::clone(&attempts);
            async move {
                let attempt = attempts.fetch_add(1, Ordering::SeqCst);
                if attempt < 2 {
                    return Err(AdkError::model("code 429 RESOURCE_EXHAUSTED"));
                }
                Ok("ok")
            }
        })
        .await
        .expect("retry should eventually succeed");

        assert_eq!(result, "ok");
        assert_eq!(attempts.load(Ordering::SeqCst), 3);
    }

    #[tokio::test]
    async fn execute_with_retry_does_not_retry_non_retryable_errors() {
        let retry_config = RetryConfig::default()
            .with_max_retries(3)
            .with_initial_delay(Duration::from_millis(0))
            .with_max_delay(Duration::from_millis(0));
        let attempts = Arc::new(AtomicU32::new(0));

        let error = execute_with_retry(&retry_config, is_retryable_model_error, || {
            let attempts = Arc::clone(&attempts);
            async move {
                attempts.fetch_add(1, Ordering::SeqCst);
                Err::<(), _>(AdkError::model("code 400 invalid request"))
            }
        })
        .await
        .expect_err("non-retryable error should return immediately");

        assert!(error.is_model());
        assert_eq!(attempts.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn execute_with_retry_respects_disabled_config() {
        let retry_config = RetryConfig::disabled().with_max_retries(10);
        let attempts = Arc::new(AtomicU32::new(0));

        let error = execute_with_retry(&retry_config, is_retryable_model_error, || {
            let attempts = Arc::clone(&attempts);
            async move {
                attempts.fetch_add(1, Ordering::SeqCst);
                Err::<(), _>(AdkError::model("code 429 RESOURCE_EXHAUSTED"))
            }
        })
        .await
        .expect_err("disabled retries should return first error");

        assert!(error.is_model());
        assert_eq!(attempts.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn convert_response_preserves_citation_metadata() {
        let response = adk_gemini::GenerationResponse {
            candidates: vec![adk_gemini::Candidate {
                content: adk_gemini::Content {
                    role: Some(adk_gemini::Role::Model),
                    parts: Some(vec![adk_gemini::Part::Text {
                        text: "hello world".to_string(),
                        thought: None,
                        thought_signature: None,
                    }]),
                },
                safety_ratings: None,
                citation_metadata: Some(adk_gemini::CitationMetadata {
                    citation_sources: vec![adk_gemini::CitationSource {
                        uri: Some("https://example.com".to_string()),
                        title: Some("Example".to_string()),
                        start_index: Some(0),
                        end_index: Some(5),
                        license: Some("CC-BY".to_string()),
                        publication_date: None,
                    }],
                }),
                grounding_metadata: None,
                finish_reason: Some(adk_gemini::FinishReason::Stop),
                index: Some(0),
                logprobs_result: None,
                avg_logprobs: None,
            }],
            prompt_feedback: None,
            usage_metadata: None,
            model_version: None,
            response_id: None,
        };

        let converted =
            GeminiModel::convert_response(&response).expect("conversion should succeed");
        let metadata = converted.citation_metadata.expect("citation metadata should be mapped");
        assert_eq!(metadata.citation_sources.len(), 1);
        assert_eq!(metadata.citation_sources[0].uri.as_deref(), Some("https://example.com"));
        assert_eq!(metadata.citation_sources[0].start_index, Some(0));
        assert_eq!(metadata.citation_sources[0].end_index, Some(5));
    }

    #[test]
    fn convert_response_keeps_function_call_turn_open() {
        let response = adk_gemini::GenerationResponse {
            candidates: vec![adk_gemini::Candidate {
                content: adk_gemini::Content {
                    role: Some(adk_gemini::Role::Model),
                    parts: Some(vec![adk_gemini::Part::FunctionCall {
                        function_call: adk_gemini::FunctionCall {
                            name: "get_weather".to_string(),
                            args: serde_json::json!({"city": "Boston"}),
                            id: Some("call-1".to_string()),
                            thought_signature: None,
                        },
                        thought_signature: None,
                    }]),
                },
                safety_ratings: None,
                citation_metadata: None,
                grounding_metadata: None,
                finish_reason: Some(adk_gemini::FinishReason::Stop),
                index: Some(0),
                logprobs_result: None,
                avg_logprobs: None,
            }],
            prompt_feedback: None,
            usage_metadata: None,
            model_version: None,
            response_id: None,
        };

        let converted =
            GeminiModel::convert_response(&response).expect("conversion should succeed");

        assert!(!converted.turn_complete);
        assert!(converted.content.is_some_and(|content| content.has_function_calls()));
    }

    #[test]
    fn convert_response_handles_inline_data_from_model() {
        let image_bytes = vec![0x89, 0x50, 0x4E, 0x47];
        let encoded = crate::attachment::encode_base64(&image_bytes);

        let response = adk_gemini::GenerationResponse {
            candidates: vec![adk_gemini::Candidate {
                content: adk_gemini::Content {
                    role: Some(adk_gemini::Role::Model),
                    parts: Some(vec![
                        adk_gemini::Part::Text {
                            text: "Here is the image".to_string(),
                            thought: None,
                            thought_signature: None,
                        },
                        adk_gemini::Part::InlineData {
                            inline_data: adk_gemini::Blob {
                                mime_type: "image/png".to_string(),
                                data: encoded,
                            },
                            video_metadata: None,
                        },
                    ]),
                },
                safety_ratings: None,
                citation_metadata: None,
                grounding_metadata: None,
                finish_reason: Some(adk_gemini::FinishReason::Stop),
                index: Some(0),
                logprobs_result: None,
                avg_logprobs: None,
            }],
            prompt_feedback: None,
            usage_metadata: None,
            model_version: None,
            response_id: None,
        };

        let converted =
            GeminiModel::convert_response(&response).expect("conversion should succeed");
        let content = converted.content.expect("should have content");
        assert!(
            content
                .parts
                .iter()
                .any(|part| matches!(part, Part::Text { text } if text == "Here is the image"))
        );
        assert!(content.parts.iter().any(|part| {
            matches!(
                part,
                Part::InlineData { mime_type, data, .. }
                    if mime_type == "image/png" && data.as_slice() == image_bytes.as_slice()
            )
        }));
    }

    #[test]
    fn gemini_function_response_payload_preserves_objects() {
        let value = serde_json::json!({
            "documents": [
                { "id": "pricing", "score": 0.91 }
            ]
        });

        let payload = GeminiModel::gemini_function_response_payload(value.clone());

        assert_eq!(payload, value);
    }

    #[test]
    fn gemini_function_response_payload_wraps_arrays() {
        let payload =
            GeminiModel::gemini_function_response_payload(serde_json::json!([{ "id": "pricing" }]));

        assert_eq!(payload, serde_json::json!({ "result": [{ "id": "pricing" }] }));
    }

    // ===== Multimodal function response conversion tests =====

    /// Helper to build a FunctionResponse with nested multimodal parts
    /// simulating the conversion logic from generate_content_internal.
    fn convert_function_response_to_gemini_fr(
        frd: &adk_core::FunctionResponseData,
    ) -> adk_gemini::tools::FunctionResponse {
        let mut fr_parts = Vec::new();

        for inline in &frd.inline_data {
            let encoded = crate::attachment::encode_base64(&inline.data);
            fr_parts.push(adk_gemini::FunctionResponsePart::InlineData {
                inline_data: adk_gemini::Blob {
                    mime_type: inline.mime_type.clone(),
                    data: encoded,
                },
            });
        }

        for file in &frd.file_data {
            fr_parts.push(adk_gemini::FunctionResponsePart::FileData {
                file_data: adk_gemini::FileDataRef {
                    mime_type: file.mime_type.clone(),
                    file_uri: file.file_uri.clone(),
                },
            });
        }

        let mut gemini_fr = adk_gemini::tools::FunctionResponse::new(
            &frd.name,
            GeminiModel::gemini_function_response_payload(frd.response.clone()),
        );
        gemini_fr.parts = fr_parts;
        gemini_fr
    }

    #[test]
    fn json_only_function_response_has_no_nested_parts() {
        let frd = adk_core::FunctionResponseData::new("tool", serde_json::json!({"ok": true}));
        let gemini_fr = convert_function_response_to_gemini_fr(&frd);
        assert!(gemini_fr.parts.is_empty());
        // Serialized JSON should have name and response but no parts key
        let json = serde_json::to_string(&gemini_fr).unwrap();
        assert!(!json.contains("\"parts\""));
    }

    #[test]
    fn function_response_with_inline_data_has_nested_parts() {
        let frd = adk_core::FunctionResponseData::with_inline_data(
            "chart",
            serde_json::json!({"status": "ok"}),
            vec![adk_core::InlineDataPart {
                mime_type: "image/png".to_string(),
                data: vec![0x89, 0x50, 0x4E, 0x47],
                uri: None,
                annotations: None,
            }],
        );
        let gemini_fr = convert_function_response_to_gemini_fr(&frd);
        assert_eq!(gemini_fr.parts.len(), 1);
        match &gemini_fr.parts[0] {
            adk_gemini::FunctionResponsePart::InlineData { inline_data } => {
                assert_eq!(inline_data.mime_type, "image/png");
                let decoded = BASE64_STANDARD.decode(&inline_data.data).unwrap();
                assert_eq!(decoded, vec![0x89, 0x50, 0x4E, 0x47]);
            }
            other => panic!("expected InlineData, got {other:?}"),
        }
    }

    #[test]
    fn function_response_with_file_data_has_nested_parts() {
        let frd = adk_core::FunctionResponseData::with_file_data(
            "doc",
            serde_json::json!({"ok": true}),
            vec![adk_core::FileDataPart {
                mime_type: "application/pdf".to_string(),
                file_uri: "gs://bucket/report.pdf".to_string(),
                annotations: None,
            }],
        );
        let gemini_fr = convert_function_response_to_gemini_fr(&frd);
        assert_eq!(gemini_fr.parts.len(), 1);
        match &gemini_fr.parts[0] {
            adk_gemini::FunctionResponsePart::FileData { file_data } => {
                assert_eq!(file_data.mime_type, "application/pdf");
                assert_eq!(file_data.file_uri, "gs://bucket/report.pdf");
            }
            other => panic!("expected FileData, got {other:?}"),
        }
    }

    #[test]
    fn function_response_with_both_inline_and_file_data_ordering() {
        let frd = adk_core::FunctionResponseData::with_multimodal(
            "multi",
            serde_json::json!({}),
            vec![
                adk_core::InlineDataPart {
                    mime_type: "image/png".to_string(),
                    data: vec![1, 2],
                    uri: None,
                    annotations: None,
                },
                adk_core::InlineDataPart {
                    mime_type: "image/jpeg".to_string(),
                    data: vec![3, 4],
                    uri: None,
                    annotations: None,
                },
            ],
            vec![adk_core::FileDataPart {
                mime_type: "application/pdf".to_string(),
                file_uri: "gs://b/f.pdf".to_string(),
                annotations: None,
            }],
        );
        let gemini_fr = convert_function_response_to_gemini_fr(&frd);
        // 2 inline + 1 file = 3 nested parts
        assert_eq!(gemini_fr.parts.len(), 3);
        assert!(matches!(&gemini_fr.parts[0], adk_gemini::FunctionResponsePart::InlineData { .. }));
        assert!(matches!(&gemini_fr.parts[1], adk_gemini::FunctionResponsePart::InlineData { .. }));
        assert!(matches!(&gemini_fr.parts[2], adk_gemini::FunctionResponsePart::FileData { .. }));
    }
}

#[cfg(all(test, feature = "gemini-interactions"))]
mod interactions_transport_tests {
    use super::*;
    use adk_core::GenerateContentConfig;

    /// **Feature: gemini-interactions-runtime, Property 2: Default options match the API**
    /// *For any* default `InteractionOptions`, `store == true`, `stateful == true`,
    /// `background` is `AgentTargetsOnly`, and `poll_interval` is 1 second.
    /// **Validates: Requirements 3.1, 3.2, 3.3**
    #[test]
    fn default_interaction_options_match_api_posture() {
        let opts = InteractionOptions::default();
        assert!(opts.store, "store should default to true");
        assert!(opts.stateful, "stateful should default to true");
        assert_eq!(opts.background, BackgroundMode::AgentTargetsOnly);
        assert_eq!(opts.poll_interval, std::time::Duration::from_secs(1));
    }

    #[test]
    fn new_model_defaults_to_generate_content_transport() {
        let model = GeminiModel::new("test-key", "gemini-3.7-flash")
            .expect("constructing a Gemini model should not require network");
        assert_eq!(model.transport(), GeminiTransport::GenerateContent);
    }

    #[test]
    fn use_interactions_api_enables_transport_for_allowlisted_model() {
        let model = GeminiModel::new("test-key", "gemini-3.7-flash")
            .expect("construct model")
            .use_interactions_api(true)
            .expect("allowlisted model should enable the Interactions transport");

        assert_eq!(model.transport(), GeminiTransport::Interactions);
        assert_eq!(
            model.interaction_target,
            Some(InteractionTarget::Model("gemini-3.7-flash".to_string()))
        );
    }

    #[test]
    fn use_interactions_api_rejects_unsupported_model_with_invalid_input() {
        let result = GeminiModel::new("test-key", "gemini-2.0-flash")
            .expect("construct model")
            .use_interactions_api(true);

        let err = match result {
            Ok(_) => panic!("unsupported model should be rejected"),
            Err(err) => err,
        };
        assert_eq!(err.category, adk_core::ErrorCategory::InvalidInput);
        assert_eq!(err.details.provider.as_deref(), Some("gemini"));
    }

    #[test]
    fn use_interactions_api_false_reverts_to_generate_content() {
        let model = GeminiModel::new("test-key", "gemini-3.7-flash")
            .expect("construct model")
            .use_interactions_api(true)
            .expect("enable interactions")
            .use_interactions_api(false)
            .expect("disabling should always succeed");

        assert_eq!(model.transport(), GeminiTransport::GenerateContent);
        assert_eq!(model.interaction_target, None);
    }

    #[test]
    fn interaction_options_override_is_stored() {
        let opts = InteractionOptions {
            store: false,
            stateful: false,
            background: BackgroundMode::Always,
            poll_interval: std::time::Duration::from_millis(250),
        };
        let model = GeminiModel::new("test-key", "gemini-3.7-flash")
            .expect("construct model")
            .interaction_options(opts.clone());

        let stored = model.interaction_options_ref();
        assert_eq!(stored.store, opts.store);
        assert_eq!(stored.stateful, opts.stateful);
        assert_eq!(stored.background, opts.background);
        assert_eq!(stored.poll_interval, opts.poll_interval);
    }

    #[test]
    fn resolve_background_honors_background_mode() {
        // Always → true regardless of target.
        let always = GeminiModel::new("test-key", "gemini-3.7-flash")
            .expect("construct model")
            .use_interactions_api(true)
            .expect("enable")
            .interaction_options(InteractionOptions {
                background: BackgroundMode::Always,
                ..InteractionOptions::default()
            });
        assert!(always.resolve_background());

        // Never → false regardless of target.
        let never = GeminiModel::new("test-key", "gemini-3.7-flash")
            .expect("construct model")
            .use_interactions_api(true)
            .expect("enable")
            .interaction_options(InteractionOptions {
                background: BackgroundMode::Never,
                ..InteractionOptions::default()
            });
        assert!(!never.resolve_background());

        // AgentTargetsOnly → false for a model target.
        let model_target = GeminiModel::new("test-key", "gemini-3.7-flash")
            .expect("construct model")
            .use_interactions_api(true)
            .expect("enable");
        assert!(!model_target.resolve_background());

        // AgentTargetsOnly → true for an agent target.
        let agent_target = GeminiModel::new("test-key", "deep-research-preview-04-2026")
            .expect("construct model")
            .use_interactions_api(true)
            .expect("enable");
        assert!(agent_target.resolve_background());
    }

    /// Requirements 7.7 / 9.2: a terminal `failed` status maps to an
    /// `Internal` `AdkError` (provider `"gemini"`).
    #[test]
    fn terminal_failed_status_maps_to_error() {
        use adk_gemini::interactions::InteractionStatus;

        let err = interaction_status_to_result(InteractionStatus::Failed)
            .expect_err("a failed interaction must surface an error");
        assert_eq!(err.category, adk_core::ErrorCategory::Internal);
        assert_eq!(err.details.provider.as_deref(), Some("gemini"));
        assert_eq!(err.code, "model.gemini.interactions.failed");
    }

    /// Requirements 7.7 / 9.2: a terminal `budget_exceeded` status maps to an
    /// `Internal` `AdkError` (provider `"gemini"`).
    #[test]
    fn terminal_budget_exceeded_status_maps_to_error() {
        use adk_gemini::interactions::InteractionStatus;

        let err = interaction_status_to_result(InteractionStatus::BudgetExceeded)
            .expect_err("a budget_exceeded interaction must surface an error");
        assert_eq!(err.category, adk_core::ErrorCategory::Internal);
        assert_eq!(err.details.provider.as_deref(), Some("gemini"));
        assert_eq!(err.code, "model.gemini.interactions.budget_exceeded");
    }

    /// Non-failure statuses (including `requires_action` and the other terminal
    /// states the transport reads content from) do not produce an error.
    #[test]
    fn non_failure_statuses_are_ok() {
        use adk_gemini::interactions::InteractionStatus;

        for status in [
            InteractionStatus::InProgress,
            InteractionStatus::RequiresAction,
            InteractionStatus::Completed,
            InteractionStatus::Cancelled,
            InteractionStatus::Incomplete,
            InteractionStatus::RequiresContinuation,
            InteractionStatus::Unknown,
        ] {
            assert!(
                interaction_status_to_result(status).is_ok(),
                "status {status:?} should not map to an error"
            );
        }
    }

    /// A constructed `failed` `Interaction` flows through the same status check
    /// the transport uses, surfacing an error after conversion.
    #[test]
    fn failed_interaction_resource_surfaces_error() {
        use adk_gemini::interactions::{Interaction, InteractionStatus};

        let interaction = Interaction {
            id: "v1_failed".to_string(),
            model: Some("gemini-3.7-flash".to_string()),
            agent: None,
            status: InteractionStatus::Failed,
            steps: Vec::new(),
            usage: None,
            created: None,
            updated: None,
            environment_id: None,
            continuation_token: None,
        };

        let err = interaction_status_to_result(interaction.status)
            .expect_err("failed interaction must surface an error");
        assert_eq!(err.category, adk_core::ErrorCategory::Internal);
        assert_eq!(err.details.provider.as_deref(), Some("gemini"));
    }
    #[test]
    fn gemini_37_rejects_sampling_before_network_io() {
        for name in ["gemini-3.7-flash", "gemini-3.8-flash"] {
            let model = GeminiModel::new("test-key", name).expect("construct model");
            let mut request = LlmRequest::new(name, Vec::new());
            request.config =
                Some(GenerateContentConfig { temperature: Some(0.2), ..Default::default() });

            let error = model
                .validate_request_contract(&request, false)
                .expect_err("sampling must be rejected locally");
            assert_eq!(error.code, "model.gemini.sampling_unsupported", "{name}");
        }
    }

    #[test]
    fn gemini_37_rejects_token_budget_thinking() {
        let model = GeminiModel::new("test-key", "gemini-3.7-flash")
            .expect("construct model")
            .with_thinking_config(adk_gemini::ThinkingConfig {
                thinking_budget: Some(1024),
                include_thoughts: None,
                thinking_level: None,
            });

        let error = model
            .validate_request_contract(&LlmRequest::new("gemini-3.7-flash", Vec::new()), false)
            .expect_err("token budgets must be rejected locally");
        assert_eq!(error.code, "model.gemini.thinking_budget_unsupported");
    }

    /// The error code a Gemini 4 request gets before anything is sent, if any.
    fn gemini_4_refusal(
        name: &str,
        level: Option<adk_gemini::ThinkingLevel>,
        config: GenerateContentConfig,
        stream: bool,
    ) -> Option<&'static str> {
        let mut model = GeminiModel::new("test-key", name).expect("construct model");
        if let Some(level) = level {
            model = model
                .with_thinking_config(adk_gemini::ThinkingConfig::new().with_thinking_level(level));
        }
        let mut request = LlmRequest::new(name, Vec::new());
        request.config = Some(config);
        model.validate_request_contract(&request, stream).err().map(|error| error.code)
    }

    /// Every Gemini 4 model refuses `minimal` thinking, explicit caching and sampling
    /// parameters (<https://aistudio.google.com/docs/thinking#thinking-levels>,
    /// <https://aistudio.google.com/docs/whats-new-gemini-4-hydrogen>).
    #[test]
    fn gemini_4_rejects_minimal_thinking_explicit_caches_and_sampling() {
        use adk_gemini::ThinkingLevel;

        for name in ["gemini-4-carbon", "gemini-4-argon", "gemini-4-neon", "gemini-4-hydrogen"] {
            let plain = GenerateContentConfig::default;
            assert_eq!(
                gemini_4_refusal(name, Some(ThinkingLevel::Minimal), plain(), true),
                Some("model.gemini.thinking_level_unsupported"),
                "{name}"
            );
            let cached = GenerateContentConfig {
                cached_content: Some("cachedContents/abc".to_string()),
                ..Default::default()
            };
            assert_eq!(
                gemini_4_refusal(name, None, cached, true),
                Some("model.gemini.explicit_cache_unsupported"),
                "{name}"
            );
            let sampled = GenerateContentConfig { top_p: Some(0.5), ..Default::default() };
            assert_eq!(
                gemini_4_refusal(name, None, sampled, true),
                Some("model.gemini.sampling_unsupported"),
                "{name}"
            );
            assert_eq!(gemini_4_refusal(name, Some(ThinkingLevel::High), plain(), false), None);
            assert!(
                !GeminiModel::new("test-key", name)
                    .expect("construct model")
                    .supports_explicit_cache()
            );
        }
        assert!(
            GeminiModel::new("test-key", "gemini-3.8-flash")
                .expect("construct model")
                .supports_explicit_cache()
        );
    }

    /// `xhigh` runs on Neon and Hydrogen only, and a non-streaming generateContent call to
    /// Carbon or Argon returns at most 32,768 tokens
    /// (<https://aistudio.google.com/docs/long-decode>).
    #[test]
    fn gemini_4_carbon_and_argon_refuse_xhigh_and_a_non_streaming_cap_above_32k() {
        use adk_gemini::ThinkingLevel;

        let plain = GenerateContentConfig::default;
        let capped =
            |max| GenerateContentConfig { max_output_tokens: Some(max), ..Default::default() };
        for name in ["gemini-4-carbon", "gemini-4-argon"] {
            assert_eq!(
                gemini_4_refusal(name, Some(ThinkingLevel::XHigh), plain(), true),
                Some("model.gemini.thinking_level_unsupported"),
                "{name}"
            );
            assert_eq!(
                gemini_4_refusal(name, None, capped(65_536), false),
                Some("model.gemini.output_cap_exceeded"),
                "{name}"
            );
            assert_eq!(gemini_4_refusal(name, None, capped(65_536), true), None, "{name}");
            assert_eq!(gemini_4_refusal(name, None, capped(32_768), false), None, "{name}");
        }
        for name in ["gemini-4-neon", "gemini-4-hydrogen"] {
            assert_eq!(gemini_4_refusal(name, Some(ThinkingLevel::XHigh), plain(), false), None);
            assert_eq!(gemini_4_refusal(name, None, capped(65_536), false), None, "{name}");
        }
    }
}

#[cfg(all(test, feature = "gemini-vertex"))]
mod vertex_rag_tests {
    use super::*;
    use adk_gemini::VertexRagStore;

    fn test_store() -> VertexRagStore {
        VertexRagStore::corpus("projects/p/locations/us-central1/ragCorpora/123").with_top_k(5)
    }

    fn vertex_model() -> GeminiModel {
        GeminiModel::new_google_cloud("test-key", "p", "us-central1", "gemini-3.7-flash")
            .expect("construct vertex model")
    }

    // The Vertex constructor builds credential plumbing that requires a
    // current Tokio runtime, so this test is async.
    #[tokio::test]
    async fn vertex_backend_accepts_and_stores_the_rag_store() {
        let model = vertex_model().with_vertex_rag_store(test_store());

        model
            .validate_request_contract(&LlmRequest::new("gemini-3.7-flash", Vec::new()), false)
            .expect("vertex backend must accept the rag store");

        // The stored store is handed to adk-gemini's ContentBuilder per
        // request; the exact wire-shape injection is asserted in adk-gemini's
        // backend tests.
        assert_eq!(model.vertex_rag_store(), Some(&test_store()));
    }

    #[test]
    fn studio_backend_rejects_rag_store_before_network_io() {
        let model = GeminiModel::new("test-key", "gemini-3.7-flash")
            .expect("construct studio model")
            .with_vertex_rag_store(test_store());

        let error = model
            .validate_request_contract(&LlmRequest::new("gemini-3.7-flash", Vec::new()), false)
            .expect_err("studio backend must reject the rag store locally");
        assert_eq!(error.code, "model.gemini.rag_store_requires_vertex");
        assert_eq!(error.category, adk_core::ErrorCategory::Unsupported);
        assert_eq!(error.details.provider.as_deref(), Some("gemini"));
    }

    #[test]
    fn no_rag_store_means_no_gate() {
        let model = GeminiModel::new("test-key", "gemini-3.7-flash").expect("construct model");
        assert_eq!(model.vertex_rag_store(), None);
        model
            .validate_request_contract(&LlmRequest::new("gemini-3.7-flash", Vec::new()), false)
            .expect("no store configured, nothing to reject");
    }
}

#[cfg(all(test, feature = "gemini-vertex"))]
mod vertex_transport_tests {
    use super::*;
    use google_cloud_gax::error::{
        Error as GaxError,
        rpc::{Code, Status, StatusDetails},
    };

    #[test]
    fn service_status_and_reason_are_preserved() {
        let detail: StatusDetails = serde_json::from_value(serde_json::json!({
            "@type": "type.googleapis.com/google.rpc.ErrorInfo",
            "reason": "QUOTA_EXCEEDED"
        }))
        .expect("valid ErrorInfo detail");
        let status = Status::default()
            .set_code(Code::ResourceExhausted)
            .set_message("code 400; invalid API key")
            .set_details([detail]);
        let error = adk_gemini::ClientError::GoogleCloudRequest {
            source: GaxError::service_with_http_metadata(status, Some(429), None),
        };

        let mapped = gemini_error_to_adk(&error);
        assert_eq!(mapped.category, ErrorCategory::RateLimited);
        assert_eq!(mapped.code, "model.gemini.rate_limited");
        assert_eq!(mapped.details.upstream_status_code, Some(429));
        assert_eq!(mapped.details.metadata["provider_error_code"], "QUOTA_EXCEEDED");
    }

    #[test]
    fn rpc_status_does_not_invent_http_status() {
        let detail: StatusDetails = serde_json::from_value(serde_json::json!({
            "@type": "type.googleapis.com/google.rpc.ErrorInfo",
            "reason": "RATE_LIMITED"
        }))
        .expect("valid ErrorInfo detail");
        let status = Status::default()
            .set_code(Code::ResourceExhausted)
            .set_message("code 503; unavailable")
            .set_details([detail]);
        let error =
            adk_gemini::ClientError::GoogleCloudRequest { source: GaxError::service(status) };

        let mapped = gemini_error_to_adk(&error);
        assert_eq!(mapped.category, ErrorCategory::RateLimited);
        assert_eq!(mapped.code, "model.gemini.rate_limited");
        assert_eq!(mapped.details.upstream_status_code, None);
        assert_eq!(mapped.details.metadata["provider_error_code"], "RATE_LIMITED");
    }

    #[test]
    fn retry_info_on_the_status_is_the_retry_hint() {
        let detail: StatusDetails = serde_json::from_value(serde_json::json!({
            "@type": "type.googleapis.com/google.rpc.RetryInfo",
            "retryDelay": "2.5s"
        }))
        .expect("valid RetryInfo detail");
        let status = Status::default()
            .set_code(Code::ResourceExhausted)
            .set_message("quota")
            .set_details([detail]);
        let error = adk_gemini::ClientError::GoogleCloudRequest {
            source: GaxError::service_with_http_metadata(status, Some(429), None),
        };
        assert_eq!(
            gemini_error_to_adk(&error).retry.retry_after(),
            Some(std::time::Duration::from_millis(2500))
        );
    }

    #[test]
    fn rpc_status_name_is_the_fallback_code() {
        let status = Status::default().set_code(Code::ResourceExhausted).set_message("quota");
        let error =
            adk_gemini::ClientError::GoogleCloudRequest { source: GaxError::service(status) };
        assert_eq!(
            gemini_error_to_adk(&error).details.metadata["provider_error_code"],
            "RESOURCE_EXHAUSTED"
        );
    }

    #[test]
    fn vertex_transport_failures_are_retryable() {
        let source = GaxError::connect(std::io::Error::other("dns failure"));
        let mapped = gemini_error_to_adk(&adk_gemini::ClientError::GoogleCloudRequest { source });
        assert_eq!(
            (mapped.category, mapped.code, mapped.is_retryable()),
            (ErrorCategory::Unavailable, "model.gemini.unavailable", true)
        );

        let error = adk_gemini::ClientError::GoogleCloudRequest {
            source: GaxError::deser(std::io::Error::other(
                "the transport reports an error: http2 error",
            )),
        };
        assert_eq!(gemini_error_to_adk(&error).category, ErrorCategory::Internal);
    }
}