oxibonsai-runtime 0.1.4

Inference runtime, sampling, tokenizer, and server for OxiBonsai
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
//! Multi-model serving: manage base models + LoRA adapters with smart routing.
//!
//! Supports:
//! - Multiple base model configurations
//! - Hot-swappable LoRA adapter registry
//! - Request routing by model ID
//! - Model alias resolution
//! - Adapter composition (stacking multiple LoRAs)

use std::collections::HashMap;

// ─────────────────────────────────────────────────────────────────────────────
// ModelId
// ─────────────────────────────────────────────────────────────────────────────

/// A model endpoint identifier.
///
/// Uses a convention where `"base_name"` denotes a base model and
/// `"base_name:adapter_name"` denotes a base model with a LoRA adapter applied.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ModelId(pub String);

impl ModelId {
    /// Create a new model identifier from any string-like value.
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// Return the identifier as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns `true` if this is a base model (no `":"` separator).
    pub fn is_base(&self) -> bool {
        !self.0.contains(':')
    }

    /// If the identifier has the form `"base:adapter"`, return `Some("adapter")`.
    /// Otherwise return `None`.
    pub fn adapter_name(&self) -> Option<&str> {
        self.0.split_once(':').map(|(_, adapter)| adapter)
    }
}

impl std::fmt::Display for ModelId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// EndpointStatus
// ─────────────────────────────────────────────────────────────────────────────

/// Status of a model endpoint.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum EndpointStatus {
    /// The model is loaded and ready to serve requests.
    Ready,
    /// The model is currently being loaded.
    Loading,
    /// The model encountered an error and is unavailable.
    Error,
    /// The model has been explicitly disabled by an administrator.
    Disabled,
}

impl EndpointStatus {
    /// Returns `true` if the endpoint is available for serving requests.
    pub fn is_available(&self) -> bool {
        *self == Self::Ready
    }

    /// Human-readable name for this status.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Ready => "ready",
            Self::Loading => "loading",
            Self::Error => "error",
            Self::Disabled => "disabled",
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// ModelEndpoint
// ─────────────────────────────────────────────────────────────────────────────

/// Metadata for a served model variant.
///
/// Each endpoint represents a unique model configuration that can receive
/// inference requests. A base model may have multiple endpoints, each with
/// a different LoRA adapter applied.
#[derive(Debug, Clone)]
pub struct ModelEndpoint {
    /// Unique identifier for this endpoint.
    pub id: ModelId,
    /// Human-readable display name.
    pub display_name: String,
    /// Longer description of what this endpoint provides.
    pub description: String,
    /// Name of the underlying base model.
    pub base_model: String,
    /// Optional LoRA adapter name applied on top of the base model.
    pub adapter: Option<String>,
    /// Maximum context length (in tokens) this endpoint supports.
    pub max_context_length: usize,
    /// Whether this endpoint is the default when no model is specified.
    pub is_default: bool,
    /// Current operational status.
    pub status: EndpointStatus,
}

impl ModelEndpoint {
    /// Create a new endpoint with sensible defaults.
    ///
    /// Status is set to `Ready`, no adapter, default context length of 4096.
    pub fn new(id: impl Into<String>, base_model: impl Into<String>) -> Self {
        let id_str: String = id.into();
        let base: String = base_model.into();
        Self {
            display_name: id_str.clone(),
            id: ModelId::new(id_str),
            description: String::new(),
            base_model: base,
            adapter: None,
            max_context_length: 4096,
            is_default: false,
            status: EndpointStatus::Ready,
        }
    }

    /// Attach a LoRA adapter to this endpoint.
    pub fn with_adapter(mut self, adapter: impl Into<String>) -> Self {
        self.adapter = Some(adapter.into());
        self
    }

    /// Set a human-readable description.
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = desc.into();
        self
    }

    /// Set the maximum context length.
    pub fn with_context_length(mut self, ctx: usize) -> Self {
        self.max_context_length = ctx;
        self
    }

