ante-llm 0.4.2

Streaming LLM client for Anthropic, OpenAI, Gemini and Chat Completions servers, from the Ante coding agent
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
// Copyright 2026 Antigma Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

mod convert;
mod types;

pub(crate) use convert::effort_levels;

use self::convert::{
    finish_reason_error, format_grounding_sources, prompt_blocked_error, stop_reason,
    stream_events_from_part, to_gemini_request,
};
use self::types::{
    GeminiContent, GeminiPart, GeminiRequest, GeminiResponse, GeminiStreamChunk, GeminiTool,
    ListModelsResponse,
};
use crate::WireStyle;
use crate::client::{ChatClient, Client, ClientResponse, ProviderClient};
use crate::error::{LlmError, LlmErrorKind, http_status_to_kind, parse_error_body};
use crate::extra_body::decorate;
use crate::stream_driver::StreamMapper;
use crate::system_messages;
use crate::types::{
    ChatRequest, ChatResponseStream, Effort, ModelSpec, StreamEvent, ThinkingDisplay, Usage,
    WebSearchResult, supported_efforts_by_model,
};
use anyhow::Result;
use async_trait::async_trait;
use serde_json::{Map, Value};
use std::collections::HashMap;

/// The Gemini API, for [`Client::new`].
pub const BASE_URL: &str = "https://generativelanguage.googleapis.com/v1beta";

/// Gemini API client.
#[derive(Clone)]
pub struct Gemini {
    client: ProviderClient,
    extra_body: Map<String, Value>,
    thinking_display: Option<ThinkingDisplay>,
    max_request_images: Option<u32>,
    supported_efforts: HashMap<String, Vec<Effort>>,
}

pub(super) async fn search(
    transport: &Client,
    query: &str,
    model: &ModelSpec,
) -> Result<WebSearchResult, LlmError> {
    let client = ProviderClient::new(transport.clone(), classify_gemini_http_response);
    let request = GeminiRequest {
        contents: vec![GeminiContent { role: None, parts: vec![GeminiPart::text(query)] }],
        tools: Some(vec![GeminiTool::google_search()]),
        ..Default::default()
    };

    let endpoint = format!("/models/{}:generateContent", model.id);
    let gemini_response: GeminiResponse = client.post_json(&endpoint, &request).await?;
    WebSearchResult::try_from(gemini_response)
}

#[async_trait]
impl ChatClient for Gemini {
    async fn stream_chat(&self, request: ChatRequest) -> Result<ChatResponseStream, LlmError> {
        let wire = self.wire_request(&request)?;

        // Vertex AI requires ?alt=sse query parameter for SSE streaming
        let endpoint = format!("/models/{}:streamGenerateContent?alt=sse", request.model);
        let body = decorate(&wire, &self.extra_body);

        self.client.post_stream(&endpoint, &body, GeminiMapper::default()).await
    }

    async fn list_models(&self) -> Result<Vec<ModelSpec>, LlmError> {
        let resp: ListModelsResponse = self.client.get_json("/models", &()).await?;
        Ok(resp.models.into_iter().map(ModelSpec::from).collect())
    }
}

impl Gemini {
    /// A client that sends through `client`, usually built on [`BASE_URL`].
    pub fn new(client: Client) -> Self {
        Self {
            client: ProviderClient::new(client, classify_gemini_http_response),
            extra_body: Map::new(),
            thinking_display: None,
            max_request_images: None,
            supported_efforts: HashMap::new(),
        }
    }

    /// Add these fields to every chat request body. They are sent as given:
    /// pass only what [`WireStyle::conflicts`] clears.
    pub fn with_extra_body(mut self, extra_body: Map<String, Value>) -> Self {
        self.extra_body = extra_body;
        self
    }

    /// Ask for readable reasoning in this form. `None` leaves the provider's
    /// default.
    pub fn with_thinking_display(mut self, display: Option<ThinkingDisplay>) -> Self {
        self.thinking_display = display;
        self
    }

    /// Send at most this many images per request: the newest stay and older
    /// ones become text markers. `None` sends them all.
    pub fn with_max_request_images(mut self, max_request_images: Option<u32>) -> Self {
        self.max_request_images = max_request_images;
        self
    }

    /// Round effort onto the levels each model in `models` declares.
    pub fn with_supported_efforts(mut self, models: &[ModelSpec]) -> Self {
        self.supported_efforts = supported_efforts_by_model(models);
        self
    }

