agentic-core 0.1.3

Core AI orchestration library for Ruixen - the collaborative AI agent framework
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
use anyhow::Result;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::time::Duration;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AtomicNote {
    pub header_tags: Vec<String>,
    pub body_text: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OllamaModel {
    pub name: String,
    pub size: String,
    pub modified: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LocalModel {
    pub name: String,
    pub id: String,
    pub provider: LocalProvider,
    pub size: String,
    pub modified: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum LocalProvider {
    Ollama,
    LMStudio,
    OpenAI,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenRouterModel {
    pub id: String,
    pub name: String,
    pub description: String,
    pub pricing: ModelPricing,
    pub context_length: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelPricing {
    pub prompt: String,
    pub completion: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct OllamaListResponse {
    models: Vec<OllamaModelRaw>,
}

#[derive(Debug, Serialize, Deserialize)]
struct OllamaModelRaw {
    name: String,
    size: i64,
    modified_at: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct OpenRouterListResponse {
    data: Vec<OpenRouterModelRaw>,
}

#[derive(Debug, Serialize, Deserialize)]
struct OpenRouterModelRaw {
    id: String,
    name: String,
    description: Option<String>,
    pricing: ModelPricingRaw,
    context_length: u32,
}

#[derive(Debug, Serialize, Deserialize)]
struct ModelPricingRaw {
    prompt: String,
    completion: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct OpenAIListResponse {
    data: Vec<OpenAIModelRaw>,
}

#[derive(Debug, Serialize, Deserialize)]
struct OpenAIModelRaw {
    id: String,
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    created: Option<u64>,
}

pub struct ModelValidator {
    client: Client,
}

impl ModelValidator {
    pub fn new() -> Self {
        let client = Client::builder()
            .timeout(Duration::from_secs(5))
            .build()
            .unwrap_or_default();

        Self { client }
    }

    pub async fn detect_provider_type(&self, endpoint: &str) -> LocalProvider {
        // Try OpenAI/LM Studio API first for port 1234
        if endpoint.to_lowercase().contains("1234")
            && self.test_openai_endpoint(endpoint).await.is_ok()
        {
            return LocalProvider::LMStudio;
        }

        // Try Ollama API
        if self.test_ollama_endpoint(endpoint).await.is_ok() {
            return LocalProvider::Ollama;
        }

        // Try generic OpenAI API
        if self.test_openai_endpoint(endpoint).await.is_ok() {
            return LocalProvider::OpenAI;
        }

        // Default to Ollama if all detection fails
        LocalProvider::Ollama
    }

    async fn test_ollama_endpoint(&self, endpoint: &str) -> Result<()> {
        let url = if endpoint.starts_with("http") {
            format!("{}/api/tags", endpoint)
        } else {
            format!("http://{}/api/tags", endpoint)
        };

        let response = self.client.get(&url).send().await?;
        if response.status().is_success() {
            Ok(())
        } else {
            Err(anyhow::anyhow!("Ollama endpoint not accessible"))
        }
    }

    async fn test_openai_endpoint(&self, endpoint: &str) -> Result<()> {
        let normalized_endpoint = endpoint.to_lowercase();
        let url = if normalized_endpoint.starts_with("http") {
            format!("{}/v1/models", normalized_endpoint)
        } else {
            format!("http://{}/v1/models", normalized_endpoint)
        };

        let response = self.client.get(&url).send().await?;
        if response.status().is_success() {
            Ok(())
        } else {
            Err(anyhow::anyhow!("OpenAI endpoint not accessible"))
        }
    }

    pub async fn fetch_local_models(&self, endpoint: &str) -> Result<Vec<LocalModel>> {
        let provider = self.detect_provider_type(endpoint).await;

        match provider {
            LocalProvider::Ollama => {
                let ollama_models = self.fetch_ollama_models(endpoint).await?;
                let local_models = ollama_models
                    .into_iter()
                    .map(|model| LocalModel {
                        name: model.name.clone(),
                        id: model.name,
                        provider: LocalProvider::Ollama,
                        size: model.size,
                        modified: model.modified,
                    })
                    .collect();
                Ok(local_models)
            }
            LocalProvider::LMStudio | LocalProvider::OpenAI => {
                self.fetch_openai_models(endpoint).await
            }
        }
    }

    pub async fn fetch_ollama_models(&self, endpoint: &str) -> Result<Vec<OllamaModel>> {
        let url = if endpoint.starts_with("http") {
            format!("{}/api/tags", endpoint)
        } else {
            format!("http://{}/api/tags", endpoint)
        };

        let response = self.client.get(&url).send().await?;

        if !response.status().is_success() {
            return Err(anyhow::anyhow!("Ollama endpoint not accessible"));
        }

        let ollama_response: OllamaListResponse = response.json().await?;

        let models = ollama_response
            .models
            .into_iter()
            .map(|raw| OllamaModel {
                name: raw.name,
                size: format_size(raw.size),
                modified: format_relative_time(&raw.modified_at),
            })
            .collect();

        Ok(models)
    }

    pub async fn fetch_openrouter_models(&self, api_key: &str) -> Result<Vec<OpenRouterModel>> {
        let url = "https://openrouter.ai/api/v1/models";

        let response = self
            .client
            .get(url)
            .header("Authorization", format!("Bearer {}", api_key))
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(anyhow::anyhow!(
                "OpenRouter API not accessible or invalid API key"
            ));
        }

        let openrouter_response: OpenRouterListResponse = response.json().await?;

        let mut models: Vec<OpenRouterModel> = openrouter_response
            .data
            .into_iter()
            .map(|raw| OpenRouterModel {
                id: raw.id,
                name: raw.name,
                description: raw
                    .description
                    .unwrap_or_else(|| "No description available".to_string()),
                pricing: ModelPricing {
                    prompt: raw.pricing.prompt,
                    completion: raw.pricing.completion,
                },
                context_length: raw.context_length,
            })
            .collect();

        // Sort models: free models first, then paid models
        models.sort_by(|a, b| {
            let a_is_free = a.pricing.prompt == "0" && a.pricing.completion == "0";
            let b_is_free = b.pricing.prompt == "0" && b.pricing.completion == "0";

            match (a_is_free, b_is_free) {
                (true, false) => std::cmp::Ordering::Less, // Free comes first
                (false, true) => std::cmp::Ordering::Greater, // Paid comes after
                _ => a.name.cmp(&b.name),                  // Same type, sort by name
            }
        });

        Ok(models)
    }

    pub async fn fetch_openai_models(&self, endpoint: &str) -> Result<Vec<LocalModel>> {
        let url = if endpoint.starts_with("http") {
            format!("{}/v1/models", endpoint)
        } else {
            format!("http://{}/v1/models", endpoint)
        };

        let response = self.client.get(&url).send().await?;

        if !response.status().is_success() {
            return Err(anyhow::anyhow!("OpenAI/LM Studio endpoint not accessible"));
        }

        let openai_response: OpenAIListResponse = response.json().await?;

        let provider = if endpoint.contains("1234") {
            LocalProvider::LMStudio
        } else {
            LocalProvider::OpenAI
        };

        let models = openai_response
            .data
            .into_iter()
            .map(|raw| LocalModel {
                name: raw.name.unwrap_or_else(|| raw.id.clone()),
                id: raw.id,
                provider: provider.clone(),
                size: "Unknown".to_string(),
                modified: "recently".to_string(),
            })
            .collect();

        Ok(models)
    }

    pub async fn validate_local_endpoint(&self, endpoint: &str, model: &str) -> Result<()> {
        let provider = self.detect_provider_type(endpoint).await;

        match provider {
            LocalProvider::Ollama => {
                let url = if endpoint.starts_with("http") {
                    format!("{}/api/tags", endpoint)
                } else {
                    format!("http://{}/api/tags", endpoint)
                };

                let response = self.client.get(&url).send().await?;
                if !response.status().is_success() {
                    return Err(anyhow::anyhow!("Local endpoint not accessible"));
                }

                let models: Value = response.json().await?;
                if let Some(models_array) = models.get("models").and_then(|m| m.as_array()) {
                    let model_exists = models_array.iter().any(|m| {
                        m.get("name")
                            .and_then(|name| name.as_str())
                            .map(|name| name == model)
                            .unwrap_or(false)
                    });

                    if model_exists {
                        Ok(())
                    } else {
                        Err(anyhow::anyhow!(
                            "Model '{}' not found on local endpoint",
                            model
                        ))
                    }
                } else {
                    Err(anyhow::anyhow!(
                        "Invalid response format from local endpoint"
                    ))
                }
            }
            LocalProvider::LMStudio | LocalProvider::OpenAI => {
                let url = if endpoint.starts_with("http") {
                    format!("{}/v1/models", endpoint)
                } else {
                    format!("http://{}/v1/models", endpoint)
                };

                let response = self.client.get(&url).send().await?;
                if !response.status().is_success() {
                    return Err(anyhow::anyhow!("Local endpoint not accessible"));
                }

                let models: Value = response.json().await?;
                if let Some(models_array) = models.get("data").and_then(|m| m.as_array()) {
                    let model_exists = models_array.iter().any(|m| {
                        m.get("id")
                            .and_then(|id| id.as_str())
                            .map(|id| id == model)
                            .unwrap_or(false)
                    });

                    if model_exists {
                        Ok(())
                    } else {
                        Err(anyhow::anyhow!(
                            "Model '{}' not found on local endpoint",
                            model
                        ))
                    }
                } else {
                    Err(anyhow::anyhow!(
                        "Invalid response format from local endpoint"
                    ))
                }
            }
        }
    }

    pub async fn validate_cloud_endpoint(&self, api_key: &str, model: &str) -> Result<()> {
        let url = "https://openrouter.ai/api/v1/models";

        let response = self
            .client
            .get(url)
            .header("Authorization", format!("Bearer {}", api_key))
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(anyhow::anyhow!(
                "Cloud API key invalid or endpoint not accessible"
            ));
        }

        let models: Value = response.json().await?;

        if let Some(models_array) = models.get("data").and_then(|m| m.as_array()) {
            let model_exists = models_array.iter().any(|m| {
                m.get("id")
                    .and_then(|id| id.as_str())
                    .map(|id| id == model)
                    .unwrap_or(false)
            });

            if model_exists {
                Ok(())
            } else {
                Err(anyhow::anyhow!("Model '{}' not found in OpenRouter", model))
            }
        } else {
            Err(anyhow::anyhow!("Invalid response format from OpenRouter"))
        }
    }

    pub async fn test_local_generation(&self, endpoint: &str, model: &str) -> Result<()> {
        let url = if endpoint.starts_with("http") {
            format!("{}/api/generate", endpoint)
        } else {
            format!("http://{}/api/generate", endpoint)
        };

        let payload = serde_json::json!({
            "model": model,
            "prompt": "Hello",
            "stream": false,
            "options": {
                "num_predict": 1
            }
        });

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

        if response.status().is_success() {
            Ok(())
        } else {
            Err(anyhow::anyhow!(
                "Failed to generate response from local model"
            ))
        }
    }

    pub async fn test_cloud_generation(&self, api_key: &str, model: &str) -> Result<()> {
        let url = "https://openrouter.ai/api/v1/chat/completions";

        let payload = serde_json::json!({
            "model": model,
            "messages": [{"role": "user", "content": "Hello"}],
            "max_tokens": 1
        });

        let response = self
            .client
            .post(url)
            .header("Authorization", format!("Bearer {}", api_key))
            .header("Content-Type", "application/json")
            .json(&payload)
            .send()
            .await?;

        if response.status().is_success() {
            Ok(())
        } else {
            Err(anyhow::anyhow!(
                "Failed to generate response from cloud model"
            ))
        }
    }
}

#[derive(Serialize)]
struct LocalGenerationRequest<'a> {
    model: &'a str,
    prompt: &'a str,
    stream: bool,
}

#[derive(Deserialize)]
struct LocalGenerationResponse {
    response: String,
}

pub async fn call_local_model(
    endpoint: &str,
    model: &str,
    prompt: &str,
) -> Result<String, anyhow::Error> {
    let validator = ModelValidator::new();
    let provider = validator.detect_provider_type(endpoint).await;

    match provider {
        LocalProvider::Ollama => call_ollama_model(endpoint, model, prompt).await,
        LocalProvider::LMStudio | LocalProvider::OpenAI => {
            call_openai_model(endpoint, model, prompt).await
        }
    }
}

pub async fn call_ollama_model(
    endpoint: &str,
    model: &str,
    prompt: &str,
) -> Result<String, anyhow::Error> {
    let client = Client::new();
    let url = if endpoint.starts_with("http") {
        format!("{}/api/generate", endpoint)
    } else {
        format!("http://{}/api/generate", endpoint)
    };

    let payload = LocalGenerationRequest {
        model,
        prompt,
        stream: false,
    };

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

    if response.status().is_success() {
        let gen_response: LocalGenerationResponse = response.json().await?;
        Ok(gen_response.response)
    } else {
        Err(anyhow::anyhow!(
            "Failed to get response from local model. Status: {}",
            response.status()
        ))
    }
}

#[derive(Serialize)]
struct OpenAIGenerationRequest<'a> {
    model: &'a str,
    messages: Vec<serde_json::Value>,
    max_tokens: u32,
    temperature: f32,
}

#[derive(Deserialize)]
struct OpenAIGenerationResponse {
    choices: Vec<OpenAIChoice>,
}

#[derive(Deserialize)]
struct OpenAIChoice {
    message: OpenAIMessage,
}

#[derive(Deserialize)]
struct OpenAIMessage {
    content: String,
}

pub async fn call_openai_model(
    endpoint: &str,
    model: &str,
    prompt: &str,
) -> Result<String, anyhow::Error> {
    let client = Client::new();
    let url = if endpoint.starts_with("http") {
        format!("{}/v1/chat/completions", endpoint)
    } else {
        format!("http://{}/v1/chat/completions", endpoint)
    };

    let payload = OpenAIGenerationRequest {
        model,
        messages: vec![serde_json::json!({
            "role": "user",
            "content": prompt
        })],
        max_tokens: 2000,
        temperature: 0.7,
    };

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

    if response.status().is_success() {
        let gen_response: OpenAIGenerationResponse = response.json().await?;
        if let Some(choice) = gen_response.choices.first() {
            Ok(choice.message.content.clone())
        } else {
            Err(anyhow::anyhow!("No response choices from OpenAI model"))
        }
    } else {
        let status = response.status();
        let error_text = response
            .text()
            .await
            .unwrap_or_else(|_| "Unknown error".to_string());
        Err(anyhow::anyhow!(
            "Failed to get response from OpenAI model. Status: {}. Error: {}",
            status,
            error_text
        ))
    }
}

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

fn format_size(bytes: i64) -> String {
    const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
    let mut size = bytes as f64;
    let mut unit_index = 0;

    while size >= 1024.0 && unit_index < UNITS.len() - 1 {
        size /= 1024.0;
        unit_index += 1;
    }

    if unit_index == 0 {
        format!("{} {}", size as i64, UNITS[unit_index])
    } else {
        format!("{:.1} {}", size, UNITS[unit_index])
    }
}

fn format_relative_time(_iso_time: &str) -> String {
    // For now, just return a simple format
    // Parse ISO time and return relative time
    "recently".to_string()
}