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
//! Azure OpenAI provider implementation for CoderLib
//!
//! This module provides integration with Azure OpenAI Service, supporting
//! GPT-4, GPT-3.5-turbo, and other models deployed on Azure with enterprise features.

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

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;

/// Azure OpenAI provider
pub struct AzureProvider {
    client: Client,
    api_key: String,
    endpoint: String,
    deployment_name: String,
    api_version: String,
    model: Model,
    max_tokens: Option<u32>,
    temperature: Option<f32>,
}

/// Azure OpenAI request format
#[derive(Debug, Serialize)]
struct AzureRequest {
    messages: Vec<AzureMessage>,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tools: Option<Vec<serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_choice: Option<String>,
    stream: bool,
}

/// Azure OpenAI message format
#[derive(Debug, Serialize)]
struct AzureMessage {
    role: String,
    content: String,
}

/// Azure OpenAI response format
#[derive(Debug, Deserialize)]
struct AzureResponse {
    choices: Vec<AzureChoice>,
    usage: Option<AzureUsage>,
}

/// Azure OpenAI choice
#[derive(Debug, Deserialize)]
struct AzureChoice {
    message: AzureResponseMessage,
    finish_reason: Option<String>,
}

/// Azure OpenAI response message
#[derive(Debug, Deserialize)]
struct AzureResponseMessage {
    role: String,
    content: Option<String>,
    tool_calls: Option<Vec<serde_json::Value>>,
}

/// Azure OpenAI usage information
#[derive(Debug, Deserialize)]
struct AzureUsage {
    prompt_tokens: u32,
    completion_tokens: u32,
    total_tokens: u32,
}

/// Azure OpenAI streaming response chunk
#[derive(Debug, Deserialize)]
struct AzureStreamChunk {
    choices: Vec<AzureStreamChoice>,
}

/// Azure OpenAI streaming choice
#[derive(Debug, Deserialize)]
struct AzureStreamChoice {
    delta: AzureDelta,
    finish_reason: Option<String>,
}

/// Azure OpenAI streaming delta
#[derive(Debug, Deserialize)]
struct AzureDelta {
    role: Option<String>,
    content: Option<String>,
}

impl AzureProvider {
    /// Create a new Azure OpenAI provider
    pub fn new(
        api_key: String,
        endpoint: String,
        deployment_name: String,
        api_version: Option<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)))?;
        
        // Ensure endpoint doesn't end with slash
        let endpoint = endpoint.trim_end_matches('/').to_string();
        
        Ok(Self {
            client,
            api_key,
            endpoint,
            deployment_name,
            api_version: api_version.unwrap_or_else(|| "2024-02-15-preview".to_string()),
            model,
            max_tokens,
            temperature,
        })
    }
    
    /// Get the full API URL for requests
    fn get_api_url(&self) -> String {
        format!(
            "{}/openai/deployments/{}/chat/completions?api-version={}",
            self.endpoint, self.deployment_name, self.api_version
        )
    }
    
    /// Convert CoderLib messages to Azure format
    fn convert_messages(&self, messages: Vec<Message>) -> Vec<AzureMessage> {
        messages
            .into_iter()
            .map(|msg| AzureMessage {
                role: msg.role.to_string(),
                content: msg.content.as_text(),
            })
            .collect()
    }
    
    /// Create request payload
    fn create_request(&self, messages: Vec<Message>, stream: bool) -> AzureRequest {
        AzureRequest {
            messages: self.convert_messages(messages),
            max_tokens: self.max_tokens,
            temperature: self.temperature,
            tools: None, // TODO: Implement tool support
            tool_choice: None,
            stream,
        }
    }
    
    /// Parse non-streaming response
    fn parse_response(&self, response: AzureResponse) -> Result<ProviderResponse, ProviderError> {
        let choice = response.choices
            .into_iter()
            .next()
            .ok_or_else(|| ProviderError::ResponseParsing("No choices in response".to_string()))?;
        
        let content = choice.message.content
            .unwrap_or_default();
        
        let token_usage = response.usage.map(|usage| TokenUsage {
            input_tokens: usage.prompt_tokens,
            output_tokens: usage.completion_tokens,
            total_tokens: usage.prompt_tokens + usage.completion_tokens,
            cache_creation_tokens: 0,
            cache_read_tokens: 0,
        });
        
        Ok(ProviderResponse {
            content,
            tool_calls: Vec::new(), // TODO: Parse tool calls
            token_usage,
            metadata: serde_json::json!({
                "finish_reason": choice.finish_reason,
                "model": self.model.id,
                "provider": "azure",
                "deployment": self.deployment_name
            }),
        })
    }
}

