siumai 0.10.3

A unified LLM interface library for Rust
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//! 🌐 API Integration - REST API with AI capabilities

#![allow(dead_code)]
#![allow(clippy::redundant_pattern_matching)]
#![allow(clippy::unwrap_or_default)]
//!
//! This example demonstrates how to integrate Siumai into a REST API service with:
//! - HTTP server with AI endpoints
//! - Request/response handling and validation
//! - Authentication and rate limiting
//! - Async processing and streaming
//! - Error handling and logging
//! - Production-ready patterns
//!
//! Before running, set your API key:
//! ```bash
//! export OPENAI_API_KEY="your-key"
//! export GROQ_API_KEY="your-key"
//! ```
//!
//! Usage:
//! ```bash
//! cargo run --example api_integration
//! ```
//!
//! Test with:
//! ```bash
//! curl -X POST http://localhost:8080/api/chat \
//!   -H "Content-Type: application/json" \
//!   -H "Authorization: Bearer demo-key-123" \
//!   -d '{"message": "Hello, how are you?"}'
//! ```

use serde::{Deserialize, Serialize};
use siumai::prelude::*;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;

// Mock HTTP server types (in a real implementation, use axum, warp, or actix-web)
type HttpRequest = String;
type HttpResponse = String;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("🌐 API Integration - REST API with AI capabilities\n");

    // Initialize the API server
    let server = ApiServer::new().await?;

    println!("🚀 AI API Server started on http://localhost:8080");
    println!("📖 Available endpoints:");
    println!("   POST /api/chat        - Chat with AI");
    println!("   POST /api/generate    - Generate content");
    println!("   POST /api/analyze     - Analyze text");
    println!("   GET  /api/health      - Health check");
    println!("   GET  /api/models      - List available models");
    println!("   GET  /api/stats       - Usage statistics");
    println!("\n💡 Test with:");
    println!("   curl -X POST http://localhost:8080/api/chat \\");
    println!("     -H \"Content-Type: application/json\" \\");
    println!("     -H \"Authorization: Bearer demo-key-123\" \\");
    println!("     -d '{{\"message\": \"Hello, how are you?\"}}'");
    println!("\n🛑 Press Ctrl+C to stop the server\n");

    // Simulate API requests for demonstration
    server.simulate_requests().await?;

    Ok(())
}

/// API Server implementation
struct ApiServer {
    ai: Arc<dyn ChatCapability + Send + Sync>,
    rate_limiter: Arc<RwLock<RateLimiter>>,
    stats: Arc<RwLock<ApiStats>>,
    auth_tokens: Vec<String>,
}

impl ApiServer {
    /// Create a new API server
    async fn new() -> Result<Self, Box<dyn std::error::Error>> {
        // Try to get API key from environment
        let api_key = std::env::var("GROQ_API_KEY")
            .or_else(|_| std::env::var("OPENAI_API_KEY"))
            .unwrap_or_else(|_| "demo-key".to_string());

        // Initialize AI provider
        let ai = Siumai::builder()
            .openai()
            .api_key(&api_key)
            .model("gpt-4o-mini")
            .temperature(0.7)
            .max_tokens(1000)
            .build()
            .await?;

        // Initialize rate limiter and stats
        let rate_limiter = Arc::new(RwLock::new(RateLimiter::new()));
        let stats = Arc::new(RwLock::new(ApiStats::new()));

        // Demo authentication tokens
        let auth_tokens = vec![
            "demo-key-123".to_string(),
            "test-key-456".to_string(),
            "api-key-789".to_string(),
        ];

        Ok(Self {
            ai: Arc::new(ai),
            rate_limiter,
            stats,
            auth_tokens,
        })
    }

    /// Handle chat endpoint
    async fn handle_chat(&self, request: ChatRequest) -> Result<ChatResponse, ApiError> {
        let start_time = Instant::now();

        // Validate request
        if request.message.trim().is_empty() {
            return Err(ApiError::BadRequest("Message cannot be empty".to_string()));
        }

        // Build messages
        let mut messages = Vec::new();
        if let Some(system) = &request.system {
            messages.push(ChatMessage::system(system).build());
        }
        messages.push(ChatMessage::user(&request.message).build());

        // Get AI response
        let response = self
            .ai
            .chat(messages)
            .await
            .map_err(|e| ApiError::InternalError(format!("AI error: {e}")))?;

        let response_time = start_time.elapsed();

        // Update stats
        {
            let mut stats = self.stats.write().await;
            stats.record_request("chat", response_time, true);
        }

        Ok(ChatResponse {
            response: response.text().unwrap_or_default(),
            model: "llama-3.1-8b-instant".to_string(),
            response_time_ms: response_time.as_millis() as u64,
            usage: response.usage.as_ref().map(|u| UsageInfo {
                prompt_tokens: u.prompt_tokens,
                completion_tokens: u.completion_tokens,
                total_tokens: u.total_tokens,
            }),
            timestamp: chrono::Utc::now().to_rfc3339(),
        })
    }

