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
//! Conversion layer between ADK request/response types and the Gemini
//! Interactions API (Beta) wire types.
//!
//! This module mirrors the `generateContent` request-building logic in
//! [`crate::gemini::client`] but targets the Interactions API's stateful,
//! step-based contract. The request half
//! ([`build_request`](crate::gemini::interactions_convert::build_request)) maps an
//! [`adk_core::LlmRequest`] onto an
//! [`adk_gemini::interactions::CreateInteractionRequest`]; the response half and
//! the tool-mixing validation are layered on top by sibling tasks.
//!
//! Mapping summary (ADK → Interactions):
//!
//! | ADK source | Interactions |
//! |------------|--------------|
//! | system `Content` | `system_instruction` |
//! | user/model `Content` | transcript `Input` (or latest turn when stateful) |
//! | `Part::InlineData`/`FileData` | image/audio/document/video `Content` |
//! | `Part::FunctionResponse{id,..}` | `function_result` `Step{call_id,..}` |
//! | `tools` | `Tool::Function{..}` |
//! | `config.response_schema` | `ResponseFormat::json_schema(schema)` |
//! | thinking level | `generation_config.thinking_level` |
//! | `LlmRequest.previous_response_id` | `previous_interaction_id` (stateful) |
//!
//! This module is only compiled when the `gemini-interactions` feature is
//! enabled.

use std::collections::HashMap;

use adk_core::{
    AdkError, Content, ErrorCategory, ErrorComponent, FinishReason, GenerateContentConfig,
    LlmRequest, LlmResponse, Part, UsageMetadata,
};
use adk_gemini::ThinkingLevel;
use adk_gemini::interactions::{
    AudioContent, Content as IxContent, CreateInteractionRequest, DocumentContent,
    GenerationConfig, ImageContent, Input, Interaction, InteractionSseEvent, InteractionStatus,
    InteractionStreamError, ResponseFormat, Step, StepDelta, Tool, Usage, VideoContent,
};
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use serde_json::Value;

use super::interactions_target::InteractionTarget;

/// The declaration key that marks a built-in (server-side) Gemini tool.
///
/// Built-in tool wrappers in `adk-tool` (e.g. `GoogleSearchTool`,
/// `UrlContextTool`, `GeminiCodeExecutionTool`) attach this key to their
/// [`Tool::declaration()`](adk_core::Tool::declaration) JSON, with a nested
/// object naming the specific built-in (e.g. `{"google_search": {}}`). Custom
/// function tools — including bypass-converted built-ins — never carry this key;
/// they declare a `parameters` schema instead. The tool-mixing validation in
/// [`build_request`] uses this marker to classify each declaration.
const BUILTIN_TOOL_MARKER: &str = "x-adk-gemini-tool";

/// Maps a completed (non-streaming) [`Interaction`] back into an [`LlmResponse`].
///
/// This is the response half of the Interactions transport: it walks the
/// interaction's [`Step`] timeline, assembling the model turn's [`Part`]s, then
/// folds in usage, the server-assigned interaction id, and a status-derived
/// finish reason. The mapping follows the design's "Response: Interactions → ADK"
/// table:
///
/// - **`model_output`** content blocks become [`Part::Text`] (text),
///   [`Part::InlineData`] (inline base64 image/audio/document/video), or
///   [`Part::FileData`] (URI-referenced media).
/// - **`thought`** steps become a single [`Part::Thinking`] carrying the
///   concatenated summary text and the step signature.
/// - **`function_call`** steps become [`Part::FunctionCall`] (these drive the
///   runner's tool loop).
/// - **server-side tool steps** ([`Step::Other`]) are *not* placed in the
///   content; their raw JSON is collected into
///   `provider_metadata["gemini"]["interaction_steps"]`.
/// - **`user_input`** / **`function_result`** steps are skipped — they are
///   request-side artefacts and unusual in a response.
///
/// The interaction's [`usage`](Interaction::usage) maps to
/// [`UsageMetadata`], its [`id`](Interaction::id) to
/// [`LlmResponse::interaction_id`] (when non-empty), and its
/// [`status`](Interaction::status) to [`finish_reason`](LlmResponse::finish_reason)
/// / `turn_complete` / `partial`:
///
/// | Status | `finish_reason` | `turn_complete` | `partial` |
/// |--------|-----------------|-----------------|-----------|
/// | `Completed` | `Some(Stop)` | `true` | `false` |
/// | `RequiresAction` | `None` | `false` | `false` |
/// | `Incomplete` / `RequiresContinuation` | `Some(MaxTokens)` | `true` | `false` |
/// | `Failed` / `BudgetExceeded` / `Cancelled` / `Unknown` | `Some(Other)` | `true` | `false` |
/// | `InProgress` | `None` | `false` | `true` |
///
/// `Failed` / `BudgetExceeded` are left *total* here — they are mapped to a
/// finish reason rather than an error; the client transport (task 7) decides
/// whether to surface them as `Err`.
///
/// # Arguments
///
/// * `interaction` - The interaction resource to convert.
///
/// # Returns
///
/// An [`LlmResponse`] with `content` set to a `"model"` [`Content`] when any
/// parts were produced (or `None` when the timeline yields no content parts).
pub fn to_llm_response(interaction: &Interaction) -> LlmResponse {
    let mut parts: Vec<Part> = Vec::new();
    let mut server_steps: Vec<Value> = Vec::new();

    for step in &interaction.steps {
        match step {
            Step::ModelOutput { content } => {
                for block in content {
                    if let Some(part) = content_to_part(block) {
                        parts.push(part);
                    }
                }
            }
            Step::Thought { signature, summary } => {
                let thinking =
                    summary.iter().filter_map(IxContent::as_text).collect::<Vec<_>>().join("");
                parts.push(Part::Thinking { thinking, signature: signature.clone() });
            }
            Step::FunctionCall { id, name, arguments, signature } => {
                parts.push(Part::FunctionCall {
                    name: name.clone(),
                    args: arguments.clone(),
                    id: Some(id.clone()),
                    thought_signature: signature.clone(),
                });
            }
            Step::Other(value) => server_steps.push(value.clone()),
            // `user_input` / `function_result` are request-side; skip them.
            Step::UserInput { .. } | Step::FunctionResult { .. } => {}
        }
    }

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

    let interaction_id =
        if interaction.id.is_empty() { None } else { Some(interaction.id.clone()) };

    let usage_metadata = interaction.usage.as_ref().map(usage_to_metadata);

    let provider_metadata = if server_steps.is_empty() {
        None
    } else {
        Some(serde_json::json!({
            "gemini": {
                "interaction_steps": server_steps,
                "status": status_label(interaction.status),
            }
        }))
    };

    let (finish_reason, mut turn_complete, partial) = status_to_completion(interaction.status);
    if content.as_ref().is_some_and(Content::has_function_calls) {
        turn_complete = false;
    }

    LlmResponse {
        content,
        usage_metadata,
        finish_reason,
        partial,
        turn_complete,
        provider_metadata,
        interaction_id,
        ..Default::default()
    }
}

/// Converts an Interactions response [`IxContent`] block into an ADK [`Part`].
///
/// Inline (base64) media decodes to bytes and becomes [`Part::InlineData`];
/// URI-referenced media becomes [`Part::FileData`]. A block carrying neither
/// `data` nor `uri` yields `None`.
fn content_to_part(block: &IxContent) -> Option<Part> {
    match block {
        IxContent::Text(text) => Some(Part::Text { text: text.text.clone() }),
        IxContent::Image(ImageContent { data, mime_type, uri, .. }) => {
            media_part(data.as_deref(), mime_type.as_deref(), uri.as_deref(), "image/png")
        }
        IxContent::Audio(AudioContent { data, mime_type, uri, .. }) => {
            media_part(data.as_deref(), mime_type.as_deref(), uri.as_deref(), "audio/wav")
        }
        IxContent::Document(DocumentContent { data, mime_type, uri }) => {
            media_part(data.as_deref(), mime_type.as_deref(), uri.as_deref(), "application/pdf")
        }
        IxContent::Video(VideoContent { data, mime_type, uri, .. }) => {
            media_part(data.as_deref(), mime_type.as_deref(), uri.as_deref(), "video/mp4")
        }
    }
}

/// Builds a media [`Part`] from an inline-or-URI content block.
///
/// Inline base64 `data` decodes to [`Part::InlineData`]; a `uri` (with no inline
/// data) becomes [`Part::FileData`]. `default_mime` supplies a MIME type when the
/// block omits one. Returns `None` when the block carries neither payload, or
/// when the inline data fails to decode.
fn media_part(
    data: Option<&str>,
    mime_type: Option<&str>,
    uri: Option<&str>,
    default_mime: &str,
) -> Option<Part> {
    let mime = mime_type.unwrap_or(default_mime).to_string();
    if let Some(encoded) = data {
        let bytes = BASE64_STANDARD.decode(encoded).ok()?;
        Some(Part::InlineData {
            mime_type: mime,
            data: bytes,
            uri: uri.map(str::to_string),
            annotations: None,
        })
    } else {
        uri.map(|file_uri| Part::FileData {
            mime_type: mime,
            file_uri: file_uri.to_string(),
            annotations: None,
        })
    }
}

/// Maps an Interactions [`Usage`] into ADK [`UsageMetadata`].
///
/// `total_input_tokens`/`total_output_tokens`/`total_tokens` map to
/// `prompt_token_count`/`candidates_token_count`/`total_token_count`
/// (saturating `i64` → `i32`). `total_thought_tokens` and `total_cached_tokens`
/// populate `thinking_token_count` / `cache_read_input_token_count` only when
/// positive. `provider_usage` keeps the `usage` object as received.
fn usage_to_metadata(usage: &Usage) -> UsageMetadata {
    UsageMetadata {
        prompt_token_count: clamp_i64(usage.total_input_tokens),
        candidates_token_count: clamp_i64(usage.total_output_tokens),
        // An unreported (`null` or zero) total is at least the input and output reported.
        total_token_count: clamp_i64(if usage.total_tokens > 0 {
            usage.total_tokens
        } else {
            usage.total_input_tokens.saturating_add(usage.total_output_tokens)
        }),
        thinking_token_count: (usage.total_thought_tokens > 0)
            .then(|| clamp_i64(usage.total_thought_tokens)),
        cache_read_input_token_count: (usage.total_cached_tokens > 0)
            .then(|| clamp_i64(usage.total_cached_tokens)),
        provider_usage: usage.raw.clone().or_else(|| serde_json::to_value(usage).ok()),
        ..Default::default()
    }
}

/// Saturating conversion from the wire `i64` token counts to ADK's `i32`.
fn clamp_i64(value: i64) -> i32 {
    value.clamp(i32::MIN as i64, i32::MAX as i64) as i32
}

