Skip to main content

adk_gemini/generation/
model.rs

1use reqwest::Url;
2use serde::{Deserialize, Serialize, de};
3use time::OffsetDateTime;
4
5use crate::{
6    Content, Modality, Part,
7    safety::{SafetyRating, SafetySetting},
8};
9
10/// Reason why generation finished
11///
12/// The enum is `#[non_exhaustive]`: the API adds finish reasons, and a value this version does
13/// not know deserializes as [`Other`](Self::Other).
14#[derive(Debug, Clone, Serialize, PartialEq)]
15#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
16#[non_exhaustive]
17pub enum FinishReason {
18    /// Default value. This value is unused.
19    FinishReasonUnspecified,
20    /// Natural stop point of the model or provided stop sequence.
21    Stop,
22    /// The maximum number of tokens as specified in the request was reached.
23    MaxTokens,
24    /// The response candidate content was flagged for safety reasons.
25    Safety,
26    /// The response candidate content was flagged for recitation reasons.
27    Recitation,
28    /// The response candidate content was flagged for using an unsupported language.
29    Language,
30    /// Unknown reason.
31    Other,
32    /// Token generation stopped because the content contains forbidden terms.
33    Blocklist,
34    /// Token generation stopped for potentially containing prohibited content.
35    ProhibitedContent,
36    /// Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).
37    Spii,
38    /// The function call generated by the model is invalid.
39    MalformedFunctionCall,
40    /// Token generation stopped because the response was blocked by Model Armor.
41    ModelArmor,
42    /// Token generation stopped because generated images contain safety violations.
43    ImageSafety,
44    /// Model generated a tool call but no tools were enabled in the request.
45    UnexpectedToolCall,
46    /// Model called too many tools consecutively, thus the system exited execution.
47    TooManyToolCalls,
48    /// The request is missing at least one thought signature.
49    MissingThoughtSignature,
50    /// Generation finished because the response was malformed.
51    MalformedResponse,
52    /// The response reached the per-request token limit before generation finished; a later
53    /// request that carries the response's continuation token continues it (long decode).
54    Continuation,
55}
56
57impl FinishReason {
58    fn from_wire_str(value: &str) -> Self {
59        match value {
60            "FINISH_REASON_UNSPECIFIED" => Self::FinishReasonUnspecified,
61            "STOP" => Self::Stop,
62            "MAX_TOKENS" => Self::MaxTokens,
63            "SAFETY" => Self::Safety,
64            "RECITATION" => Self::Recitation,
65            "LANGUAGE" => Self::Language,
66            "OTHER" => Self::Other,
67            "BLOCKLIST" => Self::Blocklist,
68            "PROHIBITED_CONTENT" => Self::ProhibitedContent,
69            "SPII" => Self::Spii,
70            "MALFORMED_FUNCTION_CALL" => Self::MalformedFunctionCall,
71            "MODEL_ARMOR" => Self::ModelArmor,
72            "IMAGE_SAFETY" => Self::ImageSafety,
73            "UNEXPECTED_TOOL_CALL" => Self::UnexpectedToolCall,
74            "TOO_MANY_TOOL_CALLS" => Self::TooManyToolCalls,
75            "MISSING_THOUGHT_SIGNATURE" => Self::MissingThoughtSignature,
76            "MALFORMED_RESPONSE" => Self::MalformedResponse,
77            "CONTINUATION" => Self::Continuation,
78            _ => Self::Other,
79        }
80    }
81
82    fn from_wire_number(value: i64) -> Self {
83        match value {
84            0 => Self::FinishReasonUnspecified,
85            1 => Self::Stop,
86            2 => Self::MaxTokens,
87            3 => Self::Safety,
88            4 => Self::Recitation,
89            5 => Self::Other,
90            6 => Self::Blocklist,
91            7 => Self::ProhibitedContent,
92            8 => Self::Spii,
93            9 => Self::MalformedFunctionCall,
94            10 => Self::ModelArmor,
95            _ => Self::Other,
96        }
97    }
98}
99
100impl<'de> Deserialize<'de> for FinishReason {
101    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
102    where
103        D: serde::Deserializer<'de>,
104    {
105        let value = serde_json::Value::deserialize(deserializer)?;
106        match value {
107            serde_json::Value::String(s) => Ok(Self::from_wire_str(&s)),
108            serde_json::Value::Number(n) => {
109                n.as_i64().map(Self::from_wire_number).ok_or_else(|| {
110                    de::Error::custom("finishReason must be an integer-compatible number")
111                })
112            }
113            _ => Err(de::Error::custom("finishReason must be a string or integer")),
114        }
115    }
116}
117
118/// Citation metadata for content
119#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
120#[serde(rename_all = "camelCase")]
121pub struct CitationMetadata {
122    /// The citation sources
123    #[serde(default)]
124    pub citation_sources: Vec<CitationSource>,
125}
126
127/// Citation source
128#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
129#[serde(rename_all = "camelCase")]
130pub struct CitationSource {
131    /// The URI of the citation source
132    pub uri: Option<String>,
133    /// The title of the citation source
134    pub title: Option<String>,
135    /// The start index of the citation in the response
136    pub start_index: Option<i32>,
137    /// The end index of the citation in the response
138    pub end_index: Option<i32>,
139    /// The license of the citation source
140    pub license: Option<String>,
141    /// The publication date of the citation source
142    #[serde(default, with = "time::serde::rfc3339::option")]
143    pub publication_date: Option<OffsetDateTime>,
144}
145
146/// A candidate response
147#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
148#[serde(rename_all = "camelCase")]
149pub struct Candidate {
150    /// The content of the candidate
151    #[serde(default)]
152    pub content: Content,
153    /// The safety ratings for the candidate
154    #[serde(skip_serializing_if = "Option::is_none")]
155    pub safety_ratings: Option<Vec<SafetyRating>>,
156    /// The citation metadata for the candidate
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub citation_metadata: Option<CitationMetadata>,
159    /// The grounding metadata for the candidate
160    #[serde(skip_serializing_if = "Option::is_none")]
161    pub grounding_metadata: Option<GroundingMetadata>,
162    /// The finish reason for the candidate
163    #[serde(skip_serializing_if = "Option::is_none")]
164    pub finish_reason: Option<FinishReason>,
165    /// The index of the candidate
166    #[serde(skip_serializing_if = "Option::is_none")]
167    pub index: Option<i32>,
168    /// Log probabilities of the chosen and top tokens, when the request set
169    /// [`GenerationConfig::response_logprobs`].
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub logprobs_result: Option<LogprobsResult>,
172    /// Average log probability of the candidate's tokens.
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub avg_logprobs: Option<f64>,
175}
176
177/// Log probabilities of a candidate's tokens.
178///
179/// # Example
180///
181/// ```
182/// use adk_gemini::LogprobsResult;
183///
184/// let result: LogprobsResult = serde_json::from_value(serde_json::json!({
185///     "topCandidates": [{"candidates": [{"token": "Hi", "tokenId": 17, "logProbability": -0.01}]}],
186///     "chosenCandidates": [{"token": "Hi", "tokenId": 17, "logProbability": -0.01}],
187///     "logProbabilitySum": -0.01
188/// }))
189/// .unwrap();
190/// assert_eq!(result.chosen_candidates[0].token.as_deref(), Some("Hi"));
191/// ```
192#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
193#[serde(rename_all = "camelCase")]
194pub struct LogprobsResult {
195    /// The most likely tokens at each decoding step, most likely first.
196    #[serde(default, skip_serializing_if = "Vec::is_empty")]
197    pub top_candidates: Vec<TopLogprobsCandidates>,
198    /// The token chosen at each decoding step; it may not be among `top_candidates`.
199    #[serde(default, skip_serializing_if = "Vec::is_empty")]
200    pub chosen_candidates: Vec<LogprobsCandidate>,
201    /// Sum of the log probabilities of every chosen token.
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub log_probability_sum: Option<f64>,
204}
205
206/// The top candidate tokens at one decoding step.
207#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
208#[serde(rename_all = "camelCase")]
209pub struct TopLogprobsCandidates {
210    /// Candidates sorted by log probability, most likely first.
211    #[serde(default, skip_serializing_if = "Vec::is_empty")]
212    pub candidates: Vec<LogprobsCandidate>,
213}
214
215/// One token and its log probability.
216#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
217#[serde(rename_all = "camelCase")]
218pub struct LogprobsCandidate {
219    /// The token text.
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub token: Option<String>,
222    /// The token id.
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub token_id: Option<i32>,
225    /// The token's log probability.
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub log_probability: Option<f64>,
228}
229
230/// Metadata about token usage.
231///
232/// A count the API reports as `null` or leaves out reads as `None` (zero inside the detail
233/// lists) instead of failing the response, and [`raw`](Self::raw) keeps the object exactly as
234/// it was sent, including fields this type does not model.
235///
236/// # Example
237///
238/// ```
239/// use adk_gemini::UsageMetadata;
240///
241/// let usage: UsageMetadata = serde_json::from_value(serde_json::json!({
242///     "promptTokenCount": 12,
243///     "promptTokensDetails": [{"modality": "TEXT", "tokenCount": null}],
244///     "toolUsePromptTokenCount": 30
245/// }))
246/// .unwrap();
247/// assert_eq!(usage.prompt_tokens_details.as_ref().unwrap()[0].token_count, 0);
248/// assert_eq!(usage.raw.as_ref().unwrap()["toolUsePromptTokenCount"], 30);
249/// ```
250#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
251#[serde(rename_all = "camelCase", try_from = "serde_json::Value")]
252pub struct UsageMetadata {
253    /// The number of prompt tokens (null if request processing failed)
254    #[serde(skip_serializing_if = "Option::is_none")]
255    pub prompt_token_count: Option<i32>,
256    /// The number of response tokens (null if generation failed)
257    #[serde(skip_serializing_if = "Option::is_none")]
258    pub candidates_token_count: Option<i32>,
259    /// The total number of tokens (null if individual counts unavailable)
260    #[serde(skip_serializing_if = "Option::is_none")]
261    pub total_token_count: Option<i32>,
262    /// The number of thinking tokens (Gemini 2.5 series only)
263    #[serde(skip_serializing_if = "Option::is_none")]
264    pub thoughts_token_count: Option<i32>,
265    /// Detailed prompt token information
266    #[serde(skip_serializing_if = "Option::is_none")]
267    pub prompt_tokens_details: Option<Vec<PromptTokenDetails>>,
268    /// The number of cached content tokens (batch API)
269    #[serde(skip_serializing_if = "Option::is_none")]
270    pub cached_content_token_count: Option<i32>,
271    /// Detailed cache token information (batch API)
272    #[serde(skip_serializing_if = "Option::is_none")]
273    pub cache_tokens_details: Option<Vec<PromptTokenDetails>>,
274    /// The `usageMetadata` object exactly as the API sent it, including fields this type
275    /// does not model, such as `toolUsePromptTokenCount` or `trafficType`.
276    ///
277    /// `None` for a value built in code.
278    #[serde(skip)]
279    pub raw: Option<serde_json::Value>,
280}
281
282#[derive(Deserialize)]
283#[serde(rename_all = "camelCase")]
284struct UsageMetadataWire {
285    #[serde(default)]
286    prompt_token_count: Option<i32>,
287    #[serde(default)]
288    candidates_token_count: Option<i32>,
289    #[serde(default)]
290    total_token_count: Option<i32>,
291    #[serde(default)]
292    thoughts_token_count: Option<i32>,
293    #[serde(default)]
294    prompt_tokens_details: Option<Vec<PromptTokenDetails>>,
295    #[serde(default)]
296    cached_content_token_count: Option<i32>,
297    #[serde(default)]
298    cache_tokens_details: Option<Vec<PromptTokenDetails>>,
299}
300
301impl TryFrom<serde_json::Value> for UsageMetadata {
302    type Error = serde_json::Error;
303
304    fn try_from(raw: serde_json::Value) -> Result<Self, Self::Error> {
305        let wire = UsageMetadataWire::deserialize(&raw)?;
306        Ok(Self {
307            prompt_token_count: wire.prompt_token_count,
308            candidates_token_count: wire.candidates_token_count,
309            total_token_count: wire.total_token_count,
310            thoughts_token_count: wire.thoughts_token_count,
311            prompt_tokens_details: wire.prompt_tokens_details,
312            cached_content_token_count: wire.cached_content_token_count,
313            cache_tokens_details: wire.cache_tokens_details,
314            raw: Some(raw),
315        })
316    }
317}
318
319/// Details about prompt tokens by modality
320#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
321#[serde(rename_all = "camelCase")]
322pub struct PromptTokenDetails {
323    /// The modality (e.g., "TEXT"); `MODALITY_UNSPECIFIED` when the API leaves it out
324    #[serde(default = "unspecified_modality")]
325    pub modality: Modality,
326    /// Token count for this modality; zero when the API reports `null` or leaves it out
327    #[serde(default, deserialize_with = "adk_core::nullable_count")]
328    pub token_count: i32,
329}
330
331fn unspecified_modality() -> Modality {
332    Modality::ModalityUnspecified
333}
334
335/// Grounding metadata for responses that use grounding tools
336#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
337#[serde(rename_all = "camelCase")]
338pub struct GroundingMetadata {
339    /// Grounding chunks containing source information
340    #[serde(skip_serializing_if = "Option::is_none")]
341    pub grounding_chunks: Option<Vec<GroundingChunk>>,
342    /// Grounding supports connecting response text to sources
343    #[serde(skip_serializing_if = "Option::is_none")]
344    pub grounding_supports: Option<Vec<GroundingSupport>>,
345    /// Web search queries used for grounding
346    #[serde(skip_serializing_if = "Option::is_none")]
347    pub web_search_queries: Option<Vec<String>>,
348    /// Provider-rendered Google Search suggestions and SDK data.
349    #[serde(skip_serializing_if = "Option::is_none")]
350    pub search_entry_point: Option<SearchEntryPoint>,
351    /// Google Maps widget context token
352    #[serde(skip_serializing_if = "Option::is_none")]
353    pub google_maps_widget_context_token: Option<String>,
354}
355
356/// Google Search suggestions returned alongside a grounded answer.
357#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
358#[serde(rename_all = "camelCase")]
359pub struct SearchEntryPoint {
360    /// HTML and CSS to display the provider's search suggestions.
361    #[serde(skip_serializing_if = "Option::is_none")]
362    pub rendered_content: Option<String>,
363    /// Base64-encoded search term and URL tuples for native SDKs.
364    #[serde(skip_serializing_if = "Option::is_none")]
365    pub sdk_blob: Option<String>,
366}
367
368/// A chunk of grounding information from a source
369#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
370#[serde(rename_all = "camelCase")]
371pub struct GroundingChunk {
372    /// Maps-specific grounding information
373    #[serde(skip_serializing_if = "Option::is_none")]
374    pub maps: Option<MapsGroundingChunk>,
375    /// Web-specific grounding information
376    #[serde(skip_serializing_if = "Option::is_none")]
377    pub web: Option<WebGroundingChunk>,
378}
379
380/// Maps-specific grounding chunk information
381#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
382#[serde(rename_all = "camelCase")]
383pub struct MapsGroundingChunk {
384    /// The URI of the Maps source
385    #[serde(default)]
386    pub uri: Option<Url>,
387    /// The title of the Maps source
388    #[serde(default)]
389    pub title: Option<String>,
390    /// The place ID from Google Maps
391    #[serde(skip_serializing_if = "Option::is_none")]
392    pub place_id: Option<String>,
393}
394
395/// Web-specific grounding chunk information
396#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
397#[serde(rename_all = "camelCase")]
398pub struct WebGroundingChunk {
399    /// The URI of the web source
400    #[serde(default)]
401    pub uri: Option<Url>,
402    /// The title of the web source
403    #[serde(default)]
404    pub title: Option<String>,
405}
406
407/// Support information connecting response text to grounding sources
408#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
409#[serde(rename_all = "camelCase")]
410pub struct GroundingSupport {
411    /// Segment of the response text
412    pub segment: GroundingSegment,
413    /// Indices of grounding chunks that support this segment
414    pub grounding_chunk_indices: Vec<u32>,
415}
416
417/// A segment of response text
418#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
419#[serde(rename_all = "camelCase")]
420pub struct GroundingSegment {
421    /// Index of the Part within the candidate's Content.
422    ///
423    /// The API omits zero values, so the field is absent when the segment is in the
424    /// first part; treat `None` as part `0`.
425    #[serde(default, skip_serializing_if = "Option::is_none")]
426    pub part_index: Option<u32>,
427    /// Start index of the segment in the response text
428    #[serde(default)]
429    pub start_index: Option<u32>,
430    /// End index of the segment in the response text
431    #[serde(default)]
432    pub end_index: Option<u32>,
433    /// The text content of the segment
434    #[serde(default)]
435    pub text: Option<String>,
436}
437
438/// Response from the Gemini API for content generation
439#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
440#[serde(rename_all = "camelCase")]
441pub struct GenerationResponse {
442    /// The candidates generated
443    #[serde(default, skip_serializing_if = "Vec::is_empty")]
444    pub candidates: Vec<Candidate>,
445    /// The prompt feedback
446    #[serde(skip_serializing_if = "Option::is_none")]
447    pub prompt_feedback: Option<PromptFeedback>,
448    /// Usage metadata
449    #[serde(skip_serializing_if = "Option::is_none")]
450    pub usage_metadata: Option<UsageMetadata>,
451    /// Model version used
452    #[serde(skip_serializing_if = "Option::is_none")]
453    pub model_version: Option<String>,
454    /// Response ID
455    #[serde(skip_serializing_if = "Option::is_none")]
456    pub response_id: Option<String>,
457}
458
459/// Reason why content was blocked
460#[derive(Debug, Clone, Serialize, PartialEq)]
461#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
462pub enum BlockReason {
463    /// Default value. This value is unused.
464    BlockReasonUnspecified,
465    /// Prompt was blocked due to safety reasons. Inspect safetyRatings to understand which safety category blocked it.
466    Safety,
467    /// Prompt was blocked due to unknown reasons.
468    Other,
469    /// Prompt was blocked due to the terms which are included from the terminology blocklist.
470    Blocklist,
471    /// Prompt was blocked due to prohibited content.
472    ProhibitedContent,
473    /// Prompt was blocked by Model Armor.
474    ModelArmor,
475    /// Prompt was blocked due to jailbreak detection.
476    Jailbreak,
477    /// Candidates blocked due to unsafe image generation content.
478    ImageSafety,
479}
480
481impl BlockReason {
482    fn from_wire_str(value: &str) -> Self {
483        match value {
484            "BLOCK_REASON_UNSPECIFIED" | "BLOCKED_REASON_UNSPECIFIED" => {
485                Self::BlockReasonUnspecified
486            }
487            "SAFETY" => Self::Safety,
488            "OTHER" => Self::Other,
489            "BLOCKLIST" => Self::Blocklist,
490            "PROHIBITED_CONTENT" => Self::ProhibitedContent,
491            "MODEL_ARMOR" => Self::ModelArmor,
492            "JAILBREAK" => Self::Jailbreak,
493            "IMAGE_SAFETY" => Self::ImageSafety,
494            _ => Self::Other,
495        }
496    }
497
498    fn from_wire_number(value: i64) -> Self {
499        match value {
500            0 => Self::BlockReasonUnspecified,
501            1 => Self::Safety,
502            2 => Self::Other,
503            3 => Self::Blocklist,
504            4 => Self::ProhibitedContent,
505            5 => Self::ModelArmor,
506            6 => Self::Jailbreak,
507            7 => Self::ImageSafety,
508            _ => Self::Other,
509        }
510    }
511}
512
513impl<'de> Deserialize<'de> for BlockReason {
514    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
515    where
516        D: serde::Deserializer<'de>,
517    {
518        let value = serde_json::Value::deserialize(deserializer)?;
519        match value {
520            serde_json::Value::String(s) => Ok(Self::from_wire_str(&s)),
521            serde_json::Value::Number(n) => {
522                n.as_i64().map(Self::from_wire_number).ok_or_else(|| {
523                    de::Error::custom("blockReason must be an integer-compatible number")
524                })
525            }
526            _ => Err(de::Error::custom("blockReason must be a string or integer")),
527        }
528    }
529}
530
531/// Feedback about the prompt
532#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
533#[serde(rename_all = "camelCase")]
534pub struct PromptFeedback {
535    /// The safety ratings for the prompt
536    #[serde(default, skip_serializing_if = "Vec::is_empty")]
537    pub safety_ratings: Vec<SafetyRating>,
538    /// The block reason if the prompt was blocked
539    #[serde(skip_serializing_if = "Option::is_none")]
540    pub block_reason: Option<BlockReason>,
541}
542
543impl GenerationResponse {
544    /// Get the visible answer text of the first candidate.
545    ///
546    /// Concatenates every non-thought text part, in order. This is deliberately
547    /// not "the first part": responses that use thinking or built-in tools
548    /// (Google Search, URL context, code execution) commonly lead with thought
549    /// or tool parts and place the answer text in a later part — so reading only
550    /// the first part would return an empty string. Thought parts are excluded;
551    /// use [`text_with_thoughts`](Self::text_with_thoughts) to inspect them.
552    pub fn text(&self) -> String {
553        self.candidates
554            .first()
555            .and_then(|c| c.content.parts.as_ref())
556            .map(|parts| {
557                parts
558                    .iter()
559                    .filter_map(|p| match p {
560                        Part::Text { text, thought, thought_signature: _ }
561                            if !thought.unwrap_or(false) =>
562                        {
563                            Some(text.as_str())
564                        }
565                        _ => None,
566                    })
567                    .collect::<String>()
568            })
569            .unwrap_or_default()
570    }
571
572    /// Get function calls from the response
573    pub fn function_calls(&self) -> Vec<&crate::tools::FunctionCall> {
574        self.candidates
575            .iter()
576            .flat_map(|c| {
577                c.content
578                    .parts
579                    .as_ref()
580                    .map(|parts| {
581                        parts
582                            .iter()
583                            .filter_map(|p| match p {
584                                Part::FunctionCall { function_call, thought_signature: _ } => {
585                                    Some(function_call)
586                                }
587                                _ => None,
588                            })
589                            .collect::<Vec<_>>()
590                    })
591                    .unwrap_or_default()
592            })
593            .collect()
594    }
595
596    /// Get function calls with their thought signatures from the response
597    pub fn function_calls_with_thoughts(
598        &self,
599    ) -> Vec<(&crate::tools::FunctionCall, Option<&String>)> {
600        self.candidates
601            .iter()
602            .flat_map(|c| {
603                c.content
604                    .parts
605                    .as_ref()
606                    .map(|parts| {
607                        parts
608                            .iter()
609                            .filter_map(|p| match p {
610                                Part::FunctionCall { function_call, thought_signature } => {
611                                    Some((function_call, thought_signature.as_ref()))
612                                }
613                                _ => None,
614                            })
615                            .collect::<Vec<_>>()
616                    })
617                    .unwrap_or_default()
618            })
619            .collect()
620    }
621
622    /// Get thought summaries from the response
623    pub fn thoughts(&self) -> Vec<String> {
624        self.candidates
625            .iter()
626            .flat_map(|c| {
627                c.content
628                    .parts
629                    .as_ref()
630                    .map(|parts| {
631                        parts
632                            .iter()
633                            .filter_map(|p| match p {
634                                Part::Text { text, thought: Some(true), thought_signature: _ } => {
635                                    Some(text.clone())
636                                }
637                                _ => None,
638                            })
639                            .collect::<Vec<_>>()
640                    })
641                    .unwrap_or_default()
642            })
643            .collect()
644    }
645
646    /// Get all text parts (both regular text and thoughts)
647    pub fn all_text(&self) -> Vec<(String, bool)> {
648        self.candidates
649            .iter()
650            .flat_map(|c| {
651                c.content
652                    .parts
653                    .as_ref()
654                    .map(|parts| {
655                        parts
656                            .iter()
657                            .filter_map(|p| match p {
658                                Part::Text { text, thought, thought_signature: _ } => {
659                                    Some((text.clone(), thought.unwrap_or(false)))
660                                }
661                                _ => None,
662                            })
663                            .collect::<Vec<_>>()
664                    })
665                    .unwrap_or_default()
666            })
667            .collect()
668    }
669
670    /// Get text parts with their thought signatures from the response
671    pub fn text_with_thoughts(&self) -> Vec<(String, bool, Option<&String>)> {
672        self.candidates
673            .iter()
674            .flat_map(|c| {
675                c.content
676                    .parts
677                    .as_ref()
678                    .map(|parts| {
679                        parts
680                            .iter()
681                            .filter_map(|p| match p {
682                                Part::Text { text, thought, thought_signature } => Some((
683                                    text.clone(),
684                                    thought.unwrap_or(false),
685                                    thought_signature.as_ref(),
686                                )),
687                                _ => None,
688                            })
689                            .collect::<Vec<_>>()
690                    })
691                    .unwrap_or_default()
692            })
693            .collect()
694    }
695}
696
697/// Request to generate content
698#[derive(Debug, Clone, Serialize, Deserialize)]
699#[serde(rename_all = "camelCase")]
700pub struct GenerateContentRequest {
701    /// The contents to generate content from
702    pub contents: Vec<Content>,
703    /// The generation config
704    #[serde(skip_serializing_if = "Option::is_none")]
705    pub generation_config: Option<GenerationConfig>,
706    /// The safety settings
707    #[serde(skip_serializing_if = "Option::is_none")]
708    pub safety_settings: Option<Vec<SafetySetting>>,
709    /// The tools that the model can use
710    #[serde(skip_serializing_if = "Option::is_none")]
711    pub tools: Option<Vec<crate::tools::Tool>>,
712    /// The tool config
713    #[serde(skip_serializing_if = "Option::is_none")]
714    pub tool_config: Option<crate::tools::ToolConfig>,
715    /// The system instruction
716    #[serde(skip_serializing_if = "Option::is_none")]
717    pub system_instruction: Option<Content>,
718    /// The cached content to use
719    #[serde(skip_serializing_if = "Option::is_none")]
720    pub cached_content: Option<String>,
721}
722
723impl GenerateContentRequest {
724    /// Strips fields that Vertex AI does not support.
725    ///
726    /// The Vertex AI surface (`aiplatform.googleapis.com`) rejects
727    /// `includeServerSideToolInvocations` with a 400 error. Vertex AI handles
728    /// built-in tools (Google Search, URL Context, etc.) natively without
729    /// needing this flag. This method clears the flag so the request can be
730    /// sent to Vertex AI without modification.
731    ///
732    /// AI Studio (`generativelanguage.googleapis.com`) requires the flag for
733    /// Gemini 3 models to return `toolCall`/`toolResponse` parts instead of
734    /// silently truncating the response.
735    pub fn strip_vertex_unsupported_fields(&mut self) {
736        if let Some(tc) = &mut self.tool_config {
737            tc.include_server_side_tool_invocations = None;
738        }
739    }
740}
741
742/// Native thinking level for Gemini 4 and Gemini 3 models.
743///
744/// Controls the amount of reasoning effort the model applies. This is the
745/// Gemini 3 native thinking control — for Gemini 2.5 budget-based thinking,
746/// use [`ThinkingConfig::with_thinking_budget`] instead.
747///
748/// Serializes as lowercase per the Gemini API contract
749/// (e.g., `"low"`, `"xhigh"`).
750///
751/// Available levels (model support and defaults vary by model, see
752/// <https://aistudio.google.com/docs/thinking#thinking-levels>):
753/// - `Minimal` — matches "no thinking" for most queries; model may still
754///   think minimally for complex coding tasks. Not supported on Gemini 4 models,
755///   Gemini 3.8 Flash or Gemini 3.1 Pro.
756/// - `Low` — minimizes latency and cost; improved for code and agentic tasks
757///   that require fewer steps.
758/// - `Medium` — balanced thinking for most tasks. Default for Gemini 4 Carbon,
759///   Gemini 4 Argon and Gemini 3.8 Flash.
760/// - `High` — maximizes reasoning depth. Default for Gemini 4 Neon, Gemini 4
761///   Hydrogen and Gemini 3.1 Pro.
762/// - `XHigh` — the deepest reasoning, for hard multi-step problems. Supported on
763///   Gemini 4 Neon and Gemini 4 Hydrogen only.
764///
765/// The enum is `#[non_exhaustive]`: Google adds levels.
766///
767/// Note: `temperature`, `top_p`, and `top_k` are no longer recommended for
768/// Gemini 3.x models — their reasoning is tuned for the default sampling
769/// settings. Use `thinking_level` to control reasoning effort instead.
770#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
771#[serde(rename_all = "lowercase")]
772#[non_exhaustive]
773pub enum ThinkingLevel {
774    /// Minimal reasoning effort. Matches "no thinking" for most queries.
775    /// Not supported on Gemini 4 models, Gemini 3.8 Flash or Gemini 3.1 Pro.
776    Minimal,
777    /// Low reasoning effort. Best for simple instruction following and chat.
778    Low,
779    /// Medium reasoning effort. Balanced thinking for most tasks.
780    /// Default for Gemini 4 Carbon, Gemini 4 Argon and Gemini 3.8 Flash.
781    Medium,
782    /// High reasoning effort — maximizes reasoning depth. Default for
783    /// Gemini 4 Neon, Gemini 4 Hydrogen and Gemini 3.1 Pro.
784    High,
785    /// Extra-high reasoning effort: the most tokens and the deepest reasoning.
786    /// Supported on Gemini 4 Neon and Gemini 4 Hydrogen only.
787    XHigh,
788}
789
790/// The harness effort levels (spec 3.1 §7.23): `Low`, `Medium` and `High` map to the
791/// thinking level of the same name; `Minimal` and `XHigh` stay reachable only through
792/// [`ThinkingConfig::with_thinking_level`], since [`adk_core::Effort`] has no level below
793/// `Low` or above `High`.
794///
795/// # Example
796///
797/// ```rust
798/// use adk_gemini::ThinkingLevel;
799///
800/// assert_eq!(ThinkingLevel::from(adk_core::Effort::Medium), ThinkingLevel::Medium);
801/// ```
802impl From<adk_core::Effort> for ThinkingLevel {
803    fn from(effort: adk_core::Effort) -> Self {
804        match effort {
805            adk_core::Effort::Low => Self::Low,
806            adk_core::Effort::Medium => Self::Medium,
807            adk_core::Effort::High => Self::High,
808        }
809    }
810}
811
812/// Configuration for thinking (Gemini 2.5 and 3 series)
813#[derive(Debug, Clone, Serialize, Deserialize)]
814#[serde(rename_all = "camelCase")]
815pub struct ThinkingConfig {
816    /// The thinking budget (number of thinking tokens)
817    ///
818    /// This is the Gemini 2.5 budget-based thinking control.
819    ///
820    /// - Set to 0 to disable thinking
821    /// - Set to -1 for dynamic thinking (model decides)
822    /// - Set to a positive number for a specific token budget
823    ///
824    /// Model-specific ranges:
825    /// - 2.5 Pro: 128 to 32768 (cannot disable thinking)
826    /// - 2.5 Flash: 0 to 24576
827    /// - 2.5 Flash Lite: 512 to 24576
828    #[serde(skip_serializing_if = "Option::is_none")]
829    pub thinking_budget: Option<i32>,
830
831    /// Whether to include thought summaries in the response
832    ///
833    /// When enabled, the response will include synthesized versions of the model's
834    /// raw thoughts, providing insights into the reasoning process.
835    #[serde(skip_serializing_if = "Option::is_none")]
836    pub include_thoughts: Option<bool>,
837
838    /// Native thinking level for Gemini 3 models.
839    ///
840    /// When set, the model uses level-based reasoning instead of a token budget.
841    /// Do not combine with `thinking_budget` — use one or the other.
842    #[serde(skip_serializing_if = "Option::is_none")]
843    pub thinking_level: Option<ThinkingLevel>,
844}
845
846impl ThinkingConfig {
847    /// Validate the thinking configuration.
848    ///
849    /// Returns an error if both `thinking_budget` and `thinking_level` are set,
850    /// since they are mutually exclusive controls (budget for Gemini 2.5, level for Gemini 3).
851    pub fn validate(&self) -> Result<(), String> {
852        if self.thinking_budget.is_some() && self.thinking_level.is_some() {
853            return Err(
854                "thinking_budget and thinking_level are mutually exclusive; use one or the other"
855                    .to_string(),
856            );
857        }
858        Ok(())
859    }
860
861    /// Create a new thinking config with default settings
862    pub fn new() -> Self {
863        Self { thinking_budget: None, include_thoughts: None, thinking_level: None }
864    }
865
866    /// Set the thinking budget (Gemini 2.5 budget-based control)
867    pub fn with_thinking_budget(mut self, budget: i32) -> Self {
868        self.thinking_budget = Some(budget);
869        self
870    }
871
872    /// Enable dynamic thinking (model decides the budget)
873    pub fn with_dynamic_thinking(mut self) -> Self {
874        self.thinking_budget = Some(-1);
875        self
876    }
877
878    /// Include thought summaries in the response
879    pub fn with_thoughts_included(mut self, include: bool) -> Self {
880        self.include_thoughts = Some(include);
881        self
882    }
883
884    /// Set the thinking level (Gemini 3 native level-based control).
885    ///
886    /// This is the preferred control for Gemini 3 models. Do not combine
887    /// with `with_thinking_budget` — use one or the other.
888    pub fn with_thinking_level(mut self, level: ThinkingLevel) -> Self {
889        self.thinking_level = Some(level);
890        self
891    }
892
893    /// Create a thinking config that enables dynamic thinking with thoughts included
894    pub fn dynamic_thinking() -> Self {
895        Self { thinking_budget: Some(-1), include_thoughts: Some(true), thinking_level: None }
896    }
897}
898
899impl Default for ThinkingConfig {
900    fn default() -> Self {
901        Self::new()
902    }
903}
904
905/// Configuration for generation
906#[derive(Debug, Default, Clone, Serialize, Deserialize)]
907#[serde(rename_all = "camelCase")]
908pub struct GenerationConfig {
909    /// The temperature for the model (0.0 to 1.0)
910    ///
911    /// Controls the randomness of the output. Higher values (e.g., 0.9) make output
912    /// more random, lower values (e.g., 0.1) make output more deterministic.
913    #[serde(skip_serializing_if = "Option::is_none")]
914    pub temperature: Option<f32>,
915
916    /// The top-p value for the model (0.0 to 1.0)
917    ///
918    /// For each token generation step, the model considers the top_p percentage of
919    /// probability mass for potential token choices. Lower values are more selective,
920    /// higher values allow more variety.
921    #[serde(skip_serializing_if = "Option::is_none")]
922    pub top_p: Option<f32>,
923
924    /// The top-k value for the model
925    ///
926    /// For each token generation step, the model considers the top_k most likely tokens.
927    /// Lower values are more selective, higher values allow more variety.
928    #[serde(skip_serializing_if = "Option::is_none")]
929    pub top_k: Option<i32>,
930
931    /// The maximum number of tokens to generate
932    ///
933    /// Limits the length of the generated content. One token is roughly 4 characters.
934    #[serde(skip_serializing_if = "Option::is_none")]
935    pub max_output_tokens: Option<i32>,
936
937    /// The candidate count
938    ///
939    /// Number of alternative responses to generate.
940    #[serde(skip_serializing_if = "Option::is_none")]
941    pub candidate_count: Option<i32>,
942
943    /// Whether to stop on specific sequences
944    ///
945    /// The model will stop generating content when it encounters any of these sequences.
946    #[serde(skip_serializing_if = "Option::is_none")]
947    pub stop_sequences: Option<Vec<String>>,
948
949    /// Seed used in decoding, so repeated requests with the same seed return the same output.
950    #[serde(default, skip_serializing_if = "Option::is_none")]
951    pub seed: Option<i64>,
952
953    /// Penalty applied to tokens that already appear in the response, encouraging new topics.
954    ///
955    /// The API rejects it with `INVALID_ARGUMENT` for models that do not enable penalties.
956    #[serde(default, skip_serializing_if = "Option::is_none")]
957    pub presence_penalty: Option<f32>,
958
959    /// Penalty scaled by how often a token already appears in the response.
960    ///
961    /// The API rejects it with `INVALID_ARGUMENT` for models that do not enable penalties.
962    #[serde(default, skip_serializing_if = "Option::is_none")]
963    pub frequency_penalty: Option<f32>,
964
965    /// Whether to return the log probabilities of the chosen tokens in
966    /// [`Candidate::logprobs_result`].
967    ///
968    /// The API rejects it with `INVALID_ARGUMENT` for models that do not enable log
969    /// probabilities.
970    #[serde(default, skip_serializing_if = "Option::is_none")]
971    pub response_logprobs: Option<bool>,
972
973    /// Number of top candidate tokens, with their log probabilities, to return at each
974    /// decoding step. Requires `response_logprobs`.
975    #[serde(default, skip_serializing_if = "Option::is_none")]
976    pub logprobs: Option<i32>,
977
978    /// The response mime type
979    ///
980    /// Specifies the format of the model's response.
981    #[serde(skip_serializing_if = "Option::is_none")]
982    pub response_mime_type: Option<String>,
983    /// The response schema
984    ///
985    /// Specifies the JSON schema for structured responses.
986    #[serde(skip_serializing_if = "Option::is_none")]
987    pub response_schema: Option<serde_json::Value>,
988
989    /// Response modalities (for TTS and other multimodal outputs)
990    #[serde(skip_serializing_if = "Option::is_none")]
991    pub response_modalities: Option<Vec<String>>,
992
993    /// Speech configuration for text-to-speech generation
994    #[serde(skip_serializing_if = "Option::is_none")]
995    pub speech_config: Option<SpeechConfig>,
996
997    /// The thinking configuration
998    ///
999    /// Configuration for the model's thinking process (Gemini 2.5 series only).
1000    #[serde(skip_serializing_if = "Option::is_none")]
1001    pub thinking_config: Option<ThinkingConfig>,
1002
1003    /// The resolution images and video frames are tokenised at, which their token count
1004    /// and cost depend on.
1005    #[serde(default, skip_serializing_if = "Option::is_none")]
1006    pub media_resolution: Option<MediaResolution>,
1007}
1008
1009/// The resolution Gemini tokenises images and video frames at: `generationConfig.mediaResolution`.
1010///
1011/// A video frame costs about 66 tokens at `Low` and about 258 at `Medium` and `High`; with
1012/// 32 tokens a second of audio, a second of video at 1 fps is about 100 or about 300 tokens.
1013///
1014/// # Example
1015///
1016/// ```rust
1017/// use adk_gemini::{GenerationConfig, MediaResolution};
1018///
1019/// let config = GenerationConfig { media_resolution: Some(MediaResolution::Low), ..Default::default() };
1020/// let json = serde_json::to_value(&config).unwrap();
1021/// assert_eq!(json["mediaResolution"], "MEDIA_RESOLUTION_LOW");
1022/// ```
1023#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1024#[non_exhaustive]
1025pub enum MediaResolution {
1026    /// The model's default.
1027    #[serde(rename = "MEDIA_RESOLUTION_UNSPECIFIED")]
1028    Unspecified,
1029    /// 64 tokens a frame (about 66 with overhead).
1030    #[serde(rename = "MEDIA_RESOLUTION_LOW")]
1031    Low,
1032    /// 256 tokens a frame.
1033    #[serde(rename = "MEDIA_RESOLUTION_MEDIUM")]
1034    Medium,
1035    /// Up to 256 tokens a frame, with zoomed reframing for images.
1036    #[serde(rename = "MEDIA_RESOLUTION_HIGH")]
1037    High,
1038}
1039
1040impl GenerationConfig {
1041    /// Validate the generation configuration.
1042    ///
1043    /// Returns an error if any parameter is outside its valid range:
1044    /// - `temperature`: must be between 0.0 and 2.0
1045    /// - `top_p`: must be between 0.0 and 1.0
1046    /// - `top_k`: must be positive
1047    /// - `max_output_tokens`: must be positive
1048    ///
1049    /// If `thinking_config` is present, delegates to [`ThinkingConfig::validate`] as well.
1050    /// All `None` fields are accepted without error.
1051    pub fn validate(&self) -> Result<(), String> {
1052        if let Some(t) = self.temperature
1053            && !(0.0..=2.0).contains(&t)
1054        {
1055            return Err("temperature must be between 0.0 and 2.0".to_string());
1056        }
1057        if let Some(p) = self.top_p
1058            && !(0.0..=1.0).contains(&p)
1059        {
1060            return Err("top_p must be between 0.0 and 1.0".to_string());
1061        }
1062        if let Some(k) = self.top_k
1063            && k <= 0
1064        {
1065            return Err("top_k must be positive".to_string());
1066        }
1067        if let Some(m) = self.max_output_tokens
1068            && m <= 0
1069        {
1070            return Err("max_output_tokens must be positive".to_string());
1071        }
1072        if let Some(ref tc) = self.thinking_config {
1073            tc.validate()?;
1074        }
1075        Ok(())
1076    }
1077}
1078
1079/// Configuration for speech generation (text-to-speech)
1080#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1081#[serde(rename_all = "camelCase")]
1082pub struct SpeechConfig {
1083    /// Single voice configuration
1084    #[serde(skip_serializing_if = "Option::is_none")]
1085    pub voice_config: Option<VoiceConfig>,
1086    /// Multi-speaker voice configuration
1087    #[serde(skip_serializing_if = "Option::is_none")]
1088    pub multi_speaker_voice_config: Option<MultiSpeakerVoiceConfig>,
1089}
1090
1091/// Voice configuration for text-to-speech
1092#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1093#[serde(rename_all = "camelCase")]
1094pub struct VoiceConfig {
1095    /// Prebuilt voice configuration
1096    #[serde(skip_serializing_if = "Option::is_none")]
1097    pub prebuilt_voice_config: Option<PrebuiltVoiceConfig>,
1098}
1099
1100/// Prebuilt voice configuration
1101#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1102#[serde(rename_all = "camelCase")]
1103pub struct PrebuiltVoiceConfig {
1104    /// The name of the voice to use
1105    pub voice_name: String,
1106}
1107
1108/// Multi-speaker voice configuration
1109#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1110#[serde(rename_all = "camelCase")]
1111pub struct MultiSpeakerVoiceConfig {
1112    /// Configuration for each speaker
1113    pub speaker_voice_configs: Vec<SpeakerVoiceConfig>,
1114}
1115
1116/// Configuration for a specific speaker in multi-speaker TTS
1117#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1118#[serde(rename_all = "camelCase")]
1119pub struct SpeakerVoiceConfig {
1120    /// The name of the speaker (must match the name used in the prompt)
1121    pub speaker: String,
1122    /// Voice configuration for this speaker
1123    pub voice_config: VoiceConfig,
1124}
1125
1126impl SpeechConfig {
1127    /// Create a new speech config with a single voice
1128    pub fn single_voice(voice_name: impl Into<String>) -> Self {
1129        Self {
1130            voice_config: Some(VoiceConfig {
1131                prebuilt_voice_config: Some(PrebuiltVoiceConfig { voice_name: voice_name.into() }),
1132            }),
1133            multi_speaker_voice_config: None,
1134        }
1135    }
1136
1137    /// Create a new speech config with multiple speakers
1138    pub fn multi_speaker(speakers: Vec<SpeakerVoiceConfig>) -> Self {
1139        Self {
1140            voice_config: None,
1141            multi_speaker_voice_config: Some(MultiSpeakerVoiceConfig {
1142                speaker_voice_configs: speakers,
1143            }),
1144        }
1145    }
1146}
1147
1148impl SpeakerVoiceConfig {
1149    /// Create a new speaker voice configuration
1150    pub fn new(speaker: impl Into<String>, voice_name: impl Into<String>) -> Self {
1151        Self {
1152            speaker: speaker.into(),
1153            voice_config: VoiceConfig {
1154                prebuilt_voice_config: Some(PrebuiltVoiceConfig { voice_name: voice_name.into() }),
1155            },
1156        }
1157    }
1158}
1159
1160#[cfg(test)]
1161mod effort_tests {
1162    use super::ThinkingLevel;
1163
1164    /// The harness levels map to their namesakes; `Minimal` is never produced.
1165    #[test]
1166    fn every_harness_effort_maps_to_its_namesake() {
1167        for (core, level) in [
1168            (adk_core::Effort::Low, ThinkingLevel::Low),
1169            (adk_core::Effort::Medium, ThinkingLevel::Medium),
1170            (adk_core::Effort::High, ThinkingLevel::High),
1171        ] {
1172            assert_eq!(ThinkingLevel::from(core), level);
1173        }
1174    }
1175}