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
use super::error::GeminiResponseError;
use super::types::caching::{CachedContent, CachedContentList, CachedContentUpdate};
use super::types::request::*;
use super::types::response::*;
use super::types::sessions::Session;
use reqwest::Client;
use serde_json::{Value, json};
use std::time::Duration;

const BASE_URL: &str = "https://generativelanguage.googleapis.com/v1beta/models";

/// The main client for interacting with the Gemini API.
#[derive(Clone, Default, Debug)]
pub struct Gemini {
    client: Client,
    api_key: String,
    model: String,
    sys_prompt: Option<SystemInstruction>,
    generation_config: Option<Value>,
    safety_settings: Option<Vec<SafetySetting>>,
    tools: Option<Vec<Tool>>,
    tool_config: Option<ToolConfig>,
    cached_content: Option<String>,
}

impl Gemini {
    /// Creates a new `Gemini` client.
    ///
    /// # Arguments
    /// * `api_key` - Your Gemini API key. Get one from [Google AI studio](https://aistudio.google.com/app/apikey).
    /// * `model` - The model variation to use (e.g., "gemini-2.5-flash"). See [model variations](https://ai.google.dev/gemini-api/docs/models#model-variations).
    /// * `sys_prompt` - Optional system instructions. See [system instructions](https://ai.google.dev/gemini-api/docs/text-generation#image-input).
    pub fn new(
        api_key: impl Into<String>,
        model: impl Into<String>,
        sys_prompt: Option<SystemInstruction>,
    ) -> Self {
        Self {
            client: Client::builder()
                .timeout(Duration::from_secs(60))
                .build()
                .unwrap(),
            api_key: api_key.into(),
            model: model.into(),
            sys_prompt,
            generation_config: None,
            safety_settings: None,
            tools: None,
            tool_config: None,
            cached_content: None,
        }
    }
    /// Creates a new `Gemini` client with a custom API timeout.
    ///
    /// # Arguments
    /// * `api_key` - Your Gemini API key.
    /// * `model` - The model variation to use.
    /// * `sys_prompt` - Optional system instructions.
    /// * `api_timeout` - Custom duration for request timeouts.
    #[deprecated]
    pub fn new_with_timeout(
        api_key: impl Into<String>,
        model: impl Into<String>,
        sys_prompt: Option<SystemInstruction>,
        api_timeout: Duration,
    ) -> Self {
        Self {
            client: Client::builder().timeout(api_timeout).build().unwrap(),
            api_key: api_key.into(),
            model: model.into(),
            sys_prompt,
            generation_config: None,
            safety_settings: None,
            tools: None,
            tool_config: None,
            cached_content: None,
        }
    }
    /// Creates a new `Gemini` client with a custom API reqwest::Client.
    ///
    /// # Arguments
    /// * `api_key` - Your Gemini API key.
    /// * `model` - The model variation to use.
    /// * `sys_prompt` - Optional system instructions.
    /// * `client` - reqwest::Client to request gemini API.
    pub fn new_with_client(
        api_key: impl Into<String>,
        model: impl Into<String>,
        sys_prompt: Option<SystemInstruction>,
        client: Client,
    ) -> Self {
        Self {
            client,
            api_key: api_key.into(),
            model: model.into(),
            sys_prompt,
            generation_config: None,
            safety_settings: None,
            tools: None,
            tool_config: None,
            cached_content: None,
        }
    }
    /// Returns a mutable reference to the generation configuration.
    /// If not already set, initializes it to an empty object.
    ///
    /// See [Gemini docs](https://ai.google.dev/api/generate-content#generationconfig) for schema details.
    pub fn set_generation_config(&mut self) -> &mut Value {
        if let None = self.generation_config {
            self.generation_config = Some(json!({}));
        }
        self.generation_config.as_mut().unwrap()
    }
    pub fn set_tool_config(mut self, config: ToolConfig) -> Self {
        self.tool_config = Some(config);
        self
    }
    pub fn set_thinking_config(mut self, config: ThinkingConfig) -> Self {
        if let Value::Object(map) = self.set_generation_config() {
            if let Ok(thinking_value) = serde_json::to_value(config) {
                map.insert("thinking_config".to_string(), thinking_value);
            }
        }
        self
    }
    pub fn set_model(mut self, model: impl Into<String>) -> Self {
        self.model = model.into();
        self
    }
    /// # Warning
    /// Changing sys_prompt in middle of a conversation can confuse the model.
    pub fn set_sys_prompt(mut self, sys_prompt: Option<SystemInstruction>) -> Self {
        self.sys_prompt = sys_prompt;
        self
    }
    pub fn set_safety_settings(mut self, settings: Option<Vec<SafetySetting>>) -> Self {
        self.safety_settings = settings;
        self
    }
    pub fn set_api_key(mut self, api_key: impl Into<String>) -> Self {
        self.api_key = api_key.into();
        self
    }
    /// Sets the response format to JSON mode with a specific schema.
    ///
    /// To use a Rust struct as a schema, decorate it with `#[gemini_schema]` and pass
    /// `StructName::gemini_schema()`.
    ///
    /// # Arguments
    /// * `schema` - The JSON schema for the response. See [Gemini Schema docs](https://ai.google.dev/api/caching#Schema).
    pub fn set_json_mode(mut self, schema: Value) -> Self {
        let config = self.set_generation_config();
        config["response_mime_type"] = "application/json".into();
        config["response_schema"] = schema.into();
        self
    }
    pub fn remove_json_mode(mut self) -> Self {
        if let Some(ref mut generation_config) = self.generation_config {
            generation_config["response_schema"] = None::<Value>.into();
            generation_config["response_mime_type"] = None::<Value>.into();
        }
        self
    }
    /// Sets the tools (functions) available to the model.
    pub fn set_tools(mut self, tools: Vec<Tool>) -> Self {
        self.tools = Some(tools);
        self
    }
    /// Removes all tools.
    pub fn remove_tools(mut self) -> Self {
        self.tools = None;
        self
    }
    pub fn set_cached_content(mut self, name: impl Into<String>) -> Self {
        self.cached_content = Some(name.into());
        self
    }
    pub fn remove_cached_content(mut self) -> Self {
        self.cached_content = None;
        self
    }

