rustchain-community 1.0.0

Open-source AI agent framework with core functionality and plugin 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
// Azure OpenAI LLM Provider Implementation
use super::{ChatMessage, LLMProvider, LLMRequest, LLMResponse, MessageRole, ModelInfo};
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::{debug, error, info};

#[derive(Debug, Clone)]
pub struct AzureOpenAIProvider {
    client: reqwest::Client,
    api_key: String,
    endpoint: String,
    api_version: String,
    deployment_name: String,
}

impl AzureOpenAIProvider {
    pub fn new(api_key: String, endpoint: String, deployment_name: String) -> Self {
        Self {
            client: reqwest::Client::new(),
            api_key,
            endpoint: endpoint.trim_end_matches('/').to_string(),
            api_version: "2024-06-01".to_string(), // Latest stable API version
            deployment_name,
        }
    }

    pub fn with_api_version(mut self, api_version: String) -> Self {
        self.api_version = api_version;
        self
    }

    pub fn with_deployment(mut self, deployment_name: String) -> Self {
        self.deployment_name = deployment_name;
        self
    }

    fn get_azure_url(&self) -> String {
        format!(
            "{}/openai/deployments/{}/chat/completions?api-version={}",
            self.endpoint, self.deployment_name, self.api_version
        )
    }

    fn convert_messages_to_azure(&self, messages: &[ChatMessage]) -> Vec<AzureMessage> {
        messages
            .iter()
            .map(|msg| {
                let role = match msg.role {
                    MessageRole::System => "system",
                    MessageRole::User => "user",
                    MessageRole::Assistant => "assistant",
                    MessageRole::Tool => "user", // Tool responses as user messages
                };
                
                AzureMessage {
                    role: role.to_string(),
                    content: Some(msg.content.clone()),
                    tool_calls: None, // Tool calls handled separately in requests
                }
            })
            .collect()
    }
}

#[async_trait]
impl LLMProvider for AzureOpenAIProvider {
    async fn complete(&self, request: LLMRequest) -> Result<LLMResponse> {
        debug!("Azure OpenAI completion request: {:?}", request.model);
        
        let url = self.get_azure_url();
        let messages = self.convert_messages_to_azure(&request.messages);
        
        let azure_request = AzureRequest {
            messages,
            temperature: request.temperature,
            max_tokens: request.max_tokens,
            top_p: None,
            frequency_penalty: None,
            presence_penalty: None,
            stop: None,
            stream: false,
        };

        let payload = serde_json::to_string(&azure_request)?;
        
        debug!("Sending request to Azure OpenAI: {}", url);
        
        let response = self
            .client
            .post(&url)
            .header("api-key", &self.api_key)
            .header("Content-Type", "application/json")
            .body(payload)
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            error!("Azure OpenAI API error: {} - {}", status, error_text);
            return Err(anyhow!("Azure OpenAI API error: {} - {}", status, error_text));
        }

        let azure_response: AzureResponse = response.json().await?;
        
        let choice = azure_response
            .choices
            .first()
            .ok_or_else(|| anyhow!("No choices in Azure OpenAI response"))?;
            
        let content = choice.message.content.clone().unwrap_or_default();
        
        let usage = super::TokenUsage {
            prompt_tokens: azure_response.usage.prompt_tokens,
            completion_tokens: azure_response.usage.completion_tokens,
            total_tokens: azure_response.usage.total_tokens,
        };

        let finish_reason = match choice.finish_reason.as_deref().unwrap_or("stop") {
            "stop" => super::FinishReason::Stop,
            "length" => super::FinishReason::Length,
            "tool_calls" => super::FinishReason::ToolCalls,
            "content_filter" => super::FinishReason::ContentFilter,
            _ => super::FinishReason::Error,
        };

        info!("Azure OpenAI completion successful, {} input tokens, {} output tokens", 
              azure_response.usage.prompt_tokens, azure_response.usage.completion_tokens);

