axonml-server 0.6.2

REST API server for AxonML Machine Learning Framework
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
//! Ollama Client — Local LLM Inference for AI Assistance
//!
//! HTTP client for a local Ollama service (default
//! `http://127.0.0.1:11434`, default model `qwen2.5-coder:7b`). Defines
//! `OllamaClient` (built on `reqwest::Client`) and the wire-level
//! `GenerateRequest` / `GenerateOptions` / `GenerateResponse` structs.
//! `generate_code` wraps prompts with a framework-aware system prompt and
//! parses code-fence blocks out of the response via
//! `extract_code_and_explanation`. `generate_markdown` is the docs variant.
//! `is_available` pings `/api/tags`; `generate` posts to `/api/generate` and
//! maps a 404 to `OllamaError::ModelNotFound`. `with_config` +
//! `validate_internal_url` enforce SSRF protection by restricting the base
//! URL to loopback or RFC1918 private networks over http/https. Errors flow
//! through the `OllamaError` enum (Request/ServiceUnavailable/ModelNotFound/
//! GenerationFailed/InvalidUrl). `CodeSuggestion` is the public result DTO.
//!
//! # File
//! `crates/axonml-server/src/llm/ollama.rs`
//!
//! # Author
//! Andrew Jewell Sr. — AutomataNexus LLC
//! ORCID: 0009-0005-2158-7060
//!
//! # Updated
//! April 16, 2026 11:15 PM EST
//!
//! # Disclaimer
//! Use at own risk. This software is provided "as is", without warranty of any
//! kind, express or implied. The author and AutomataNexus shall not be held
//! liable for any damages arising from the use of this software.

// =============================================================================
// Imports
// =============================================================================

use reqwest::Client;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use url::Url;

// =============================================================================
// Constants
// =============================================================================

/// Default Ollama endpoint
pub const DEFAULT_OLLAMA_URL: &str = "http://127.0.0.1:11434";

/// Default model for code generation
pub const DEFAULT_CODE_MODEL: &str = "qwen2.5-coder:7b";

// =============================================================================
// Error Type
// =============================================================================

#[derive(Error, Debug)]
pub enum OllamaError {
    #[error("HTTP request failed: {0}")]
    Request(#[from] reqwest::Error),

    #[error("Ollama service unavailable")]
    #[allow(dead_code)]
    ServiceUnavailable,

    #[error("Model not found: {0}")]
    ModelNotFound(String),

    #[error("Generation failed: {0}")]
    GenerationFailed(String),

    #[error("Invalid URL: {0}")]
    InvalidUrl(String),
}

// =============================================================================
// Wire Types — Requests and Responses
// =============================================================================

/// Ollama generate request
#[derive(Debug, Serialize)]
pub struct GenerateRequest {
    pub model: String,
    pub prompt: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub template: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<Vec<i64>>,
    pub stream: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub options: Option<GenerateOptions>,
}

/// Generation options
#[derive(Debug, Serialize, Default)]
pub struct GenerateOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_k: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub num_predict: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop: Option<Vec<String>>,
}

/// Ollama generate response
#[derive(Debug, Deserialize)]
pub struct GenerateResponse {
    pub model: String,
    pub response: String,
    #[allow(dead_code)]
    pub done: bool,
    #[serde(default)]
    #[allow(dead_code)]
    pub context: Option<Vec<i64>>,
    #[serde(default)]
    #[allow(dead_code)]
    pub total_duration: Option<u64>,
    #[serde(default)]
    #[allow(dead_code)]
    pub load_duration: Option<u64>,
    #[serde(default)]
    #[allow(dead_code)]
    pub prompt_eval_count: Option<u32>,
    #[serde(default)]
    pub eval_count: Option<u32>,
    #[serde(default)]
    #[allow(dead_code)]
    pub eval_duration: Option<u64>,
}

// =============================================================================
// Client
// =============================================================================

/// Ollama client for LLM inference
#[derive(Clone)]
pub struct OllamaClient {
    client: Client,
    base_url: String,
    model: String,
}

impl OllamaClient {
    // -------------------------------------------------------------------------
    // Construction
    // -------------------------------------------------------------------------

    /// Create a new Ollama client with default settings
    pub fn new() -> Self {
        Self {
            client: Client::new(),
            base_url: DEFAULT_OLLAMA_URL.to_string(),
            model: DEFAULT_CODE_MODEL.to_string(),
        }
    }