    /// Mark this endpoint as the default.
    pub fn set_default(mut self) -> Self {
        self.is_default = true;
        self
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// ModelRegistry
// ─────────────────────────────────────────────────────────────────────────────

/// The multi-model registry.
///
/// Manages a collection of [`ModelEndpoint`] instances and supports alias
/// resolution so that clients can refer to models by friendly names.
pub struct ModelRegistry {
    endpoints: HashMap<ModelId, ModelEndpoint>,
    aliases: HashMap<String, ModelId>,
    default_model: Option<ModelId>,
}

impl ModelRegistry {
    /// Create an empty registry.
    pub fn new() -> Self {
        Self {
            endpoints: HashMap::new(),
            aliases: HashMap::new(),
            default_model: None,
        }
    }

    /// Register a model endpoint.
    ///
    /// If the endpoint has `is_default` set, it becomes the default model.
    /// Replaces any existing endpoint with the same ID.
    pub fn register(&mut self, endpoint: ModelEndpoint) {
        if endpoint.is_default {
            self.default_model = Some(endpoint.id.clone());
        }
        self.endpoints.insert(endpoint.id.clone(), endpoint);
    }

    /// Remove an endpoint from the registry.
    ///
    /// Also clears the default-model pointer if it pointed to the removed
    /// endpoint, and removes any aliases that targeted this ID.
    pub fn unregister(&mut self, id: &ModelId) -> Option<ModelEndpoint> {
        let removed = self.endpoints.remove(id);
        if removed.is_some() {
            // Clear default if it was this model.
            if self.default_model.as_ref() == Some(id) {
                self.default_model = None;
            }
            // Remove aliases pointing to this model.
            self.aliases.retain(|_, target| target != id);
        }
        removed
    }

    /// Add an alias: e.g. `"gpt-4"` maps to `ModelId("bonsai-8b")`.
    pub fn add_alias(&mut self, alias: impl Into<String>, target: ModelId) {
        self.aliases.insert(alias.into(), target);
    }

    /// Resolve a model identifier (checks ID first, then aliases).
    ///
    /// Returns `None` if neither a direct ID nor an alias matches.
    pub fn resolve(&self, id_or_alias: &str) -> Option<&ModelEndpoint> {
        let model_id = ModelId::new(id_or_alias);
        if let Some(ep) = self.endpoints.get(&model_id) {
            return Some(ep);
        }
        // Try alias resolution.
        if let Some(target_id) = self.aliases.get(id_or_alias) {
            return self.endpoints.get(target_id);
        }
        None
    }

    /// Get the default model endpoint.
    pub fn default_endpoint(&self) -> Option<&ModelEndpoint> {
        self.default_model
            .as_ref()
            .and_then(|id| self.endpoints.get(id))
    }

    /// List all available (Ready) endpoints.
    pub fn available_endpoints(&self) -> Vec<&ModelEndpoint> {
        self.endpoints
            .values()
            .filter(|ep| ep.status.is_available())
            .collect()
    }

    /// List all registered endpoints (including non-ready ones).
    pub fn all_endpoints(&self) -> Vec<&ModelEndpoint> {
        self.endpoints.values().collect()
    }

    /// Update an endpoint's status.
    ///
    /// Returns `true` if the endpoint was found and updated.
    pub fn set_status(&mut self, id: &ModelId, status: EndpointStatus) -> bool {
        if let Some(ep) = self.endpoints.get_mut(id) {
            ep.status = status;
            true
        } else {
            false
        }
    }

    /// Number of registered endpoints.
    pub fn len(&self) -> usize {
        self.endpoints.len()
    }

    /// Is the registry empty?
    pub fn is_empty(&self) -> bool {
        self.endpoints.is_empty()
    }
}

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

// ─────────────────────────────────────────────────────────────────────────────
// RoutingError
// ─────────────────────────────────────────────────────────────────────────────

/// Errors that can occur when routing a request to a model endpoint.
#[derive(Debug, thiserror::Error)]
pub enum RoutingError {
    /// The requested model was not found in the registry.
    #[error("model '{0}' not found")]
    ModelNotFound(String),

    /// The requested model cannot accommodate the required context length.
    #[error("model '{model}' cannot handle context length {required} (max: {available})")]
    ContextTooLong {
        model: String,
        required: usize,
        available: usize,
    },

    /// No models are currently available in the registry.
    #[error("no models are currently available")]
    NoModelsAvailable,

    /// The model was found but is not in a ready state.
    #[error("model '{0}' is not ready (status: {1})")]
    ModelNotReady(String, String),
}

// ─────────────────────────────────────────────────────────────────────────────
// ModelRouter
// ─────────────────────────────────────────────────────────────────────────────

/// Smart request router: selects the best model endpoint for a request.
///
/// Wraps a [`ModelRegistry`] and adds routing logic including fallback to
/// the default model, context-length awareness, and OpenAI-compatible
/// model listing.
pub struct ModelRouter {
    registry: ModelRegistry,
}

impl ModelRouter {
    /// Create a new router backed by the given registry.
    pub fn new(registry: ModelRegistry) -> Self {
        Self { registry }
    }

    /// Route a request: resolve `model_id` from the request.
    ///
    /// Falls back to the default model if `requested_model` is `None`.
    /// Returns an error if the resolved endpoint is not in a `Ready` state.
    pub fn route(&self, requested_model: Option<&str>) -> Result<&ModelEndpoint, RoutingError> {
        let endpoint = match requested_model {
            Some(model_name) => self
                .registry
                .resolve(model_name)
                .ok_or_else(|| RoutingError::ModelNotFound(model_name.to_string()))?,
            None => self
                .registry
                .default_endpoint()
                .ok_or(RoutingError::NoModelsAvailable)?,
        };

        if !endpoint.status.is_available() {
            return Err(RoutingError::ModelNotReady(
                endpoint.id.to_string(),
                endpoint.status.name().to_string(),
            ));
        }

        Ok(endpoint)
    }

    /// Route with context-length awareness: pick a model that can accommodate
    /// the required context length.
    ///
    /// If a specific model is requested, validates it has sufficient context.
    /// If no model is specified, finds the default model that fits, or falls
    /// back to any available model with sufficient context capacity.
    pub fn route_for_context(
        &self,
        requested_model: Option<&str>,
        required_context: usize,
    ) -> Result<&ModelEndpoint, RoutingError> {
        let endpoint = self.route(requested_model)?;

        if endpoint.max_context_length < required_context {
            // If a specific model was requested but is too small, error out.
            if requested_model.is_some() {
                return Err(RoutingError::ContextTooLong {
                    model: endpoint.id.to_string(),
                    required: required_context,
                    available: endpoint.max_context_length,
                });
            }

            // No specific model requested — try to find any available endpoint
            // with sufficient context capacity.
            let fallback = self
                .registry
                .available_endpoints()
                .into_iter()
                .filter(|ep| ep.max_context_length >= required_context)
                .max_by_key(|ep| ep.max_context_length);

            return fallback.ok_or(RoutingError::ContextTooLong {
                model: endpoint.id.to_string(),
                required: required_context,
                available: endpoint.max_context_length,
            });
        }

        Ok(endpoint)
    }

    /// OpenAI-compatible `/v1/models` list.
    ///
    /// Returns an entry for every available endpoint in the registry.
    pub fn models_list(&self) -> Vec<ModelListEntry> {
        let created = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        self.registry
            .available_endpoints()
            .into_iter()
            .map(|ep| ModelListEntry {
                id: ep.id.to_string(),
                object: "model".to_string(),
                owned_by: "oxibonsai".to_string(),
                created,
            })
            .collect()
    }

    /// Immutable access to the underlying registry.
    pub fn registry(&self) -> &ModelRegistry {
        &self.registry
    }

    /// Mutable access to the underlying registry.
    pub fn registry_mut(&mut self) -> &mut ModelRegistry {
        &mut self.registry
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// ModelListEntry
// ─────────────────────────────────────────────────────────────────────────────

/// Entry for an OpenAI-compatible `/v1/models` response.
#[derive(Debug, Clone)]
pub struct ModelListEntry {
    /// Model identifier string.
    pub id: String,
    /// Object type — always `"model"`.
    pub object: String,
    /// Organisation that owns the model.
    pub owned_by: String,
    /// Unix timestamp when the model was created/registered.
    pub created: u64,
}

// ─────────────────────────────────────────────────────────────────────────────
// AdapterRef / AdapterStack
// ─────────────────────────────────────────────────────────────────────────────

/// A reference to a single LoRA adapter with a blending weight.
#[derive(Debug, Clone)]
pub struct AdapterRef {
    /// Name of the LoRA adapter.
    pub name: String,
    /// Blending weight in the range `[0.0, 1.0]`.
    pub weight: f32,
}

/// Adapter composition: apply multiple LoRA adapters in sequence.
///
/// Allows stacking several adapters with independent blending weights.
/// Weights can be normalized so they sum to 1.0, which is useful for
/// even blending across adapters.
#[derive(Debug, Clone)]
pub struct AdapterStack {
    /// The ordered list of adapters to apply.
    pub adapters: Vec<AdapterRef>,
}

impl AdapterStack {
    /// Create an empty adapter stack.
    pub fn new() -> Self {
        Self {
            adapters: Vec::new(),
        }
    }

    /// Add an adapter with the given blending weight.
    pub fn add(mut self, name: impl Into<String>, weight: f32) -> Self {
        self.adapters.push(AdapterRef {
            name: name.into(),
            weight,
        });
        self
    }

    /// Number of adapters in the stack.
    pub fn len(&self) -> usize {
        self.adapters.len()
    }

    /// Whether the stack is empty.
    pub fn is_empty(&self) -> bool {
        self.adapters.is_empty()
    }

    /// Sum of all adapter weights.
    pub fn total_weight(&self) -> f32 {
        self.adapters.iter().map(|a| a.weight).sum()
    }

    /// Normalize weights so they sum to 1.0.
    ///
    /// If the total weight is zero (or very close to it), weights are left
    /// unchanged to avoid division by zero.
    pub fn normalize_weights(&mut self) {
        let total = self.total_weight();
        if total.abs() < f32::EPSILON {
            return;
        }
        for adapter in &mut self.adapters {
            adapter.weight /= total;
        }
    }
}

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

// ─────────────────────────────────────────────────────────────────────────────
// Unit tests
// ─────────────────────────────────────────────────────────────────────────────

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

    #[test]
    fn model_id_display() {
        let id = ModelId::new("bonsai-8b");
        assert_eq!(format!("{id}"), "bonsai-8b");
    }

    #[test]
    fn endpoint_status_name() {
        assert_eq!(EndpointStatus::Ready.name(), "ready");
        assert_eq!(EndpointStatus::Loading.name(), "loading");
        assert_eq!(EndpointStatus::Error.name(), "error");
        assert_eq!(EndpointStatus::Disabled.name(), "disabled");
    }

    #[test]
    fn endpoint_display_name_defaults_to_id() {
        let ep = ModelEndpoint::new("bonsai-8b", "qwen3-8b");
        assert_eq!(ep.display_name, "bonsai-8b");
    }
}