yoagent 0.25.13

The agent loop for Rust: stream from 7 LLM protocols, run tools, loop until done. Native or wasm32 (Cloudflare Workers).
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
//! Google Generative AI (Gemini) provider.
//!
//! Uses the `streamGenerateContent` endpoint with SSE streaming.
//! API key is passed as a query parameter.
//!
//! # Prompt caching: implicit only, deliberately
//!
//! This provider sends no cache directives and ignores [`CacheStrategy`].
//! Gemini caches implicitly on its own, and the `cachedContentTokenCount` this
//! module reads back into [`Usage::cache_read`] reports the result of that
//! automatic behaviour — it is telemetry, not an acknowledgement of anything
//! the client asked for.
//!
//! Gemini's *explicit* caching is a separate resource with a different
//! lifecycle: you create a `CachedContent` object, receive a handle, reference
//! it by name on later requests, and manage its TTL and its own billing line.
//! That does not fit behind [`CacheStrategy`], which describes where to place
//! markers inside a single request. Wiring it here would mean either
//! misrepresenting a stateful resource as a per-request flag, or silently
//! creating server-side objects with a lifetime the caller cannot see.
//!
//! It is worth doing as its own API — with explicit create/reference/expire
//! surface — and it is not worth pretending the current enum can express it.
//! See yologdev/yoagent#123.

use super::traits::*;
use crate::types::*;
use futures::StreamExt;
use serde::Deserialize;
use tokio::sync::mpsc;
use tracing::{debug, warn};

pub struct GoogleProvider;

#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
impl StreamProvider for GoogleProvider {
    fn protocol(&self) -> Option<crate::provider::ApiProtocol> {
        Some(crate::provider::ApiProtocol::GoogleGenerativeAi)
    }