#[async_trait]
impl Provider for AzureProvider {
    async fn send_messages(
        &self,
        messages: Vec<Message>,
        _tools: Vec<Box<dyn Tool>>,
    ) -> Result<ProviderResponse, ProviderError> {
        let request = self.create_request(messages, false);
        
        let response = self.client
            .post(&self.get_api_url())
            .header("api-key", &self.api_key)
            .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!(
                "Azure API error {}: {}", status, error_text
            )));
        }
        
        let azure_response: AzureResponse = response.json().await
            .map_err(|e| ProviderError::ResponseParsing(format!("Failed to parse Azure response: {}", e)))?;
        
        self.parse_response(azure_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, true);
        let client = self.client.clone();
        let url = self.get_api_url();
        let api_key = self.api_key.clone();
        
        tokio::spawn(async move {
            let response_result = client
                .post(&url)
                .header("api-key", &api_key)
                .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!(
                            "Azure API error {}: {}", status, error_text
                        )))).await;
                        return;
                    }
                    
                    let mut stream = response.bytes_stream();
                    let mut buffer = String::new();
                    
                    while let Some(chunk_result) = stream.next().await {
                        match chunk_result {
                            Ok(chunk) => {
                                let chunk_str = String::from_utf8_lossy(&chunk);
                                buffer.push_str(&chunk_str);
                                
                                // Process complete lines
                                while let Some(line_end) = buffer.find('\n') {
                                    let line = buffer[..line_end].trim().to_string();
                                    buffer = buffer[line_end + 1..].to_string();
                                    
                                    if line.starts_with("data: ") {
                                        let data = &line[6..];
                                        
                                        if data == "[DONE]" {
                                            let _ = tx.send(Ok(ProviderEvent::Complete { token_usage: None })).await;
                                            return;
                                        }
                                        
                                        if let Ok(chunk) = serde_json::from_str::<AzureStreamChunk>(data) {
                                            for choice in chunk.choices {
                                                if let Some(content) = choice.delta.content {
                                                    let _ = tx.send(Ok(ProviderEvent::ContentChunk { content })).await;
                                                }

                                                if choice.finish_reason.is_some() {
                                                    let _ = tx.send(Ok(ProviderEvent::Complete { token_usage: None })).await;
                                                    return;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            Err(e) => {
                                let _ = tx.send(Err(ProviderError::Streaming(format!("Stream error: {}", e)))).await;
                                break;
                            }
                        }
                    }
                }
                Err(e) => {
                    let _ = tx.send(Err(ProviderError::Http(e))).await;
                }
            }
        });
        
        Ok(rx)
    }
    
    fn model(&self) -> &Model {
        &self.model
    }
    
    fn name(&self) -> &str {
        "azure"
    }
    
    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, false);
        
        self.client
            .post(&self.get_api_url())
            .header("api-key", &self.api_key)
            .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_azure_provider_creation() {
        let model = Model {
            id: "gpt-4".to_string(),
            name: "GPT-4".to_string(),
            provider: "azure".to_string(),
            context_length: 8192,
            max_output_tokens: 4000,
            supports_tools: true,
            supports_streaming: true,
            supports_vision: false,
            cost_per_input_token: 0.03,
            cost_per_output_token: 0.06,
            capabilities: ModelCapabilities::default(),
        };
        
        let provider = AzureProvider::new(
            "test-key".to_string(),
            "https://test.openai.azure.com".to_string(),
            "gpt-4-deployment".to_string(),
            None,
            model,
            Some(1000),
            Some(0.7),
        ).unwrap();
        
        assert_eq!(provider.name(), "azure");
        assert_eq!(provider.deployment_name, "gpt-4-deployment");
        assert_eq!(provider.api_version, "2024-02-15-preview");
    }
    
    #[test]
    fn test_api_url_generation() {
        let model = Model {
            id: "gpt-4".to_string(),
            name: "GPT-4".to_string(),
            provider: "azure".to_string(),
            context_length: 8192,
            max_output_tokens: 4000,
            supports_tools: true,
            supports_streaming: true,
            supports_vision: false,
            cost_per_input_token: 0.03,
            cost_per_output_token: 0.06,
            capabilities: ModelCapabilities::default(),
        };
        
        let provider = AzureProvider::new(
            "test-key".to_string(),
            "https://test.openai.azure.com/".to_string(), // With trailing slash
            "my-deployment".to_string(),
            Some("2023-12-01-preview".to_string()),
            model,
            None,
            None,
        ).unwrap();
        
        let expected_url = "https://test.openai.azure.com/openai/deployments/my-deployment/chat/completions?api-version=2023-12-01-preview";
        assert_eq!(provider.get_api_url(), expected_url);
    }
    
    #[test]
    fn test_message_conversion() {
        let model = Model {
            id: "gpt-4".to_string(),
            name: "GPT-4".to_string(),
            provider: "azure".to_string(),
            context_length: 8192,
            max_output_tokens: 4000,
            supports_tools: true,
            supports_streaming: true,
            supports_vision: false,
            cost_per_input_token: 0.03,
            cost_per_output_token: 0.06,
            capabilities: ModelCapabilities::default(),
        };
        
        let provider = AzureProvider::new(
            "test-key".to_string(),
            "https://test.openai.azure.com".to_string(),
            "gpt-4-deployment".to_string(),
            None,
            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,
            },
        ];
        
        let azure_messages = provider.convert_messages(messages);
        
        assert_eq!(azure_messages.len(), 2);
        assert_eq!(azure_messages[0].role, "system");
        assert_eq!(azure_messages[0].content, "You are a helpful assistant.");
        assert_eq!(azure_messages[1].role, "user");
        assert_eq!(azure_messages[1].content, "Hello!");
    }
}