    // Cache management methods

    pub async fn create_cache(
        &self,
        cached_content: &CachedContent,
    ) -> Result<CachedContent, GeminiResponseError> {
        let req_url = format!(
            "https://generativelanguage.googleapis.com/v1beta/cachedContents?key={}",
            self.api_key
        );

        let response = self
            .client
            .post(req_url)
            .json(cached_content)
            .send()
            .await
            .map_err(|e| GeminiResponseError::ReqwestError(e))?;

        if !response.status().is_success() {
            let error = response
                .json()
                .await
                .map_err(|e| GeminiResponseError::ReqwestError(e))?;
            return Err(GeminiResponseError::StatusNotOk(error));
        }

        let cached_content: CachedContent = response
            .json()
            .await
            .map_err(|e| GeminiResponseError::ReqwestError(e))?;
        Ok(cached_content)
    }

    pub async fn list_caches(&self) -> Result<CachedContentList, GeminiResponseError> {
        let req_url = format!(
            "https://generativelanguage.googleapis.com/v1beta/cachedContents?key={}",
            self.api_key
        );

        let response = self
            .client
            .get(req_url)
            .send()
            .await
            .map_err(|e| GeminiResponseError::ReqwestError(e))?;

        if !response.status().is_success() {
            let error = response
                .json()
                .await
                .map_err(|e| GeminiResponseError::ReqwestError(e))?;
            return Err(GeminiResponseError::StatusNotOk(error));
        }

        let list: CachedContentList = response
            .json()
            .await
            .map_err(|e| GeminiResponseError::ReqwestError(e))?;
        Ok(list)
    }

    pub async fn get_cache(&self, name: &str) -> Result<CachedContent, GeminiResponseError> {
        let req_url = format!(
            "https://generativelanguage.googleapis.com/v1beta/{}?key={}",
            name, self.api_key
        );

        let response = self
            .client
            .get(req_url)
            .send()
            .await
            .map_err(|e| GeminiResponseError::ReqwestError(e))?;

        if !response.status().is_success() {
            let error = response
                .json()
                .await
                .map_err(|e| GeminiResponseError::ReqwestError(e))?;
            return Err(GeminiResponseError::StatusNotOk(error));
        }

        let cached_content: CachedContent = response
            .json()
            .await
            .map_err(|e| GeminiResponseError::ReqwestError(e))?;
        Ok(cached_content)
    }

    pub async fn update_cache(
        &self,
        name: &str,
        update: &CachedContentUpdate,
    ) -> Result<CachedContent, GeminiResponseError> {
        let req_url = format!(
            "https://generativelanguage.googleapis.com/v1beta/{}?key={}",
            name, self.api_key
        );

        let response = self
            .client
            .patch(req_url)
            .json(update)
            .send()
            .await
            .map_err(|e| GeminiResponseError::ReqwestError(e))?;

        if !response.status().is_success() {
            let error = response
                .json()
                .await
                .map_err(|e| GeminiResponseError::ReqwestError(e))?;
            return Err(GeminiResponseError::StatusNotOk(error));
        }

        let cached_content: CachedContent = response
            .json()
            .await
            .map_err(|e| GeminiResponseError::ReqwestError(e))?;
        Ok(cached_content)
    }

    pub async fn delete_cache(&self, name: &str) -> Result<(), GeminiResponseError> {
        let req_url = format!(
            "https://generativelanguage.googleapis.com/v1beta/{}?key={}",
            name, self.api_key
        );

        let response = self
            .client
            .delete(req_url)
            .send()
            .await
            .map_err(|e| GeminiResponseError::ReqwestError(e))?;

        if !response.status().is_success() {
            let error = response
                .json()
                .await
                .map_err(|e| GeminiResponseError::ReqwestError(e))?;
            return Err(GeminiResponseError::StatusNotOk(error));
        }

        Ok(())
    }