    async fn stream(
        &self,
        config: StreamConfig,
        tx: mpsc::UnboundedSender<StreamEvent>,
        cancel: tokio_util::sync::CancellationToken,
    ) -> Result<Message, ProviderError> {
        let model_config = config
            .model_config
            .as_ref()
            .ok_or_else(|| ProviderError::Other("ModelConfig required".into()))?;

        let base_url = &model_config.base_url;
        // The key goes in a header, never the URL: reqwest puts the URL in
        // its error text, which reaches logs, retry events and transcripts.
        let url = format!(
            "{}/v1beta/models/{}:streamGenerateContent?alt=sse",
            base_url, config.model
        );
        // Trimmed: the URL parser used to strip a trailing CR/LF (a key read
        // from a CRLF `.env`), and a header value rejects it. Skipped when the
        // caller sets `x-goog-api-key` in `ModelConfig.headers` (a header is
        // appended, not replaced, so it would be sent twice) or has no key.
        // An `Authorization` header is left alone: it may be a proxy's own.
        let key = config.api_key.trim();
        let user_key = model_config
            .headers
            .keys()
            .any(|k| k.eq_ignore_ascii_case("x-goog-api-key"));
        let key = if key.is_empty() || user_key {
            None
        } else {
            let mut value = reqwest::header::HeaderValue::from_str(key).map_err(|_| {
                ProviderError::Auth(
                    "the Gemini API key contains a character not allowed in an HTTP header \
                     (check GEMINI_API_KEY / GOOGLE_API_KEY, or the configured key)"
                        .into(),
                )
            })?;
            value.set_sensitive(true);
            Some(value)
        };

        let body = build_request_body(&config);
        debug!("Google GenAI request: model={}", config.model);

        let client = reqwest::Client::new();
        let mut request = client.post(&url).header("content-type", "application/json");
        if let Some(key) = key {
            request = request.header("x-goog-api-key", key);
        }

        for (k, v) in &model_config.headers {
            request = request.header(k, v);
        }

        // Google streams JSON chunks separated by newlines, not SSE.
        // With alt=sse, it does use SSE format.
        let response = request
            .json(&body)
            .send()
            .await
            .map_err(|e| ProviderError::Network(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status();
            let retry_after = parse_retry_after(response.headers());
            let body = response.text().await.unwrap_or_default();
            return Err(ProviderError::classify_with_retry_after(
                status.as_u16(),
                &format!("Google API error {}: {}", status, body),
                retry_after,
            ));
        }

        parse_stream(response, &config.model, &model_config.provider, tx, cancel).await
    }
}

/// Parse a Gemini `streamGenerateContent?alt=sse` response into the turn's
/// message. Shared with Vertex AI, which streams the same format.
pub(crate) async fn parse_stream(
    response: reqwest::Response,
    model: &str,
    provider: &str,
    tx: mpsc::UnboundedSender<StreamEvent>,
    cancel: tokio_util::sync::CancellationToken,
) -> Result<Message, ProviderError> {
    let mut content: Vec<Content> = Vec::new();
    let mut usage = Usage::default();
    let mut stop_reason = StopReason::Stop;
    let mut error_message: Option<String> = None;
    // Every complete Gemini response ends with a `finishReason` (or a
    // `promptFeedback.blockReason` when the prompt itself was blocked). A
    // stream that ends without one was cut off: an error, never a finished
    // (empty or truncated) answer.
    let mut finished = false;

    let _ = tx.send(StreamEvent::Start);

    // Parse SSE stream
    let mut stream = response.bytes_stream();
    let mut buffer = String::new();

    loop {
        tokio::select! {
            _ = cancel.cancelled() => {
                return Err(ProviderError::Cancelled);
            }
            chunk = stream.next() => {
                match chunk {
                    None if finished => break,
                    None => {
                        let err = ProviderError::Network(
                            "Gemini stream ended without a finishReason".into(),
                        );
                        warn!("Google stream error: {}", err);
                        return Err(err);
                    }
                    // The response was already complete (a finishReason
                    // arrived): keep it rather than retry and bill it twice.
                    Some(Err(e)) if finished => {
                        warn!("Google stream error after finishReason; keeping the response: {}", e);
                        break;
                    }
                    Some(Err(e)) => {
                        // Match the other providers: a transport failure is an
                        // error (and retryable), not a silently truncated turn.
                        let provider_err = ProviderError::Network(e.to_string());
                        warn!("Google stream error: {}", provider_err);
                        return Err(provider_err);
                    }
                    Some(Ok(bytes)) => {
                        buffer.push_str(&String::from_utf8_lossy(&bytes));

                        // Process complete SSE events (handle both \n\n and \r\n\r\n)
                        while let Some(data) = next_sse_data(&mut buffer) {
                            if data.is_empty() {
                                continue;
                            }

                            // Google reports mid-stream failures as
                            // {"error": {...}} payloads, which would otherwise
                            // deserialize into an empty chunk and vanish.
                            if is_error_payload(&data) {
                                let provider_err = classify_sse_error_event(&data);
                                warn!("Google in-stream error: {}", provider_err);
                                return Err(provider_err);
                            }

                            let chunk: GoogleChunk = match serde_json::from_str(&data) {
                                Ok(c) => c,
                                Err(e) => {
                                    warn!("Failed to parse Google chunk: {}", e);
                                    continue;
                                }
                            };

                            // The prompt itself was blocked: no candidates follow.
                            if let Some(reason) = chunk
                                .prompt_feedback
                                .as_ref()
                                .and_then(|f| f.block_reason.as_deref())
                            {
                                finished = true;
                                warn!("Gemini blocked the prompt (blockReason={})", reason);
                                error_message = Some(format!(
                                    "Prompt blocked by Gemini (blockReason: {})",
                                    reason
                                ));
                                stop_reason = StopReason::Refusal;
                            }

                            // Process candidates
                            for candidate in &chunk.candidates.unwrap_or_default() {
                                if let Some(c) = &candidate.content {
                                    for part in &c.parts {
                                        if let Some(text) = part_text(part) {
                                            if part.thought.unwrap_or(false) {
                                                // Thought summary part → Thinking content.
                                                let think_idx = content.iter().position(|c| matches!(c, Content::Thinking { .. }));
                                                let idx = match think_idx {
                                                    Some(i) => i,
                                                    None => {
                                                        content.push(Content::thinking(String::new()));
                                                        content.len() - 1
                                                    }
                                                };
                                                if let Some(Content::Thinking { thinking, .. }) = content.get_mut(idx) {
                                                    thinking.push_str(text);
                                                }
                                                let _ = tx.send(StreamEvent::ThinkingDelta {
                                                    content_index: idx,
                                                    delta: text.to_string(),
                                                });
                                                continue;
                                            }
                                            let text_idx = content.iter().position(|c| matches!(c, Content::Text { .. }));
                                            let idx = match text_idx {
                                                Some(i) => i,
                                                None => {
                                                    content.push(Content::Text { text: String::new() });
                                                    content.len() - 1
                                                }
                                            };
                                            if let Some(Content::Text { text: t }) = content.get_mut(idx) {
                                                t.push_str(text);
                                            }
                                            let _ = tx.send(StreamEvent::TextDelta {
                                                content_index: idx,
                                                delta: text.to_string(),
                                            });
                                        }
                                        if let Some(fc) = &part.function_call {
                                            let id = fc.id.clone().unwrap_or_else(|| format!("google-fc-{}", content.len()));
                                            let args = fc.args.clone().unwrap_or(serde_json::Value::Object(Default::default()));
                                            let metadata = part.thought_signature.as_ref().map(|sig| {
                                                serde_json::json!({"thought_signature": sig})
                                            });
                                            let idx = content.len();
                                            content.push(Content::ToolCall {
                                                id: id.clone(),
                                                name: fc.name.clone(),
                                                arguments: args,
                                                provider_metadata: metadata,
                                            });
                                            let _ = tx.send(StreamEvent::ToolCallStart {
                                                content_index: idx,
                                                id,
                                                name: fc.name.clone(),
                                            });
                                            let _ = tx.send(StreamEvent::ToolCallEnd { content_index: idx });
                                            stop_reason = StopReason::ToolUse;
                                        }
                                    }
                                }
                                if let Some(reason) = &candidate.finish_reason {
                                    finished = true;
                                    // Don't override ToolUse -- Gemini returns "STOP"
                                    // even when it emits function calls
                                    if stop_reason != StopReason::ToolUse {
                                        stop_reason = match reason.as_str() {
                                            "STOP" => StopReason::Stop,
                                            "MAX_TOKENS" | "RECITATION" => StopReason::Length,
                                            // A tool call Gemini could not produce or
                                            // was not allowed to make: a failed turn,
                                            // with Gemini's own explanation when given.
                                            "MALFORMED_FUNCTION_CALL" | "UNEXPECTED_TOOL_CALL"
                                            | "TOO_MANY_TOOL_CALLS" => {
                                                let detail = candidate
                                                    .finish_message
                                                    .as_deref()
                                                    .map(|m| format!(": {m}"))
                                                    .unwrap_or_default();
                                                warn!("Gemini tool call failed (finishReason={}){}", reason, detail);
                                                error_message = Some(format!(
                                                    "Gemini failed to make a valid tool call (finishReason: {reason}){detail}. Retrying the request usually works."
                                                ));
                                                StopReason::Error
                                            }
                                            "SAFETY" | "PROHIBITED_CONTENT" | "BLOCKLIST"
                                            | "SPII" | "IMAGE_SAFETY" => {
                                                warn!(
                                                    "Gemini blocked the response (finishReason={})",
                                                    reason
                                                );
                                                error_message = Some(format!(
                                                    "Response blocked by Gemini safety filters (finishReason: {})",
                                                    reason
                                                ));
                                                StopReason::Refusal
                                            }
                                            other => {
                                                warn!("Gemini finished with an unhandled finishReason={}", other);
                                                StopReason::Stop
                                            }
                                        };
                                    }
                                }
                            }

                            // Process usage
                            if let Some(u) = &chunk.usage_metadata {
                                // promptTokenCount includes cached tokens;
                                // keep `input` as the uncached remainder so
                                // downstream sums don't double-count.
                                usage.input = u
                                    .prompt_token_count
                                    .unwrap_or(0)
                                    .saturating_sub(u.cached_content_token_count.unwrap_or(0));
                                // Thinking tokens bill as output ("Output price
                                // (including thinking tokens)") but are counted
                                // apart, in `thoughtsTokenCount`.
                                usage.output = u
                                    .candidates_token_count
                                    .unwrap_or(0)
                                    .saturating_add(u.thoughts_token_count.unwrap_or(0));
                                usage.total_tokens = u.total_token_count.unwrap_or(0);
                                usage.cache_read = u.cached_content_token_count.unwrap_or(0);
                            }
                        }
                    }
                }
            }
        }
    }

    let message = Message::Assistant {
        content,
        stop_reason,
        model: model.to_string(),
        provider: provider.to_string(),
        usage,
        timestamp: now_ms(),
        error_message,
    };

    let _ = tx.send(StreamEvent::Done {
        message: message.clone(),
    });
    Ok(message)
}

/// Pop the next complete SSE event from `buffer` and return its `data:`
/// payload (empty string when the event carries no data line). Handles both
/// `\n\n` and `\r\n\r\n` event separators, splitting at whichever occurs
/// first. Returns `None` until a complete event is buffered. Only the first
/// `data:` line of an event is returned.
fn next_sse_data(buffer: &mut String) -> Option<String> {
    let lf = buffer.find("\n\n");
    let crlf = buffer.find("\r\n\r\n");
    let (pos, sep_len) = match (lf, crlf) {
        (Some(l), Some(c)) if c < l => (c, 4),
        (Some(l), _) => (l, 2),
        (None, Some(c)) => (c, 4),
        (None, None) => return None,
    };
    let event_str = buffer[..pos].to_string();
    *buffer = buffer[pos + sep_len..].to_string();
    let data = event_str
        .lines()
        .map(|l| l.trim_end_matches('\r'))
        .find(|l| l.starts_with("data: "))
        .map(|l| l[6..].to_string())
        .unwrap_or_default();
    Some(data)
}

/// Whether an SSE data payload is a Google error envelope
/// (`{"error": {...}}`) rather than a content chunk.
fn is_error_payload(data: &str) -> bool {
    serde_json::from_str::<serde_json::Value>(data)
        .map(|v| v.get("error").is_some())
        .unwrap_or(false)
}

/// Non-empty text of a part. Gemini streams empty text parts while thinking;
/// those must be skipped.
fn part_text(part: &GooglePart) -> Option<&str> {
    part.text.as_deref().filter(|t| !t.is_empty())
}

/// Token budget for Gemini 2.x's `thinkingConfig.thinkingBudget` per level.
/// Only reached through [`gemini_thinking_config`], which Vertex AI shares.
pub(crate) fn gemini_thinking_budget(level: ThinkingLevel) -> u32 {
    match level {
        ThinkingLevel::Off => 0,
        ThinkingLevel::Minimal | ThinkingLevel::Low => 1024,
        ThinkingLevel::Medium => 8192,
        // Clamped: 24,576 is the documented thinkingBudget maximum of Gemini
        // 2.5 Flash and Flash-Lite; 2.5 Pro's is 32,768
        // (cloud.google.com/vertex-ai/generative-ai/docs/thinking). There is
        // no per-model table here, so the crate stays within the smallest
        // documented maximum rather than send an out-of-range budget.
        ThinkingLevel::High | ThinkingLevel::XHigh | ThinkingLevel::Max => 24576,
    }
}

/// Which `thinkingConfig` field a Gemini model takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GeminiThinkingParam {
    /// `thinkingBudget` — Gemini 2.x, and any id the version rule cannot read
    /// (Gemini 3 still accepts a budget for backward compatibility).
    Budget,
    /// `thinkingLevel` — Gemini 3 and later, restricted to the rungs the
    /// model documents as accepted.
    Level(GeminiRungs),
    /// No `thinkingConfig` at all — Gemini 3+ TTS models, which neither
    /// thinking guide lists as supporting thinking.
    Omit,
}

