cert-x-gen 1.9.2

Advanced Multi-Language Security Scanning Engine
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
//! Ollama LLM Provider Implementation
//!
//! Ollama is a local LLM provider that runs models on your own hardware.
//! No API key required, completely free, and works offline.
//!
//! # Features
//!
//! - Local execution (no data leaves your machine)
//! - No API costs
//! - Multiple model support (CodeLlama, Mistral, Llama2, etc.)
//! - Streaming support (optional)
//! - Health checking
//!
//! # Setup
//!
//! 1. Install Ollama: https://ollama.ai/
//! 2. Download a model: `ollama pull codellama:13b`
//! 3. Start the server: `ollama serve`
//!
//! # Example
//!
//! ```no_run
//! use cert_x_gen::ai::providers::ollama::OllamaProvider;
//! use cert_x_gen::ai::providers::{LLMProvider, GenerationOptions};
//!
//! async fn example() -> anyhow::Result<()> {
//!     let provider = OllamaProvider::default();
//!     
//!     if !provider.is_available() {
//!         eprintln!("Ollama is not running. Start it with: ollama serve");
//!         return Ok(());
//!     }
//!     
//!     let code = provider.generate(
//!         "Write a Python function to check if a port is open",
//!         GenerationOptions::default(),
//!     ).await?;
//!     
//!     println!("Generated:\n{}", code);
//!     Ok(())
//! }
//! ```

use super::{
    AuthStatus, ConnectionStatus, GenerationOptions, LLMProvider, ModelInfo, ProviderHealthStatus,
};
use anyhow::{Context, Result};
use async_trait::async_trait;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::time::Duration;
use tracing::{debug, info, warn};

/// Ollama provider for local LLM execution
///
/// Ollama runs large language models locally on your machine, providing:
/// - Complete privacy (no data sent to cloud)
/// - No API costs
/// - Offline capability
/// - Multiple model support
///
/// Default configuration:
/// - Endpoint: http://localhost:11434
/// - Model: codellama:13b (optimized for code generation)
#[derive(Debug, Clone)]
pub struct OllamaProvider {
    /// Ollama API endpoint
    endpoint: String,

    /// Model name to use (e.g., "codellama:13b", "mistral:7b")
    model: String,

    /// HTTP client for API requests
    client: Client,
}

impl OllamaProvider {
    /// Create a new Ollama provider with custom endpoint and model
    ///
    /// # Arguments
    ///
    /// * `endpoint` - Ollama API endpoint (e.g., "http://localhost:11434")
    /// * `model` - Model name (e.g., "codellama:13b", "mistral:7b")
    ///
    /// # Example
    ///
    /// ```
    /// use cert_x_gen::ai::providers::ollama::OllamaProvider;
    ///
    /// let provider = OllamaProvider::new(
    ///     "http://localhost:11434".to_string(),
    ///     "codellama:13b".to_string(),
    /// );
    /// ```
    pub fn new(endpoint: String, model: String) -> Self {
        let client = Client::builder()
            .timeout(Duration::from_secs(300)) // 5 minutes for local generation
            .build()
            .expect("Failed to build HTTP client");

        Self {
            endpoint,
            model,
            client,
        }
    }

    /// Create a provider with default settings
    ///
    /// Uses:
    /// - Endpoint: http://localhost:11434
    /// - Model: codellama:13b
    ///
    /// # Example
    ///
    /// ```
    /// use cert_x_gen::ai::providers::ollama::OllamaProvider;
    ///
    /// let provider = OllamaProvider::default();
    /// ```
    pub fn default() -> Self {
        Self::new(
            "http://localhost:11434".to_string(),
            "codellama:13b".to_string(),
        )
    }

    /// Check if Ollama server is healthy and responding
    ///
    /// Makes a GET request to /api/tags to verify the server is running.
    #[allow(dead_code)]
    async fn check_health(&self) -> Result<bool> {
        let response = self
            .client
            .get(format!("{}/api/tags", self.endpoint))
            .timeout(Duration::from_secs(5)) // Quick health check
            .send()
            .await
            .context("Failed to connect to Ollama server")?;

        Ok(response.status().is_success())
    }

    /// Get the current model name
    pub fn model(&self) -> &str {
        &self.model
    }

    /// Get the endpoint URL
    pub fn endpoint(&self) -> &str {
        &self.endpoint
    }
}

#[async_trait]
impl LLMProvider for OllamaProvider {
    fn name(&self) -> &str {
        "ollama"
    }