    /// Lower `request` to the provider's wire shape; the provider never sees a
    /// request that fails here.
    fn wire_request(&self, request: &ChatRequest) -> Result<GeminiRequest, LlmError> {
        system_messages::prepare(request, &WireStyle::Gemini, self.client.base_url())
            .map(|request| request.within_image_budget(self.max_request_images))
            .and_then(|request| {
                let declared = self.supported_efforts.get(&request.model).map(Vec::as_slice);
                to_gemini_request(&request, self.thinking_display, declared)
            })
            .map_err(LlmError::request_conversion)
    }
}

fn classify_gemini_http_response(resp: ClientResponse) -> LlmError {
    let (status_name, message) = parse_error_body(&resp.body, &["status"]);
    let kind = gemini_error_kind(resp.status, status_name.as_deref(), message.as_deref());
    LlmError::http(kind, resp.status, status_name, message.unwrap_or(resp.body))
}

fn gemini_error_kind(
    http_status: reqwest::StatusCode,
    status_name: Option<&str>,
    message: Option<&str>,
) -> LlmErrorKind {
    // Gemini uses RESOURCE_EXHAUSTED for both hard quota exhaustion and
    // transient rate limits. Quota messages often mention an exceeded token
    // metric, so classify this structured status before the broad context
    // overflow heuristic below.
    if status_name == Some("RESOURCE_EXHAUSTED") {
        return if gemini_message_is_quota(message) {
            LlmErrorKind::Quota
        } else {
            LlmErrorKind::RateLimited
        };
    }

    if gemini_message_is_context_overflow(message) {
        return LlmErrorKind::ContextOverflow;
    }

    if let Some(status_name) = status_name {
        match status_name {
            "UNAUTHENTICATED" | "PERMISSION_DENIED" => return LlmErrorKind::Auth,
            "UNAVAILABLE" => return LlmErrorKind::Overloaded,
            "INTERNAL" | "DATA_LOSS" => return LlmErrorKind::ServerError,
            "DEADLINE_EXCEEDED" => return LlmErrorKind::Timeout,
            "INVALID_ARGUMENT" | "FAILED_PRECONDITION" | "NOT_FOUND" => {
                return LlmErrorKind::InvalidRequest;
            }
            _ => {}
        }
    }

    http_status_to_kind(http_status)
}

fn gemini_message_is_context_overflow(message: Option<&str>) -> bool {
    let Some(message) = message else {
        return false;
    };
    let message = message.to_ascii_lowercase();
    message.contains("exceed") && (message.contains("token") || message.contains("context"))
}

fn gemini_message_is_quota(message: Option<&str>) -> bool {
    let Some(message) = message else {
        return false;
    };
    let message = message.to_ascii_lowercase();
    // A project spend cap reads "temporarily rate-limited", but it lasts until
    // someone raises the cap, so retrying cannot help.
    message.contains("quota") || message.contains("billing") || message.contains("spending cap")
}

#[derive(Default)]
struct GeminiMapper {
    /// Counter for generating unique tool-call ids.
    tool_call_counter: usize,
    grounding_emitted: bool,
    /// Usage from whichever chunk carries `usageMetadata`: Gemini may send it
    /// with `finishReason` or in a separate candidates-less chunk.
    pending_usage: Option<Usage>,
}

impl StreamMapper for GeminiMapper {
    type Raw = GeminiStreamChunk;

    fn map(&mut self, chunk: GeminiStreamChunk) -> Result<Vec<StreamEvent>, LlmError> {
        let mut events = Vec::new();

        if let Some(m) = chunk.usage_metadata {
            self.pending_usage = Some(Usage::from(&m));
        }

        if let Some(reason) = chunk.prompt_feedback.and_then(|f| f.block_reason) {
            return Err(prompt_blocked_error(&reason));
        }

        let Some(candidate) = chunk.candidates.into_iter().next() else {
            return Ok(events);
        };

        for part in candidate.content.parts {
            events.extend(stream_events_from_part(part, &mut self.tool_call_counter));
        }

        if !self.grounding_emitted
            && let Some(ref grounding) = candidate.grounding_metadata
            && let Some(text) = format_grounding_sources(grounding)
        {
            self.grounding_emitted = true;
            events.push(StreamEvent::TextDelta(text));
        }

        if let Some(finish_reason) = &candidate.finish_reason {
            if let Some(err) = finish_reason_error(finish_reason) {
                return Err(err);
            }
            events.push(StreamEvent::MessageStop {
                usage: self.pending_usage.take().unwrap_or_default(),
                stop_reason: Some(stop_reason(finish_reason.as_str())),
            });
        }

        Ok(events)
    }
}

