Skip to main content

agent86_core/provider/
google.rs

1//! The Google provider (beyond Python): Gemini on the Gemini API's
2//! `generateContent`, streamed, under `google:<model>`.
3//!
4//! Gemini's OpenAI-compatible endpoint loses the thought signature Gemini 3 and
5//! later attach to a step's function calls, and the next request in the turn
6//! fails without it, so this is an adapter of its own. Facts below were checked
7//! against Google's documentation (now at `aistudio.google.com`) on 2026-11-17.
8//!
9//! - `POST {base_url}/models/{model}:streamGenerateContent?alt=sse` on `v1`, the
10//!   stable version, which has function calling, thinking, and `store`. The key
11//!   goes in the `x-goog-api-key` header, never in the URL, so it cannot leak into
12//!   an error, a trace, or a log.
13//! - The full history is sent every time; the stateful Interactions API is not
14//!   used, since agent86 keeps the conversation in its own session.
15//! - `store: false` on every request unless `[providers.google] store = true`:
16//!   since 2026-10-26 Google keeps generateContent requests of new paid projects
17//!   in AI Studio's logs for 55 days by default, and a request holds every file
18//!   the agent read.
19//! - No `temperature`, `top_p`, or `top_k`: Gemini 4 and 3.6+ ignore them (and
20//!   will refuse them), and Google advises keeping earlier Gemini 3 models at the
21//!   defaults. `thinkingConfig.includeThoughts` asks for thought summaries, which
22//!   arrive as parts with `thought: true` and go to the reasoning; the level is
23//!   left to each model's default.
24//! - Retries follow `retry.rs` (429 and 5xx, never once text was shown); a 402
25//!   (prepaid credits used up) is not retried and says so.
26//!
27//! Tools, as checked against the live API on 2026-11-17 (`tests/google_live.rs`,
28//! on `gemini-3.1-flash-lite` and `gemini-4-hydrogen`):
29//!
30//! - Declared through `parametersJsonSchema`, unchanged: every built-in schema and
31//!   MCP-shaped ones (`$ref`/`$defs`, `additionalProperties`, `anyOf` with null,
32//!   type arrays, `oneOf`/`const`/`pattern`, `default`, `$schema`) were accepted.
33//! - A function name must start with a letter or `_`; a tool whose name does not
34//!   (an MCP name such as `1password-get`) is declared as `_<name>`, and the
35//!   model's calls are mapped back ([`gemini_name`]).
36//! - Every call came back with an `id` and its step's first call with a
37//!   `thoughtSignature`. The step sent back without the signature is a 400
38//!   ("Function call is missing a thought_signature"); with it, or with
39//!   [`SKIP_SIGNATURE`], it passes, and the response passes with or without the
40//!   call's id. The adapter keeps each call's signature in memory, keyed by the
41//!   call id, and sends it back on the same part, with the id when Google issued
42//!   it. Signatures are not saved with the session: Google checks only the
43//!   current turn, and a turn never outlives the process yet, so a call with no
44//!   signature kept (another provider's, a resumed session's) gets the
45//!   placeholder.
46
47use super::openai::error_chain;
48use super::retry::{is_retryable_status, parse_retry_after, RetryPolicy};
49use super::{DeltaStream, Provider, ProviderError};
50use crate::pricing::PriceTable;
51use crate::secrets::redact;
52use crate::types::{
53    Completion, CompletionDelta, CompletionRequest, Message, Role, StopReason, ToolCall, Usage,
54    INVALID_TOOL_ARGS_KEY,
55};
56use serde_json::{json, Map, Value};
57use std::collections::{HashMap, VecDeque};
58use std::fmt;
59use std::sync::atomic::{AtomicU64, Ordering};
60use std::sync::Mutex;
61use std::time::Duration;
62
63/// The stable Gemini API.
64pub const DEFAULT_BASE_URL: &str = "https://generativelanguage.googleapis.com/v1";
65pub const DEFAULT_API_KEY_ENV: &str = "GEMINI_API_KEY";
66
67/// Google's documented thought signature for a function call that carries none
68/// (a call from another provider, or from a session saved before signatures
69/// were kept); Google validates only the current turn.
70pub const SKIP_SIGNATURE: &str = "skip_thought_signature_validator";
71
72/// The prefix of a stop reason that means the provider ended the reply itself
73/// (`stopped:SAFETY`); the loop announces it and does not ask again.
74pub const STOPPED_PREFIX: &str = "stopped:";
75
76/// How much of an error body is kept.
77const ERROR_BODY_LIMIT: usize = 2000;
78
79/// Calls remembered before those no longer in the history are dropped.
80const REMEMBERED_CALLS: usize = 4096;
81
82/// What the adapter keeps about a call Gemini made.
83#[derive(Debug, Clone, PartialEq, Eq)]
84struct CallMeta {
85    signature: Option<String>,
86    /// The id is Google's, so it goes back with the call and its response.
87    google_id: bool,
88}
89
90/// Settings from `[providers.google]` this adapter uses.
91#[derive(Debug, Clone, PartialEq)]
92pub struct GoogleConfig {
93    pub base_url: Option<String>,
94    pub api_key_env: String,
95    /// The section name, which is also the keyring account.
96    pub config_name: String,
97    pub max_tokens: Option<u32>,
98    pub connect_timeout: Duration,
99    /// The longest gap between streamed chunks.
100    pub read_timeout: Duration,
101    pub max_retries: u32,
102    /// Let Google keep the requests (`store`); off unless the section says so.
103    pub store: bool,
104}
105
106impl Default for GoogleConfig {
107    fn default() -> Self {
108        Self {
109            base_url: None,
110            api_key_env: DEFAULT_API_KEY_ENV.to_owned(),
111            config_name: "google".to_owned(),
112            max_tokens: None,
113            connect_timeout: Duration::from_secs(10),
114            read_timeout: Duration::from_secs(1200),
115            max_retries: super::retry::DEFAULT_MAX_RETRIES,
116            store: false,
117        }
118    }
119}
120
121pub struct GoogleProvider {
122    model: String,
123    url: String,
124    api_key: String,
125    config: GoogleConfig,
126    client: reqwest::Client,
127    pricing: PriceTable,
128    price_ref: String,
129    /// Each call's signature and id kind, by call id, for sending the step back.
130    calls: Mutex<HashMap<String, CallMeta>>,
131    /// For ids made up for calls Gemini sent without one (Gemini 2.5).
132    next_id: AtomicU64,
133}
134
135impl fmt::Debug for GoogleProvider {
136    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
137        formatter
138            .debug_struct("GoogleProvider")
139            .field("model", &self.model)
140            .field("url", &self.url)
141            .field("api_key", &"***redacted***")
142            .field("config", &self.config)
143            .finish()
144    }
145}
146
147impl GoogleProvider {
148    pub fn new(
149        model: impl Into<String>,
150        config: GoogleConfig,
151        api_key: Option<String>,
152    ) -> Result<Self, ProviderError> {
153        let Some(api_key) = api_key.filter(|key| !key.is_empty()) else {
154            return Err(ProviderError::MissingApiKey {
155                env: config.api_key_env.clone(),
156                account: config.config_name.clone(),
157            });
158        };
159        let model = model.into();
160        // `models/gemini-...`, as Google's own list names them, is the same model.
161        let bare = model.strip_prefix("models/").unwrap_or(&model).to_owned();
162        let base = config
163            .base_url
164            .as_deref()
165            .unwrap_or(DEFAULT_BASE_URL)
166            .trim_end_matches('/');
167        let url = format!("{base}/models/{bare}:streamGenerateContent?alt=sse");
168        let client = build_client(&config)?;
169        Ok(Self {
170            price_ref: bare.clone(),
171            model: bare,
172            url,
173            api_key,
174            config,
175            client,
176            pricing: PriceTable::builtin(),
177            calls: Mutex::new(HashMap::new()),
178            next_id: AtomicU64::new(0),
179        })
180    }
181
182    /// Price usage with `pricing`, looked up under `price_ref` (the full ref).
183    pub fn with_pricing(mut self, pricing: PriceTable, price_ref: impl Into<String>) -> Self {
184        self.pricing = pricing;
185        self.price_ref = price_ref.into();
186        self
187    }
188
189    /// The streaming endpoint, which never carries the key.
190    pub fn url(&self) -> &str {
191        &self.url
192    }
193
194    /// The `generateContent` body for `request`.
195    pub fn payload(&self, request: &CompletionRequest) -> Value {
196        self.prepare(request).0
197    }
198
199    /// The body, and the declared name of each renamed tool to its own name.
200    fn prepare(&self, request: &CompletionRequest) -> (Value, HashMap<String, String>) {
201        let mut declared: HashMap<String, String> = HashMap::new();
202        let mut taken: Vec<String> = request.tools.iter().map(|tool| tool.name.clone()).collect();
203        let mut rename = |name: &str| -> String {
204            if let Some(known) = declared.get(name) {
205                return known.clone();
206            }
207            let wire = gemini_name(name, &taken);
208            if wire != name {
209                taken.push(wire.clone());
210            }
211            declared.insert(name.to_owned(), wire.clone());
212            wire
213        };
214        let declarations: Vec<Value> = request
215            .tools
216            .iter()
217            .map(|tool| {
218                json!({
219                    "name": rename(&tool.name),
220                    "description": tool.description,
221                    "parametersJsonSchema": tool.parameters,
222                })
223            })
224            .collect();
225        let calls = {
226            let mut calls = self.calls.lock().unwrap_or_else(|p| p.into_inner());
227            if calls.len() > REMEMBERED_CALLS {
228                let live: std::collections::HashSet<&str> = request
229                    .messages
230                    .iter()
231                    .flat_map(|message| message.tool_calls.iter().map(|call| call.id.as_str()))
232                    .collect();
233                calls.retain(|id, _| live.contains(id.as_str()));
234            }
235            calls.clone()
236        };
237        let (system, contents) = to_contents_with(&request.messages, &calls, &mut rename);
238        let mut generation = json!({"thinkingConfig": {"includeThoughts": true}});
239        let cap = request
240            .max_tokens
241            .filter(|&cap| cap > 0)
242            .or(self.config.max_tokens.filter(|&cap| cap > 0));
243        if let Some(cap) = cap {
244            generation["maxOutputTokens"] = json!(cap);
245        }
246        let mut body = json!({
247            "contents": contents,
248            "generationConfig": generation,
249            "store": self.config.store,
250        });
251        if !system.is_empty() {
252            body["systemInstruction"] = json!({"parts": [{"text": system}]});
253        }
254        if !declarations.is_empty() {
255            body["tools"] = json!([{"functionDeclarations": declarations}]);
256            body["toolConfig"] = json!({"functionCallingConfig": {"mode": "AUTO"}});
257        }
258        let back = declared
259            .into_iter()
260            .filter(|(own, wire)| own != wire)
261            .map(|(own, wire)| (wire, own))
262            .collect();
263        (body, back)
264    }
265
266    fn redact(&self, text: &str) -> String {
267        redact(text, &[self.api_key.as_str()])
268    }
269
270    fn http_error(&self, status: u16, body: &str) -> ProviderError {
271        let body: String = self
272            .redact(body.trim())
273            .chars()
274            .take(ERROR_BODY_LIMIT)
275            .collect();
276        match status {
277            400 if body.contains("thought_signature") => ProviderError::HttpHint {
278                status,
279                body,
280                hint: "agent86 sent back a tool call without the signature Gemini gave it; \
281                       this is a bug, please report it at \
282                       https://github.com/Maetek-Technologies/agent86/issues"
283                    .to_owned(),
284            },
285            402 => ProviderError::HttpHint {
286                status,
287                body,
288                hint: "the Google project's prepaid credits are used up; add credits in \
289                       Google AI Studio's billing settings"
290                    .to_owned(),
291            },
292            _ => ProviderError::Http { status, body },
293        }
294    }
295
296    fn connect_error(&self, error: &reqwest::Error) -> ProviderError {
297        if error.is_timeout() && error.is_connect() {
298            ProviderError::ConnectTimeout {
299                endpoint: self.url.clone(),
300                seconds: self.config.connect_timeout.as_secs_f64(),
301            }
302        } else if error.is_timeout() {
303            ProviderError::ReadTimeout {
304                endpoint: self.url.clone(),
305                seconds: self.config.read_timeout.as_secs_f64(),
306            }
307        } else if error.is_connect() {
308            ProviderError::Connect {
309                endpoint: self.url.clone(),
310                detail: self.redact(&error_chain(error)),
311            }
312        } else {
313            ProviderError::StreamInterrupted {
314                provider: "google".to_owned(),
315                endpoint: self.url.clone(),
316                model: self.model.clone(),
317                detail: self.redact(&error_chain(error)),
318            }
319        }
320    }
321}
322
323fn build_client(config: &GoogleConfig) -> Result<reqwest::Client, ProviderError> {
324    reqwest::Client::builder()
325        .connect_timeout(config.connect_timeout)
326        .read_timeout(config.read_timeout)
327        .build()
328        .map_err(|error| ProviderError::Client {
329            detail: error_chain(&error),
330        })
331}
332
333impl Provider for GoogleProvider {
334    fn name(&self) -> &str {
335        "google"
336    }
337
338    fn model(&self) -> &str {
339        &self.model
340    }
341
342    fn fresh(&self) -> Result<std::sync::Arc<dyn Provider>, ProviderError> {
343        Ok(std::sync::Arc::new(Self {
344            model: self.model.clone(),
345            url: self.url.clone(),
346            api_key: self.api_key.clone(),
347            config: self.config.clone(),
348            client: build_client(&self.config)?,
349            pricing: self.pricing.clone(),
350            price_ref: self.price_ref.clone(),
351            calls: Mutex::new(self.calls.lock().unwrap_or_else(|p| p.into_inner()).clone()),
352            next_id: AtomicU64::new(self.next_id.load(Ordering::Relaxed)),
353        }))
354    }
355
356    fn stream(&self, request: CompletionRequest) -> DeltaStream<'_> {
357        let (body, names) = self.prepare(&request);
358        let state = StreamState {
359            provider: self,
360            body: body.to_string(),
361            names,
362            policy: RetryPolicy::new(self.config.max_retries),
363            response: None,
364            buffer: Vec::new(),
365            pending: VecDeque::new(),
366            turn: TurnState::default(),
367            finished: false,
368        };
369        Box::pin(futures_util::stream::unfold(
370            state,
371            |mut state| async move {
372                let item = state.next_delta().await?;
373                Some((item, state))
374            },
375        ))
376    }
377}
378
379/// The system text and the `contents` for `messages`.
380///
381/// System messages become `systemInstruction`, in order. User turns are `user`
382/// contents and assistant turns `model` contents, an assistant's tool calls as
383/// `functionCall` parts. The results that follow a step are `functionResponse`
384/// parts in one `user` content, in call order, after all of the step's calls, as
385/// Google requires. Consecutive contents of one role are merged by joining their
386/// part lists, never by joining parts, so a signed part stays apart. A model
387/// content's first function call carries [`SKIP_SIGNATURE`], as there is no
388/// signature kept for any call here; see [`GoogleProvider`] for the calls it made.
389pub fn to_contents(messages: &[Message]) -> (String, Vec<Value>) {
390    to_contents_with(messages, &HashMap::new(), &mut |name: &str| name.to_owned())
391}
392
393/// [`to_contents`] with the calls Gemini made (their signatures go back on their
394/// own parts, with Google's ids) and the declared name of each tool. A step none
395/// of whose calls has a signature kept gets the placeholder on its first call.
396fn to_contents_with(
397    messages: &[Message],
398    calls: &HashMap<String, CallMeta>,
399    rename: &mut dyn FnMut(&str) -> String,
400) -> (String, Vec<Value>) {
401    let mut system: Vec<&str> = Vec::new();
402    let mut contents: Vec<(String, Vec<Value>)> = Vec::new();
403    let mut names: HashMap<&str, &str> = HashMap::new();
404    let mut push = |role: &str, parts: Vec<Value>| {
405        if parts.is_empty() {
406            return;
407        }
408        match contents.last_mut() {
409            Some((last, existing)) if last == role => existing.extend(parts),
410            _ => contents.push((role.to_owned(), parts)),
411        }
412    };
413    for message in messages {
414        match message.role {
415            Role::System => {
416                if !message.content.trim().is_empty() {
417                    system.push(&message.content);
418                }
419            }
420            Role::User => {
421                let parts = text_part(&message.content).into_iter().collect();
422                push("user", parts);
423            }
424            Role::Assistant => {
425                let mut parts: Vec<Value> = text_part(&message.content).into_iter().collect();
426                let signed = message.tool_calls.iter().any(|call| {
427                    calls
428                        .get(&call.id)
429                        .is_some_and(|meta| meta.signature.is_some())
430                });
431                for (index, call) in message.tool_calls.iter().enumerate() {
432                    names.insert(call.id.as_str(), call.name.as_str());
433                    let args = call.replay_arguments().into_owned();
434                    let meta = calls.get(&call.id);
435                    let mut function = json!({"name": rename(&call.name), "args": args});
436                    if meta.is_some_and(|meta| meta.google_id) {
437                        function["id"] = json!(call.id);
438                    }
439                    let mut part = json!({"functionCall": function});
440                    match meta.and_then(|meta| meta.signature.as_deref()) {
441                        Some(signature) => part["thoughtSignature"] = json!(signature),
442                        None if index == 0 && !signed => {
443                            part["thoughtSignature"] = json!(SKIP_SIGNATURE);
444                        }
445                        None => {}
446                    }
447                    parts.push(part);
448                }
449                push("model", parts);
450            }
451            Role::Tool => {
452                let name = message
453                    .name
454                    .as_deref()
455                    .or_else(|| {
456                        message
457                            .tool_call_id
458                            .as_deref()
459                            .and_then(|id| names.get(id).copied())
460                    })
461                    .unwrap_or("tool");
462                let mut response = json!({
463                    "name": rename(name),
464                    "response": {"result": message.content},
465                });
466                if let Some(id) = message
467                    .tool_call_id
468                    .as_deref()
469                    .filter(|id| calls.get(*id).is_some_and(|meta| meta.google_id))
470                {
471                    response["id"] = json!(id);
472                }
473                push("user", vec![json!({ "functionResponse": response })]);
474            }
475        }
476    }
477    let contents = contents
478        .into_iter()
479        .map(|(role, parts)| json!({"role": role, "parts": parts}))
480        .collect();
481    (system.join("\n\n"), contents)
482}
483
484fn text_part(text: &str) -> Option<Value> {
485    (!text.is_empty()).then(|| json!({"text": text}))
486}
487
488/// The name a tool is declared under: its own when Gemini takes it (a letter or
489/// `_` first, then letters, digits, `_`, `.`, `:`, `-`, at most 128), else with a
490/// `_` in front, more while that is taken by another tool in `taken`.
491pub fn gemini_name(name: &str, taken: &[String]) -> String {
492    let starts_well = name
493        .chars()
494        .next()
495        .is_some_and(|ch| ch.is_ascii_alphabetic() || ch == '_');
496    if starts_well {
497        return name.to_owned();
498    }
499    let mut wire = format!("_{name}");
500    while taken.contains(&wire) {
501        wire.insert(0, '_');
502    }
503    wire
504}
505
506/// What a `finishReason` (or a blocked prompt's `blockReason`) means for the turn.
507pub fn stop_reason(reason: Option<&str>, has_tool_calls: bool) -> Option<String> {
508    let wire = |reason: StopReason| {
509        serde_json::to_value(reason)
510            .ok()
511            .and_then(|value| value.as_str().map(str::to_owned))
512    };
513    match reason {
514        None if has_tool_calls => wire(StopReason::ToolUse),
515        None => None,
516        Some("STOP") if has_tool_calls => wire(StopReason::ToolUse),
517        Some("STOP") => wire(StopReason::EndTurn),
518        // A Gemini 4 reply cut at its per-request cap ends with either.
519        Some("MAX_TOKENS" | "CONTINUATION") => wire(StopReason::MaxTokens),
520        Some(other) => Some(format!("{STOPPED_PREFIX}{other}")),
521    }
522}
523
524/// Accumulators for one attempt; a retry starts over.
525#[derive(Default)]
526struct TurnState {
527    text: String,
528    thinking: String,
529    tool_calls: Vec<ToolCall>,
530    input_tokens: u64,
531    output_tokens: u64,
532    cached_tokens: u64,
533    finish_reason: Option<String>,
534    emitted: bool,
535}
536
537struct StreamState<'a> {
538    provider: &'a GoogleProvider,
539    body: String,
540    /// Declared name to the tool's own, for renamed tools.
541    names: HashMap<String, String>,
542    policy: RetryPolicy,
543    response: Option<reqwest::Response>,
544    buffer: Vec<u8>,
545    pending: VecDeque<CompletionDelta>,
546    turn: TurnState,
547    finished: bool,
548}
549
550impl StreamState<'_> {
551    async fn next_delta(&mut self) -> Option<Result<CompletionDelta, ProviderError>> {
552        if let Some(delta) = self.pending.pop_front() {
553            return Some(Ok(delta));
554        }
555        if self.finished {
556            return None;
557        }
558        let result = self.advance().await;
559        if result.is_err() {
560            self.finished = true;
561            self.response = None;
562        }
563        result.map(|()| self.pending.pop_front()).transpose()
564    }
565
566    async fn advance(&mut self) -> Result<(), ProviderError> {
567        while self.pending.is_empty() && !self.finished {
568            if self.response.is_none() {
569                self.response = Some(self.connect().await?);
570            }
571            if let Some(line) = self.take_line() {
572                self.handle_line(&line)?;
573                continue;
574            }
575            let Some(response) = self.response.as_mut() else {
576                continue;
577            };
578            match response.chunk().await {
579                Ok(Some(bytes)) => self.buffer.extend_from_slice(&bytes),
580                Ok(None) => {
581                    if !self.buffer.is_empty() {
582                        let line = std::mem::take(&mut self.buffer);
583                        self.handle_line(&line)?;
584                    }
585                    self.finish();
586                }
587                Err(error) => {
588                    let failure = self.provider.connect_error(&error);
589                    let retryable = !matches!(failure, ProviderError::ReadTimeout { .. });
590                    match self.policy.next_delay(self.turn.emitted, None) {
591                        Some(delay) if retryable => {
592                            tokio::time::sleep(delay).await;
593                            self.response = None;
594                            self.turn = TurnState::default();
595                        }
596                        _ => return Err(failure),
597                    }
598                }
599            }
600        }
601        Ok(())
602    }
603
604    async fn connect(&mut self) -> Result<reqwest::Response, ProviderError> {
605        let provider = self.provider;
606        loop {
607            let request = provider
608                .client
609                .post(&provider.url)
610                .header(reqwest::header::CONTENT_TYPE, "application/json")
611                .header("x-goog-api-key", &provider.api_key)
612                .body(self.body.clone());
613            let response = match request.send().await {
614                Ok(response) => response,
615                Err(error) => {
616                    let failure = provider.connect_error(&error);
617                    let retryable = matches!(
618                        failure,
619                        ProviderError::Connect { .. }
620                            | ProviderError::ConnectTimeout { .. }
621                            | ProviderError::StreamInterrupted { .. }
622                    );
623                    match self.policy.next_delay(false, None) {
624                        Some(delay) if retryable => {
625                            tokio::time::sleep(delay).await;
626                            continue;
627                        }
628                        _ => return Err(failure),
629                    }
630                }
631            };
632            let status = response.status().as_u16();
633            if status == 200 {
634                return Ok(response);
635            }
636            let retry_after = response
637                .headers()
638                .get(reqwest::header::RETRY_AFTER)
639                .and_then(|value| value.to_str().ok())
640                .and_then(parse_retry_after);
641            let body = response.text().await.unwrap_or_default();
642            if is_retryable_status(status) {
643                if let Some(delay) = self.policy.next_delay(false, retry_after) {
644                    tokio::time::sleep(delay).await;
645                    continue;
646                }
647            }
648            return Err(provider.http_error(status, &body));
649        }
650    }
651
652    fn take_line(&mut self) -> Option<Vec<u8>> {
653        let end = self.buffer.iter().position(|&byte| byte == b'\n')?;
654        let mut line: Vec<u8> = self.buffer.drain(..=end).collect();
655        line.pop();
656        Some(line)
657    }
658
659    fn handle_line(&mut self, line: &[u8]) -> Result<(), ProviderError> {
660        let line = String::from_utf8_lossy(line);
661        let line = line.trim_end_matches('\r');
662        let Some(data) = line.strip_prefix("data:") else {
663            return Ok(());
664        };
665        let data = data.trim();
666        if data.is_empty() {
667            return Ok(());
668        }
669        let chunk: Value =
670            serde_json::from_str(data).map_err(|error| ProviderError::MalformedChunk {
671                provider: "google".to_owned(),
672                endpoint: self.provider.url.clone(),
673                model: self.provider.model.clone(),
674                detail: error.to_string(),
675            })?;
676        if let Some(error) = chunk.get("error").filter(|error| error.is_object()) {
677            let status = error
678                .get("code")
679                .and_then(Value::as_u64)
680                .and_then(|code| u16::try_from(code).ok())
681                .unwrap_or(500);
682            return Err(self.provider.http_error(status, data));
683        }
684        if let Some(usage) = chunk.get("usageMetadata") {
685            let count = |key: &str| usage.get(key).and_then(Value::as_u64).unwrap_or(0);
686            // Thinking is billed as output; tool-use prompts as input.
687            self.turn.input_tokens = count("promptTokenCount") + count("toolUsePromptTokenCount");
688            self.turn.output_tokens = count("candidatesTokenCount") + count("thoughtsTokenCount");
689            self.turn.cached_tokens = count("cachedContentTokenCount");
690        }
691        if let Some(reason) = chunk
692            .pointer("/promptFeedback/blockReason")
693            .and_then(Value::as_str)
694        {
695            self.turn.finish_reason = Some(reason.to_owned());
696        }
697        let candidate = chunk.pointer("/candidates/0");
698        let parts = candidate
699            .and_then(|candidate| candidate.pointer("/content/parts"))
700            .and_then(Value::as_array);
701        for part in parts.into_iter().flatten() {
702            self.part(part);
703        }
704        if let Some(reason) = candidate
705            .and_then(|candidate| candidate.get("finishReason"))
706            .and_then(Value::as_str)
707        {
708            if reason == "MALFORMED_FUNCTION_CALL" {
709                // The model is told its call was malformed, as other adapters do
710                // with bad JSON, when the response carries the call's text.
711                if let Some(message) = candidate
712                    .and_then(|candidate| candidate.get("finishMessage"))
713                    .and_then(Value::as_str)
714                {
715                    let mut arguments = Map::new();
716                    arguments.insert(INVALID_TOOL_ARGS_KEY.to_owned(), json!(message));
717                    let n = self.provider.next_id.fetch_add(1, Ordering::Relaxed);
718                    let id = format!("call_g{n}");
719                    self.turn.tool_calls.push(ToolCall {
720                        id,
721                        name: "unknown".to_owned(),
722                        arguments,
723                    });
724                }
725            }
726            self.turn.finish_reason = Some(reason.to_owned());
727        }
728        Ok(())
729    }
730
731    fn part(&mut self, part: &Value) {
732        if let Some(call) = part.get("functionCall") {
733            let wire = call.get("name").and_then(Value::as_str).unwrap_or_default();
734            let name = self.names.get(wire).map_or(wire, String::as_str).to_owned();
735            let arguments = call
736                .get("args")
737                .and_then(Value::as_object)
738                .cloned()
739                .unwrap_or_default();
740            let google = call
741                .get("id")
742                .and_then(Value::as_str)
743                .filter(|id| !id.is_empty());
744            let id = google.map_or_else(
745                || {
746                    let n = self.provider.next_id.fetch_add(1, Ordering::Relaxed);
747                    format!("call_g{n}")
748                },
749                str::to_owned,
750            );
751            let meta = CallMeta {
752                signature: part
753                    .get("thoughtSignature")
754                    .and_then(Value::as_str)
755                    .filter(|signature| !signature.is_empty())
756                    .map(str::to_owned),
757                google_id: google.is_some(),
758            };
759            self.provider
760                .calls
761                .lock()
762                .unwrap_or_else(|p| p.into_inner())
763                .insert(id.clone(), meta);
764            self.turn.tool_calls.push(ToolCall {
765                id,
766                name,
767                arguments,
768            });
769            return;
770        }
771        let Some(text) = part.get("text").and_then(Value::as_str) else {
772            return;
773        };
774        if text.is_empty() {
775            return;
776        }
777        let thought = part.get("thought").and_then(Value::as_bool) == Some(true);
778        self.turn.emitted = true;
779        if thought {
780            self.turn.thinking.push_str(text);
781            self.pending.push_back(CompletionDelta {
782                thinking: text.to_owned(),
783                ..CompletionDelta::default()
784            });
785        } else {
786            self.turn.text.push_str(text);
787            self.pending.push_back(CompletionDelta {
788                text: text.to_owned(),
789                ..CompletionDelta::default()
790            });
791        }
792    }
793
794    fn finish(&mut self) {
795        self.finished = true;
796        self.response = None;
797        let turn = std::mem::take(&mut self.turn);
798        let has_calls = !turn.tool_calls.is_empty();
799        let usage = Usage {
800            input_tokens: turn.input_tokens,
801            output_tokens: turn.output_tokens,
802            cache_read_tokens: turn.cached_tokens,
803            ..Usage::default()
804        };
805        self.pending.push_back(CompletionDelta {
806            done: true,
807            completion: Some(Completion {
808                text: turn.text,
809                tool_calls: turn.tool_calls,
810                usage: self
811                    .provider
812                    .pricing
813                    .priced_usage(&self.provider.price_ref, usage),
814                stop_reason: stop_reason(turn.finish_reason.as_deref(), has_calls),
815                model: Some(self.provider.model.clone()),
816                thinking: turn.thinking,
817            }),
818            ..CompletionDelta::default()
819        });
820    }
821}
822
823#[cfg(test)]
824mod tests {
825    use super::*;
826    use crate::types::Role;
827
828    fn message(role: Role, content: &str) -> Message {
829        Message {
830            role,
831            content: content.to_owned(),
832            tool_calls: Vec::new(),
833            tool_call_id: None,
834            name: None,
835        }
836    }
837
838    #[test]
839    fn names_gemini_refuses_get_an_underscore_and_stay_unique() {
840        let taken = vec!["_1tool".to_owned()];
841        assert_eq!(gemini_name("read_file", &taken), "read_file");
842        assert_eq!(gemini_name("_private", &taken), "_private");
843        assert_eq!(gemini_name("1password-get", &taken), "_1password-get");
844        assert_eq!(gemini_name("-dash", &taken), "_-dash");
845        assert_eq!(gemini_name("1tool", &taken), "__1tool", "past a taken name");
846    }
847
848    #[test]
849    fn finish_reasons_map_and_the_rest_stop_the_turn() {
850        assert_eq!(
851            stop_reason(Some("STOP"), false).as_deref(),
852            Some("end_turn")
853        );
854        assert_eq!(stop_reason(Some("STOP"), true).as_deref(), Some("tool_use"));
855        assert_eq!(stop_reason(None, true).as_deref(), Some("tool_use"));
856        assert_eq!(stop_reason(None, false), None);
857        for cut in ["MAX_TOKENS", "CONTINUATION"] {
858            assert_eq!(stop_reason(Some(cut), false).as_deref(), Some("max_tokens"));
859        }
860        for stopped in [
861            "SAFETY",
862            "RECITATION",
863            "PROHIBITED_CONTENT",
864            "OTHER",
865            "SOMETHING_NEW",
866        ] {
867            assert_eq!(
868                stop_reason(Some(stopped), false),
869                Some(format!("stopped:{stopped}"))
870            );
871        }
872    }
873
874    #[test]
875    fn contents_merge_by_role_and_keep_calls_before_their_results() {
876        let mut assistant = message(Role::Assistant, "Looking.");
877        assistant.tool_calls = vec![
878            ToolCall {
879                id: "a".into(),
880                name: "read_file".into(),
881                arguments: json!({"path": "x"}).as_object().unwrap().clone(),
882            },
883            ToolCall {
884                id: "b".into(),
885                name: "list_dir".into(),
886                arguments: Map::new(),
887            },
888        ];
889        let mut first = message(Role::Tool, "contents of x");
890        first.tool_call_id = Some("a".into());
891        first.name = Some("read_file".into());
892        let mut second = message(Role::Tool, "a b c");
893        second.tool_call_id = Some("b".into());
894        let (system, contents) = to_contents(&[
895            message(Role::System, "You are a test."),
896            message(Role::User, "Hi"),
897            message(Role::User, "again"),
898            assistant,
899            first,
900            second,
901        ]);
902        assert_eq!(system, "You are a test.");
903        assert_eq!(
904            Value::Array(contents),
905            json!([
906                {"role": "user", "parts": [{"text": "Hi"}, {"text": "again"}]},
907                {"role": "model", "parts": [
908                    {"text": "Looking."},
909                    {"functionCall": {"name": "read_file", "args": {"path": "x"}},
910                     "thoughtSignature": SKIP_SIGNATURE},
911                    {"functionCall": {"name": "list_dir", "args": {}}},
912                ]},
913                {"role": "user", "parts": [
914                    {"functionResponse": {"name": "read_file", "response": {"result": "contents of x"}}},
915                    {"functionResponse": {"name": "list_dir", "response": {"result": "a b c"}}},
916                ]},
917            ])
918        );
919    }
920}