api_gemini 0.5.0

Gemini's API for accessing large language models (LLMs).
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
491
492
493
494
495
496
497
# Usage Examples

This document contains comprehensive usage examples for the api_gemini crate.

## Text Generation

```rust,no_run
use api_gemini::{ client::Client, models::* };

#[tokio::main]
async fn main() -> Result< (), Box< dyn std::error::Error > >
{
  let client = Client::new()?;

  let request = GenerateContentRequest
  {
    contents: vec!
    [
      Content
      {
        parts: vec!
        [
          Part
          {
            text: Some( "Explain quantum computing in simple terms".to_string() ),
            ..Default::default()
          }
        ],
        role: "user".to_string(),
      }
    ],
    generation_config: Some
    (
      GenerationConfig
      {
        temperature: Some( 0.7 ),
        top_k: Some( 40 ),
        top_p: Some( 0.95 ),
        max_output_tokens: Some( 1024 ),
        ..Default::default()
      }
    ),
    ..Default::default()
  };

  let response = client
    .models()
    .by_name( "gemini-1.5-pro-latest" )
    .generate_content( &request )
    .await?;
  Ok( () )
}
```

## Multi-turn Conversations

```rust,no_run
use api_gemini::{ client::Client, models::* };

#[tokio::main]
async fn main() -> Result< (), Box< dyn std::error::Error > >
{
  let client = Client::new()?;

  let conversation = vec!
  [
    Content
    {
      role: "user".to_string(),
      parts: vec![ Part { text: Some( "What is the capital of France?".to_string() ), ..Default::default() } ],
    },
    Content
    {
      role: "model".to_string(),
      parts: vec![ Part { text: Some( "The capital of France is Paris.".to_string() ), ..Default::default() } ],
    },
    Content
    {
      role: "user".to_string(),
      parts: vec![ Part { text: Some( "What's the population?".to_string() ), ..Default::default() } ],
    },
  ];

  let request = GenerateContentRequest { contents: conversation, ..Default::default() };
  Ok( () )
}
```

## Vision (Multimodal)

```rust,no_run
use api_gemini::{ client::Client, models::* };
use base64::Engine;

#[tokio::main]
async fn main() -> Result< (), Box< dyn std::error::Error > >
{
  let client = Client::new()?;

  let image_data = std::fs::read( "image.jpg" )?;
  let base64_image = base64::engine::general_purpose::STANDARD.encode( image_data );

  let request = GenerateContentRequest
  {
    contents: vec!
    [
      Content
      {
        parts: vec!
        [
          Part { text: Some( "What's in this image?".to_string() ), ..Default::default() },
          Part { inline_data: Some( Blob { mime_type: "image/jpeg".to_string(), data: base64_image } ), ..Default::default() },
        ],
        role: "user".to_string(),
      }
    ],
    ..Default::default()
  };
  Ok( () )
}
```

## Function Calling

```rust,no_run
use api_gemini::{ client::Client, models::* };
use serde_json::json;

#[tokio::main]
async fn main() -> Result< (), Box< dyn std::error::Error > >
{
  let client = Client::new()?;

  let tools = vec!
  [
    Tool
    {
      function_declarations: Some
      (
        vec!
        [
          FunctionDeclaration
          {
            name: "get_weather".to_string(),
            description: "Get weather in a location".to_string(),
            parameters: Some
            (
              json!
              (
                {
                  "type": "object",
                  "properties": { "location": { "type": "string", "description": "City name" } },
                  "required": ["location"]
                }
              )
            ),
          }
        ]
      ),
      code_execution: None,
      google_search_retrieval: None,
      code_execution_tool: None,
    }
  ];

  let request = GenerateContentRequest
  {
    contents: vec!
    [
      Content
      {
        parts: vec![ Part { text: Some( "What's the weather in Tokyo?".to_string() ), ..Default::default() } ],
        role: "user".to_string(),
      }
    ],
    tools: Some( tools ),
    ..Default::default()
  };
  Ok( () )
}
```

## Google Search Grounding

Real-time web search integration with attribution:

```rust,no_run
use api_gemini::{ client::Client, models::* };

#[tokio::main]
async fn main() -> Result< (), Box< dyn std::error::Error > >
{
  let client = Client::new()?;

  let tools = vec!
  [
    Tool
    {
      function_declarations: None,
      code_execution: None,
      google_search_retrieval: Some( GoogleSearchTool { config: None } ),
      code_execution_tool: None,
    }
  ];

  let request = GenerateContentRequest
  {
    contents: vec!
    [
      Content
      {
        parts: vec![ Part { text: Some( "What are the latest developments in AI technology?".to_string() ), ..Default::default() } ],
        role: "user".to_string(),
      }
    ],
    tools: Some( tools ),
    ..Default::default()
  };

  let response = client.models().by_name( "gemini-2.5-flash" ).generate_content( &request ).await?;

  // Check for grounding metadata and citations
  if let Some( grounding_metadata ) = &response.grounding_metadata
  {
    if let Some( grounding_chunks ) = &grounding_metadata.grounding_chunks
    {
      println!( "Sources used:" );
      for chunk in grounding_chunks
      {
        if let Some( uri ) = &chunk.uri { println!( "  - {}", uri ); }
      }
    }
  }
  Ok( () )
}
```

## System Instructions

```rust,no_run
use api_gemini::{ client::Client, models::* };

#[tokio::main]
async fn main() -> Result< (), Box< dyn std::error::Error > >
{
  let client = Client::new()?;

  let system_instruction = SystemInstruction
  {
    role: "system".to_string(),
    parts: vec!
    [
      Part
      {
        text: Some( "You are a helpful technical assistant. Always provide code examples.".to_string() ),
        ..Default::default()
      }
    ],
  };

  let request = GenerateContentRequest
  {
    contents: vec!
    [
      Content
      {
        parts: vec![ Part { text: Some( "How do I implement error handling in Rust?".to_string() ), ..Default::default() } ],
        role: "user".to_string(),
      }
    ],
    system_instruction: Some( system_instruction ),
    ..Default::default()
  };

  let response = client.models().by_name( "gemini-2.5-flash" ).generate_content( &request ).await?;
  Ok( () )
}
```