/// The `thinkingLevel` values a Gemini 3+ model accepts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GeminiRungs {
    /// `MINIMAL`, `LOW`, `MEDIUM`, `HIGH` — 3.6 / 3.5 Flash, 3.x Flash-Lite,
    /// 3 Flash.
    All,
    /// `LOW`, `MEDIUM`, `HIGH` — 3.8 / 3.7 Flash, 3.1 Pro, and every 3.x+
    /// model not documented as accepting `MINIMAL`.
    NoMinimal,
    /// `MINIMAL`, `HIGH` — 3.1 Flash Image and 3.1 Flash-Lite Image.
    MinimalHigh,
    /// `HIGH` only — 3 Pro Image.
    HighOnly,
}

/// Reads the Gemini generation off a model id.
///
/// Google's rule is version-based: `thinkingLevel` is "Recommended for Gemini
/// 3 or later models. Use with earlier models results in an error." (REST
/// reference, `ThinkingConfig`). So the version number decides, not a model
/// list. Accepts bare ids (`gemini-3.8-flash`), `models/…` names, Vertex
/// resource paths (`projects/…/publishers/google/models/gemini-3.1-pro-preview`)
/// and `@version` suffixes.
///
/// `MINIMAL` per the Gemini API thinking guide's level table: rejected by 3.8
/// and 3.7 Flash, not supported by 3.1 Pro; accepted by 3.6 / 3.5 Flash, every
/// 3.x Flash-Lite and 3 Flash. Unlisted 3.x+ models (Pro variants, future
/// Flash releases) are treated as not accepting it, so the worst case is
/// `LOW` where `MINIMAL` would have worked, never a 400.
///
/// Image models, per the Vertex AI thinking table ("Supported thinking_level
/// values"): Gemini 3.1 Flash Image and 3.1 Flash-Lite Image take
/// "MINIMAL , HIGH"; Gemini 3 Pro Image takes "HIGH" only. Every 3.x+
/// `-image` id is read that way (`-pro…-image` → `HIGH` only, any other →
/// `MINIMAL`/`HIGH`).
///
/// TTS models (`gemini-3.8-flash-tts`, `gemini-3.8-flash-lite-tts`,
/// `gemini-3.1-flash-tts-preview`) appear in neither guide's list of models
/// that support thinking, so they get no `thinkingConfig`.
///
/// Aliases: `gemini-flash-latest` (3.5 Flash since 2026-05-19) and
/// `gemini-pro-latest` (3 Pro preview since 2026-01-21) point at Gemini 3
/// per the API changelog; they are hot-swapped, so `MINIMAL` is not assumed.
/// `gemini-flash-lite-latest` has no documented target, so it keeps the
/// budget, which every generation accepts.
fn gemini_thinking_param(model: &str) -> GeminiThinkingParam {
    let name = model.rsplit('/').next().unwrap_or(model);
    let name = name.split('@').next().unwrap_or(name).to_ascii_lowercase();
    let Some(rest) = name.strip_prefix("gemini-") else {
        return GeminiThinkingParam::Budget;
    };
    if rest == "flash-latest" || rest == "pro-latest" {
        return GeminiThinkingParam::Level(GeminiRungs::NoMinimal);
    }

    let major_len = rest.bytes().take_while(u8::is_ascii_digit).count();
    let Ok(major) = rest[..major_len].parse::<u32>() else {
        return GeminiThinkingParam::Budget;
    };
    if major < 3 {
        return GeminiThinkingParam::Budget;
    }
    let after_major = &rest[major_len..];
    let (minor, variant) = match after_major.strip_prefix('.') {
        Some(tail) => {
            let len = tail.bytes().take_while(u8::is_ascii_digit).count();
            (tail[..len].parse::<u32>().ok(), &tail[len..])
        }
        None => (Some(0), after_major),
    };

    if variant.contains("-tts") {
        return GeminiThinkingParam::Omit;
    }
    let rungs = if variant.contains("-image") {
        if variant.starts_with("-pro") {
            GeminiRungs::HighOnly
        } else {
            GeminiRungs::MinimalHigh
        }
    } else if major == 3
        && (variant.starts_with("-flash-lite")
            || (variant.starts_with("-flash") && matches!(minor, Some(0 | 5 | 6))))
    {
        GeminiRungs::All
    } else {
        GeminiRungs::NoMinimal
    };
    GeminiThinkingParam::Level(rungs)
}

/// The `thinkingLevel` string for a non-`Off` [`ThinkingLevel`] on a Gemini
/// 3+ model: the requested rung, or the nearest one the model accepts.
///
/// `Minimal` → `LOW` where `MINIMAL` is not accepted. On the `MINIMAL`/`HIGH`
/// image models, `Low` goes down to `MINIMAL` (both are the "minimize latency
/// and cost" end) and `Medium` goes up to `HIGH` (a request for some thinking
/// gets thinking). `Off` never reaches here in practice: it omits
/// `thinkingConfig`, and is mapped like `Minimal` only to keep the match total.
fn gemini_thinking_level(level: ThinkingLevel, rungs: GeminiRungs) -> &'static str {
    use GeminiRungs::*;
    use ThinkingLevel::*;
    match (rungs, level) {
        (HighOnly, _) => "HIGH",
        (MinimalHigh, Off | Minimal | Low) => "MINIMAL",
        (MinimalHigh, _) => "HIGH",
        (All, Off | Minimal) => "MINIMAL",
        (_, Off | Minimal | Low) => "LOW",
        (_, Medium) => "MEDIUM",
        (_, High | XHigh | Max) => "HIGH",
    }
}

/// The `generationConfig.thinkingConfig` object for a request, or `None` to
/// omit it. Shared by the Gemini API and Vertex AI providers so the two
/// cannot drift.
///
/// Exactly one of `thinkingLevel` / `thinkingBudget` is ever sent: Gemini 3
/// rejects a request carrying both, and pre-3 models reject `thinkingLevel`.
/// The choice comes from [`GoogleCompat::thinking_level`] when set, else
/// from the model id (see `gemini_thinking_param`).
///
/// `ThinkingLevel::Off` omits `thinkingConfig` on every model. On Gemini 3
/// that does **not** disable thinking — the model runs at its own default
/// level (3.1 Pro `HIGH`, 3.5–3.8 Flash `MEDIUM`, Flash-Lite `MINIMAL`);
/// `ThinkingLevel::Minimal` is the way to ask for the least thinking.
///
/// [`GoogleCompat::thinking_level`]: super::GoogleCompat::thinking_level
pub(crate) fn gemini_thinking_config(config: &StreamConfig) -> Option<serde_json::Value> {
    if config.thinking_level == ThinkingLevel::Off {
        return None;
    }
    let forced = config
        .model_config
        .as_ref()
        .and_then(|mc| mc.google.as_ref())
        .and_then(|g| g.thinking_level);
    let param = match (forced, gemini_thinking_param(&config.model)) {
        (Some(false), _) => GeminiThinkingParam::Budget,
        (Some(true), GeminiThinkingParam::Budget) => {
            GeminiThinkingParam::Level(GeminiRungs::NoMinimal)
        }
        (_, inferred) => inferred,
    };

    match param {
        // Gemini 2.x: the payload this crate has always sent — budget scales
        // with the level and includeThoughts streams thought summaries back
        // as thought parts.
        GeminiThinkingParam::Budget => Some(serde_json::json!({
            "thinkingBudget": gemini_thinking_budget(config.thinking_level),
            "includeThoughts": true,
        })),
        GeminiThinkingParam::Level(rungs) => Some(serde_json::json!({
            "thinkingLevel": gemini_thinking_level(config.thinking_level, rungs),
            "includeThoughts": true,
        })),
        GeminiThinkingParam::Omit => None,
    }
}