/// Maps an [`InteractionStatus`] to `(finish_reason, turn_complete, partial)`.
fn status_to_completion(status: InteractionStatus) -> (Option<FinishReason>, bool, bool) {
    match status {
        InteractionStatus::Completed => (Some(FinishReason::Stop), true, false),
        InteractionStatus::RequiresAction => (None, false, false),
        // A long-decode hop that stops at its output cap is cut short like a turn that used
        // all of `max_output_tokens`: ADK sends no continuation request.
        InteractionStatus::Incomplete | InteractionStatus::RequiresContinuation => {
            (Some(FinishReason::MaxTokens), true, false)
        }
        InteractionStatus::Failed
        | InteractionStatus::BudgetExceeded
        | InteractionStatus::Cancelled => (Some(FinishReason::Other), true, false),
        InteractionStatus::InProgress => (None, false, true),
        // A status this release does not model ends the turn without claiming a reason.
        InteractionStatus::Unknown => (Some(FinishReason::Other), true, false),
        _ => (Some(FinishReason::Other), true, false),
    }
}

/// Returns the snake_case wire label for an [`InteractionStatus`], used in
/// `provider_metadata`.
fn status_label(status: InteractionStatus) -> &'static str {
    match status {
        InteractionStatus::InProgress => "in_progress",
        InteractionStatus::RequiresAction => "requires_action",
        InteractionStatus::Completed => "completed",
        InteractionStatus::Failed => "failed",
        InteractionStatus::Cancelled => "cancelled",
        InteractionStatus::Incomplete => "incomplete",
        InteractionStatus::RequiresContinuation => "requires_continuation",
        InteractionStatus::BudgetExceeded => "budget_exceeded",
        InteractionStatus::Unknown => "unknown",
        _ => "unknown",
    }
}

/// Builds a [`CreateInteractionRequest`] from an [`LlmRequest`].
///
/// The conversion follows the Interactions transport's mapping rules:
///
/// - **System instruction.** All `Content` entries with role `"system"` have
///   their text parts concatenated (newline-joined) into `system_instruction`.
/// - **Input.** When stateful continuation applies (see below) only the most
///   recent user turn is sent as [`Input::Content`]; otherwise the full
///   transcript is sent. A lone user turn is sent as [`Input::Content`], while a
///   multi-turn transcript is mapped to [`Input::Steps`] (`user_input`,
///   `model_output`, `function_call`, and `function_result` steps).
/// - **Tools.** Each declaration in [`LlmRequest::tools`] is mapped to a
///   [`Tool::Function`]. (Tool-mixing validation is layered on by a later task.)
/// - **Response format.** `config.response_schema` becomes
///   [`ResponseFormat::json_schema`].
/// - **Generation config.** `thinking_level` plus common sampling parameters
///   (`max_output_tokens`, `temperature`, `top_p`, `seed`, `stop_sequences`) are
///   forwarded into [`GenerationConfig`]. `frequency_penalty`, `presence_penalty`, and
///   `top_logprobs` have no Interactions field and fail the request with
///   `model.unsupported_config`.
/// - **Continuity.** When `stateful` and `store` are both `true` and the request
///   carries a `previous_response_id`, it is set as `previous_interaction_id`.
///
/// # Arguments
///
/// * `request` - The ADK request to convert.
/// * `target` - The validated Interactions destination. A
///   [`InteractionTarget::Model`] sets the request `model` field; a
///   [`InteractionTarget::Agent`] sets the `agent` field.
/// * `thinking_level` - The resolved thinking level (from the model's thinking
///   config), forwarded to `generation_config.thinking_level` when present.
/// * `stateful` - Whether stateful continuation is enabled. When `false`, the
///   full transcript is always sent.
/// * `store` - Whether the interaction is stored server-side. Set on the
///   request as `store`; when `false`, stateful continuation is disabled (per
///   the API's incompatibility rules).
///
/// # Returns
///
/// A [`CreateInteractionRequest`] ready to send. `background` is intentionally
/// left unset for the client transport (task 7) to populate.
///
/// # Errors
///
/// Returns an [`adk_core::Result`] error with category
/// [`ErrorCategory::InvalidInput`] and provider `"gemini"` when the resolved
/// tool set mixes a built-in (server-side) tool with a custom function tool.
/// The Interactions API forbids this combination; the error message names the
/// offending built-in tool(s) and points the developer at
/// `with_bypass_multi_tools_limit`. A uniform tool set (all function tools, all
/// built-in tools, or no tools) builds successfully.
///
/// Returns `model.unsupported_config` when the config sets `frequency_penalty`,
/// `presence_penalty`, or `top_logprobs`.
pub fn build_request(
    request: &LlmRequest,
    target: &InteractionTarget,
    thinking_level: Option<ThinkingLevel>,
    stateful: bool,
    store: bool,
) -> adk_core::Result<CreateInteractionRequest> {
    // 1. Separate system content from the conversation transcript.
    let mut system_texts: Vec<String> = Vec::new();
    let mut transcript: Vec<&Content> = Vec::new();
    for content in &request.contents {
        if content.role == "system" {
            for part in &content.parts {
                if let Part::Text { text } = part {
                    system_texts.push(text.clone());
                }
            }
        } else {
            transcript.push(content);
        }
    }
    let system_instruction =
        if system_texts.is_empty() { None } else { Some(system_texts.join("\n")) };

    // 2. Determine whether stateful continuation applies. Per Requirement 3.6,
    //    `store == false` disables continuation regardless of `stateful`.
    let continuation_id = if stateful && store && request.previous_response_id.is_some() {
        request.previous_response_id.clone()
    } else {
        None
    };

    // 3. Build the input. When chaining statefully, send only the latest user
    //    turn (Property 4: stateful minimization); otherwise send the full
    //    transcript.
    let input = if continuation_id.is_some() {
        let latest_user = transcript.iter().rev().find(|c| c.role == "user");
        match latest_user {
            Some(content) => Input::Content(content_parts(content)),
            None => Input::Content(Vec::new()),
        }
    } else {
        build_transcript_input(&transcript)
    };

    // 4. Validate the tool set and map it to uniform `Tool` declarations. The
    //    Interactions API forbids mixing built-in (server-side) tools with
    //    custom function tools in a single request (Requirement 6.5/6.6).
    let tools = build_tools(&request.tools)?;

    // 5. Response schema → structured JSON `ResponseFormat`.
    let response_format = request
        .config
        .as_ref()
        .and_then(|config| config.response_schema.clone())
        .map(ResponseFormat::json_schema);

    // 6. Generation config (thinking level + common sampling parameters). The Interactions
    //    `generation_config` has no penalty or log-probability field.
    crate::generation_config::reject_unsupported(
        "Gemini Interactions",
        request.config.as_ref(),
        crate::generation_config::Supports {
            stop_sequences: true,
            seed: true,
            penalties: false,
            top_logprobs: false,
        },
    )
    .map_err(|error| error.with_provider("gemini"))?;
    let generation_config = build_generation_config(request.config.as_ref(), thinking_level);

    // 7. Resolve the model/agent target field.
    let (model, agent) = match target {
        InteractionTarget::Model(id) => (Some(id.clone()), None),
        InteractionTarget::Agent(id) => (None, Some(id.clone())),
    };

    Ok(CreateInteractionRequest {
        model,
        agent,
        input,
        system_instruction,
        tools,
        response_format,
        store: Some(store),
        generation_config,
        previous_interaction_id: continuation_id,
        // `background` is the client transport's responsibility (task 7).
        ..Default::default()
    })
}

/// Builds the `input` field from a full conversation transcript.
///
/// A single user turn is sent as [`Input::Content`]; any multi-turn transcript
/// (or one that contains model/function turns) is sent as [`Input::Steps`].
fn build_transcript_input(transcript: &[&Content]) -> Input {
    if transcript.len() == 1 && transcript[0].role == "user" {
        return Input::Content(content_parts(transcript[0]));
    }

    let mut steps: Vec<Step> = Vec::new();
    for content in transcript {
        append_steps(content, &mut steps);
    }

    if steps.is_empty() { Input::Content(Vec::new()) } else { Input::Steps(steps) }
}

/// Appends the [`Step`]s produced by a single ADK [`Content`] to `steps`.
///
/// User content becomes a single `user_input` step; model content becomes
/// `function_call` steps (for tool calls) plus a `model_output` step (for the
/// remaining content); function content becomes one `function_result` step per
/// [`Part::FunctionResponse`].
fn append_steps(content: &Content, steps: &mut Vec<Step>) {
    match content.role.as_str() {
        "user" => {
            let blocks = content_parts(content);
            if !blocks.is_empty() {
                steps.push(Step::UserInput { content: blocks });
            }
        }
        "model" => {
            let mut output_blocks: Vec<IxContent> = Vec::new();
            for part in &content.parts {
                match part {
                    Part::FunctionCall { name, args, id, thought_signature } => {
                        steps.push(Step::FunctionCall {
                            id: id.clone().unwrap_or_default(),
                            name: name.clone(),
                            arguments: args.clone(),
                            signature: thought_signature.clone(),
                        });
                    }
                    other => {
                        if let Some(block) = part_to_content(other) {
                            output_blocks.push(block);
                        }
                    }
                }
            }
            if !output_blocks.is_empty() {
                steps.push(Step::ModelOutput { content: output_blocks });
            }
        }
        "function" => {
            for part in &content.parts {
                if let Part::FunctionResponse { function_response, id, .. } = part {
                    steps.push(Step::FunctionResult {
                        call_id: id.clone().unwrap_or_default(),
                        name: Some(function_response.name.clone()),
                        result: function_response.response.clone(),
                        // Only an answer the agent wrote says the call failed or never ran.
                        is_error: part
                            .tool_result_status()
                            .is_some_and(adk_core::ToolResultStatus::is_error)
                            .then_some(true),
                        signature: None,
                    });
                }
            }
        }
        _ => {}
    }
}

/// Converts the parts of a [`Content`] into Interactions content blocks,
/// skipping parts that have no input representation (thinking traces, tool
/// calls/responses, server-tool parts).
fn content_parts(content: &Content) -> Vec<IxContent> {
    content.parts.iter().filter_map(part_to_content).collect()
}

/// Converts a single ADK [`Part`] into an Interactions [`IxContent`] block.
///
/// Returns `None` for parts that are not input content (thinking, function
/// calls/responses, server-tool parts) — these are represented as [`Step`]s or
/// omitted.
fn part_to_content(part: &Part) -> Option<IxContent> {
    match part {
        Part::Text { text } => Some(IxContent::text(text.clone())),
        Part::InlineData { mime_type, data, .. } => {
            let encoded = crate::attachment::encode_base64(data);
            Some(inline_content(mime_type, encoded))
        }
        Part::FileData { mime_type, file_uri, .. } => Some(uri_content(mime_type, file_uri)),
        _ => None,
    }
}

/// Builds an inline (base64) content block, choosing the variant from the MIME
/// type's top-level category.
fn inline_content(mime_type: &str, data: String) -> IxContent {
    if mime_type.starts_with("image/") {
        IxContent::image(data, mime_type)
    } else if mime_type.starts_with("audio/") {
        IxContent::audio(data, mime_type)
    } else if mime_type.starts_with("video/") {
        IxContent::Video(VideoContent {
            data: Some(data),
            mime_type: Some(mime_type.to_string()),
            uri: None,
            resolution: None,
        })
    } else {
        IxContent::document(data, mime_type)
    }
}

