coderlib 0.1.0

A Rust library for AI-powered code assistance and agentic system
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
498
499
500
501
502
503
504
505
506
507
//! Google Cloud Vertex AI provider implementation for CoderLib
//!
//! This module provides integration with Google Cloud Vertex AI, supporting
//! Gemini models and other Google AI models through the Vertex AI platform.

use async_trait::async_trait;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;

use crate::core::error::ProviderError;
use crate::core::TokenUsage;
use crate::llm::{Provider, ProviderEvent, ProviderResponse, Model};
use crate::storage::{Message, MessageRole};
use crate::tools::Tool;

/// Google Cloud Vertex AI provider
pub struct VertexProvider {
    client: Client,
    project_id: String,
    location: String,
    access_token: String,
    model: Model,
    max_tokens: Option<u32>,
    temperature: Option<f32>,
}

/// Vertex AI request format
#[derive(Debug, Serialize)]
struct VertexRequest {
    contents: Vec<VertexContent>,
    #[serde(skip_serializing_if = "Option::is_none")]
    generation_config: Option<VertexGenerationConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    safety_settings: Option<Vec<VertexSafetySetting>>,
}

/// Vertex AI content
#[derive(Debug, Serialize)]
struct VertexContent {
    role: String,
    parts: Vec<VertexPart>,
}

/// Vertex AI content part
#[derive(Debug, Serialize)]
struct VertexPart {
    text: String,
}

/// Vertex AI generation configuration
#[derive(Debug, Serialize)]
struct VertexGenerationConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_output_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    top_p: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    top_k: Option<u32>,
}

/// Vertex AI safety setting
#[derive(Debug, Serialize)]
struct VertexSafetySetting {
    category: String,
    threshold: String,
}

/// Vertex AI response format
#[derive(Debug, Deserialize)]
struct VertexResponse {
    candidates: Vec<VertexCandidate>,
    #[serde(rename = "usageMetadata")]
    usage_metadata: Option<VertexUsageMetadata>,
}

/// Vertex AI candidate
#[derive(Debug, Deserialize)]
struct VertexCandidate {
    content: VertexResponseContent,
    #[serde(rename = "finishReason")]
    finish_reason: Option<String>,
}

/// Vertex AI response content
#[derive(Debug, Deserialize)]
struct VertexResponseContent {
    parts: Vec<VertexResponsePart>,
    role: String,
}

/// Vertex AI response part
#[derive(Debug, Deserialize)]
struct VertexResponsePart {
    text: Option<String>,
}

/// Vertex AI usage metadata
#[derive(Debug, Deserialize)]
struct VertexUsageMetadata {
    #[serde(rename = "promptTokenCount")]
    prompt_token_count: Option<u32>,
    #[serde(rename = "candidatesTokenCount")]
    candidates_token_count: Option<u32>,
    #[serde(rename = "totalTokenCount")]
    total_token_count: Option<u32>,
}

impl VertexProvider {
    /// Create a new Vertex AI provider
    pub fn new(
        project_id: String,
        location: String,
        access_token: String,
        model: Model,
        max_tokens: Option<u32>,
        temperature: Option<f32>,
    ) -> Result<Self, ProviderError> {
        let client = Client::builder()
            .timeout(std::time::Duration::from_secs(120))
            .build()
            .map_err(|e| ProviderError::Configuration(format!("Failed to create HTTP client: {}", e)))?;
        
        Ok(Self {
            client,
            project_id,
            location,
            access_token,
            model,
            max_tokens,
            temperature,
        })
    }
    
    /// Get the API endpoint URL
    fn get_api_url(&self) -> String {
        format!(
            "https://{}-aiplatform.googleapis.com/v1/projects/{}/locations/{}/publishers/google/models/{}:generateContent",
            self.location, self.project_id, self.location, self.model.id
        )
    }
    
    /// Get the streaming API endpoint URL
    fn get_streaming_api_url(&self) -> String {
        format!(
            "https://{}-aiplatform.googleapis.com/v1/projects/{}/locations/{}/publishers/google/models/{}:streamGenerateContent",
            self.location, self.project_id, self.location, self.model.id
        )
    }
    
    /// Convert CoderLib messages to Vertex format
    fn convert_messages(&self, messages: Vec<Message>) -> Vec<VertexContent> {
        messages
            .into_iter()
            .filter_map(|msg| {
                // Vertex AI uses "user" and "model" roles
                let role = match msg.role {
                    MessageRole::User => "user",
                    MessageRole::Assistant => "model",
                    MessageRole::System => "user", // System messages are treated as user messages
                    MessageRole::Tool => return None, // Skip tool messages for now
                };

                Some(VertexContent {
                    role: role.to_string(),
                    parts: vec![VertexPart {
                        text: msg.content.as_text(),
                    }],
                })
            })
            .collect()
    }
    
