cllient 0.2.1

A comprehensive Rust client for LLM APIs with unified interface and model management
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
//! Bidirectional index for service ↔ model relationships.
//!
//! This module provides eager indexing of the registry, built at initialization time.
//! It enables fast lookups in both directions:
//! - model → service (which service does this model use?)
//! - service → models (which models use this service?)

use std::collections::HashMap;
use std::path::PathBuf;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::client::ConfigProvider;
use crate::config::VerificationStatus;
use crate::error::{ClientError, ConfigError, Result};

/// A broken reference where a model references a non-existent service.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrokenReference {
    /// The model ID that has the broken reference
    pub model_id: String,
    /// The service name that was referenced but doesn't exist
    pub referenced_service: String,
    /// Optional path to the config file (if available)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub config_path: Option<PathBuf>,
}

impl std::fmt::Display for BrokenReference {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Model '{}' references non-existent service '{}'",
            self.model_id, self.referenced_service
        )?;
        if let Some(path) = &self.config_path {
            write!(f, " (in {})", path.display())?;
        }
        Ok(())
    }
}

/// Bidirectional index for the model registry.
///
/// This structure is built once at registry initialization and provides
/// O(1) lookups for common queries.
#[derive(Debug, Clone, Default)]
pub struct RegistryIndex {
    /// Forward mapping: model_id → service_name
    model_to_service: HashMap<String, String>,

    /// Reverse mapping: service_name → list of model_ids
    service_to_models: HashMap<String, Vec<String>>,

    /// Family grouping: family_name → list of model_ids
    family_to_models: HashMap<String, Vec<String>>,

    /// Model status grouping: status → list of model_ids
    status_to_models: HashMap<VerificationStatus, Vec<String>>,

    /// Service status grouping: status → list of service_names
    service_status_to_services: HashMap<VerificationStatus, Vec<String>>,

    /// Service name → verification status
    service_statuses: HashMap<String, VerificationStatus>,

    /// Services that have no models using them
    orphan_services: Vec<String>,

    /// Models that reference non-existent services
    broken_refs: Vec<BrokenReference>,

    /// All known service names
    all_services: Vec<String>,

    /// All known model IDs
    all_models: Vec<String>,
}

impl RegistryIndex {
    /// Build the index from a config provider.
    ///
    /// This iterates through all services and models once to build
    /// all the lookup tables.
    pub fn build<P: ConfigProvider>(provider: &P) -> Self {
        use std::collections::hash_map::Entry;

        let mut index = Self::default();

        // Collect all services - convert to owned strings once
        let services: Vec<String> = provider
            .list_services()
            .into_iter()
            .map(String::from)
            .collect();

        // Pre-allocate capacity based on expected sizes
        index.service_to_models.reserve(services.len());
        index.service_statuses.reserve(services.len());

        // Initialize service_to_models with empty vecs and track service statuses
        for service_name in &services {
            index
                .service_to_models
                .insert(service_name.clone(), Vec::new());

            // Get service status
            if let Ok(service_config) = provider.get_service(service_name) {
                let status = service_config.service.status.clone();
                index
                    .service_statuses
                    .insert(service_name.clone(), status.clone());
                index
                    .service_status_to_services
                    .entry(status)
                    .or_default()
                    .push(service_name.clone());
            }
        }

        // Store all_services after we're done using services
        index.all_services = services;

        // Collect all models and build mappings
        let model_ids: Vec<&str> = provider.list_models();
        index.all_models.reserve(model_ids.len());
        index.model_to_service.reserve(model_ids.len());

        for model_id in model_ids {
            let model_id_owned = model_id.to_string();

            if let Ok(model_config) = provider.get_model(model_id) {
                let service_name = &model_config.model.service;
                let family = &model_config.model.family;
                let status = &model_config.model.status;

                // Forward mapping: model → service
                index
                    .model_to_service
                    .insert(model_id_owned.clone(), service_name.clone());

                // Reverse mapping: service → models (use entry API to avoid double lookup)
                match index.service_to_models.entry(service_name.clone()) {
                    Entry::Occupied(mut entry) => {
                        entry.get_mut().push(model_id_owned.clone());
                    }
                    Entry::Vacant(_) => {
                        // Service doesn't exist - this is a broken reference
                        index.broken_refs.push(BrokenReference {
                            model_id: model_id_owned.clone(),
                            referenced_service: service_name.clone(),
                            config_path: None,
                        });
                    }
                }

                // Family grouping
                index
                    .family_to_models
                    .entry(family.clone())
                    .or_default()
                    .push(model_id_owned.clone());

                // Status grouping
                index
                    .status_to_models
                    .entry(status.clone())
                    .or_default()
                    .push(model_id_owned.clone());
            }

            index.all_models.push(model_id_owned);
        }

        // Find orphan services (services with no models) and sort in one pass
        index.orphan_services = index
            .service_to_models
            .iter()
            .filter_map(|(service, models)| {
                if models.is_empty() {
                    Some(service.clone())
                } else {
                    None
                }
            })
            .collect();
        index.orphan_services.sort_unstable();

        // Sort for consistent ordering (use sort_unstable for better performance)
        index.all_models.sort_unstable();
        for models in index.service_to_models.values_mut() {
            models.sort_unstable();
        }
        for models in index.family_to_models.values_mut() {
            models.sort_unstable();
        }
        for models in index.status_to_models.values_mut() {
            models.sort_unstable();
        }

        index
    }