/// Builds a URI-referenced content block, choosing the variant from the MIME
/// type's top-level category.
fn uri_content(mime_type: &str, uri: &str) -> IxContent {
    if mime_type.starts_with("image/") {
        IxContent::Image(ImageContent {
            data: None,
            mime_type: Some(mime_type.to_string()),
            uri: Some(uri.to_string()),
            resolution: None,
        })
    } else if mime_type.starts_with("audio/") {
        IxContent::Audio(AudioContent {
            data: None,
            mime_type: Some(mime_type.to_string()),
            uri: Some(uri.to_string()),
            sample_rate: None,
            channels: None,
        })
    } else if mime_type.starts_with("video/") {
        IxContent::video_uri(uri)
    } else {
        IxContent::Document(DocumentContent {
            data: None,
            mime_type: Some(mime_type.to_string()),
            uri: Some(uri.to_string()),
        })
    }
}

/// Classifies a tool declaration as built-in (server-side) when it carries the
/// [`BUILTIN_TOOL_MARKER`] key.
///
/// Custom function tools — including bypass-converted built-ins — declare a
/// `parameters` schema and never carry the marker, so this returns `false` for
/// them.
fn is_builtin_declaration(decl: &Value) -> bool {
    decl.get(BUILTIN_TOOL_MARKER).is_some()
}

/// Validates the resolved tool set and maps it to Interactions [`Tool`] entries.
///
/// The Interactions API forbids mixing built-in (server-side) tools with custom
/// function tools in a single request. This function partitions the
/// declarations by [`is_builtin_declaration`] and:
///
/// - **errors** with [`ErrorCategory::InvalidInput`] when the set contains *both*
///   at least one built-in tool and at least one function tool (Requirement
///   6.5), naming the offending built-in tool(s) and pointing the developer at
///   `with_bypass_multi_tools_limit`;
/// - **succeeds** when the set is uniform — all function tools (Requirement 6.6),
///   all built-in tools, or empty.
///
/// Function declarations become [`Tool::Function`]. Built-in declarations (only
/// reachable when the set is built-in-only) are mapped to their dedicated
/// [`Tool`] variant when recognised (`google_search`, `code_execution`,
/// `url_context`) and otherwise passed through verbatim as [`Tool::Other`].
///
/// Declarations are processed in name-sorted order so the produced request is
/// deterministic (the source is a [`HashMap`], whose iteration order is
/// unspecified).
fn build_tools(tools: &adk_core::ToolDeclarations) -> adk_core::Result<Vec<Tool>> {
    let mut entries: Vec<(&String, &Value)> = tools.iter().collect();
    entries.sort_by(|a, b| a.0.cmp(b.0));

    let mut builtin_names: Vec<String> = Vec::new();
    let mut function_present = false;
    for (key, decl) in &entries {
        if is_builtin_declaration(decl) {
            let name = decl.get("name").and_then(Value::as_str).unwrap_or(key).to_string();
            builtin_names.push(name);
        } else {
            function_present = true;
        }
    }

    // The genuine mix — at least one built-in AND at least one function tool —
    // is the only case the API rejects (Requirement 6.5).
    if !builtin_names.is_empty() && function_present {
        return Err(mixed_tools_error(&builtin_names));
    }

    let mapped = entries.into_iter().map(|(key, decl)| map_tool(key, decl)).collect();
    Ok(mapped)
}

/// Maps a single declaration to an Interactions [`Tool`].
///
/// Function declarations (no built-in marker) become [`Tool::Function`].
/// Built-in declarations map to their dedicated variant when recognised, falling
/// back to [`Tool::Other`] with the raw declaration for any other built-in.
fn map_tool(key: &str, decl: &Value) -> Tool {
    if let Some(builtin) = decl.get(BUILTIN_TOOL_MARKER) {
        return map_builtin_tool(builtin, decl);
    }
    let name = decl.get("name").and_then(Value::as_str).unwrap_or(key).to_string();
    let description = decl.get("description").and_then(Value::as_str).map(ToString::to_string);
    let parameters = decl.get("parameters").cloned();
    Tool::Function { name, description, parameters }
}

/// Maps a built-in tool declaration to its Interactions [`Tool`] variant.
///
/// The `marker` is the value of the [`BUILTIN_TOOL_MARKER`] key, a nested object
/// naming the specific built-in (e.g. `{"google_search": {}}`). Recognised
/// built-ins map to their dedicated variant; anything else is passed through as
/// [`Tool::Other`] carrying the raw declaration so forward-compatibility is
/// preserved.
fn map_builtin_tool(marker: &Value, decl: &Value) -> Tool {
    if marker.get("google_search").is_some() {
        Tool::GoogleSearch { search_types: Vec::new() }
    } else if marker.get("code_execution").is_some() {
        Tool::CodeExecution
    } else if marker.get("url_context").is_some() {
        Tool::UrlContext
    } else {
        Tool::Other(decl.clone())
    }
}

/// Builds the `InvalidInput` error returned when a request mixes built-in and
/// function tools.
///
/// The message names the offending built-in tool(s) and points the developer at
/// `with_bypass_multi_tools_limit`, mirroring ADK-Python's guidance.
fn mixed_tools_error(builtin_names: &[String]) -> AdkError {
    AdkError::new(
        ErrorComponent::Model,
        ErrorCategory::InvalidInput,
        "model.gemini.interactions.mixed_tools",
        format!(
            "the Interactions API cannot mix built-in tool(s) [{}] with custom function tools in \
             one request. Convert each built-in tool with `with_bypass_multi_tools_limit` so the \
             tool set is uniform.",
            builtin_names.join(", "),
        ),
    )
    .with_provider("gemini")
}

/// Builds the Interactions [`GenerationConfig`] from the ADK generation config
/// and the resolved thinking level.
///
/// Returns `None` when there is nothing to configure, leaving the request's
/// `generation_config` unset.
fn build_generation_config(
    config: Option<&GenerateContentConfig>,
    thinking_level: Option<ThinkingLevel>,
) -> Option<GenerationConfig> {
    let mut gen_config = GenerationConfig::default();
    let mut populated = false;

    if let Some(config) = config {
        if let Some(max_output_tokens) = config.max_output_tokens {
            gen_config.max_output_tokens = Some(max_output_tokens);
            populated = true;
        }
        if let Some(temperature) = config.temperature {
            gen_config.temperature = Some(temperature);
            populated = true;
        }
        if let Some(top_p) = config.top_p {
            gen_config.top_p = Some(top_p);
            populated = true;
        }
        if let Some(seed) = config.seed {
            gen_config.seed = Some(seed);
            populated = true;
        }
        if !config.stop_sequences.is_empty() {
            gen_config.stop_sequences = config.stop_sequences.clone();
            populated = true;
        }
    }

    if let Some(level) = thinking_level {
        gen_config.thinking_level = Some(level);
        populated = true;
    }

    if populated { Some(gen_config) } else { None }
}

// ══════════════════════════════════════════════════════════════════════
// Streaming: SSE event → LlmResponse chunk
// ══════════════════════════════════════════════════════════════════════

/// Accumulator threaded across an interaction SSE stream.
///
/// The Interactions API streams a turn as a sequence of [`InteractionSseEvent`]s rather than
/// a single response (<https://aistudio.google.com/docs/streaming>). Each step opens with a
/// `step.start`, streams `step.delta` events and closes with a `step.stop`, and the terminal
/// `interaction.completed` event carries no steps, so the response is assembled by folding
/// the stream. This accumulator carries the cross-event state the fold needs: the
/// server-assigned interaction id and the in-flight function calls keyed by step index.
///
/// The fold itself lives in [`sse_event_to_chunk`], which is a pure function of
/// `(event, &mut SseAccumulator)` so it can be unit-tested without a network
/// round-trip (the streaming transport in `client` simply drives it over the
/// real SSE stream).
#[derive(Debug, Default)]
pub(crate) struct SseAccumulator {
    /// The server-assigned interaction id, recorded from `interaction.created`,
    /// `interaction.status_update`, or `interaction.completed`. Stamped onto
    /// every emitted chunk so the agent's continuity plumbing can chain turns.
    interaction_id: Option<String>,
    /// In-flight function calls keyed by step index. A call's `name` and `id` arrive on its
    /// `step.start`, its arguments as `arguments_delta` fragments of one JSON string.
    function_calls: HashMap<i64, FunctionCallBuilder>,
}

/// A function call being assembled from its `step.start` and `step.delta` events.
#[derive(Debug, Default)]
struct FunctionCallBuilder {
    name: Option<String>,
    id: Option<String>,
    /// The arguments the `step.start` carried: `{}` when they stream as deltas.
    start_arguments: Option<Value>,
    /// The concatenated `arguments_delta` fragments.
    arguments: String,
    signature: Option<String>,
}

impl SseAccumulator {
    /// Creates an empty accumulator for a fresh interaction stream.
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Returns the recorded interaction id, if any has been seen yet.
    ///
    /// Used by the streaming transport's tests to assert id propagation; the
    /// fold functions read the field directly.
    #[cfg(test)]
    pub(crate) fn interaction_id(&self) -> Option<&str> {
        self.interaction_id.as_deref()
    }
}

/// Folds a single [`InteractionSseEvent`] into the running [`SseAccumulator`],
/// optionally producing an [`LlmResponse`] chunk to yield.
///
/// This is the streaming counterpart to [`to_llm_response`]: where that maps a
/// *completed* [`Interaction`] in one shot, this maps the SSE event timeline
/// incrementally:
///
/// | SSE event | Result |
/// |-----------|--------|
/// | `interaction.created` / `interaction.status_update` | record id; no chunk |
/// | `step.start` of a `model_output` step with content | partial chunk of that content |
/// | `step.start` of a `thought` step with a summary or signature | partial [`Part::Thinking`] |
/// | `step.start` of a `function_call` step | record name, id and arguments; no chunk |
/// | `step.delta` `text`, `image`, `audio`, `document`, `video` | partial content chunk |
/// | `step.delta` `thought_summary` / `thought_signature` | partial [`Part::Thinking`] |
/// | `step.delta` `arguments_delta` | accumulate arguments; no chunk |
/// | `step.stop` | no chunk |
/// | `interaction.completed` | final chunk; tool-call turns remain open for Runner execution |
/// | `error` | `Some(Err(AdkError))` |
/// | `Other` | ignored (forward-compatible) |
///
/// Content is emitted as partial chunks as it arrives so the runner can stream it to the
/// client; the agent joins the partial [`Part::Thinking`] items of one thought, the last
/// of which carries the signature. Function-call argument fragments are *not* emitted
/// per-delta — a partial JSON arguments string is not a usable `FunctionCall` — they are
/// accumulated and flushed as complete [`Part::FunctionCall`]s on `interaction.completed`.
/// Each chunk carries the recorded `interaction_id` so the agent's continuity plumbing
/// works identically to the non-streaming path.
///
/// # Arguments
///
/// * `event` - The SSE event to fold.
/// * `acc` - The cross-event accumulator (interaction id + in-flight calls).
///
/// # Returns
///
/// `Some(Ok(chunk))` to yield a response chunk, `Some(Err(..))` for a terminal
/// `error` event, or `None` for events that only update accumulator state.
pub(crate) fn sse_event_to_chunk(
    event: InteractionSseEvent,
    acc: &mut SseAccumulator,
) -> Option<adk_core::Result<LlmResponse>> {
    match event {
        InteractionSseEvent::InteractionCreated { interaction, .. } => {
            record_id(acc, interaction.id);
            None
        }
        InteractionSseEvent::InteractionStatusUpdate { interaction_id, .. } => {
            record_id(acc, interaction_id);
            None
        }
        InteractionSseEvent::StepStart { index, step, .. } => {
            sse_step_start_to_chunk(index, step, acc)
        }
        InteractionSseEvent::StepDelta { index, delta, .. } => {
            sse_step_delta_to_chunk(index, delta, acc)
        }
        InteractionSseEvent::InteractionCompleted { interaction, .. } => {
            Some(Ok(complete_chunk(interaction, acc)))
        }
        InteractionSseEvent::Error { error, .. } => Some(Err(stream_error_to_adk(&error))),
        // `step.stop` carries no content: a function call flushes on completion, once its
        // arguments are whole. `Other` is ignored for forward-compatibility.
        InteractionSseEvent::StepStop { .. } | InteractionSseEvent::Other(_) => None,
    }
}