    fn is_available(&self) -> bool {
        // For availability check, we need to handle being called from both
        // sync and async contexts. We'll spawn a blocking thread to avoid
        // "cannot start runtime from within runtime" errors.

        let endpoint = self.endpoint.clone();
        let client = self.client.clone();

        // Run the check in a separate thread to avoid runtime conflicts
        std::thread::spawn(move || {
            // Create a new runtime just for this check
            let rt = match tokio::runtime::Runtime::new() {
                Ok(rt) => rt,
                Err(_) => return false,
            };

            rt.block_on(async {
                let result = client
                    .get(format!("{}/api/tags", endpoint))
                    .timeout(Duration::from_secs(5))
                    .send()
                    .await;

                match result {
                    Ok(response) => response.status().is_success(),
                    Err(_) => false,
                }
            })
        })
        .join()
        .unwrap_or(false)
    }

    async fn generate(&self, prompt: &str, options: GenerationOptions) -> Result<String> {
        info!("Generating with Ollama model: {}", self.model);
        debug!("Prompt length: {} chars", prompt.len());

        // Request structure for Ollama /api/generate endpoint
        #[derive(Serialize)]
        struct GenerateRequest {
            model: String,
            prompt: String,
            stream: bool,
            #[serde(skip_serializing_if = "Option::is_none")]
            options: Option<GenerateRequestOptions>,
        }

        #[derive(Serialize)]
        struct GenerateRequestOptions {
            #[serde(skip_serializing_if = "Option::is_none")]
            num_predict: Option<u32>,
            #[serde(skip_serializing_if = "Option::is_none")]
            temperature: Option<f32>,
        }

        // Response structure for non-streaming
        #[derive(Deserialize)]
        struct GenerateResponse {
            #[serde(default)]
            response: String,
            #[serde(default)]
            done: bool,
        }

        let request_options = if options.max_tokens.is_some() || options.temperature.is_some() {
            Some(GenerateRequestOptions {
                num_predict: options.max_tokens,
                temperature: options.temperature,
            })
        } else {
            None
        };

        let request = GenerateRequest {
            model: self.model.clone(),
            prompt: prompt.to_string(),
            stream: false,
            options: request_options,
        };

        let timeout = options.timeout.unwrap_or(Duration::from_secs(300));

        debug!("Sending request to Ollama: {}/api/generate", self.endpoint);

        let response = self
            .client
            .post(format!("{}/api/generate", self.endpoint))
            .json(&request)
            .timeout(timeout)
            .send()
            .await
            .context("Failed to connect to Ollama. Is it running? Try: ollama serve")?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!(
                "Ollama returned error {}: {}. Check if model '{}' is installed with: ollama list",
                status,
                error_text,
                self.model
            );
        }

        let response_data: GenerateResponse = response
            .json()
            .await
            .context("Failed to parse Ollama response")?;

        if !response_data.done {
            warn!("Ollama response not marked as done, may be incomplete");
        }

        info!(
            "Generation completed, response length: {} chars",
            response_data.response.len()
        );