    /// Create request payload
    fn create_request(&self, messages: Vec<Message>) -> VertexRequest {
        let generation_config = if self.max_tokens.is_some() || self.temperature.is_some() {
            Some(VertexGenerationConfig {
                temperature: self.temperature,
                max_output_tokens: self.max_tokens,
                top_p: None,
                top_k: None,
            })
        } else {
            None
        };
        
        // Default safety settings (permissive for development)
        let safety_settings = Some(vec![
            VertexSafetySetting {
                category: "HARM_CATEGORY_HARASSMENT".to_string(),
                threshold: "BLOCK_MEDIUM_AND_ABOVE".to_string(),
            },
            VertexSafetySetting {
                category: "HARM_CATEGORY_HATE_SPEECH".to_string(),
                threshold: "BLOCK_MEDIUM_AND_ABOVE".to_string(),
            },
            VertexSafetySetting {
                category: "HARM_CATEGORY_SEXUALLY_EXPLICIT".to_string(),
                threshold: "BLOCK_MEDIUM_AND_ABOVE".to_string(),
            },
            VertexSafetySetting {
                category: "HARM_CATEGORY_DANGEROUS_CONTENT".to_string(),
                threshold: "BLOCK_MEDIUM_AND_ABOVE".to_string(),
            },
        ]);
        
        VertexRequest {
            contents: self.convert_messages(messages),
            generation_config,
            safety_settings,
        }
    }
    
    /// Parse response
    fn parse_response(&self, response: VertexResponse) -> Result<ProviderResponse, ProviderError> {
        let candidate = response.candidates
            .into_iter()
            .next()
            .ok_or_else(|| ProviderError::ResponseParsing("No candidates in response".to_string()))?;
        
        let content = candidate.content.parts
            .into_iter()
            .filter_map(|part| part.text)
            .collect::<Vec<_>>()
            .join("");
        
        let token_usage = response.usage_metadata.map(|usage| TokenUsage {
            input_tokens: usage.prompt_token_count.unwrap_or(0),
            output_tokens: usage.candidates_token_count.unwrap_or(0),
            total_tokens: usage.prompt_token_count.unwrap_or(0) + usage.candidates_token_count.unwrap_or(0),
            cache_creation_tokens: 0,
            cache_read_tokens: 0,
        });
        
        Ok(ProviderResponse {
            content,
            tool_calls: Vec::new(), // TODO: Implement tool calls for Vertex AI
            token_usage,
            metadata: serde_json::json!({
                "finish_reason": candidate.finish_reason,
                "model": self.model.id,
                "provider": "vertex",
                "project_id": self.project_id,
                "location": self.location
            }),
        })
    }
}

#[async_trait]
impl Provider for VertexProvider {
    async fn send_messages(
        &self,
        messages: Vec<Message>,
        _tools: Vec<Box<dyn Tool>>,
    ) -> Result<ProviderResponse, ProviderError> {
        let request = self.create_request(messages);
        
        let response = self.client
            .post(&self.get_api_url())
            .header("Authorization", format!("Bearer {}", self.access_token))
            .header("Content-Type", "application/json")
            .json(&request)
            .send()
            .await
            .map_err(|e| ProviderError::Http(e))?;
        
        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            return Err(ProviderError::ApiError(format!(
                "Vertex AI error {}: {}", status, error_text
            )));
        }
        
        let vertex_response: VertexResponse = response.json().await
            .map_err(|e| ProviderError::ResponseParsing(format!("Failed to parse Vertex AI response: {}", e)))?;
        