    /// Create with custom URL and model.
    /// Only allows connections to loopback/private network addresses to prevent SSRF.
    #[allow(dead_code)]
    pub fn with_config(base_url: &str, model: &str) -> Result<Self, OllamaError> {
        validate_internal_url(base_url)?;
        Ok(Self {
            client: Client::new(),
            base_url: base_url.to_string(),
            model: model.to_string(),
        })
    }

    // -------------------------------------------------------------------------
    // Health Check
    // -------------------------------------------------------------------------

    /// Check if Ollama service is available
    pub async fn is_available(&self) -> bool {
        let url = match Url::parse(&self.base_url).and_then(|u| u.join("/api/tags")) {
            Ok(u) => u,
            Err(_) => return false,
        };
        self.client.get(url).send().await.is_ok()
    }

    // -------------------------------------------------------------------------
    // High-Level Generation Helpers
    // -------------------------------------------------------------------------

    /// Generate code based on a prompt
    pub async fn generate_code(
        &self,
        prompt: &str,
        context: Option<&str>,
        include_imports: bool,
    ) -> Result<CodeSuggestion, OllamaError> {
        let system_prompt = build_code_system_prompt(include_imports);
        let full_prompt = if let Some(ctx) = context {
            format!("Context:\n```\n{}\n```\n\nTask: {}", ctx, prompt)
        } else {
            prompt.to_string()
        };

        let request = GenerateRequest {
            model: self.model.clone(),
            prompt: full_prompt,
            system: Some(system_prompt),
            template: None,
            context: None,
            stream: false,
            options: Some(GenerateOptions {
                temperature: Some(0.7),
                top_p: Some(0.9),
                num_predict: Some(1024),
                ..Default::default()
            }),
        };

        let response = self.generate(request).await?;

        // Extract code from response
        let (code, explanation) = extract_code_and_explanation(&response.response);

        Ok(CodeSuggestion {
            code,
            explanation,
            model: response.model,
            tokens_generated: response.eval_count.unwrap_or(0),
        })
    }

    /// Generate markdown content
    pub async fn generate_markdown(&self, prompt: &str) -> Result<CodeSuggestion, OllamaError> {
        let system_prompt =
            r#"You are a technical documentation writer for machine learning projects.
Generate clear, well-structured markdown documentation.
Use proper headings, lists, and code blocks where appropriate.
Be concise but comprehensive."#
                .to_string();

        let request = GenerateRequest {
            model: self.model.clone(),
            prompt: prompt.to_string(),
            system: Some(system_prompt),
            template: None,
            context: None,
            stream: false,
            options: Some(GenerateOptions {
                temperature: Some(0.7),
                num_predict: Some(512),
                ..Default::default()
            }),
        };

        let response = self.generate(request).await?;

        Ok(CodeSuggestion {
            code: response.response.trim().to_string(),
            explanation: None,
            model: response.model,
            tokens_generated: response.eval_count.unwrap_or(0),
        })
    }

    // -------------------------------------------------------------------------
    // Low-Level Generate Call
    // -------------------------------------------------------------------------

    /// Raw generate call to Ollama
    pub async fn generate(
        &self,
        request: GenerateRequest,
    ) -> Result<GenerateResponse, OllamaError> {
        // SECURITY: base_url is validated at construction time (new() uses hardcoded localhost,
        // with_config() validates via validate_internal_url). Build path from validated base.
        let url = Url::parse(&self.base_url)
            .and_then(|u| u.join("/api/generate"))
            .map_err(|e| OllamaError::InvalidUrl(e.to_string()))?;

        let response = self.client.post(url).json(&request).send().await?;

        if response.status() == reqwest::StatusCode::NOT_FOUND {
            return Err(OllamaError::ModelNotFound(request.model));
        }

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(OllamaError::GenerationFailed(format!(
                "Status {}: {}",
                status, body
            )));
        }

        let result: GenerateResponse = response.json().await?;
        Ok(result)
    }
}

impl Default for OllamaClient {
    fn default() -> Self {
        Self::new()
    }
}

// =============================================================================
// Result DTOs
// =============================================================================