#[cfg(test)]
mod tests {
    use super::types::{
        Candidate, FunctionCall, GeminiPartData, GroundingChunk, GroundingMetadata,
        GroundingSupport, GroundingWeb, UsageMetadata,
    };
    use super::*;
    use crate::test_support::{chat_request, image_request, prompted, tool_request, tool_results};
    use crate::types::{Effort, Message, StopReason};
    use reqwest::{StatusCode, header::HeaderMap};

    /// The `contents` Gemini is sent for `messages`.
    fn contents(messages: Vec<Message>) -> Value {
        let request =
            to_gemini_request(&chat_request("gemini-test", messages), None, None).unwrap();
        serde_json::to_value(&request.contents).unwrap()
    }

    const FREE_TIER_INPUT_TOKEN_QUOTA_ERROR: &str = r#"{
        "error": {
            "code": 429,
            "message": "You exceeded your current quota. Quota exceeded for metric: generativelanguage.googleapis.com/generate_content_free_tier_input_token_count, limit: 250000, model: gemini-3.6-flash",
            "status": "RESOURCE_EXHAUSTED"
        }
    }"#;

    const SPENDING_CAP_ERROR: &str = r#"{
        "error": {
            "code": 429,
            "message": "Your project is temporarily rate-limited to prevent exceeding its monthly spending cap. Please raise your project spend cap or wait before retrying.",
            "status": "RESOURCE_EXHAUSTED"
        }
    }"#;

    #[test]
    fn system_messages_fall_back_without_changing_system_instruction() {
        use crate::types::Content;
        let request = prompted(
            "gemini-3.8-pro",
            &["fixed prompt"],
            vec![Message::user_text("question".into()), Message::system("runtime rule".into())],
        );
        let request = crate::system_messages::prepare(
            &request,
            &crate::WireStyle::Gemini,
            "https://generativelanguage.googleapis.com/v1beta",
        )
        .unwrap();
        let json = serde_json::to_value(to_gemini_request(&request, None, None).unwrap()).unwrap();
        assert_eq!(json["systemInstruction"]["parts"][0]["text"], "fixed prompt");
        assert_eq!(json["contents"][0]["parts"][0]["text"], "question");
        assert_eq!(json["contents"][1]["role"], "user");
        assert_eq!(
            json["contents"][1]["parts"][0]["text"],
            Content::reminder("runtime rule".into()).as_text()
        );
    }

    #[test]
    fn images_reach_user_content_and_tool_results() {
        let request = image_request();
        let wire = to_gemini_request(&request, None, None).unwrap();
        let json = serde_json::to_string(&wire.contents).unwrap();
        // Tool-result URLs keep Gemini's existing inline text-reference encoding.
        assert_eq!(json.matches("inlineData").count(), 3);
        assert_eq!(json.matches("fileData").count(), 1);
        assert!(json.contains("aW1hZ2U="));
    }

    #[test]
    fn test_free_tier_input_token_quota_is_not_context_overflow() {
        let error = classify_gemini_http_response(ClientResponse {
            status: StatusCode::TOO_MANY_REQUESTS,
            headers: HeaderMap::new(),
            body: FREE_TIER_INPUT_TOKEN_QUOTA_ERROR.to_string(),
        });

        assert_eq!(error.kind, LlmErrorKind::Quota);
        assert_eq!(error.detail.provider_code.as_deref(), Some("RESOURCE_EXHAUSTED"));
        assert!(error.detail.message.contains("generate_content_free_tier_input_token_count"));
    }

    #[test]
    fn spending_cap_is_quota() {
        let error = classify_gemini_http_response(ClientResponse {
            status: StatusCode::TOO_MANY_REQUESTS,
            headers: HeaderMap::new(),
            body: SPENDING_CAP_ERROR.to_string(),
        });

        assert_eq!(error.kind, LlmErrorKind::Quota);
    }

    #[test]
    fn test_stream_aggregator_multiple_function_calls() {
        let mut mapper = GeminiMapper::default();

        let chunk = GeminiStreamChunk {
            candidates: vec![Candidate {
                content: GeminiContent {
                    role: Some("model".to_string()),
                    parts: vec![
                        GeminiPart::function_call(
                            FunctionCall {
                                id: None,
                                name: "search".to_string(),
                                args: serde_json::json!({"query": "rust"}),
                            },
                            None,
                        ),
                        GeminiPart::function_call(
                            FunctionCall {
                                id: None,
                                name: "search".to_string(),
                                args: serde_json::json!({"query": "python"}),
                            },
                            None,
                        ),
                    ],
                },
                finish_reason: None,
                grounding_metadata: None,
            }],
            usage_metadata: None,
            prompt_feedback: None,
        };

        let evs = mapper.map(chunk).unwrap();
        assert_eq!(evs.len(), 2);

        // Without ids on the wire, calls to the same function still get unique ones.
        match (&evs[0], &evs[1]) {
            (StreamEvent::ToolUse(tool1), StreamEvent::ToolUse(tool2)) => {
                assert_eq!(tool1.name, "search");
                assert_eq!(tool2.name, "search");
                assert_ne!(tool1.id, tool2.id); // IDs should be different
                assert_eq!(tool1.id, "call_search_0");
                assert_eq!(tool2.id, "call_search_1");
                assert_eq!(tool1.signature, None);
                assert_eq!(tool2.signature, None);
            }
            _ => panic!("Expected ToolUse events"),
        }
    }

    #[test]
    fn test_stream_aggregator_function_call_keeps_wire_id_and_thought_signature() {
        let mut mapper = GeminiMapper::default();

        let chunk = GeminiStreamChunk {
            candidates: vec![Candidate {
                content: GeminiContent {
                    role: Some("model".to_string()),
                    parts: vec![GeminiPart::function_call(
                        FunctionCall {
                            id: Some("call_8262150237656834604".to_string()),
                            name: "search".to_string(),
                            args: serde_json::json!({"query": "rust"}),
                        },
                        Some("signature123".to_string()),
                    )],
                },
                finish_reason: None,
                grounding_metadata: None,
            }],
            usage_metadata: None,
            prompt_feedback: None,
        };

        let evs = mapper.map(chunk).unwrap();
        assert_eq!(evs.len(), 1);
        match &evs[0] {
            StreamEvent::ToolUse(tool) => {
                assert_eq!(tool.id, "call_8262150237656834604");
                assert_eq!(tool.name, "search");
                assert_eq!(tool.signature, Some("signature123".to_string()));
            }
            other => panic!("Expected ToolUse, got {other:?}"),
        }
    }

    #[test]
    fn thinking_display_uses_closest_gemini_mode_and_preserves_effort() {
        for model in ["gemini-3-pro-preview", "gemini-3.8-flash"] {
            let request = ChatRequest {
                model: model.into(),
                effort: Some(Effort::High),
                ..Default::default()
            };
            let mut automatic =
                serde_json::to_value(to_gemini_request(&request, None, None).unwrap()).unwrap();
            assert!(
                automatic["generationConfig"]["thinkingConfig"].get("includeThoughts").is_none()
            );
            for (display, include) in [
                (ThinkingDisplay::Off, false),
                (ThinkingDisplay::Concise, true),
                (ThinkingDisplay::Detailed, true),
            ] {
                let wire =
                    serde_json::to_value(to_gemini_request(&request, Some(display), None).unwrap())
                        .unwrap();
                automatic["generationConfig"]["thinkingConfig"]["includeThoughts"] =
                    Value::Bool(include);
                assert_eq!(wire, automatic, "display must not change reasoning for {model}");
            }
        }
        let request = ChatRequest::new("gemini-3.8-flash");
        for display in [
            None,
            Some(ThinkingDisplay::Off),
            Some(ThinkingDisplay::Concise),
            Some(ThinkingDisplay::Detailed),
        ] {
            let wire =
                serde_json::to_value(to_gemini_request(&request, display, None).unwrap()).unwrap();
            assert!(wire.pointer("/generationConfig/thinkingConfig").is_none());
        }
    }

    #[test]
    fn test_stream_aggregator_thinking_with_signature() {
        let mut mapper = GeminiMapper::default();

        let chunk = GeminiStreamChunk {
            candidates: vec![Candidate {
                content: GeminiContent {
                    role: Some("model".to_string()),
                    parts: vec![GeminiPart::thought(
                        "Let me think...",
                        Some("signature123".to_string()),
                    )],
                },
                finish_reason: None,
                grounding_metadata: None,
            }],
            usage_metadata: None,
            prompt_feedback: None,
        };

        let evs = mapper.map(chunk).unwrap();
        assert_eq!(evs.len(), 1, "thought text and signature must arrive in a single delta");
        match &evs[0] {
            StreamEvent::ThinkingDelta { thinking, signature } => {
                assert_eq!(thinking, "Let me think...");
                assert_eq!(signature.as_deref(), Some("signature123"));
            }
            other => panic!("Expected ThinkingDelta, got {other:?}"),
        }
    }

    #[test]
    fn test_stream_aggregator_signature_only_text_is_text_delta() {
        let mut mapper = GeminiMapper::default();

        let part = GeminiPart {
            thought: false,
            thought_signature: Some("signature123".to_string()),
            data: Some(GeminiPartData::Text { text: "Hello".to_string() }),
        };

        let chunk = GeminiStreamChunk {
            candidates: vec![Candidate {
                content: GeminiContent { role: Some("model".to_string()), parts: vec![part] },
                finish_reason: None,
                grounding_metadata: None,
            }],
            usage_metadata: None,
            prompt_feedback: None,
        };

        let evs = mapper.map(chunk).unwrap();
        match &evs[0] {
            StreamEvent::TextDelta(text) => assert_eq!(text, "Hello"),
            other => panic!("Expected TextDelta, got {other:?}"),
        }
    }

    #[test]
    fn test_stop_reason_classifies_content_flag_family_as_refusal() {
        for reason in
            ["PROHIBITED_CONTENT", "SAFETY", "SPII", "RECITATION", "BLOCKLIST", "LANGUAGE"]
        {
            assert_eq!(stop_reason(reason), StopReason::Refusal, "{reason}");
        }
        assert_eq!(stop_reason("STOP"), StopReason::EndTurn);
        assert_eq!(stop_reason("MAX_TOKENS"), StopReason::MaxTokens);
        assert_eq!(
            stop_reason("TOO_MANY_TOOL_CALLS"),
            StopReason::Other("TOO_MANY_TOOL_CALLS".to_string())
        );
    }

    #[test]
    fn test_stream_malformed_function_call_is_error() {
        let mut mapper = GeminiMapper::default();

        let chunk = GeminiStreamChunk {
            candidates: vec![Candidate {
                content: GeminiContent { role: Some("model".to_string()), parts: vec![] },
                finish_reason: Some("MALFORMED_FUNCTION_CALL".to_string()),
                grounding_metadata: None,
            }],
            usage_metadata: None,
            prompt_feedback: None,
        };

        let err = mapper.map(chunk).unwrap_err();
        assert_eq!(err.detail.provider_code.as_deref(), Some("MALFORMED_FUNCTION_CALL"));
    }

    #[test]
    fn test_stream_usage_includes_thoughts_token_count() {
        let mut mapper = GeminiMapper::default();

        let chunk = GeminiStreamChunk {
            candidates: vec![Candidate {
                content: GeminiContent { role: Some("model".to_string()), parts: vec![] },
                finish_reason: Some("STOP".to_string()),
                grounding_metadata: None,
            }],
            usage_metadata: Some(UsageMetadata {
                prompt_token_count: 10,
                candidates_token_count: 5,
                cached_content_token_count: None,
                thoughts_token_count: Some(120),
            }),
            prompt_feedback: None,
        };

        let evs = mapper.map(chunk).unwrap();
        match &evs[0] {
            StreamEvent::MessageStop { usage, .. } => {
                assert_eq!(usage.input_tokens, 10);
                assert_eq!(usage.output_tokens, 125);
            }
            other => panic!("Expected MessageStop, got {other:?}"),
        }
    }

    #[test]
    fn test_stream_aggregator_emits_grounding_sources_once() {
        let mut mapper = GeminiMapper::default();

        let chunk = GeminiStreamChunk {
            candidates: vec![Candidate {
                content: GeminiContent { role: Some("model".to_string()), parts: vec![] },
                finish_reason: None,
                grounding_metadata: Some(GroundingMetadata {
                    grounding_chunks: vec![GroundingChunk {
                        web: Some(GroundingWeb {
                            uri: "https://vertexaisearch.cloud.google.com/abc".to_string(),
                            title: "aljazeera.com".to_string(),
                        }),
                    }],
                    grounding_supports: vec![GroundingSupport { grounding_chunk_indices: vec![0] }],
                }),
            }],
            usage_metadata: None,
            prompt_feedback: None,
        };

        let evs = mapper.map(chunk).unwrap();
        assert_eq!(evs.len(), 1);
        match &evs[0] {
            StreamEvent::TextDelta(s) => assert!(s.contains("Sources:")),
            other => panic!("Expected TextDelta, got {other:?}"),
        }

        // Metadata arrives again; should not emit twice
        let chunk2 = GeminiStreamChunk {
            candidates: vec![Candidate {
                content: GeminiContent { role: Some("model".to_string()), parts: vec![] },
                finish_reason: None,
                grounding_metadata: Some(GroundingMetadata {
                    grounding_chunks: vec![GroundingChunk {
                        web: Some(GroundingWeb {
                            uri: "https://vertexaisearch.cloud.google.com/abc".to_string(),
                            title: "aljazeera.com".to_string(),
                        }),
                    }],
                    grounding_supports: vec![],
                }),
            }],
            usage_metadata: None,
            prompt_feedback: None,
        };
        assert!(mapper.map(chunk2).unwrap().is_empty());
    }

    #[test]
    fn test_web_search_result_from_grounding_metadata() {
        let resp = serde_json::json!({
          "candidates": [
            {
              "content": {
                "parts": [
                  { "text": "Spain won Euro 2024, defeating England 2-1 in the final." }
                ],
                "role": "model"
              },
              "groundingMetadata": {
                "webSearchQueries": [
                  "UEFA Euro 2024 winner",
                  "who won euro 2024"
                ],
                "searchEntryPoint": {
                  "renderedContent": "<!-- HTML and CSS for the search widget -->"
                },
                "groundingChunks": [
                  { "web": { "uri": "https://vertexaisearch.cloud.google.com/abc", "title": "aljazeera.com" } },
                  { "web": { "uri": "https://vertexaisearch.cloud.google.com/def", "title": "uefa.com" } }
                ],
                "groundingSupports": [
                  { "segment": { "startIndex": 0, "endIndex": 10, "text": "Spain won" }, "groundingChunkIndices": [0] },
                  { "segment": { "startIndex": 11, "endIndex": 20, "text": "Euro 2024" }, "groundingChunkIndices": [0, 1] }
                ]
              }
            }
          ],
          "usageMetadata": {
            "promptTokenCount": 1,
            "candidatesTokenCount": 2
          }
        });

        let gemini: GeminiResponse = serde_json::from_value(resp).unwrap();
        let result = WebSearchResult::try_from(gemini).unwrap();
        assert!(result.content.as_text().contains("Spain won Euro 2024"));
        let citations = result.citations;
        assert_eq!(citations.len(), 2);
        assert_eq!(citations[0].title, "aljazeera.com");
        assert_eq!(citations[1].title, "uefa.com");
    }

    #[test]
    fn test_gemini_request_serializes_contents_and_function_declarations() {
        use crate::types::{Content, ContentPart, ToolResult, ToolUse};

        let messages = vec![
            Message::user_text("Check the weather in Paris and London.".to_string()),
            Message::model_content(Content::Parts(vec![
                ContentPart::ToolUse(ToolUse {
                    id: "call_get_current_temperature_0".to_string(),
                    name: "get_current_temperature".to_string(),
                    args: serde_json::json!({ "city": "Paris" }),
                    malformed_args: None,
                    signature: Some("<SIGNATURE_A>".to_string()),
                }),
                ContentPart::ToolUse(ToolUse::new(
                    "call_get_current_temperature_1",
                    "get_current_temperature",
                    serde_json::json!({ "city": "London" }),
                )),
            ])),
            tool_results(vec![
                ToolResult::ok(
                    "call_get_current_temperature_0".to_string(),
                    Content::Text(r#"{"temp":"15C"}"#.to_string()),
                ),
                ToolResult::ok(
                    "call_get_current_temperature_1".to_string(),
                    Content::Text(r#"{"temp":"12C"}"#.to_string()),
                ),
            ]),
        ];

        let got = contents(messages);
        let expected = serde_json::json!([
          {
            "role": "user",
            "parts": [
              {
                "text": "Check the weather in Paris and London."
              }
            ]
          },
          {
            "role": "model",
            "parts": [
              {
                "functionCall": {
                  "id": "call_get_current_temperature_0",
                  "name": "get_current_temperature",
                  "args": {
                    "city": "Paris"
                  }
                },
                "thoughtSignature": "<SIGNATURE_A>"
              },
              {
                "functionCall": {
                  "id": "call_get_current_temperature_1",
                  "name": "get_current_temperature",
                  "args": {
                    "city": "London"
                  }
                }
              }
            ]
          },
          {
            "role": "user",
            "parts": [
              {
                "functionResponse": {
                  "id": "call_get_current_temperature_0",
                  "name": "get_current_temperature",
                  "response": {
                    "output": { "temp": "15C" }
                  }
                }
              },
              {
                "functionResponse": {
                  "id": "call_get_current_temperature_1",
                  "name": "get_current_temperature",
                  "response": {
                    "output": { "temp": "12C" }
                  }
                }
              }
            ]
          }
        ]);

        assert_eq!(got, expected);
    }

    #[test]
    fn test_function_response_name_resolved_from_the_stored_tool_use() {
        use crate::types::{Content, ContentPart, ToolResult, ToolUse};

        // Anthropic-style id from a mid-conversation provider switch: the
        // name cannot be derived from the id and must come from the stored
        // tool call.
        let messages = vec![
            Message::model_content(Content::Parts(vec![ContentPart::ToolUse(ToolUse::new(
                "toolu_01AbCdEf",
                "get_weather",
                serde_json::json!({ "city": "Paris" }),
            ))])),
            tool_results(vec![ToolResult::ok(
                "toolu_01AbCdEf".to_string(),
                Content::Text(r#"{"temp":"15C"}"#.to_string()),
            )]),
        ];

        let got = contents(messages);

        assert_eq!(got[1]["parts"][0]["functionResponse"]["name"], "get_weather");
    }

    #[test]
    fn test_malformed_tool_use_replays_safe_args_after_provider_switch() {
        use crate::types::{Content, ContentPart, MalformedToolArgs, ToolUse};

        let messages =
            vec![Message::model_content(Content::Parts(vec![ContentPart::ToolUse(ToolUse {
                id: "toolu_malformed".to_string(),
                name: "get_weather".to_string(),
                args: serde_json::json!({ "stale": "must not be replayed" }),
                malformed_args: Some(MalformedToolArgs {
                    raw: "{oops".to_string(),
                    error: "invalid JSON".to_string(),
                }),
                signature: None,
            })]))];

        let got = contents(messages);

        assert_eq!(got[0]["parts"][0]["functionCall"]["args"], serde_json::json!({}));
    }

    #[test]
    fn test_gemini_function_response_requires_object_response_wrapped() {
        use crate::types::{Content, ToolResult};

        let messages = vec![tool_results(vec![
            // Valid JSON, but not an object -> must be wrapped as an object for Gemini.
            ToolResult::ok("call_calculator_0".to_string(), Content::Text("105".to_string())),
            // Valid JSON string -> also must be wrapped.
            ToolResult::ok("call_echo_0".to_string(), Content::Text(r#""hello""#.to_string())),
            // Valid JSON array -> also must be wrapped.
            ToolResult::ok("call_list_0".to_string(), Content::Text("[1,2,3]".to_string())),
        ])];

        let got = contents(messages);

        let expected = serde_json::json!([
          {
            "role": "user",
            "parts": [
              {
                "functionResponse": {
                  "id": "call_calculator_0",
                  "name": "calculator",
                  "response": { "output": 105 }
                }
              },
              {
                "functionResponse": {
                  "id": "call_echo_0",
                  "name": "echo",
                  "response": { "output": "hello" }
                }
              },
              {
                "functionResponse": {
                  "id": "call_list_0",
                  "name": "list",
                  "response": { "output": [1,2,3] }
                }
              }
            ]
          }
        ]);

        assert_eq!(got, expected);
    }

    #[test]
    fn test_gemini_tool_result_with_image_is_function_response_plus_inline_data() {
        use crate::types::{Attachment, Content, ContentPart, ToolResult};

        let png_1x1_base64 =
            "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO2lGkQAAAAASUVORK5CYII="
                .to_string();

        let messages = vec![tool_results(vec![ToolResult::ok(
            "call_calculator_0".to_string(),
            Content::Parts(vec![
                ContentPart::Text("6".to_string()),
                ContentPart::Image(Attachment::Base64 {
                    media_type: "image/png".to_string(),
                    data: png_1x1_base64.clone(),
                }),
            ]),
        )])];

        let got = contents(messages);

        let expected = serde_json::json!([
          {
            "role": "user",
            "parts": [
              {
                "functionResponse": {
                  "id": "call_calculator_0",
                  "name": "calculator",
                  "response": { "output": 6 },
                  "parts": [
                    {
                      "inlineData": {
                        "mimeType": "image/png",
                        "data": png_1x1_base64
                      }
                    }
                  ]
                }
              }
            ]
          }
        ]);

        assert_eq!(got, expected);
    }

    #[test]
    fn test_gemini_request_emits_auto_tool_config_only_when_tools_present() {
        let model = ModelSpec { id: "gemini-test".into(), ..Default::default() };
        let plain = tool_request(&model, &[]);
        let with_tool = tool_request(&model, &["calculator"]);
        let request = to_gemini_request(&with_tool, None, None).unwrap();
        let value = serde_json::to_value(&request).unwrap();

        assert_eq!(
            value["toolConfig"],
            serde_json::json!({ "functionCallingConfig": { "mode": "AUTO" } }),
        );
        assert_eq!(
            value["tools"][0]["functionDeclarations"][0]["parameters"],
            serde_json::json!({ "type": "object" }),
        );

        let request = to_gemini_request(&plain, None, None).unwrap();
        let value = serde_json::to_value(&request).unwrap();

        assert!(value.get("toolConfig").is_none(), "toolConfig should be omitted: {value}");
        assert!(value.get("tools").is_none(), "tools should be omitted: {value}");
    }

    #[test]
    fn test_gemini_tool_choice_maps_onto_function_calling_config() {
        use crate::types::ToolChoice;

        let model = ModelSpec { id: "gemini-test".into(), ..Default::default() };
        let base = tool_request(&model, &["calculator"]);
        let config = |tool_choice: ToolChoice| {
            let request = ChatRequest { tool_choice: Some(tool_choice), ..base.clone() };
            let value =
                serde_json::to_value(to_gemini_request(&request, None, None).unwrap()).unwrap();
            value["toolConfig"]["functionCallingConfig"].clone()
        };

        assert_eq!(config(ToolChoice::Required), serde_json::json!({ "mode": "ANY" }));
        assert_eq!(
            config(ToolChoice::Tool("calculator".into())),
            serde_json::json!({ "mode": "ANY", "allowedFunctionNames": ["calculator"] })
        );
        assert_eq!(config(ToolChoice::Forbid), serde_json::json!({ "mode": "NONE" }));
    }

    /// Drive synthetic SSE frames through the real driver, as a caller sees them.
    async fn drive_frames(frames: &[&str]) -> crate::streaming::CollectedResponse {
        let chunks: Vec<Result<GeminiStreamChunk, LlmError>> =
            frames.iter().map(|frame| Ok(serde_json::from_str(frame).unwrap())).collect();
        let stream = crate::stream_driver::drive_stream(
            futures_util::stream::iter(chunks),
            GeminiMapper::default(),
        );
        crate::streaming::collect(stream, |_| {}).await
    }

    #[tokio::test]
    async fn prompt_block_reason_is_a_terminal_content_policy_error() {
        for frame in [
            r#"{"promptFeedback":{"blockReason":"SAFETY"}}"#,
            r#"{"candidates":[],"promptFeedback":{"blockReason":"SAFETY"}}"#,
        ] {
            let collected = drive_frames(&[frame]).await;
            let err = collected.error.expect("a blocked prompt fails the call");
            assert_eq!(err.kind, LlmErrorKind::ContentPolicy, "{frame}");
            assert_eq!(err.detail.provider_code.as_deref(), Some("SAFETY"));
            assert!(err.detail.message.contains("SAFETY"), "{}", err.detail.message);
            assert_eq!(err.retry_delay(1), None, "a blocked prompt is never reconnected");
            assert!(!collected.completed);
        }
    }

    #[tokio::test]
    async fn safety_finish_reason_without_text_is_a_refusal() {
        for frame in [
            r#"{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"SAFETY"}]}"#,
            r#"{"candidates":[{"finishReason":"SAFETY"}]}"#,
        ] {
            let collected = drive_frames(&[frame]).await;
            assert!(collected.error.is_none(), "{frame}: {:?}", collected.error);
            assert!(collected.completed);
            assert_eq!(collected.response.stop_reason, Some(StopReason::Refusal));
            assert!(collected.response.message.is_empty());
        }
    }

    #[tokio::test]
    async fn bare_other_finish_reason_is_not_a_block() {
        let collected =
            drive_frames(&[r#"{"candidates":[{"content":{"parts":[]},"finishReason":"OTHER"}]}"#])
                .await;
        assert!(collected.error.is_none(), "{:?}", collected.error);
        assert_eq!(collected.response.stop_reason, Some(StopReason::Other("OTHER".into())));
    }

    #[tokio::test]
    async fn usage_only_chunk_then_stop_completes() {
        let collected = drive_frames(&[
            r#"{"usageMetadata":{"promptTokenCount":7,"candidatesTokenCount":2}}"#,
            r#"{"candidates":[{"content":{"role":"model","parts":[{"text":"hi"}]},"finishReason":"STOP"}]}"#,
        ])
        .await;
        assert!(collected.error.is_none(), "{:?}", collected.error);
        assert!(collected.completed);
        assert_eq!(collected.response.stop_reason, Some(StopReason::EndTurn));
        assert_eq!(collected.response.message.content.as_text(), "hi");
        assert_eq!(collected.response.usage.input_tokens, 7);
    }

    #[tokio::test]
    async fn close_without_terminal_signal_is_unexpected_eof() {
        let partial = r#"{"candidates":[{"content":{"role":"model","parts":[{"text":"par"}]}}]}"#;
        for frames in [vec![], vec![partial]] {
            let collected = drive_frames(&frames).await;
            let err = collected.error.expect("a cut stream fails the call");
            assert_eq!(err.kind, LlmErrorKind::UnexpectedEof, "{frames:?}");
            assert!(!collected.completed);
        }
    }
}