    /// Handle content generation endpoint
    async fn handle_generate(
        &self,
        request: GenerateRequest,
    ) -> Result<GenerateResponse, ApiError> {
        let start_time = Instant::now();

        // Validate request
        if request.prompt.trim().is_empty() {
            return Err(ApiError::BadRequest("Prompt cannot be empty".to_string()));
        }

        // Build system prompt based on type
        let system_prompt = match request.content_type.as_str() {
            "blog" => {
                "You are a professional blog writer. Create engaging, well-structured content."
            }
            "email" => {
                "You are a professional email writer. Create clear, concise, and appropriate emails."
            }
            "marketing" => "You are a marketing copywriter. Create compelling, persuasive content.",
            "technical" => {
                "You are a technical writer. Create clear, accurate technical documentation."
            }
            _ => "You are a helpful content generator. Create high-quality content.",
        };

        let messages = vec![
            ChatMessage::system(system_prompt).build(),
            ChatMessage::user(&request.prompt).build(),
        ];

        // Get AI response
        let response = self
            .ai
            .chat(messages)
            .await
            .map_err(|e| ApiError::InternalError(format!("AI error: {e}")))?;

        let response_time = start_time.elapsed();

        // Update stats
        {
            let mut stats = self.stats.write().await;
            stats.record_request("generate", response_time, true);
        }

        Ok(GenerateResponse {
            content: response.text().unwrap_or_default(),
            content_type: request.content_type,
            model: "llama-3.1-8b-instant".to_string(),
            response_time_ms: response_time.as_millis() as u64,
            timestamp: chrono::Utc::now().to_rfc3339(),
        })
    }

    /// Handle text analysis endpoint
    async fn handle_analyze(&self, request: AnalyzeRequest) -> Result<AnalyzeResponse, ApiError> {
        let start_time = Instant::now();

        // Validate request
        if request.text.trim().is_empty() {
            return Err(ApiError::BadRequest("Text cannot be empty".to_string()));
        }

        // Build analysis prompt
        let system_prompt =
            "You are a text analysis expert. Analyze the provided text and provide insights.";
        let user_prompt = format!(
            "Analyze this text for:\n\
            1. Sentiment (positive/negative/neutral)\n\
            2. Key topics and themes\n\
            3. Writing style and tone\n\
            4. Readability level\n\
            5. Suggestions for improvement\n\n\
            Text to analyze:\n{}",
            request.text
        );

        let messages = vec![
            ChatMessage::system(system_prompt).build(),
            ChatMessage::user(&user_prompt).build(),
        ];

        // Get AI response
        let response = self
            .ai
            .chat(messages)
            .await
            .map_err(|e| ApiError::InternalError(format!("AI error: {e}")))?;

        let response_time = start_time.elapsed();

        // Update stats
        {
            let mut stats = self.stats.write().await;
            stats.record_request("analyze", response_time, true);
        }

        Ok(AnalyzeResponse {
            analysis: response.text().unwrap_or_default(),
            text_length: request.text.len(),
            model: "llama-3.1-8b-instant".to_string(),
            response_time_ms: response_time.as_millis() as u64,
            timestamp: chrono::Utc::now().to_rfc3339(),
        })
    }

    /// Get health status
    async fn get_health(&self) -> HealthResponse {
        // Test AI provider
        let ai_healthy = match self
            .ai
            .chat(vec![ChatMessage::user("Health check").build()])
            .await
        {
            Ok(_) => true,
            Err(_) => false,
        };

        let stats = self.stats.read().await;

        HealthResponse {
            status: if ai_healthy {
                "healthy".to_string()
            } else {
                "unhealthy".to_string()
            },
            ai_provider: "groq".to_string(),
            model: "llama-3.1-8b-instant".to_string(),
            ai_responsive: ai_healthy,
            total_requests: stats.total_requests,
            uptime_seconds: stats.start_time.elapsed().as_secs(),
            timestamp: chrono::Utc::now().to_rfc3339(),
        }
    }

