flyllm 0.4.1

A Rust library for unifying LLM backends as an abstraction layer with load balancing.
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
use crate::load_balancer::tasks::TaskDefinition;
use crate::providers::instances::{LlmInstance, BaseInstance};
use crate::providers::types::{LlmRequest, LlmResponse, LlmStream, StreamChunk, TokenUsage, Message};
use crate::errors::{LlmError, LlmResult};
use crate::constants;

use async_trait::async_trait;
use reqwest::header;
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use log::debug;
use futures::StreamExt;

/// Provider implementation for Google's Gemini AI models
pub struct GoogleInstance {
    base: BaseInstance,
}

/// Request structure for Google's Gemini API
#[derive(Serialize)]
struct GoogleGenerateContentRequest {
    contents: Vec<GoogleContent>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "generationConfig")]
    generation_config: Option<GoogleGenerationConfig>,
}

/// Content structure for Google's Gemini API messages
#[derive(Serialize, Deserialize)]
struct GoogleContent {
    role: String,
    parts: Vec<GooglePart>,
}

/// Individual content part for Google's Gemini API
#[derive(Serialize, Deserialize)]
struct GooglePart {
    text: String,
}

/// Generation configuration for Google's Gemini API
#[derive(Serialize, Default)] 
struct GoogleGenerationConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    temperature: Option<f32>,
    // #[serde(skip_serializing_if = "Option::is_none")]
    // top_k: Option<u32>,
    // #[serde(skip_serializing_if = "Option::is_none")]
    // top_p: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "maxOutputTokens")]
    max_output_tokens: Option<u32>,
    // #[serde(skip_serializing_if = "Option::is_none")]
    // stop_sequences: Option<Vec<String>>,
}

/// Response structure from Google's Gemini API
#[derive(Deserialize)]
struct GoogleGenerateContentResponse {
    candidates: Vec<GoogleCandidate>,
}

/// Individual candidate from Google's Gemini API response
#[derive(Deserialize)]
struct GoogleCandidate {
    content: GoogleContent,
    #[serde(rename = "tokenCount")]
    #[serde(default)]
    token_count: u32, // Note: Google provides total token count here
    // safety_ratings: Vec<SafetyRating>, // We don't use this currently
}

/// Streaming response structure from Google's Gemini API
#[derive(Deserialize)]
struct GoogleStreamChunk {
    candidates: Option<Vec<GoogleStreamCandidate>>,
}

/// Streaming candidate from Google's response
#[derive(Deserialize)]
struct GoogleStreamCandidate {
    content: Option<GoogleContent>,
    #[serde(rename = "finishReason")]
    finish_reason: Option<String>,
}


impl GoogleInstance {
    /// Creates a new Google provider instance
    ///
    /// # Parameters
    /// * `api_key` - Google API key
    /// * `model` - Default model to use (e.g. "gemini-pro")
    /// * `supported_tasks` - Map of tasks this provider supports
    /// * `enabled` - Whether this provider is enabled
    pub fn new(api_key: String, model: String, supported_tasks: HashMap<String, TaskDefinition>, enabled: bool) -> Self {
        let base = BaseInstance::new("google".to_string(), api_key, model, supported_tasks, enabled);
        Self { base }
    }