        Ok(LLMResponse {
            content,
            role: MessageRole::Assistant,
            model: self.deployment_name.clone(),
            usage,
            tool_calls: choice.message.tool_calls.clone().map(|calls| 
                calls.into_iter().map(|call| super::ToolCall {
                    id: call.id,
                    function: super::FunctionCall {
                        name: call.function.name,
                        arguments: call.function.arguments,
                    },
                }).collect()
            ),
            finish_reason,
            metadata: HashMap::new(),
        })
    }

    async fn stream(
        &self,
        _request: LLMRequest,
    ) -> Result<Box<dyn futures::Stream<Item = Result<LLMResponse>> + Send + Unpin>> {
        // Streaming support for Azure OpenAI - not implemented in this version
        // Azure OpenAI streaming requires Server-Sent Events (SSE) parsing
        // This is a lower priority feature that can be added in future versions
        Err(anyhow!("Streaming support requires SSE implementation - planned for future release"))
    }

    async fn list_models(&self) -> Result<Vec<ModelInfo>> {
        // Azure OpenAI models are deployment-specific, so we return common deployment models
        Ok(vec![
            ModelInfo {
                id: "gpt-4".to_string(),
                name: "GPT-4".to_string(),
                provider: "azure-openai".to_string(),
                context_length: 8192,
                max_output_tokens: 4096,
                supports_tools: true,
                supports_streaming: false, // Streaming planned for future release
                cost_per_input_token: Some(0.00003), // $30 per 1M tokens
                cost_per_output_token: Some(0.00006), // $60 per 1M tokens
            },
            ModelInfo {
                id: "gpt-4-32k".to_string(),
                name: "GPT-4 32K".to_string(),
                provider: "azure-openai".to_string(),
                context_length: 32768,
                max_output_tokens: 4096,
                supports_tools: true,
                supports_streaming: false,
                cost_per_input_token: Some(0.00006), // $60 per 1M tokens
                cost_per_output_token: Some(0.00012), // $120 per 1M tokens
            },
            ModelInfo {
                id: "gpt-35-turbo".to_string(),
                name: "GPT-3.5 Turbo".to_string(),
                provider: "azure-openai".to_string(),
                context_length: 4096,
                max_output_tokens: 4096,
                supports_tools: true,
                supports_streaming: false,
                cost_per_input_token: Some(0.0000015), // $1.5 per 1M tokens
                cost_per_output_token: Some(0.000002), // $2 per 1M tokens
            },
            ModelInfo {
                id: "gpt-35-turbo-16k".to_string(),
                name: "GPT-3.5 Turbo 16K".to_string(),
                provider: "azure-openai".to_string(),
                context_length: 16384,
                max_output_tokens: 4096,
                supports_tools: true,
                supports_streaming: false,
                cost_per_input_token: Some(0.000003), // $3 per 1M tokens
                cost_per_output_token: Some(0.000004), // $4 per 1M tokens
            },
        ])
    }

    fn provider_name(&self) -> &str {
        "azure-openai"
    }

    fn supports_streaming(&self) -> bool {
        false // Streaming planned for future release - requires SSE implementation
    }

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

// Azure OpenAI API request/response structures
#[derive(Debug, Serialize)]
struct AzureRequest {
    messages: Vec<AzureMessage>,
    #[serde(skip_serializing_if = "Option::is_none")]
    temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    top_p: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    frequency_penalty: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    presence_penalty: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    stop: Option<Vec<String>>,
    stream: bool,
}