/// Result of code generation
#[derive(Debug)]
pub struct CodeSuggestion {
    pub code: String,
    pub explanation: Option<String>,
    pub model: String,
    pub tokens_generated: u32,
}

// =============================================================================
// URL Validation (SSRF Protection)
// =============================================================================

/// SECURITY: Validate that a URL points to a loopback or private network address.
/// Prevents SSRF by ensuring we only connect to internal services.
#[allow(dead_code)]
fn validate_internal_url(url_str: &str) -> Result<(), OllamaError> {
    let parsed = Url::parse(url_str)
        .map_err(|e| OllamaError::InvalidUrl(format!("Invalid URL '{}': {}", url_str, e)))?;

    let scheme = parsed.scheme();
    if scheme != "http" && scheme != "https" {
        return Err(OllamaError::InvalidUrl(format!(
            "Only http/https schemes allowed, got '{}'",
            scheme
        )));
    }

    let host = parsed
        .host_str()
        .ok_or_else(|| OllamaError::InvalidUrl("URL must have a host".to_string()))?;

    // Allow loopback and private network addresses only
    let is_allowed = host == "localhost"
        || host == "127.0.0.1"
        || host == "::1"
        || host == "[::1]"
        || host.starts_with("10.")
        || host.starts_with("172.")
        || host.starts_with("192.168.");

    if !is_allowed {
        return Err(OllamaError::InvalidUrl(format!(
            "Only loopback/private network hosts allowed, got '{}'",
            host
        )));
    }

    Ok(())
}

// =============================================================================
// Prompt Construction and Response Parsing
// =============================================================================

/// Build system prompt for code generation
fn build_code_system_prompt(include_imports: bool) -> String {
    let import_instruction = if include_imports {
        "Include necessary imports at the top of the code."
    } else {
        "Do not include imports, assume they are already available."
    };

    format!(
        r#"You are an expert machine learning engineer and Python/Rust programmer.
You are helping a user write code for the AxonML machine learning framework.

AxonML is similar to PyTorch with these key modules:
- axonml.nn: Neural network layers (Linear, Conv2d, BatchNorm, ReLU, etc.)
- axonml.optim: Optimizers (SGD, Adam, AdamW)
- axonml.data: DataLoader, Dataset
- axonml.autograd: Automatic differentiation

Guidelines:
- Write clean, well-documented code
- {}
- Use type hints where appropriate
- Follow ML best practices
- Keep code concise but readable

Respond with ONLY the code, no explanations unless asked.
If you need to explain, put explanations in code comments."#,
        import_instruction
    )
}

/// Extract code and explanation from LLM response
fn extract_code_and_explanation(response: &str) -> (String, Option<String>) {
    let response = response.trim();

    // Check if response contains code blocks
    if response.contains("```") {
        let mut code_parts = Vec::new();
        let mut explanation_parts = Vec::new();
        let mut in_code_block = false;
        let mut current_block = String::new();

        for line in response.lines() {
            if line.starts_with("```") {
                if in_code_block {
                    // End of code block
                    code_parts.push(current_block.trim().to_string());
                    current_block.clear();
                }
                in_code_block = !in_code_block;
            } else if in_code_block {
                current_block.push_str(line);
                current_block.push('\n');
            } else {
                let trimmed = line.trim();
                if !trimmed.is_empty() {
                    explanation_parts.push(trimmed.to_string());
                }
            }
        }

        let code = code_parts.join("\n\n");
        let explanation = if explanation_parts.is_empty() {
            None
        } else {
            Some(explanation_parts.join(" "))
        };

        (code, explanation)
    } else {
        // No code blocks, treat entire response as code
        (response.to_string(), None)
    }
}

// =============================================================================
// Tests
// =============================================================================

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

    #[test]
    fn test_extract_code_simple() {
        let response = "def hello():\n    print('Hello')";
        let (code, explanation) = extract_code_and_explanation(response);
        assert_eq!(code, response);
        assert!(explanation.is_none());
    }

    #[test]
    fn test_extract_code_with_blocks() {
        let response = "Here's the code:\n```python\ndef hello():\n    print('Hello')\n```\nThis prints hello.";
        let (code, explanation) = extract_code_and_explanation(response);
        assert!(code.contains("def hello()"));
        assert!(explanation.is_some());
        assert!(explanation.unwrap().contains("prints hello"));
    }
}