/// Records a non-empty interaction id onto the accumulator.
fn record_id(acc: &mut SseAccumulator, id: String) {
    if !id.is_empty() {
        acc.interaction_id = Some(id);
    }
}

/// Maps a `step.start` to a chunk, or records the function call it opens.
///
/// A step can start with content already in it
/// (<https://aistudio.google.com/docs/interactions-breaking-changes-may-2026#streaming>):
/// a `model_output` step's first content blocks, a `thought` step's signature, or a
/// `function_call` step's `name`, `id` and (empty) `arguments`.
fn sse_step_start_to_chunk(
    index: i64,
    step: Step,
    acc: &mut SseAccumulator,
) -> Option<adk_core::Result<LlmResponse>> {
    match step {
        Step::ModelOutput { content } => {
            partial_chunk(content.iter().filter_map(content_to_part).collect(), acc)
        }
        Step::Thought { signature, summary } => {
            let thinking: String = summary.iter().filter_map(IxContent::as_text).collect();
            if thinking.is_empty() && signature.is_none() {
                return None;
            }
            partial_chunk(vec![Part::Thinking { thinking, signature }], acc)
        }
        Step::FunctionCall { id, name, arguments, signature } => {
            let call = acc.function_calls.entry(index).or_default();
            call.name = Some(name);
            call.id = Some(id);
            call.start_arguments = Some(arguments);
            call.signature = signature;
            None
        }
        // Request-side steps and server-side tool steps add nothing to the model turn.
        Step::UserInput { .. } | Step::FunctionResult { .. } | Step::Other(_) => None,
    }
}

/// Maps a `step.delta` to a partial chunk, or accumulates a function call's arguments.
fn sse_step_delta_to_chunk(
    index: i64,
    delta: StepDelta,
    acc: &mut SseAccumulator,
) -> Option<adk_core::Result<LlmResponse>> {
    let parts = match delta {
        StepDelta::Text { text } => vec![Part::Text { text }],
        StepDelta::Image(image) => content_to_part(&IxContent::Image(image)).into_iter().collect(),
        StepDelta::Audio(audio) => content_to_part(&IxContent::Audio(audio)).into_iter().collect(),
        StepDelta::Document(document) => {
            content_to_part(&IxContent::Document(document)).into_iter().collect()
        }
        StepDelta::Video(video) => content_to_part(&IxContent::Video(video)).into_iter().collect(),
        StepDelta::ArgumentsDelta { arguments } => {
            let call = acc.function_calls.entry(index).or_default();
            call.arguments.push_str(arguments.as_deref().unwrap_or_default());
            Vec::new()
        }
        StepDelta::ThoughtSignature { signature } => match acc.function_calls.get_mut(&index) {
            // A signature streamed on a function-call step belongs to that call.
            Some(call) => {
                call.signature = signature;
                Vec::new()
            }
            None => signature
                .map(|signature| Part::Thinking {
                    thinking: String::new(),
                    signature: Some(signature),
                })
                .into_iter()
                .collect(),
        },
        StepDelta::ThoughtSummary { content } => content
            .as_ref()
            .and_then(IxContent::as_text)
            .map(|text| Part::Thinking { thinking: text.to_string(), signature: None })
            .into_iter()
            .collect(),
        // A delta type this release does not model, now or in a later API revision.
        StepDelta::Other(_) => Vec::new(),
        _ => Vec::new(),
    };
    partial_chunk(parts, acc)
}

/// Builds a partial chunk (`partial = true`, `turn_complete = false`) of `parts`, or `None`
/// when there are no parts.
fn partial_chunk(parts: Vec<Part>, acc: &SseAccumulator) -> Option<adk_core::Result<LlmResponse>> {
    if parts.is_empty() {
        return None;
    }
    Some(Ok(LlmResponse {
        content: Some(Content { role: "model".to_string(), parts }),
        partial: true,
        turn_complete: false,
        interaction_id: acc.interaction_id.clone(),
        ..Default::default()
    }))
}

/// Builds the terminal chunk for an `interaction.completed` event.
///
/// Flushes any accumulated function calls into [`Part::FunctionCall`]s (the tool
/// loop needs complete calls), folds in usage/finish-reason from the completed
/// interaction, and stamps the interaction id. When the completed interaction
/// carries its own steps (some servers populate them), those parts are taken via
/// [`to_llm_response`] and the streamed function calls are appended.
fn complete_chunk(interaction: Interaction, acc: &mut SseAccumulator) -> LlmResponse {
    record_id(acc, interaction.id.clone());

    // Start from whatever the completed interaction carries (usually empty
    // steps, but be faithful when populated), then append the flushed
    // function calls accumulated from the delta stream.
    let mut response = to_llm_response(&interaction);

    let flushed = flush_function_calls(acc);
    if !flushed.is_empty() {
        match response.content {
            Some(ref mut content) => content.parts.extend(flushed),
            None => {
                response.content = Some(Content { role: "model".to_string(), parts: flushed });
            }
        }
    }

    // The completed event is the final protocol chunk, but a tool-call turn
    // remains open so the Runner can execute the requested tools.
    response.partial = false;
    response.turn_complete =
        response.content.as_ref().is_none_or(|content| !content.has_function_calls());
    if response.interaction_id.is_none() {
        response.interaction_id = acc.interaction_id.clone();
    }
    if response.finish_reason.is_none() {
        response.finish_reason = Some(FinishReason::Stop);
    }
    response
}

/// Drains the accumulated function calls into [`Part::FunctionCall`]s.
///
/// Calls are flushed in step-index order so the produced parts are deterministic. The
/// concatenated `arguments_delta` fragments are parsed into a [`Value`]; with no fragments,
/// the arguments the `step.start` carried are used, and an empty or unparseable string falls
/// back to an empty object so the tool loop always receives a structured arguments value.
fn flush_function_calls(acc: &mut SseAccumulator) -> Vec<Part> {
    let mut entries: Vec<(i64, FunctionCallBuilder)> = acc.function_calls.drain().collect();
    entries.sort_by_key(|(index, _)| *index);
    entries
        .into_iter()
        .filter_map(|(_, call)| {
            let name = call.name?;
            let args = if call.arguments.trim().is_empty() {
                call.start_arguments
                    .filter(Value::is_object)
                    .unwrap_or_else(|| Value::Object(serde_json::Map::new()))
            } else {
                parse_arguments(&call.arguments)
            };
            Some(Part::FunctionCall { name, args, id: call.id, thought_signature: call.signature })
        })
        .collect()
}

/// Parses an accumulated function-call arguments string into a [`Value`].
///
/// Returns an empty JSON object when the string is empty or fails to parse, so
/// the tool loop always receives a well-formed arguments value.
fn parse_arguments(raw: &str) -> Value {
    if raw.trim().is_empty() {
        return Value::Object(serde_json::Map::new());
    }
    serde_json::from_str(raw).unwrap_or_else(|_| Value::Object(serde_json::Map::new()))
}

/// Maps a streamed [`InteractionStreamError`] to an [`AdkError`].
///
/// The error is attributed to the `"gemini"` provider with category
/// [`ErrorCategory::Internal`]; the wire `code` (when present) is folded into
/// the human-readable message so callers can distinguish stream error types.
fn stream_error_to_adk(error: &InteractionStreamError) -> AdkError {
    let base = if error.message.is_empty() {
        "the Gemini interaction stream reported an error".to_string()
    } else {
        error.message.clone()
    };
    let message = match &error.code {
        Some(code) if !code.is_empty() => format!("{base} (code: {code})"),
        _ => base,
    };
    AdkError::new(
        ErrorComponent::Model,
        ErrorCategory::Internal,
        "model.gemini.interactions.stream_error",
        message,
    )
    .with_provider("gemini")
}

#[cfg(test)]
mod tests {
    use super::*;
    use adk_core::FunctionResponseData;

    fn request_with(contents: Vec<Content>) -> LlmRequest {
        LlmRequest {
            model: "gemini-3.7-flash".to_string(),
            contents,
            config: None,
            tools: adk_core::ToolDeclarations::new(),
            previous_response_id: None,
        }
    }

    fn model_target() -> InteractionTarget {
        InteractionTarget::Model("gemini-3.7-flash".to_string())
    }

    #[test]
    fn single_turn_maps_contents_to_input_and_sets_model_target() {
        let request = request_with(vec![Content::new("user").with_text("Hello there")]);

        let built = build_request(&request, &model_target(), None, true, true)
            .expect("build_request should succeed");

        assert_eq!(built.model.as_deref(), Some("gemini-3.7-flash"));
        assert_eq!(built.agent, None);
        match built.input {
            Input::Content(blocks) => {
                assert_eq!(blocks.len(), 1);
                assert_eq!(blocks[0].as_text(), Some("Hello there"));
            }
            other => panic!("expected Input::Content, got {other:?}"),
        }
    }

    #[test]
    fn agent_target_sets_agent_field() {
        let request = request_with(vec![Content::new("user").with_text("Research this")]);
        let target = InteractionTarget::Agent("deep-research-preview-04-2026".to_string());

        let built = build_request(&request, &target, None, true, true)
            .expect("build_request should succeed");

        assert_eq!(built.agent.as_deref(), Some("deep-research-preview-04-2026"));
        assert_eq!(built.model, None);
    }

    #[test]
    fn system_content_maps_to_system_instruction() {
        let request = request_with(vec![
            Content::new("system").with_text("You are helpful."),
            Content::new("user").with_text("Hi"),
        ]);

        let built = build_request(&request, &model_target(), None, true, true)
            .expect("build_request should succeed");

        assert_eq!(built.system_instruction.as_deref(), Some("You are helpful."));
        // The system turn must not leak into the input.
        match built.input {
            Input::Content(blocks) => {
                assert_eq!(blocks.len(), 1);
                assert_eq!(blocks[0].as_text(), Some("Hi"));
            }
            other => panic!("expected Input::Content, got {other:?}"),
        }
    }