    /// Sends a prompt to the model and waits for the full response.
    ///
    /// Updates the `session` history with the model's reply.
    ///
    /// # Errors
    /// Returns `GeminiResponseError::NothingToRespond` if the last message in history is from the model.
    pub async fn ask(&self, session: &mut Session) -> Result<GeminiResponse, GeminiResponseError> {
        if session
            .get_last_chat()
            .is_some_and(|chat| *chat.role() == Role::Model)
        {
            return Err(GeminiResponseError::NothingToRespond);
        }
        let req_url = format!(
            "{BASE_URL}/{}:generateContent?key={}",
            self.model, self.api_key
        );

        let response = self
            .client
            .post(req_url)
            .json(&GeminiRequestBody::new(
                self.sys_prompt.as_ref(),
                self.tools.as_deref(),
                &session.get_history().as_slice(),
                self.generation_config.as_ref(),
                self.safety_settings.as_deref(),
                self.tool_config.as_ref(),
                self.cached_content.clone(),
            ))
            .send()
            .await
            .map_err(|e| GeminiResponseError::ReqwestError(e))?;

        if !response.status().is_success() {
            let error = response
                .json()
                .await
                .map_err(|e| GeminiResponseError::ReqwestError(e))?;
            return Err(GeminiResponseError::StatusNotOk(error));
        }

        let reply = GeminiResponse::new(response)
            .await
            .map_err(|e| GeminiResponseError::ReqwestError(e))?;
        session.update(&reply);
        Ok(reply)
    }
    /// # Warning
    /// You must read the response stream to get reply stored context in `session`.
    /// `data_extractor` is used to extract data that you get as a stream of futures.
    /// # Example
    ///```ignore
    ///use futures::StreamExt
    ///let mut response_stream = gemini.ask_as_stream_with_extractor(session,
    ///     |session, _gemini_response| session.get_last_chat().unwrap().get_text_no_think("\n"))
    ///    .await.unwrap(); // Use _gemini_response.get_text("") to just get the text received in every chunk
    ///while let Some(response) = response_stream.next().await {
    ///    println!("{}", response);
    ///}
    ///```
    pub async fn ask_as_stream_with_extractor<F, StreamType>(
        &self,
        session: Session,
        data_extractor: F,
    ) -> Result<ResponseStream<F, StreamType>, (Session, GeminiResponseError)>
    where
        F: FnMut(&Session, GeminiResponse) -> StreamType,
    {
        if session
            .get_last_chat()
            .is_some_and(|chat| *chat.role() == Role::Model)
        {
            return Err((session, GeminiResponseError::NothingToRespond));
        }
        let req_url = format!(
            "{BASE_URL}/{}:streamGenerateContent?alt=sse&key={}",
            self.model, self.api_key
        );

        let request = self
            .client
            .post(req_url)
            .json(&GeminiRequestBody::new(
                self.sys_prompt.as_ref(),
                self.tools.as_deref(),
                session.get_history().as_slice(),
                self.generation_config.as_ref(),
                self.safety_settings.as_deref(),
                self.tool_config.as_ref(),
                self.cached_content.clone(),
            ))
            .send()
            .await;
        let response = match request {
            Ok(response) => response,
            Err(e) => return Err((session, GeminiResponseError::ReqwestError(e))),
        };

        if !response.status().is_success() {
            let error = match response.json().await {
                Ok(response) => response,
                Err(e) => return Err((session, GeminiResponseError::ReqwestError(e))),
            };
            return Err((session, GeminiResponseError::StatusNotOk(error)));
        }

        Ok(ResponseStream::new(
            Box::new(response.bytes_stream()),
            session,
            data_extractor,
        ))
    }
    /// Sends a prompt to the model and returns a stream of responses.
    ///
    /// # Warning
    /// You must exhaust the response stream to ensure the `session` history is correctly updated.
    ///
    /// # Example
    /// ```no_run
    /// use futures::StreamExt;
    /// # async fn run(gemini: gemini_client_api::gemini::ask::Gemini, session: gemini_client_api::gemini::types::sessions::Session) {
    /// let mut response_stream = gemini.ask_as_stream(session).await.unwrap();
    ///
    /// while let Some(response) = response_stream.next().await {
    ///     if let Ok(response) = response {
    ///         println!("{}", response.get_chat().get_text_no_think("\n"));
    ///     }
    /// }
    /// # }
    /// ```
    pub async fn ask_as_stream(
        &self,
        session: Session,
    ) -> Result<GeminiResponseStream, (Session, GeminiResponseError)> {
        self.ask_as_stream_with_extractor(
            session,
            (|_, gemini_response| gemini_response)
                as fn(&Session, GeminiResponse) -> GeminiResponse,
        )
        .await
    }
}