herolib-ai 0.3.13

AI client with multi-provider support (Groq, OpenRouter, SambaNova) and automatic failover
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
//! Model test utility for herolib-ai.
//!
//! This binary tests model availability across all configured providers.
//! It queries provider APIs for available models, validates our model mappings,
//! and runs a simple "whoami" test on each model.

use std::collections::HashMap;
use std::time::{Duration, Instant};

use herolib_ai::{AiClient, Message, Model, Provider, ProviderConfig};

/// Result of testing a single model on a provider.
#[derive(Debug)]
struct ModelTestResult {
    model: Model,
    provider: Provider,
    provider_model_id: String,
    success: bool,
    response_time_ms: u64,
    error: Option<String>,
    response_preview: Option<String>,
}

/// Result of querying provider's model list.
#[allow(dead_code)]
#[derive(Debug)]
#[allow(dead_code)]
struct ProviderModelsResult {
    provider: Provider,
    available: bool,
    models: Vec<String>,
    error: Option<String>,
}

/// Fetches available models from OpenRouter.
fn fetch_openrouter_models(api_key: &str) -> Result<Vec<String>, String> {
    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_global(Some(Duration::from_secs(30)))
            .build(),
    );

    let response = agent
        .get("https://openrouter.ai/api/v1/models")
        .header("Authorization", &format!("Bearer {}", api_key))
        .call()
        .map_err(|e| format!("HTTP error: {}", e))?;

    let body = response
        .into_body()
        .read_to_string()
        .map_err(|e| format!("Read error: {}", e))?;

    let json: serde_json::Value =
        serde_json::from_str(&body).map_err(|e| format!("JSON parse error: {}", e))?;

    let models = json["data"]
        .as_array()
        .map(|arr| {
            arr.iter()
                .filter_map(|m| m["id"].as_str().map(|s| s.to_string()))
                .collect()
        })
        .unwrap_or_default();

    Ok(models)
}

/// Fetches available models from Groq.
fn fetch_groq_models(api_key: &str) -> Result<Vec<String>, String> {
    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_global(Some(Duration::from_secs(30)))
            .build(),
    );

    let response = agent
        .get("https://api.groq.com/openai/v1/models")
        .header("Authorization", &format!("Bearer {}", api_key))
        .call()
        .map_err(|e| format!("HTTP error: {}", e))?;

    let body = response
        .into_body()
        .read_to_string()
        .map_err(|e| format!("Read error: {}", e))?;

    let json: serde_json::Value =
        serde_json::from_str(&body).map_err(|e| format!("JSON parse error: {}", e))?;

    let models = json["data"]
        .as_array()
        .map(|arr| {
            arr.iter()
                .filter_map(|m| m["id"].as_str().map(|s| s.to_string()))
                .collect()
        })
        .unwrap_or_default();

    Ok(models)
}

/// Fetches available models from SambaNova.
fn fetch_sambanova_models(api_key: &str) -> Result<Vec<String>, String> {
    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_global(Some(Duration::from_secs(30)))
            .build(),
    );

    let response = agent
        .get("https://api.sambanova.ai/v1/models")
        .header("Authorization", &format!("Bearer {}", api_key))
        .call()
        .map_err(|e| format!("HTTP error: {}", e))?;

    let body = response
        .into_body()
        .read_to_string()
        .map_err(|e| format!("Read error: {}", e))?;

    let json: serde_json::Value =
        serde_json::from_str(&body).map_err(|e| format!("JSON parse error: {}", e))?;

    let models = json["data"]
        .as_array()
        .map(|arr| {
            arr.iter()
                .filter_map(|m| m["id"].as_str().map(|s| s.to_string()))
                .collect()
        })
        .unwrap_or_default();

    Ok(models)
}