    /// Check if the index has any broken references.
    pub fn has_broken_refs(&self) -> bool {
        !self.broken_refs.is_empty()
    }

    /// Get all broken references.
    pub fn broken_refs(&self) -> &[BrokenReference] {
        &self.broken_refs
    }

    /// Get all orphan services (services with no models).
    pub fn orphan_services(&self) -> &[String] {
        &self.orphan_services
    }

    /// Check if a service has any models.
    pub fn service_has_models(&self, service: &str) -> bool {
        self.service_to_models
            .get(service)
            .map(|models| !models.is_empty())
            .unwrap_or(false)
    }

    /// Get the service name for a model.
    pub fn service_for_model(&self, model_id: &str) -> Option<&str> {
        self.model_to_service.get(model_id).map(String::as_str)
    }

    /// Get all models for a service.
    pub fn models_for_service(&self, service: &str) -> &[String] {
        self.service_to_models
            .get(service)
            .map(Vec::as_slice)
            .unwrap_or(&[])
    }

    /// Get all models in a family.
    pub fn models_in_family(&self, family: &str) -> &[String] {
        self.family_to_models
            .get(family)
            .map(Vec::as_slice)
            .unwrap_or(&[])
    }

    /// Get all models with a specific status.
    pub fn models_with_status(&self, status: &VerificationStatus) -> &[String] {
        self.status_to_models
            .get(status)
            .map(Vec::as_slice)
            .unwrap_or(&[])
    }

    /// Get the verification status of a service.
    pub fn service_status(&self, service: &str) -> Option<&VerificationStatus> {
        self.service_statuses.get(service)
    }

    /// Get all services with a specific verification status.
    pub fn services_with_status(&self, status: &VerificationStatus) -> &[String] {
        self.service_status_to_services
            .get(status)
            .map(Vec::as_slice)
            .unwrap_or(&[])
    }

    /// Get verified services.
    pub fn verified_services(&self) -> &[String] {
        self.services_with_status(&VerificationStatus::Verified)
    }

    /// Get unverified services.
    pub fn unverified_services(&self) -> &[String] {
        self.services_with_status(&VerificationStatus::Unverified)
    }

    /// Get all known services.
    pub fn all_services(&self) -> &[String] {
        &self.all_services
    }

    /// Get all known models.
    pub fn all_models(&self) -> &[String] {
        &self.all_models
    }