    /// Maps standard message format to Google's expected format
    ///
    /// This function handles several Google-specific requirements:
    /// - Converts "assistant" role to "model" role
    /// - Prepends system messages to the first user message
    /// - Validates that the first message is from the user
    ///
    /// # Parameters
    /// * `messages` - Array of messages in our standard format
    ///
    /// # Returns
    /// * `LlmResult<Vec<GoogleContent>>` - Mapped contents or an error
    fn map_messages_to_contents(messages: &[Message]) -> LlmResult<Vec<GoogleContent>> {
        let mut contents = Vec::new();
        let mut system_prompt: Option<String> = None;
        let mut first_user_message_index: Option<usize> = None;
        for (_, msg) in messages.iter().enumerate() {
             match msg.role.as_str() {
                 "system" => {
                     if system_prompt.is_some() {
                         return Err(LlmError::ApiError("Multiple system messages are not supported by Google provider mapping.".to_string()));
                     }
                     system_prompt = Some(msg.content.clone());
                 }
                 "user" | "model" | "assistant" => { 
                     let role = if msg.role == "assistant" { "model" } else { &msg.role };
                     if role == "user" && first_user_message_index.is_none() {
                        first_user_message_index = Some(contents.len()); 
                     }
                     contents.push(GoogleContent {
                         role: role.to_string(),
                         parts: vec![GooglePart { text: msg.content.clone() }],
                     });
                 }
                 _ => {
                     log::warn!("Ignoring message with unknown role: {}", msg.role);
                 }
             }
        }
        
        if let Some(sys_prompt) = &system_prompt {
            if let Some(user_idx) = first_user_message_index {
                if let Some(user_content) = contents.get_mut(user_idx) {
                    if let Some(part) = user_content.parts.get_mut(0) {
                        part.text = format!("{}\n\n{}", sys_prompt, part.text);
                    }
                } else {
                    return Err(LlmError::ApiError("System message provided but no user message found.".to_string()));
                }
            } else {
                return Err(LlmError::ApiError("System message provided but no user message found.".to_string()));
            }
        }
        
        if contents.is_empty() {
            return Err(LlmError::ApiError("No valid messages found for Google provider.".to_string()));
        }
        if contents[0].role != "user" {
             return Err(LlmError::ApiError(format!("Google chat must start with a 'user' role message, found '{}'.", contents[0].role)));
        }
        Ok(contents)
    }
}

#[async_trait]
impl LlmInstance for GoogleInstance {
    /// Generates a completion using Google's Gemini API
    ///
    /// # Parameters
    /// * `request` - The LLM request containing messages and parameters
    ///
    /// # Returns
    /// * `LlmResult<LlmResponse>` - The response from the model or an error
    async fn generate(&self, request: &LlmRequest) -> LlmResult<LlmResponse> {
        if !self.base.is_enabled() {
            return Err(LlmError::ProviderDisabled("Google".to_string()));
        }

        let model_name = self.base.model(); 
        let api_key = self.base.api_key();

        let url = format!(
            "{}/v1beta/models/{}:generateContent?key={}",
            constants::GOOGLE_API_ENDPOINT_PREFIX, 
            model_name,
            api_key
        );

        let mut headers = header::HeaderMap::new();
        headers.insert(
            header::CONTENT_TYPE,
            header::HeaderValue::from_static("application/json"),
        );

        let contents = Self::map_messages_to_contents(&request.messages)?;

        let mut generation_config = GoogleGenerationConfig::default();
        generation_config.temperature = request.temperature;
        generation_config.max_output_tokens = request.max_tokens;

        let google_request = GoogleGenerateContentRequest {
            contents,
            generation_config: Some(generation_config).filter(|gc| {
                gc.temperature.is_some() || gc.max_output_tokens.is_some()
            }),
        };

        let response = self.base.client()
            .post(&url)
            .headers(headers)
            .json(&google_request)
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status();
            let error_json: Result<serde_json::Value, _> = response.json().await;
             let error_details = match error_json {
                 Ok(json) => json.get("error")
                                .and_then(|e| e.get("message"))
                                .and_then(|m| m.as_str())
                                .map(|s| s.to_string())
                                .unwrap_or_else(|| format!("Unknown error structure: {}", json)),
                 Err(_) => "Failed to parse error response body".to_string(),
             };

            return Err(LlmError::ApiError(format!(
                "Google API error ({}): {}",
                status, error_details
            )));
        }

        let google_response: GoogleGenerateContentResponse = response.json().await
            .map_err(|e| LlmError::ApiError(format!("Failed to parse Google JSON response: {}", e)))?;


        if google_response.candidates.is_empty() {
            return Err(LlmError::ApiError("No candidates returned from Google. Content may have been blocked.".to_string()));
        }

        let candidate = &google_response.candidates[0];

        let combined_content = candidate.content.parts.iter()
            .map(|part| part.text.clone())
            .collect::<Vec<String>>()
            .join(""); 

        let usage = if candidate.token_count > 0 {
            // Simply use the token count as the total
            Some(TokenUsage {
                prompt_tokens: 0,
                completion_tokens: 0,
                total_tokens: candidate.token_count,
            })
        } else {
            None
        };

        debug!("Google usage: {:?}", usage);