    #[test]
    fn previous_response_id_sets_continuation_and_sends_latest_turn_only() {
        // A multi-turn transcript with a prior interaction id and stateful=true.
        let mut request = request_with(vec![
            Content::new("user").with_text("First question"),
            Content::new("model").with_text("First answer"),
            Content::new("user").with_text("Second question"),
        ]);
        request.previous_response_id = Some("interaction-123".to_string());

        let built = build_request(&request, &model_target(), None, true, true)
            .expect("build_request should succeed");

        // Continuation id is set.
        assert_eq!(built.previous_interaction_id.as_deref(), Some("interaction-123"));

        // Only the latest user turn is sent (Property 4: stateful minimization).
        match built.input {
            Input::Content(blocks) => {
                assert_eq!(blocks.len(), 1, "stateful continuation must send only the latest turn");
                assert_eq!(blocks[0].as_text(), Some("Second question"));
            }
            other => panic!("expected Input::Content with the latest turn, got {other:?}"),
        }
    }

    #[test]
    fn stateless_when_store_false_disables_continuation() {
        let mut request = request_with(vec![Content::new("user").with_text("Only question")]);
        request.previous_response_id = Some("interaction-123".to_string());

        // store=false must disable stateful continuation and send the transcript.
        let built = build_request(&request, &model_target(), None, true, false)
            .expect("build_request should succeed");

        assert_eq!(built.previous_interaction_id, None);
        assert_eq!(built.store, Some(false));
        match built.input {
            Input::Content(blocks) => assert_eq!(blocks[0].as_text(), Some("Only question")),
            other => panic!("expected Input::Content, got {other:?}"),
        }
    }

    #[test]
    fn multi_turn_transcript_maps_to_steps_when_not_chaining() {
        let request = request_with(vec![
            Content::new("user").with_text("Question one"),
            Content::new("model").with_text("Answer one"),
            Content::new("user").with_text("Question two"),
        ]);

        // No previous_response_id → full transcript as steps.
        let built = build_request(&request, &model_target(), None, true, true)
            .expect("build_request should succeed");

        match built.input {
            Input::Steps(steps) => {
                assert_eq!(steps.len(), 3);
                assert!(matches!(steps[0], Step::UserInput { .. }));
                assert!(matches!(steps[1], Step::ModelOutput { .. }));
                assert!(matches!(steps[2], Step::UserInput { .. }));
            }
            other => panic!("expected Input::Steps, got {other:?}"),
        }
    }

