gemini-client-api 7.4.5

Library to use Google Gemini API. Automatic context management, schema generation, function calling and more.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use base64::{Engine, engine::general_purpose::STANDARD};
use core::fmt;
use derive_new::new;
use getset::Getters;
use mime::{FromStrError, Mime};
#[cfg(feature = "reqwest")]
use reqwest::header::{HeaderMap, ToStrError};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
use std::str::FromStr;
mod chat;
pub use chat::Chat;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum Role {
    User,
    Model,
    Function,
}

fn deserialize_mime<'de, D>(deserializer: D) -> Result<Mime, D::Error>
where
    D: Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    Mime::from_str(&s).map_err(serde::de::Error::custom)
}
fn serialize_mime<S>(mime: &Mime, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    serializer.serialize_str(mime.as_ref())
}
#[derive(Serialize, Deserialize, Clone, Getters, Debug)]
pub struct InlineData {
    #[get = "pub"]
    #[serde(
        deserialize_with = "deserialize_mime",
        serialize_with = "serialize_mime"
    )]
    mime_type: Mime,
    #[get = "pub"]
    ///Base64 encoded string.
    data: String,
}

#[derive(thiserror::Error, Debug)]
pub enum InlineDataError {
    #[error(transparent)]
    #[cfg(feature = "reqwest")]
    RequestFailed(reqwest::Error),
    #[error("Checker function returned false")]
    ///Checker function returned false
    CheckerFalse,
    #[error("Content-Type was missing in response headers")]
    ///Content-Type was missing in response headers
    ContentTypeMissing,
    #[error(transparent)]
    #[cfg(feature = "reqwest")]
    ContentTypeParseFailed(ToStrError),
    #[error("Failed to parse mime type: {0}")]
    ///Failed to parse mime type
    InvalidMimeType(FromStrError),
}

impl InlineData {
    /// Creates a new InlineData.
    /// `data` must be a base64 encoded string.
    pub fn new(mime_type: Mime, data: String) -> Self {
        Self { mime_type, data }
    }

    #[cfg(feature = "reqwest")]
    pub async fn from_url_with_check<F: FnOnce(&HeaderMap) -> bool>(
        url: &str,
        checker: F,
    ) -> Result<Self, InlineDataError> {
        let response = reqwest::get(url)
            .await
            .map_err(|e| InlineDataError::RequestFailed(e))?;
        if !checker(response.headers()) {
            return Err(InlineDataError::CheckerFalse);
        }

        let mime_type = response
            .headers()
            .get("Content-Type")
            .ok_or(InlineDataError::ContentTypeMissing)?
            .to_str()
            .map_err(|e| InlineDataError::ContentTypeParseFailed(e))?;
        let mime_type =
            Mime::from_str(mime_type).map_err(|e| InlineDataError::InvalidMimeType(e))?;

        let body = response
            .bytes()
            .await
            .map_err(|e| InlineDataError::RequestFailed(e))?;

        Ok(InlineData::new(mime_type, STANDARD.encode(body)))
    }

    #[cfg(feature = "reqwest")]
    pub async fn from_url(url: &str) -> Result<Self, InlineDataError> {
        Self::from_url_with_check(url, |_| true).await
    }