    /// Get all families.
    pub fn all_families(&self) -> Vec<&str> {
        let mut families: Vec<&str> = self.family_to_models.keys().map(String::as_str).collect();
        families.sort_unstable();
        families
    }

    /// Get count of models per service.
    pub fn model_counts_by_service(&self) -> HashMap<&str, usize> {
        self.service_to_models
            .iter()
            .map(|(k, v)| (k.as_str(), v.len()))
            .collect()
    }

    /// Get count of models per status.
    pub fn model_counts_by_status(&self) -> HashMap<VerificationStatus, usize> {
        self.status_to_models
            .iter()
            .map(|(k, v)| (k.clone(), v.len()))
            .collect()
    }

    /// Validate that all cross-references are valid.
    /// Returns Ok(()) if valid, or an error with all broken references.
    pub fn validate_refs(&self) -> Result<()> {
        if self.broken_refs.is_empty() {
            Ok(())
        } else {
            let messages: Vec<String> = self.broken_refs.iter().map(|r| r.to_string()).collect();
            Err(ClientError::Config(ConfigError::BrokenReferences(messages)))
        }
    }

    /// Get count of services per status.
    pub fn service_counts_by_status(&self) -> HashMap<VerificationStatus, usize> {
        self.service_status_to_services
            .iter()
            .map(|(k, v)| (k.clone(), v.len()))
            .collect()
    }

    /// Get summary statistics.
    pub fn stats(&self) -> IndexStats {
        let model_status_counts = self.model_counts_by_status();
        let service_status_counts = self.service_counts_by_status();
        IndexStats {
            total_services: self.all_services.len(),
            verified_services: service_status_counts
                .get(&VerificationStatus::Verified)
                .copied()
                .unwrap_or(0),
            unverified_services: service_status_counts
                .get(&VerificationStatus::Unverified)
                .copied()
                .unwrap_or(0),
            total_models: self.all_models.len(),
            verified_models: model_status_counts
                .get(&VerificationStatus::Verified)
                .copied()
                .unwrap_or(0),
            unverified_models: model_status_counts
                .get(&VerificationStatus::Unverified)
                .copied()
                .unwrap_or(0),
            total_families: self.family_to_models.len(),
            orphan_services: self.orphan_services.len(),
            broken_refs: self.broken_refs.len(),
        }
    }
}

/// Summary statistics for the registry index.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct IndexStats {
    pub total_services: usize,
    pub verified_services: usize,
    pub unverified_services: usize,
    pub total_models: usize,
    pub verified_models: usize,
    pub unverified_models: usize,
    pub total_families: usize,
    pub orphan_services: usize,
    pub broken_refs: usize,
}

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

    // Tests will use the embedded config loader
    #[test]
    fn test_index_build() {
        use crate::embedded_config::EmbeddedConfigLoader;

        let loader = EmbeddedConfigLoader::new().expect("Failed to load configs");
        let index = RegistryIndex::build(&loader);

        // Should have services and models
        assert!(!index.all_services().is_empty());
        assert!(!index.all_models().is_empty());

        // Check that anthropic service has claude models
        let anthropic_models = index.models_for_service("anthropic");
        assert!(!anthropic_models.is_empty());
        assert!(anthropic_models.iter().any(|m| m.contains("claude")));
    }

    #[test]
    fn test_bidirectional_lookup() {
        use crate::embedded_config::EmbeddedConfigLoader;

        let loader = EmbeddedConfigLoader::new().expect("Failed to load configs");
        let index = RegistryIndex::build(&loader);

        // For any model, we should be able to look up its service
        // and then find the model in that service's model list
        for model_id in index.all_models().iter().take(10) {
            if let Some(service) = index.service_for_model(model_id) {
                let models_for_service = index.models_for_service(service);
                assert!(
                    models_for_service.contains(model_id),
                    "Model {} should be in service {} model list",
                    model_id,
                    service
                );
            }
        }
    }
}