## Code Execution

```rust,no_run
use api_gemini::{ client::Client, models::* };

#[tokio::main]
async fn main() -> Result< (), Box< dyn std::error::Error > >
{
  let client = Client::new()?;

  let code_execution_tool = CodeExecutionTool
  {
    config: Some
    (
      CodeExecutionConfig
      {
        timeout: Some( 30 ),
        enable_network: Some( false ),
      }
    ),
  };

  let tools = vec!
  [
    Tool
    {
      function_declarations: None,
      code_execution: None,
      google_search_retrieval: None,
      code_execution_tool: Some( code_execution_tool ),
    }
  ];

  let request = GenerateContentRequest
  {
    contents: vec!
    [
      Content
      {
        parts: vec![ Part { text: Some( "Calculate the factorial of 10 using Python".to_string() ), ..Default::default() } ],
        role: "user".to_string(),
      }
    ],
    tools: Some( tools ),
    ..Default::default()
  };

  let response = client.models().by_name( "gemini-2.5-flash" ).generate_content( &request ).await?;
  Ok( () )
}
```

## Embeddings

```rust,no_run
use api_gemini::{ client::Client, models::* };

#[tokio::main]
async fn main() -> Result< (), Box< dyn std::error::Error > >
{
  let client = Client::new()?;

  let embed_request = EmbedContentRequest
  {
    content: Content
    {
      parts: vec![ Part { text: Some( "The quick brown fox".to_string() ), ..Default::default() } ],
      role: "user".to_string(),
    },
    task_type: Some( "RETRIEVAL_DOCUMENT".to_string() ),
    title: None,
    output_dimensionality: None,
  };

  let response = client.models().by_name( "models/text-embedding-004" ).embed_content( &embed_request ).await?;
  println!( "Embedding dimensions: {}", response.embedding.values.len() );
  Ok( () )
}
```

## Model Information

```rust,no_run
use api_gemini::{ client::Client, models::* };

#[tokio::main]
async fn main() -> Result< (), Box< dyn std::error::Error > >
{
  let client = Client::new()?;

  // List available models
  let models = client.models().list().await?;
  for model in models.models
  {
    println!( "Model: {}", model.name );
  }

  // Get specific model details
  let model = client.models().get( "models/gemini-1.5-pro-latest" ).await?;
  println!( "Token limit: {:?}", model.input_token_limit );
  Ok( () )
}
```

## Synchronous API

```rust,no_run
use api_gemini::{ client::Client, models::* };
use std::time::Duration;

fn main() -> Result< (), Box< dyn std::error::Error > >
{
  let sync_client = Client::sync_builder()
    .api_key( "your-api-key".to_string() )
    .timeout( Duration::from_secs( 30 ) )
    .build()?;

  let request = GenerateContentRequest
  {
    contents: vec!
    [
      Content
      {
        parts: vec![ Part { text: Some( "Hello, Gemini!".to_string() ), ..Default::default() } ],
        role: "user".to_string(),
      }
    ],
    ..Default::default()
  };

  let response = sync_client.models().by_name( "gemini-1.5-pro-latest" )?.generate_content( &request )?;

  if let Some( text ) = response.candidates.first()
    .and_then( |c| c.content.parts.first() )
    .and_then( |p| p.text.as_ref() )
  {
    println!( "Response: {}", text );
  }
  Ok( () )
}
```

## Safety Settings

```rust,no_run
use api_gemini::{ client::Client, models::* };

let safety_settings = vec!
[
  SafetySetting
  {
    category: HarmCategory::HarmCategoryHarassment,
    threshold: HarmBlockThreshold::BlockMediumAndAbove,
  },
  SafetySetting
  {
    category: HarmCategory::HarmCategoryHateSpeech,
    threshold: HarmBlockThreshold::BlockOnlyHigh,
  },
];

let request = GenerateContentRequest
{
  safety_settings: Some( safety_settings ),
  ..Default::default()
};
```

## Server-side Cached Content

```rust,no_run
use api_gemini::{ client::Client, models::* };

#[tokio::main]
async fn main() -> Result< (), Box< dyn std::error::Error > >
{
  let client = Client::new()?;

  let cache_request = CreateCachedContentRequest
  {
    model: "gemini-1.5-pro-latest".to_string(),
    contents: vec![/* conversation context */],
    ttl: Some( "3600s".to_string() ),
    expire_time: None,
    display_name: Some( "My Conversation Cache".to_string() ),
    system_instruction: Some
    (
      Content
      {
        parts: vec![ Part { text: Some( "You are a helpful assistant".to_string() ), ..Default::default() } ],
        role: "system".to_string(),
      }
    ),
    tools: None,
    tool_config: None,
  };

  let cache = client.cached_content().create( &cache_request ).await?;
  println!( "Created cache: {}", cache.name );

  // Use cached content in conversations
  let request = GenerateContentRequest
  {
    contents: vec![/* new messages only */],
    cached_content: Some( cache.name ),
    ..Default::default()
  };

  let response = client.models().by_name( "gemini-1.5-pro-latest" ).generate_content( &request ).await?;
  Ok( () )
}
```

## Related Documentation

- **[Cookbook]cookbook.md** - Recipe patterns for common use cases
- **[Testing]testing.md** - Test organization and coverage
- **[API Coverage]api_coverage.md** - Complete API endpoint documentation