Skip to main content

adk_model/gemini/
client.rs

1use crate::attachment;
2use crate::retry::{RetryConfig, execute_with_retry, is_retryable_model_error};
3use adk_core::{
4    CacheCapable, CitationMetadata, CitationSource, Content, ErrorCategory, ErrorComponent,
5    FinishReason, Llm, LlmRequest, LlmResponse, LlmResponseStream, Part, Result, SchemaAdapter,
6    SchemaCache, UsageMetadata,
7};
8use adk_gemini::Gemini;
9use adk_gemini::schema_adapter::GeminiSchemaAdapter;
10use async_trait::async_trait;
11use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
12use futures::TryStreamExt;
13
14#[cfg(feature = "gemini-interactions")]
15use super::interactions_target::InteractionTarget;
16
17/// Which Gemini wire API a [`GeminiModel`] uses.
18///
19/// Defaults to [`GeminiTransport::GenerateContent`], the classic
20/// `models/{model}:generateContent` endpoint. Selecting
21/// [`GeminiTransport::Interactions`] (via [`GeminiModel::use_interactions_api`])
22/// routes requests through the Interactions API (Beta): a stateful, step-based
23/// transport that drives the same [`adk_core::Llm`] contract.
24///
25/// Only compiled when the `gemini-interactions` feature is enabled.
26#[cfg(feature = "gemini-interactions")]
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
28pub enum GeminiTransport {
29    /// The classic `models/{model}:generateContent` API (default).
30    #[default]
31    GenerateContent,
32    /// The Interactions API (Beta): stateful, step-based.
33    Interactions,
34}
35
36/// Background-execution policy for the Interactions transport.
37///
38/// Controls whether interactions run with `background=true`. The default,
39/// [`BackgroundMode::AgentTargetsOnly`], keeps low-latency chat turns
40/// foreground while letting long-running agent targets (e.g. Deep Research)
41/// run in the background.
42///
43/// Only compiled when the `gemini-interactions` feature is enabled.
44#[cfg(feature = "gemini-interactions")]
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
46pub enum BackgroundMode {
47    /// `background=true` for agent targets, `false` for model targets
48    /// (default). Keeps chat turns low-latency while letting Deep Research and
49    /// other long-running agents run in the background.
50    #[default]
51    AgentTargetsOnly,
52    /// Always run interactions with `background=true`.
53    Always,
54    /// Never run interactions in the background.
55    Never,
56}
57
58/// Faithful-to-API options for the Interactions transport.
59///
60/// The defaults mirror the Interactions API's intended posture: interactions
61/// are stored (`store = true`), stateful continuation via
62/// `previous_interaction_id` is enabled (`stateful = true`), background
63/// execution applies to agent targets only
64/// ([`BackgroundMode::AgentTargetsOnly`]), and background interactions are
65/// polled once per second.
66///
67/// Only compiled when the `gemini-interactions` feature is enabled.
68#[cfg(feature = "gemini-interactions")]
69#[derive(Debug, Clone)]
70pub struct InteractionOptions {
71    /// Whether interactions are stored server-side. Default: `true`.
72    pub store: bool,
73    /// Whether to continue conversations statefully via
74    /// `previous_interaction_id`. Default: `true`.
75    pub stateful: bool,
76    /// Background-execution policy. Default: [`BackgroundMode::AgentTargetsOnly`].
77    pub background: BackgroundMode,
78    /// Poll interval for background interactions. Default: 1 second.
79    pub poll_interval: std::time::Duration,
80}
81
82#[cfg(feature = "gemini-interactions")]
83impl Default for InteractionOptions {
84    fn default() -> Self {
85        Self {
86            store: true,
87            stateful: true,
88            background: BackgroundMode::AgentTargetsOnly,
89            poll_interval: std::time::Duration::from_secs(1),
90        }
91    }
92}
93
94/// A file uploaded through the Gemini File API.
95#[derive(Clone, Debug, PartialEq, Eq)]
96#[non_exhaustive]
97pub struct GeminiFile {
98    /// The resource name, `files/<id>`.
99    pub name: String,
100    /// The URI a `Part::FileData` names.
101    pub uri: String,
102    /// The MIME type Gemini recorded.
103    pub mime_type: Option<String>,
104    /// The size in bytes.
105    pub size_bytes: Option<u64>,
106    /// Whether Gemini has processed it.
107    pub state: GeminiFileState,
108}
109
110impl GeminiFile {
111    fn from_wire(file: &adk_gemini::File) -> Result<Self> {
112        let uri = file.uri.as_ref().map(ToString::to_string).ok_or_else(|| {
113            adk_core::AdkError::model(format!("the File API returned {} without a URI", file.name))
114        })?;
115        Ok(Self {
116            name: file.name.clone(),
117            uri,
118            mime_type: file.mime_type.clone(),
119            size_bytes: file.size_bytes.and_then(|n| u64::try_from(n).ok()),
120            state: match file.state {
121                Some(adk_gemini::FileState::Active) => GeminiFileState::Active,
122                Some(adk_gemini::FileState::Processing) => GeminiFileState::Processing,
123                Some(adk_gemini::FileState::Failed) => GeminiFileState::Failed,
124                _ => GeminiFileState::Unknown,
125            },
126        })
127    }
128}
129
130/// Where Gemini is in processing an uploaded file.
131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
132#[non_exhaustive]
133pub enum GeminiFileState {
134    /// Being processed; a video is not usable yet.
135    Processing,
136    /// Ready to use.
137    Active,
138    /// Processing failed.
139    Failed,
140    /// Not reported, or deleted.
141    Unknown,
142}
143
144/// `true` for a URI Gemini fetches itself: a File API, Cloud Storage or HTTP(S) URI.
145fn is_fetchable_uri(uri: &str) -> bool {
146    let scheme = uri.split_once("://").map(|(s, _)| s.to_ascii_lowercase());
147    matches!(scheme.as_deref(), Some("https" | "http" | "gs"))
148}
149
150/// Gemini model client wrapping the `adk-gemini` crate for the `Llm` trait.
151pub struct GeminiModel {
152    client: Gemini,
153    model_name: String,
154    retry_config: RetryConfig,
155    /// Default thinking configuration applied to every request.
156    ///
157    /// Controls the model's reasoning effort. For Gemini 3 series, use
158    /// `ThinkingLevel` (Low/Medium/High). For Gemini 2.5 series, use
159    /// `thinking_budget` (token count).
160    thinking_config: Option<adk_gemini::ThinkingConfig>,
161    /// Selected wire transport. Defaults to
162    /// [`GeminiTransport::GenerateContent`]; set to
163    /// [`GeminiTransport::Interactions`] via [`GeminiModel::use_interactions_api`].
164    #[cfg(feature = "gemini-interactions")]
165    transport: GeminiTransport,
166    /// The validated Interactions destination, populated when the Interactions
167    /// transport is enabled. `None` for the generateContent transport.
168    #[cfg(feature = "gemini-interactions")]
169    interaction_target: Option<InteractionTarget>,
170    /// Faithful-to-API options for the Interactions transport.
171    #[cfg(feature = "gemini-interactions")]
172    interaction_options: InteractionOptions,
173    /// Server-side RAG grounding declaration attached to every request.
174    /// Vertex AI backend only; see [`GeminiModel::with_vertex_rag_store`].
175    #[cfg(feature = "gemini-vertex")]
176    vertex_rag_store: Option<adk_gemini::VertexRagStore>,
177    /// Whether the wrapped client targets the Vertex AI backend (as opposed
178    /// to AI Studio). Set by the `new_google_cloud*` constructors.
179    #[cfg(feature = "gemini-vertex")]
180    vertex_backend: bool,
181}
182
183/// Built-in tool uses observed across the responses of one Gemini call.
184///
185/// Search is counted per distinct `webSearchQueries` entry, Maps once per grounded
186/// response and code execution per `executableCode` part.
187#[derive(Debug, Default)]
188struct GeminiBuiltinToolUses {
189    search_queries: std::collections::BTreeSet<String>,
190    maps_grounded: bool,
191    code_executions: u32,
192}
193
194impl GeminiBuiltinToolUses {
195    fn observe(&mut self, response: &adk_gemini::GenerationResponse) {
196        let Some(candidate) = response.candidates.first() else {
197            return;
198        };
199        if let Some(grounding) = &candidate.grounding_metadata {
200            self.search_queries.extend(grounding.web_search_queries.iter().flatten().cloned());
201            self.maps_grounded |=
202                grounding.grounding_chunks.iter().flatten().any(|chunk| chunk.maps.is_some());
203        }
204        let executions = candidate
205            .content
206            .parts
207            .iter()
208            .flatten()
209            .filter(|part| matches!(part, adk_gemini::Part::ExecutableCode { .. }))
210            .count();
211        self.code_executions =
212            self.code_executions.saturating_add(u32::try_from(executions).unwrap_or(u32::MAX));
213    }
214
215    fn uses(&self) -> Vec<adk_core::BuiltinToolUse> {
216        let searches = u32::try_from(self.search_queries.len()).unwrap_or(u32::MAX);
217        [
218            ("code_execution", self.code_executions),
219            ("google_maps", u32::from(self.maps_grounded)),
220            ("google_search", searches),
221        ]
222        .into_iter()
223        .filter(|(_, count)| *count > 0)
224        .map(|(kind, count)| adk_core::BuiltinToolUse::new(kind, count))
225        .collect()
226    }
227}
228
229/// Converts a Gemini client error into an [`adk_core::AdkError`] for both the AI Studio
230/// and Vertex AI backends.
231///
232/// The category comes from the HTTP status the transport reported, or, without one,
233/// from the RPC status code or the typed transport failure; error text never decides
234/// it. 500, 502, 503 and other 5xx statuses are `Unavailable` and 504 is `Timeout`, so
235/// all are retried; 403 is `Forbidden`. The provider's own code is kept in
236/// `details.metadata["provider_error_code"]`: the first `ErrorInfo.reason`, then the
237/// error object's string `code`, then its `status`.
238pub(crate) fn gemini_error_to_adk(e: &adk_gemini::ClientError) -> adk_core::AdkError {
239    fn format_error_chain(e: &dyn std::error::Error) -> String {
240        let mut msg = e.to_string();
241        let mut source = e.source();
242        while let Some(s) = source {
243            msg.push_str(": ");
244            msg.push_str(&s.to_string());
245            source = s.source();
246        }
247        msg
248    }
249
250    // A response body can echo the request, so the message quotes a bounded excerpt.
251    let message = format_error_chain(e);
252    let message = adk_core::upstream_excerpt(&message);
253
254    // Response text can mention a different status; only the transport may
255    // establish an upstream HTTP status.
256    let status_code = match e {
257        adk_gemini::ClientError::BadResponse { code, .. } => Some(*code),
258        #[cfg(feature = "gemini-vertex")]
259        adk_gemini::ClientError::GoogleCloudRequest { source } => source.http_status_code(),
260        _ => None,
261    };
262    // An error object inside a successful response reports its own status; the
263    // transport status stays unset.
264    let reported_status = match e {
265        adk_gemini::ClientError::ErrorInResponse { code, .. } => *code,
266        _ => None,
267    };
268    let (category, code) = match status_code.or(reported_status) {
269        Some(401) => (ErrorCategory::Unauthorized, "model.gemini.unauthorized"),
270        Some(403) => (ErrorCategory::Forbidden, "model.gemini.forbidden"),
271        Some(404) => (ErrorCategory::NotFound, "model.gemini.not_found"),
272        Some(408 | 504) => (ErrorCategory::Timeout, "model.gemini.timeout"),
273        Some(429) => (ErrorCategory::RateLimited, "model.gemini.rate_limited"),
274        Some(529) => (ErrorCategory::Unavailable, "model.gemini.overloaded"),
275        Some(400..=499) => (ErrorCategory::InvalidInput, "model.gemini.bad_request"),
276        Some(500..=599) => (ErrorCategory::Unavailable, "model.gemini.unavailable"),
277        _ => error_without_status(e),
278    };
279
280    let mut err = adk_core::AdkError::new(ErrorComponent::Model, category, code, message)
281        .with_provider("gemini");
282    if let Some(status_code) = status_code {
283        err = err.with_upstream_status(status_code);
284    }
285    // One rule for every backend: the first `ErrorInfo.reason`, then the error
286    // object's string `code`, then its `status`.
287    let provider_code = match e {
288        adk_gemini::ClientError::BadResponse { description: Some(body), .. }
289        | adk_gemini::ClientError::ErrorInResponse { description: body, .. } => {
290            crate::error_metadata::code_from_body(body)
291        }
292        #[cfg(feature = "gemini-vertex")]
293        adk_gemini::ClientError::GoogleCloudRequest { source } => {
294            let status = source.status();
295            let reason = status.into_iter().flat_map(|status| &status.details).find_map(|detail| {
296                let detail = serde_json::to_value(detail).ok()?;
297                if !detail["@type"].as_str().is_some_and(crate::error_metadata::is_error_info) {
298                    return None;
299                }
300                detail["reason"].as_str().filter(|reason| !reason.is_empty()).map(str::to_owned)
301            });
302            reason
303                .or_else(|| {
304                    let body = std::str::from_utf8(source.http_payload()?).ok()?;
305                    crate::error_metadata::code_from_body(body)
306                })
307                .or_else(|| {
308                    status
309                        .map(|status| status.code.name())
310                        .filter(|name| *name != "OK")
311                        .map(str::to_owned)
312                })
313        }
314        _ => None,
315    };
316    let err = crate::error_metadata::with_code(err, provider_code.as_deref());
317    let header = match e {
318        adk_gemini::ClientError::BadResponse { retry_after: Some(header), .. } => {
319            crate::retry::parse_retry_after(header)
320        }
321        _ => None,
322    };
323    crate::retry::with_retry_after(err, header.or_else(|| retry_info_delay(e)))
324}
325
326/// The delay a `google.rpc.RetryInfo` detail of the error asks for: the Gemini API reports
327/// the wait a quota needs there (`"retryDelay": "37s"`), not in a `Retry-After` header.
328fn retry_info_delay(error: &adk_gemini::ClientError) -> Option<std::time::Duration> {
329    let details: Vec<serde_json::Value> = match error {
330        adk_gemini::ClientError::BadResponse { description: Some(body), .. }
331        | adk_gemini::ClientError::ErrorInResponse { description: body, .. } => {
332            if body.len() > crate::error_metadata::MAX_BODY_LEN {
333                return None;
334            }
335            let body: serde_json::Value = serde_json::from_str(body).ok()?;
336            let error =
337                body.get("error").or_else(|| body.get(0).and_then(|item| item.get("error")))?;
338            error.get("details")?.as_array()?.clone()
339        }
340        #[cfg(feature = "gemini-vertex")]
341        adk_gemini::ClientError::GoogleCloudRequest { source } => source
342            .status()?
343            .details
344            .iter()
345            .filter_map(|detail| serde_json::to_value(detail).ok())
346            .collect(),
347        _ => return None,
348    };
349    details
350        .iter()
351        .filter(|detail| {
352            detail["@type"].as_str().is_some_and(|kind| kind.ends_with("google.rpc.RetryInfo"))
353        })
354        .find_map(|detail| parse_rpc_duration(detail["retryDelay"].as_str()?))
355}
356
357/// Parses a protobuf `Duration` in its JSON form (`"12s"`, `"1.5s"`), rounded up to whole
358/// milliseconds so a retry never starts early. Negative or malformed values are `None`.
359fn parse_rpc_duration(value: &str) -> Option<std::time::Duration> {
360    let value = value.strip_suffix('s')?;
361    let (seconds, fraction) = value.split_once('.').unwrap_or((value, ""));
362    let digits = |text: &str| text.bytes().all(|byte| byte.is_ascii_digit());
363    if seconds.is_empty() || !digits(seconds) || fraction.len() > 9 || !digits(fraction) {
364        return None;
365    }
366    let nanos: u32 = format!("{fraction:0<9}").parse().ok()?;
367    let delay = std::time::Duration::new(seconds.parse().ok()?, nanos);
368    let millis = u64::try_from(delay.as_nanos().div_ceil(1_000_000)).ok()?;
369    Some(std::time::Duration::from_millis(millis))
370}
371
372/// Whether a google-cloud-gax error without a status is a failed connection or
373/// transport. gax's `is_connect`/`is_transport` are hidden and outside its semver
374/// guarantee, so this reads the prefixes its `Display` writes for those kinds.
375#[cfg(feature = "gemini-vertex")]
376fn is_gax_connection_failure(message: &str) -> bool {
377    message.starts_with("cannot connect to endpoint")
378        || message.starts_with("the transport reports an error")
379}
380
381/// Classify failures with no HTTP response without inventing an upstream status.
382fn error_without_status(error: &adk_gemini::ClientError) -> (ErrorCategory, &'static str) {
383    if let Some(error) = error.request_error() {
384        let category = crate::http_timeouts::transport_category(error);
385        let code = if category == ErrorCategory::Timeout {
386            "model.gemini.timeout"
387        } else {
388            "model.gemini.unavailable"
389        };
390        return (category, code);
391    }
392    match error {
393        adk_gemini::ClientError::InvalidGenerationConfig { .. } => {
394            (ErrorCategory::InvalidInput, "model.gemini.invalid_config")
395        }
396        adk_gemini::ClientError::Validation { .. } => {
397            (ErrorCategory::InvalidInput, "model.gemini.bad_request")
398        }
399        adk_gemini::ClientError::InvalidApiKey { .. } => {
400            (ErrorCategory::Unauthorized, "model.gemini.unauthorized")
401        }
402        #[cfg(feature = "gemini-vertex")]
403        adk_gemini::ClientError::GoogleCloudRequest { source } if source.is_timeout() => {
404            (ErrorCategory::Timeout, "model.gemini.timeout")
405        }
406        #[cfg(feature = "gemini-vertex")]
407        adk_gemini::ClientError::GoogleCloudRequest { source } => {
408            if let Some(status) = source.status() {
409                category_for_rpc_status(status.code.name())
410            } else if is_gax_connection_failure(&source.to_string()) {
411                (ErrorCategory::Unavailable, "model.gemini.unavailable")
412            } else {
413                (ErrorCategory::Internal, "model.gemini.internal")
414            }
415        }
416        adk_gemini::ClientError::ErrorInResponse { status: Some(status), .. } => {
417            category_for_rpc_status(status)
418        }
419        _ => (ErrorCategory::Internal, "model.gemini.internal"),
420    }
421}
422
423/// Classifies a Google RPC status name such as `UNAVAILABLE`.
424fn category_for_rpc_status(name: &str) -> (ErrorCategory, &'static str) {
425    match name {
426        "RESOURCE_EXHAUSTED" => (ErrorCategory::RateLimited, "model.gemini.rate_limited"),
427        "UNAVAILABLE" => (ErrorCategory::Unavailable, "model.gemini.unavailable"),
428        "DEADLINE_EXCEEDED" => (ErrorCategory::Timeout, "model.gemini.timeout"),
429        "UNAUTHENTICATED" => (ErrorCategory::Unauthorized, "model.gemini.unauthorized"),
430        "PERMISSION_DENIED" => (ErrorCategory::Forbidden, "model.gemini.forbidden"),
431        "NOT_FOUND" => (ErrorCategory::NotFound, "model.gemini.not_found"),
432        "INVALID_ARGUMENT" => (ErrorCategory::InvalidInput, "model.gemini.bad_request"),
433        _ => (ErrorCategory::Internal, "model.gemini.internal"),
434    }
435}
436
437/// Maps a terminal [`InteractionStatus`](adk_gemini::interactions::InteractionStatus)
438/// to a `Result`, surfacing the API's failure states as errors.
439///
440/// The Interactions API can terminate an interaction in `failed` or
441/// `budget_exceeded` (Requirements 7.7 / 9.2). This helper converts those two
442/// states into an [`adk_core::AdkError`] (provider `"gemini"`, category
443/// [`ErrorCategory::Internal`]) and treats every other status as success — the
444/// caller has already decided to read the interaction's content for non-failure
445/// states. Factored out as a free function so the terminal-status mapping is
446/// unit-testable without a network round-trip.
447#[cfg(feature = "gemini-interactions")]
448fn interaction_status_to_result(status: adk_gemini::interactions::InteractionStatus) -> Result<()> {
449    use adk_gemini::interactions::InteractionStatus;
450    match status {
451        InteractionStatus::Failed => Err(interaction_terminal_error(
452            "model.gemini.interactions.failed",
453            "the Gemini interaction terminated with status `failed`",
454        )),
455        InteractionStatus::BudgetExceeded => Err(interaction_terminal_error(
456            "model.gemini.interactions.budget_exceeded",
457            "the Gemini interaction terminated with status `budget_exceeded`",
458        )),
459        InteractionStatus::RequiresContinuation => {
460            tracing::warn!(
461                "gemini interaction stopped at its per-request output cap with token budget left; \
462                 no continuation request is sent, so the turn ends with finish reason MaxTokens"
463            );
464            Ok(())
465        }
466        InteractionStatus::InProgress
467        | InteractionStatus::RequiresAction
468        | InteractionStatus::Completed
469        | InteractionStatus::Cancelled
470        | InteractionStatus::Incomplete
471        | InteractionStatus::Unknown => Ok(()),
472        _ => Ok(()),
473    }
474}
475
476/// Builds the [`adk_core::AdkError`] for a terminal Interactions failure status.
477#[cfg(feature = "gemini-interactions")]
478fn interaction_terminal_error(code: &'static str, message: &str) -> adk_core::AdkError {
479    adk_core::AdkError::new(
480        ErrorComponent::Model,
481        ErrorCategory::Internal,
482        code,
483        message.to_string(),
484    )
485    .with_provider("gemini")
486}
487
488/// Returns the value of the environment variable `name` when it is set and
489/// non-empty (after trimming whitespace).
490fn env_non_empty(name: &str) -> Option<String> {
491    std::env::var(name).ok().filter(|v| !v.trim().is_empty())
492}
493
494/// Returns `true` when an opt-in flag value selects the Vertex AI backend:
495/// `1` or a case-insensitive `true`.
496fn env_flag_truthy(value: &str) -> bool {
497    let v = value.trim();
498    v == "1" || v.eq_ignore_ascii_case("true")
499}
500
501/// Reports whether the environment opts in to the Vertex AI backend.
502///
503/// Consults `GOOGLE_GENAI_USE_ENTERPRISE` first and, when that variable is
504/// unset or empty, the deprecated `GOOGLE_GENAI_USE_VERTEXAI`. A flag is
505/// truthy when its value is `1` or a case-insensitive `true`.
506/// `GOOGLE_GENAI_USE_ENTERPRISE` takes precedence when both are set.
507///
508/// # Example
509///
510/// ```rust,no_run
511/// if adk_model::gemini::vertex_env_requested() {
512///     // route Gemini traffic through Vertex AI
513/// }
514/// ```
515pub fn vertex_env_requested() -> bool {
516    // `GOOGLE_GENAI_USE_VERTEXAI` is the deprecated name adk-python still
517    // honors. Deliberately no deprecation warning for it —
518    // google/adk-python#6168 documents the churn such a warning caused.
519    if let Some(v) = env_non_empty("GOOGLE_GENAI_USE_ENTERPRISE") {
520        return env_flag_truthy(&v);
521    }
522    env_non_empty("GOOGLE_GENAI_USE_VERTEXAI").is_some_and(|v| env_flag_truthy(&v))
523}
524
525/// Reads `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`, erroring with a
526/// message that names whichever variable is missing.
527#[cfg(feature = "gemini-vertex")]
528fn vertex_target_from_env() -> Result<(String, String)> {
529    let project = env_non_empty("GOOGLE_CLOUD_PROJECT");
530    let location = env_non_empty("GOOGLE_CLOUD_LOCATION");
531    if let (Some(project), Some(location)) = (&project, &location) {
532        return Ok((project.clone(), location.clone()));
533    }
534    let mut missing = Vec::new();
535    if project.is_none() {
536        missing.push("GOOGLE_CLOUD_PROJECT");
537    }
538    if location.is_none() {
539        missing.push("GOOGLE_CLOUD_LOCATION");
540    }
541    Err(adk_core::AdkError::new(
542        ErrorComponent::Model,
543        ErrorCategory::InvalidInput,
544        "model.gemini.vertex_env_incomplete",
545        format!(
546            "Vertex AI backend selected via GOOGLE_GENAI_USE_ENTERPRISE/GOOGLE_GENAI_USE_VERTEXAI, but {} not set. Set the missing variable(s) to your Google Cloud project ID and region (e.g. us-central1).",
547            missing.join(" and ")
548        ),
549    )
550    .with_provider("gemini"))
551}
552
553impl GeminiModel {
554    /// The thinking configuration of one request (spec 3.1 §7.23, §10 C4): the request's
555    /// `effort` becomes the `thinking_level` for this call on Gemini 3 and later, or on any
556    /// model configured with a level, replacing a configured token budget; elsewhere it is
557    /// logged and ignored.
558    fn request_thinking_config(&self, req: &LlmRequest) -> Option<adk_gemini::ThinkingConfig> {
559        let configured = self.thinking_config.clone();
560        let Some(level) = req.config.as_ref().and_then(|config| config.effort) else {
561            return configured;
562        };
563        let configured_level =
564            configured.as_ref().is_some_and(|config| config.thinking_level.is_some());
565        let generation = self.model_name.find("gemini-").and_then(|start| {
566            let version = &self.model_name[start + "gemini-".len()..];
567            let end = version.find(|c: char| !c.is_ascii_digit()).unwrap_or(version.len());
568            version[..end].parse::<u32>().ok()
569        });
570        if !configured_level && generation.is_none_or(|major| major < 3) {
571            tracing::debug!(
572                model.name = %self.model_name,
573                effort = %level,
574                "model takes no thinking level; the request's effort is ignored"
575            );
576            return configured;
577        }
578        let mut config = configured.unwrap_or_default();
579        config.thinking_budget = None;
580        config.thinking_level = Some(level.into());
581        Some(config)
582    }
583
584    fn gemini_part_thought_signature(value: &serde_json::Value) -> Option<String> {
585        value.get("thoughtSignature").and_then(serde_json::Value::as_str).map(str::to_string)
586    }
587
588    /// The Gemini part a stored server-tool payload replays as: a `toolCall`, `toolResponse`,
589    /// `executableCode` or `codeExecutionResult` part, or the code-execution shape the Vertex
590    /// AI session service restores (`vertexExecutableCode`, `vertexCodeExecutionResult`), with
591    /// its thought signature. `None` for any other payload.
592    fn native_server_part(payload: &serde_json::Value) -> Option<adk_gemini::Part> {
593        let thought_signature = Self::gemini_part_thought_signature(payload);
594        if let Some(executable_code) = payload.get("vertexExecutableCode") {
595            return Some(adk_gemini::Part::ExecutableCode {
596                executable_code: executable_code.clone(),
597                thought_signature,
598            });
599        }
600        if let Some(code_execution_result) = payload.get("vertexCodeExecutionResult") {
601            return Some(adk_gemini::Part::CodeExecutionResult {
602                code_execution_result: code_execution_result.clone(),
603                thought_signature,
604            });
605        }
606        match serde_json::from_value::<adk_gemini::Part>(payload.clone()).ok()? {
607            part @ (adk_gemini::Part::ToolCall { .. }
608            | adk_gemini::Part::ToolResponse { .. }
609            | adk_gemini::Part::ExecutableCode { .. }
610            | adk_gemini::Part::CodeExecutionResult { .. }) => Some(part),
611            adk_gemini::Part::Text { .. }
612            | adk_gemini::Part::InlineData { .. }
613            | adk_gemini::Part::FileData { .. }
614            | adk_gemini::Part::FunctionCall { .. }
615            | adk_gemini::Part::FunctionResponse { .. } => None,
616        }
617    }
618
619    fn validate_request_contract(&self, req: &LlmRequest, stream: bool) -> Result<()> {
620        // Server-side RAG grounding is a Vertex AI capability; reject it on
621        // the AI Studio backend before any network IO (mirrors the request-
622        // time gating the Vertex backend applies to Studio-only fields).
623        #[cfg(feature = "gemini-vertex")]
624        if self.vertex_rag_store.is_some() && !self.vertex_backend {
625            return Err(adk_core::AdkError::new(
626                ErrorComponent::Model,
627                ErrorCategory::Unsupported,
628                "model.gemini.rag_store_requires_vertex",
629                "Vertex RAG store grounding requires the Vertex AI backend. Construct the model with new_google_cloud/new_google_cloud_adc (or set GOOGLE_GENAI_USE_VERTEXAI with GOOGLE_CLOUD_PROJECT/GOOGLE_CLOUD_LOCATION) instead of an AI Studio API key.",
630            )
631            .with_provider("gemini"));
632        }
633
634        let model = self.model_name.strip_prefix("models/").unwrap_or(&self.model_name);
635        let gemini_4 = !self.supports_explicit_cache();
636        if !gemini_4
637            && !matches!(model, "gemini-3.6-flash" | "gemini-3.7-flash" | "gemini-3.8-flash")
638        {
639            return Ok(());
640        }
641
642        if let Some(config) = &req.config
643            && (config.temperature.is_some() || config.top_p.is_some() || config.top_k.is_some())
644        {
645            return Err(adk_core::AdkError::new(
646                ErrorComponent::Model,
647                ErrorCategory::InvalidInput,
648                "model.gemini.sampling_unsupported",
649                format!(
650                    "{model} does not accept temperature, top_p, or top_k; remove explicit sampling parameters"
651                ),
652            )
653            .with_provider("gemini"));
654        }
655        if !gemini_4 {
656            if self.thinking_config.as_ref().is_some_and(|config| config.thinking_budget.is_some())
657            {
658                return Err(adk_core::AdkError::new(
659                    ErrorComponent::Model,
660                    ErrorCategory::InvalidInput,
661                    "model.gemini.thinking_budget_unsupported",
662                    format!(
663                        "{model} uses thinking levels instead of token budgets; set thinking_level and clear thinking_budget"
664                    ),
665                )
666                .with_provider("gemini"));
667            }
668            return Ok(());
669        }
670
671        // Gemini 4 (https://aistudio.google.com/docs/whats-new-gemini-4-hydrogen and the Neon,
672        // Carbon and Argon pages): a token budget maps to the nearest level, so only levels
673        // are checked.
674        let carbon_or_argon = matches!(model, "gemini-4-carbon" | "gemini-4-argon");
675        let refused_level = match self.request_thinking_config(req).and_then(|c| c.thinking_level) {
676            Some(adk_gemini::ThinkingLevel::Minimal) => Some("minimal"),
677            Some(adk_gemini::ThinkingLevel::XHigh) if carbon_or_argon => Some("xhigh"),
678            _ => None,
679        };
680        if let Some(level) = refused_level {
681            return Err(adk_core::AdkError::new(
682                ErrorComponent::Model,
683                ErrorCategory::InvalidInput,
684                "model.gemini.thinking_level_unsupported",
685                format!(
686                    "{model} does not accept thinking level {level}; set low, medium or high \
687                     (xhigh runs on gemini-4-neon and gemini-4-hydrogen)"
688                ),
689            )
690            .with_provider("gemini"));
691        }
692        if req.config.as_ref().is_some_and(|config| config.cached_content.is_some()) {
693            return Err(adk_core::AdkError::new(
694                ErrorComponent::Model,
695                ErrorCategory::Unsupported,
696                "model.gemini.explicit_cache_unsupported",
697                format!(
698                    "{model} does not support explicit context caching; remove cached_content \
699                     (implicit caching applies to prompts of at least 4,096 tokens)"
700                ),
701            )
702            .with_provider("gemini"));
703        }
704        // https://aistudio.google.com/docs/long-decode: a direct non-streaming generateContent
705        // call to Carbon or Argon returns at most 32,768 tokens and refuses a larger cap.
706        #[cfg(feature = "gemini-interactions")]
707        let interactions = self.transport == GeminiTransport::Interactions;
708        #[cfg(not(feature = "gemini-interactions"))]
709        let interactions = false;
710        if carbon_or_argon
711            && !stream
712            && !interactions
713            && req
714                .config
715                .as_ref()
716                .and_then(|config| config.max_output_tokens)
717                .is_some_and(|max| max > 32_768)
718        {
719            return Err(adk_core::AdkError::new(
720                ErrorComponent::Model,
721                ErrorCategory::InvalidInput,
722                "model.gemini.output_cap_exceeded",
723                format!(
724                    "{model} returns at most 32,768 output tokens on a non-streaming call; set \
725                     max_output_tokens to 32768 or less, or stream the request"
726                ),
727            )
728            .with_provider("gemini"));
729        }
730        Ok(())
731    }
732
733    /// Whether the model supports explicit context caching
734    /// ([`create_cached_content`](Self::create_cached_content) and `cached_content` on a
735    /// request). The Gemini 4 models do not: they cache implicitly
736    /// (<https://aistudio.google.com/docs/whats-new-gemini-4-hydrogen>).
737    ///
738    /// # Example
739    ///
740    /// ```rust,no_run
741    /// use adk_model::GeminiModel;
742    ///
743    /// let model = GeminiModel::new("api-key", "gemini-4-hydrogen")?;
744    /// assert!(!model.supports_explicit_cache());
745    /// # Ok::<(), adk_core::AdkError>(())
746    /// ```
747    pub fn supports_explicit_cache(&self) -> bool {
748        let model = self.model_name.strip_prefix("models/").unwrap_or(&self.model_name);
749        !matches!(
750            model,
751            "gemini-4-carbon" | "gemini-4-argon" | "gemini-4-neon" | "gemini-4-hydrogen"
752        )
753    }
754
755    /// Builds a `GeminiModel` from a constructed client and model name with all
756    /// configurable fields defaulted.
757    ///
758    /// Centralizing struct construction here keeps the cfg-gated Interactions
759    /// fields out of every public constructor's `Self { .. }` literal.
760    pub(crate) fn from_client(client: Gemini, model_name: String) -> Self {
761        Self {
762            client,
763            model_name,
764            retry_config: RetryConfig::default(),
765            thinking_config: None,
766            #[cfg(feature = "gemini-interactions")]
767            transport: GeminiTransport::GenerateContent,
768            #[cfg(feature = "gemini-interactions")]
769            interaction_target: None,
770            #[cfg(feature = "gemini-interactions")]
771            interaction_options: InteractionOptions::default(),
772            #[cfg(feature = "gemini-vertex")]
773            vertex_rag_store: None,
774            #[cfg(feature = "gemini-vertex")]
775            vertex_backend: false,
776        }
777    }
778
779    /// Create a new Gemini model client with an API key and model name.
780    pub fn new(api_key: impl Into<String>, model: impl Into<String>) -> Result<Self> {
781        let model_name = model.into();
782        crate::catalog::warn_if_obsolete("gemini", &model_name);
783        let client = Gemini::with_model(api_key.into(), model_name.clone())
784            .map_err(|e| adk_core::AdkError::model(e.to_string()))?;
785
786        Ok(Self::from_client(client, model_name))
787    }
788
789    /// Create an API-key model using an explicit REST base URL.
790    ///
791    /// The base URL includes the API version and ends with a slash. No environment
792    /// variable is read.
793    ///
794    /// # Errors
795    ///
796    /// Returns an error when `base_url` is not a valid URL or the client cannot be built.
797    ///
798    /// # Example
799    ///
800    /// ```
801    /// use adk_model::GeminiModel;
802    ///
803    /// let model = GeminiModel::new_with_base_url(
804    ///     "api-key",
805    ///     "gemini-3.8-flash",
806    ///     "https://gateway.example.com/v1beta/",
807    /// )?;
808    /// # Ok::<(), adk_core::AdkError>(())
809    /// ```
810    pub fn new_with_base_url(
811        api_key: impl Into<String>,
812        model: impl Into<String>,
813        base_url: impl AsRef<str>,
814    ) -> Result<Self> {
815        let model_name = model.into();
816        let base_url = base_url
817            .as_ref()
818            .parse()
819            .map_err(|_| adk_core::AdkError::model("Invalid Gemini base URL"))?;
820        let client = Gemini::with_model_and_base_url(api_key.into(), model_name.clone(), base_url)
821            .map_err(|e| adk_core::AdkError::model(e.to_string()))?;
822        Ok(Self::from_client(client, model_name))
823    }
824
825    /// Create an API-key model with explicit connect and byte-idle timeouts.
826    ///
827    /// The other API-key constructors apply [`HttpTimeouts::default`](crate::HttpTimeouts),
828    /// the SDK's own defaults. This constructor uses the same SDK builder and adds no
829    /// response-level or total-request timer.
830    ///
831    /// # Example
832    ///
833    /// ```
834    /// use adk_model::{GeminiModel, HttpTimeouts};
835    /// use std::time::Duration;
836    ///
837    /// let model = GeminiModel::new_with_base_url_and_timeouts(
838    ///     "api-key", "gemini-3.8-flash", "https://gateway.example.com/v1beta/",
839    ///     HttpTimeouts::new(Duration::from_secs(30), Duration::from_secs(300)),
840    /// )?;
841    /// # Ok::<(), adk_core::AdkError>(())
842    /// ```
843    pub fn new_with_base_url_and_timeouts(
844        api_key: impl Into<String>,
845        model: impl Into<String>,
846        base_url: impl AsRef<str>,
847        timeouts: crate::HttpTimeouts,
848    ) -> Result<Self> {
849        let model_name = model.into();
850        let base_url = base_url
851            .as_ref()
852            .parse()
853            .map_err(|_| adk_core::AdkError::model("Invalid Gemini base URL"))?;
854        let client = adk_gemini::GeminiBuilder::new(api_key.into())
855            .with_model(model_name.clone())
856            .with_base_url(base_url)
857            .with_http_client(timeouts.apply(reqwest::Client::builder()))
858            .build()
859            .map_err(|error| gemini_error_to_adk(&error))?;
860        Ok(Self::from_client(client, model_name))
861    }
862
863    /// Create a Gemini model via Vertex AI with API key auth.
864    ///
865    /// Requires `gemini-vertex` feature.
866    #[cfg(feature = "gemini-vertex")]
867    pub fn new_google_cloud(
868        api_key: impl Into<String>,
869        project_id: impl AsRef<str>,
870        location: impl AsRef<str>,
871        model: impl Into<String>,
872    ) -> Result<Self> {
873        let model_name = model.into();
874        let client = Gemini::with_google_cloud_model(
875            api_key.into(),
876            project_id,
877            location,
878            model_name.clone(),
879        )
880        .map_err(|e| adk_core::AdkError::model(e.to_string()))?;
881
882        let mut model = Self::from_client(client, model_name);
883        model.vertex_backend = true;
884        Ok(model)
885    }
886
887    /// Use an explicit Vertex endpoint and either a supplied key or execution-host ADC.
888    ///
889    /// Requires `gemini-vertex` feature.
890    ///
891    /// # Errors
892    ///
893    /// Returns an error when Application Default Credentials are requested
894    /// (`api_key` is `None`) but unavailable, or when the client cannot be built.
895    ///
896    /// # Example
897    ///
898    /// ```no_run
899    /// use adk_model::GeminiModel;
900    ///
901    /// let model = GeminiModel::new_google_cloud_endpoint(
902    ///     None,
903    ///     "my-project",
904    ///     "us-central1",
905    ///     "gemini-3.8-flash",
906    ///     "https://us-central1-aiplatform.googleapis.com",
907    /// )?;
908    /// # Ok::<(), adk_core::AdkError>(())
909    /// ```
910    #[cfg(feature = "gemini-vertex")]
911    pub fn new_google_cloud_endpoint(
912        api_key: Option<&str>,
913        project: &str,
914        location: &str,
915        model_name: &str,
916        endpoint: &str,
917    ) -> Result<Self> {
918        let mut builder = adk_gemini::GeminiBuilder::new(api_key.unwrap_or_default())
919            .with_model(model_name.to_owned())
920            .with_google_cloud(project, location)
921            .with_google_cloud_endpoint(endpoint);
922        if api_key.is_none() {
923            builder = builder.with_google_cloud_adc().map_err(|e| gemini_error_to_adk(&e))?;
924        }
925        let client = builder.build().map_err(|e| gemini_error_to_adk(&e))?;
926        let mut model = Self::from_client(client, model_name.to_owned());
927        model.vertex_backend = true;
928        Ok(model)
929    }
930
931    /// Create a Gemini model via Vertex AI with service account JSON.
932    ///
933    /// Requires `gemini-vertex` feature.
934    #[cfg(feature = "gemini-vertex")]
935    pub fn new_google_cloud_service_account(
936        service_account_json: &str,
937        project_id: impl AsRef<str>,
938        location: impl AsRef<str>,
939        model: impl Into<String>,
940    ) -> Result<Self> {
941        let model_name = model.into();
942        let client = Gemini::with_google_cloud_service_account_json(
943            service_account_json,
944            project_id.as_ref(),
945            location.as_ref(),
946            model_name.clone(),
947        )
948        .map_err(|e| adk_core::AdkError::model(e.to_string()))?;
949
950        let mut model = Self::from_client(client, model_name);
951        model.vertex_backend = true;
952        Ok(model)
953    }
954
955    /// Create a Gemini model via Vertex AI with Application Default Credentials.
956    ///
957    /// Requires `gemini-vertex` feature.
958    #[cfg(feature = "gemini-vertex")]
959    pub fn new_google_cloud_adc(
960        project_id: impl AsRef<str>,
961        location: impl AsRef<str>,
962        model: impl Into<String>,
963    ) -> Result<Self> {
964        let model_name = model.into();
965        let client = Gemini::with_google_cloud_adc_model(
966            project_id.as_ref(),
967            location.as_ref(),
968            model_name.clone(),
969        )
970        .map_err(|e| adk_core::AdkError::model(e.to_string()))?;
971
972        let mut model = Self::from_client(client, model_name);
973        model.vertex_backend = true;
974        Ok(model)
975    }
976
977    /// Create a Gemini model via Vertex AI with Workload Identity Federation.
978    ///
979    /// Requires `gemini-vertex` feature.
980    #[cfg(feature = "gemini-vertex")]
981    pub fn new_google_cloud_wif(
982        wif_json: &str,
983        project_id: impl AsRef<str>,
984        location: impl AsRef<str>,
985        model: impl Into<String>,
986    ) -> Result<Self> {
987        let model_name = model.into();
988        let client = Gemini::with_google_cloud_wif_json(
989            wif_json,
990            project_id.as_ref(),
991            location.as_ref(),
992            model_name.clone(),
993        )
994        .map_err(|e| adk_core::AdkError::model(e.to_string()))?;
995
996        let mut model = Self::from_client(client, model_name);
997        model.vertex_backend = true;
998        Ok(model)
999    }
1000
1001    /// Create a Gemini model from environment variables.
1002    ///
1003    /// When `GOOGLE_GENAI_USE_ENTERPRISE` or `GOOGLE_GENAI_USE_VERTEXAI` is
1004    /// truthy (`1` or a case-insensitive `true`), builds a Vertex AI client
1005    /// with Application Default Credentials from `GOOGLE_CLOUD_PROJECT` and
1006    /// `GOOGLE_CLOUD_LOCATION` — this path requires the `gemini-vertex`
1007    /// feature. Otherwise builds a Gemini API (AI Studio) client from
1008    /// `GOOGLE_API_KEY` or `GEMINI_API_KEY`.
1009    ///
1010    /// `GOOGLE_GENAI_USE_ENTERPRISE` takes precedence when both flags are set.
1011    ///
1012    /// The Vertex path builds Application Default Credentials, which requires
1013    /// a Tokio runtime to be current — call from async code or under
1014    /// `#[tokio::main]`.
1015    ///
1016    /// # Errors
1017    ///
1018    /// - A Vertex flag is truthy but `GOOGLE_CLOUD_PROJECT` or
1019    ///   `GOOGLE_CLOUD_LOCATION` is not set.
1020    /// - A Vertex flag is truthy but the `gemini-vertex` feature is not
1021    ///   compiled.
1022    /// - No Vertex flag is truthy and neither `GOOGLE_API_KEY` nor
1023    ///   `GEMINI_API_KEY` is set.
1024    ///
1025    /// # Example
1026    ///
1027    /// ```rust,no_run
1028    /// use adk_model::gemini::GeminiModel;
1029    ///
1030    /// # #[tokio::main]
1031    /// # async fn main() -> adk_core::Result<()> {
1032    /// let model = GeminiModel::from_env("gemini-3.8-flash")?;
1033    /// # Ok(())
1034    /// # }
1035    /// ```
1036    pub fn from_env(model: &str) -> Result<Self> {
1037        if vertex_env_requested() {
1038            #[cfg(feature = "gemini-vertex")]
1039            {
1040                let (project, location) = vertex_target_from_env()?;
1041                return Self::new_google_cloud_adc(project, location, model);
1042            }
1043            #[cfg(not(feature = "gemini-vertex"))]
1044            {
1045                return Err(adk_core::AdkError::new(
1046                    ErrorComponent::Model,
1047                    ErrorCategory::Unsupported,
1048                    "model.gemini.vertex_feature_missing",
1049                    "Vertex AI backend selected via GOOGLE_GENAI_USE_ENTERPRISE/GOOGLE_GENAI_USE_VERTEXAI, but the `gemini-vertex` feature is not compiled. Enable the `gemini-vertex` feature (or `gemini-agent-platform` on the adk-rust umbrella crate) to route Gemini traffic through Vertex AI.",
1050                )
1051                .with_provider("gemini"));
1052            }
1053        }
1054
1055        let Some(api_key) =
1056            env_non_empty("GOOGLE_API_KEY").or_else(|| env_non_empty("GEMINI_API_KEY"))
1057        else {
1058            return Err(adk_core::AdkError::new(
1059                ErrorComponent::Model,
1060                ErrorCategory::InvalidInput,
1061                "model.gemini.api_key_missing",
1062                "No Gemini API key found. Set GOOGLE_API_KEY or GEMINI_API_KEY, or set GOOGLE_GENAI_USE_ENTERPRISE=true with GOOGLE_CLOUD_PROJECT/GOOGLE_CLOUD_LOCATION for Vertex AI.",
1063            )
1064            .with_provider("gemini"));
1065        };
1066        Self::new(api_key, model)
1067    }
1068
1069    /// Set the retry configuration (builder pattern).
1070    #[must_use]
1071    pub fn with_retry_config(mut self, retry_config: RetryConfig) -> Self {
1072        self.retry_config = retry_config;
1073        self
1074    }
1075
1076    /// Set the retry configuration (mutable reference).
1077    pub fn set_retry_config(&mut self, retry_config: RetryConfig) {
1078        self.retry_config = retry_config;
1079    }
1080
1081    /// Returns the current retry configuration.
1082    pub fn retry_config(&self) -> &RetryConfig {
1083        &self.retry_config
1084    }
1085
1086    /// Set the default thinking configuration applied to every request.
1087    ///
1088    /// Controls the model's reasoning effort. For Gemini 3 series models,
1089    /// use `ThinkingLevel` (Low/Medium/High). For Gemini 2.5 series, use
1090    /// `thinking_budget` (token count).
1091    ///
1092    /// # Example
1093    ///
1094    /// ```rust,ignore
1095    /// use adk_gemini::{ThinkingConfig, ThinkingLevel};
1096    ///
1097    /// // Gemini 3 — level-based thinking
1098    /// let model = GeminiModel::new(api_key, "gemini-3.1-pro-preview")?
1099    ///     .with_thinking_config(
1100    ///         ThinkingConfig::new().with_thinking_level(ThinkingLevel::Low)
1101    ///     );
1102    ///
1103    /// // Gemini 2.5 — budget-based thinking
1104    /// let model = GeminiModel::new(api_key, "gemini-3.8-flash")?
1105    ///     .with_thinking_config(
1106    ///         ThinkingConfig::new().with_thinking_budget(2048)
1107    ///     );
1108    /// ```
1109    #[must_use]
1110    pub fn with_thinking_config(mut self, thinking_config: adk_gemini::ThinkingConfig) -> Self {
1111        self.thinking_config = Some(thinking_config);
1112        self
1113    }
1114
1115    /// Set the thinking configuration (mutable reference variant).
1116    pub fn set_thinking_config(&mut self, thinking_config: adk_gemini::ThinkingConfig) {
1117        self.thinking_config = Some(thinking_config);
1118    }
1119
1120    /// Returns the current thinking configuration, if set.
1121    pub fn thinking_config(&self) -> Option<&adk_gemini::ThinkingConfig> {
1122        self.thinking_config.as_ref()
1123    }
1124
1125    /// Ground every request in a Vertex AI RAG store (server-side retrieval).
1126    ///
1127    /// Declares a `retrieval` tool on each outgoing `generateContent` request
1128    /// so Vertex AI retrieves grounding context from the referenced RAG
1129    /// corpora before generating. Requires a Vertex AI backend — requests on
1130    /// an AI Studio model fail with the structured error
1131    /// `model.gemini.rag_store_requires_vertex` before any network IO.
1132    ///
1133    /// # Example
1134    ///
1135    /// ```rust,no_run
1136    /// use adk_gemini::VertexRagStore;
1137    /// use adk_model::gemini::GeminiModel;
1138    ///
1139    /// # fn main() -> adk_core::Result<()> {
1140    /// let store = VertexRagStore::corpus("projects/p/locations/us-central1/ragCorpora/123")
1141    ///     .with_top_k(5);
1142    /// let model =
1143    ///     GeminiModel::new_google_cloud("api-key", "p", "us-central1", "gemini-3.8-flash")?
1144    ///         .with_vertex_rag_store(store);
1145    /// # Ok(())
1146    /// # }
1147    /// ```
1148    #[cfg(feature = "gemini-vertex")]
1149    #[must_use]
1150    pub fn with_vertex_rag_store(mut self, store: adk_gemini::VertexRagStore) -> Self {
1151        self.vertex_rag_store = Some(store);
1152        self
1153    }
1154
1155    /// Returns the configured Vertex RAG store, if set.
1156    #[cfg(feature = "gemini-vertex")]
1157    pub fn vertex_rag_store(&self) -> Option<&adk_gemini::VertexRagStore> {
1158        self.vertex_rag_store.as_ref()
1159    }
1160
1161    /// Enable (or disable) the Interactions API transport.
1162    ///
1163    /// When enabling, the model's configured model id is validated against the
1164    /// Interactions allowlist via [`InteractionTarget::parse`]. On success the
1165    /// transport switches to [`GeminiTransport::Interactions`] and the
1166    /// validated target is stored. Disabling reverts to
1167    /// [`GeminiTransport::GenerateContent`] and clears the stored target.
1168    ///
1169    /// Requires the `gemini-interactions` feature.
1170    ///
1171    /// # Errors
1172    ///
1173    /// Returns an [`adk_core::AdkError`] with category `InvalidInput` when
1174    /// enabling the transport for a model id outside the Interactions
1175    /// allowlist (Requirement 2.4). The error message names the supported
1176    /// model and agent targets.
1177    ///
1178    /// # Example
1179    ///
1180    /// ```rust,ignore
1181    /// let model = GeminiModel::new(api_key, "gemini-3.8-flash")?
1182    ///     .use_interactions_api(true)?;
1183    /// ```
1184    #[cfg(feature = "gemini-interactions")]
1185    pub fn use_interactions_api(mut self, enabled: bool) -> Result<Self> {
1186        if enabled {
1187            let target = InteractionTarget::parse(&self.model_name)?;
1188            self.transport = GeminiTransport::Interactions;
1189            self.interaction_target = Some(target);
1190        } else {
1191            self.transport = GeminiTransport::GenerateContent;
1192            self.interaction_target = None;
1193        }
1194        Ok(self)
1195    }
1196
1197    /// Override the Interactions transport options (store, stateful, background
1198    /// mode, poll interval).
1199    ///
1200    /// Requires the `gemini-interactions` feature. The defaults (see
1201    /// [`InteractionOptions::default`]) mirror the Interactions API's intended
1202    /// posture; override only when a different behavior is required.
1203    #[cfg(feature = "gemini-interactions")]
1204    #[must_use]
1205    pub fn interaction_options(mut self, opts: InteractionOptions) -> Self {
1206        self.interaction_options = opts;
1207        self
1208    }
1209
1210    /// Returns the currently selected wire transport.
1211    ///
1212    /// Requires the `gemini-interactions` feature.
1213    #[cfg(feature = "gemini-interactions")]
1214    pub fn transport(&self) -> GeminiTransport {
1215        self.transport
1216    }
1217
1218    /// Returns the configured Interactions options.
1219    ///
1220    /// Requires the `gemini-interactions` feature.
1221    #[cfg(feature = "gemini-interactions")]
1222    pub fn interaction_options_ref(&self) -> &InteractionOptions {
1223        &self.interaction_options
1224    }
1225
1226    /// Resolves whether background execution should be used for the configured
1227    /// Interactions target, honoring [`BackgroundMode`].
1228    ///
1229    /// Returns `true` when the mode is [`BackgroundMode::Always`], `false` when
1230    /// [`BackgroundMode::Never`], and (for [`BackgroundMode::AgentTargetsOnly`])
1231    /// `true` only when the configured target is an agent target. When no
1232    /// Interactions target is configured, agent-targets-only resolves to
1233    /// `false`.
1234    ///
1235    /// Used by the non-streaming/background Interactions path (task 7.3); kept
1236    /// here so the transport state and its policy resolution live together.
1237    #[cfg(feature = "gemini-interactions")]
1238    fn resolve_background(&self) -> bool {
1239        match self.interaction_options.background {
1240            BackgroundMode::Always => true,
1241            BackgroundMode::Never => false,
1242            BackgroundMode::AgentTargetsOnly => {
1243                self.interaction_target.as_ref().is_some_and(InteractionTarget::is_agent)
1244            }
1245        }
1246    }
1247
1248    fn convert_response(resp: &adk_gemini::GenerationResponse) -> Result<LlmResponse> {
1249        let mut converted_parts: Vec<Part> = Vec::new();
1250
1251        // Convert content parts
1252        if let Some(parts) = resp.candidates.first().and_then(|c| c.content.parts.as_ref()) {
1253            for p in parts {
1254                match p {
1255                    adk_gemini::Part::Text { text, thought, thought_signature } => {
1256                        if thought == &Some(true) {
1257                            converted_parts.push(Part::Thinking {
1258                                thinking: text.clone(),
1259                                signature: thought_signature.clone(),
1260                            });
1261                        } else {
1262                            converted_parts.push(Part::Text { text: text.clone() });
1263                        }
1264                    }
1265                    adk_gemini::Part::InlineData { inline_data, .. } => {
1266                        let decoded =
1267                            BASE64_STANDARD.decode(&inline_data.data).map_err(|error| {
1268                                adk_core::AdkError::model(format!(
1269                                    "failed to decode inline data from gemini response: {error}"
1270                                ))
1271                            })?;
1272                        converted_parts.push(Part::InlineData {
1273                            mime_type: inline_data.mime_type.clone(),
1274                            data: decoded,
1275                            uri: None,
1276                            annotations: None,
1277                        });
1278                    }
1279                    adk_gemini::Part::FunctionCall { function_call, thought_signature } => {
1280                        converted_parts.push(Part::FunctionCall {
1281                            name: function_call.name.clone(),
1282                            args: function_call.args.clone(),
1283                            id: function_call.id.clone(),
1284                            thought_signature: thought_signature.clone(),
1285                        });
1286                    }
1287                    adk_gemini::Part::FunctionResponse { function_response, .. } => {
1288                        converted_parts.push(Part::FunctionResponse {
1289                            function_response: adk_core::FunctionResponseData::new(
1290                                function_response.name.clone(),
1291                                function_response
1292                                    .response
1293                                    .clone()
1294                                    .unwrap_or(serde_json::Value::Null),
1295                            ),
1296                            id: None,
1297                            annotations: None,
1298                        });
1299                    }
1300                    adk_gemini::Part::ToolCall { .. } | adk_gemini::Part::ExecutableCode { .. } => {
1301                        if let Ok(value) = serde_json::to_value(p) {
1302                            converted_parts.push(Part::ServerToolCall { server_tool_call: value });
1303                        }
1304                    }
1305                    adk_gemini::Part::ToolResponse { .. }
1306                    | adk_gemini::Part::CodeExecutionResult { .. } => {
1307                        let value = serde_json::to_value(p).unwrap_or(serde_json::Value::Null);
1308                        converted_parts
1309                            .push(Part::ServerToolResponse { server_tool_response: value });
1310                    }
1311                    adk_gemini::Part::FileData { file_data, .. } => {
1312                        converted_parts.push(Part::FileData {
1313                            mime_type: file_data.mime_type.clone(),
1314                            file_uri: file_data.file_uri.clone(),
1315                            annotations: None,
1316                        });
1317                    }
1318                }
1319            }
1320        }
1321
1322        let content = if converted_parts.is_empty() {
1323            None
1324        } else {
1325            Some(Content { role: "model".to_string(), parts: converted_parts })
1326        };
1327        let tool_call_turn = content.as_ref().is_some_and(Content::has_function_calls);
1328
1329        let usage_metadata = resp.usage_metadata.as_ref().map(|u| {
1330            let prompt = u.prompt_token_count.unwrap_or(0);
1331            // Gemini's candidate count excludes the separately reported thoughts.
1332            let candidates = u
1333                .candidates_token_count
1334                .unwrap_or(0)
1335                .saturating_add(u.thoughts_token_count.unwrap_or(0));
1336            UsageMetadata {
1337                prompt_token_count: prompt,
1338                candidates_token_count: candidates,
1339                // An unreported total is at least the parts that were reported.
1340                total_token_count: u
1341                    .total_token_count
1342                    .unwrap_or_else(|| prompt.saturating_add(candidates)),
1343                thinking_token_count: u.thoughts_token_count,
1344                cache_read_input_token_count: u.cached_content_token_count,
1345                // As received, so fields such as `toolUsePromptTokenCount` survive.
1346                provider_usage: u.raw.clone().or_else(|| serde_json::to_value(u).ok()),
1347                builtin_tool_uses: {
1348                    let mut uses = GeminiBuiltinToolUses::default();
1349                    uses.observe(resp);
1350                    uses.uses()
1351                },
1352                ..Default::default()
1353            }
1354        });
1355
1356        let finish_reason =
1357            resp.candidates.first().and_then(|c| c.finish_reason.as_ref()).map(|fr| match fr {
1358                adk_gemini::FinishReason::Stop => FinishReason::Stop,
1359                // A long-decode hop stops at the per-request cap; no continuation request is
1360                // sent, so the response is cut short.
1361                adk_gemini::FinishReason::MaxTokens | adk_gemini::FinishReason::Continuation => {
1362                    FinishReason::MaxTokens
1363                }
1364                adk_gemini::FinishReason::Safety
1365                | adk_gemini::FinishReason::Blocklist
1366                | adk_gemini::FinishReason::ProhibitedContent
1367                | adk_gemini::FinishReason::Spii
1368                | adk_gemini::FinishReason::ImageSafety
1369                | adk_gemini::FinishReason::ModelArmor => FinishReason::Safety,
1370                adk_gemini::FinishReason::Recitation => FinishReason::Recitation,
1371                // https://ai.google.dev/api/generate-content#FinishReason: the function call is
1372                // invalid, or names a tool when no tools were enabled.
1373                adk_gemini::FinishReason::MalformedFunctionCall
1374                | adk_gemini::FinishReason::UnexpectedToolCall => FinishReason::MalformedToolCall,
1375                adk_gemini::FinishReason::FinishReasonUnspecified
1376                | adk_gemini::FinishReason::Language
1377                | adk_gemini::FinishReason::Other
1378                | adk_gemini::FinishReason::TooManyToolCalls
1379                | adk_gemini::FinishReason::MissingThoughtSignature
1380                | adk_gemini::FinishReason::MalformedResponse => FinishReason::Other,
1381                _ => FinishReason::Other,
1382            });
1383        // A blocked prompt has no candidates: it ends the turn as a safety stop, and
1384        // `error_code` marks it as a failure rather than an empty answer.
1385        let block_reason = resp
1386            .prompt_feedback
1387            .as_ref()
1388            .and_then(|feedback| feedback.block_reason.as_ref())
1389            .and_then(|reason| match reason {
1390                adk_gemini::BlockReason::BlockReasonUnspecified => None,
1391                adk_gemini::BlockReason::Safety => Some("SAFETY"),
1392                adk_gemini::BlockReason::Other => Some("OTHER"),
1393                adk_gemini::BlockReason::Blocklist => Some("BLOCKLIST"),
1394                adk_gemini::BlockReason::ProhibitedContent => Some("PROHIBITED_CONTENT"),
1395                adk_gemini::BlockReason::ModelArmor => Some("MODEL_ARMOR"),
1396                adk_gemini::BlockReason::Jailbreak => Some("JAILBREAK"),
1397                adk_gemini::BlockReason::ImageSafety => Some("IMAGE_SAFETY"),
1398            });
1399        let finish_reason =
1400            if block_reason.is_some() { Some(FinishReason::Safety) } else { finish_reason };
1401
1402        let citation_metadata =
1403            resp.candidates.first().and_then(|c| c.citation_metadata.as_ref()).map(|meta| {
1404                CitationMetadata {
1405                    citation_sources: meta
1406                        .citation_sources
1407                        .iter()
1408                        .map(|source| CitationSource {
1409                            uri: source.uri.clone(),
1410                            title: source.title.clone(),
1411                            start_index: source.start_index,
1412                            end_index: source.end_index,
1413                            license: source.license.clone(),
1414                            publication_date: source.publication_date.map(|d| d.to_string()),
1415                        })
1416                        .collect(),
1417                }
1418            });
1419
1420        // Serialize grounding metadata into provider_metadata so consumers
1421        // can display search queries and sources without changing the answer.
1422        let mut provider_metadata = resp
1423            .candidates
1424            .first()
1425            .and_then(|c| c.grounding_metadata.as_ref())
1426            .and_then(|g| serde_json::to_value(g).ok());
1427        // Requested through `GenerateContentConfig::top_logprobs`; kept as Gemini sent them.
1428        if let Some(logprobs) = resp
1429            .candidates
1430            .first()
1431            .and_then(|c| c.logprobs_result.as_ref())
1432            .and_then(|result| serde_json::to_value(result).ok())
1433            && let serde_json::Value::Object(metadata) =
1434                provider_metadata.get_or_insert_with(|| serde_json::json!({}))
1435        {
1436            metadata.insert("logprobs".to_string(), logprobs);
1437        }
1438
1439        Ok(LlmResponse {
1440            content,
1441            usage_metadata,
1442            finish_reason,
1443            citation_metadata,
1444            partial: false,
1445            turn_complete: !tool_call_turn,
1446            interrupted: false,
1447            error_code: block_reason.map(str::to_owned),
1448            error_message: block_reason
1449                .map(|reason| format!("Gemini blocked the prompt (blockReason {reason})")),
1450            provider_metadata,
1451            interaction_id: None,
1452            model: resp.model_version.clone().filter(|version| !version.is_empty()),
1453            provider: None,
1454        })
1455    }
1456
1457    fn gemini_function_response_payload(response: serde_json::Value) -> serde_json::Value {
1458        match response {
1459            // Gemini functionResponse.response must be a JSON object.
1460            serde_json::Value::Object(_) => response,
1461            other => serde_json::json!({ "result": other }),
1462        }
1463    }
1464
1465    fn merge_object_value(
1466        target: &mut serde_json::Map<String, serde_json::Value>,
1467        value: serde_json::Value,
1468    ) {
1469        if let serde_json::Value::Object(object) = value {
1470            for (key, value) in object {
1471                target.insert(key, value);
1472            }
1473        }
1474    }
1475
1476    fn build_gemini_tools(
1477        tools: &adk_core::ToolDeclarations,
1478        adapter: &dyn SchemaAdapter,
1479        cache: &SchemaCache,
1480    ) -> Result<(Vec<adk_gemini::Tool>, adk_gemini::ToolConfig)> {
1481        let mut gemini_tools = Vec::new();
1482        let mut function_declarations = Vec::new();
1483        let mut has_provider_native_tools = false;
1484        let mut tool_config_json = serde_json::Map::new();
1485
1486        for (name, tool_decl) in tools {
1487            if let Some(provider_tool) = tool_decl.get("x-adk-gemini-tool") {
1488                let tool = serde_json::from_value::<adk_gemini::Tool>(provider_tool.clone())
1489                    .map_err(|error| {
1490                        adk_core::AdkError::model(format!(
1491                            "failed to deserialize Gemini native tool '{name}': {error}"
1492                        ))
1493                    })?;
1494                has_provider_native_tools = true;
1495                gemini_tools.push(tool);
1496            } else {
1497                // Normalize tool name via the schema adapter
1498                let normalized_name = adapter.normalize_tool_name(name);
1499
1500                // Get the parameters schema from the declaration, or use the
1501                // adapter's empty_schema fallback when none is provided.
1502                let schema =
1503                    tool_decl.get("parameters").cloned().unwrap_or_else(|| adapter.empty_schema());
1504                let normalized_schema = cache.normalize(&schema);
1505
1506                // Build the FunctionDeclaration with normalized values
1507                let description =
1508                    tool_decl.get("description").and_then(|v| v.as_str()).unwrap_or("").to_string();
1509
1510                let mut func_decl_json = serde_json::json!({
1511                    "name": normalized_name.as_ref(),
1512                    "description": description,
1513                    "parameters": normalized_schema,
1514                });
1515
1516                // Preserve response schema if present (normalized like parameters)
1517                if let Some(response) = tool_decl.get("response") {
1518                    func_decl_json["response"] = cache.normalize(response);
1519                }
1520
1521                // Preserve behavior if present
1522                if let Some(behavior) = tool_decl.get("behavior") {
1523                    func_decl_json["behavior"] = behavior.clone();
1524                }
1525
1526                let func_decl =
1527                    serde_json::from_value::<adk_gemini::FunctionDeclaration>(func_decl_json)
1528                        .map_err(|error| {
1529                            adk_core::AdkError::model(format!(
1530                                "failed to build Gemini function declaration for '{name}': {error}"
1531                            ))
1532                        })?;
1533                function_declarations.push(func_decl);
1534            }
1535
1536            if let Some(tool_config) = tool_decl.get("x-adk-gemini-tool-config") {
1537                Self::merge_object_value(&mut tool_config_json, tool_config.clone());
1538            }
1539        }
1540
1541        let has_function_declarations = !function_declarations.is_empty();
1542        if has_function_declarations {
1543            gemini_tools.push(adk_gemini::Tool::with_functions(function_declarations));
1544        }
1545
1546        if has_provider_native_tools {
1547            tool_config_json.insert(
1548                "includeServerSideToolInvocations".to_string(),
1549                serde_json::Value::Bool(true),
1550            );
1551        }
1552
1553        let tool_config = if tool_config_json.is_empty() {
1554            adk_gemini::ToolConfig::default()
1555        } else {
1556            serde_json::from_value::<adk_gemini::ToolConfig>(serde_json::Value::Object(
1557                tool_config_json,
1558            ))
1559            .map_err(|error| {
1560                adk_core::AdkError::model(format!(
1561                    "failed to deserialize Gemini tool configuration: {error}"
1562                ))
1563            })?
1564        };
1565
1566        Ok((gemini_tools, tool_config))
1567    }
1568
1569    /// Splits one streamed Gemini response into the chunks the stream yields.
1570    ///
1571    /// A response without `finishReason` is a partial chunk. Its function calls go to
1572    /// `deferred_calls` and reach the stream once, ahead of the final chunk's own parts:
1573    /// the agent repeats every partial chunk's content in the terminal event it persists,
1574    /// so a call yielded mid-stream would appear twice to anything counting calls over
1575    /// events (spec 3.1 §7.13).
1576    fn stream_chunks_from_response(
1577        mut response: LlmResponse,
1578        saw_partial_chunk: bool,
1579        deferred_calls: &mut Vec<Part>,
1580    ) -> (Vec<LlmResponse>, bool) {
1581        let is_final = response.finish_reason.is_some();
1582
1583        if !is_final {
1584            response.partial = true;
1585            response.turn_complete = false;
1586            if let Some(content) = response.content.as_mut() {
1587                let (calls, rest): (Vec<Part>, Vec<Part>) = std::mem::take(&mut content.parts)
1588                    .into_iter()
1589                    .partition(|part| matches!(part, Part::FunctionCall { .. }));
1590                deferred_calls.extend(calls);
1591                content.parts = rest;
1592            }
1593            if response.content.as_ref().is_some_and(|content| content.parts.is_empty()) {
1594                response.content = None;
1595            }
1596            return (vec![response], true);
1597        }
1598
1599        response.partial = false;
1600        if !deferred_calls.is_empty() {
1601            let content = response
1602                .content
1603                .get_or_insert_with(|| Content { role: "model".to_string(), parts: Vec::new() });
1604            let mut parts = std::mem::take(deferred_calls);
1605            parts.append(&mut content.parts);
1606            content.parts = parts;
1607        }
1608        response.turn_complete =
1609            response.content.as_ref().is_none_or(|content| !content.has_function_calls());
1610
1611        if saw_partial_chunk {
1612            return (vec![response], true);
1613        }
1614
1615        let synthetic_partial = LlmResponse {
1616            content: None,
1617            usage_metadata: None,
1618            finish_reason: None,
1619            citation_metadata: None,
1620            partial: true,
1621            turn_complete: false,
1622            interrupted: false,
1623            error_code: None,
1624            error_message: None,
1625            provider_metadata: None,
1626            interaction_id: None,
1627            model: None,
1628            provider: None,
1629        };
1630
1631        (vec![synthetic_partial, response], true)
1632    }
1633
1634    async fn generate_content_internal(
1635        &self,
1636        req: LlmRequest,
1637        stream: bool,
1638    ) -> Result<LlmResponseStream> {
1639        let mut builder = self.client.generate_content();
1640        let thinking_config = self.request_thinking_config(&req);
1641
1642        // Build a map of function_name → thought_signature from FunctionCall parts
1643        // in model content. Gemini 3.x requires thought_signature on FunctionResponse
1644        // parts when thinking is active, but adk_core::Part::FunctionResponse doesn't
1645        // carry it (it's Gemini-specific). We recover it here at the provider boundary.
1646        let mut fn_call_signatures: std::collections::HashMap<String, String> =
1647            std::collections::HashMap::new();
1648        for content in &req.contents {
1649            if content.role == "model" {
1650                for part in &content.parts {
1651                    if let Part::FunctionCall { name, thought_signature: Some(sig), .. } = part {
1652                        fn_call_signatures.insert(name.clone(), sig.clone());
1653                    }
1654                }
1655            }
1656        }
1657
1658        // System contents become Gemini's `systemInstruction`, as adk-python and adk-go send
1659        // the agent's instruction. A request on a context cache keeps them as leading user
1660        // turns: the cache already carries a system instruction, and Gemini takes only one.
1661        let on_cache = req.config.as_ref().is_some_and(|config| config.cached_content.is_some());
1662        if !on_cache {
1663            let instruction: Vec<&str> = req
1664                .contents
1665                .iter()
1666                .filter(|content| content.role == "system")
1667                .flat_map(|content| content.parts.iter().filter_map(Part::text))
1668                .filter(|text| !text.trim().is_empty())
1669                .collect();
1670            if !instruction.is_empty() {
1671                builder = builder.with_system_instruction(instruction.join("\n\n"));
1672            }
1673        }
1674
1675        // Add contents using proper builder methods
1676        for content in &join_function_responses(&req.contents) {
1677            match content.role.as_str() {
1678                "system" if !on_cache => {}
1679                "user" | "system" => {
1680                    // For user messages, build gemini Content with potentially multiple parts
1681                    let mut gemini_parts = Vec::new();
1682                    for part in &content.parts {
1683                        match part {
1684                            Part::Text { text } => {
1685                                gemini_parts.push(adk_gemini::Part::Text {
1686                                    text: text.clone(),
1687                                    thought: None,
1688                                    thought_signature: None,
1689                                });
1690                            }
1691                            Part::InlineData { data, mime_type, annotations, .. } => {
1692                                let encoded = attachment::encode_base64(data);
1693                                gemini_parts.push(adk_gemini::Part::InlineData {
1694                                    inline_data: adk_gemini::Blob {
1695                                        mime_type: mime_type.clone(),
1696                                        data: encoded,
1697                                    },
1698                                    video_metadata: super::options::video_metadata(
1699                                        annotations.as_ref(),
1700                                    ),
1701                                });
1702                            }
1703                            // Gemini fetches File API, Cloud Storage and HTTP(S) URIs itself;
1704                            // any other scheme (`artifact://`, `file://`) would fail the
1705                            // request, so it stays a text reference.
1706                            Part::FileData { mime_type, file_uri, annotations }
1707                                if is_fetchable_uri(file_uri) =>
1708                            {
1709                                gemini_parts.push(adk_gemini::Part::FileData {
1710                                    file_data: adk_gemini::FileDataRef {
1711                                        mime_type: mime_type.clone(),
1712                                        file_uri: file_uri.clone(),
1713                                    },
1714                                    video_metadata: super::options::video_metadata(
1715                                        annotations.as_ref(),
1716                                    ),
1717                                });
1718                            }
1719                            Part::FileData { mime_type, file_uri, .. } => {
1720                                gemini_parts.push(adk_gemini::Part::Text {
1721                                    text: attachment::file_attachment_to_text(mime_type, file_uri),
1722                                    thought: None,
1723                                    thought_signature: None,
1724                                });
1725                            }
1726                            _ => {}
1727                        }
1728                    }
1729                    if !gemini_parts.is_empty() {
1730                        let user_content = adk_gemini::Content {
1731                            role: Some(adk_gemini::Role::User),
1732                            parts: Some(gemini_parts),
1733                        };
1734                        builder = builder.with_message(adk_gemini::Message {
1735                            content: user_content,
1736                            role: adk_gemini::Role::User,
1737                        });
1738                    }
1739                }
1740                "model" => {
1741                    // For model messages, build gemini Content
1742                    let mut gemini_parts = Vec::new();
1743                    for part in &content.parts {
1744                        match part {
1745                            Part::Text { text } => {
1746                                gemini_parts.push(adk_gemini::Part::Text {
1747                                    text: text.clone(),
1748                                    thought: None,
1749                                    thought_signature: None,
1750                                });
1751                            }
1752                            Part::Thinking { thinking, signature } => {
1753                                gemini_parts.push(adk_gemini::Part::Text {
1754                                    text: thinking.clone(),
1755                                    thought: Some(true),
1756                                    thought_signature: signature.clone(),
1757                                });
1758                            }
1759                            Part::FunctionCall { name, args, thought_signature, id } => {
1760                                gemini_parts.push(adk_gemini::Part::FunctionCall {
1761                                    function_call: adk_gemini::FunctionCall {
1762                                        name: name.clone(),
1763                                        args: args.clone(),
1764                                        id: id.clone(),
1765                                        thought_signature: None,
1766                                    },
1767                                    thought_signature: thought_signature.clone(),
1768                                });
1769                            }
1770                            // Only a payload that is a Gemini part replays: another
1771                            // provider's payload (Anthropic's preserved message holds its
1772                            // thinking) never reaches Gemini.
1773                            Part::ServerToolCall { server_tool_call: payload }
1774                            | Part::ServerToolResponse { server_tool_response: payload } => {
1775                                match Self::native_server_part(payload) {
1776                                    Some(native_part) => gemini_parts.push(native_part),
1777                                    None => tracing::debug!(
1778                                        "server tool payload is not a gemini part; left out"
1779                                    ),
1780                                }
1781                            }
1782                            _ => {}
1783                        }
1784                    }
1785                    if !gemini_parts.is_empty() {
1786                        let model_content = adk_gemini::Content {
1787                            role: Some(adk_gemini::Role::Model),
1788                            parts: Some(gemini_parts),
1789                        };
1790                        builder = builder.with_message(adk_gemini::Message {
1791                            content: model_content,
1792                            role: adk_gemini::Role::Model,
1793                        });
1794                    }
1795                }
1796                "function" => {
1797                    // For function responses, build content directly to attach thought_signature
1798                    // recovered from the preceding FunctionCall (Gemini 3.x requirement)
1799                    let mut gemini_parts = Vec::new();
1800                    for part in &content.parts {
1801                        if let Part::FunctionResponse { function_response, id, .. } = part {
1802                            let sig = fn_call_signatures.get(&function_response.name).cloned();
1803
1804                            // Build nested FunctionResponsePart entries for multimodal data
1805                            let mut fr_parts = Vec::new();
1806                            for inline in &function_response.inline_data {
1807                                let encoded = attachment::encode_base64(&inline.data);
1808                                fr_parts.push(adk_gemini::FunctionResponsePart::InlineData {
1809                                    inline_data: adk_gemini::Blob {
1810                                        mime_type: inline.mime_type.clone(),
1811                                        data: encoded,
1812                                    },
1813                                });
1814                            }
1815                            for file in &function_response.file_data {
1816                                fr_parts.push(adk_gemini::FunctionResponsePart::FileData {
1817                                    file_data: adk_gemini::FileDataRef {
1818                                        mime_type: file.mime_type.clone(),
1819                                        file_uri: file.file_uri.clone(),
1820                                    },
1821                                });
1822                            }
1823
1824                            let mut gemini_fr = adk_gemini::tools::FunctionResponse::new(
1825                                &function_response.name,
1826                                Self::gemini_function_response_payload(
1827                                    function_response.response.clone(),
1828                                ),
1829                            );
1830                            gemini_fr.parts = fr_parts;
1831                            // Echo the call id so Gemini 3.x strict response matching
1832                            // (id + name + count) can correlate this response.
1833                            gemini_fr.id = id.clone();
1834
1835                            gemini_parts.push(adk_gemini::Part::FunctionResponse {
1836                                function_response: gemini_fr,
1837                                thought_signature: sig,
1838                            });
1839                        }
1840                    }
1841                    if !gemini_parts.is_empty() {
1842                        let fn_content = adk_gemini::Content {
1843                            role: Some(adk_gemini::Role::User),
1844                            parts: Some(gemini_parts),
1845                        };
1846                        builder = builder.with_message(adk_gemini::Message {
1847                            content: fn_content,
1848                            role: adk_gemini::Role::User,
1849                        });
1850                    }
1851                }
1852                _ => {}
1853            }
1854        }
1855
1856        // Add generation config
1857        if let Some(config) = req.config {
1858            let has_schema = config.response_schema.is_some();
1859            let options = super::options::GeminiRequestOptions::from_config(&config);
1860            let gen_config = adk_gemini::GenerationConfig {
1861                temperature: config.temperature,
1862                top_p: config.top_p,
1863                top_k: config.top_k,
1864                max_output_tokens: config.max_output_tokens,
1865                stop_sequences: (!config.stop_sequences.is_empty())
1866                    .then_some(config.stop_sequences),
1867                seed: config.seed,
1868                presence_penalty: config.presence_penalty,
1869                frequency_penalty: config.frequency_penalty,
1870                response_logprobs: config.top_logprobs.map(|_| true),
1871                logprobs: config.top_logprobs.map(i32::from),
1872                // The response schema takes the same OpenAPI subset as tool parameters:
1873                // Gemini rejects `additionalProperties` and the other JSON Schema
1874                // keywords there with HTTP 400.
1875                response_schema: config
1876                    .response_schema
1877                    .map(|schema| self.schema_adapter().normalize_schema(schema)),
1878                response_modalities: config.response_modalities,
1879                response_mime_type: if has_schema {
1880                    Some("application/json".to_string())
1881                } else {
1882                    None
1883                },
1884                thinking_config: thinking_config.clone(),
1885                media_resolution: options.media_resolution,
1886                ..Default::default()
1887            };
1888            builder = builder.with_generation_config(gen_config);
1889
1890            // Attach cached content reference if provided
1891            if let Some(ref name) = config.cached_content {
1892                let handle = self.client.get_cached_content(name);
1893                builder = builder.with_cached_content(&handle);
1894            }
1895        } else if thinking_config.is_some() {
1896            // No generation config from the request, but we have a default
1897            // thinking config — apply it in an otherwise-default gen config.
1898            let gen_config = adk_gemini::GenerationConfig {
1899                thinking_config: thinking_config.clone(),
1900                ..Default::default()
1901            };
1902            builder = builder.with_generation_config(gen_config);
1903        }
1904
1905        // Add tools
1906        if !req.tools.is_empty() {
1907            let adapter = self.schema_adapter();
1908            use std::sync::LazyLock;
1909            static SCHEMA_CACHE: LazyLock<SchemaCache> = LazyLock::new(|| {
1910                SchemaCache::for_adapter(std::sync::Arc::new(GeminiSchemaAdapter::new()))
1911            });
1912            let (gemini_tools, tool_config) =
1913                Self::build_gemini_tools(&req.tools, adapter, &SCHEMA_CACHE)?;
1914            for tool in gemini_tools {
1915                builder = builder.with_tool(tool);
1916            }
1917            if tool_config != adk_gemini::ToolConfig::default() {
1918                builder = builder.with_tool_config(tool_config);
1919            }
1920        }
1921
1922        // Declare server-side RAG grounding; the Vertex backend injects it
1923        // as a `retrieval` tool at send time (validate_request_contract has
1924        // already rejected the Studio backend at this point).
1925        #[cfg(feature = "gemini-vertex")]
1926        if let Some(store) = &self.vertex_rag_store {
1927            builder = builder.with_vertex_rag_store(store.clone());
1928        }
1929
1930        if stream {
1931            adk_telemetry::debug!("Executing streaming request");
1932            let response_stream = builder.execute_stream().await.map_err(|e| {
1933                let error = gemini_error_to_adk(&e);
1934                adk_telemetry::error!(error = %error.diagnostics(), "model request failed");
1935                error
1936            })?;
1937
1938            let mapped_stream = async_stream::stream! {
1939                let mut stream = response_stream;
1940                let mut saw_partial_chunk = false;
1941                // Function calls from partial chunks, yielded once on the final chunk.
1942                let mut deferred_calls: Vec<Part> = Vec::new();
1943                // Only a chunk with `finishReason` (or a prompt block) ends a Gemini turn.
1944                let mut finished = false;
1945                // Gemini reports usage cumulatively per chunk; built-in tool uses follow suit.
1946                let mut builtin_uses = GeminiBuiltinToolUses::default();
1947                while let Some(result) = stream.try_next().await.transpose() {
1948                    match result {
1949                        Ok(resp) => {
1950                            builtin_uses.observe(&resp);
1951                            match Self::convert_response(&resp) {
1952                                Ok(mut llm_resp) => {
1953                                    if let Some(usage) = llm_resp.usage_metadata.as_mut() {
1954                                        usage.builtin_tool_uses = builtin_uses.uses();
1955                                    }
1956                                    finished |= llm_resp.finish_reason.is_some();
1957                                    let (chunks, next_saw_partial) =
1958                                        Self::stream_chunks_from_response(
1959                                            llm_resp,
1960                                            saw_partial_chunk,
1961                                            &mut deferred_calls,
1962                                        );
1963                                    saw_partial_chunk = next_saw_partial;
1964                                    for chunk in chunks {
1965                                        yield Ok(chunk);
1966                                    }
1967                                }
1968                                Err(e) => {
1969                                    adk_telemetry::error!(error = %e.diagnostics(), "failed to convert response");
1970                                    yield Err(e);
1971                                    return;
1972                                }
1973                            }
1974                        }
1975                        Err(e) => {
1976                            if finished && matches!(&e,
1977                                adk_gemini::ClientError::PerformRequestNew { .. }
1978                                | adk_gemini::ClientError::PerformRequest { .. }
1979                                | adk_gemini::ClientError::BadPart { .. }
1980                                | adk_gemini::ClientError::Deserialize { .. }
1981                                | adk_gemini::ClientError::DecodeResponse { .. }
1982                                | adk_gemini::ClientError::Io { .. }
1983                            ) {
1984                                return;
1985                            }
1986                            let error = gemini_error_to_adk(&e);
1987                            adk_telemetry::error!(error = %error.diagnostics(), "stream error");
1988                            yield Err(error);
1989                            return;
1990                        }
1991                    }
1992                }
1993                if !finished {
1994                    yield Err(adk_core::AdkError::new(
1995                        ErrorComponent::Model,
1996                        ErrorCategory::Unavailable,
1997                        "model.gemini.unfinished_stream",
1998                        "Gemini stream ended before any chunk carried a finish reason",
1999                    )
2000                    .with_provider("gemini"));
2001                }
2002            };
2003
2004            Ok(crate::usage_tracking::with_terminal_usage(Box::pin(mapped_stream)))
2005        } else {
2006            adk_telemetry::debug!("Executing blocking request");
2007            let response = builder.execute().await.map_err(|e| {
2008                let error = gemini_error_to_adk(&e);
2009                adk_telemetry::error!(error = %error.diagnostics(), "model request failed");
2010                error
2011            })?;
2012
2013            let llm_response = Self::convert_response(&response)?;
2014
2015            let stream = async_stream::stream! {
2016                yield Ok(llm_response);
2017            };
2018
2019            Ok(Box::pin(stream))
2020        }
2021    }
2022
2023    /// Create a cached content resource with the given system instruction, tools, and TTL.
2024    ///
2025    /// Returns the cache name (e.g., "cachedContents/abc123") on success.
2026    /// The cache is created using the model configured on this `GeminiModel` instance.
2027    ///
2028    /// # Errors
2029    ///
2030    /// Returns `model.gemini.explicit_cache_unsupported` for a model without explicit caching
2031    /// (see [`supports_explicit_cache`](Self::supports_explicit_cache)), and an error when the
2032    /// cache cannot be created.
2033    pub async fn create_cached_content(
2034        &self,
2035        system_instruction: &str,
2036        tools: &adk_core::ToolDeclarations,
2037        ttl_seconds: u32,
2038    ) -> Result<String> {
2039        if !self.supports_explicit_cache() {
2040            return Err(adk_core::AdkError::new(
2041                ErrorComponent::Model,
2042                ErrorCategory::Unsupported,
2043                "model.gemini.explicit_cache_unsupported",
2044                format!(
2045                    "{} does not support explicit context caching; it caches prompts of at least \
2046                     4,096 tokens implicitly",
2047                    self.model_name
2048                ),
2049            )
2050            .with_provider("gemini"));
2051        }
2052        let mut cache_builder = self
2053            .client
2054            .create_cache()
2055            .with_system_instruction(system_instruction)
2056            .with_ttl(std::time::Duration::from_secs(u64::from(ttl_seconds)));
2057
2058        let adapter = self.schema_adapter();
2059        use std::sync::LazyLock;
2060        static SCHEMA_CACHE: LazyLock<SchemaCache> = LazyLock::new(|| {
2061            SchemaCache::for_adapter(std::sync::Arc::new(GeminiSchemaAdapter::new()))
2062        });
2063        let (gemini_tools, tool_config) = Self::build_gemini_tools(tools, adapter, &SCHEMA_CACHE)?;
2064        if !gemini_tools.is_empty() {
2065            cache_builder = cache_builder.with_tools(gemini_tools);
2066        }
2067        if tool_config != adk_gemini::ToolConfig::default() {
2068            cache_builder = cache_builder.with_tool_config(tool_config);
2069        }
2070
2071        let handle = cache_builder
2072            .execute()
2073            .await
2074            .map_err(|e| adk_core::AdkError::model(format!("cache creation failed: {e}")))?;
2075
2076        Ok(handle.name().to_string())
2077    }
2078
2079    /// Delete a cached content resource by name.
2080    pub async fn delete_cached_content(&self, name: &str) -> Result<()> {
2081        let handle = self.client.get_cached_content(name);
2082        handle
2083            .delete()
2084            .await
2085            .map_err(|(_, e)| adk_core::AdkError::model(format!("cache deletion failed: {e}")))?;
2086        Ok(())
2087    }
2088
2089    /// Uploads `bytes` through the Gemini File API, for media above the 20 MB a request may
2090    /// carry inline; a `Part::FileData` naming the returned [`GeminiFile::uri`] then goes
2091    /// out as native `fileData`. A video is usable once its state is
2092    /// [`GeminiFileState::Active`] ([`wait_for_file`](Self::wait_for_file)). Files expire
2093    /// after 48 hours. AI Studio only: Vertex AI reads Cloud Storage URIs instead.
2094    ///
2095    /// # Errors
2096    ///
2097    /// An invalid MIME type, the upload's failure, or an answer without a file URI.
2098    pub async fn upload_file(
2099        &self,
2100        bytes: Vec<u8>,
2101        mime_type: &str,
2102        display_name: Option<&str>,
2103    ) -> Result<GeminiFile> {
2104        let parsed: mime::Mime = mime_type.parse().map_err(|_| {
2105            adk_core::AdkError::model(format!("`{mime_type}` is not a valid MIME type"))
2106        })?;
2107        let mut builder = self.client.create_file(bytes).with_mime_type(parsed);
2108        if let Some(name) = display_name {
2109            builder = builder.display_name(name);
2110        }
2111        let handle = builder
2112            .upload()
2113            .await
2114            .map_err(|e| adk_core::AdkError::model(format!("file upload failed: {e}")))?;
2115        GeminiFile::from_wire(handle.get_file_meta())
2116    }
2117
2118    /// The File API's current view of an uploaded file.
2119    ///
2120    /// # Errors
2121    ///
2122    /// The lookup's failure, or an answer without a file URI.
2123    pub async fn get_file(&self, name: &str) -> Result<GeminiFile> {
2124        let handle = self
2125            .client
2126            .get_file(name)
2127            .await
2128            .map_err(|e| adk_core::AdkError::model(format!("file lookup failed: {e}")))?;
2129        GeminiFile::from_wire(handle.get_file_meta())
2130    }
2131
2132    /// Polls an uploaded file every `interval` until Gemini has processed it.
2133    ///
2134    /// # Errors
2135    ///
2136    /// A file whose processing failed, one still processing after `timeout`, and the
2137    /// lookup's failure.
2138    pub async fn wait_for_file(
2139        &self,
2140        name: &str,
2141        interval: std::time::Duration,
2142        timeout: std::time::Duration,
2143    ) -> Result<GeminiFile> {
2144        let started = std::time::Instant::now();
2145        loop {
2146            let file = self.get_file(name).await?;
2147            match file.state {
2148                GeminiFileState::Active => return Ok(file),
2149                GeminiFileState::Failed => {
2150                    return Err(adk_core::AdkError::model(format!(
2151                        "Gemini could not process file {name}; check that it is a supported format"
2152                    )));
2153                }
2154                GeminiFileState::Processing | GeminiFileState::Unknown => {}
2155            }
2156            if started.elapsed() >= timeout {
2157                return Err(adk_core::AdkError::new(
2158                    adk_core::ErrorComponent::Model,
2159                    adk_core::ErrorCategory::Timeout,
2160                    "model.gemini.file_processing_timeout",
2161                    format!("file {name} was still processing after {timeout:?}"),
2162                ));
2163            }
2164            tokio::time::sleep(interval).await;
2165        }
2166    }
2167
2168    /// Deletes an uploaded file.
2169    ///
2170    /// # Errors
2171    ///
2172    /// The deletion's failure.
2173    pub async fn delete_file(&self, name: &str) -> Result<()> {
2174        let handle = self
2175            .client
2176            .get_file(name)
2177            .await
2178            .map_err(|e| adk_core::AdkError::model(format!("file lookup failed: {e}")))?;
2179        handle
2180            .delete()
2181            .await
2182            .map_err(|(_, e)| adk_core::AdkError::model(format!("file deletion failed: {e}")))
2183    }
2184
2185    /// Drives a single turn through the Interactions API (Beta), non-streaming.
2186    ///
2187    /// This is the Interactions counterpart to
2188    /// [`generate_content_internal`](Self::generate_content_internal). It builds
2189    /// a [`CreateInteractionRequest`](adk_gemini::interactions::CreateInteractionRequest)
2190    /// from `req` via [`interactions_convert::build_request`], sends it, polls to
2191    /// completion when running in the background, maps terminal failure statuses
2192    /// to errors, and converts the final interaction into a single
2193    /// [`LlmResponse`].
2194    ///
2195    /// Behavior of note:
2196    ///
2197    /// - **Background completion (Requirement 7.5).** When `background` is set
2198    ///   and the first response is neither terminal nor awaiting a tool result,
2199    ///   the interaction is polled via
2200    ///   [`get_interaction`](adk_gemini::Gemini::get_interaction) every
2201    ///   `poll_interval` until it reaches a terminal or `requires_action` state.
2202    /// - **Stale continuation fallback (Requirement 4.4).** If the initial send
2203    ///   fails with a `NotFound` error *and* the request carried a
2204    ///   `previous_response_id`, the request is transparently rebuilt without
2205    ///   stateful continuation (full transcript, no `previous_interaction_id`)
2206    ///   and re-sent once. The original `NotFound` is not surfaced.
2207    /// - **Terminal failure (Requirements 7.7 / 9.2).** A final `failed` /
2208    ///   `budget_exceeded` status becomes an [`adk_core::AdkError`].
2209    ///
2210    /// The streaming counterpart is
2211    /// [`generate_interactions_stream`](Self::generate_interactions_stream).
2212    #[cfg(feature = "gemini-interactions")]
2213    async fn generate_interactions_once(&self, req: LlmRequest) -> Result<LlmResponse> {
2214        use super::interactions_convert;
2215
2216        // The Interactions target is always populated when the transport is
2217        // active (set by `use_interactions_api`); guard defensively.
2218        let target = self.interaction_target.as_ref().ok_or_else(|| {
2219            adk_core::AdkError::new(
2220                ErrorComponent::Model,
2221                ErrorCategory::InvalidInput,
2222                "model.gemini.interactions.missing_target",
2223                "the Interactions transport is active but no validated target is configured",
2224            )
2225            .with_provider("gemini")
2226        })?;
2227
2228        // Resolve the thinking level (Gemini 3 level-based reasoning). Budget-only
2229        // configs (Gemini 2.5) carry no level, so this stays `None` for them.
2230        let thinking_level = self.request_thinking_config(&req).and_then(|c| c.thinking_level);
2231
2232        let stateful = self.interaction_options.stateful;
2233        let store = self.interaction_options.store;
2234        let background = self.resolve_background();
2235
2236        // Build the request and stamp the background flag.
2237        let mut request =
2238            interactions_convert::build_request(&req, target, thinking_level, stateful, store)?;
2239        request.background = Some(background);
2240
2241        // Send, with a transparent transcript fallback for a stale continuation id.
2242        let interaction = match self.client.send_interaction(request.clone()).await {
2243            Ok(interaction) => interaction,
2244            Err(error) => {
2245                let mapped = gemini_error_to_adk(&error);
2246                // Requirement 4.4: a rejected `previous_interaction_id` (retention
2247                // expiry) maps to NotFound. Rebuild statelessly (full transcript,
2248                // no continuation id) and retry once, without surfacing the error.
2249                if mapped.category == ErrorCategory::NotFound && req.previous_response_id.is_some()
2250                {
2251                    let mut fallback = interactions_convert::build_request(
2252                        &req,
2253                        target,
2254                        thinking_level,
2255                        /* stateful */ false,
2256                        store,
2257                    )?;
2258                    fallback.background = Some(background);
2259                    self.client
2260                        .send_interaction(fallback)
2261                        .await
2262                        .map_err(|e| gemini_error_to_adk(&e))?
2263                } else {
2264                    return Err(mapped);
2265                }
2266            }
2267        };
2268
2269        // Background completion: poll until terminal or awaiting a tool result.
2270        let final_interaction = if background {
2271            self.poll_interaction_to_completion(interaction).await?
2272        } else {
2273            interaction
2274        };
2275
2276        // Requirements 7.7 / 9.2: surface terminal failure statuses as errors.
2277        interaction_status_to_result(final_interaction.status)?;
2278
2279        Ok(interactions_convert::to_llm_response(&final_interaction))
2280    }
2281
2282    /// Polls a background interaction until it reaches a terminal or
2283    /// `requires_action` state, honoring the configured `poll_interval`
2284    /// (Requirement 7.5).
2285    ///
2286    /// Returns immediately when the interaction is already terminal or awaiting
2287    /// a tool result. Otherwise it sleeps for `poll_interval` and re-fetches via
2288    /// [`get_interaction`](adk_gemini::Gemini::get_interaction) (with
2289    /// `include_input = false`) until one of those states is reached, or until a
2290    /// bounded safeguard (`MAX_POLL_ATTEMPTS`) trips.
2291    ///
2292    /// ## Cancellation (Requirement 7.6)
2293    ///
2294    /// True invocation-driven cancellation (calling
2295    /// [`cancel_interaction`](adk_gemini::Gemini::cancel_interaction) when the
2296    /// caller cancels) is **not reachable from this layer**: the [`Llm`] trait's
2297    /// [`generate_content`](Llm::generate_content) signature receives only an
2298    /// [`LlmRequest`] and a `stream` flag — it has no `InvocationContext` or
2299    /// cancellation token. Cancellation is handled by the runner at the
2300    /// event-stream boundary: when a run is cancelled the runner stops consuming
2301    /// the agent's event stream, which drops this future and cancels its
2302    /// `await` points (the in-flight `sleep` / `get_interaction`) cooperatively.
2303    /// The polled interaction is left running server-side; reviving it to issue
2304    /// an explicit `cancel_interaction` would require threading the cancellation
2305    /// token through the trait, which is intentionally out of scope here (the
2306    /// trait is transport-only and shared by every provider).
2307    ///
2308    /// The `MAX_POLL_ATTEMPTS` bound is a safeguard against an interaction that
2309    /// never reaches a terminal/`requires_action` state (e.g. a server-side
2310    /// stall): rather than looping forever it returns a [`ErrorCategory::Timeout`]
2311    /// error so the call fails fast instead of hanging.
2312    #[cfg(feature = "gemini-interactions")]
2313    async fn poll_interaction_to_completion(
2314        &self,
2315        interaction: adk_gemini::interactions::Interaction,
2316    ) -> Result<adk_gemini::interactions::Interaction> {
2317        /// Upper bound on poll iterations before giving up, guarding against an
2318        /// interaction that never settles. With the default 1s `poll_interval`
2319        /// this is ~10 minutes; shorter intervals trade latency for a tighter
2320        /// wall-clock cap. Deep Research agents complete well within this.
2321        const MAX_POLL_ATTEMPTS: u32 = 600;
2322
2323        let mut current = interaction;
2324        let mut attempts: u32 = 0;
2325        while !current.status.is_terminal() && !current.status.requires_action() {
2326            if attempts >= MAX_POLL_ATTEMPTS {
2327                return Err(adk_core::AdkError::new(
2328                    ErrorComponent::Model,
2329                    ErrorCategory::Timeout,
2330                    "model.gemini.interactions.poll_timeout",
2331                    format!(
2332                        "the Gemini interaction did not reach a terminal or requires_action \
2333                         state after {MAX_POLL_ATTEMPTS} poll attempts"
2334                    ),
2335                )
2336                .with_provider("gemini"));
2337            }
2338            attempts += 1;
2339            tokio::time::sleep(self.interaction_options.poll_interval).await;
2340            current = self
2341                .client
2342                .get_interaction(&current.id, false)
2343                .await
2344                .map_err(|e| gemini_error_to_adk(&e))?;
2345        }
2346        Ok(current)
2347    }
2348
2349    /// Drives a single turn through the Interactions API (Beta) as an SSE
2350    /// stream, yielding partial→final [`LlmResponse`] chunks (Requirement 7.4).
2351    ///
2352    /// This is the streaming counterpart to
2353    /// [`generate_interactions_once`](Self::generate_interactions_once). It
2354    /// builds the request the same way, forces non-background completion
2355    /// (streaming and background polling are mutually exclusive completion
2356    /// modes — SSE delivers the turn incrementally, so `background` is set to
2357    /// `false`), opens the SSE stream via
2358    /// [`send_interaction_stream`](adk_gemini::Gemini::send_interaction_stream),
2359    /// and folds each [`InteractionSseEvent`](adk_gemini::interactions::InteractionSseEvent)
2360    /// into chunks via [`interactions_convert::sse_event_to_chunk`].
2361    ///
2362    /// Stream setup (target resolution, request building, opening the SSE
2363    /// connection) is fallible and returns `Err` synchronously, so
2364    /// `execute_with_retry` (which wraps this in `generate_content`) can retry
2365    /// transient setup failures. Errors that occur *after* the stream starts
2366    /// are yielded into the stream and not retried, mirroring the
2367    /// generateContent streaming path. The stream fails when it ends before
2368    /// `interaction.completed`, and when the interaction reaches `failed` or
2369    /// `budget_exceeded`.
2370    ///
2371    /// The stale-continuation fallback used by the non-streaming path is not
2372    /// applied here: a `NotFound` on stream setup surfaces as a normal error
2373    /// (the streaming path is opt-in and lower-level; callers that need
2374    /// transparent retention fallback use the default non-streaming path).
2375    #[cfg(feature = "gemini-interactions")]
2376    async fn generate_interactions_stream(&self, req: LlmRequest) -> Result<LlmResponseStream> {
2377        use super::interactions_convert::{self, SseAccumulator, sse_event_to_chunk};
2378
2379        let target = self.interaction_target.as_ref().ok_or_else(|| {
2380            adk_core::AdkError::new(
2381                ErrorComponent::Model,
2382                ErrorCategory::InvalidInput,
2383                "model.gemini.interactions.missing_target",
2384                "the Interactions transport is active but no validated target is configured",
2385            )
2386            .with_provider("gemini")
2387        })?;
2388
2389        let thinking_level = self.request_thinking_config(&req).and_then(|c| c.thinking_level);
2390        let stateful = self.interaction_options.stateful;
2391        let store = self.interaction_options.store;
2392
2393        let mut request =
2394            interactions_convert::build_request(&req, target, thinking_level, stateful, store)?;
2395        // Streaming uses SSE for incremental completion, not background polling;
2396        // the two are distinct completion modes (Requirement 7.4 vs 7.5). Force
2397        // foreground so the server streams the turn rather than returning a
2398        // background handle.
2399        request.background = Some(false);
2400
2401        let sse_stream = self
2402            .client
2403            .send_interaction_stream(request)
2404            .await
2405            .map_err(|e| gemini_error_to_adk(&e))?;
2406
2407        let mapped = async_stream::stream! {
2408            use adk_gemini::interactions::{InteractionSseEvent, InteractionStatus};
2409
2410            let mut sse_stream = sse_stream;
2411            let mut acc = SseAccumulator::new();
2412            while let Some(result) = sse_stream.try_next().await.transpose() {
2413                match result {
2414                    Ok(event) => {
2415                        // A terminal failure status fails the turn, whether it arrives on
2416                        // `interaction.completed` or as a status update.
2417                        let (status, completed) = match &event {
2418                            InteractionSseEvent::InteractionCompleted { interaction, .. } => {
2419                                (Some(interaction.status), true)
2420                            }
2421                            InteractionSseEvent::InteractionStatusUpdate {
2422                                status:
2423                                    status @ (InteractionStatus::Failed
2424                                    | InteractionStatus::BudgetExceeded),
2425                                ..
2426                            } => (Some(*status), false),
2427                            _ => (None, false),
2428                        };
2429                        if let Some(Err(error)) = status.map(interaction_status_to_result) {
2430                            yield Err(error);
2431                            return;
2432                        }
2433                        match sse_event_to_chunk(event, &mut acc) {
2434                            Some(Err(error)) => {
2435                                yield Err(error);
2436                                return;
2437                            }
2438                            Some(Ok(chunk)) => yield Ok(chunk),
2439                            None => {}
2440                        }
2441                        if completed {
2442                            return;
2443                        }
2444                    }
2445                    Err(e) => {
2446                        let error = gemini_error_to_adk(&e);
2447                        adk_telemetry::error!(error = %error.diagnostics(), "interaction stream error");
2448                        yield Err(error);
2449                        return;
2450                    }
2451                }
2452            }
2453            yield Err(adk_core::AdkError::new(
2454                ErrorComponent::Model,
2455                ErrorCategory::Unavailable,
2456                "model.gemini.interactions.unfinished_stream",
2457                "Gemini interaction stream ended before interaction.completed",
2458            )
2459            .with_provider("gemini"));
2460        };
2461
2462        Ok(Box::pin(mapped))
2463    }
2464}
2465
2466#[async_trait]
2467impl Llm for GeminiModel {
2468    // The request's `maxOutputTokens`, thinking included, or the model's output limit.
2469    fn max_cost_micro_usd(&self, request: &adk_core::LlmRequest) -> Option<u64> {
2470        crate::pricing::PricingCatalog::standard().max_cost_micro_usd(
2471            Some("gemini"),
2472            self.name(),
2473            request,
2474            crate::pricing::request_output_cap(request),
2475        )
2476    }
2477
2478    fn context_window(&self) -> Option<u64> {
2479        crate::pricing::PricingCatalog::standard().context_window(Some("gemini"), self.name())
2480    }
2481
2482    // AI Studio, a custom base URL, or the Vertex AI endpoint of the configured location.
2483    fn data_destinations(&self) -> Vec<adk_core::DataDestination> {
2484        self.client
2485            .endpoint()
2486            .map(|url| adk_core::DataDestination::of_url("gemini", url))
2487            .into_iter()
2488            .collect()
2489    }
2490
2491    fn name(&self) -> &str {
2492        &self.model_name
2493    }
2494
2495    fn schema_adapter(&self) -> &dyn SchemaAdapter {
2496        use std::sync::LazyLock;
2497        static ADAPTER: LazyLock<GeminiSchemaAdapter> = LazyLock::new(GeminiSchemaAdapter::new);
2498        &*ADAPTER
2499    }
2500
2501    #[cfg(feature = "gemini-interactions")]
2502    fn uses_interactions_api(&self) -> bool {
2503        self.transport == GeminiTransport::Interactions
2504    }
2505
2506    // generateContent serves `google_search` beside function tools on both backends, with
2507    // no domain allowlist; the Interactions transport refuses that mix (spec 3.1 §7.20).
2508    fn native_web_search(&self) -> Option<adk_core::NativeWebSearch> {
2509        #[cfg(feature = "gemini-interactions")]
2510        if self.transport == GeminiTransport::Interactions {
2511            return None;
2512        }
2513        Some(adk_core::NativeWebSearch::new(
2514            "gemini",
2515            adk_core::NativeWebSearchTool::GoogleSearch,
2516            false,
2517        ))
2518    }
2519
2520    // Named distinctly from the agent layer's `call_llm` span (which carries
2521    // the gcp.vertex.agent.* attributes and is what trace exporters capture):
2522    // this is the model-transport layer, so traces show one `call_llm` per
2523    // LLM call instead of an identical nested pair.
2524    #[adk_telemetry::instrument(
2525        name = "model.generate_content",
2526        skip(self, req),
2527        fields(
2528            model.name = %self.model_name,
2529            stream = %stream,
2530            request.contents_count = %req.contents.len(),
2531            request.tools_count = %req.tools.len()
2532        )
2533    )]
2534    async fn generate_content(
2535        &self,
2536        mut req: LlmRequest,
2537        stream: bool,
2538    ) -> Result<LlmResponseStream> {
2539        // Native items reach this provider only from the turns its own origin marks.
2540        adk_core::history::retain_replayable(
2541            &mut req.contents,
2542            &adk_core::history::ProviderOrigin::new("gemini", &self.model_name),
2543        );
2544        adk_telemetry::info!("Generating content");
2545        self.validate_request_contract(&req, stream)?;
2546        #[cfg(feature = "gemini-vertex")]
2547        let provider = if self.vertex_backend { "gemini-vertex" } else { "gemini" };
2548        #[cfg(not(feature = "gemini-vertex"))]
2549        let provider = "gemini";
2550        let usage_span = crate::telemetry::inference_span(provider, &self.model_name, stream, &req);
2551
2552        // Dispatch on the configured transport. The default `GenerateContent`
2553        // path is unchanged; the Interactions path (task 7.3/7.4) is only
2554        // reachable when `use_interactions_api` switched the transport.
2555        //
2556        // Retries only cover request setup/execution. Stream failures after the
2557        // stream starts are yielded to the caller and are not replayed
2558        // automatically.
2559        #[cfg(feature = "gemini-interactions")]
2560        if self.transport == GeminiTransport::Interactions {
2561            // Streaming and non-streaming are distinct completion modes. The
2562            // streaming path consumes the Interactions SSE stream and yields
2563            // partial→final chunks; the non-streaming path sends a single
2564            // request and (optionally) polls a background interaction to
2565            // completion. `execute_with_retry` wraps only request *setup* in
2566            // both cases — once a stream starts, its mid-flight errors are
2567            // surfaced to the caller rather than replayed (mirroring the
2568            // generateContent streaming path).
2569            if stream {
2570                let mapped =
2571                    execute_with_retry(&self.retry_config, is_retryable_model_error, || {
2572                        self.generate_interactions_stream(req.clone())
2573                    })
2574                    .await?;
2575                return Ok(crate::usage_tracking::with_priced_usage_tracking(
2576                    mapped,
2577                    usage_span,
2578                    "gemini",
2579                    &self.model_name,
2580                ));
2581            }
2582            let response = execute_with_retry(&self.retry_config, is_retryable_model_error, || {
2583                self.generate_interactions_once(req.clone())
2584            })
2585            .await?;
2586            let single = async_stream::stream! {
2587                yield Ok(response);
2588            };
2589            return Ok(crate::usage_tracking::with_priced_usage_tracking(
2590                Box::pin(single),
2591                usage_span,
2592                "gemini",
2593                &self.model_name,
2594            ));
2595        }
2596
2597        let result = execute_with_retry(&self.retry_config, is_retryable_model_error, || {
2598            self.generate_content_internal(req.clone(), stream)
2599        })
2600        .await?;
2601        Ok(crate::usage_tracking::with_priced_usage_tracking(
2602            result,
2603            usage_span,
2604            "gemini",
2605            &self.model_name,
2606        ))
2607    }
2608}
2609
2610#[cfg(test)]
2611mod native_tool_tests {
2612    use super::*;
2613
2614    fn test_adapter() -> GeminiSchemaAdapter {
2615        GeminiSchemaAdapter::new()
2616    }
2617
2618    fn test_cache() -> SchemaCache {
2619        SchemaCache::for_adapter(std::sync::Arc::new(GeminiSchemaAdapter::new()))
2620    }
2621
2622    #[test]
2623    fn test_build_gemini_tools_supports_native_tool_metadata() {
2624        let mut tools = adk_core::ToolDeclarations::new();
2625        tools.insert(
2626            "google_search".to_string(),
2627            serde_json::json!({
2628                "x-adk-gemini-tool": {
2629                    "google_search": {}
2630                }
2631            }),
2632        );
2633        tools.insert(
2634            "lookup_weather".to_string(),
2635            serde_json::json!({
2636                "name": "lookup_weather",
2637                "description": "lookup weather",
2638                "parameters": {
2639                    "type": "object",
2640                    "properties": {
2641                        "city": { "type": "string" }
2642                    }
2643                }
2644            }),
2645        );
2646
2647        let adapter = test_adapter();
2648        let cache = test_cache();
2649        let (gemini_tools, tool_config) = GeminiModel::build_gemini_tools(&tools, &adapter, &cache)
2650            .expect("tool conversion should succeed");
2651
2652        assert_eq!(gemini_tools.len(), 2);
2653        assert_eq!(tool_config.include_server_side_tool_invocations, Some(true));
2654    }
2655
2656    #[test]
2657    fn test_build_gemini_tools_sets_flag_for_builtin_only() {
2658        let mut tools = adk_core::ToolDeclarations::new();
2659        tools.insert(
2660            "google_search".to_string(),
2661            serde_json::json!({
2662                "x-adk-gemini-tool": {
2663                    "google_search": {}
2664                }
2665            }),
2666        );
2667
2668        let adapter = test_adapter();
2669        let cache = test_cache();
2670        let (_gemini_tools, tool_config) =
2671            GeminiModel::build_gemini_tools(&tools, &adapter, &cache)
2672                .expect("tool conversion should succeed");
2673
2674        assert_eq!(
2675            tool_config.include_server_side_tool_invocations,
2676            Some(true),
2677            "includeServerSideToolInvocations should be set even with only built-in tools"
2678        );
2679    }
2680
2681    #[test]
2682    fn test_build_gemini_tools_no_flag_for_function_only() {
2683        let mut tools = adk_core::ToolDeclarations::new();
2684        tools.insert(
2685            "lookup_weather".to_string(),
2686            serde_json::json!({
2687                "name": "lookup_weather",
2688                "description": "lookup weather",
2689                "parameters": {
2690                    "type": "object",
2691                    "properties": {
2692                        "city": { "type": "string" }
2693                    }
2694                }
2695            }),
2696        );
2697
2698        let adapter = test_adapter();
2699        let cache = test_cache();
2700        let (_gemini_tools, tool_config) =
2701            GeminiModel::build_gemini_tools(&tools, &adapter, &cache)
2702                .expect("tool conversion should succeed");
2703
2704        assert_eq!(
2705            tool_config.include_server_side_tool_invocations, None,
2706            "includeServerSideToolInvocations should NOT be set for function-only tools"
2707        );
2708    }
2709
2710    #[test]
2711    fn test_build_gemini_tools_merges_native_tool_config() {
2712        let mut tools = adk_core::ToolDeclarations::new();
2713        tools.insert(
2714            "google_maps".to_string(),
2715            serde_json::json!({
2716                "x-adk-gemini-tool": {
2717                    "google_maps": {
2718                        "enable_widget": true
2719                    }
2720                },
2721                "x-adk-gemini-tool-config": {
2722                    "retrievalConfig": {
2723                        "latLng": {
2724                            "latitude": 1.23,
2725                            "longitude": 4.56
2726                        }
2727                    }
2728                }
2729            }),
2730        );
2731
2732        let adapter = test_adapter();
2733        let cache = test_cache();
2734        let (_gemini_tools, tool_config) =
2735            GeminiModel::build_gemini_tools(&tools, &adapter, &cache)
2736                .expect("tool conversion should succeed");
2737
2738        assert_eq!(
2739            tool_config.retrieval_config,
2740            Some(serde_json::json!({
2741                "latLng": {
2742                    "latitude": 1.23,
2743                    "longitude": 4.56
2744                }
2745            }))
2746        );
2747    }
2748
2749    #[test]
2750    fn test_response_schema_is_normalized_like_parameters() {
2751        // Regression test: MCP tools provide an output_schema that becomes the
2752        // `response` field in the tool declaration. Gemini rejects JSON-Schema
2753        // dialect fields ($schema, additionalProperties) in the response schema.
2754        // This test verifies that the response schema is normalized the same way
2755        // parameters are — stripping unsupported keywords.
2756        let mut tools = adk_core::ToolDeclarations::new();
2757        tools.insert(
2758            "read_file".to_string(),
2759            serde_json::json!({
2760                "name": "read_file",
2761                "description": "Read a file from the filesystem",
2762                "parameters": {
2763                    "$schema": "http://json-schema.org/draft-07/schema#",
2764                    "type": "object",
2765                    "properties": {
2766                        "path": { "type": "string", "description": "File path" }
2767                    },
2768                    "required": ["path"],
2769                    "additionalProperties": false
2770                },
2771                "response": {
2772                    "$schema": "http://json-schema.org/draft-07/schema#",
2773                    "type": "object",
2774                    "properties": {
2775                        "content": { "type": "string", "description": "File contents" }
2776                    },
2777                    "required": ["content"],
2778                    "additionalProperties": false
2779                }
2780            }),
2781        );
2782
2783        let adapter = test_adapter();
2784        let cache = test_cache();
2785        let (gemini_tools, _) = GeminiModel::build_gemini_tools(&tools, &adapter, &cache)
2786            .expect("tool conversion should succeed");
2787
2788        // Find the function declaration
2789        let func_tool = gemini_tools
2790            .iter()
2791            .find(|t| matches!(t, adk_gemini::Tool::Function { .. }))
2792            .expect("should have function declarations");
2793
2794        let decls = match func_tool {
2795            adk_gemini::Tool::Function { function_declarations } => function_declarations,
2796            _ => panic!("expected Function tool"),
2797        };
2798
2799        let decl = &decls[0];
2800        let decl_json = serde_json::to_value(decl).unwrap();
2801
2802        // Parameters should be normalized (no $schema, no additionalProperties)
2803        let params = &decl_json["parameters"];
2804        assert!(params.get("$schema").is_none(), "parameters.$schema should be stripped");
2805        assert!(
2806            params.get("additionalProperties").is_none(),
2807            "parameters.additionalProperties should be stripped"
2808        );
2809
2810        // Response should ALSO be normalized (this was the bug)
2811        let response = &decl_json["response"];
2812        assert!(
2813            response.get("$schema").is_none(),
2814            "response.$schema should be stripped (was the bug: copied raw)"
2815        );
2816        assert!(
2817            response.get("additionalProperties").is_none(),
2818            "response.additionalProperties should be stripped (was the bug: copied raw)"
2819        );
2820    }
2821}
2822
2823#[async_trait]
2824impl CacheCapable for GeminiModel {
2825    async fn create_cache(
2826        &self,
2827        system_instruction: &str,
2828        tools: &adk_core::ToolDeclarations,
2829        ttl_seconds: u32,
2830    ) -> Result<String> {
2831        self.create_cached_content(system_instruction, tools, ttl_seconds).await
2832    }
2833
2834    async fn delete_cache(&self, name: &str) -> Result<()> {
2835        self.delete_cached_content(name).await
2836    }
2837}
2838
2839/// Joins adjacent `function` contents into one. Gemini expects the responses to a turn of
2840/// parallel calls in a single content, one function response per call, as adk-python and
2841/// adk-go send them; the history holds one content per tool result.
2842fn join_function_responses(contents: &[Content]) -> Vec<Content> {
2843    let mut joined: Vec<Content> = Vec::with_capacity(contents.len());
2844    for content in contents {
2845        if content.role == "function"
2846            && let Some(last) = joined.last_mut()
2847            && last.role == "function"
2848        {
2849            last.parts.extend(content.parts.iter().cloned());
2850            continue;
2851        }
2852        joined.push(content.clone());
2853    }
2854    joined
2855}
2856
2857#[cfg(test)]
2858mod tests {
2859
2860    #[test]
2861    fn parallel_function_responses_travel_in_one_content() {
2862        let response = |id: &str| Part::FunctionResponse {
2863            function_response: adk_core::FunctionResponseData::new(
2864                "tool",
2865                serde_json::json!({"ok": id}),
2866            ),
2867            id: Some(id.to_string()),
2868            annotations: None,
2869        };
2870        let contents = vec![
2871            Content::new("user").with_text("both"),
2872            Content { role: "function".to_string(), parts: vec![response("c1")] },
2873            Content { role: "function".to_string(), parts: vec![response("c2")] },
2874            Content::new("model").with_text("done"),
2875            Content { role: "function".to_string(), parts: vec![response("c3")] },
2876        ];
2877        let joined = join_function_responses(&contents);
2878        let shape: Vec<(&str, usize)> =
2879            joined.iter().map(|content| (content.role.as_str(), content.parts.len())).collect();
2880        assert_eq!(shape, vec![("user", 1), ("function", 2), ("model", 1), ("function", 1)]);
2881    }
2882    use super::*;
2883    use adk_core::AdkError;
2884    use std::{
2885        sync::{
2886            Arc,
2887            atomic::{AtomicU32, Ordering},
2888        },
2889        time::Duration,
2890    };
2891
2892    #[test]
2893    fn response_status_ignores_misleading_text() {
2894        for (status, category, code) in [
2895            (400, ErrorCategory::InvalidInput, "model.gemini.bad_request"),
2896            (401, ErrorCategory::Unauthorized, "model.gemini.unauthorized"),
2897            (403, ErrorCategory::Forbidden, "model.gemini.forbidden"),
2898            (404, ErrorCategory::NotFound, "model.gemini.not_found"),
2899            (408, ErrorCategory::Timeout, "model.gemini.timeout"),
2900            (429, ErrorCategory::RateLimited, "model.gemini.rate_limited"),
2901            (500, ErrorCategory::Unavailable, "model.gemini.unavailable"),
2902            (504, ErrorCategory::Timeout, "model.gemini.timeout"),
2903            (529, ErrorCategory::Unavailable, "model.gemini.overloaded"),
2904        ] {
2905            let error = gemini_error_to_adk(&adk_gemini::ClientError::BadResponse {
2906                retry_after: None,
2907                code: status,
2908                description: Some(
2909                    serde_json::json!({"error": {
2910                        "code": "unsupported_capability",
2911                        "message": "code 400; code 401; code 429; rate limit; UNAVAILABLE; TIMEOUT"
2912                    }})
2913                    .to_string(),
2914                ),
2915            });
2916            assert_eq!(error.category, category);
2917            assert_eq!(error.code, code);
2918            assert_eq!(error.details.upstream_status_code, Some(status));
2919            assert_eq!(error.details.metadata["provider_error_code"], "unsupported_capability");
2920        }
2921    }
2922
2923    #[test]
2924    fn provider_codes_require_bounded_json_fields() {
2925        for (body, expected) in [
2926            (
2927                serde_json::json!({"error":{"code":"unsupported_capability"}}).to_string(),
2928                Some("unsupported_capability"),
2929            ),
2930            (
2931                serde_json::json!({"error":{"code":400,"status":"INVALID_ARGUMENT"}})
2932                    .to_string(),
2933                Some("INVALID_ARGUMENT"),
2934            ),
2935            (
2936                serde_json::json!({"error":{"code":"", "status":"INVALID_ARGUMENT"}})
2937                    .to_string(),
2938                Some("INVALID_ARGUMENT"),
2939            ),
2940            ("unsupported_capability".to_string(), None),
2941            (serde_json::json!({"error":{"code":"unsupported capability"}}).to_string(), None),
2942            (serde_json::json!({"error":{"code":"x".repeat(129)}}).to_string(), None),
2943            (
2944                serde_json::json!({"error":{"code":"unsupported_capability", "message":"x".repeat(64 * 1024)}}).to_string(),
2945                None,
2946            ),
2947        ] {
2948            let error = gemini_error_to_adk(&adk_gemini::ClientError::BadResponse {
2949                retry_after: None,
2950                code: 400,
2951                description: Some(body),
2952            });
2953            let actual = error
2954                .details
2955                .metadata
2956                .get("provider_error_code")
2957                .and_then(serde_json::Value::as_str);
2958            assert_eq!(actual, expected);
2959        }
2960    }
2961
2962    #[test]
2963    fn studio_body_prefers_error_info_reason_over_status() {
2964        let body = serde_json::json!({"error": {
2965            "code": 429,
2966            "message": "Resource has been exhausted",
2967            "status": "RESOURCE_EXHAUSTED",
2968            "details": [{
2969                "@type": "type.googleapis.com/google.rpc.ErrorInfo",
2970                "reason": "RATE_LIMIT_EXCEEDED",
2971                "domain": "googleapis.com"
2972            }]
2973        }});
2974        let error = gemini_error_to_adk(&adk_gemini::ClientError::BadResponse {
2975            retry_after: None,
2976            code: 429,
2977            description: Some(body.to_string()),
2978        });
2979        assert_eq!(error.details.metadata["provider_error_code"], "RATE_LIMIT_EXCEEDED");
2980
2981        let without_reason = serde_json::json!({"error": {
2982            "code": 429,
2983            "status": "RESOURCE_EXHAUSTED"
2984        }});
2985        let error = gemini_error_to_adk(&adk_gemini::ClientError::BadResponse {
2986            retry_after: None,
2987            code: 429,
2988            description: Some(without_reason.to_string()),
2989        });
2990        assert_eq!(error.details.metadata["provider_error_code"], "RESOURCE_EXHAUSTED");
2991    }
2992
2993    fn quota_body(retry_delay: &str) -> String {
2994        serde_json::json!({"error": {
2995            "code": 429,
2996            "message": "You exceeded your current quota.",
2997            "status": "RESOURCE_EXHAUSTED",
2998            "details": [
2999                {"@type": "type.googleapis.com/google.rpc.QuotaFailure", "violations": []},
3000                {"@type": "type.googleapis.com/google.rpc.RetryInfo", "retryDelay": retry_delay}
3001            ]
3002        }})
3003        .to_string()
3004    }
3005
3006    #[test]
3007    fn retry_info_delay_is_the_retry_hint() {
3008        for (delay, expected) in [
3009            ("12s", Some(Duration::from_secs(12))),
3010            ("1.5s", Some(Duration::from_millis(1500))),
3011            ("0.000001s", Some(Duration::from_millis(1))),
3012            ("0s", Some(Duration::ZERO)),
3013            ("-1s", None),
3014            ("12", None),
3015            ("1.5.0s", None),
3016            ("1.0000000001s", None),
3017            ("s", None),
3018            ("soon", None),
3019        ] {
3020            let error = gemini_error_to_adk(&adk_gemini::ClientError::BadResponse {
3021                retry_after: None,
3022                code: 429,
3023                description: Some(quota_body(delay)),
3024            });
3025            assert_eq!(error.retry.retry_after(), expected, "{delay}");
3026        }
3027
3028        // The header is the server's explicit answer; the body is the fallback.
3029        let error = gemini_error_to_adk(&adk_gemini::ClientError::BadResponse {
3030            retry_after: Some("3".into()),
3031            code: 429,
3032            description: Some(quota_body("40s")),
3033        });
3034        assert_eq!(error.retry.retry_after(), Some(Duration::from_secs(3)));
3035
3036        // An error object inside a successful response carries the same detail.
3037        let error = gemini_error_to_adk(&adk_gemini::ClientError::ErrorInResponse {
3038            code: Some(429),
3039            status: Some("RESOURCE_EXHAUSTED".into()),
3040            message: None,
3041            description: quota_body("7s"),
3042        });
3043        assert_eq!(error.retry.retry_after(), Some(Duration::from_secs(7)));
3044
3045        // A non-retryable error carries no hint.
3046        let error = gemini_error_to_adk(&adk_gemini::ClientError::BadResponse {
3047            retry_after: None,
3048            code: 400,
3049            description: Some(quota_body("12s")),
3050        });
3051        assert_eq!(error.retry.retry_after(), None);
3052    }
3053
3054    #[test]
3055    fn local_config_error_has_no_upstream_status() {
3056        let error = gemini_error_to_adk(&adk_gemini::ClientError::InvalidGenerationConfig {
3057            message: "code 429; RESOURCE_EXHAUSTED".to_string(),
3058        });
3059        assert_eq!(error.category, ErrorCategory::InvalidInput);
3060        assert_eq!(error.code, "model.gemini.invalid_config");
3061        assert_eq!(error.details.upstream_status_code, None);
3062        assert!(error.details.metadata.is_empty());
3063    }
3064
3065    #[test]
3066    fn env_flag_truthy_accepts_one_and_case_insensitive_true() {
3067        for truthy in ["1", "true", "TRUE", "True", " true ", "tRuE"] {
3068            assert!(env_flag_truthy(truthy), "expected {truthy:?} to be truthy");
3069        }
3070        for falsy in ["0", "false", "FALSE", "yes", "on", "", "2", "vertex"] {
3071            assert!(!env_flag_truthy(falsy), "expected {falsy:?} to be falsy");
3072        }
3073    }
3074
3075    #[test]
3076    fn constructor_is_backward_compatible_and_sync() {
3077        fn accepts_sync_constructor<F>(_f: F)
3078        where
3079            F: Fn(&str, &str) -> Result<GeminiModel>,
3080        {
3081        }
3082
3083        accepts_sync_constructor(|api_key, model| GeminiModel::new(api_key, model));
3084    }
3085
3086    #[test]
3087    fn stream_chunks_from_response_injects_partial_before_lone_final_chunk() {
3088        let response = LlmResponse {
3089            content: Some(Content::new("model").with_text("hello")),
3090            usage_metadata: None,
3091            finish_reason: Some(FinishReason::Stop),
3092            citation_metadata: None,
3093            partial: false,
3094            turn_complete: true,
3095            interrupted: false,
3096            error_code: None,
3097            error_message: None,
3098            provider_metadata: None,
3099            interaction_id: None,
3100            model: None,
3101            provider: None,
3102        };
3103
3104        let (chunks, saw_partial) =
3105            GeminiModel::stream_chunks_from_response(response, false, &mut Vec::new());
3106        assert!(saw_partial);
3107        assert_eq!(chunks.len(), 2);
3108        assert!(chunks[0].partial);
3109        assert!(!chunks[0].turn_complete);
3110        assert!(chunks[0].content.is_none());
3111        assert!(!chunks[1].partial);
3112        assert!(chunks[1].turn_complete);
3113    }
3114
3115    #[test]
3116    fn stream_chunks_from_response_keeps_final_only_when_partial_already_seen() {
3117        let response = LlmResponse {
3118            content: Some(Content::new("model").with_text("done")),
3119            usage_metadata: None,
3120            finish_reason: Some(FinishReason::Stop),
3121            citation_metadata: None,
3122            partial: false,
3123            turn_complete: true,
3124            interrupted: false,
3125            error_code: None,
3126            error_message: None,
3127            provider_metadata: None,
3128            interaction_id: None,
3129            model: None,
3130            provider: None,
3131        };
3132
3133        let (chunks, saw_partial) =
3134            GeminiModel::stream_chunks_from_response(response, true, &mut Vec::new());
3135        assert!(saw_partial);
3136        assert_eq!(chunks.len(), 1);
3137        assert!(!chunks[0].partial);
3138        assert!(chunks[0].turn_complete);
3139    }
3140
3141    #[test]
3142    fn stream_chunks_from_response_keeps_tool_call_turn_open() {
3143        let response = LlmResponse {
3144            content: Some(Content {
3145                role: "model".to_string(),
3146                parts: vec![Part::FunctionCall {
3147                    name: "get_weather".to_string(),
3148                    args: serde_json::json!({"city": "Boston"}),
3149                    id: Some("call-1".to_string()),
3150                    thought_signature: None,
3151                }],
3152            }),
3153            finish_reason: Some(FinishReason::Stop),
3154            turn_complete: true,
3155            ..Default::default()
3156        };
3157
3158        let (chunks, _) = GeminiModel::stream_chunks_from_response(response, true, &mut Vec::new());
3159
3160        assert_eq!(chunks.len(), 1);
3161        assert!(!chunks[0].partial);
3162        assert!(!chunks[0].turn_complete);
3163    }
3164
3165    #[test]
3166    fn stream_chunks_from_response_yields_a_partial_chunks_function_calls_on_the_final_chunk() {
3167        let call = |id: &str| Part::FunctionCall {
3168            name: "read_file".to_string(),
3169            args: serde_json::json!({ "path": id }),
3170            id: Some(id.to_string()),
3171            thought_signature: Some(format!("sig-{id}")),
3172        };
3173        let partial = LlmResponse {
3174            content: Some(Content {
3175                role: "model".to_string(),
3176                parts: vec![Part::Text { text: "Reading".to_string() }, call("a")],
3177            }),
3178            ..Default::default()
3179        };
3180        let last = LlmResponse {
3181            content: Some(Content { role: "model".to_string(), parts: vec![call("b")] }),
3182            finish_reason: Some(FinishReason::Stop),
3183            ..Default::default()
3184        };
3185
3186        let mut deferred = Vec::new();
3187        let (first, saw_partial) =
3188            GeminiModel::stream_chunks_from_response(partial, false, &mut deferred);
3189        assert!(saw_partial);
3190        assert_eq!(first.len(), 1);
3191        assert!(first[0].partial);
3192        assert_eq!(
3193            serde_json::to_value(&first[0].content).unwrap(),
3194            serde_json::to_value(Some(Content {
3195                role: "model".to_string(),
3196                parts: vec![Part::Text { text: "Reading".to_string() }],
3197            }))
3198            .unwrap(),
3199            "the partial chunk keeps its text and loses its call"
3200        );
3201        assert_eq!(deferred.len(), 1);
3202
3203        let (chunks, _) =
3204            GeminiModel::stream_chunks_from_response(last, saw_partial, &mut deferred);
3205        assert!(deferred.is_empty());
3206        assert_eq!(chunks.len(), 1);
3207        assert!(!chunks[0].partial);
3208        assert!(!chunks[0].turn_complete);
3209        assert_eq!(
3210            serde_json::to_value(&chunks[0].content).unwrap(),
3211            serde_json::to_value(Some(Content {
3212                role: "model".to_string(),
3213                parts: vec![call("a"), call("b")],
3214            }))
3215            .unwrap(),
3216            "the final chunk carries every call once, in stream order, with its signature"
3217        );
3218    }
3219
3220    #[tokio::test]
3221    async fn execute_with_retry_retries_retryable_errors() {
3222        let retry_config = RetryConfig::default()
3223            .with_max_retries(2)
3224            .with_initial_delay(Duration::from_millis(0))
3225            .with_max_delay(Duration::from_millis(0));
3226        let attempts = Arc::new(AtomicU32::new(0));
3227
3228        let result = execute_with_retry(&retry_config, is_retryable_model_error, || {
3229            let attempts = Arc::clone(&attempts);
3230            async move {
3231                let attempt = attempts.fetch_add(1, Ordering::SeqCst);
3232                if attempt < 2 {
3233                    return Err(AdkError::model("code 429 RESOURCE_EXHAUSTED"));
3234                }
3235                Ok("ok")
3236            }
3237        })
3238        .await
3239        .expect("retry should eventually succeed");
3240
3241        assert_eq!(result, "ok");
3242        assert_eq!(attempts.load(Ordering::SeqCst), 3);
3243    }
3244
3245    #[tokio::test]
3246    async fn execute_with_retry_does_not_retry_non_retryable_errors() {
3247        let retry_config = RetryConfig::default()
3248            .with_max_retries(3)
3249            .with_initial_delay(Duration::from_millis(0))
3250            .with_max_delay(Duration::from_millis(0));
3251        let attempts = Arc::new(AtomicU32::new(0));
3252
3253        let error = execute_with_retry(&retry_config, is_retryable_model_error, || {
3254            let attempts = Arc::clone(&attempts);
3255            async move {
3256                attempts.fetch_add(1, Ordering::SeqCst);
3257                Err::<(), _>(AdkError::model("code 400 invalid request"))
3258            }
3259        })
3260        .await
3261        .expect_err("non-retryable error should return immediately");
3262
3263        assert!(error.is_model());
3264        assert_eq!(attempts.load(Ordering::SeqCst), 1);
3265    }
3266
3267    #[tokio::test]
3268    async fn execute_with_retry_respects_disabled_config() {
3269        let retry_config = RetryConfig::disabled().with_max_retries(10);
3270        let attempts = Arc::new(AtomicU32::new(0));
3271
3272        let error = execute_with_retry(&retry_config, is_retryable_model_error, || {
3273            let attempts = Arc::clone(&attempts);
3274            async move {
3275                attempts.fetch_add(1, Ordering::SeqCst);
3276                Err::<(), _>(AdkError::model("code 429 RESOURCE_EXHAUSTED"))
3277            }
3278        })
3279        .await
3280        .expect_err("disabled retries should return first error");
3281
3282        assert!(error.is_model());
3283        assert_eq!(attempts.load(Ordering::SeqCst), 1);
3284    }
3285
3286    #[test]
3287    fn convert_response_preserves_citation_metadata() {
3288        let response = adk_gemini::GenerationResponse {
3289            candidates: vec![adk_gemini::Candidate {
3290                content: adk_gemini::Content {
3291                    role: Some(adk_gemini::Role::Model),
3292                    parts: Some(vec![adk_gemini::Part::Text {
3293                        text: "hello world".to_string(),
3294                        thought: None,
3295                        thought_signature: None,
3296                    }]),
3297                },
3298                safety_ratings: None,
3299                citation_metadata: Some(adk_gemini::CitationMetadata {
3300                    citation_sources: vec![adk_gemini::CitationSource {
3301                        uri: Some("https://example.com".to_string()),
3302                        title: Some("Example".to_string()),
3303                        start_index: Some(0),
3304                        end_index: Some(5),
3305                        license: Some("CC-BY".to_string()),
3306                        publication_date: None,
3307                    }],
3308                }),
3309                grounding_metadata: None,
3310                finish_reason: Some(adk_gemini::FinishReason::Stop),
3311                index: Some(0),
3312                logprobs_result: None,
3313                avg_logprobs: None,
3314            }],
3315            prompt_feedback: None,
3316            usage_metadata: None,
3317            model_version: None,
3318            response_id: None,
3319        };
3320
3321        let converted =
3322            GeminiModel::convert_response(&response).expect("conversion should succeed");
3323        let metadata = converted.citation_metadata.expect("citation metadata should be mapped");
3324        assert_eq!(metadata.citation_sources.len(), 1);
3325        assert_eq!(metadata.citation_sources[0].uri.as_deref(), Some("https://example.com"));
3326        assert_eq!(metadata.citation_sources[0].start_index, Some(0));
3327        assert_eq!(metadata.citation_sources[0].end_index, Some(5));
3328    }
3329
3330    #[test]
3331    fn convert_response_keeps_function_call_turn_open() {
3332        let response = adk_gemini::GenerationResponse {
3333            candidates: vec![adk_gemini::Candidate {
3334                content: adk_gemini::Content {
3335                    role: Some(adk_gemini::Role::Model),
3336                    parts: Some(vec![adk_gemini::Part::FunctionCall {
3337                        function_call: adk_gemini::FunctionCall {
3338                            name: "get_weather".to_string(),
3339                            args: serde_json::json!({"city": "Boston"}),
3340                            id: Some("call-1".to_string()),
3341                            thought_signature: None,
3342                        },
3343                        thought_signature: None,
3344                    }]),
3345                },
3346                safety_ratings: None,
3347                citation_metadata: None,
3348                grounding_metadata: None,
3349                finish_reason: Some(adk_gemini::FinishReason::Stop),
3350                index: Some(0),
3351                logprobs_result: None,
3352                avg_logprobs: None,
3353            }],
3354            prompt_feedback: None,
3355            usage_metadata: None,
3356            model_version: None,
3357            response_id: None,
3358        };
3359
3360        let converted =
3361            GeminiModel::convert_response(&response).expect("conversion should succeed");
3362
3363        assert!(!converted.turn_complete);
3364        assert!(converted.content.is_some_and(|content| content.has_function_calls()));
3365    }
3366
3367    #[test]
3368    fn convert_response_handles_inline_data_from_model() {
3369        let image_bytes = vec![0x89, 0x50, 0x4E, 0x47];
3370        let encoded = crate::attachment::encode_base64(&image_bytes);
3371
3372        let response = adk_gemini::GenerationResponse {
3373            candidates: vec![adk_gemini::Candidate {
3374                content: adk_gemini::Content {
3375                    role: Some(adk_gemini::Role::Model),
3376                    parts: Some(vec![
3377                        adk_gemini::Part::Text {
3378                            text: "Here is the image".to_string(),
3379                            thought: None,
3380                            thought_signature: None,
3381                        },
3382                        adk_gemini::Part::InlineData {
3383                            inline_data: adk_gemini::Blob {
3384                                mime_type: "image/png".to_string(),
3385                                data: encoded,
3386                            },
3387                            video_metadata: None,
3388                        },
3389                    ]),
3390                },
3391                safety_ratings: None,
3392                citation_metadata: None,
3393                grounding_metadata: None,
3394                finish_reason: Some(adk_gemini::FinishReason::Stop),
3395                index: Some(0),
3396                logprobs_result: None,
3397                avg_logprobs: None,
3398            }],
3399            prompt_feedback: None,
3400            usage_metadata: None,
3401            model_version: None,
3402            response_id: None,
3403        };
3404
3405        let converted =
3406            GeminiModel::convert_response(&response).expect("conversion should succeed");
3407        let content = converted.content.expect("should have content");
3408        assert!(
3409            content
3410                .parts
3411                .iter()
3412                .any(|part| matches!(part, Part::Text { text } if text == "Here is the image"))
3413        );
3414        assert!(content.parts.iter().any(|part| {
3415            matches!(
3416                part,
3417                Part::InlineData { mime_type, data, .. }
3418                    if mime_type == "image/png" && data.as_slice() == image_bytes.as_slice()
3419            )
3420        }));
3421    }
3422
3423    #[test]
3424    fn gemini_function_response_payload_preserves_objects() {
3425        let value = serde_json::json!({
3426            "documents": [
3427                { "id": "pricing", "score": 0.91 }
3428            ]
3429        });
3430
3431        let payload = GeminiModel::gemini_function_response_payload(value.clone());
3432
3433        assert_eq!(payload, value);
3434    }
3435
3436    #[test]
3437    fn gemini_function_response_payload_wraps_arrays() {
3438        let payload =
3439            GeminiModel::gemini_function_response_payload(serde_json::json!([{ "id": "pricing" }]));
3440
3441        assert_eq!(payload, serde_json::json!({ "result": [{ "id": "pricing" }] }));
3442    }
3443
3444    // ===== Multimodal function response conversion tests =====
3445
3446    /// Helper to build a FunctionResponse with nested multimodal parts
3447    /// simulating the conversion logic from generate_content_internal.
3448    fn convert_function_response_to_gemini_fr(
3449        frd: &adk_core::FunctionResponseData,
3450    ) -> adk_gemini::tools::FunctionResponse {
3451        let mut fr_parts = Vec::new();
3452
3453        for inline in &frd.inline_data {
3454            let encoded = crate::attachment::encode_base64(&inline.data);
3455            fr_parts.push(adk_gemini::FunctionResponsePart::InlineData {
3456                inline_data: adk_gemini::Blob {
3457                    mime_type: inline.mime_type.clone(),
3458                    data: encoded,
3459                },
3460            });
3461        }
3462
3463        for file in &frd.file_data {
3464            fr_parts.push(adk_gemini::FunctionResponsePart::FileData {
3465                file_data: adk_gemini::FileDataRef {
3466                    mime_type: file.mime_type.clone(),
3467                    file_uri: file.file_uri.clone(),
3468                },
3469            });
3470        }
3471
3472        let mut gemini_fr = adk_gemini::tools::FunctionResponse::new(
3473            &frd.name,
3474            GeminiModel::gemini_function_response_payload(frd.response.clone()),
3475        );
3476        gemini_fr.parts = fr_parts;
3477        gemini_fr
3478    }
3479
3480    #[test]
3481    fn json_only_function_response_has_no_nested_parts() {
3482        let frd = adk_core::FunctionResponseData::new("tool", serde_json::json!({"ok": true}));
3483        let gemini_fr = convert_function_response_to_gemini_fr(&frd);
3484        assert!(gemini_fr.parts.is_empty());
3485        // Serialized JSON should have name and response but no parts key
3486        let json = serde_json::to_string(&gemini_fr).unwrap();
3487        assert!(!json.contains("\"parts\""));
3488    }
3489
3490    #[test]
3491    fn function_response_with_inline_data_has_nested_parts() {
3492        let frd = adk_core::FunctionResponseData::with_inline_data(
3493            "chart",
3494            serde_json::json!({"status": "ok"}),
3495            vec![adk_core::InlineDataPart {
3496                mime_type: "image/png".to_string(),
3497                data: vec![0x89, 0x50, 0x4E, 0x47],
3498                uri: None,
3499                annotations: None,
3500            }],
3501        );
3502        let gemini_fr = convert_function_response_to_gemini_fr(&frd);
3503        assert_eq!(gemini_fr.parts.len(), 1);
3504        match &gemini_fr.parts[0] {
3505            adk_gemini::FunctionResponsePart::InlineData { inline_data } => {
3506                assert_eq!(inline_data.mime_type, "image/png");
3507                let decoded = BASE64_STANDARD.decode(&inline_data.data).unwrap();
3508                assert_eq!(decoded, vec![0x89, 0x50, 0x4E, 0x47]);
3509            }
3510            other => panic!("expected InlineData, got {other:?}"),
3511        }
3512    }
3513
3514    #[test]
3515    fn function_response_with_file_data_has_nested_parts() {
3516        let frd = adk_core::FunctionResponseData::with_file_data(
3517            "doc",
3518            serde_json::json!({"ok": true}),
3519            vec![adk_core::FileDataPart {
3520                mime_type: "application/pdf".to_string(),
3521                file_uri: "gs://bucket/report.pdf".to_string(),
3522                annotations: None,
3523            }],
3524        );
3525        let gemini_fr = convert_function_response_to_gemini_fr(&frd);
3526        assert_eq!(gemini_fr.parts.len(), 1);
3527        match &gemini_fr.parts[0] {
3528            adk_gemini::FunctionResponsePart::FileData { file_data } => {
3529                assert_eq!(file_data.mime_type, "application/pdf");
3530                assert_eq!(file_data.file_uri, "gs://bucket/report.pdf");
3531            }
3532            other => panic!("expected FileData, got {other:?}"),
3533        }
3534    }
3535
3536    #[test]
3537    fn function_response_with_both_inline_and_file_data_ordering() {
3538        let frd = adk_core::FunctionResponseData::with_multimodal(
3539            "multi",
3540            serde_json::json!({}),
3541            vec![
3542                adk_core::InlineDataPart {
3543                    mime_type: "image/png".to_string(),
3544                    data: vec![1, 2],
3545                    uri: None,
3546                    annotations: None,
3547                },
3548                adk_core::InlineDataPart {
3549                    mime_type: "image/jpeg".to_string(),
3550                    data: vec![3, 4],
3551                    uri: None,
3552                    annotations: None,
3553                },
3554            ],
3555            vec![adk_core::FileDataPart {
3556                mime_type: "application/pdf".to_string(),
3557                file_uri: "gs://b/f.pdf".to_string(),
3558                annotations: None,
3559            }],
3560        );
3561        let gemini_fr = convert_function_response_to_gemini_fr(&frd);
3562        // 2 inline + 1 file = 3 nested parts
3563        assert_eq!(gemini_fr.parts.len(), 3);
3564        assert!(matches!(&gemini_fr.parts[0], adk_gemini::FunctionResponsePart::InlineData { .. }));
3565        assert!(matches!(&gemini_fr.parts[1], adk_gemini::FunctionResponsePart::InlineData { .. }));
3566        assert!(matches!(&gemini_fr.parts[2], adk_gemini::FunctionResponsePart::FileData { .. }));
3567    }
3568}
3569
3570#[cfg(all(test, feature = "gemini-interactions"))]
3571mod interactions_transport_tests {
3572    use super::*;
3573    use adk_core::GenerateContentConfig;
3574
3575    /// **Feature: gemini-interactions-runtime, Property 2: Default options match the API**
3576    /// *For any* default `InteractionOptions`, `store == true`, `stateful == true`,
3577    /// `background` is `AgentTargetsOnly`, and `poll_interval` is 1 second.
3578    /// **Validates: Requirements 3.1, 3.2, 3.3**
3579    #[test]
3580    fn default_interaction_options_match_api_posture() {
3581        let opts = InteractionOptions::default();
3582        assert!(opts.store, "store should default to true");
3583        assert!(opts.stateful, "stateful should default to true");
3584        assert_eq!(opts.background, BackgroundMode::AgentTargetsOnly);
3585        assert_eq!(opts.poll_interval, std::time::Duration::from_secs(1));
3586    }
3587
3588    #[test]
3589    fn new_model_defaults_to_generate_content_transport() {
3590        let model = GeminiModel::new("test-key", "gemini-3.7-flash")
3591            .expect("constructing a Gemini model should not require network");
3592        assert_eq!(model.transport(), GeminiTransport::GenerateContent);
3593    }
3594
3595    #[test]
3596    fn use_interactions_api_enables_transport_for_allowlisted_model() {
3597        let model = GeminiModel::new("test-key", "gemini-3.7-flash")
3598            .expect("construct model")
3599            .use_interactions_api(true)
3600            .expect("allowlisted model should enable the Interactions transport");
3601
3602        assert_eq!(model.transport(), GeminiTransport::Interactions);
3603        assert_eq!(
3604            model.interaction_target,
3605            Some(InteractionTarget::Model("gemini-3.7-flash".to_string()))
3606        );
3607    }
3608
3609    #[test]
3610    fn use_interactions_api_rejects_unsupported_model_with_invalid_input() {
3611        let result = GeminiModel::new("test-key", "gemini-2.0-flash")
3612            .expect("construct model")
3613            .use_interactions_api(true);
3614
3615        let err = match result {
3616            Ok(_) => panic!("unsupported model should be rejected"),
3617            Err(err) => err,
3618        };
3619        assert_eq!(err.category, adk_core::ErrorCategory::InvalidInput);
3620        assert_eq!(err.details.provider.as_deref(), Some("gemini"));
3621    }
3622
3623    #[test]
3624    fn use_interactions_api_false_reverts_to_generate_content() {
3625        let model = GeminiModel::new("test-key", "gemini-3.7-flash")
3626            .expect("construct model")
3627            .use_interactions_api(true)
3628            .expect("enable interactions")
3629            .use_interactions_api(false)
3630            .expect("disabling should always succeed");
3631
3632        assert_eq!(model.transport(), GeminiTransport::GenerateContent);
3633        assert_eq!(model.interaction_target, None);
3634    }
3635
3636    #[test]
3637    fn interaction_options_override_is_stored() {
3638        let opts = InteractionOptions {
3639            store: false,
3640            stateful: false,
3641            background: BackgroundMode::Always,
3642            poll_interval: std::time::Duration::from_millis(250),
3643        };
3644        let model = GeminiModel::new("test-key", "gemini-3.7-flash")
3645            .expect("construct model")
3646            .interaction_options(opts.clone());
3647
3648        let stored = model.interaction_options_ref();
3649        assert_eq!(stored.store, opts.store);
3650        assert_eq!(stored.stateful, opts.stateful);
3651        assert_eq!(stored.background, opts.background);
3652        assert_eq!(stored.poll_interval, opts.poll_interval);
3653    }
3654
3655    #[test]
3656    fn resolve_background_honors_background_mode() {
3657        // Always → true regardless of target.
3658        let always = GeminiModel::new("test-key", "gemini-3.7-flash")
3659            .expect("construct model")
3660            .use_interactions_api(true)
3661            .expect("enable")
3662            .interaction_options(InteractionOptions {
3663                background: BackgroundMode::Always,
3664                ..InteractionOptions::default()
3665            });
3666        assert!(always.resolve_background());
3667
3668        // Never → false regardless of target.
3669        let never = GeminiModel::new("test-key", "gemini-3.7-flash")
3670            .expect("construct model")
3671            .use_interactions_api(true)
3672            .expect("enable")
3673            .interaction_options(InteractionOptions {
3674                background: BackgroundMode::Never,
3675                ..InteractionOptions::default()
3676            });
3677        assert!(!never.resolve_background());
3678
3679        // AgentTargetsOnly → false for a model target.
3680        let model_target = GeminiModel::new("test-key", "gemini-3.7-flash")
3681            .expect("construct model")
3682            .use_interactions_api(true)
3683            .expect("enable");
3684        assert!(!model_target.resolve_background());
3685
3686        // AgentTargetsOnly → true for an agent target.
3687        let agent_target = GeminiModel::new("test-key", "deep-research-preview-04-2026")
3688            .expect("construct model")
3689            .use_interactions_api(true)
3690            .expect("enable");
3691        assert!(agent_target.resolve_background());
3692    }
3693
3694    /// Requirements 7.7 / 9.2: a terminal `failed` status maps to an
3695    /// `Internal` `AdkError` (provider `"gemini"`).
3696    #[test]
3697    fn terminal_failed_status_maps_to_error() {
3698        use adk_gemini::interactions::InteractionStatus;
3699
3700        let err = interaction_status_to_result(InteractionStatus::Failed)
3701            .expect_err("a failed interaction must surface an error");
3702        assert_eq!(err.category, adk_core::ErrorCategory::Internal);
3703        assert_eq!(err.details.provider.as_deref(), Some("gemini"));
3704        assert_eq!(err.code, "model.gemini.interactions.failed");
3705    }
3706
3707    /// Requirements 7.7 / 9.2: a terminal `budget_exceeded` status maps to an
3708    /// `Internal` `AdkError` (provider `"gemini"`).
3709    #[test]
3710    fn terminal_budget_exceeded_status_maps_to_error() {
3711        use adk_gemini::interactions::InteractionStatus;
3712
3713        let err = interaction_status_to_result(InteractionStatus::BudgetExceeded)
3714            .expect_err("a budget_exceeded interaction must surface an error");
3715        assert_eq!(err.category, adk_core::ErrorCategory::Internal);
3716        assert_eq!(err.details.provider.as_deref(), Some("gemini"));
3717        assert_eq!(err.code, "model.gemini.interactions.budget_exceeded");
3718    }
3719
3720    /// Non-failure statuses (including `requires_action` and the other terminal
3721    /// states the transport reads content from) do not produce an error.
3722    #[test]
3723    fn non_failure_statuses_are_ok() {
3724        use adk_gemini::interactions::InteractionStatus;
3725
3726        for status in [
3727            InteractionStatus::InProgress,
3728            InteractionStatus::RequiresAction,
3729            InteractionStatus::Completed,
3730            InteractionStatus::Cancelled,
3731            InteractionStatus::Incomplete,
3732            InteractionStatus::RequiresContinuation,
3733            InteractionStatus::Unknown,
3734        ] {
3735            assert!(
3736                interaction_status_to_result(status).is_ok(),
3737                "status {status:?} should not map to an error"
3738            );
3739        }
3740    }
3741
3742    /// A constructed `failed` `Interaction` flows through the same status check
3743    /// the transport uses, surfacing an error after conversion.
3744    #[test]
3745    fn failed_interaction_resource_surfaces_error() {
3746        use adk_gemini::interactions::{Interaction, InteractionStatus};
3747
3748        let interaction = Interaction {
3749            id: "v1_failed".to_string(),
3750            model: Some("gemini-3.7-flash".to_string()),
3751            agent: None,
3752            status: InteractionStatus::Failed,
3753            steps: Vec::new(),
3754            usage: None,
3755            created: None,
3756            updated: None,
3757            environment_id: None,
3758            continuation_token: None,
3759        };
3760
3761        let err = interaction_status_to_result(interaction.status)
3762            .expect_err("failed interaction must surface an error");
3763        assert_eq!(err.category, adk_core::ErrorCategory::Internal);
3764        assert_eq!(err.details.provider.as_deref(), Some("gemini"));
3765    }
3766    #[test]
3767    fn gemini_37_rejects_sampling_before_network_io() {
3768        for name in ["gemini-3.7-flash", "gemini-3.8-flash"] {
3769            let model = GeminiModel::new("test-key", name).expect("construct model");
3770            let mut request = LlmRequest::new(name, Vec::new());
3771            request.config =
3772                Some(GenerateContentConfig { temperature: Some(0.2), ..Default::default() });
3773
3774            let error = model
3775                .validate_request_contract(&request, false)
3776                .expect_err("sampling must be rejected locally");
3777            assert_eq!(error.code, "model.gemini.sampling_unsupported", "{name}");
3778        }
3779    }
3780
3781    #[test]
3782    fn gemini_37_rejects_token_budget_thinking() {
3783        let model = GeminiModel::new("test-key", "gemini-3.7-flash")
3784            .expect("construct model")
3785            .with_thinking_config(adk_gemini::ThinkingConfig {
3786                thinking_budget: Some(1024),
3787                include_thoughts: None,
3788                thinking_level: None,
3789            });
3790
3791        let error = model
3792            .validate_request_contract(&LlmRequest::new("gemini-3.7-flash", Vec::new()), false)
3793            .expect_err("token budgets must be rejected locally");
3794        assert_eq!(error.code, "model.gemini.thinking_budget_unsupported");
3795    }
3796
3797    /// The error code a Gemini 4 request gets before anything is sent, if any.
3798    fn gemini_4_refusal(
3799        name: &str,
3800        level: Option<adk_gemini::ThinkingLevel>,
3801        config: GenerateContentConfig,
3802        stream: bool,
3803    ) -> Option<&'static str> {
3804        let mut model = GeminiModel::new("test-key", name).expect("construct model");
3805        if let Some(level) = level {
3806            model = model
3807                .with_thinking_config(adk_gemini::ThinkingConfig::new().with_thinking_level(level));
3808        }
3809        let mut request = LlmRequest::new(name, Vec::new());
3810        request.config = Some(config);
3811        model.validate_request_contract(&request, stream).err().map(|error| error.code)
3812    }
3813
3814    /// Every Gemini 4 model refuses `minimal` thinking, explicit caching and sampling
3815    /// parameters (<https://aistudio.google.com/docs/thinking#thinking-levels>,
3816    /// <https://aistudio.google.com/docs/whats-new-gemini-4-hydrogen>).
3817    #[test]
3818    fn gemini_4_rejects_minimal_thinking_explicit_caches_and_sampling() {
3819        use adk_gemini::ThinkingLevel;
3820
3821        for name in ["gemini-4-carbon", "gemini-4-argon", "gemini-4-neon", "gemini-4-hydrogen"] {
3822            let plain = GenerateContentConfig::default;
3823            assert_eq!(
3824                gemini_4_refusal(name, Some(ThinkingLevel::Minimal), plain(), true),
3825                Some("model.gemini.thinking_level_unsupported"),
3826                "{name}"
3827            );
3828            let cached = GenerateContentConfig {
3829                cached_content: Some("cachedContents/abc".to_string()),
3830                ..Default::default()
3831            };
3832            assert_eq!(
3833                gemini_4_refusal(name, None, cached, true),
3834                Some("model.gemini.explicit_cache_unsupported"),
3835                "{name}"
3836            );
3837            let sampled = GenerateContentConfig { top_p: Some(0.5), ..Default::default() };
3838            assert_eq!(
3839                gemini_4_refusal(name, None, sampled, true),
3840                Some("model.gemini.sampling_unsupported"),
3841                "{name}"
3842            );
3843            assert_eq!(gemini_4_refusal(name, Some(ThinkingLevel::High), plain(), false), None);
3844            assert!(
3845                !GeminiModel::new("test-key", name)
3846                    .expect("construct model")
3847                    .supports_explicit_cache()
3848            );
3849        }
3850        assert!(
3851            GeminiModel::new("test-key", "gemini-3.8-flash")
3852                .expect("construct model")
3853                .supports_explicit_cache()
3854        );
3855    }
3856
3857    /// `xhigh` runs on Neon and Hydrogen only, and a non-streaming generateContent call to
3858    /// Carbon or Argon returns at most 32,768 tokens
3859    /// (<https://aistudio.google.com/docs/long-decode>).
3860    #[test]
3861    fn gemini_4_carbon_and_argon_refuse_xhigh_and_a_non_streaming_cap_above_32k() {
3862        use adk_gemini::ThinkingLevel;
3863
3864        let plain = GenerateContentConfig::default;
3865        let capped =
3866            |max| GenerateContentConfig { max_output_tokens: Some(max), ..Default::default() };
3867        for name in ["gemini-4-carbon", "gemini-4-argon"] {
3868            assert_eq!(
3869                gemini_4_refusal(name, Some(ThinkingLevel::XHigh), plain(), true),
3870                Some("model.gemini.thinking_level_unsupported"),
3871                "{name}"
3872            );
3873            assert_eq!(
3874                gemini_4_refusal(name, None, capped(65_536), false),
3875                Some("model.gemini.output_cap_exceeded"),
3876                "{name}"
3877            );
3878            assert_eq!(gemini_4_refusal(name, None, capped(65_536), true), None, "{name}");
3879            assert_eq!(gemini_4_refusal(name, None, capped(32_768), false), None, "{name}");
3880        }
3881        for name in ["gemini-4-neon", "gemini-4-hydrogen"] {
3882            assert_eq!(gemini_4_refusal(name, Some(ThinkingLevel::XHigh), plain(), false), None);
3883            assert_eq!(gemini_4_refusal(name, None, capped(65_536), false), None, "{name}");
3884        }
3885    }
3886}
3887
3888#[cfg(all(test, feature = "gemini-vertex"))]
3889mod vertex_rag_tests {
3890    use super::*;
3891    use adk_gemini::VertexRagStore;
3892
3893    fn test_store() -> VertexRagStore {
3894        VertexRagStore::corpus("projects/p/locations/us-central1/ragCorpora/123").with_top_k(5)
3895    }
3896
3897    fn vertex_model() -> GeminiModel {
3898        GeminiModel::new_google_cloud("test-key", "p", "us-central1", "gemini-3.7-flash")
3899            .expect("construct vertex model")
3900    }
3901
3902    // The Vertex constructor builds credential plumbing that requires a
3903    // current Tokio runtime, so this test is async.
3904    #[tokio::test]
3905    async fn vertex_backend_accepts_and_stores_the_rag_store() {
3906        let model = vertex_model().with_vertex_rag_store(test_store());
3907
3908        model
3909            .validate_request_contract(&LlmRequest::new("gemini-3.7-flash", Vec::new()), false)
3910            .expect("vertex backend must accept the rag store");
3911
3912        // The stored store is handed to adk-gemini's ContentBuilder per
3913        // request; the exact wire-shape injection is asserted in adk-gemini's
3914        // backend tests.
3915        assert_eq!(model.vertex_rag_store(), Some(&test_store()));
3916    }
3917
3918    #[test]
3919    fn studio_backend_rejects_rag_store_before_network_io() {
3920        let model = GeminiModel::new("test-key", "gemini-3.7-flash")
3921            .expect("construct studio model")
3922            .with_vertex_rag_store(test_store());
3923
3924        let error = model
3925            .validate_request_contract(&LlmRequest::new("gemini-3.7-flash", Vec::new()), false)
3926            .expect_err("studio backend must reject the rag store locally");
3927        assert_eq!(error.code, "model.gemini.rag_store_requires_vertex");
3928        assert_eq!(error.category, adk_core::ErrorCategory::Unsupported);
3929        assert_eq!(error.details.provider.as_deref(), Some("gemini"));
3930    }
3931
3932    #[test]
3933    fn no_rag_store_means_no_gate() {
3934        let model = GeminiModel::new("test-key", "gemini-3.7-flash").expect("construct model");
3935        assert_eq!(model.vertex_rag_store(), None);
3936        model
3937            .validate_request_contract(&LlmRequest::new("gemini-3.7-flash", Vec::new()), false)
3938            .expect("no store configured, nothing to reject");
3939    }
3940}
3941
3942#[cfg(all(test, feature = "gemini-vertex"))]
3943mod vertex_transport_tests {
3944    use super::*;
3945    use google_cloud_gax::error::{
3946        Error as GaxError,
3947        rpc::{Code, Status, StatusDetails},
3948    };
3949
3950    #[test]
3951    fn service_status_and_reason_are_preserved() {
3952        let detail: StatusDetails = serde_json::from_value(serde_json::json!({
3953            "@type": "type.googleapis.com/google.rpc.ErrorInfo",
3954            "reason": "QUOTA_EXCEEDED"
3955        }))
3956        .expect("valid ErrorInfo detail");
3957        let status = Status::default()
3958            .set_code(Code::ResourceExhausted)
3959            .set_message("code 400; invalid API key")
3960            .set_details([detail]);
3961        let error = adk_gemini::ClientError::GoogleCloudRequest {
3962            source: GaxError::service_with_http_metadata(status, Some(429), None),
3963        };
3964
3965        let mapped = gemini_error_to_adk(&error);
3966        assert_eq!(mapped.category, ErrorCategory::RateLimited);
3967        assert_eq!(mapped.code, "model.gemini.rate_limited");
3968        assert_eq!(mapped.details.upstream_status_code, Some(429));
3969        assert_eq!(mapped.details.metadata["provider_error_code"], "QUOTA_EXCEEDED");
3970    }
3971
3972    #[test]
3973    fn rpc_status_does_not_invent_http_status() {
3974        let detail: StatusDetails = serde_json::from_value(serde_json::json!({
3975            "@type": "type.googleapis.com/google.rpc.ErrorInfo",
3976            "reason": "RATE_LIMITED"
3977        }))
3978        .expect("valid ErrorInfo detail");
3979        let status = Status::default()
3980            .set_code(Code::ResourceExhausted)
3981            .set_message("code 503; unavailable")
3982            .set_details([detail]);
3983        let error =
3984            adk_gemini::ClientError::GoogleCloudRequest { source: GaxError::service(status) };
3985
3986        let mapped = gemini_error_to_adk(&error);
3987        assert_eq!(mapped.category, ErrorCategory::RateLimited);
3988        assert_eq!(mapped.code, "model.gemini.rate_limited");
3989        assert_eq!(mapped.details.upstream_status_code, None);
3990        assert_eq!(mapped.details.metadata["provider_error_code"], "RATE_LIMITED");
3991    }
3992
3993    #[test]
3994    fn retry_info_on_the_status_is_the_retry_hint() {
3995        let detail: StatusDetails = serde_json::from_value(serde_json::json!({
3996            "@type": "type.googleapis.com/google.rpc.RetryInfo",
3997            "retryDelay": "2.5s"
3998        }))
3999        .expect("valid RetryInfo detail");
4000        let status = Status::default()
4001            .set_code(Code::ResourceExhausted)
4002            .set_message("quota")
4003            .set_details([detail]);
4004        let error = adk_gemini::ClientError::GoogleCloudRequest {
4005            source: GaxError::service_with_http_metadata(status, Some(429), None),
4006        };
4007        assert_eq!(
4008            gemini_error_to_adk(&error).retry.retry_after(),
4009            Some(std::time::Duration::from_millis(2500))
4010        );
4011    }
4012
4013    #[test]
4014    fn rpc_status_name_is_the_fallback_code() {
4015        let status = Status::default().set_code(Code::ResourceExhausted).set_message("quota");
4016        let error =
4017            adk_gemini::ClientError::GoogleCloudRequest { source: GaxError::service(status) };
4018        assert_eq!(
4019            gemini_error_to_adk(&error).details.metadata["provider_error_code"],
4020            "RESOURCE_EXHAUSTED"
4021        );
4022    }
4023
4024    #[test]
4025    fn vertex_transport_failures_are_retryable() {
4026        let source = GaxError::connect(std::io::Error::other("dns failure"));
4027        let mapped = gemini_error_to_adk(&adk_gemini::ClientError::GoogleCloudRequest { source });
4028        assert_eq!(
4029            (mapped.category, mapped.code, mapped.is_retryable()),
4030            (ErrorCategory::Unavailable, "model.gemini.unavailable", true)
4031        );
4032
4033        let error = adk_gemini::ClientError::GoogleCloudRequest {
4034            source: GaxError::deser(std::io::Error::other(
4035                "the transport reports an error: http2 error",
4036            )),
4037        };
4038        assert_eq!(gemini_error_to_adk(&error).category, ErrorCategory::Internal);
4039    }
4040}