        Ok(LlmResponse {
            content: combined_content,
            model: model_name.to_string(), 
            usage,
        })
    }

    async fn generate_stream(&self, request: &LlmRequest) -> LlmResult<LlmStream> {
        if !self.base.is_enabled() {
            return Err(LlmError::ProviderDisabled("Google".to_string()));
        }

        let model_name = self.base.model();
        let api_key = self.base.api_key();

        // Use streamGenerateContent endpoint for streaming
        let url = format!(
            "{}/v1beta/models/{}:streamGenerateContent?alt=sse&key={}",
            constants::GOOGLE_API_ENDPOINT_PREFIX,
            model_name,
            api_key
        );

        let mut headers = header::HeaderMap::new();
        headers.insert(
            header::CONTENT_TYPE,
            header::HeaderValue::from_static("application/json"),
        );

        let contents = Self::map_messages_to_contents(&request.messages)?;

        let mut generation_config = GoogleGenerationConfig::default();
        generation_config.temperature = request.temperature;
        generation_config.max_output_tokens = request.max_tokens;

        let google_request = GoogleGenerateContentRequest {
            contents,
            generation_config: Some(generation_config).filter(|gc| {
                gc.temperature.is_some() || gc.max_output_tokens.is_some()
            }),
        };

        let response = self.base.client()
            .post(&url)
            .headers(headers)
            .json(&google_request)
            .send()
            .await?;

        let response_status = response.status();

        if response_status.as_u16() == 429 {
            let error_text = response.text().await
                .unwrap_or_else(|_| "Rate limit exceeded".to_string());
            return Err(LlmError::RateLimit(format!("Google rate limit: {}", error_text)));
        }

        if !response_status.is_success() {
            let error_json: Result<serde_json::Value, _> = response.json().await;
            let error_details = match error_json {
                Ok(json) => json.get("error")
                    .and_then(|e| e.get("message"))
                    .and_then(|m| m.as_str())
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| format!("Unknown error: {}", json)),
                Err(_) => "Failed to parse error response".to_string(),
            };
            return Err(LlmError::ApiError(format!("Google API error ({}): {}", response_status, error_details)));
        }

        let byte_stream = response.bytes_stream();

        let chunk_stream = byte_stream
            .map(|result| result.map_err(|e| LlmError::RequestError(e)))
            .flat_map(|result| {
                match result {
                    Ok(bytes) => {
                        let text = String::from_utf8_lossy(&bytes);
                        let chunks: Vec<Result<StreamChunk, LlmError>> = text
                            .lines()
                            .filter_map(|line| {
                                let line = line.trim();
                                // Google SSE format: data: {...}
                                if line.starts_with("data: ") {
                                    let data = &line[6..];
                                    match serde_json::from_str::<GoogleStreamChunk>(data) {
                                        Ok(chunk) => {
                                            if let Some(candidates) = chunk.candidates {
                                                if let Some(candidate) = candidates.first() {
                                                    let is_final = candidate.finish_reason.is_some();
                                                    if let Some(content) = &candidate.content {
                                                        let text = content.parts.iter()
                                                            .map(|p| p.text.clone())
                                                            .collect::<Vec<_>>()
                                                            .join("");
                                                        return Some(Ok(StreamChunk {
                                                            content: text,
                                                            model: None,
                                                            is_final,
                                                            usage: None,
                                                        }));
                                                    }
                                                }
                                            }
                                            None
                                        }
                                        Err(e) => {
                                            // Skip parse errors for incomplete chunks
                                            debug!("Failed to parse Google streaming chunk: {}", e);
                                            None
                                        }
                                    }
                                } else {
                                    None
                                }
                            })
                            .collect();
                        futures::stream::iter(chunks)
                    }
                    Err(e) => futures::stream::iter(vec![Err(e)])
                }
            });

        Ok(Box::pin(chunk_stream))
    }

    fn supports_streaming(&self) -> bool {
        true
    }

    /// Returns provider name
    fn get_name(&self) -> &str {
        self.base.name()
    }

    /// Returns current model name
    fn get_model(&self) -> &str {
        self.base.model()
    }

    /// Returns supported tasks for this provider
    fn get_supported_tasks(&self) -> &HashMap<String, TaskDefinition> {
        &self.base.supported_tasks()
    }

    /// Returns whether this provider is enabled
    fn is_enabled(&self) -> bool {
        self.base.is_enabled()
    }
}