    #[test]
    fn function_response_maps_to_function_result_step() {
        let request = request_with(vec![
            Content::new("user").with_text("What's the weather?"),
            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,
                }],
            },
            Content {
                role: "function".to_string(),
                parts: vec![Part::FunctionResponse {
                    function_response: FunctionResponseData::new(
                        "get_weather",
                        serde_json::json!({"temp": 72}),
                    ),
                    id: Some("call-1".to_string()),
                    annotations: None,
                }],
            },
        ]);

        let built = build_request(&request, &model_target(), None, true, true)
            .expect("build_request should succeed");

        match built.input {
            Input::Steps(steps) => {
                let has_call = steps.iter().any(|s| {
                    matches!(s, Step::FunctionCall { id, name, .. } if id == "call-1" && name == "get_weather")
                });
                let has_result = steps.iter().any(
                    |s| matches!(s, Step::FunctionResult { call_id, .. } if call_id == "call-1"),
                );
                assert!(has_call, "expected a function_call step");
                assert!(has_result, "expected a function_result step");
            }
            other => panic!("expected Input::Steps, got {other:?}"),
        }
    }

    /// A function result is flagged `is_error` only when the agent wrote it for a call that
    /// was refused, not run, or failed.
    #[test]
    fn only_a_refused_unrun_or_failed_answer_is_flagged_an_error() {
        use adk_core::ToolResultStatus;
        let flag = |status: Option<ToolResultStatus>| {
            let mut answer = Part::FunctionResponse {
                function_response: FunctionResponseData::new(
                    "get_weather",
                    serde_json::json!({ "error": "denied" }),
                ),
                id: Some("call-1".to_string()),
                annotations: None,
            };
            if let Some(status) = status {
                answer.set_tool_result_status(status, None);
            }
            let request = request_with(vec![
                Content::new("user").with_text("What's the weather?"),
                Content {
                    role: "model".to_string(),
                    parts: vec![Part::FunctionCall {
                        name: "get_weather".to_string(),
                        args: serde_json::json!({}),
                        id: Some("call-1".to_string()),
                        thought_signature: None,
                    }],
                },
                Content { role: "function".to_string(), parts: vec![answer] },
            ]);
            let built = build_request(&request, &model_target(), None, true, true)
                .expect("build_request should succeed");
            let Input::Steps(steps) = built.input else { panic!("expected steps") };
            steps
                .into_iter()
                .find_map(|step| match step {
                    Step::FunctionResult { is_error, .. } => Some(is_error),
                    _ => None,
                })
                .expect("a function_result step")
        };
        for status in
            [ToolResultStatus::Refused, ToolResultStatus::NotRun, ToolResultStatus::Failed]
        {
            assert_eq!(flag(Some(status)), Some(true), "{status:?}");
        }
        for status in [
            ToolResultStatus::Held,
            ToolResultStatus::OutcomeUnknown,
            ToolResultStatus::Withheld,
            ToolResultStatus::Succeeded,
        ] {
            assert_eq!(flag(Some(status)), None, "{status:?}");
        }
        assert_eq!(flag(None), None, "a tool's own payload is not read");
    }

    #[test]
    fn response_schema_maps_to_response_format() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": { "answer": { "type": "string" } }
        });
        let mut request = request_with(vec![Content::new("user").with_text("Answer in JSON")]);
        request.config = Some(GenerateContentConfig {
            response_schema: Some(schema.clone()),
            ..Default::default()
        });

        let built = build_request(&request, &model_target(), None, true, true)
            .expect("build_request should succeed");

        match built.response_format {
            Some(ResponseFormat::Text { mime_type, schema: out_schema }) => {
                assert_eq!(mime_type.as_deref(), Some("application/json"));
                assert_eq!(out_schema, Some(schema));
            }
            other => panic!("expected ResponseFormat::Text, got {other:?}"),
        }
    }

    #[test]
    fn thinking_level_maps_to_generation_config() {
        let request = request_with(vec![Content::new("user").with_text("Think hard")]);

        let built = build_request(&request, &model_target(), Some(ThinkingLevel::High), true, true)
            .expect("build_request should succeed");

        let gen_config = built.generation_config.expect("generation_config should be set");
        assert_eq!(gen_config.thinking_level, Some(ThinkingLevel::High));
    }

    #[test]
    fn no_generation_config_when_nothing_to_configure() {
        let request = request_with(vec![Content::new("user").with_text("Plain")]);

        let built = build_request(&request, &model_target(), None, true, true)
            .expect("build_request should succeed");

        assert!(built.generation_config.is_none());
    }

    #[test]
    fn sampling_parameters_map_to_generation_config() {
        let mut request = request_with(vec![Content::new("user").with_text("Configure me")]);
        request.config = Some(GenerateContentConfig {
            max_output_tokens: Some(256),
            temperature: Some(0.5),
            top_p: Some(0.9),
            seed: Some(42),
            stop_sequences: vec!["STOP".to_string()],
            ..Default::default()
        });

        let built = build_request(&request, &model_target(), None, true, true)
            .expect("build_request should succeed");

        let gen_config = built.generation_config.expect("generation_config should be set");
        assert_eq!(gen_config.max_output_tokens, Some(256));
        assert_eq!(gen_config.temperature, Some(0.5));
        assert_eq!(gen_config.top_p, Some(0.9));
        assert_eq!(gen_config.seed, Some(42));
        assert_eq!(gen_config.stop_sequences, vec!["STOP".to_string()]);
    }

    #[test]
    fn penalties_and_logprobs_fail_by_name() {
        let mut request = request_with(vec![Content::new("user").with_text("Configure me")]);
        request.config = Some(GenerateContentConfig {
            presence_penalty: Some(0.25),
            frequency_penalty: Some(0.5),
            top_logprobs: Some(2),
            seed: Some(42),
            ..Default::default()
        });

        let error = build_request(&request, &model_target(), None, true, true)
            .expect_err("the Interactions API has no penalty or logprobs field");

        assert_eq!(error.code, "model.unsupported_config");
        assert!(
            error.message.contains("`frequency_penalty`, `presence_penalty`, `top_logprobs`"),
            "{}",
            error.message
        );
    }

    #[test]
    fn tools_map_to_function_tools() {
        let mut tools = adk_core::ToolDeclarations::new();
        tools.insert(
            "get_weather".to_string(),
            serde_json::json!({
                "name": "get_weather",
                "description": "Get the weather for a city",
                "parameters": {
                    "type": "object",
                    "properties": { "city": { "type": "string" } }
                }
            }),
        );
        tools.insert(
            "get_time".to_string(),
            serde_json::json!({
                "name": "get_time",
                "description": "Get the current time"
            }),
        );

        let mut request = request_with(vec![Content::new("user").with_text("Tools please")]);
        request.tools = tools;

        let built = build_request(&request, &model_target(), None, true, true)
            .expect("build_request should succeed");

        assert_eq!(built.tools.len(), 2);
        // Sorted by name → get_time, get_weather.
        match &built.tools[0] {
            Tool::Function { name, description, .. } => {
                assert_eq!(name, "get_time");
                assert_eq!(description.as_deref(), Some("Get the current time"));
            }
            other => panic!("expected Tool::Function, got {other:?}"),
        }
        match &built.tools[1] {
            Tool::Function { name, parameters, .. } => {
                assert_eq!(name, "get_weather");
                assert!(parameters.is_some(), "get_weather should carry its parameters schema");
            }
            other => panic!("expected Tool::Function, got {other:?}"),
        }
    }

    #[test]
    fn tool_name_falls_back_to_map_key() {
        let mut tools = adk_core::ToolDeclarations::new();
        // Declaration with no explicit "name" field.
        tools.insert(
            "lookup".to_string(),
            serde_json::json!({ "description": "Look something up" }),
        );

        let mut request = request_with(vec![Content::new("user").with_text("Hi")]);
        request.tools = tools;

        let built = build_request(&request, &model_target(), None, true, true)
            .expect("build_request should succeed");

        match &built.tools[0] {
            Tool::Function { name, .. } => assert_eq!(name, "lookup"),
            other => panic!("expected Tool::Function, got {other:?}"),
        }
    }

    /// A built-in declaration (carrying the `x-adk-gemini-tool` marker) is the
    /// shape produced by `GoogleSearchTool::declaration()`.
    fn builtin_search_declaration() -> Value {
        serde_json::json!({
            "name": "google_search",
            "description": "Performs a Google search to retrieve information from the web.",
            "x-adk-gemini-tool": { "google_search": {} }
        })
    }

    /// A custom function declaration (carrying `parameters`, no marker).
    fn function_declaration(name: &str) -> Value {
        serde_json::json!({
            "name": name,
            "description": format!("Custom tool {name}"),
            "parameters": {
                "type": "object",
                "properties": { "value": { "type": "string" } }
            }
        })
    }

    #[test]
    fn mixing_builtin_and_function_tools_errors_invalid_input() {
        let mut tools = adk_core::ToolDeclarations::new();
        tools.insert("google_search".to_string(), builtin_search_declaration());
        tools.insert("get_weather".to_string(), function_declaration("get_weather"));

        let mut request = request_with(vec![Content::new("user").with_text("Search and tools")]);
        request.tools = tools;

        let err = build_request(&request, &model_target(), None, true, true)
            .expect_err("mixing built-in and function tools must error");

        assert_eq!(err.category, ErrorCategory::InvalidInput);
        assert_eq!(err.details.provider.as_deref(), Some("gemini"));
        assert_eq!(err.code, "model.gemini.interactions.mixed_tools");

        let message = err.to_string();
        // The message names the offending built-in tool.
        assert!(message.contains("google_search"), "message should name the built-in tool");
        // The message points the developer at the bypass option.
        assert!(
            message.contains("with_bypass_multi_tools_limit"),
            "message should reference the bypass option"
        );
    }

    #[test]
    fn all_function_tools_including_bypass_converted_succeed() {
        let mut tools = adk_core::ToolDeclarations::new();
        // A bypass-converted google_search declares `parameters` and no marker,
        // so it is indistinguishable from any other function tool.
        tools.insert(
            "google_search".to_string(),
            serde_json::json!({
                "name": "google_search",
                "description": "Performs a Google search to retrieve information from the web.",
                "parameters": {
                    "type": "object",
                    "properties": { "query": { "type": "string" } },
                    "required": ["query"]
                }
            }),
        );
        tools.insert("get_weather".to_string(), function_declaration("get_weather"));

        let mut request = request_with(vec![Content::new("user").with_text("Uniform tools")]);
        request.tools = tools;

        let built = build_request(&request, &model_target(), None, true, true)
            .expect("a uniform function-tool set must build successfully");

        assert_eq!(built.tools.len(), 2);
        for tool in &built.tools {
            assert!(
                matches!(tool, Tool::Function { .. }),
                "every tool should be a function tool, got {tool:?}"
            );
        }
    }

    #[test]
    fn builtin_only_set_succeeds_and_maps_to_dedicated_variant() {
        let mut tools = adk_core::ToolDeclarations::new();
        tools.insert("google_search".to_string(), builtin_search_declaration());

        let mut request = request_with(vec![Content::new("user").with_text("Search only")]);
        request.tools = tools;

        let built = build_request(&request, &model_target(), None, true, true)
            .expect("a built-in-only tool set must build successfully");

        assert_eq!(built.tools.len(), 1);
        assert!(
            matches!(built.tools[0], Tool::GoogleSearch { .. }),
            "google_search should map to Tool::GoogleSearch, got {:?}",
            built.tools[0]
        );
    }

    #[test]
    fn unrecognized_builtin_only_set_maps_to_other() {
        let mut tools = adk_core::ToolDeclarations::new();
        tools.insert(
            "google_maps".to_string(),
            serde_json::json!({
                "name": "google_maps",
                "description": "Maps grounding",
                "x-adk-gemini-tool": { "google_maps": {} }
            }),
        );

        let mut request = request_with(vec![Content::new("user").with_text("Maps")]);
        request.tools = tools;

        let built = build_request(&request, &model_target(), None, true, true)
            .expect("an unrecognized built-in-only set must still build");

        assert_eq!(built.tools.len(), 1);
        assert!(
            matches!(built.tools[0], Tool::Other(_)),
            "an unrecognized built-in should pass through as Tool::Other, got {:?}",
            built.tools[0]
        );
    }

    #[test]
    fn inline_image_part_maps_to_image_content() {
        let request = request_with(vec![
            Content::new("user")
                .with_text("Describe")
                .with_inline_data("image/png", vec![0x89, 0x50, 0x4E, 0x47]),
        ]);

        let built = build_request(&request, &model_target(), None, true, true)
            .expect("build_request should succeed");

        match built.input {
            Input::Content(blocks) => {
                assert_eq!(blocks.len(), 2);
                assert!(
                    matches!(blocks[1], IxContent::Image(_)),
                    "expected an image content block"
                );
            }
            other => panic!("expected Input::Content, got {other:?}"),
        }
    }

    #[test]
    fn store_flag_is_forwarded() {
        let request = request_with(vec![Content::new("user").with_text("Store me")]);

        let stored = build_request(&request, &model_target(), None, true, true)
            .expect("build_request should succeed");
        assert_eq!(stored.store, Some(true));

        let not_stored = build_request(&request, &model_target(), None, true, false)
            .expect("build_request should succeed");
        assert_eq!(not_stored.store, Some(false));
    }

    // ── to_llm_response ────────────────────────────────────────────────

    /// Builds an [`Interaction`] with the given id, status, and steps.
    fn interaction_with(id: &str, status: InteractionStatus, steps: Vec<Step>) -> Interaction {
        Interaction {
            id: id.to_string(),
            model: Some("gemini-3.7-flash".to_string()),
            agent: None,
            status,
            steps,
            usage: None,
            created: None,
            updated: None,
            environment_id: None,
            continuation_token: None,
        }
    }

    #[test]
    fn completed_text_output_maps_to_text_part_and_stop() {
        let interaction = interaction_with(
            "v1_abc",
            InteractionStatus::Completed,
            vec![Step::ModelOutput { content: vec![IxContent::text("Hello, world.")] }],
        );

        let response = to_llm_response(&interaction);

        let content = response.content.expect("completed output should carry content");
        assert_eq!(content.role, "model");
        assert_eq!(content.parts.len(), 1);
        match &content.parts[0] {
            Part::Text { text } => assert_eq!(text, "Hello, world."),
            other => panic!("expected Part::Text, got {other:?}"),
        }
        assert_eq!(response.finish_reason, Some(FinishReason::Stop));
        assert!(response.turn_complete);
        assert!(!response.partial);
        assert_eq!(response.interaction_id.as_deref(), Some("v1_abc"));
    }

    #[test]
    fn requires_action_maps_function_call_with_no_finish_reason() {
        let args = serde_json::json!({ "city": "Boston" });
        let interaction = interaction_with(
            "v1_call",
            InteractionStatus::RequiresAction,
            vec![Step::FunctionCall {
                id: "call-1".to_string(),
                name: "get_weather".to_string(),
                arguments: args.clone(),
                signature: Some("sig-xyz".to_string()),
            }],
        );

        let response = to_llm_response(&interaction);

        let content = response.content.expect("requires_action should carry a function call");
        assert_eq!(content.parts.len(), 1);
        match &content.parts[0] {
            Part::FunctionCall { name, args: call_args, id, thought_signature } => {
                assert_eq!(name, "get_weather");
                assert_eq!(call_args, &args);
                assert_eq!(id.as_deref(), Some("call-1"));
                assert_eq!(thought_signature.as_deref(), Some("sig-xyz"));
            }
            other => panic!("expected Part::FunctionCall, got {other:?}"),
        }
        // requires_action keeps the turn open so the tool loop can run.
        assert_eq!(response.finish_reason, None);
        assert!(!response.turn_complete);
    }

    #[test]
    fn thought_step_maps_to_thinking_part() {
        let interaction = interaction_with(
            "v1_think",
            InteractionStatus::Completed,
            vec![
                Step::Thought {
                    signature: Some("think-sig".to_string()),
                    summary: vec![
                        IxContent::text("First I consider, "),
                        IxContent::text("then I conclude."),
                    ],
                },
                Step::ModelOutput { content: vec![IxContent::text("Answer.")] },
            ],
        );

        let response = to_llm_response(&interaction);
        let content = response.content.expect("should carry content");
        // Thinking part first, then text.
        match &content.parts[0] {
            Part::Thinking { thinking, signature } => {
                assert_eq!(thinking, "First I consider, then I conclude.");
                assert_eq!(signature.as_deref(), Some("think-sig"));
            }
            other => panic!("expected Part::Thinking, got {other:?}"),
        }
        assert!(matches!(&content.parts[1], Part::Text { text } if text == "Answer."));
    }

    #[test]
    fn inline_image_step_maps_to_inline_data_with_bytes() {
        let bytes = vec![0x89, 0x50, 0x4E, 0x47];
        let encoded = BASE64_STANDARD.encode(&bytes);
        let interaction = interaction_with(
            "v1_img",
            InteractionStatus::Completed,
            vec![Step::ModelOutput { content: vec![IxContent::image(encoded, "image/png")] }],
        );

        let response = to_llm_response(&interaction);
        let content = response.content.expect("should carry content");
        match &content.parts[0] {
            Part::InlineData { mime_type, data, .. } => {
                assert_eq!(mime_type, "image/png");
                assert_eq!(data, &bytes);
            }
            other => panic!("expected Part::InlineData, got {other:?}"),
        }
    }

    #[test]
    fn uri_image_step_maps_to_file_data() {
        let interaction = interaction_with(
            "v1_uri",
            InteractionStatus::Completed,
            vec![Step::ModelOutput {
                content: vec![IxContent::Image(ImageContent {
                    data: None,
                    mime_type: Some("image/jpeg".to_string()),
                    uri: Some("https://example.com/cat.jpg".to_string()),
                    resolution: None,
                })],
            }],
        );

        let response = to_llm_response(&interaction);
        let content = response.content.expect("should carry content");
        match &content.parts[0] {
            Part::FileData { mime_type, file_uri, .. } => {
                assert_eq!(mime_type, "image/jpeg");
                assert_eq!(file_uri, "https://example.com/cat.jpg");
            }
            other => panic!("expected Part::FileData, got {other:?}"),
        }
    }

    #[test]
    fn server_tool_step_recorded_in_provider_metadata_not_content() {
        let server_step = serde_json::json!({
            "type": "code_execution_call",
            "code": "print(2 + 2)"
        });
        let interaction = interaction_with(
            "v1_srv",
            InteractionStatus::Completed,
            vec![
                Step::Other(server_step.clone()),
                Step::ModelOutput { content: vec![IxContent::text("The answer is 4.")] },
            ],
        );

        let response = to_llm_response(&interaction);

        // The server step is NOT in the content parts.
        let content = response.content.expect("should carry the model_output text");
        assert_eq!(content.parts.len(), 1);
        assert!(matches!(&content.parts[0], Part::Text { .. }));

        // It IS recorded in provider_metadata.
        let metadata = response.provider_metadata.expect("server steps populate provider_metadata");
        let recorded = &metadata["gemini"]["interaction_steps"];
        assert_eq!(recorded.as_array().map(Vec::len), Some(1));
        assert_eq!(recorded[0], server_step);
        assert_eq!(metadata["gemini"]["status"], "completed");
    }

    #[test]
    fn no_provider_metadata_without_server_steps() {
        let interaction = interaction_with(
            "v1_plain",
            InteractionStatus::Completed,
            vec![Step::ModelOutput { content: vec![IxContent::text("plain")] }],
        );

        let response = to_llm_response(&interaction);
        assert!(response.provider_metadata.is_none());
    }

    #[test]
    fn usage_mapping_preserves_token_counts() {
        let mut interaction = interaction_with(
            "v1_usage",
            InteractionStatus::Completed,
            vec![Step::ModelOutput { content: vec![IxContent::text("counted")] }],
        );
        interaction.usage = Some(Usage {
            total_input_tokens: 120,
            total_output_tokens: 45,
            total_thought_tokens: 17,
            total_cached_tokens: 30,
            total_tool_use_tokens: 5,
            total_tokens: 182,
            input_tokens_by_modality: Vec::new(),
            output_tokens_by_modality: Vec::new(),
            raw: None,
        });

        let response = to_llm_response(&interaction);
        let usage = response.usage_metadata.expect("usage should map");
        assert_eq!(usage.prompt_token_count, 120);
        assert_eq!(usage.candidates_token_count, 45);
        assert_eq!(usage.total_token_count, 182);
        assert_eq!(usage.thinking_token_count, Some(17));
        assert_eq!(usage.cache_read_input_token_count, Some(30));
    }

    #[test]
    fn usage_zero_optional_counts_stay_none() {
        let mut interaction = interaction_with(
            "v1_usage_zero",
            InteractionStatus::Completed,
            vec![Step::ModelOutput { content: vec![IxContent::text("x")] }],
        );
        interaction.usage = Some(Usage {
            total_input_tokens: 10,
            total_output_tokens: 5,
            total_tokens: 15,
            ..Default::default()
        });

        let response = to_llm_response(&interaction);
        let usage = response.usage_metadata.expect("usage should map");
        assert_eq!(usage.thinking_token_count, None);
        assert_eq!(usage.cache_read_input_token_count, None);
    }

    #[test]
    fn empty_interaction_id_maps_to_none() {
        let interaction = interaction_with(
            "",
            InteractionStatus::Completed,
            vec![Step::ModelOutput { content: vec![IxContent::text("anon")] }],
        );

        let response = to_llm_response(&interaction);
        assert_eq!(response.interaction_id, None);
    }

    #[test]
    fn terminal_failure_statuses_map_to_total_finish_reasons() {
        for status in [
            InteractionStatus::Failed,
            InteractionStatus::BudgetExceeded,
            InteractionStatus::Cancelled,
            InteractionStatus::Unknown,
        ] {
            let interaction = interaction_with("v1_term", status, Vec::new());
            let response = to_llm_response(&interaction);
            assert_eq!(response.finish_reason, Some(FinishReason::Other));
            assert!(response.turn_complete);
            // No content parts → content is None.
            assert!(response.content.is_none());
        }
    }

    /// A hop that stops at its output cap (`requires_continuation`,
    /// <https://aistudio.google.com/docs/long-decode>) ends the turn as cut short, like
    /// `incomplete`.
    #[test]
    fn incomplete_and_continuation_statuses_map_to_max_tokens() {
        for status in [InteractionStatus::Incomplete, InteractionStatus::RequiresContinuation] {
            let interaction = interaction_with(
                "v1_inc",
                status,
                vec![Step::ModelOutput { content: vec![IxContent::text("partial answer")] }],
            );
            let response = to_llm_response(&interaction);
            assert_eq!(response.finish_reason, Some(FinishReason::MaxTokens), "{status:?}");
            assert!(response.turn_complete);
        }
    }

    #[test]
    fn in_progress_status_is_partial() {
        let interaction = interaction_with("v1_prog", InteractionStatus::InProgress, Vec::new());
        let response = to_llm_response(&interaction);
        assert_eq!(response.finish_reason, None);
        assert!(!response.turn_complete);
        assert!(response.partial);
    }

    #[test]
    fn user_input_and_function_result_steps_are_skipped_for_content() {
        let interaction = interaction_with(
            "v1_skip",
            InteractionStatus::Completed,
            vec![
                Step::UserInput { content: vec![IxContent::text("a question")] },
                Step::FunctionResult {
                    call_id: "call-1".to_string(),
                    name: Some("get_weather".to_string()),
                    result: serde_json::json!({ "temp": 72 }),
                    is_error: None,
                    signature: None,
                },
                Step::ModelOutput { content: vec![IxContent::text("the answer")] },
            ],
        );

        let response = to_llm_response(&interaction);
        let content = response.content.expect("should carry only the model output");
        assert_eq!(content.parts.len(), 1);
        assert!(matches!(&content.parts[0], Part::Text { text } if text == "the answer"));
    }

    // ──────────────────────────────────────────────────────────────────
    // Streaming SSE fold (`sse_event_to_chunk`)
    // ──────────────────────────────────────────────────────────────────

    fn created_event(id: &str) -> InteractionSseEvent {
        InteractionSseEvent::InteractionCreated {
            interaction: interaction_with(id, InteractionStatus::InProgress, Vec::new()),
            event_id: None,
        }
    }

    fn text_delta_event(index: i64, text: &str) -> InteractionSseEvent {
        InteractionSseEvent::StepDelta {
            index,
            delta: StepDelta::Text { text: text.to_string() },
            event_id: None,
        }
    }

    /// The `step.start` of a streamed function call: name and id, empty arguments
    /// (<https://aistudio.google.com/docs/streaming#event-step-start>).
    fn function_call_start_event(index: i64, name: &str, id: &str) -> InteractionSseEvent {
        InteractionSseEvent::StepStart {
            index,
            step: Step::FunctionCall {
                id: id.to_string(),
                name: name.to_string(),
                arguments: serde_json::json!({}),
                signature: None,
            },
            event_id: None,
        }
    }

    /// An `arguments_delta` fragment of a streamed function call.
    fn arguments_delta_event(index: i64, fragment: &str) -> InteractionSseEvent {
        InteractionSseEvent::StepDelta {
            index,
            delta: StepDelta::ArgumentsDelta { arguments: Some(fragment.to_string()) },
            event_id: None,
        }
    }

    fn delta_event(index: i64, delta: StepDelta) -> InteractionSseEvent {
        InteractionSseEvent::StepDelta { index, delta, event_id: None }
    }

    /// The parts of the partial chunk an event emits.
    fn partial_parts(event: InteractionSseEvent, acc: &mut SseAccumulator) -> Vec<Part> {
        let chunk = sse_event_to_chunk(event, acc)
            .expect("the event should emit a chunk")
            .expect("the chunk should be Ok");
        assert!(chunk.partial && !chunk.turn_complete, "{chunk:?}");
        chunk.content.expect("the chunk should carry content").parts
    }

    fn completed_event(id: &str) -> InteractionSseEvent {
        InteractionSseEvent::InteractionCompleted {
            interaction: interaction_with(id, InteractionStatus::Completed, Vec::new()),
            event_id: None,
        }
    }

    #[test]
    fn sse_created_records_id_without_emitting_a_chunk() {
        let mut acc = SseAccumulator::new();
        let chunk = sse_event_to_chunk(created_event("v1_stream"), &mut acc);
        assert!(chunk.is_none(), "created event should not emit a chunk");
        assert_eq!(acc.interaction_id(), Some("v1_stream"));
    }

    #[test]
    fn sse_status_update_records_id() {
        let mut acc = SseAccumulator::new();
        let event = InteractionSseEvent::InteractionStatusUpdate {
            interaction_id: "v1_status".to_string(),
            status: InteractionStatus::InProgress,
            event_id: None,
            continuation_token: None,
        };
        let chunk = sse_event_to_chunk(event, &mut acc);
        assert!(chunk.is_none());
        assert_eq!(acc.interaction_id(), Some("v1_status"));
    }

    #[test]
    fn sse_text_delta_emits_partial_text_chunk_with_id() {
        let mut acc = SseAccumulator::new();
        sse_event_to_chunk(created_event("v1_text"), &mut acc);

        let chunk = sse_event_to_chunk(text_delta_event(0, "Hello"), &mut acc)
            .expect("text delta should emit a chunk")
            .expect("text delta chunk should be Ok");

        assert!(chunk.partial, "text delta should be a partial chunk");
        assert!(!chunk.turn_complete, "text delta should not complete the turn");
        assert_eq!(chunk.interaction_id.as_deref(), Some("v1_text"));
        let content = chunk.content.expect("text delta should carry content");
        assert_eq!(content.role, "model");
        assert!(matches!(&content.parts[0], Part::Text { text } if text == "Hello"));
    }

    #[test]
    fn sse_completed_emits_final_chunk_with_turn_complete_and_id() {
        let mut acc = SseAccumulator::new();
        sse_event_to_chunk(created_event("v1_done"), &mut acc);
        sse_event_to_chunk(text_delta_event(0, "Hi"), &mut acc);

        let chunk = sse_event_to_chunk(completed_event("v1_done"), &mut acc)
            .expect("completed event should emit a chunk")
            .expect("completed chunk should be Ok");

        assert!(!chunk.partial, "completed chunk should not be partial");
        assert!(chunk.turn_complete, "completed chunk should complete the turn");
        assert_eq!(chunk.interaction_id.as_deref(), Some("v1_done"));
        assert_eq!(chunk.finish_reason, Some(FinishReason::Stop));
    }

    #[test]
    fn sse_error_event_maps_to_err() {
        let mut acc = SseAccumulator::new();
        let event = InteractionSseEvent::Error {
            error: InteractionStreamError {
                message: "model overloaded".to_string(),
                code: Some("RESOURCE_EXHAUSTED".to_string()),
            },
            event_id: None,
        };
        let result =
            sse_event_to_chunk(event, &mut acc).expect("error event should produce a result");
        let err = result.expect_err("error event should map to Err");
        assert_eq!(err.category, ErrorCategory::Internal);
        assert_eq!(err.details.provider.as_deref(), Some("gemini"));
        assert!(err.message.contains("model overloaded"));
        assert!(err.message.contains("RESOURCE_EXHAUSTED"));
    }

    #[test]
    fn sse_function_call_deltas_accumulate_then_flush_on_completion() {
        let mut acc = SseAccumulator::new();
        sse_event_to_chunk(created_event("v1_fn"), &mut acc);

        // The step's start carries name and id; argument fragments follow as deltas.
        assert!(
            sse_event_to_chunk(function_call_start_event(0, "get_weather", "call-1"), &mut acc)
                .is_none(),
            "a function call emits no chunk mid-stream"
        );
        for fragment in ["{\"ci", "ty\":\"NYC\"}"] {
            assert!(sse_event_to_chunk(arguments_delta_event(0, fragment), &mut acc).is_none());
        }

        let chunk = sse_event_to_chunk(completed_event("v1_fn"), &mut acc)
            .expect("completed event should emit a chunk")
            .expect("completed chunk should be Ok");

        let content = chunk.content.expect("completed chunk should carry the function call");
        assert_eq!(content.parts.len(), 1);
        match &content.parts[0] {
            Part::FunctionCall { name, args, id, .. } => {
                assert_eq!(name, "get_weather");
                assert_eq!(id.as_deref(), Some("call-1"));
                assert_eq!(args, &serde_json::json!({ "city": "NYC" }));
            }
            other => panic!("expected Part::FunctionCall, got {other:?}"),
        }
        assert!(!chunk.turn_complete, "tool-call turns must remain open for execution");
        assert_eq!(chunk.interaction_id.as_deref(), Some("v1_fn"));
    }

    #[test]
    fn sse_function_call_with_unparseable_args_falls_back_to_empty_object() {
        let mut acc = SseAccumulator::new();
        sse_event_to_chunk(function_call_start_event(0, "do_thing", "call-9"), &mut acc);
        sse_event_to_chunk(arguments_delta_event(0, "not json"), &mut acc);

        let chunk = sse_event_to_chunk(completed_event("v1_bad_args"), &mut acc)
            .expect("completed event should emit a chunk")
            .expect("completed chunk should be Ok");

        let content = chunk.content.expect("should carry the function call");
        match &content.parts[0] {
            Part::FunctionCall { name, args, .. } => {
                assert_eq!(name, "do_thing");
                assert_eq!(args, &serde_json::json!({}));
            }
            other => panic!("expected Part::FunctionCall, got {other:?}"),
        }
    }

    #[test]
    fn sse_multiple_function_calls_flush_in_index_order() {
        let mut acc = SseAccumulator::new();
        // Provide the calls out of index order to confirm deterministic ordering.
        for (index, name, id) in [(1, "second", "call-2"), (0, "first", "call-1")] {
            sse_event_to_chunk(function_call_start_event(index, name, id), &mut acc);
            sse_event_to_chunk(arguments_delta_event(index, "{}"), &mut acc);
        }

        let chunk = sse_event_to_chunk(completed_event("v1_multi"), &mut acc)
            .expect("completed event should emit a chunk")
            .expect("completed chunk should be Ok");

        let content = chunk.content.expect("should carry both function calls");
        assert_eq!(content.parts.len(), 2);
        assert!(matches!(&content.parts[0], Part::FunctionCall { name, .. } if name == "first"));
        assert!(matches!(&content.parts[1], Part::FunctionCall { name, .. } if name == "second"));
    }

    #[test]
    fn sse_step_start_stop_and_other_are_ignored() {
        let mut acc = SseAccumulator::new();
        let start = InteractionSseEvent::StepStart {
            index: 0,
            step: Step::ModelOutput { content: Vec::new() },
            event_id: None,
        };
        let stop = InteractionSseEvent::StepStop { index: 0, event_id: None };
        let other = InteractionSseEvent::Other(serde_json::json!({ "event_type": "future.thing" }));

        assert!(sse_event_to_chunk(start, &mut acc).is_none());
        assert!(sse_event_to_chunk(stop, &mut acc).is_none());
        assert!(sse_event_to_chunk(other, &mut acc).is_none());
    }

    /// A `model_output` step can start with its first content
    /// (<https://aistudio.google.com/docs/interactions-breaking-changes-may-2026#streaming>),
    /// so a short reply sent entirely on `step.start` still reaches the turn.
    #[test]
    fn sse_model_output_content_on_step_start_emits_a_partial_chunk() {
        let mut acc = SseAccumulator::new();
        let start = InteractionSseEvent::StepStart {
            index: 1,
            step: Step::ModelOutput { content: vec![IxContent::text("Once upon")] },
            event_id: None,
        };
        assert_eq!(partial_parts(start, &mut acc), vec![Part::Text { text: "Once upon".into() }]);
    }

    /// A `thought` step's signature arrives on its `step.start` or as a `thought_signature`
    /// delta, its summary as `thought_summary` deltas; each becomes a partial
    /// [`Part::Thinking`] the agent joins (<https://aistudio.google.com/docs/streaming>).
    #[test]
    fn sse_thought_steps_emit_thinking_with_their_signature() {
        let mut acc = SseAccumulator::new();
        let start = InteractionSseEvent::StepStart {
            index: 0,
            step: Step::Thought { signature: Some("abc123...".into()), summary: Vec::new() },
            event_id: None,
        };
        assert_eq!(
            partial_parts(start, &mut acc),
            vec![Part::Thinking { thinking: String::new(), signature: Some("abc123...".into()) }]
        );

        let bare_start = InteractionSseEvent::StepStart {
            index: 2,
            step: Step::Thought { signature: None, summary: Vec::new() },
            event_id: None,
        };
        assert!(sse_event_to_chunk(bare_start, &mut acc).is_none());
        let summary = delta_event(
            2,
            StepDelta::ThoughtSummary { content: Some(IxContent::text("I need the GCD...")) },
        );
        assert_eq!(
            partial_parts(summary, &mut acc),
            vec![Part::Thinking { thinking: "I need the GCD...".into(), signature: None }]
        );
        let signature =
            delta_event(2, StepDelta::ThoughtSignature { signature: Some("sig-2".into()) });
        assert_eq!(
            partial_parts(signature, &mut acc),
            vec![Part::Thinking { thinking: String::new(), signature: Some("sig-2".into()) }]
        );
    }

    /// A signature streamed on a function-call step stays with the call.
    #[test]
    fn sse_signature_on_a_function_call_step_belongs_to_the_call() {
        let mut acc = SseAccumulator::new();
        sse_event_to_chunk(function_call_start_event(3, "get_weather", "ktr5aysg"), &mut acc);
        let signature =
            delta_event(3, StepDelta::ThoughtSignature { signature: Some("call-sig".into()) });
        assert!(sse_event_to_chunk(signature, &mut acc).is_none());
        let chunk = sse_event_to_chunk(completed_event("v1_sig"), &mut acc).unwrap().unwrap();
        assert_eq!(
            chunk.content.unwrap().parts,
            vec![Part::FunctionCall {
                name: "get_weather".into(),
                args: serde_json::json!({}),
                id: Some("ktr5aysg".into()),
                thought_signature: Some("call-sig".into()),
            }]
        );
    }

    #[test]
    fn sse_completed_without_prior_id_uses_interaction_id_from_completed_event() {
        let mut acc = SseAccumulator::new();
        // No created/status events: id must come from the completed event.
        let chunk = sse_event_to_chunk(completed_event("v1_late"), &mut acc)
            .expect("completed event should emit a chunk")
            .expect("completed chunk should be Ok");
        assert_eq!(chunk.interaction_id.as_deref(), Some("v1_late"));
    }

    // ──────────────────────────────────────────────────────────────────
    // Tool-loop call-id round-trip (Property 5 / Requirement 6.4)
    // ──────────────────────────────────────────────────────────────────

    /// **Feature: gemini-interactions-runtime, Property 5: Round-trip call id**
    /// *For any* generated `function_call` id, after mapping to
    /// [`Part::FunctionCall`] and back through a `function_result`, the
    /// `call_id` equals the original.
    /// **Validates: Requirements 6.4**
    ///
    /// This exercises the network-free, deterministic half of the tool loop
    /// end-to-end through the conversion layer, mirroring ADK-Python's
    /// `requires_action` → tool exec → `function_result` cycle:
    ///
    /// 1. A `requires_action` [`Interaction`] carrying a
    ///    [`Step::FunctionCall`] with id `"call-abc"` is mapped by
    ///    [`to_llm_response`] to a [`Part::FunctionCall`] preserving that id
    ///    (this drives the runner's tool loop; the turn stays open).
    /// 2. After the agent runs the tool and appends a
    ///    [`Part::FunctionResponse`] carrying the *same* id, [`build_request`]
    ///    maps it to a [`Step::FunctionResult`] whose `call_id` equals the
    ///    original `function_call` id.
    ///
    /// The id therefore round-trips unchanged end-to-end:
    /// `function_call.id` → `Part::FunctionCall.id` → (tool runs) →
    /// `Part::FunctionResponse.id` → `function_result.call_id`.
    #[test]
    fn function_call_id_round_trips_through_tool_loop() {
        const CALL_ID: &str = "call-abc";
        let args = serde_json::json!({ "city": "Boston" });

        // ── Step 1: server emits requires_action with a function_call ──────
        let interaction = interaction_with(
            "v1_tool_loop",
            InteractionStatus::RequiresAction,
            vec![Step::FunctionCall {
                id: CALL_ID.to_string(),
                name: "get_weather".to_string(),
                arguments: args.clone(),
                signature: None,
            }],
        );

        let response = to_llm_response(&interaction);

        // requires_action keeps the turn open so the runner's tool loop runs.
        assert_eq!(response.finish_reason, None);
        assert!(!response.turn_complete);

        let content = response.content.expect("requires_action should carry a function call");
        assert_eq!(content.parts.len(), 1);
        let call_id = match &content.parts[0] {
            Part::FunctionCall { name, args: call_args, id, .. } => {
                assert_eq!(name, "get_weather");
                assert_eq!(call_args, &args);
                assert_eq!(
                    id.as_deref(),
                    Some(CALL_ID),
                    "the call id must survive to_llm_response"
                );
                id.clone().expect("function call must carry an id")
            }
            other => panic!("expected Part::FunctionCall, got {other:?}"),
        };

        // ── Step 2: the agent runs the tool and continues the conversation ─
        // The next-turn transcript carries the model's function call followed
        // by the function turn's response, both referencing the same id the
        // server assigned. Built statelessly (stateful=false) so the full
        // transcript maps to `Input::Steps`.
        let request = request_with(vec![
            Content::new("user").with_text("What's the weather in Boston?"),
            Content {
                role: "model".to_string(),
                parts: vec![Part::FunctionCall {
                    name: "get_weather".to_string(),
                    args: args.clone(),
                    id: Some(call_id.clone()),
                    thought_signature: None,
                }],
            },
            Content {
                role: "function".to_string(),
                parts: vec![Part::FunctionResponse {
                    function_response: FunctionResponseData::new(
                        "get_weather",
                        serde_json::json!({ "temp": 72, "conditions": "sunny" }),
                    ),
                    id: Some(call_id.clone()),
                    annotations: None,
                }],
            },
        ]);

        let built = build_request(&request, &model_target(), None, false, true)
            .expect("build_request should succeed");

        let steps = match built.input {
            Input::Steps(steps) => steps,
            other => panic!("expected Input::Steps for a multi-turn transcript, got {other:?}"),
        };

        // The function_call id round-tripped into the function_result call_id.
        let result_call_id = steps
            .iter()
            .find_map(|step| match step {
                Step::FunctionResult { call_id, .. } => Some(call_id.clone()),
                _ => None,
            })
            .expect("transcript should contain a function_result step");
        assert_eq!(
            result_call_id, call_id,
            "the function_result call_id must equal the original function_call id"
        );
        assert_eq!(result_call_id, CALL_ID);

        // And the originating function_call step kept the same id.
        let call_step_id = steps
            .iter()
            .find_map(|step| match step {
                Step::FunctionCall { id, .. } => Some(id.clone()),
                _ => None,
            })
            .expect("transcript should contain a function_call step");
        assert_eq!(call_step_id, CALL_ID, "the function_call step must keep the original id");
    }
}