/// Each user content's `functionResponse` parts first, then its other parts,
/// each group in its order. A merged turn of tool results would otherwise
/// interleave a result's images between the responses (`response A, image
/// A, response B`); Gemini matches responses to the calls by count and
/// position, and images among them are a reported cause of its "number of
/// function response parts" 400.
pub(crate) fn function_responses_first(
    mut contents: Vec<serde_json::Value>,
) -> Vec<serde_json::Value> {
    for content in &mut contents {
        if let Some(parts) = content
            .get_mut("parts")
            .and_then(serde_json::Value::as_array_mut)
        {
            let (mut responses, rest): (Vec<_>, Vec<_>) = std::mem::take(parts)
                .into_iter()
                .partition(|part| part.get("functionResponse").is_some());
            responses.extend(rest);
            *parts = responses;
        }
    }
    contents
}

fn build_request_body(config: &StreamConfig) -> serde_json::Value {
    let mut contents: Vec<serde_json::Value> = Vec::new();

    for msg in &config.messages {
        match msg {
            Message::User { content, .. } => {
                let parts = content_to_google_parts(content);
                contents.push(serde_json::json!({
                    "role": "user",
                    "parts": parts,
                }));
            }
            Message::Assistant { content, .. } => {
                let parts = content_to_google_parts(content);
                contents.push(serde_json::json!({
                    "role": "model",
                    "parts": parts,
                }));
            }
            Message::ToolResult {
                tool_call_id,
                tool_name,
                content,
                ..
            } => {
                let text = super::tool_result_text(content);

                let mut fr = serde_json::json!({
                    "name": tool_name,
                    "response": {"result": text},
                });
                if !tool_call_id.is_empty() && !tool_call_id.starts_with("google-fc-") {
                    fr["id"] = serde_json::json!(tool_call_id);
                }
                let mut parts = vec![serde_json::json!({"functionResponse": fr})];

                // Append image parts if present
                for c in content {
                    if let Content::Image { data, mime_type } = c {
                        parts.push(serde_json::json!({
                            "inlineData": {"mimeType": mime_type, "data": data},
                        }));
                    }
                }

                contents.push(serde_json::json!({
                    "role": "user",
                    "parts": parts,
                }));
            }
        }
    }

    // Gemini wants a turn's function responses in one content, matching its
    // function calls — the responses first, then any images and text.
    let contents = function_responses_first(super::merge_same_role(contents, "parts"));
    let mut body = serde_json::json!({
        "contents": contents,
    });

    if !config.system_prompt.is_empty() {
        body["systemInstruction"] = serde_json::json!({
            "parts": [{"text": config.system_prompt}],
        });
    }

    let mut generation_config = serde_json::json!({});
    if let Some(max) = config.max_tokens {
        generation_config["maxOutputTokens"] = serde_json::json!(max);
    }
    if let Some(temp) = config.temperature {
        generation_config["temperature"] = serde_json::json!(temp);
    }
    // Structured outputs: native responseSchema (Gemini's OpenAPI-style
    // schema dialect — pass the caller's schema through as given).
    if let Some(schema) = &config.output_schema {
        generation_config["responseMimeType"] = serde_json::json!("application/json");
        generation_config["responseSchema"] = schema.schema.clone();
    }

    // Thinking: thinkingLevel on Gemini 3+, thinkingBudget on 2.x.
    if let Some(thinking) = gemini_thinking_config(config) {
        generation_config["thinkingConfig"] = thinking;
    }

    if generation_config != serde_json::json!({}) {
        body["generationConfig"] = generation_config;
    }

    if !config.tools.is_empty() {
        let declarations: Vec<serde_json::Value> = config
            .tools
            .iter()
            .map(|t| {
                serde_json::json!({
                    "name": t.name,
                    "description": t.description,
                    "parameters": t.parameters,
                })
            })
            .collect();
        body["tools"] = serde_json::json!([{
            "functionDeclarations": declarations,
        }]);
    }

    body
}

fn content_to_google_parts(content: &[Content]) -> Vec<serde_json::Value> {
    content
        .iter()
        .filter(|c| !matches!(c, Content::Text { text } if text.is_empty()))
        .filter_map(|c| match c {
            Content::Text { text } => Some(serde_json::json!({"text": text})),
            Content::Image { data, mime_type } => Some(serde_json::json!({
                "inlineData": {"mimeType": mime_type, "data": data},
            })),
            Content::ToolCall {
                id,
                name,
                arguments,
                provider_metadata,
            } => {
                let mut fc = serde_json::json!({"name": name, "args": arguments});
                if !id.is_empty() && !id.starts_with("google-fc-") {
                    fc["id"] = serde_json::json!(id);
                }
                let mut part = serde_json::json!({"functionCall": fc});
                if let Some(sig) = provider_metadata
                    .as_ref()
                    .and_then(|m| m.get("thought_signature"))
                    .and_then(|v| v.as_str())
                {
                    part["thoughtSignature"] = serde_json::json!(sig);
                }
                Some(part)
            }
            Content::Thinking { .. } => None,
        })
        .collect()
}

// Google API response types
#[derive(Deserialize)]
struct GoogleChunk {
    #[serde(default)]
    candidates: Option<Vec<GoogleCandidate>>,
    #[serde(default, rename = "promptFeedback")]
    prompt_feedback: Option<GooglePromptFeedback>,
    #[serde(default, rename = "usageMetadata")]
    usage_metadata: Option<GoogleUsageMetadata>,
}

#[derive(Deserialize)]
struct GooglePromptFeedback {
    #[serde(default, rename = "blockReason")]
    block_reason: Option<String>,
}

#[derive(Deserialize)]
struct GoogleCandidate {
    #[serde(default)]
    content: Option<GoogleContent>,
    #[serde(default, rename = "finishReason")]
    finish_reason: Option<String>,
    /// Gemini's explanation for some finish reasons (a malformed call).
    #[serde(default, rename = "finishMessage")]
    finish_message: Option<String>,
}

#[derive(Deserialize)]
struct GoogleContent {
    #[serde(default)]
    parts: Vec<GooglePart>,
}

#[derive(Deserialize)]
struct GooglePart {
    #[serde(default)]
    text: Option<String>,
    /// True when this part is a thought summary (thinkingConfig.includeThoughts).
    #[serde(default)]
    thought: Option<bool>,
    #[serde(default, rename = "functionCall")]
    function_call: Option<GoogleFunctionCall>,
    #[serde(default, rename = "thoughtSignature")]
    thought_signature: Option<String>,
}

#[derive(Deserialize)]
struct GoogleFunctionCall {
    name: String,
    #[serde(default)]
    args: Option<serde_json::Value>,
    #[serde(default)]
    id: Option<String>,
}

#[derive(Deserialize)]
struct GoogleUsageMetadata {
    #[serde(default, rename = "promptTokenCount")]
    prompt_token_count: Option<u64>,
    #[serde(default, rename = "candidatesTokenCount")]
    candidates_token_count: Option<u64>,
    #[serde(default, rename = "totalTokenCount")]
    total_token_count: Option<u64>,
    #[serde(default, rename = "cachedContentTokenCount")]
    cached_content_token_count: Option<u64>,
    #[serde(default, rename = "thoughtsTokenCount")]
    thoughts_token_count: Option<u64>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::provider::{GoogleCompat, ModelConfig};

