rig/providers/gemini/
completion.rs

1// ================================================================
2//! Google Gemini Completion Integration
3//! From [Gemini API Reference](https://ai.google.dev/api/generate-content)
4// ================================================================
5/// `gemini-2.5-pro-preview-06-05` completion model
6pub const GEMINI_2_5_PRO_PREVIEW_06_05: &str = "gemini-2.5-pro-preview-06-05";
7/// `gemini-2.5-pro-preview-05-06` completion model
8pub const GEMINI_2_5_PRO_PREVIEW_05_06: &str = "gemini-2.5-pro-preview-05-06";
9/// `gemini-2.5-pro-preview-03-25` completion model
10pub const GEMINI_2_5_PRO_PREVIEW_03_25: &str = "gemini-2.5-pro-preview-03-25";
11/// `gemini-2.5-flash-preview-05-20` completion model
12pub const GEMINI_2_5_FLASH_PREVIEW_05_20: &str = "gemini-2.5-flash-preview-05-20";
13/// `gemini-2.5-flash-preview-04-17` completion model
14pub const GEMINI_2_5_FLASH_PREVIEW_04_17: &str = "gemini-2.5-flash-preview-04-17";
15/// `gemini-2.5-pro-exp-03-25` experimental completion model
16pub const GEMINI_2_5_PRO_EXP_03_25: &str = "gemini-2.5-pro-exp-03-25";
17/// `gemini-2.0-flash-lite` completion model
18pub const GEMINI_2_0_FLASH_LITE: &str = "gemini-2.0-flash-lite";
19/// `gemini-2.0-flash` completion model
20pub const GEMINI_2_0_FLASH: &str = "gemini-2.0-flash";
21/// `gemini-1.5-flash` completion model
22pub const GEMINI_1_5_FLASH: &str = "gemini-1.5-flash";
23/// `gemini-1.5-pro` completion model
24pub const GEMINI_1_5_PRO: &str = "gemini-1.5-pro";
25/// `gemini-1.5-pro-8b` completion model
26pub const GEMINI_1_5_PRO_8B: &str = "gemini-1.5-pro-8b";
27/// `gemini-1.0-pro` completion model
28pub const GEMINI_1_0_PRO: &str = "gemini-1.0-pro";
29
30use self::gemini_api_types::Schema;
31use crate::providers::gemini::streaming::StreamingCompletionResponse;
32use crate::{
33    OneOrMany,
34    completion::{self, CompletionError, CompletionRequest},
35};
36use gemini_api_types::{
37    Content, FunctionDeclaration, GenerateContentRequest, GenerateContentResponse,
38    GenerationConfig, Part, Role, Tool,
39};
40use serde_json::{Map, Value};
41use std::convert::TryFrom;
42
43use super::Client;
44
45// =================================================================
46// Rig Implementation Types
47// =================================================================
48
49#[derive(Clone)]
50pub struct CompletionModel {
51    pub(crate) client: Client,
52    pub model: String,
53}
54
55impl CompletionModel {
56    pub fn new(client: Client, model: &str) -> Self {
57        Self {
58            client,
59            model: model.to_string(),
60        }
61    }
62}
63
64impl completion::CompletionModel for CompletionModel {
65    type Response = GenerateContentResponse;
66    type StreamingResponse = StreamingCompletionResponse;
67
68    #[cfg_attr(feature = "worker", worker::send)]
69    async fn completion(
70        &self,
71        completion_request: CompletionRequest,
72    ) -> Result<completion::CompletionResponse<GenerateContentResponse>, CompletionError> {
73        let request = create_request_body(completion_request)?;
74
75        tracing::debug!(
76            "Sending completion request to Gemini API {}",
77            serde_json::to_string_pretty(&request)?
78        );
79
80        let response = self
81            .client
82            .post(&format!("/v1beta/models/{}:generateContent", self.model))
83            .json(&request)
84            .send()
85            .await?;
86
87        if response.status().is_success() {
88            let response = response.json::<GenerateContentResponse>().await?;
89            match response.usage_metadata {
90                Some(ref usage) => tracing::info!(target: "rig",
91                "Gemini completion token usage: {}",
92                usage
93                ),
94                None => tracing::info!(target: "rig",
95                    "Gemini completion token usage: n/a",
96                ),
97            }
98
99            tracing::debug!("Received response");
100
101            Ok(completion::CompletionResponse::try_from(response))
102        } else {
103            Err(CompletionError::ProviderError(response.text().await?))
104        }?
105    }
106
107    #[cfg_attr(feature = "worker", worker::send)]
108    async fn stream(
109        &self,
110        request: CompletionRequest,
111    ) -> Result<
112        crate::streaming::StreamingCompletionResponse<Self::StreamingResponse>,
113        CompletionError,
114    > {
115        CompletionModel::stream(self, request).await
116    }
117}
118
119pub(crate) fn create_request_body(
120    completion_request: CompletionRequest,
121) -> Result<GenerateContentRequest, CompletionError> {
122    let mut full_history = Vec::new();
123    full_history.extend(completion_request.chat_history);
124
125    let additional_params = completion_request
126        .additional_params
127        .unwrap_or_else(|| Value::Object(Map::new()));
128
129    let mut generation_config = serde_json::from_value::<GenerationConfig>(additional_params)?;
130
131    if let Some(temp) = completion_request.temperature {
132        generation_config.temperature = Some(temp);
133    }
134
135    if let Some(max_tokens) = completion_request.max_tokens {
136        generation_config.max_output_tokens = Some(max_tokens);
137    }
138
139    let system_instruction = completion_request.preamble.clone().map(|preamble| Content {
140        parts: OneOrMany::one(preamble.into()),
141        role: Some(Role::Model),
142    });
143
144    let tools = if completion_request.tools.is_empty() {
145        None
146    } else {
147        Some(Tool::try_from(completion_request.tools)?)
148    };
149
150    let request = GenerateContentRequest {
151        contents: full_history
152            .into_iter()
153            .map(|msg| {
154                msg.try_into()
155                    .map_err(|e| CompletionError::RequestError(Box::new(e)))
156            })
157            .collect::<Result<Vec<_>, _>>()?,
158        generation_config: Some(generation_config),
159        safety_settings: None,
160        tools,
161        tool_config: None,
162        system_instruction,
163    };
164
165    Ok(request)
166}
167
168impl TryFrom<completion::ToolDefinition> for Tool {
169    type Error = CompletionError;
170
171    fn try_from(tool: completion::ToolDefinition) -> Result<Self, Self::Error> {
172        let parameters: Option<Schema> =
173            if tool.parameters == serde_json::json!({"type": "object", "properties": {}}) {
174                None
175            } else {
176                Some(tool.parameters.try_into()?)
177            };
178
179        Ok(Self {
180            function_declarations: vec![FunctionDeclaration {
181                name: tool.name,
182                description: tool.description,
183                parameters,
184            }],
185            code_execution: None,
186        })
187    }
188}
189
190impl TryFrom<Vec<completion::ToolDefinition>> for Tool {
191    type Error = CompletionError;
192
193    fn try_from(tools: Vec<completion::ToolDefinition>) -> Result<Self, Self::Error> {
194        let mut function_declarations = Vec::new();
195
196        for tool in tools {
197            let parameters =
198                if tool.parameters == serde_json::json!({"type": "object", "properties": {}}) {
199                    None
200                } else {
201                    match tool.parameters.try_into() {
202                        Ok(schema) => Some(schema),
203                        Err(e) => {
204                            let emsg = format!(
205                                "Tool '{}' could not be converted to a schema: {:?}",
206                                tool.name, e,
207                            );
208                            return Err(CompletionError::ProviderError(emsg));
209                        }
210                    }
211                };
212
213            function_declarations.push(FunctionDeclaration {
214                name: tool.name,
215                description: tool.description,
216                parameters,
217            });
218        }
219
220        Ok(Self {
221            function_declarations,
222            code_execution: None,
223        })
224    }
225}
226
227impl TryFrom<GenerateContentResponse> for completion::CompletionResponse<GenerateContentResponse> {
228    type Error = CompletionError;
229
230    fn try_from(response: GenerateContentResponse) -> Result<Self, Self::Error> {
231        let candidate = response.candidates.first().ok_or_else(|| {
232            CompletionError::ResponseError("No response candidates in response".into())
233        })?;
234
235        let content = candidate
236            .content
237            .parts
238            .iter()
239            .map(|part| {
240                Ok(match part {
241                    Part::Text(text) => completion::AssistantContent::text(text),
242                    Part::FunctionCall(function_call) => completion::AssistantContent::tool_call(
243                        &function_call.name,
244                        &function_call.name,
245                        function_call.args.clone(),
246                    ),
247                    _ => {
248                        return Err(CompletionError::ResponseError(
249                            "Response did not contain a message or tool call".into(),
250                        ));
251                    }
252                })
253            })
254            .collect::<Result<Vec<_>, _>>()?;
255
256        let choice = OneOrMany::many(content).map_err(|_| {
257            CompletionError::ResponseError(
258                "Response contained no message or tool call (empty)".to_owned(),
259            )
260        })?;
261
262        let usage = response
263            .usage_metadata
264            .as_ref()
265            .map(|usage| completion::Usage {
266                input_tokens: usage.prompt_token_count as u64,
267                output_tokens: usage.candidates_token_count as u64,
268                total_tokens: usage.total_token_count as u64,
269            })
270            .unwrap_or_default();
271
272        Ok(completion::CompletionResponse {
273            choice,
274            usage,
275            raw_response: response,
276        })
277    }
278}
279
280pub mod gemini_api_types {
281    use std::{collections::HashMap, convert::Infallible, str::FromStr};
282
283    // =================================================================
284    // Gemini API Types
285    // =================================================================
286    use serde::{Deserialize, Serialize};
287    use serde_json::{Value, json};
288
289    use crate::{
290        OneOrMany,
291        completion::CompletionError,
292        message::{self, MessageError, MimeType as _},
293        one_or_many::string_or_one_or_many,
294        providers::gemini::gemini_api_types::{CodeExecutionResult, ExecutableCode},
295    };
296
297    /// Response from the model supporting multiple candidate responses.
298    /// Safety ratings and content filtering are reported for both prompt in GenerateContentResponse.prompt_feedback
299    /// and for each candidate in finishReason and in safetyRatings.
300    /// The API:
301    ///     - Returns either all requested candidates or none of them
302    ///     - Returns no candidates at all only if there was something wrong with the prompt (check promptFeedback)
303    ///     - Reports feedback on each candidate in finishReason and safetyRatings.
304    #[derive(Debug, Deserialize)]
305    #[serde(rename_all = "camelCase")]
306    pub struct GenerateContentResponse {
307        /// Candidate responses from the model.
308        pub candidates: Vec<ContentCandidate>,
309        /// Returns the prompt's feedback related to the content filters.
310        pub prompt_feedback: Option<PromptFeedback>,
311        /// Output only. Metadata on the generation requests' token usage.
312        pub usage_metadata: Option<UsageMetadata>,
313        pub model_version: Option<String>,
314    }
315
316    /// A response candidate generated from the model.
317    #[derive(Debug, Deserialize)]
318    #[serde(rename_all = "camelCase")]
319    pub struct ContentCandidate {
320        /// Output only. Generated content returned from the model.
321        pub content: Content,
322        /// Optional. Output only. The reason why the model stopped generating tokens.
323        /// If empty, the model has not stopped generating tokens.
324        pub finish_reason: Option<FinishReason>,
325        /// List of ratings for the safety of a response candidate.
326        /// There is at most one rating per category.
327        pub safety_ratings: Option<Vec<SafetyRating>>,
328        /// Output only. Citation information for model-generated candidate.
329        /// This field may be populated with recitation information for any text included in the content.
330        /// These are passages that are "recited" from copyrighted material in the foundational LLM's training data.
331        pub citation_metadata: Option<CitationMetadata>,
332        /// Output only. Token count for this candidate.
333        pub token_count: Option<i32>,
334        /// Output only.
335        pub avg_logprobs: Option<f64>,
336        /// Output only. Log-likelihood scores for the response tokens and top tokens
337        pub logprobs_result: Option<LogprobsResult>,
338        /// Output only. Index of the candidate in the list of response candidates.
339        pub index: Option<i32>,
340    }
341    #[derive(Debug, Deserialize, Serialize)]
342    pub struct Content {
343        /// Ordered Parts that constitute a single message. Parts may have different MIME types.
344        #[serde(deserialize_with = "string_or_one_or_many")]
345        pub parts: OneOrMany<Part>,
346        /// The producer of the content. Must be either 'user' or 'model'.
347        /// Useful to set for multi-turn conversations, otherwise can be left blank or unset.
348        pub role: Option<Role>,
349    }
350
351    impl TryFrom<message::Message> for Content {
352        type Error = message::MessageError;
353
354        fn try_from(msg: message::Message) -> Result<Self, Self::Error> {
355            Ok(match msg {
356                message::Message::User { content } => Content {
357                    parts: content.try_map(|c| c.try_into())?,
358                    role: Some(Role::User),
359                },
360                message::Message::Assistant { content, .. } => Content {
361                    role: Some(Role::Model),
362                    parts: content.map(|content| content.into()),
363                },
364            })
365        }
366    }
367
368    impl TryFrom<Content> for message::Message {
369        type Error = message::MessageError;
370
371        fn try_from(content: Content) -> Result<Self, Self::Error> {
372            match content.role {
373                Some(Role::User) | None => Ok(message::Message::User {
374                    content: content.parts.try_map(|part| {
375                        Ok(match part {
376                            Part::Text(text) => message::UserContent::text(text),
377                            Part::InlineData(inline_data) => {
378                                let mime_type =
379                                    message::MediaType::from_mime_type(&inline_data.mime_type);
380
381                                match mime_type {
382                                    Some(message::MediaType::Image(media_type)) => {
383                                        message::UserContent::image(
384                                            inline_data.data,
385                                            Some(message::ContentFormat::default()),
386                                            Some(media_type),
387                                            Some(message::ImageDetail::default()),
388                                        )
389                                    }
390                                    Some(message::MediaType::Document(media_type)) => {
391                                        message::UserContent::document(
392                                            inline_data.data,
393                                            Some(message::ContentFormat::default()),
394                                            Some(media_type),
395                                        )
396                                    }
397                                    Some(message::MediaType::Audio(media_type)) => {
398                                        message::UserContent::audio(
399                                            inline_data.data,
400                                            Some(message::ContentFormat::default()),
401                                            Some(media_type),
402                                        )
403                                    }
404                                    _ => {
405                                        return Err(message::MessageError::ConversionError(
406                                            format!("Unsupported media type {mime_type:?}"),
407                                        ));
408                                    }
409                                }
410                            }
411                            _ => {
412                                return Err(message::MessageError::ConversionError(format!(
413                                    "Unsupported gemini content part type: {part:?}"
414                                )));
415                            }
416                        })
417                    })?,
418                }),
419                Some(Role::Model) => Ok(message::Message::Assistant {
420                    id: None,
421                    content: content.parts.try_map(|part| {
422                        Ok(match part {
423                            Part::Text(text) => message::AssistantContent::text(text),
424                            Part::FunctionCall(function_call) => {
425                                message::AssistantContent::ToolCall(function_call.into())
426                            }
427                            _ => {
428                                return Err(message::MessageError::ConversionError(format!(
429                                    "Unsupported part type: {part:?}"
430                                )));
431                            }
432                        })
433                    })?,
434                }),
435            }
436        }
437    }
438
439    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
440    #[serde(rename_all = "lowercase")]
441    pub enum Role {
442        User,
443        Model,
444    }
445
446    /// A datatype containing media that is part of a multi-part [Content] message.
447    /// A Part consists of data which has an associated datatype. A Part can only contain one of the accepted types in Part.data.
448    /// A Part must have a fixed IANA MIME type identifying the type and subtype of the media if the inlineData field is filled with raw bytes.
449    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
450    #[serde(rename_all = "camelCase")]
451    pub enum Part {
452        Text(String),
453        InlineData(Blob),
454        FunctionCall(FunctionCall),
455        FunctionResponse(FunctionResponse),
456        FileData(FileData),
457        ExecutableCode(ExecutableCode),
458        CodeExecutionResult(CodeExecutionResult),
459    }
460
461    impl From<String> for Part {
462        fn from(text: String) -> Self {
463            Self::Text(text)
464        }
465    }
466
467    impl From<&str> for Part {
468        fn from(text: &str) -> Self {
469            Self::Text(text.to_string())
470        }
471    }
472
473    impl FromStr for Part {
474        type Err = Infallible;
475
476        fn from_str(s: &str) -> Result<Self, Self::Err> {
477            Ok(s.into())
478        }
479    }
480
481    impl TryFrom<message::UserContent> for Part {
482        type Error = message::MessageError;
483
484        fn try_from(content: message::UserContent) -> Result<Self, Self::Error> {
485            match content {
486                message::UserContent::Text(message::Text { text }) => Ok(Self::Text(text)),
487                message::UserContent::ToolResult(message::ToolResult { id, content, .. }) => {
488                    let content = match content.first() {
489                        message::ToolResultContent::Text(text) => text.text,
490                        message::ToolResultContent::Image(_) => {
491                            return Err(message::MessageError::ConversionError(
492                                "Tool result content must be text".to_string(),
493                            ));
494                        }
495                    };
496                    // Convert to JSON since this value may be a valid JSON value
497                    let result: serde_json::Value = serde_json::from_str(&content)
498                        .map_err(|x| MessageError::ConversionError(x.to_string()))?;
499                    Ok(Part::FunctionResponse(FunctionResponse {
500                        name: id,
501                        response: Some(json!({ "result": result })),
502                    }))
503                }
504                message::UserContent::Image(message::Image {
505                    data, media_type, ..
506                }) => match media_type {
507                    Some(media_type) => match media_type {
508                        message::ImageMediaType::JPEG
509                        | message::ImageMediaType::PNG
510                        | message::ImageMediaType::WEBP
511                        | message::ImageMediaType::HEIC
512                        | message::ImageMediaType::HEIF => Ok(Self::InlineData(Blob {
513                            mime_type: media_type.to_mime_type().to_owned(),
514                            data,
515                        })),
516                        _ => Err(message::MessageError::ConversionError(format!(
517                            "Unsupported image media type {media_type:?}"
518                        ))),
519                    },
520                    None => Err(message::MessageError::ConversionError(
521                        "Media type for image is required for Anthropic".to_string(),
522                    )),
523                },
524                message::UserContent::Document(message::Document {
525                    data, media_type, ..
526                }) => match media_type {
527                    Some(media_type) => match media_type {
528                        message::DocumentMediaType::PDF
529                        | message::DocumentMediaType::TXT
530                        | message::DocumentMediaType::RTF
531                        | message::DocumentMediaType::HTML
532                        | message::DocumentMediaType::CSS
533                        | message::DocumentMediaType::MARKDOWN
534                        | message::DocumentMediaType::CSV
535                        | message::DocumentMediaType::XML => Ok(Self::InlineData(Blob {
536                            mime_type: media_type.to_mime_type().to_owned(),
537                            data,
538                        })),
539                        _ => Err(message::MessageError::ConversionError(format!(
540                            "Unsupported document media type {media_type:?}"
541                        ))),
542                    },
543                    None => Err(message::MessageError::ConversionError(
544                        "Media type for document is required for Anthropic".to_string(),
545                    )),
546                },
547                message::UserContent::Audio(message::Audio {
548                    data, media_type, ..
549                }) => match media_type {
550                    Some(media_type) => Ok(Self::InlineData(Blob {
551                        mime_type: media_type.to_mime_type().to_owned(),
552                        data,
553                    })),
554                    None => Err(message::MessageError::ConversionError(
555                        "Media type for audio is required for Anthropic".to_string(),
556                    )),
557                },
558            }
559        }
560    }
561
562    impl From<message::AssistantContent> for Part {
563        fn from(content: message::AssistantContent) -> Self {
564            match content {
565                message::AssistantContent::Text(message::Text { text }) => text.into(),
566                message::AssistantContent::ToolCall(tool_call) => tool_call.into(),
567            }
568        }
569    }
570
571    impl From<message::ToolCall> for Part {
572        fn from(tool_call: message::ToolCall) -> Self {
573            Self::FunctionCall(FunctionCall {
574                name: tool_call.function.name,
575                args: tool_call.function.arguments,
576            })
577        }
578    }
579
580    /// Raw media bytes.
581    /// Text should not be sent as raw bytes, use the 'text' field.
582    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
583    #[serde(rename_all = "camelCase")]
584    pub struct Blob {
585        /// The IANA standard MIME type of the source data. Examples: - image/png - image/jpeg
586        /// If an unsupported MIME type is provided, an error will be returned.
587        pub mime_type: String,
588        /// Raw bytes for media formats. A base64-encoded string.
589        pub data: String,
590    }
591
592    /// A predicted FunctionCall returned from the model that contains a string representing the
593    /// FunctionDeclaration.name with the arguments and their values.
594    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
595    pub struct FunctionCall {
596        /// Required. The name of the function to call. Must be a-z, A-Z, 0-9, or contain underscores
597        /// and dashes, with a maximum length of 63.
598        pub name: String,
599        /// Optional. The function parameters and values in JSON object format.
600        pub args: serde_json::Value,
601    }
602
603    impl From<FunctionCall> for message::ToolCall {
604        fn from(function_call: FunctionCall) -> Self {
605            Self {
606                id: function_call.name.clone(),
607                call_id: None,
608                function: message::ToolFunction {
609                    name: function_call.name,
610                    arguments: function_call.args,
611                },
612            }
613        }
614    }
615
616    impl From<message::ToolCall> for FunctionCall {
617        fn from(tool_call: message::ToolCall) -> Self {
618            Self {
619                name: tool_call.function.name,
620                args: tool_call.function.arguments,
621            }
622        }
623    }
624
625    /// The result output from a FunctionCall that contains a string representing the FunctionDeclaration.name
626    /// and a structured JSON object containing any output from the function is used as context to the model.
627    /// This should contain the result of aFunctionCall made based on model prediction.
628    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
629    pub struct FunctionResponse {
630        /// The name of the function to call. Must be a-z, A-Z, 0-9, or contain underscores and dashes,
631        /// with a maximum length of 63.
632        pub name: String,
633        /// The function response in JSON object format.
634        pub response: Option<serde_json::Value>,
635    }
636
637    /// URI based data.
638    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
639    #[serde(rename_all = "camelCase")]
640    pub struct FileData {
641        /// Optional. The IANA standard MIME type of the source data.
642        pub mime_type: Option<String>,
643        /// Required. URI.
644        pub file_uri: String,
645    }
646
647    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
648    pub struct SafetyRating {
649        pub category: HarmCategory,
650        pub probability: HarmProbability,
651    }
652
653    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
654    #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
655    pub enum HarmProbability {
656        HarmProbabilityUnspecified,
657        Negligible,
658        Low,
659        Medium,
660        High,
661    }
662
663    #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
664    #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
665    pub enum HarmCategory {
666        HarmCategoryUnspecified,
667        HarmCategoryDerogatory,
668        HarmCategoryToxicity,
669        HarmCategoryViolence,
670        HarmCategorySexually,
671        HarmCategoryMedical,
672        HarmCategoryDangerous,
673        HarmCategoryHarassment,
674        HarmCategoryHateSpeech,
675        HarmCategorySexuallyExplicit,
676        HarmCategoryDangerousContent,
677        HarmCategoryCivicIntegrity,
678    }
679
680    #[derive(Debug, Deserialize, Clone, Default)]
681    #[serde(rename_all = "camelCase")]
682    pub struct UsageMetadata {
683        pub prompt_token_count: i32,
684        #[serde(skip_serializing_if = "Option::is_none")]
685        pub cached_content_token_count: Option<i32>,
686        pub candidates_token_count: i32,
687        pub total_token_count: i32,
688    }
689
690    impl std::fmt::Display for UsageMetadata {
691        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
692            write!(
693                f,
694                "Prompt token count: {}\nCached content token count: {}\nCandidates token count: {}\nTotal token count: {}",
695                self.prompt_token_count,
696                match self.cached_content_token_count {
697                    Some(count) => count.to_string(),
698                    None => "n/a".to_string(),
699                },
700                self.candidates_token_count,
701                self.total_token_count
702            )
703        }
704    }
705
706    /// A set of the feedback metadata the prompt specified in [GenerateContentRequest.contents](GenerateContentRequest).
707    #[derive(Debug, Deserialize)]
708    #[serde(rename_all = "camelCase")]
709    pub struct PromptFeedback {
710        /// Optional. If set, the prompt was blocked and no candidates are returned. Rephrase the prompt.
711        pub block_reason: Option<BlockReason>,
712        /// Ratings for safety of the prompt. There is at most one rating per category.
713        pub safety_ratings: Option<Vec<SafetyRating>>,
714    }
715
716    /// Reason why a prompt was blocked by the model
717    #[derive(Debug, Deserialize)]
718    #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
719    pub enum BlockReason {
720        /// Default value. This value is unused.
721        BlockReasonUnspecified,
722        /// Prompt was blocked due to safety reasons. Inspect safetyRatings to understand which safety category blocked it.
723        Safety,
724        /// Prompt was blocked due to unknown reasons.
725        Other,
726        /// Prompt was blocked due to the terms which are included from the terminology blocklist.
727        Blocklist,
728        /// Prompt was blocked due to prohibited content.
729        ProhibitedContent,
730    }
731
732    #[derive(Debug, Deserialize)]
733    #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
734    pub enum FinishReason {
735        /// Default value. This value is unused.
736        FinishReasonUnspecified,
737        /// Natural stop point of the model or provided stop sequence.
738        Stop,
739        /// The maximum number of tokens as specified in the request was reached.
740        MaxTokens,
741        /// The response candidate content was flagged for safety reasons.
742        Safety,
743        /// The response candidate content was flagged for recitation reasons.
744        Recitation,
745        /// The response candidate content was flagged for using an unsupported language.
746        Language,
747        /// Unknown reason.
748        Other,
749        /// Token generation stopped because the content contains forbidden terms.
750        Blocklist,
751        /// Token generation stopped for potentially containing prohibited content.
752        ProhibitedContent,
753        /// Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).
754        Spii,
755        /// The function call generated by the model is invalid.
756        MalformedFunctionCall,
757    }
758
759    #[derive(Debug, Deserialize)]
760    #[serde(rename_all = "camelCase")]
761    pub struct CitationMetadata {
762        pub citation_sources: Vec<CitationSource>,
763    }
764
765    #[derive(Debug, Deserialize)]
766    #[serde(rename_all = "camelCase")]
767    pub struct CitationSource {
768        #[serde(skip_serializing_if = "Option::is_none")]
769        pub uri: Option<String>,
770        #[serde(skip_serializing_if = "Option::is_none")]
771        pub start_index: Option<i32>,
772        #[serde(skip_serializing_if = "Option::is_none")]
773        pub end_index: Option<i32>,
774        #[serde(skip_serializing_if = "Option::is_none")]
775        pub license: Option<String>,
776    }
777
778    #[derive(Debug, Deserialize)]
779    #[serde(rename_all = "camelCase")]
780    pub struct LogprobsResult {
781        pub top_candidate: Vec<TopCandidate>,
782        pub chosen_candidate: Vec<LogProbCandidate>,
783    }
784
785    #[derive(Debug, Deserialize)]
786    pub struct TopCandidate {
787        pub candidates: Vec<LogProbCandidate>,
788    }
789
790    #[derive(Debug, Deserialize)]
791    #[serde(rename_all = "camelCase")]
792    pub struct LogProbCandidate {
793        pub token: String,
794        pub token_id: String,
795        pub log_probability: f64,
796    }
797
798    /// Gemini API Configuration options for model generation and outputs. Not all parameters are
799    /// configurable for every model. From [Gemini API Reference](https://ai.google.dev/api/generate-content#generationconfig)
800    /// ### Rig Note:
801    /// Can be used to construct a typesafe `additional_params` in rig::[AgentBuilder](crate::agent::AgentBuilder).
802    #[derive(Debug, Deserialize, Serialize)]
803    #[serde(rename_all = "camelCase")]
804    pub struct GenerationConfig {
805        /// The set of character sequences (up to 5) that will stop output generation. If specified, the API will stop
806        /// at the first appearance of a stop_sequence. The stop sequence will not be included as part of the response.
807        #[serde(skip_serializing_if = "Option::is_none")]
808        pub stop_sequences: Option<Vec<String>>,
809        /// MIME type of the generated candidate text. Supported MIME types are:
810        ///     - text/plain:  (default) Text output
811        ///     - application/json: JSON response in the response candidates.
812        ///     - text/x.enum: ENUM as a string response in the response candidates.
813        /// Refer to the docs for a list of all supported text MIME types
814        #[serde(skip_serializing_if = "Option::is_none")]
815        pub response_mime_type: Option<String>,
816        /// Output schema of the generated candidate text. Schemas must be a subset of the OpenAPI schema and can be
817        /// objects, primitives or arrays. If set, a compatible responseMimeType must also  be set. Compatible MIME
818        /// types: application/json: Schema for JSON response. Refer to the JSON text generation guide for more details.
819        #[serde(skip_serializing_if = "Option::is_none")]
820        pub response_schema: Option<Schema>,
821        /// Number of generated responses to return. Currently, this value can only be set to 1. If
822        /// unset, this will default to 1.
823        #[serde(skip_serializing_if = "Option::is_none")]
824        pub candidate_count: Option<i32>,
825        /// The maximum number of tokens to include in a response candidate. Note: The default value varies by model, see
826        /// the Model.output_token_limit attribute of the Model returned from the getModel function.
827        #[serde(skip_serializing_if = "Option::is_none")]
828        pub max_output_tokens: Option<u64>,
829        /// Controls the randomness of the output. Note: The default value varies by model, see the Model.temperature
830        /// attribute of the Model returned from the getModel function. Values can range from [0.0, 2.0].
831        #[serde(skip_serializing_if = "Option::is_none")]
832        pub temperature: Option<f64>,
833        /// The maximum cumulative probability of tokens to consider when sampling. The model uses combined Top-k and
834        /// Top-p (nucleus) sampling. Tokens are sorted based on their assigned probabilities so that only the most
835        /// likely tokens are considered. Top-k sampling directly limits the maximum number of tokens to consider, while
836        /// Nucleus sampling limits the number of tokens based on the cumulative probability. Note: The default value
837        /// varies by Model and is specified by theModel.top_p attribute returned from the getModel function. An empty
838        /// topK attribute indicates that the model doesn't apply top-k sampling and doesn't allow setting topK on requests.
839        #[serde(skip_serializing_if = "Option::is_none")]
840        pub top_p: Option<f64>,
841        /// The maximum number of tokens to consider when sampling. Gemini models use Top-p (nucleus) sampling or a
842        /// combination of Top-k and nucleus sampling. Top-k sampling considers the set of topK most probable tokens.
843        /// Models running with nucleus sampling don't allow topK setting. Note: The default value varies by Model and is
844        /// specified by theModel.top_p attribute returned from the getModel function. An empty topK attribute indicates
845        /// that the model doesn't apply top-k sampling and doesn't allow setting topK on requests.
846        #[serde(skip_serializing_if = "Option::is_none")]
847        pub top_k: Option<i32>,
848        /// Presence penalty applied to the next token's logprobs if the token has already been seen in the response.
849        /// This penalty is binary on/off and not dependent on the number of times the token is used (after the first).
850        /// Use frequencyPenalty for a penalty that increases with each use. A positive penalty will discourage the use
851        /// of tokens that have already been used in the response, increasing the vocabulary. A negative penalty will
852        /// encourage the use of tokens that have already been used in the response, decreasing the vocabulary.
853        #[serde(skip_serializing_if = "Option::is_none")]
854        pub presence_penalty: Option<f64>,
855        /// Frequency penalty applied to the next token's logprobs, multiplied by the number of times each token has been
856        /// seen in the response so far. A positive penalty will discourage the use of tokens that have already been
857        /// used, proportional to the number of times the token has been used: The more a token is used, the more
858        /// difficult it is for the  model to use that token again increasing the vocabulary of responses. Caution: A
859        /// negative penalty will encourage the model to reuse tokens proportional to the number of times the token has
860        /// been used. Small negative values will reduce the vocabulary of a response. Larger negative values will cause
861        /// the model to  repeating a common token until it hits the maxOutputTokens limit: "...the the the the the...".
862        #[serde(skip_serializing_if = "Option::is_none")]
863        pub frequency_penalty: Option<f64>,
864        /// If true, export the logprobs results in response.
865        #[serde(skip_serializing_if = "Option::is_none")]
866        pub response_logprobs: Option<bool>,
867        /// Only valid if responseLogprobs=True. This sets the number of top logprobs to return at each decoding step in
868        /// [Candidate.logprobs_result].
869        #[serde(skip_serializing_if = "Option::is_none")]
870        pub logprobs: Option<i32>,
871    }
872
873    impl Default for GenerationConfig {
874        fn default() -> Self {
875            Self {
876                temperature: Some(1.0),
877                max_output_tokens: Some(4096),
878                stop_sequences: None,
879                response_mime_type: None,
880                response_schema: None,
881                candidate_count: None,
882                top_p: None,
883                top_k: None,
884                presence_penalty: None,
885                frequency_penalty: None,
886                response_logprobs: None,
887                logprobs: None,
888            }
889        }
890    }
891    /// The Schema object allows the definition of input and output data types. These types can be objects, but also
892    /// primitives and arrays. Represents a select subset of an OpenAPI 3.0 schema object.
893    /// From [Gemini API Reference](https://ai.google.dev/api/caching#Schema)
894    #[derive(Debug, Deserialize, Serialize, Clone)]
895    pub struct Schema {
896        pub r#type: String,
897        #[serde(skip_serializing_if = "Option::is_none")]
898        pub format: Option<String>,
899        #[serde(skip_serializing_if = "Option::is_none")]
900        pub description: Option<String>,
901        #[serde(skip_serializing_if = "Option::is_none")]
902        pub nullable: Option<bool>,
903        #[serde(skip_serializing_if = "Option::is_none")]
904        pub r#enum: Option<Vec<String>>,
905        #[serde(skip_serializing_if = "Option::is_none")]
906        pub max_items: Option<i32>,
907        #[serde(skip_serializing_if = "Option::is_none")]
908        pub min_items: Option<i32>,
909        #[serde(skip_serializing_if = "Option::is_none")]
910        pub properties: Option<HashMap<String, Schema>>,
911        #[serde(skip_serializing_if = "Option::is_none")]
912        pub required: Option<Vec<String>>,
913        #[serde(skip_serializing_if = "Option::is_none")]
914        pub items: Option<Box<Schema>>,
915    }
916
917    impl TryFrom<Value> for Schema {
918        type Error = CompletionError;
919
920        fn try_from(value: Value) -> Result<Self, Self::Error> {
921            if let Some(obj) = value.as_object() {
922                Ok(Schema {
923                    r#type: obj
924                        .get("type")
925                        .and_then(|v| {
926                            if v.is_string() {
927                                v.as_str().map(String::from)
928                            } else if v.is_array() {
929                                v.as_array()
930                                    .and_then(|arr| arr.first())
931                                    .and_then(|v| v.as_str().map(String::from))
932                            } else {
933                                None
934                            }
935                        })
936                        .unwrap_or_default(),
937                    format: obj.get("format").and_then(|v| v.as_str()).map(String::from),
938                    description: obj
939                        .get("description")
940                        .and_then(|v| v.as_str())
941                        .map(String::from),
942                    nullable: obj.get("nullable").and_then(|v| v.as_bool()),
943                    r#enum: obj.get("enum").and_then(|v| v.as_array()).map(|arr| {
944                        arr.iter()
945                            .filter_map(|v| v.as_str().map(String::from))
946                            .collect()
947                    }),
948                    max_items: obj
949                        .get("maxItems")
950                        .and_then(|v| v.as_i64())
951                        .map(|v| v as i32),
952                    min_items: obj
953                        .get("minItems")
954                        .and_then(|v| v.as_i64())
955                        .map(|v| v as i32),
956                    properties: obj
957                        .get("properties")
958                        .and_then(|v| v.as_object())
959                        .map(|map| {
960                            map.iter()
961                                .filter_map(|(k, v)| {
962                                    v.clone().try_into().ok().map(|schema| (k.clone(), schema))
963                                })
964                                .collect()
965                        }),
966                    required: obj.get("required").and_then(|v| v.as_array()).map(|arr| {
967                        arr.iter()
968                            .filter_map(|v| v.as_str().map(String::from))
969                            .collect()
970                    }),
971                    items: obj
972                        .get("items")
973                        .map(|v| Box::new(v.clone().try_into().unwrap())),
974                })
975            } else {
976                Err(CompletionError::ResponseError(
977                    "Expected a JSON object for Schema".into(),
978                ))
979            }
980        }
981    }
982
983    #[derive(Debug, Serialize)]
984    #[serde(rename_all = "camelCase")]
985    pub struct GenerateContentRequest {
986        pub contents: Vec<Content>,
987        #[serde(skip_serializing_if = "Option::is_none")]
988        pub tools: Option<Tool>,
989        pub tool_config: Option<ToolConfig>,
990        /// Optional. Configuration options for model generation and outputs.
991        pub generation_config: Option<GenerationConfig>,
992        /// Optional. A list of unique SafetySetting instances for blocking unsafe content. This will be enforced on the
993        /// [GenerateContentRequest.contents] and [GenerateContentResponse.candidates]. There should not be more than one
994        /// setting for each SafetyCategory type. The API will block any contents and responses that fail to meet the
995        /// thresholds set by these settings. This list overrides the default settings for each SafetyCategory specified
996        /// in the safetySettings. If there is no SafetySetting for a given SafetyCategory provided in the list, the API
997        /// will use the default safety setting for that category. Harm categories:
998        ///     - HARM_CATEGORY_HATE_SPEECH,
999        ///     - HARM_CATEGORY_SEXUALLY_EXPLICIT
1000        ///     - HARM_CATEGORY_DANGEROUS_CONTENT
1001        ///     - HARM_CATEGORY_HARASSMENT
1002        /// are supported.
1003        /// Refer to the guide for detailed information on available safety settings. Also refer to the Safety guidance
1004        /// to learn how to incorporate safety considerations in your AI applications.
1005        pub safety_settings: Option<Vec<SafetySetting>>,
1006        /// Optional. Developer set system instruction(s). Currently, text only.
1007        /// From [Gemini API Reference](https://ai.google.dev/gemini-api/docs/system-instructions?lang=rest)
1008        pub system_instruction: Option<Content>,
1009        // cachedContent: Optional<String>
1010    }
1011
1012    #[derive(Debug, Serialize)]
1013    #[serde(rename_all = "camelCase")]
1014    pub struct Tool {
1015        pub function_declarations: Vec<FunctionDeclaration>,
1016        pub code_execution: Option<CodeExecution>,
1017    }
1018
1019    #[derive(Debug, Serialize, Clone)]
1020    #[serde(rename_all = "camelCase")]
1021    pub struct FunctionDeclaration {
1022        pub name: String,
1023        pub description: String,
1024        #[serde(skip_serializing_if = "Option::is_none")]
1025        pub parameters: Option<Schema>,
1026    }
1027
1028    #[derive(Debug, Serialize)]
1029    #[serde(rename_all = "camelCase")]
1030    pub struct ToolConfig {
1031        pub schema: Option<Schema>,
1032    }
1033
1034    #[derive(Debug, Serialize)]
1035    #[serde(rename_all = "camelCase")]
1036    pub struct CodeExecution {}
1037
1038    #[derive(Debug, Serialize)]
1039    #[serde(rename_all = "camelCase")]
1040    pub struct SafetySetting {
1041        pub category: HarmCategory,
1042        pub threshold: HarmBlockThreshold,
1043    }
1044
1045    #[derive(Debug, Serialize)]
1046    #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
1047    pub enum HarmBlockThreshold {
1048        HarmBlockThresholdUnspecified,
1049        BlockLowAndAbove,
1050        BlockMediumAndAbove,
1051        BlockOnlyHigh,
1052        BlockNone,
1053        Off,
1054    }
1055}
1056
1057#[cfg(test)]
1058mod tests {
1059    use crate::message;
1060
1061    use super::*;
1062    use serde_json::json;
1063
1064    #[test]
1065    fn test_deserialize_message_user() {
1066        let raw_message = r#"{
1067            "parts": [
1068                {"text": "Hello, world!"},
1069                {"inlineData": {"mimeType": "image/png", "data": "base64encodeddata"}},
1070                {"functionCall": {"name": "test_function", "args": {"arg1": "value1"}}},
1071                {"functionResponse": {"name": "test_function", "response": {"result": "success"}}},
1072                {"fileData": {"mimeType": "application/pdf", "fileUri": "http://example.com/file.pdf"}},
1073                {"executableCode": {"code": "print('Hello, world!')", "language": "PYTHON"}},
1074                {"codeExecutionResult": {"output": "Hello, world!", "outcome": "OUTCOME_OK"}}
1075            ],
1076            "role": "user"
1077        }"#;
1078
1079        let content: Content = {
1080            let jd = &mut serde_json::Deserializer::from_str(raw_message);
1081            serde_path_to_error::deserialize(jd).unwrap_or_else(|err| {
1082                panic!("Deserialization error at {}: {}", err.path(), err);
1083            })
1084        };
1085        assert_eq!(content.role, Some(Role::User));
1086        assert_eq!(content.parts.len(), 7);
1087
1088        let parts: Vec<Part> = content.parts.into_iter().collect();
1089
1090        if let Part::Text(text) = &parts[0] {
1091            assert_eq!(text, "Hello, world!");
1092        } else {
1093            panic!("Expected text part");
1094        }
1095
1096        if let Part::InlineData(inline_data) = &parts[1] {
1097            assert_eq!(inline_data.mime_type, "image/png");
1098            assert_eq!(inline_data.data, "base64encodeddata");
1099        } else {
1100            panic!("Expected inline data part");
1101        }
1102
1103        if let Part::FunctionCall(function_call) = &parts[2] {
1104            assert_eq!(function_call.name, "test_function");
1105            assert_eq!(
1106                function_call.args.as_object().unwrap().get("arg1").unwrap(),
1107                "value1"
1108            );
1109        } else {
1110            panic!("Expected function call part");
1111        }
1112
1113        if let Part::FunctionResponse(function_response) = &parts[3] {
1114            assert_eq!(function_response.name, "test_function");
1115            assert_eq!(
1116                function_response
1117                    .response
1118                    .as_ref()
1119                    .unwrap()
1120                    .get("result")
1121                    .unwrap(),
1122                "success"
1123            );
1124        } else {
1125            panic!("Expected function response part");
1126        }
1127
1128        if let Part::FileData(file_data) = &parts[4] {
1129            assert_eq!(file_data.mime_type.as_ref().unwrap(), "application/pdf");
1130            assert_eq!(file_data.file_uri, "http://example.com/file.pdf");
1131        } else {
1132            panic!("Expected file data part");
1133        }
1134
1135        if let Part::ExecutableCode(executable_code) = &parts[5] {
1136            assert_eq!(executable_code.code, "print('Hello, world!')");
1137        } else {
1138            panic!("Expected executable code part");
1139        }
1140
1141        if let Part::CodeExecutionResult(code_execution_result) = &parts[6] {
1142            assert_eq!(
1143                code_execution_result.clone().output.unwrap(),
1144                "Hello, world!"
1145            );
1146        } else {
1147            panic!("Expected code execution result part");
1148        }
1149    }
1150
1151    #[test]
1152    fn test_deserialize_message_model() {
1153        let json_data = json!({
1154            "parts": [{"text": "Hello, user!"}],
1155            "role": "model"
1156        });
1157
1158        let content: Content = serde_json::from_value(json_data).unwrap();
1159        assert_eq!(content.role, Some(Role::Model));
1160        assert_eq!(content.parts.len(), 1);
1161        if let Part::Text(text) = &content.parts.first() {
1162            assert_eq!(text, "Hello, user!");
1163        } else {
1164            panic!("Expected text part");
1165        }
1166    }
1167
1168    #[test]
1169    fn test_message_conversion_user() {
1170        let msg = message::Message::user("Hello, world!");
1171        let content: Content = msg.try_into().unwrap();
1172        assert_eq!(content.role, Some(Role::User));
1173        assert_eq!(content.parts.len(), 1);
1174        if let Part::Text(text) = &content.parts.first() {
1175            assert_eq!(text, "Hello, world!");
1176        } else {
1177            panic!("Expected text part");
1178        }
1179    }
1180
1181    #[test]
1182    fn test_message_conversion_model() {
1183        let msg = message::Message::assistant("Hello, user!");
1184
1185        let content: Content = msg.try_into().unwrap();
1186        assert_eq!(content.role, Some(Role::Model));
1187        assert_eq!(content.parts.len(), 1);
1188        if let Part::Text(text) = &content.parts.first() {
1189            assert_eq!(text, "Hello, user!");
1190        } else {
1191            panic!("Expected text part");
1192        }
1193    }
1194
1195    #[test]
1196    fn test_message_conversion_tool_call() {
1197        let tool_call = message::ToolCall {
1198            id: "test_tool".to_string(),
1199            call_id: None,
1200            function: message::ToolFunction {
1201                name: "test_function".to_string(),
1202                arguments: json!({"arg1": "value1"}),
1203            },
1204        };
1205
1206        let msg = message::Message::Assistant {
1207            id: None,
1208            content: OneOrMany::one(message::AssistantContent::ToolCall(tool_call)),
1209        };
1210
1211        let content: Content = msg.try_into().unwrap();
1212        assert_eq!(content.role, Some(Role::Model));
1213        assert_eq!(content.parts.len(), 1);
1214        if let Part::FunctionCall(function_call) = &content.parts.first() {
1215            assert_eq!(function_call.name, "test_function");
1216            assert_eq!(
1217                function_call.args.as_object().unwrap().get("arg1").unwrap(),
1218                "value1"
1219            );
1220        } else {
1221            panic!("Expected function call part");
1222        }
1223    }
1224}