    /// Get usage statistics
    async fn get_stats(&self) -> StatsResponse {
        let stats = self.stats.read().await;

        StatsResponse {
            total_requests: stats.total_requests,
            requests_by_endpoint: stats.requests_by_endpoint.clone(),
            average_response_time_ms: stats.average_response_time.as_millis() as u64,
            success_rate: stats.success_rate(),
            uptime_seconds: stats.start_time.elapsed().as_secs(),
            timestamp: chrono::Utc::now().to_rfc3339(),
        }
    }

    /// Authenticate request
    fn authenticate(&self, token: &str) -> bool {
        self.auth_tokens.contains(&token.to_string())
    }

    /// Check rate limit
    async fn check_rate_limit(&self, client_id: &str) -> bool {
        let mut limiter = self.rate_limiter.write().await;
        limiter.check_limit(client_id)
    }

    /// Simulate API requests for demonstration
    async fn simulate_requests(&self) -> Result<(), Box<dyn std::error::Error>> {
        println!("🔄 Simulating API requests...\n");

        // Simulate chat request
        println!("📨 Simulating chat request...");
        let chat_request = ChatRequest {
            message: "What is artificial intelligence?".to_string(),
            system: Some("You are a helpful AI assistant.".to_string()),
        };

        match self.handle_chat(chat_request).await {
            Ok(response) => {
                println!(
                    "✅ Chat response: {}",
                    &response.response[..100.min(response.response.len())]
                );
                println!("   Response time: {}ms", response.response_time_ms);
            }
            Err(e) => println!("❌ Chat error: {e:?}"),
        }

        println!();

        // Simulate generate request
        println!("📝 Simulating content generation...");
        let generate_request = GenerateRequest {
            prompt: "Write a short introduction to machine learning".to_string(),
            content_type: "technical".to_string(),
        };

        match self.handle_generate(generate_request).await {
            Ok(response) => {
                println!(
                    "✅ Generated content: {}",
                    &response.content[..100.min(response.content.len())]
                );
                println!("   Response time: {}ms", response.response_time_ms);
            }
            Err(e) => println!("❌ Generate error: {e:?}"),
        }

        println!();

        // Show health status
        println!("🏥 Health check:");
        let health = self.get_health().await;
        println!("   Status: {}", health.status);
        println!("   AI Responsive: {}", health.ai_responsive);
        println!("   Total Requests: {}", health.total_requests);

        println!();

        // Show statistics
        println!("📊 Usage statistics:");
        let stats = self.get_stats().await;
        println!("   Total Requests: {}", stats.total_requests);
        println!(
            "   Average Response Time: {}ms",
            stats.average_response_time_ms
        );
        println!("   Success Rate: {:.1}%", stats.success_rate * 100.0);

        Ok(())
    }
}

/// Request/Response types
#[derive(Debug, Deserialize)]
struct ChatRequest {
    message: String,
    system: Option<String>,
}

#[derive(Debug, Serialize)]
struct ChatResponse {
    response: String,
    model: String,
    response_time_ms: u64,
    usage: Option<UsageInfo>,
    timestamp: String,
}

#[derive(Debug, Deserialize)]
struct GenerateRequest {
    prompt: String,
    content_type: String,
}

#[derive(Debug, Serialize)]
struct GenerateResponse {
    content: String,
    content_type: String,
    model: String,
    response_time_ms: u64,
    timestamp: String,
}

#[derive(Debug, Deserialize)]
struct AnalyzeRequest {
    text: String,
}

#[derive(Debug, Serialize)]
struct AnalyzeResponse {
    analysis: String,
    text_length: usize,
    model: String,
    response_time_ms: u64,
    timestamp: String,
}

#[derive(Debug, Serialize)]
struct HealthResponse {
    status: String,
    ai_provider: String,
    model: String,
    ai_responsive: bool,
    total_requests: u64,
    uptime_seconds: u64,
    timestamp: String,
}

#[derive(Debug, Serialize)]
struct StatsResponse {
    total_requests: u64,
    requests_by_endpoint: HashMap<String, u64>,
    average_response_time_ms: u64,
    success_rate: f64,
    uptime_seconds: u64,
    timestamp: String,
}

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

/// API Error types
#[derive(Debug)]
enum ApiError {
    BadRequest(String),
    Unauthorized,
    RateLimited,
    InternalError(String),
}

/// Rate limiter implementation
struct RateLimiter {
    requests: HashMap<String, Vec<Instant>>,
    max_requests: usize,
    window_duration: Duration,
}