/// Tests a single model on a specific provider.
fn test_model_on_provider(
    provider: Provider,
    api_key: &str,
    model: Model,
    model_id: &str,
) -> ModelTestResult {
    let client =
        AiClient::new().with_provider(ProviderConfig::new(provider, api_key).with_timeout(60));

    let messages = vec![
        Message::system("You are a helpful assistant. Answer in one short sentence."),
        Message::user("Who are you? Just say your name/model."),
    ];

    let start = Instant::now();

    let result = client.chat_with_options(model, messages, Some(0.1), Some(50));
    let elapsed = start.elapsed().as_millis() as u64;

    match result {
        Ok(response) => {
            let content = response.content().unwrap_or("").to_string();
            let preview = if content.len() > 100 {
                format!("{}...", &content[..100])
            } else {
                content
            };

            ModelTestResult {
                model,
                provider,
                provider_model_id: model_id.to_string(),
                success: true,
                response_time_ms: elapsed,
                error: None,
                response_preview: Some(preview),
            }
        }
        Err(e) => ModelTestResult {
            model,
            provider,
            provider_model_id: model_id.to_string(),
            success: false,
            response_time_ms: elapsed,
            error: Some(e.to_string()),
            response_preview: None,
        },
    }
}

/// Prints a section header.
fn print_header(title: &str) {
    println!("\n{}", "=".repeat(70));
    println!("{}", title);
    println!("{}", "=".repeat(70));
}

/// Prints a sub-section header.
fn print_subheader(title: &str) {
    println!("\n{}", "-".repeat(50));
    println!("{}", title);
    println!("{}", "-".repeat(50));
}