    #[cfg(all(feature = "tokio", not(target_arch = "wasm32")))]
    pub async fn from_path(file_path: &str, mime_type: Mime) -> Result<Self, std::io::Error> {
        let data = tokio::fs::read(file_path).await?;
        Ok(InlineData::new(mime_type, STANDARD.encode(data)))
    }
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Language {
    ///Unspecified language. This value should not be used.
    LanguageUnspecified,
    ///Python >= 3.10, with numpy and simpy available.
    Python,
}

#[derive(Serialize, Deserialize, Clone, new, Getters, Debug)]
pub struct ExecutableCode {
    #[get = "pub"]
    language: Language,
    #[get = "pub"]
    code: String,
}

#[derive(Serialize, Deserialize, Clone, new, Getters, Debug)]
pub struct FunctionCall {
    #[get = "pub"]
    name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[get = "pub"]
    args: Option<Value>,
}

#[derive(Serialize, Deserialize, Clone, new, Getters, Debug)]
pub struct FunctionResponse {
    #[get = "pub"]
    name: String,
    #[get = "pub"]
    response: Value,
}

#[derive(Serialize, Deserialize, Clone, new, Getters, Debug)]
pub struct FileData {
    #[serde(skip_serializing_if = "Option::is_none", alias = "mimeType")]
    #[get = "pub"]
    mime_type: Option<String>,
    #[serde(alias = "fileUri")]
    #[get = "pub"]
    file_uri: String,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Outcome {
    /// Unspecified status. This value should not be used.
    OutcomeUnspecified,
    /// Code execution completed successfully.
    OutcomeOk,
    /// Code execution finished but with a failure. `stderr` should contain the reason.
    OutcomeFailed,
    /// Code execution ran for too long, and was cancelled.
    /// There may or may not be a partial output present.
    OutcomeDeadlineExceeded,
}

#[derive(Serialize, Deserialize, Clone, new, Getters, Debug)]
pub struct CodeExecutionResult {
    #[get = "pub"]
    outcome: Outcome,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[get = "pub"]
    output: Option<String>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub enum PartType {
    Text(String),
    ///Image or document like PDF
    InlineData(InlineData),
    ExecutableCode(ExecutableCode),
    CodeExecutionResult(CodeExecutionResult),
    FunctionCall(FunctionCall),
    FunctionResponse(FunctionResponse),
    ///For Audio file URL. Not allowed for images or PDFs, use InlineData instead.
    FileData(FileData),
}
#[derive(Serialize, Deserialize, Clone, Getters)]
#[serde(rename_all = "camelCase")]
pub struct Part {
    #[get = "pub"]
    #[serde(flatten)]
    data: PartType,
    #[get = "pub"]
    #[serde(skip_serializing_if = "Option::is_none")]
    thought: Option<bool>,
    #[get = "pub"]
    #[serde(skip_serializing_if = "Option::is_none")]
    thought_signature: Option<String>,
}
impl fmt::Debug for Part {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Part")
            .field("data", &self.data)
            .field("thought", &self.thought)
            .field(
                "thought_signature",
                &self
                    .thought_signature
                    .as_ref()
                    .map(|s| format!("{}..truncated", &s[..3])),
            )
            .finish()
    }
}
impl Part {
    pub fn is_thought(&self) -> bool {
        self.thought == Some(true)
    }
    pub fn new(data: PartType) -> Self {
        Self {
            data,
            thought: None,
            thought_signature: None,
        }
    }
    pub fn data_mut(&mut self) -> &mut PartType {
        &mut self.data
    }
}
impl From<PartType> for Part {
    fn from(value: PartType) -> Self {
        Self::new(value)
    }
}
impl From<String> for Part {
    fn from(value: String) -> Self {
        Self::new(PartType::Text(value))
    }
}
impl From<&str> for Part {
    fn from(value: &str) -> Self {
        Self::new(PartType::Text(value.into()))
    }
}
impl From<InlineData> for Part {
    fn from(value: InlineData) -> Self {
        Self::new(PartType::InlineData(value))
    }
}
impl From<ExecutableCode> for Part {
    fn from(value: ExecutableCode) -> Self {
        Self::new(PartType::ExecutableCode(value))
    }
}
impl From<CodeExecutionResult> for Part {
    fn from(value: CodeExecutionResult) -> Self {
        Self::new(PartType::CodeExecutionResult(value))
    }
}
impl From<FunctionCall> for Part {
    fn from(value: FunctionCall) -> Self {
        Self::new(PartType::FunctionCall(value))
    }
}
impl From<FunctionResponse> for Part {
    fn from(value: FunctionResponse) -> Self {
        Self::new(PartType::FunctionResponse(value))
    }
}
impl From<FileData> for Part {
    fn from(value: FileData) -> Self {
        Self::new(PartType::FileData(value))
    }
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
/// Supported thinking level by model [here](https://ai.google.dev/gemini-api/docs/gemini-3#thinking_level)
pub enum ThinkingLevel {
    ///Default value.
    #[default]
    ThinkingLevelUnspecified,
    ///Often no thinking
    Minimal,
    Low,
    Medium,
    High,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub enum ThinkingControl {
    /// Recommended for Gemini 3+.
    ThinkingLevel(ThinkingLevel),
    /// Indicates the thinking budget in tokens.
    /// Supported thinking budget by model [here](https://ai.google.dev/gemini-api/docs/thinking#set-budget)
    ThinkingBudget(i32),
}
impl From<ThinkingLevel> for ThinkingControl {
    fn from(value: ThinkingLevel) -> Self {
        Self::ThinkingLevel(value)
    }
}
impl From<u32> for ThinkingControl {
    fn from(value: u32) -> Self {
        Self::ThinkingBudget(value as i32)
    }
}

#[derive(Serialize, Deserialize, Clone, Getters, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ThinkingConfig {
    /// If true, thoughts are returned only if the model supports thought and thoughts are available.
    #[get = "pub"]
    include_thoughts: bool,
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    control: Option<ThinkingControl>,
}
impl ThinkingConfig {
    /// Supported thinking level by model [here](https://ai.google.dev/gemini-api/docs/gemini-3#thinking_level)
    /// Supported thinking budget by model [here](https://ai.google.dev/gemini-api/docs/thinking#set-budget)
    pub fn control(&self) -> Option<&ThinkingControl> {
        self.control.as_ref()
    }
    /// Read [here](https://ai.google.dev/gemini-api/docs/thinking#set-budget) for allowed range of
    /// `thinking_budget`
    pub fn new(include_thoughts: bool, control: impl Into<ThinkingControl>) -> Self {
        Self {
            include_thoughts,
            control: Some(control.into()),
        }
    }
    pub fn new_disable_thinking() -> Self {
        Self::new(false, 0)
    }
    pub fn new_dynamic_thinking(include_thoughts: bool) -> Self {
        Self {
            include_thoughts,
            control: Some(ThinkingControl::ThinkingBudget(-1)),
        }
    }
}
impl Default for ThinkingConfig {
    ///Thoughts are included but thinking budget depends on model's default by google.
    fn default() -> Self {
        Self {
            include_thoughts: true,
            control: None,
        }
    }
}

#[derive(Serialize, Deserialize, Getters, new, Debug, Clone)]
pub struct SystemInstruction {
    #[get = "pub"]
    parts: Vec<Part>,
}
impl From<String> for SystemInstruction {
    fn from(prompt: String) -> Self {
        Self {
            parts: vec![prompt.into()],
        }
    }
}
impl<'a> From<&'a str> for SystemInstruction {
    fn from(prompt: &'a str) -> Self {
        Self {
            parts: vec![prompt.into()],
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum HarmCategory {
    HarmCategoryHarassment,
    HarmCategoryHateSpeech,
    HarmCategorySexuallyExplicit,
    HarmCategoryDangerousContent,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BlockThreshold {
    BlockNone,
    BlockOnlyHigh,
    BlockMediumAndAbove,
    BlockLowAndAbove,
}
#[derive(Serialize, Deserialize, new, Getters, Debug, Clone)]
pub struct SafetySetting {
    #[get = "pub"]
    category: HarmCategory,
    #[get = "pub"]
    threshold: BlockThreshold,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ToolConfig {
    /// Configuration for function calling.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub function_calling_config: Option<FunctionCallingConfig>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct FunctionCallingConfig {
    /// The mode in which function calling should execute.
    /// Can be "AUTO", "ANY", or "NONE".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<FunctionCallingMode>,

    /// Optional: Only provide this if mode is "ANY".
    /// Restricts the model to only call specific functions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_function_names: Option<Vec<String>>,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FunctionCallingMode {
    /// Default model behavior. Model decides whether to predict a
    /// function call or a natural language response.
    Auto,
    /// Model is constrained to always predict a function call.
    Any,
    /// Model will not predict any function call.
    None,
}

#[derive(Serialize, new)]
#[serde(rename_all = "camelCase")]
pub struct GeminiRequestBody<'a> {
    system_instruction: Option<&'a SystemInstruction>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tools: Option<&'a [Tool]>,
    contents: &'a [&'a Chat],
    #[serde(skip_serializing_if = "Option::is_none")]
    generation_config: Option<&'a Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    safety_settings: Option<&'a [SafetySetting]>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_config: Option<&'a ToolConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    cached_content: Option<String>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub enum Tool {
    /// Generally it can be `Tool::GoogleSearch(json!({}))`
    GoogleSearch(Value),
    /// Recommended: write `#[gemini_function]` above the function and pass
    /// `vec![function_name::gemini_schema(), ..]`
    /// OR
    /// It must be of form `vec![`[functionDeclaration](https://ai.google.dev/gemini-api/docs/function-calling?example=meeting)`, ..]`
    FunctionDeclarations(Vec<Value>),
    /// Generally it can be `Tool::CodeExecution(json!({}))`
    /// AI will execute code to respond
    CodeExecution(Value),
    /// Generally it can be `Tool::UrlContext(json!({}))`
    /// Uses URL provided in prompt for context
    UrlContext(Value),
}

pub fn concatenate_parts(updating: &mut Vec<Part>, updator: &[Part]) {
    for updator_part in updator {
        if let Some(updating_last) = updating.last_mut() {
            match &updator_part.data {
                PartType::Text(updator_text) => {
                    if updating_last.is_thought() == updator_part.is_thought() {
                        if let PartType::Text(ref mut updating_text) = updating_last.data {
                            updating_text.push_str(&updator_text);
                            continue;
                        }
                    }
                }
                _ => {}
            }
        }
        updating.push(updator_part.clone());
    }
}