    /// A model turn whose only content is thinking (not replayed), or the
    /// loop's error message (one empty text block), is not sent as an empty
    /// content (#369).
    #[test]
    fn an_empty_model_turn_is_not_sent() {
        for turn in [
            vec![Content::thinking("thought")],
            vec![Content::Text {
                text: String::new(),
            }],
        ] {
            let mut config = StreamConfig::new("gemini-2.5-pro", "k");
            config.messages = vec![
                Message::user("first"),
                Message::assistant(turn, StopReason::Error, "m", "google", Usage::default()),
                Message::user("again"),
            ];
            let body = build_request_body(&config);
            assert_eq!(
                body["contents"],
                serde_json::json!([{"role": "user", "parts": [{"text": "first"}, {"text": "again"}]}])
            );
        }
    }

    /// A parallel tool call's results go back as one user turn, with the
    /// steering message after them, so roles alternate (#223).
    #[test]
    fn parallel_tool_results_go_back_in_one_turn() {
        let mut config = StreamConfig::new("gemini-2.5-pro", "k");
        config.messages = crate::provider::parallel_tool_conversation();
        let body = build_request_body(&config);
        let contents = body["contents"].as_array().unwrap();
        let roles: Vec<&str> = contents
            .iter()
            .map(|c| c["role"].as_str().unwrap())
            .collect();
        assert_eq!(roles, ["user", "model", "user"], "{body}");
        let parts = contents[2]["parts"].as_array().unwrap();
        assert_eq!(parts[0]["functionResponse"]["name"], "read_file");
        assert_eq!(
            parts[0]["functionResponse"]["response"]["result"],
            "fn a() {}"
        );
        assert_eq!(
            parts[1]["functionResponse"]["response"]["result"],
            "fn b() {}"
        );
        assert_eq!(parts[2]["text"], "also check c.rs");
        assert_eq!(parts.len(), 3);
    }

    /// A result with an image: every function response first, in call
    /// order, then the image and the text that followed.
    #[test]
    fn merged_tool_results_put_the_function_responses_first() {
        let mut config = StreamConfig::new("gemini-2.5-pro", "k");
        config.messages = crate::provider::parallel_tool_conversation();
        if let Message::ToolResult { content, .. } = &mut config.messages[2] {
            content.push(Content::Image {
                data: "AAAA".into(),
                mime_type: "image/png".into(),
            });
        }
        let body = build_request_body(&config);
        let parts = body["contents"][2]["parts"].as_array().unwrap();
        assert_eq!(parts.len(), 4, "{body}");
        assert_eq!(
            parts[0]["functionResponse"]["response"]["result"],
            "fn a() {}"
        );
        assert_eq!(
            parts[1]["functionResponse"]["response"]["result"],
            "fn b() {}"
        );
        assert_eq!(parts[2]["inlineData"]["data"], "AAAA");
        assert_eq!(parts[3]["text"], "also check c.rs");
    }

    #[test]
    fn thinking_blocks_are_dropped_on_replay() {
        // Gemini does not accept echoed thought summaries; signatures ride on
        // functionCall parts instead. Pin the drop so it stays deliberate.
        let mut config = StreamConfig::new("gemini-2.5-pro", "k");
        config.messages = vec![
            Message::user("go"),
            Message::assistant(
                vec![
                    Content::thinking("thought"),
                    Content::Text {
                        text: "answer".into(),
                    },
                ],
                StopReason::Stop,
                "m",
                "google",
                Usage::default(),
            ),
        ];
        let body = build_request_body(&config);
        let parts = body["contents"][1]["parts"].as_array().unwrap();
        assert_eq!(parts.len(), 1, "only the text part is replayed");
        assert_eq!(parts[0]["text"], "answer");
    }

    #[test]
    fn thinking_level_sets_thinking_config() {
        let config = StreamConfig {
            model: "gemini-2.5-pro".into(),
            system_prompt: "".into(),
            messages: vec![Message::user("hi")],
            tools: vec![],
            thinking_level: ThinkingLevel::Medium,
            api_key: "test".into(),
            max_tokens: None,
            temperature: None,
            model_config: None,
            cache_config: CacheConfig::default(),
            output_schema: None,
        };
        let body = build_request_body(&config);
        assert_eq!(
            body["generationConfig"]["thinkingConfig"]["thinkingBudget"],
            8192
        );
        assert_eq!(
            body["generationConfig"]["thinkingConfig"]["includeThoughts"],
            true
        );
    }

    #[test]
    fn thinking_off_omits_thinking_config() {
        let config = StreamConfig {
            model: "gemini-2.5-pro".into(),
            system_prompt: "".into(),
            messages: vec![Message::user("hi")],
            tools: vec![],
            thinking_level: ThinkingLevel::Off,
            api_key: "test".into(),
            max_tokens: None,
            temperature: None,
            model_config: None,
            cache_config: CacheConfig::default(),
            output_schema: None,
        };
        let body = build_request_body(&config);
        assert!(body["generationConfig"]["thinkingConfig"].is_null());
    }

    #[test]
    fn structured_output_sets_response_schema() {
        let config = StreamConfig {
            model: "gemini-2.5-pro".into(),
            system_prompt: "".into(),
            messages: vec![Message::user("Hello")],
            tools: vec![],
            thinking_level: ThinkingLevel::Off,
            api_key: "test".into(),
            max_tokens: None,
            temperature: None,
            model_config: None,
            cache_config: CacheConfig::default(),
            output_schema: Some(crate::provider::OutputSchema::new(
                "structured_output",
                serde_json::json!({"type": "object", "properties": {"x": {"type": "number"}}}),
            )),
        };
        let body = build_request_body(&config);
        assert_eq!(
            body["generationConfig"]["responseMimeType"],
            "application/json"
        );
        assert_eq!(
            body["generationConfig"]["responseSchema"]["properties"]["x"]["type"],
            "number"
        );
    }

    #[test]
    fn test_build_google_request() {
        let config = StreamConfig {
            model: "gemini-2.0-flash".into(),
            system_prompt: "Be helpful".into(),
            messages: vec![Message::user("Hello")],
            tools: vec![],
            thinking_level: ThinkingLevel::Off,
            api_key: "test".into(),
            max_tokens: Some(1024),
            temperature: Some(0.7),
            model_config: None,
            cache_config: CacheConfig::default(),
            output_schema: None,
        };

        let body = build_request_body(&config);
        assert!(body["contents"].is_array());
        assert_eq!(body["contents"][0]["role"], "user");
        assert!(body["systemInstruction"].is_object());
        assert_eq!(body["generationConfig"]["maxOutputTokens"], 1024);
        let temp = body["generationConfig"]["temperature"].as_f64().unwrap();
        assert!((temp - 0.7).abs() < 0.01);
    }

    #[test]
    fn test_content_to_google_parts_text() {
        let content = vec![Content::Text {
            text: "hello".into(),
        }];
        let parts = content_to_google_parts(&content);
        assert_eq!(parts.len(), 1);
        assert_eq!(parts[0]["text"], "hello");
    }

    #[test]
    fn test_content_to_google_parts_filters_empty_text() {
        let content = vec![
            Content::Text { text: "".into() },
            Content::Text {
                text: "hello".into(),
            },
            Content::Text { text: "".into() },
        ];
        let parts = content_to_google_parts(&content);
        assert_eq!(parts.len(), 1);
        assert_eq!(parts[0]["text"], "hello");
    }

    #[test]
    fn test_content_to_google_parts_tool_call() {
        let content = vec![Content::ToolCall {
            id: "tc-1".into(),
            name: "bash".into(),
            arguments: serde_json::json!({"command": "ls"}),
            provider_metadata: None,
        }];
        let parts = content_to_google_parts(&content);
        assert_eq!(parts[0]["functionCall"]["name"], "bash");
    }