fn main() {
    println!("herolib-ai Model Test Utility");
    println!("Testing model availability across all providers\n");

    // Collect API keys from environment
    let mut api_keys: HashMap<Provider, String> = HashMap::new();

    if let Ok(key) = std::env::var("GROQ_API_KEY") {
        if !key.is_empty() {
            api_keys.insert(Provider::Groq, key);
        }
    }
    if let Ok(key) = std::env::var("OPENROUTER_API_KEY") {
        if !key.is_empty() {
            api_keys.insert(Provider::OpenRouter, key);
        }
    }
    if let Ok(key) = std::env::var("SAMBANOVA_API_KEY") {
        if !key.is_empty() {
            api_keys.insert(Provider::SambaNova, key);
        }
    }

    if api_keys.is_empty() {
        eprintln!("ERROR: No API keys configured!");
        eprintln!("Set at least one of:");
        eprintln!("  - GROQ_API_KEY");
        eprintln!("  - OPENROUTER_API_KEY");
        eprintln!("  - SAMBANOVA_API_KEY");
        std::process::exit(1);
    }

    println!("Configured providers:");
    for provider in api_keys.keys() {
        println!("  - {}", provider);
    }

    // Phase 1: Query provider model lists
    print_header("Phase 1: Querying Provider Model Lists");

    let mut provider_models: HashMap<Provider, ProviderModelsResult> = HashMap::new();
    let mut model_list_available = false;

    for (provider, api_key) in &api_keys {
        print!("Querying {}... ", provider);

        let result = match provider {
            Provider::Groq => fetch_groq_models(api_key),
            Provider::OpenRouter => fetch_openrouter_models(api_key),
            Provider::SambaNova => fetch_sambanova_models(api_key),
        };

        match result {
            Ok(models) => {
                println!("OK ({} models)", models.len());
                model_list_available = true;
                provider_models.insert(
                    *provider,
                    ProviderModelsResult {
                        provider: *provider,
                        available: true,
                        models,
                        error: None,
                    },
                );
            }
            Err(e) => {
                println!("FAILED: {}", e);
                provider_models.insert(
                    *provider,
                    ProviderModelsResult {
                        provider: *provider,
                        available: false,
                        models: vec![],
                        error: Some(e),
                    },
                );
            }
        }
    }

    // Phase 2: Validate model mappings
    if model_list_available {
        print_header("Phase 2: Validating Model Mappings");

        let mut mapping_errors: Vec<String> = Vec::new();

        for model in Model::all() {
            let info = model.info();
            println!("\n{} ({}):", model.name(), info.description);

            for mapping in &info.providers {
                if let Some(provider_result) = provider_models.get(&mapping.provider) {
                    if provider_result.available {
                        let found = provider_result.models.iter().any(|m| m == mapping.model_id);

                        if found {
                            println!("  {} {} -> OK", mapping.provider, mapping.model_id);
                        } else {
                            println!("  {} {} -> NOT FOUND", mapping.provider, mapping.model_id);
                            mapping_errors.push(format!(
                                "{}: {} not found on {}",
                                model.name(),
                                mapping.model_id,
                                mapping.provider
                            ));
                        }
                    } else {
                        println!(
                            "  {} {} -> SKIPPED (provider unavailable)",
                            mapping.provider, mapping.model_id
                        );
                    }
                } else {
                    println!(
                        "  {} {} -> SKIPPED (no API key)",
                        mapping.provider, mapping.model_id
                    );
                }
            }
        }

        if !mapping_errors.is_empty() {
            print_subheader("Mapping Errors");
            for error in &mapping_errors {
                println!("  ERROR: {}", error);
            }
        }
    } else {
        println!("\nSkipping model validation (no provider model lists available)");
    }

    // Phase 3: Test each model with whoami
    print_header("Phase 3: Testing Models with 'whoami' Query");

    let mut test_results: Vec<ModelTestResult> = Vec::new();
    let mut tested_count = 0;
    let mut success_count = 0;

    for model in Model::all() {
        let info = model.info();
        print_subheader(&format!("Testing: {}", model.name()));

        for mapping in &info.providers {
            if let Some(api_key) = api_keys.get(&mapping.provider) {
                print!("  {} ({})... ", mapping.provider, mapping.model_id);

                let result =
                    test_model_on_provider(mapping.provider, api_key, *model, mapping.model_id);

                tested_count += 1;

                if result.success {
                    success_count += 1;
                    println!("OK ({}ms)", result.response_time_ms);
                    if let Some(preview) = &result.response_preview {
                        println!("    Response: {}", preview);
                    }
                } else {
                    println!("FAILED");
                    if let Some(error) = &result.error {
                        println!("    Error: {}", error);
                    }
                }

                test_results.push(result);
            }
        }
    }

    // Final Report
    print_header("Final Report");

    println!("\nProvider Status:");
    for (provider, result) in &provider_models {
        let status = if result.available { "OK" } else { "FAILED" };
        println!(
            "  {}: {} ({} models)",
            provider,
            status,
            result.models.len()
        );
    }

    println!("\nTest Summary:");
    println!("  Total tests: {}", tested_count);
    println!("  Successful:  {}", success_count);
    println!("  Failed:      {}", tested_count - success_count);
    println!(
        "  Success rate: {:.1}%",
        if tested_count > 0 {
            (success_count as f64 / tested_count as f64) * 100.0
        } else {
            0.0
        }
    );

    println!("\nDetailed Results by Model:");
    for model in Model::all() {
        let model_results: Vec<&ModelTestResult> =
            test_results.iter().filter(|r| r.model == *model).collect();

        if model_results.is_empty() {
            continue;
        }

        let successes = model_results.iter().filter(|r| r.success).count();
        let total = model_results.len();

        println!("  {} - {}/{} providers OK", model.name(), successes, total);

        for result in model_results {
            let status = if result.success { "OK" } else { "FAIL" };
            println!(
                "    {} {}: {} ({}ms)",
                result.provider, result.provider_model_id, status, result.response_time_ms
            );
        }
    }

    // Exit with error if any tests failed
    if success_count < tested_count {
        println!("\nSome tests failed!");
        std::process::exit(1);
    } else {
        println!("\nAll tests passed!");
    }
}