1pub const GEMINI_2_5_PRO_PREVIEW_06_05: &str = "gemini-2.5-pro-preview-06-05";
7pub const GEMINI_2_5_PRO_PREVIEW_05_06: &str = "gemini-2.5-pro-preview-05-06";
9pub const GEMINI_2_5_PRO_PREVIEW_03_25: &str = "gemini-2.5-pro-preview-03-25";
11pub const GEMINI_2_5_FLASH_PREVIEW_05_20: &str = "gemini-2.5-flash-preview-05-20";
13pub const GEMINI_2_5_FLASH_PREVIEW_04_17: &str = "gemini-2.5-flash-preview-04-17";
15pub const GEMINI_2_5_PRO_EXP_03_25: &str = "gemini-2.5-pro-exp-03-25";
17pub const GEMINI_2_0_FLASH_LITE: &str = "gemini-2.0-flash-lite";
19pub const GEMINI_2_0_FLASH: &str = "gemini-2.0-flash";
21pub const GEMINI_1_5_FLASH: &str = "gemini-1.5-flash";
23pub const GEMINI_1_5_PRO: &str = "gemini-1.5-pro";
25pub const GEMINI_1_5_PRO_8B: &str = "gemini-1.5-pro-8b";
27pub 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#[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 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 #[derive(Debug, Deserialize)]
305 #[serde(rename_all = "camelCase")]
306 pub struct GenerateContentResponse {
307 pub candidates: Vec<ContentCandidate>,
309 pub prompt_feedback: Option<PromptFeedback>,
311 pub usage_metadata: Option<UsageMetadata>,
313 pub model_version: Option<String>,
314 }
315
316 #[derive(Debug, Deserialize)]
318 #[serde(rename_all = "camelCase")]
319 pub struct ContentCandidate {
320 pub content: Content,
322 pub finish_reason: Option<FinishReason>,
325 pub safety_ratings: Option<Vec<SafetyRating>>,
328 pub citation_metadata: Option<CitationMetadata>,
332 pub token_count: Option<i32>,
334 pub avg_logprobs: Option<f64>,
336 pub logprobs_result: Option<LogprobsResult>,
338 pub index: Option<i32>,
340 }
341 #[derive(Debug, Deserialize, Serialize)]
342 pub struct Content {
343 #[serde(deserialize_with = "string_or_one_or_many")]
345 pub parts: OneOrMany<Part>,
346 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 #[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 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 #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
583 #[serde(rename_all = "camelCase")]
584 pub struct Blob {
585 pub mime_type: String,
588 pub data: String,
590 }
591
592 #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
595 pub struct FunctionCall {
596 pub name: String,
599 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 #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
629 pub struct FunctionResponse {
630 pub name: String,
633 pub response: Option<serde_json::Value>,
635 }
636
637 #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
639 #[serde(rename_all = "camelCase")]
640 pub struct FileData {
641 pub mime_type: Option<String>,
643 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 #[derive(Debug, Deserialize)]
708 #[serde(rename_all = "camelCase")]
709 pub struct PromptFeedback {
710 pub block_reason: Option<BlockReason>,
712 pub safety_ratings: Option<Vec<SafetyRating>>,
714 }
715
716 #[derive(Debug, Deserialize)]
718 #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
719 pub enum BlockReason {
720 BlockReasonUnspecified,
722 Safety,
724 Other,
726 Blocklist,
728 ProhibitedContent,
730 }
731
732 #[derive(Debug, Deserialize)]
733 #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
734 pub enum FinishReason {
735 FinishReasonUnspecified,
737 Stop,
739 MaxTokens,
741 Safety,
743 Recitation,
745 Language,
747 Other,
749 Blocklist,
751 ProhibitedContent,
753 Spii,
755 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 #[derive(Debug, Deserialize, Serialize)]
803 #[serde(rename_all = "camelCase")]
804 pub struct GenerationConfig {
805 #[serde(skip_serializing_if = "Option::is_none")]
808 pub stop_sequences: Option<Vec<String>>,
809 #[serde(skip_serializing_if = "Option::is_none")]
815 pub response_mime_type: Option<String>,
816 #[serde(skip_serializing_if = "Option::is_none")]
820 pub response_schema: Option<Schema>,
821 #[serde(skip_serializing_if = "Option::is_none")]
824 pub candidate_count: Option<i32>,
825 #[serde(skip_serializing_if = "Option::is_none")]
828 pub max_output_tokens: Option<u64>,
829 #[serde(skip_serializing_if = "Option::is_none")]
832 pub temperature: Option<f64>,
833 #[serde(skip_serializing_if = "Option::is_none")]
840 pub top_p: Option<f64>,
841 #[serde(skip_serializing_if = "Option::is_none")]
847 pub top_k: Option<i32>,
848 #[serde(skip_serializing_if = "Option::is_none")]
854 pub presence_penalty: Option<f64>,
855 #[serde(skip_serializing_if = "Option::is_none")]
863 pub frequency_penalty: Option<f64>,
864 #[serde(skip_serializing_if = "Option::is_none")]
866 pub response_logprobs: Option<bool>,
867 #[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 #[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 pub generation_config: Option<GenerationConfig>,
992 pub safety_settings: Option<Vec<SafetySetting>>,
1006 pub system_instruction: Option<Content>,
1009 }
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}