    #[test]
    fn test_parse_chunk_with_function_call_and_thought_signature() {
        let data = r#"{"candidates": [{"content": {"parts": [{"functionCall": {"name": "bash", "args": {"command": "echo hi"}, "id": "abc123"}, "thoughtSignature": "SIG_DATA"}], "role": "model"}, "finishReason": "STOP", "index": 0}], "usageMetadata": {"promptTokenCount": 10, "candidatesTokenCount": 5, "totalTokenCount": 15}}"#;

        let chunk: GoogleChunk = serde_json::from_str(data).unwrap();
        let candidates = chunk.candidates.unwrap();
        assert_eq!(candidates.len(), 1);

        let parts = &candidates[0].content.as_ref().unwrap().parts;
        assert_eq!(parts.len(), 1);

        let fc = parts[0].function_call.as_ref().unwrap();
        assert_eq!(fc.name, "bash");
        assert_eq!(fc.id.as_deref(), Some("abc123"));
        assert_eq!(fc.args.as_ref().unwrap()["command"], "echo hi");

        assert_eq!(parts[0].thought_signature.as_deref(), Some("SIG_DATA"));
    }

    #[test]
    fn test_parse_chunk_with_empty_text() {
        // Gemini sends empty text parts during thinking -- part_text (used by
        // the streaming loop) must skip them and keep non-empty ones.
        let data = r#"{"candidates": [{"content": {"parts": [{"text": ""}, {"text": "Hello"}], "role": "model"}, "index": 0}]}"#;

        let chunk: GoogleChunk = serde_json::from_str(data).unwrap();
        let candidates = chunk.candidates.unwrap();
        let parts = &candidates[0].content.as_ref().unwrap().parts;
        assert_eq!(part_text(&parts[0]), None, "empty text parts are skipped");
        assert_eq!(part_text(&parts[1]), Some("Hello"));
    }

    #[test]
    fn test_parse_chunk_with_crlf_sse() {
        // Full pipeline: next_sse_data (the production splitter) on a CRLF
        // stream, then chunk parsing.
        let mut buf = "data: {\"candidates\": [{\"content\": {\"parts\": [{\"text\": \"Blue\"}], \"role\": \"model\"}, \"finishReason\": \"STOP\", \"index\": 0}]}\r\n\r\n".to_string();

        let data = next_sse_data(&mut buf).expect("complete CRLF event");
        assert!(buf.is_empty(), "event consumed from buffer");
        assert_eq!(next_sse_data(&mut buf), None);

        let chunk: GoogleChunk = serde_json::from_str(&data).unwrap();
        let candidates = chunk.candidates.unwrap();
        let text = &candidates[0].content.as_ref().unwrap().parts[0].text;
        assert_eq!(text.as_deref(), Some("Blue"));
    }

    #[test]
    fn test_next_sse_data_partial_events_stay_buffered() {
        let mut buf = "data: {\"a\":1}\n\ndata: partial".to_string();
        assert_eq!(next_sse_data(&mut buf).as_deref(), Some("{\"a\":1}"));
        assert_eq!(next_sse_data(&mut buf), None, "incomplete event waits");
        assert_eq!(buf, "data: partial");
        buf.push_str("\n\n");
        assert_eq!(next_sse_data(&mut buf).as_deref(), Some("partial"));
    }

    #[test]
    fn test_next_sse_data_consumes_events_without_data_lines() {
        // SSE comments/keepalives and leading separators must be CONSUMED
        // (returning Some("")), never None — returning None would wedge the
        // buffer and drop every subsequent event.
        let mut buf = ": keepalive\n\n\n\ndata: x\n\n".to_string();
        assert_eq!(next_sse_data(&mut buf).as_deref(), Some(""));
        assert_eq!(next_sse_data(&mut buf).as_deref(), Some(""));
        assert_eq!(next_sse_data(&mut buf).as_deref(), Some("x"));
        assert_eq!(next_sse_data(&mut buf), None);
    }