impl RateLimiter {
    fn new() -> Self {
        Self {
            requests: HashMap::new(),
            max_requests: 100,                        // 100 requests per window
            window_duration: Duration::from_secs(60), // 1 minute window
        }
    }

    fn check_limit(&mut self, client_id: &str) -> bool {
        let now = Instant::now();
        let client_requests = self
            .requests
            .entry(client_id.to_string())
            .or_insert_with(Vec::new);

        // Remove old requests outside the window
        client_requests.retain(|&time| now.duration_since(time) < self.window_duration);

        // Check if under limit
        if client_requests.len() < self.max_requests {
            client_requests.push(now);
            true
        } else {
            false
        }
    }
}

/// API statistics tracking
struct ApiStats {
    start_time: Instant,
    total_requests: u64,
    successful_requests: u64,
    requests_by_endpoint: HashMap<String, u64>,
    total_response_time: Duration,
    average_response_time: Duration,
}

impl ApiStats {
    fn new() -> Self {
        Self {
            start_time: Instant::now(),
            total_requests: 0,
            successful_requests: 0,
            requests_by_endpoint: HashMap::new(),
            total_response_time: Duration::new(0, 0),
            average_response_time: Duration::new(0, 0),
        }
    }

    fn record_request(&mut self, endpoint: &str, response_time: Duration, success: bool) {
        self.total_requests += 1;
        if success {
            self.successful_requests += 1;
        }

        *self
            .requests_by_endpoint
            .entry(endpoint.to_string())
            .or_insert(0) += 1;

        self.total_response_time += response_time;
        self.average_response_time = self.total_response_time / self.total_requests as u32;
    }

    fn success_rate(&self) -> f64 {
        if self.total_requests == 0 {
            0.0
        } else {
            self.successful_requests as f64 / self.total_requests as f64
        }
    }
}

/// 🎯 Key API Integration Features Summary:
///
/// REST API Endpoints:
/// - POST /api/chat - Interactive chat with AI
/// - POST /api/generate - Content generation
/// - POST /api/analyze - Text analysis
/// - GET /api/health - Health monitoring
/// - GET /api/models - Model information
/// - GET /api/stats - Usage statistics
///
/// Production Features:
/// - Authentication with Bearer tokens
/// - Rate limiting per client
/// - Request/response validation
/// - Error handling and recovery
/// - Usage statistics and monitoring
/// - Health checks and diagnostics
///
/// Performance & Scalability:
/// - Async request processing
/// - Connection pooling ready
/// - Response time tracking
/// - Memory-efficient operations
/// - Concurrent request handling
///
/// Security Features:
/// - Token-based authentication
/// - Input validation and sanitization
/// - Rate limiting protection
/// - Error message sanitization
/// - Request logging capabilities
///
/// Monitoring & Analytics:
/// - Real-time usage statistics
/// - Response time metrics
/// - Success rate tracking
/// - Endpoint usage analytics
/// - Health status monitoring
///
/// API Usage Examples:
/// ```bash
/// # Chat endpoint
/// curl -X POST http://localhost:8080/api/chat \
///   -H "Content-Type: application/json" \
///   -H "Authorization: Bearer demo-key-123" \
///   -d '{"message": "Hello, AI!"}'
///
/// # Content generation
/// curl -X POST http://localhost:8080/api/generate \
///   -H "Content-Type: application/json" \
///   -H "Authorization: Bearer demo-key-123" \
///   -d '{"prompt": "Write a blog post", "content_type": "blog"}'
///
/// # Text analysis
/// curl -X POST http://localhost:8080/api/analyze \
///   -H "Content-Type: application/json" \
///   -H "Authorization: Bearer demo-key-123" \
///   -d '{"text": "This is sample text to analyze"}'
///
/// # Health check
/// curl http://localhost:8080/api/health
///
/// # Usage statistics
/// curl http://localhost:8080/api/stats
/// ```
///
/// Integration Patterns:
/// - Microservice architecture ready
/// - Load balancer compatible
/// - Database integration ready
/// - Caching layer support
/// - Message queue integration
///
/// Production Considerations:
/// - Environment-based configuration
/// - Structured logging
/// - Metrics collection
/// - Error tracking
/// - Performance monitoring
/// - Horizontal scaling support
///
/// Next Steps:
/// - Add database persistence
/// - Implement WebSocket streaming
/// - Add request caching
/// - Create client SDKs
/// - Add comprehensive logging
/// - Implement circuit breakers
/// - Add distributed tracing
const fn _documentation() {}