#[derive(Debug, Serialize, Deserialize)]
struct AzureMessage {
    role: String,
    content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_calls: Option<Vec<AzureToolCall>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct AzureToolCall {
    id: String,
    function: AzureFunction,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct AzureFunction {
    name: String,
    arguments: String,
}

#[derive(Debug, Deserialize)]
struct AzureResponse {
    choices: Vec<AzureChoice>,
    usage: AzureUsage,
}

#[derive(Debug, Deserialize)]
struct AzureChoice {
    message: AzureMessage,
    #[serde(rename = "finish_reason")]
    finish_reason: Option<String>,
    #[allow(dead_code)]
    index: u32,
}

#[derive(Debug, Deserialize)]
struct AzureUsage {
    prompt_tokens: u32,
    completion_tokens: u32,
    total_tokens: u32,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_azure_provider_creation() {
        let provider = AzureOpenAIProvider::new(
            "test-api-key".to_string(),
            "https://test.openai.azure.com".to_string(),
            "gpt-4".to_string(),
        );
        assert_eq!(provider.provider_name(), "azure-openai");
        assert_eq!(provider.endpoint, "https://test.openai.azure.com");
        assert_eq!(provider.deployment_name, "gpt-4");
        assert_eq!(provider.api_version, "2024-06-01");
    }

    #[test]
    fn test_azure_provider_with_custom_api_version() {
        let provider = AzureOpenAIProvider::new(
            "test-api-key".to_string(),
            "https://test.openai.azure.com".to_string(),
            "gpt-35-turbo".to_string(),
        ).with_api_version("2023-12-01-preview".to_string());
        
        assert_eq!(provider.api_version, "2023-12-01-preview");
        assert_eq!(provider.deployment_name, "gpt-35-turbo");
    }

    #[test]
    fn test_azure_provider_with_custom_deployment() {
        let provider = AzureOpenAIProvider::new(
            "test-api-key".to_string(),
            "https://test.openai.azure.com".to_string(),
            "initial-deployment".to_string(),
        ).with_deployment("custom-deployment".to_string());
        
        assert_eq!(provider.deployment_name, "custom-deployment");
    }

    #[test]
    fn test_azure_url_generation() {
        let provider = AzureOpenAIProvider::new(
            "test-api-key".to_string(),
            "https://test.openai.azure.com".to_string(),
            "gpt-4".to_string(),
        );
        
        let url = provider.get_azure_url();
        assert_eq!(
            url,
            "https://test.openai.azure.com/openai/deployments/gpt-4/chat/completions?api-version=2024-06-01"
        );
    }

    #[test]
    fn test_azure_url_generation_with_trailing_slash() {
        let provider = AzureOpenAIProvider::new(
            "test-api-key".to_string(),
            "https://test.openai.azure.com/".to_string(), // With trailing slash
            "gpt-4".to_string(),
        );
        
        let url = provider.get_azure_url();
        assert_eq!(
            url,
            "https://test.openai.azure.com/openai/deployments/gpt-4/chat/completions?api-version=2024-06-01"
        );
    }

    #[test]
    fn test_message_conversion() {
        let provider = AzureOpenAIProvider::new(
            "test-api-key".to_string(),
            "https://test.openai.azure.com".to_string(),
            "gpt-4".to_string(),
        );
        
        let messages = vec![
            ChatMessage {
                role: MessageRole::System,
                content: "You are a helpful assistant".to_string(),
                name: None,
                tool_calls: None,
                tool_call_id: None,
            },
            ChatMessage {
                role: MessageRole::User,
                content: "Hello!".to_string(),
                name: None,
                tool_calls: None,
                tool_call_id: None,
            },
            ChatMessage {
                role: MessageRole::Assistant,
                content: "Hi there! How can I help you?".to_string(),
                name: None,
                tool_calls: None,
                tool_call_id: None,
            },
        ];
        
        let azure_messages = provider.convert_messages_to_azure(&messages);
        assert_eq!(azure_messages.len(), 3);
        assert_eq!(azure_messages[0].role, "system");
        assert_eq!(azure_messages[1].role, "user");
        assert_eq!(azure_messages[2].role, "assistant");
        assert_eq!(azure_messages[0].content, Some("You are a helpful assistant".to_string()));
        assert_eq!(azure_messages[1].content, Some("Hello!".to_string()));
        assert_eq!(azure_messages[2].content, Some("Hi there! How can I help you?".to_string()));
    }

    #[tokio::test]
    async fn test_list_models() {
        let provider = AzureOpenAIProvider::new(
            "test-api-key".to_string(),
            "https://test.openai.azure.com".to_string(),
            "gpt-4".to_string(),
        );
        
        let models = provider.list_models().await.unwrap();
        assert_eq!(models.len(), 4);
        assert!(models.iter().any(|m| m.id == "gpt-4"));
        assert!(models.iter().any(|m| m.id == "gpt-4-32k"));
        assert!(models.iter().any(|m| m.id == "gpt-35-turbo"));
        assert!(models.iter().any(|m| m.id == "gpt-35-turbo-16k"));
        
        // Check that all models have azure-openai provider
        assert!(models.iter().all(|m| m.provider == "azure-openai"));
    }
}