    #[test]
    fn test_is_error_payload() {
        assert!(is_error_payload(
            r#"{"error": {"code": 429, "status": "RESOURCE_EXHAUSTED"}}"#
        ));
        assert!(!is_error_payload(r#"{"candidates": []}"#));
        assert!(!is_error_payload("not json"));
    }

    #[test]
    fn test_next_sse_data_splits_earliest_separator_first() {
        // A CRLF-separated event earlier in the buffer must split before a
        // later LF separator (the old inline logic preferred the LF match and
        // merged the two events).
        let mut buf = "data: one\r\n\r\ndata: two\n\n".to_string();
        assert_eq!(next_sse_data(&mut buf).as_deref(), Some("one"));
        assert_eq!(next_sse_data(&mut buf).as_deref(), Some("two"));
        assert_eq!(next_sse_data(&mut buf), None);
    }

    #[test]
    fn test_thought_signature_round_trip() {
        let content = vec![Content::ToolCall {
            id: "abc123".into(),
            name: "bash".into(),
            arguments: serde_json::json!({"command": "echo hi"}),
            provider_metadata: Some(serde_json::json!({"thought_signature": "SIG_DATA"})),
        }];

        let parts = content_to_google_parts(&content);
        assert_eq!(parts.len(), 1);

        assert_eq!(parts[0]["functionCall"]["name"], "bash");
        assert_eq!(parts[0]["functionCall"]["id"], "abc123");
        assert_eq!(parts[0]["functionCall"]["args"]["command"], "echo hi");
        assert_eq!(parts[0]["thoughtSignature"], "SIG_DATA");
    }

    #[test]
    fn test_tool_call_without_thought_signature() {
        // Synthetic IDs (google-fc-*) should not be sent to Gemini
        let content = vec![Content::ToolCall {
            id: "google-fc-0".into(),
            name: "bash".into(),
            arguments: serde_json::json!({"command": "ls"}),
            provider_metadata: None,
        }];

        let parts = content_to_google_parts(&content);
        assert!(parts[0]["functionCall"].get("id").is_none());
        assert!(parts[0].get("thoughtSignature").is_none());
    }

    #[test]
    fn test_function_response_includes_id() {
        let config = StreamConfig {
            model: "gemini-2.5-flash".into(),
            system_prompt: "".into(),
            messages: vec![
                Message::Assistant {
                    content: vec![Content::ToolCall {
                        id: "abc123".into(),
                        name: "bash".into(),
                        arguments: serde_json::json!({"command": "echo hi"}),
                        provider_metadata: None,
                    }],
                    stop_reason: StopReason::ToolUse,
                    model: "test".into(),
                    provider: "test".into(),
                    usage: Usage::default(),
                    timestamp: 0,
                    error_message: None,
                },
                Message::ToolResult {
                    tool_call_id: "abc123".into(),
                    tool_name: "bash".into(),
                    content: vec![Content::Text { text: "hi".into() }],
                    is_error: false,
                    timestamp: 0,
                },
            ],
            tools: vec![],
            thinking_level: ThinkingLevel::Off,
            api_key: "test".into(),
            max_tokens: None,
            temperature: None,
            model_config: None,
            cache_config: CacheConfig::default(),
            output_schema: None,
        };

        let body = build_request_body(&config);
        let msgs = body["contents"].as_array().unwrap();
        let tool_result = &msgs[1]["parts"][0]["functionResponse"];
        assert_eq!(tool_result["name"], "bash");
        assert_eq!(tool_result["id"], "abc123");
        assert_eq!(tool_result["response"]["result"], "hi");
    }

    #[test]
    fn test_function_response_synthetic_id_omitted() {
        let config = StreamConfig {
            model: "gemini-2.5-flash".into(),
            system_prompt: "".into(),
            messages: vec![
                Message::Assistant {
                    content: vec![Content::ToolCall {
                        id: "google-fc-0".into(),
                        name: "bash".into(),
                        arguments: serde_json::json!({"command": "ls"}),
                        provider_metadata: None,
                    }],
                    stop_reason: StopReason::ToolUse,
                    model: "test".into(),
                    provider: "test".into(),
                    usage: Usage::default(),
                    timestamp: 0,
                    error_message: None,
                },
                Message::ToolResult {
                    tool_call_id: "google-fc-0".into(),
                    tool_name: "bash".into(),
                    content: vec![Content::Text {
                        text: "output".into(),
                    }],
                    is_error: false,
                    timestamp: 0,
                },
            ],
            tools: vec![],
            thinking_level: ThinkingLevel::Off,
            api_key: "test".into(),
            max_tokens: None,
            temperature: None,
            model_config: None,
            cache_config: CacheConfig::default(),
            output_schema: None,
        };

        let body = build_request_body(&config);
        let msgs = body["contents"].as_array().unwrap();
        let tool_result = &msgs[1]["parts"][0]["functionResponse"];
        assert!(
            tool_result.get("id").is_none(),
            "Synthetic ID should not be included"
        );
    }

    // --- thinkingLevel (Gemini 3+) vs thinkingBudget (2.x) -----------------

    const ALL_LEVELS: [ThinkingLevel; 7] = [
        ThinkingLevel::Off,
        ThinkingLevel::Minimal,
        ThinkingLevel::Low,
        ThinkingLevel::Medium,
        ThinkingLevel::High,
        ThinkingLevel::XHigh,
        ThinkingLevel::Max,
    ];

    fn thinking_config(model: &str, level: ThinkingLevel) -> serde_json::Value {
        let mut config = StreamConfig::new(model, "k");
        config.messages = vec![Message::user("hi")];
        config.thinking_level = level;
        build_request_body(&config)["generationConfig"]["thinkingConfig"].clone()
    }

    fn thinking_config_with(
        model: &str,
        level: ThinkingLevel,
        compat: GoogleCompat,
    ) -> serde_json::Value {
        let mut config = StreamConfig::new(model, "k");
        config.messages = vec![Message::user("hi")];
        config.thinking_level = level;
        let mut mc = ModelConfig::google(model, "test");
        mc.google = Some(compat);
        config.model_config = Some(mc);
        build_request_body(&config)["generationConfig"]["thinkingConfig"].clone()
    }

    /// The payload every release before this one sent, for every level.
    fn legacy_budget_payload(level: ThinkingLevel) -> serde_json::Value {
        let budget = match level {
            ThinkingLevel::Off => return serde_json::Value::Null,
            ThinkingLevel::Minimal | ThinkingLevel::Low => 1024,
            ThinkingLevel::Medium => 8192,
            _ => 24576,
        };
        serde_json::json!({"thinkingBudget": budget, "includeThoughts": true})
    }

    #[test]
    fn gemini_2x_payload_is_unchanged_budget() {
        // Near-misses: every id here must keep the pre-3 payload byte for byte.
        for model in [
            "gemini-2.5-pro",
            "gemini-2.5-flash",
            "gemini-2.5-flash-lite",
            "gemini-2.5-flash-preview-09-2025",
            "gemini-2.0-flash",
            "models/gemini-2.5-flash",
            "projects/p/locations/us-central1/publishers/google/models/gemini-2.5-pro",
            "gemini-2.5-pro@001",
            "gemini-flash-lite-latest",
            "gemini-exp-1206",
            "gemma-3-27b-it",
        ] {
            for level in ALL_LEVELS {
                let got = thinking_config(model, level);
                assert_eq!(got, legacy_budget_payload(level), "{model} {level:?}");
                assert_eq!(
                    serde_json::to_string(&got).unwrap(),
                    serde_json::to_string(&legacy_budget_payload(level)).unwrap(),
                    "{model} {level:?}: byte-identical"
                );
            }
        }
    }

    #[test]
    fn gemini_3_8_flash_sends_level_and_clamps_minimal_to_low() {
        // 3.8 / 3.7 Flash reject MINIMAL ("Not supported (error)").
        for model in [
            "gemini-3.8-flash",
            "gemini-3.7-flash",
            "gemini-3.8-flash-cyber",
        ] {
            let expect = [
                None,        // Off: omitted, the model runs at its default
                Some("LOW"), // Minimal clamped
                Some("LOW"),
                Some("MEDIUM"),
                Some("HIGH"),
                Some("HIGH"), // XHigh clamped
                Some("HIGH"), // Max clamped
            ];
            for (level, want) in ALL_LEVELS.into_iter().zip(expect) {
                let got = thinking_config(model, level);
                match want {
                    None => assert!(got.is_null(), "{model} {level:?}: {got}"),
                    Some(want) => assert_eq!(
                        got,
                        serde_json::json!({"thinkingLevel": want, "includeThoughts": true}),
                        "{model} {level:?}: level only, never both"
                    ),
                }
            }
        }
    }

    #[test]
    fn gemini_3_flash_lite_and_3_5_flash_pass_minimal_through() {
        for model in [
            "gemini-3.5-flash-lite",
            "gemini-3.1-flash-lite",
            "gemini-3.5-flash",
            "gemini-3.6-flash",
            "gemini-3-flash-preview",
        ] {
            assert_eq!(
                thinking_config(model, ThinkingLevel::Minimal),
                serde_json::json!({"thinkingLevel": "MINIMAL", "includeThoughts": true}),
                "{model}"
            );
            assert_eq!(
                thinking_config(model, ThinkingLevel::Low)["thinkingLevel"],
                "LOW"
            );
        }
    }

    #[test]
    fn gemini_3_pro_has_no_minimal() {
        for model in [
            "gemini-3.1-pro-preview",
            "gemini-3-pro-preview",
            "gemini-pro-latest",
            "gemini-flash-latest", // hot-swapped alias: MINIMAL not assumed
            "gemini-3.8-flash",    // rejects MINIMAL (thinking guide)
            "gemini-4-argon",      // rejects MINIMAL; thinking cannot be off
        ] {
            assert_eq!(
                thinking_config(model, ThinkingLevel::Minimal)["thinkingLevel"],
                "LOW",
                "{model}"
            );
            assert_eq!(
                thinking_config(model, ThinkingLevel::Max)["thinkingLevel"],
                "HIGH",
                "{model}"
            );
        }
    }

    #[test]
    fn off_omits_thinking_config_on_every_gemini_generation() {
        // User decision: Off sends nothing. On Gemini 3 the model then runs
        // at its own default level (it cannot be switched off).
        for model in [
            "gemini-3.8-flash",
            "gemini-3.5-flash-lite",
            "gemini-3.1-pro-preview",
            "gemini-3-flash-preview",
            "gemini-flash-latest",
            "projects/p/locations/global/publishers/google/models/gemini-3.8-flash",
            "gemini-3.1-flash-image",
            "gemini-3-pro-image",
            "gemini-3.8-flash-tts",
            "gemini-2.5-flash",
        ] {
            let mut config = StreamConfig::new(model, "k");
            config.messages = vec![Message::user("hi")];
            config.thinking_level = ThinkingLevel::Off;
            let body = build_request_body(&config);
            assert!(
                body["generationConfig"].get("thinkingConfig").is_none(),
                "{model}: {body}"
            );
        }
        // Forcing thinkingLevel does not bring Off back either.
        assert!(thinking_config_with(
            "my-gemini-alias",
            ThinkingLevel::Off,
            GoogleCompat::force_thinking_level()
        )
        .is_null());
    }

    #[test]
    fn positive_control_off_revert_only_touches_off() {
        // The same 3.x ids still get a thinkingConfig one rung up, so the
        // omission above is Off-specific, not a broken 3.x path.
        for model in [
            "gemini-3.8-flash",
            "gemini-3.5-flash-lite",
            "gemini-3.1-pro-preview",
        ] {
            assert!(
                thinking_config(model, ThinkingLevel::Minimal)
                    .get("thinkingLevel")
                    .is_some(),
                "{model}"
            );
        }
    }

    #[test]
    fn gemini_image_models_get_only_their_accepted_levels() {
        // Vertex thinking table: 3.1 Flash Image and 3.1 Flash-Lite Image take
        // "MINIMAL , HIGH"; 3 Pro Image takes "HIGH" only.
        for model in [
            "gemini-3.1-flash-image",
            "gemini-3.1-flash-image-preview",
            "gemini-3.1-flash-lite-image",
            "projects/p/locations/global/publishers/google/models/gemini-3.1-flash-image",
        ] {
            let expect = [
                None,
                Some("MINIMAL"),
                Some("MINIMAL"), // Low: down to the low-cost end
                Some("HIGH"),    // Medium: up, a request for thinking gets it
                Some("HIGH"),
                Some("HIGH"),
                Some("HIGH"),
            ];
            for (level, want) in ALL_LEVELS.into_iter().zip(expect) {
                let got = thinking_config(model, level);
                match want {
                    None => assert!(got.is_null(), "{model} {level:?}"),
                    Some(want) => assert_eq!(
                        got,
                        serde_json::json!({"thinkingLevel": want, "includeThoughts": true}),
                        "{model} {level:?}"
                    ),
                }
            }
        }
        for model in ["gemini-3-pro-image", "gemini-3-pro-image-preview"] {
            assert!(thinking_config(model, ThinkingLevel::Off).is_null());
            for level in ALL_LEVELS.into_iter().skip(1) {
                assert_eq!(
                    thinking_config(model, level),
                    serde_json::json!({"thinkingLevel": "HIGH", "includeThoughts": true}),
                    "{model} {level:?}"
                );
            }
        }
        // 2.5 Flash Image stays on the legacy budget path, byte for byte.
        for level in ALL_LEVELS {
            assert_eq!(
                thinking_config("gemini-2.5-flash-image", level),
                legacy_budget_payload(level)
            );
        }
    }

    #[test]
    fn gemini_3_tts_models_get_no_thinking_config() {
        for model in [
            "gemini-3.8-flash-tts",
            "gemini-3.8-flash-lite-tts",
            "gemini-3.1-flash-tts-preview",
        ] {
            for level in ALL_LEVELS {
                assert!(thinking_config(model, level).is_null(), "{model} {level:?}");
            }
        }
        // Positive control: the non-TTS sibling does get one.
        assert_eq!(
            thinking_config("gemini-3.8-flash", ThinkingLevel::Low)["thinkingLevel"],
            "LOW"
        );
        // 2.x TTS ids keep the pre-3 payload unchanged.
        assert_eq!(
            thinking_config("gemini-2.5-flash-preview-tts", ThinkingLevel::Low),
            legacy_budget_payload(ThinkingLevel::Low)
        );
    }

    #[test]
    fn gemini_3_ids_are_read_through_prefixes_and_paths() {
        for model in [
            "gemini-3",
            "models/gemini-3.8-flash",
            "GEMINI-3.8-FLASH",
            "projects/p/locations/global/publishers/google/models/gemini-3.8-flash",
            "gemini-3.8-flash@001",
            "gemini-4-flash", // later generations inherit the version rule
        ] {
            let got = thinking_config(model, ThinkingLevel::Medium);
            assert_eq!(
                got,
                serde_json::json!({"thinkingLevel": "MEDIUM", "includeThoughts": true}),
                "{model}"
            );
        }
    }

    #[test]
    fn positive_control_2_5_and_3_x_payloads_differ() {
        // Guards against a helper that always returns the same shape.
        let old = thinking_config("gemini-2.5-flash", ThinkingLevel::High);
        let new = thinking_config("gemini-3.5-flash", ThinkingLevel::High);
        assert_ne!(old, new);
        assert_eq!(old["thinkingBudget"], 24576);
        assert_eq!(new["thinkingLevel"], "HIGH");
    }

    #[test]
    fn google_compat_overrides_the_model_id_rule() {
        // Force level on an id the rule cannot read (a proxy alias).
        let got = thinking_config_with(
            "my-gemini-alias",
            ThinkingLevel::Minimal,
            GoogleCompat::force_thinking_level(),
        );
        assert_eq!(
            got,
            serde_json::json!({"thinkingLevel": "LOW", "includeThoughts": true})
        );
        // Forcing level on a recognised 3.x id keeps its MINIMAL knowledge.
        let got = thinking_config_with(
            "gemini-3.5-flash-lite",
            ThinkingLevel::Minimal,
            GoogleCompat::force_thinking_level(),
        );
        assert_eq!(got["thinkingLevel"], "MINIMAL");
        // Force budget on a 3.x id: the legacy payload, exactly.
        for level in ALL_LEVELS {
            let got = thinking_config_with(
                "gemini-3.8-flash",
                level,
                GoogleCompat::force_thinking_budget(),
            );
            assert_eq!(got, legacy_budget_payload(level), "{level:?}");
        }
        // Default compat == no compat.
        assert_eq!(
            thinking_config_with(
                "gemini-3.8-flash",
                ThinkingLevel::High,
                GoogleCompat::default()
            ),
            thinking_config("gemini-3.8-flash", ThinkingLevel::High)
        );
    }

    #[test]
    fn google_compat_serde_default_and_round_trip() {
        let compat: GoogleCompat = serde_json::from_value(serde_json::json!({})).unwrap();
        assert_eq!(compat, GoogleCompat::default());
        let mut mc = ModelConfig::google("gemini-2.5-flash", "G");
        let before = serde_json::to_value(&mc).unwrap();
        assert!(
            before.get("google").is_none(),
            "None is omitted on serialize"
        );
        mc.google = Some(GoogleCompat::force_thinking_level());
        let back: ModelConfig = serde_json::from_value(serde_json::to_value(&mc).unwrap()).unwrap();
        assert_eq!(back.google, Some(GoogleCompat::force_thinking_level()));
    }

    #[test]
    fn tool_result_sends_every_text_block() {
        // An MCP server may answer in several text blocks (ESLint's: an intro,
        // the findings, a closing note); the model must see all of them.
        let config = StreamConfig {
            model: "gemini-2.5-flash".into(),
            system_prompt: "".into(),
            messages: vec![Message::ToolResult {
                tool_call_id: "call-1".into(),
                tool_name: "lint".into(),
                content: vec![
                    Content::Text {
                        text: "Here are the results:".into(),
                    },
                    Content::Text {
                        text: "[{\"line\":3}]".into(),
                    },
                ],
                is_error: false,
                timestamp: 0,
            }],
            tools: vec![],
            thinking_level: ThinkingLevel::Off,
            api_key: "test".into(),
            max_tokens: None,
            temperature: None,
            model_config: None,
            cache_config: CacheConfig::default(),
            output_schema: None,
        };
        let body = build_request_body(&config);
        assert_eq!(
            body["contents"][0]["parts"][0]["functionResponse"]["response"]["result"],
            "Here are the results:\n[{\"line\":3}]"
        );
    }

    #[test]
    fn tool_result_with_an_image_sends_every_text_block_and_the_image() {
        let config = StreamConfig {
            model: "gemini-2.5-flash".into(),
            system_prompt: "".into(),
            messages: vec![Message::ToolResult {
                tool_call_id: "call-1".into(),
                tool_name: "screenshot".into(),
                content: vec![
                    Content::Text { text: "a".into() },
                    Content::Image {
                        data: "AAAA".into(),
                        mime_type: "image/png".into(),
                    },
                    Content::Text { text: "b".into() },
                ],
                is_error: false,
                timestamp: 0,
            }],
            tools: vec![],
            thinking_level: ThinkingLevel::Off,
            api_key: "test".into(),
            max_tokens: None,
            temperature: None,
            model_config: None,
            cache_config: CacheConfig::default(),
            output_schema: None,
        };
        let body = build_request_body(&config);
        let parts = &body["contents"][0]["parts"];
        assert_eq!(parts[0]["functionResponse"]["response"]["result"], "a\nb");
        assert_eq!(parts[1]["inlineData"]["data"], "AAAA");
        assert_eq!(parts.as_array().unwrap().len(), 2);
    }
}