        self.parse_response(vertex_response)
    }
    
    async fn stream_response(
        &self,
        messages: Vec<Message>,
        _tools: Vec<Box<dyn Tool>>,
    ) -> Result<mpsc::Receiver<Result<ProviderEvent, ProviderError>>, ProviderError> {
        let (tx, rx) = mpsc::channel(100);
        
        let request = self.create_request(messages);
        let client = self.client.clone();
        let url = self.get_streaming_api_url();
        let access_token = self.access_token.clone();
        
        tokio::spawn(async move {
            let response_result = client
                .post(&url)
                .header("Authorization", format!("Bearer {}", access_token))
                .header("Content-Type", "application/json")
                .json(&request)
                .send()
                .await;
            
            match response_result {
                Ok(response) => {
                    if !response.status().is_success() {
                        let status = response.status();
                        let error_text = response.text().await.unwrap_or_default();
                        let _ = tx.send(Err(ProviderError::ApiError(format!(
                            "Vertex AI error {}: {}", status, error_text
                        )))).await;
                        return;
                    }
                    
                    // Vertex AI streaming uses newline-delimited JSON
                    let text = response.text().await.unwrap_or_default();
                    
                    for line in text.lines() {
                        if line.trim().is_empty() {
                            continue;
                        }
                        
                        if let Ok(chunk) = serde_json::from_str::<VertexResponse>(line) {
                            if let Some(candidate) = chunk.candidates.first() {
                                for part in &candidate.content.parts {
                                    if let Some(text) = &part.text {
                                        let _ = tx.send(Ok(ProviderEvent::ContentChunk { content: text.clone() })).await;
                                    }
                                }
                                
                                if candidate.finish_reason.is_some() {
                                    let _ = tx.send(Ok(ProviderEvent::Complete { token_usage: None })).await;
                                    return;
                                }
                            }
                        }
                    }
                    
                    let _ = tx.send(Ok(ProviderEvent::Complete { token_usage: None })).await;
                }
                Err(e) => {
                    let _ = tx.send(Err(ProviderError::Http(e))).await;
                }
            }
        });
        
        Ok(rx)
    }
    
    fn model(&self) -> &Model {
        &self.model
    }
    
    fn name(&self) -> &str {
        "vertex"
    }
    
    async fn is_available(&self) -> bool {
        // Test availability with a simple request
        let test_messages = vec![Message {
            id: "test".to_string(),
            session_id: "test".to_string(),
            role: MessageRole::User,
            content: crate::storage::MessageContent::Text("test".to_string()),
            timestamp: chrono::Utc::now(),
            metadata: serde_json::Value::Null,
        }];
        
        let request = self.create_request(test_messages);
        
        self.client
            .post(&self.get_api_url())
            .header("Authorization", format!("Bearer {}", self.access_token))
            .header("Content-Type", "application/json")
            .json(&request)
            .send()
            .await
            .map(|response| response.status().is_success())
            .unwrap_or(false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::llm::ModelCapabilities;
    
    #[test]
    fn test_vertex_provider_creation() {
        let model = Model {
            id: "gemini-1.5-pro".to_string(),
            name: "Gemini 1.5 Pro".to_string(),
            provider: "vertex".to_string(),
            context_length: 1000000,
            max_output_tokens: 8192,
            supports_tools: true,
            supports_streaming: true,
            supports_vision: true,
            cost_per_input_token: 0.0035,
            cost_per_output_token: 0.0105,
            capabilities: ModelCapabilities::default(),
        };
        
        let provider = VertexProvider::new(
            "test-project".to_string(),
            "us-central1".to_string(),
            "test-token".to_string(),
            model,
            Some(1000),
            Some(0.7),
        ).unwrap();
        
        assert_eq!(provider.name(), "vertex");
        assert_eq!(provider.project_id, "test-project");
        assert_eq!(provider.location, "us-central1");
    }
    
    #[test]
    fn test_api_url_generation() {
        let model = Model {
            id: "gemini-1.5-pro".to_string(),
            name: "Gemini 1.5 Pro".to_string(),
            provider: "vertex".to_string(),
            context_length: 1000000,
            max_output_tokens: 8192,
            supports_tools: true,
            supports_streaming: true,
            supports_vision: true,
            cost_per_input_token: 0.0035,
            cost_per_output_token: 0.0105,
            capabilities: ModelCapabilities::default(),
        };
        
        let provider = VertexProvider::new(
            "my-project".to_string(),
            "europe-west1".to_string(),
            "test-token".to_string(),
            model,
            None,
            None,
        ).unwrap();
        
        let expected_url = "https://europe-west1-aiplatform.googleapis.com/v1/projects/my-project/locations/europe-west1/publishers/google/models/gemini-1.5-pro:generateContent";
        assert_eq!(provider.get_api_url(), expected_url);
    }
    
    #[test]
    fn test_message_conversion() {
        let model = Model {
            id: "gemini-1.5-pro".to_string(),
            name: "Gemini 1.5 Pro".to_string(),
            provider: "vertex".to_string(),
            context_length: 1000000,
            max_output_tokens: 8192,
            supports_tools: true,
            supports_streaming: true,
            supports_vision: true,
            cost_per_input_token: 0.0035,
            cost_per_output_token: 0.0105,
            capabilities: ModelCapabilities::default(),
        };
        
        let provider = VertexProvider::new(
            "test-project".to_string(),
            "us-central1".to_string(),
            "test-token".to_string(),
            model,
            None,
            None,
        ).unwrap();
        
        let messages = vec![
            Message {
                id: "1".to_string(),
                session_id: "test".to_string(),
                role: MessageRole::System,
                content: crate::storage::MessageContent::Text("You are a helpful assistant.".to_string()),
                timestamp: chrono::Utc::now(),
                metadata: serde_json::Value::Null,
            },
            Message {
                id: "2".to_string(),
                session_id: "test".to_string(),
                role: MessageRole::User,
                content: crate::storage::MessageContent::Text("Hello!".to_string()),
                timestamp: chrono::Utc::now(),
                metadata: serde_json::Value::Null,
            },
            Message {
                id: "3".to_string(),
                session_id: "test".to_string(),
                role: MessageRole::Assistant,
                content: crate::storage::MessageContent::Text("Hi there!".to_string()),
                timestamp: chrono::Utc::now(),
                metadata: serde_json::Value::Null,
            },
        ];
        
        let vertex_contents = provider.convert_messages(messages);
        
        assert_eq!(vertex_contents.len(), 3);
        assert_eq!(vertex_contents[0].role, "user"); // system -> user
        assert_eq!(vertex_contents[1].role, "user");
        assert_eq!(vertex_contents[2].role, "model"); // assistant -> model
    }
}