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
//! API handle for model-related operations.
use crate::error::Error;
use super::super::Client;
/// API handle for model-related operations.
#[ derive( Debug ) ]
pub struct ModelsApi< 'a >
{
pub( crate ) client : &'a Client,
}
impl ModelsApi< '_ >
{
/// Batch generate content for multiple requests.
///
/// This method allows you to send multiple content generation requests in a single API call,
/// improving efficiency when processing multiple inputs. Each request in the batch is processed
/// independently and returns its own response.
///
/// # Arguments
///
/// * `model_name` - The name of the model to use for generation
/// * `request` - The batch request containing multiple generation requests
///
/// # Returns
///
/// Returns a [`BatchGenerateContentResponse`] containing:
/// - `responses`: Vector of [`GenerateContentResponse`] objects, one for each input request
///
/// # Errors
///
/// This method returns an error in the following cases:
/// - [`Error::NetworkError`] - Network connectivity issues or request timeout
/// - [`Error::AuthenticationError`] - Invalid or missing API key
/// - [`Error::ServerError`] - Gemini API server-side errors (5xx status codes)
/// - [`Error::DeserializationError`] - Failed to parse the API response
/// - [`Error::ApiError`] - Other API-related errors
///
/// # Examples
///
/// ```rust,no_run
/// # use api_gemini::client::Client;
/// # use api_gemini::models::*;
/// # #[ tokio::main ]
/// # async fn main() -> Result< (), Box< dyn std::error::Error > > {
/// let client = Client::new()?;
/// let models_api = client.models();
///
/// // Create multiple generation requests
/// let requests = vec![
/// GenerateContentRequest {
/// contents : vec![Content {
/// role : "user".to_string(),
/// parts : vec![Part { text : Some("Explain AI".to_string()), ..Default::default() }],
/// }],
/// ..Default::default()
/// },
/// GenerateContentRequest {
/// contents : vec![Content {
/// role : "user".to_string(),
/// parts : vec![Part { text : Some("Explain ML".to_string()), ..Default::default() }],
/// }],
/// ..Default::default()
/// },
/// ];
///
/// let batch_request = BatchGenerateContentRequest { requests };
/// let response = models_api.batch_generate_content("gemini-2.5-flash", &batch_request).await?;
///
/// for (i, response) in response.responses.iter().enumerate() {
/// println!("Response {}: {:?}", i, response);
/// }
/// # Ok( () )
/// # }
/// ```
#[ inline ]
pub async fn batch_generate_content(
&self,
model_name : &str,
request : &crate::models::BatchGenerateContentRequest
) -> Result< crate::models::BatchGenerateContentResponse, Error >
{
let url = format!( "{}/v1beta/models/{model_name}:batchGenerateContent", self.client.base_url );
crate ::internal::http::enterprise::execute_with_optional_retries::< crate::models::BatchGenerateContentRequest, crate::models::BatchGenerateContentResponse >
(
self.client,
reqwest ::Method::POST,
&url,
&self.client.api_key,
Some( request ),
)
.await
}
/// Batch embed content for multiple requests.
///
/// This method allows you to generate embeddings for multiple pieces of content in a single API call,
/// improving efficiency when processing multiple texts. Each request in the batch is processed
/// independently and returns its own embedding.
///
/// # Arguments
///
/// * `model_name` - The name of the model to use for embeddings
/// * `request` - The batch request containing multiple embedding requests
///
/// # Returns
///
/// Returns a [`BatchEmbedContentsResponse`] containing:
/// - `embeddings`: Vector of [`ContentEmbedding`] objects, one for each input request
///
/// # Errors
///
/// This method returns an error in the following cases:
/// - [`Error::NetworkError`] - Network connectivity issues or request timeout
/// - [`Error::AuthenticationError`] - Invalid or missing API key
/// - [`Error::ServerError`] - Gemini API server-side errors (5xx status codes)
/// - [`Error::DeserializationError`] - Failed to parse the API response
/// - [`Error::ApiError`] - Other API-related errors
///
/// # Examples
///
/// ```rust,no_run
/// # use api_gemini::client::Client;
/// # use api_gemini::models::*;
/// # #[ tokio::main ]
/// # async fn main() -> Result< (), Box< dyn std::error::Error > > {
/// let client = Client::new()?;
/// let models_api = client.models();
///
/// // Create multiple embedding requests
/// let requests = vec![
/// EmbedContentRequest {
/// content : Content {
/// role : "user".to_string(),
/// parts : vec![Part { text : Some("Machine learning fundamentals".to_string()), ..Default::default() }],
/// },
/// ..Default::default()
/// },
/// EmbedContentRequest {
/// content : Content {
/// role : "user".to_string(),
/// parts : vec![Part { text : Some("Deep learning concepts".to_string()), ..Default::default() }],
/// },
/// ..Default::default()
/// },
/// ];
///
/// let batch_request = BatchEmbedContentsRequest { requests };
/// let response = models_api.batch_embed_contents("gemini-embedding-001", &batch_request).await?;
///
/// for (i, embedding) in response.embeddings.iter().enumerate() {
/// println!("Embedding {}: {} values", i, embedding.values.len());
/// }
/// # Ok( () )
/// # }
/// ```
#[ inline ]
pub async fn batch_embed_contents(
&self,
model_name : &str,
request : &crate::models::BatchEmbedContentsRequest
) -> Result< crate::models::BatchEmbedContentsResponse, Error >
{
let url = format!( "{}/v1beta/models/{model_name}:batchEmbedContents", self.client.base_url );
crate ::internal::http::enterprise::execute_with_optional_retries::< crate::models::BatchEmbedContentsRequest, crate::models::BatchEmbedContentsResponse >
(
self.client,
reqwest ::Method::POST,
&url,
&self.client.api_key,
Some( request ),
)
.await
}
/// Batch count tokens for multiple requests.
///
/// This method allows you to count tokens for multiple pieces of content in a single API call,
/// improving efficiency when analyzing token usage across multiple inputs. Each request in the batch
/// is processed independently and returns its own token count.
///
/// # Arguments
///
/// * `model_name` - The name of the model to use for token counting
/// * `request` - The batch request containing multiple token counting requests
///
/// # Returns
///
/// Returns a [`BatchCountTokensResponse`] containing:
/// - `responses`: Vector of [`CountTokensResponse`] objects, one for each input request
///
/// # Errors
///
/// This method returns an error in the following cases:
/// - [`Error::NetworkError`] - Network connectivity issues or request timeout
/// - [`Error::AuthenticationError`] - Invalid or missing API key
/// - [`Error::ServerError`] - Gemini API server-side errors (5xx status codes)
/// - [`Error::DeserializationError`] - Failed to parse the API response
/// - [`Error::ApiError`] - Other API-related errors
///
/// # Examples
///
/// ```rust,no_run
/// # use api_gemini::client::Client;
/// # use api_gemini::models::*;
/// # #[ tokio::main ]
/// # async fn main() -> Result< (), Box< dyn std::error::Error > > {
/// let client = Client::new()?;
/// let models_api = client.models();
///
/// // Create multiple token counting requests
/// let requests = vec![
/// CountTokensRequest {
/// contents : vec![Content {
/// role : "user".to_string(),
/// parts : vec![Part { text : Some("Explain machine learning".to_string()), ..Default::default() }],
/// }],
/// ..Default::default()
/// },
/// CountTokensRequest {
/// contents : vec![Content {
/// role : "user".to_string(),
/// parts : vec![Part { text : Some("What is deep learning?".to_string()), ..Default::default() }],
/// }],
/// ..Default::default()
/// },
/// ];
///
/// let batch_request = BatchCountTokensRequest { requests };
/// let response = models_api.batch_count_tokens("gemini-2.5-flash", &batch_request).await?;
///
/// for (i, response) in response.responses.iter().enumerate() {
/// println!("Request {}: {} tokens", i, response.total_tokens);
/// }
/// # Ok( () )
/// # }
/// ```
#[ inline ]
pub async fn batch_count_tokens(
&self,
model_name : &str,
request : &crate::models::BatchCountTokensRequest
) -> Result< crate::models::BatchCountTokensResponse, Error >
{
// Validate input parameters
if model_name.trim().is_empty()
{
return Err( Error::InvalidArgument( "Model name cannot be empty".to_string() ) );
}
// Validate the request structure
if let Err( validation_error ) = crate::validation::validate_batch_count_tokens_request( request )
{
return Err( Error::InvalidArgument( format!( "Invalid request : {validation_error}" ) ) );
}
let url = format!( "{}/v1beta/models/{model_name}:batchCountTokens", self.client.base_url );
crate ::internal::http::enterprise::execute_with_optional_retries::< crate::models::BatchCountTokensRequest, crate::models::BatchCountTokensResponse >
(
self.client,
reqwest ::Method::POST,
&url,
&self.client.api_key,
Some( request ),
)
.await
}
/// Analyze tokens with detailed breakdown and cost estimation.
///
/// This method provides enhanced token analysis including detailed breakdown by content type,
/// cost estimation, and optimization suggestions. It's useful for understanding token usage
/// patterns and estimating API costs.
///
/// # Arguments
///
/// * `model_name` - The name of the model to use for token analysis
/// * `request` - The analyze tokens request containing content and analysis options
///
/// # Returns
///
/// Returns an [`AnalyzeTokensResponse`] containing:
/// - `total_tokens`: Total token count across all content
/// - `breakdown`: Optional detailed breakdown by content type
/// - `cost_estimate`: Optional cost estimation based on token usage
/// - `optimization_suggestions`: Optional suggestions for reducing token usage
///
/// # Errors
///
/// This method returns an error in the following cases:
/// - [`Error::NetworkError`] - Network connectivity issues or request timeout
/// - [`Error::AuthenticationError`] - Invalid or missing API key
/// - [`Error::ServerError`] - Gemini API server-side errors (5xx status codes)
/// - [`Error::DeserializationError`] - Failed to parse the API response
/// - [`Error::ApiError`] - Other API-related errors
///
/// # Examples
///
/// ```rust,no_run
/// # use api_gemini::client::Client;
/// # use api_gemini::models::*;
/// # #[ tokio::main ]
/// # async fn main() -> Result< (), Box< dyn std::error::Error > > {
/// let client = Client::new()?;
/// let models_api = client.models();
///
/// let request = AnalyzeTokensRequest {
/// contents : vec![Content {
/// role : "user".to_string(),
/// parts : vec![Part { text : Some("Analyze this complex prompt with detailed explanations".to_string()), ..Default::default() }],
/// }],
/// generate_content_request : None,
/// include_breakdown : Some(true),
/// estimate_generation_tokens : Some(true),
/// };
///
/// let response = models_api.analyze_tokens("gemini-2.5-flash", &request).await?;
///
/// println!("Total tokens : {}", response.total_tokens);
/// if let Some(breakdown) = response.token_breakdown {
/// if let Some(text_tokens) = breakdown.text_tokens {
/// println!("Text tokens : {}", text_tokens);
/// }
/// if let Some(image_tokens) = breakdown.image_tokens {
/// println!("Image tokens : {}", image_tokens);
/// }
/// }
/// if let Some(cost) = response.cost_estimate {
/// if let Some(total) = cost.total_cost {
/// println!("Estimated cost : ${:.4}", total);
/// }
/// }
/// # Ok( () )
/// # }
/// ```
#[ inline ]
pub async fn analyze_tokens(
&self,
model_name : &str,
request : &crate::models::AnalyzeTokensRequest
) -> Result< crate::models::AnalyzeTokensResponse, Error >
{
// Validate input parameters
if model_name.trim().is_empty()
{
return Err( Error::InvalidArgument( "Model name cannot be empty".to_string() ) );
}
// Validate the request structure
if let Err( validation_error ) = crate::validation::validate_analyze_tokens_request( request )
{
return Err( Error::InvalidArgument( format!( "Invalid request : {validation_error}" ) ) );
}
let url = format!( "{}/v1beta/models/{model_name}:analyzeTokens", self.client.base_url );
crate ::internal::http::enterprise::execute_with_optional_retries::< crate::models::AnalyzeTokensRequest, crate::models::AnalyzeTokensResponse >
(
self.client,
reqwest ::Method::POST,
&url,
&self.client.api_key,
Some( request ),
)
.await
}
}