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
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),
}
}
}
/// 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,
}
/// Convert a Gemini client error to a structured `AdkError` with proper category and retry hints.
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
}
let message = format_error_chain(e);
// Extract status code from BadResponse variant via Display output
// BadResponse format: "bad response from server; code {code}; description: ..."
let (category, code, status_code) = if message.contains("code 429")
|| message.contains("RESOURCE_EXHAUSTED")
|| message.contains("rate limit")
{
(ErrorCategory::RateLimited, "model.gemini.rate_limited", Some(429u16))
} else if message.contains("code 503") || message.contains("UNAVAILABLE") {
(ErrorCategory::Unavailable, "model.gemini.unavailable", Some(503))
} else if message.contains("code 529") || message.contains("OVERLOADED") {
(ErrorCategory::Unavailable, "model.gemini.overloaded", Some(529))
} else if message.contains("code 408")
|| message.contains("DEADLINE_EXCEEDED")
|| message.contains("TIMEOUT")
{
(ErrorCategory::Timeout, "model.gemini.timeout", Some(408))
} else if message.contains("code 401") || message.contains("Invalid API key") {
(ErrorCategory::Unauthorized, "model.gemini.unauthorized", Some(401))
} else if message.contains("code 400") {
(ErrorCategory::InvalidInput, "model.gemini.bad_request", Some(400))
} else if message.contains("code 404") {
(ErrorCategory::NotFound, "model.gemini.not_found", Some(404))
} else if message.contains("invalid generation config") {
(ErrorCategory::InvalidInput, "model.gemini.invalid_config", None)
} else {
(ErrorCategory::Internal, "model.gemini.internal", None)
};
let mut err = adk_core::AdkError::new(ErrorComponent::Model, category, code, message)
.with_provider("gemini");
if let Some(sc) = status_code {
err = err.with_upstream_status(sc);
}
err
}
/// 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::InProgress
| InteractionStatus::RequiresAction
| InteractionStatus::Completed
| InteractionStatus::Cancelled
| InteractionStatus::Incomplete => 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")
}
impl GeminiModel {
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)
}
/// 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.
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(),
}
}
/// 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();
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 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()))?;
Ok(Self::from_client(client, model_name))
}
/// 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()))?;
Ok(Self::from_client(client, model_name))
}
/// 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()))?;
Ok(Self::from_client(client, model_name))
}
/// 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()))?;
Ok(Self::from_client(client, model_name))
}
/// 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-2.5-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()
}
/// 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-2.5-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,
});
}
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,
});
}
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(),
});
}
}
}
}
// Add grounding metadata as text if present (required for Google Search grounding compliance)
if let Some(grounding) = resp.candidates.first().and_then(|c| c.grounding_metadata.as_ref())
{
if let Some(queries) = &grounding.web_search_queries
&& !queries.is_empty()
{
let search_info = format!("\n\n🔍 **Searched:** {}", queries.join(", "));
converted_parts.push(Part::Text { text: search_info });
}
if let Some(chunks) = &grounding.grounding_chunks {
let sources: Vec<String> = chunks
.iter()
.filter_map(|c| {
c.web.as_ref().and_then(|w| match (&w.title, &w.uri) {
(Some(title), Some(uri)) => Some(format!("[{}]({})", title, uri)),
(Some(title), None) => Some(title.clone()),
(None, Some(uri)) => Some(uri.to_string()),
(None, None) => None,
})
})
.collect();
if !sources.is_empty() {
let sources_info = format!("\n📚 **Sources:** {}", sources.join(" | "));
converted_parts.push(Part::Text { text: sources_info });
}
}
}
let content = if converted_parts.is_empty() {
None
} else {
Some(Content { role: "model".to_string(), parts: converted_parts })
};
let usage_metadata = resp.usage_metadata.as_ref().map(|u| UsageMetadata {
prompt_token_count: u.prompt_token_count.unwrap_or(0),
candidates_token_count: u.candidates_token_count.unwrap_or(0),
total_token_count: u.total_token_count.unwrap_or(0),
thinking_token_count: u.thoughts_token_count,
cache_read_input_token_count: u.cached_content_token_count,
..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,
adk_gemini::FinishReason::MaxTokens => FinishReason::MaxTokens,
adk_gemini::FinishReason::Safety => FinishReason::Safety,
adk_gemini::FinishReason::Recitation => FinishReason::Recitation,
_ => FinishReason::Other,
});
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 access structured grounding data (search queries, sources, supports).
let provider_metadata = resp
.candidates
.first()
.and_then(|c| c.grounding_metadata.as_ref())
.and_then(|g| serde_json::to_value(g).ok());
Ok(LlmResponse {
content,
usage_metadata,
finish_reason,
citation_metadata,
partial: false,
turn_complete: true,
interrupted: false,
error_code: None,
error_message: None,
provider_metadata,
interaction_id: 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: &std::collections::HashMap<String, serde_json::Value>,
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.get_or_normalize(&schema, adapter);
// 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.get_or_normalize(response, adapter);
}
// 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))
}
fn stream_chunks_from_response(
mut response: LlmResponse,
saw_partial_chunk: bool,
) -> (Vec<LlmResponse>, bool) {
let is_final = response.finish_reason.is_some();
if !is_final {
response.partial = true;
response.turn_complete = false;
return (vec![response], true);
}
response.partial = false;
response.turn_complete = true;
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,
};
(vec![synthetic_partial, response], true)
}
async fn generate_content_internal(
&self,
req: LlmRequest,
stream: bool,
) -> Result<LlmResponseStream> {
let mut builder = self.client.generate_content();
// 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());
}
}
}
}
// Add contents using proper builder methods
for content in &req.contents {
match content.role.as_str() {
"user" => {
// 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::Thinking { thinking, signature } => {
gemini_parts.push(adk_gemini::Part::Text {
text: thinking.clone(),
thought: Some(true),
thought_signature: signature.clone(),
});
}
Part::InlineData { data, mime_type } => {
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,
},
});
}
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(),
});
}
Part::ServerToolCall { server_tool_call } => {
if let Ok(native_part) = serde_json::from_value::<adk_gemini::Part>(
server_tool_call.clone(),
) {
match native_part {
adk_gemini::Part::ToolCall { .. }
| adk_gemini::Part::ExecutableCode { .. } => {
gemini_parts.push(native_part);
continue;
}
_ => {}
}
}
gemini_parts.push(adk_gemini::Part::ToolCall {
tool_call: server_tool_call.clone(),
thought_signature: Self::gemini_part_thought_signature(
server_tool_call,
),
});
}
Part::ServerToolResponse { server_tool_response } => {
if let Ok(native_part) = serde_json::from_value::<adk_gemini::Part>(
server_tool_response.clone(),
) {
match native_part {
adk_gemini::Part::ToolResponse { .. }
| adk_gemini::Part::CodeExecutionResult { .. } => {
gemini_parts.push(native_part);
continue;
}
_ => {}
}
}
gemini_parts.push(adk_gemini::Part::ToolResponse {
tool_response: server_tool_response.clone(),
thought_signature: Self::gemini_part_thought_signature(
server_tool_response,
),
});
}
_ => {}
}
}
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 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,
response_schema: config.response_schema,
response_mime_type: if has_schema {
Some("application/json".to_string())
} else {
None
},
thinking_config: self.thinking_config.clone(),
..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 self.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: self.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::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);
}
}
if stream {
adk_telemetry::debug!("Executing streaming request");
let response_stream = builder.execute_stream().await.map_err(|e| {
adk_telemetry::error!(error = %e, "Model request failed");
gemini_error_to_adk(&e)
})?;
let mapped_stream = async_stream::stream! {
let mut stream = response_stream;
let mut saw_partial_chunk = false;
while let Some(result) = stream.try_next().await.transpose() {
match result {
Ok(resp) => {
match Self::convert_response(&resp) {
Ok(llm_resp) => {
let (chunks, next_saw_partial) =
Self::stream_chunks_from_response(llm_resp, saw_partial_chunk);
saw_partial_chunk = next_saw_partial;
for chunk in chunks {
yield Ok(chunk);
}
}
Err(e) => {
adk_telemetry::error!(error = %e, "Failed to convert response");
yield Err(e);
}
}
}
Err(e) => {
adk_telemetry::error!(error = %e, "Stream error");
yield Err(gemini_error_to_adk(&e));
}
}
}
};
Ok(Box::pin(mapped_stream))
} else {
adk_telemetry::debug!("Executing blocking request");
let response = builder.execute().await.map_err(|e| {
adk_telemetry::error!(error = %e, "Model request failed");
gemini_error_to_adk(&e)
})?;
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.
pub async fn create_cached_content(
&self,
system_instruction: &str,
tools: &std::collections::HashMap<String, serde_json::Value>,
ttl_seconds: u32,
) -> Result<String> {
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::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(())
}
/// 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.thinking_config.as_ref().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(¤t.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 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.thinking_config.as_ref().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! {
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) => {
if let Some(chunk) = sse_event_to_chunk(event, &mut acc) {
yield chunk;
}
}
Err(e) => {
adk_telemetry::error!(error = %e, "Interaction stream error");
yield Err(gemini_error_to_adk(&e));
}
}
}
};
Ok(Box::pin(mapped))
}
}
#[async_trait]
impl Llm for GeminiModel {
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
}
#[adk_telemetry::instrument(
name = "call_llm",
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, req: LlmRequest, stream: bool) -> Result<LlmResponseStream> {
adk_telemetry::info!("Generating content");
let usage_span = adk_telemetry::llm_generate_span("gemini", &self.model_name, stream);
// 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_usage_tracking(mapped, usage_span));
}
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_usage_tracking(Box::pin(single), usage_span));
}
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_usage_tracking(result, usage_span))
}
}
#[cfg(test)]
mod native_tool_tests {
use super::*;
fn test_adapter() -> GeminiSchemaAdapter {
GeminiSchemaAdapter::new()
}
fn test_cache() -> SchemaCache {
SchemaCache::new()
}
#[test]
fn test_build_gemini_tools_supports_native_tool_metadata() {
let mut tools = std::collections::HashMap::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 = std::collections::HashMap::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 = std::collections::HashMap::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 = std::collections::HashMap::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 = std::collections::HashMap::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: &std::collections::HashMap<String, serde_json::Value>,
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
}
}
#[cfg(test)]
mod tests {
use super::*;
use adk_core::AdkError;
use std::{
sync::{
Arc,
atomic::{AtomicU32, Ordering},
},
time::Duration,
};
#[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,
};
let (chunks, saw_partial) = GeminiModel::stream_chunks_from_response(response, false);
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,
};
let (chunks, saw_partial) = GeminiModel::stream_chunks_from_response(response, true);
assert!(saw_partial);
assert_eq!(chunks.len(), 1);
assert!(!chunks[0].partial);
assert!(chunks[0].turn_complete);
}
#[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),
}],
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_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,
},
},
]),
},
safety_ratings: None,
citation_metadata: None,
grounding_metadata: None,
finish_reason: Some(adk_gemini::FinishReason::Stop),
index: Some(0),
}],
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],
}],
);
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(),
}],
);
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] },
adk_core::InlineDataPart { mime_type: "image/jpeg".to_string(), data: vec![3, 4] },
],
vec![adk_core::FileDataPart {
mime_type: "application/pdf".to_string(),
file_uri: "gs://b/f.pdf".to_string(),
}],
);
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::*;
/// **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-2.5-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-2.5-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-2.5-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-2.5-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-2.5-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-2.5-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-2.5-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-2.5-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,
] {
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-2.5-flash".to_string()),
agent: None,
status: InteractionStatus::Failed,
steps: Vec::new(),
usage: None,
created: None,
updated: 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"));
}
}