        Ok(response_data.response)
    }

    async fn list_models(&self) -> Result<Vec<ModelInfo>> {
        debug!("Fetching model list from Ollama");

        // Response structure for /api/tags endpoint
        #[derive(Deserialize)]
        struct TagsResponse {
            models: Vec<OllamaModel>,
        }

        #[derive(Deserialize)]
        struct OllamaModel {
            name: String,
            #[serde(default)]
            size: u64,
            #[serde(default)]
            #[allow(dead_code)]
            details: ModelDetails,
        }

        #[derive(Deserialize, Default)]
        struct ModelDetails {
            #[serde(default)]
            #[allow(dead_code)]
            parameter_size: String,
            #[serde(default)]
            #[allow(dead_code)]
            quantization_level: String,
        }

        let response: TagsResponse = self
            .client
            .get(format!("{}/api/tags", self.endpoint))
            .timeout(Duration::from_secs(10))
            .send()
            .await
            .context("Failed to connect to Ollama")?
            .json()
            .await
            .context("Failed to parse Ollama model list")?;

        let models: Vec<ModelInfo> = response
            .models
            .into_iter()
            .map(|m| {
                let mut model_info =
                    ModelInfo::new(m.name.clone(), m.name.clone(), "ollama".to_string());

                if m.size > 0 {
                    model_info.size = Some(m.size);
                }

                // Add capabilities based on model name
                if m.name.contains("code") {
                    model_info = model_info.with_capability("code-generation");
                }
                if m.name.contains("instruct") || m.name.contains("chat") {
                    model_info = model_info.with_capability("chat");
                }

                // Try to extract context window from details
                // Most Ollama models have 2048-4096 token windows
                model_info = model_info.with_context_window(4096);

                model_info
            })
            .collect();

        info!("Found {} Ollama models", models.len());

        Ok(models)
    }

    fn estimate_cost(&self, _prompt: &str) -> Option<f64> {
        // Ollama is free (local execution)
        None
    }

    async fn health_check(&self) -> Result<ProviderHealthStatus> {
        use std::time::Instant;

        let mut status = ProviderHealthStatus::new(self.name());
        status.authentication = AuthStatus::NotRequired;
        status.add_metadata("endpoint", &self.endpoint);
        status.add_metadata("model", &self.model);
        status.add_metadata("type", "local");

        // Test connection with timing
        let start = Instant::now();
        match self
            .client
            .get(format!("{}/api/tags", self.endpoint))
            .timeout(Duration::from_secs(5))
            .send()
            .await
        {
            Ok(response) if response.status().is_success() => {
                let elapsed = start.elapsed();
                status.connection = ConnectionStatus::Connected;
                status.response_time_ms = Some(elapsed.as_millis() as u64);
                status.add_message(format!("Connected to Ollama at {}", self.endpoint));

                // Try to list models
                match self.list_models().await {
                    Ok(models) => {
                        status.models_available = Some(models.len());
                        // Take up to 5 models as sample
                        status.models = models.into_iter().take(5).collect();

                        if status.models_available == Some(0) {
                            status.add_message(
                                "⚠ No models downloaded. Run: ollama pull codellama:13b",
                            );
                        }
                    }
                    Err(e) => {
                        status.add_message(format!("Could not list models: {}", e));
                    }
                }
            }
            Ok(response) => {
                status.connection = ConnectionStatus::Failed;
                status.add_message(format!(
                    "Ollama responded with error: HTTP {}",
                    response.status()
                ));
            }
            Err(e) => {
                status.connection = ConnectionStatus::Failed;
                status.add_message(format!("Cannot connect to Ollama: {}", e));
                status.add_message("Hint: Make sure Ollama is running (ollama serve)");
                status.add_message(format!(
                    "Hint: Check if {} is the correct endpoint",
                    self.endpoint
                ));
            }
        }

        status.update_health();
        Ok(status)
    }
}

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

    #[test]
    fn test_provider_creation() {
        let provider = OllamaProvider::default();
        assert_eq!(provider.name(), "ollama");
        assert_eq!(provider.model(), "codellama:13b");
        assert_eq!(provider.endpoint(), "http://localhost:11434");
    }

    #[test]
    fn test_custom_provider() {
        let provider =
            OllamaProvider::new("http://custom:8080".to_string(), "mistral:7b".to_string());
        assert_eq!(provider.model(), "mistral:7b");
        assert_eq!(provider.endpoint(), "http://custom:8080");
    }

    #[test]
    fn test_cost_estimation() {
        let provider = OllamaProvider::default();
        assert_eq!(provider.estimate_cost("test prompt"), None);
    }

    #[tokio::test]
    async fn test_availability_check() {
        let provider = OllamaProvider::default();

        // This will fail if Ollama is not running, which is expected
        // We're just testing that the method doesn't panic
        let _ = provider.is_available();
    }

    #[tokio::test]
    #[ignore] // Only run with --ignored flag when Ollama is running
    async fn test_real_generation() {
        let provider = OllamaProvider::default();

        if !provider.is_available() {
            eprintln!("Skipping test: Ollama not available");
            return;
        }

        let options = GenerationOptions {
            max_tokens: Some(100),
            temperature: Some(0.7),
            timeout: Some(Duration::from_secs(60)),
        };

        let result = provider
            .generate("Write a one-line Python comment saying hello", options)
            .await;

        assert!(result.is_ok());
        let response = result.unwrap();
        assert!(!response.is_empty());
        println!("Generated: {}", response);
    }

    #[tokio::test]
    #[ignore] // Only run with --ignored flag when Ollama is running
    async fn test_real_model_listing() {
        let provider = OllamaProvider::default();

        if !provider.is_available() {
            eprintln!("Skipping test: Ollama not available");
            return;
        }

        let result = provider.list_models().await;
        assert!(result.is_ok());

        let models = result.unwrap();
        assert!(!models.is_empty());

        println!("Available models:");
        for model in models {
            println!("  - {} ({})", model.name, model.size_human_readable());
        }
    }
}