Skip to main content

aither_agent/
model_group.rs

1//! Model groups with budget tracking and automatic fallback.
2//!
3//! This module provides a tiered model system where models are organized by
4//! capability (advanced, balanced, fast) with automatic fallback when budgets
5//! are exhausted.
6
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use aither_core::llm::Usage;
10use num_traits::ToPrimitive;
11
12/// Budget limit for a model.
13#[derive(Debug, Clone)]
14pub enum Budget {
15    /// Unlimited usage (no budget tracking).
16    Unlimited,
17    /// Limit by total tokens.
18    Tokens(u64),
19    /// Limit by estimated cost in USD (stored as microdollars for precision).
20    Cost(f64),
21}
22
23impl Budget {
24    /// Creates a token-based budget.
25    #[must_use]
26    pub const fn tokens(limit: u64) -> Self {
27        Self::Tokens(limit)
28    }
29
30    /// Creates a cost-based budget in USD.
31    #[must_use]
32    pub const fn usd(limit: f64) -> Self {
33        Self::Cost(limit)
34    }
35}
36
37/// A model with budget tracking.
38#[derive(Debug)]
39pub struct BudgetedModel<M> {
40    /// The underlying model.
41    pub model: M,
42    /// Budget limit.
43    pub budget: Budget,
44    /// Tokens used (atomic for thread safety).
45    tokens_used: AtomicU64,
46    /// Cost used in microdollars (1 USD = `1_000_000` microdollars).
47    cost_used_micro: AtomicU64,
48    /// Whether this model's budget is exhausted.
49    exhausted: std::sync::atomic::AtomicBool,
50}
51
52impl<M> BudgetedModel<M> {
53    /// Creates a new budgeted model.
54    #[must_use]
55    pub const fn new(model: M, budget: Budget) -> Self {
56        Self {
57            model,
58            budget,
59            tokens_used: AtomicU64::new(0),
60            cost_used_micro: AtomicU64::new(0),
61            exhausted: std::sync::atomic::AtomicBool::new(false),
62        }
63    }
64
65    /// Creates a model with unlimited budget.
66    #[must_use]
67    pub const fn unlimited(model: M) -> Self {
68        Self::new(model, Budget::Unlimited)
69    }
70
71    /// Records usage from a response.
72    pub fn record_usage(&self, usage: &Usage) {
73        if let Some(tokens) = usage.total_tokens {
74            self.tokens_used
75                .fetch_add(u64::from(tokens), Ordering::Relaxed);
76        }
77        if let Some(cost) = usage.cost_usd {
78            // Convert to microdollars
79            let micro = (cost * 1_000_000.0).round().to_u64().unwrap_or(u64::MAX);
80            self.cost_used_micro.fetch_add(micro, Ordering::Relaxed);
81        }
82    }
83
84    /// Marks this model as exhausted (e.g., from API quota error).
85    pub fn mark_exhausted(&self) {
86        self.exhausted.store(true, Ordering::Release);
87    }
88
89    /// Checks if the budget is exhausted.
90    #[must_use]
91    pub fn is_exhausted(&self) -> bool {
92        if self.exhausted.load(Ordering::Acquire) {
93            return true;
94        }
95
96        match &self.budget {
97            Budget::Unlimited => false,
98            Budget::Tokens(limit) => self.tokens_used.load(Ordering::Relaxed) >= *limit,
99            Budget::Cost(limit) => {
100                let micro_limit = (*limit * 1_000_000.0).round().to_u64().unwrap_or(u64::MAX);
101                self.cost_used_micro.load(Ordering::Relaxed) >= micro_limit
102            }
103        }
104    }
105
106    /// Returns the current token usage.
107    #[must_use]
108    pub fn tokens_used(&self) -> u64 {
109        self.tokens_used.load(Ordering::Relaxed)
110    }
111
112    /// Returns the current cost usage in USD.
113    #[must_use]
114    pub fn cost_used(&self) -> f64 {
115        self.cost_used_micro
116            .load(Ordering::Relaxed)
117            .to_f64()
118            .unwrap_or(f64::MAX)
119            / 1_000_000.0
120    }
121
122    /// Resets the usage counters (but not the exhausted flag).
123    pub fn reset_usage(&self) {
124        self.tokens_used.store(0, Ordering::Relaxed);
125        self.cost_used_micro.store(0, Ordering::Relaxed);
126    }
127
128    /// Resets everything including the exhausted flag.
129    pub fn reset_all(&self) {
130        self.reset_usage();
131        self.exhausted.store(false, Ordering::Release);
132    }
133
134    /// Returns a reference to the underlying model.
135    #[must_use]
136    pub const fn inner(&self) -> &M {
137        &self.model
138    }
139}
140
141/// A group of models with the same tier, ordered by preference.
142#[derive(Debug)]
143pub struct ModelGroup<M> {
144    /// Models in preference order (first = preferred).
145    models: Vec<BudgetedModel<M>>,
146    /// Current active model index.
147    current: std::sync::atomic::AtomicUsize,
148}
149
150impl<M> ModelGroup<M> {
151    /// Creates a new model group with a single model.
152    #[must_use]
153    pub fn new(model: BudgetedModel<M>) -> Self {
154        Self {
155            models: vec![model],
156            current: std::sync::atomic::AtomicUsize::new(0),
157        }
158    }
159
160    /// Creates a group from multiple budgeted models.
161    #[must_use]
162    pub const fn from_models(models: Vec<BudgetedModel<M>>) -> Self {
163        Self {
164            models,
165            current: std::sync::atomic::AtomicUsize::new(0),
166        }
167    }
168
169    /// Adds a fallback model to the group.
170    #[must_use]
171    pub fn with_fallback(mut self, model: BudgetedModel<M>) -> Self {
172        self.models.push(model);
173        self
174    }
175
176    /// Returns the current active model, or None if all are exhausted.
177    #[must_use]
178    pub fn current(&self) -> Option<&BudgetedModel<M>> {
179        if !self.try_advance() {
180            return None;
181        }
182        let idx = self.current.load(Ordering::Acquire);
183        self.models.get(idx).filter(|m| !m.is_exhausted())
184    }
185
186    /// Advances to the next model if the current one is exhausted.
187    /// Returns true if a new model is available, false if all are exhausted.
188    pub fn try_advance(&self) -> bool {
189        loop {
190            let idx = self.current.load(Ordering::Acquire);
191            if idx >= self.models.len() {
192                return false;
193            }
194
195            if let Some(model) = self.models.get(idx)
196                && !model.is_exhausted()
197            {
198                return true;
199            }
200
201            // Try to advance
202            let next = idx + 1;
203            if next >= self.models.len() {
204                return false;
205            }
206
207            // CAS to advance
208            if self
209                .current
210                .compare_exchange(idx, next, Ordering::AcqRel, Ordering::Acquire)
211                .is_err()
212            {
213                // Another thread advanced, retry
214                continue;
215            }
216
217            // Check if the new model is available
218            if let Some(model) = self.models.get(next)
219                && !model.is_exhausted()
220            {
221                return true;
222            }
223        }
224    }
225
226    /// Records usage for the current model.
227    pub fn record_usage(&self, usage: &Usage) {
228        let idx = self.current.load(Ordering::Acquire);
229        if let Some(model) = self.models.get(idx) {
230            model.record_usage(usage);
231            if model.is_exhausted() {
232                let _ = self.try_advance();
233            }
234        }
235    }
236
237    /// Marks the current model as exhausted and tries to advance.
238    pub fn mark_current_exhausted(&self) -> bool {
239        let idx = self.current.load(Ordering::Acquire);
240        if let Some(model) = self.models.get(idx) {
241            model.mark_exhausted();
242        }
243        self.try_advance()
244    }
245
246    /// Returns true if all models in the group are exhausted.
247    #[must_use]
248    pub fn all_exhausted(&self) -> bool {
249        self.models.iter().all(BudgetedModel::is_exhausted)
250    }
251
252    /// Resets all models in the group.
253    pub fn reset_all(&self) {
254        for model in &self.models {
255            model.reset_all();
256        }
257        self.current.store(0, Ordering::Release);
258    }
259}
260
261/// Model tier classification for organizing models.
262#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
263pub enum ModelTier {
264    /// High-capability models (e.g., GPT-4, Claude Opus)
265    #[default]
266    Advanced,
267    /// Balanced capability/cost models (e.g., GPT-4o, Claude Sonnet)
268    Balanced,
269    /// Fast/cheap models (e.g., GPT-4o-mini, Claude Haiku)
270    Fast,
271}
272
273/// Collection of model groups organized by tier.
274#[derive(Debug)]
275pub struct TieredModels<M> {
276    /// Advanced tier models.
277    pub advanced: Option<ModelGroup<M>>,
278    /// Balanced tier models.
279    pub balanced: Option<ModelGroup<M>>,
280    /// Fast tier models.
281    pub fast: Option<ModelGroup<M>>,
282}
283
284impl<M> Default for TieredModels<M> {
285    fn default() -> Self {
286        Self {
287            advanced: None,
288            balanced: None,
289            fast: None,
290        }
291    }
292}
293
294impl<M> TieredModels<M> {
295    /// Creates empty tiered models.
296    #[must_use]
297    pub fn new() -> Self {
298        Self::default()
299    }
300
301    /// Sets the advanced tier models.
302    #[must_use]
303    pub fn with_advanced(mut self, group: ModelGroup<M>) -> Self {
304        self.advanced = Some(group);
305        self
306    }
307
308    /// Sets the balanced tier models.
309    #[must_use]
310    pub fn with_balanced(mut self, group: ModelGroup<M>) -> Self {
311        self.balanced = Some(group);
312        self
313    }
314
315    /// Sets the fast tier models.
316    #[must_use]
317    pub fn with_fast(mut self, group: ModelGroup<M>) -> Self {
318        self.fast = Some(group);
319        self
320    }
321
322    /// Gets the model group for a specific tier.
323    #[must_use]
324    pub const fn get(&self, tier: ModelTier) -> Option<&ModelGroup<M>> {
325        match tier {
326            ModelTier::Advanced => self.advanced.as_ref(),
327            ModelTier::Balanced => self.balanced.as_ref(),
328            ModelTier::Fast => self.fast.as_ref(),
329        }
330    }
331
332    /// Gets a mutable reference to the model group for a specific tier.
333    pub const fn get_mut(&mut self, tier: ModelTier) -> Option<&mut ModelGroup<M>> {
334        match tier {
335            ModelTier::Advanced => self.advanced.as_mut(),
336            ModelTier::Balanced => self.balanced.as_mut(),
337            ModelTier::Fast => self.fast.as_mut(),
338        }
339    }
340}
341
342// ============================================================================
343// LanguageModel implementation for ModelGroup
344// ============================================================================
345
346use aither_core::{
347    LanguageModel,
348    llm::{Event, LLMRequest, model::Profile},
349};
350use futures_core::Stream;
351
352/// Error type for model group operations.
353#[derive(Debug)]
354pub enum ModelGroupError<E> {
355    /// All models in the group are exhausted.
356    AllModelsExhausted,
357    /// Underlying model error.
358    Model(E),
359}
360
361impl<E: std::fmt::Display> std::fmt::Display for ModelGroupError<E> {
362    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
363        match self {
364            Self::AllModelsExhausted => write!(f, "all models in group are exhausted"),
365            Self::Model(e) => write!(f, "{e}"),
366        }
367    }
368}
369
370impl<E: std::error::Error + 'static> std::error::Error for ModelGroupError<E> {
371    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
372        match self {
373            Self::AllModelsExhausted => None,
374            Self::Model(e) => Some(e),
375        }
376    }
377}
378
379/// Checks if an error message indicates budget/quota exhaustion.
380fn is_quota_error(error_msg: &str) -> bool {
381    let lower = error_msg.to_lowercase();
382    lower.contains("insufficient_quota")
383        || lower.contains("rate_limit")
384        || lower.contains("quota")
385        || lower.contains("resource_exhausted")
386        || lower.contains("overloaded")
387        || lower.contains("capacity")
388        || lower.contains("billing")
389        || lower.contains("exceeded")
390}
391
392impl<M> LanguageModel for ModelGroup<M>
393where
394    M: LanguageModel + Send + Sync,
395    M::Error: Send + Sync + 'static,
396{
397    type Error = ModelGroupError<M::Error>;
398
399    fn respond(
400        &self,
401        request: LLMRequest,
402    ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
403        ModelGroupStream::new(self, request)
404    }
405
406    async fn profile(&self) -> Profile {
407        if let Some(model) = self.current() {
408            model.inner().profile().await
409        } else if let Some(model) = self.models.first() {
410            model.inner().profile().await
411        } else {
412            Profile::new("unknown", "unknown", "unknown", "Empty model group", 0)
413        }
414    }
415}
416
417use std::pin::Pin;
418use std::task::{Context, Poll};
419
420/// A boxed event stream from one of the group's models.
421/// Stream wrapper for `ModelGroup` that tracks usage and detects quota errors.
422type BoxedModelStream<'a, M> =
423    Pin<Box<dyn Stream<Item = Result<Event, <M as LanguageModel>::Error>> + Send + 'a>>;
424
425struct ModelGroupStream<'a, M: LanguageModel> {
426    group: &'a ModelGroup<M>,
427    inner: Option<BoxedModelStream<'a, M>>,
428}
429
430impl<'a, M: LanguageModel> ModelGroupStream<'a, M> {
431    fn new(group: &'a ModelGroup<M>, request: LLMRequest) -> Self {
432        let inner = group.current().map(|m| {
433            let stream = m.inner().respond(request);
434            Box::pin(stream) as BoxedModelStream<'a, M>
435        });
436        Self { group, inner }
437    }
438}
439
440impl<M: LanguageModel> Stream for ModelGroupStream<'_, M>
441where
442    M::Error: Send + 'static,
443{
444    type Item = Result<Event, ModelGroupError<M::Error>>;
445
446    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
447        let Some(ref mut inner) = self.inner else {
448            return Poll::Ready(Some(Err(ModelGroupError::AllModelsExhausted)));
449        };
450
451        match inner.as_mut().poll_next(cx) {
452            Poll::Ready(Some(Ok(event))) => {
453                // Track usage
454                if let Event::Usage(ref usage) = event
455                    && let Some(model) = self.group.current()
456                {
457                    model.record_usage(usage);
458                }
459                Poll::Ready(Some(Ok(event)))
460            }
461            Poll::Ready(Some(Err(e))) => {
462                // Check if this is a quota error
463                let error_msg = e.to_string();
464                if is_quota_error(&error_msg) {
465                    let _ = self.group.mark_current_exhausted();
466                    tracing::warn!("Model quota exhausted: {}", error_msg);
467                }
468                self.inner = None;
469                Poll::Ready(Some(Err(ModelGroupError::Model(e))))
470            }
471            Poll::Ready(None) => Poll::Ready(None),
472            Poll::Pending => Poll::Pending,
473        }
474    }
475}
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480    use aither_core::{
481        LanguageModel,
482        llm::{Event, LLMRequest, model::Profile},
483    };
484    use futures_lite::{StreamExt, stream};
485
486    #[derive(Debug, Clone)]
487    struct DummyModel {
488        name: &'static str,
489    }
490
491    #[derive(Debug)]
492    struct DummyError;
493
494    impl std::fmt::Display for DummyError {
495        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
496            f.write_str("dummy error")
497        }
498    }
499
500    impl std::error::Error for DummyError {}
501
502    impl LanguageModel for DummyModel {
503        type Error = DummyError;
504
505        fn respond(
506            &self,
507            _request: LLMRequest,
508        ) -> impl futures_core::Stream<Item = Result<Event, Self::Error>> + Send {
509            stream::iter([Ok(Event::Text(self.name.to_string()))])
510        }
511
512        fn profile(&self) -> impl std::future::Future<Output = Profile> + Send {
513            std::future::ready(Profile::new("dummy", self.name, "test", "dummy", 0))
514        }
515    }
516
517    #[test]
518    fn test_budget_tokens() {
519        let model = BudgetedModel::new("gpt-4", Budget::tokens(1000));
520        assert!(!model.is_exhausted());
521
522        model.record_usage(&Usage::new(500, 400));
523        assert!(!model.is_exhausted());
524
525        model.record_usage(&Usage::new(50, 51));
526        assert!(model.is_exhausted());
527    }
528
529    #[test]
530    fn test_budget_cost() {
531        let model = BudgetedModel::new("gpt-4", Budget::usd(1.0));
532        assert!(!model.is_exhausted());
533
534        model.record_usage(&Usage::new(0, 0).with_cost(0.5));
535        assert!(!model.is_exhausted());
536
537        model.record_usage(&Usage::new(0, 0).with_cost(0.6));
538        assert!(model.is_exhausted());
539    }
540
541    #[test]
542    fn test_model_group_fallback() {
543        let group = ModelGroup::from_models(vec![
544            BudgetedModel::new("primary", Budget::tokens(100)),
545            BudgetedModel::new("fallback", Budget::tokens(100)),
546        ]);
547
548        // Initially on primary
549        assert_eq!(
550            group.current().map(super::BudgetedModel::inner),
551            Some(&"primary")
552        );
553
554        // Exhaust primary
555        group.record_usage(&Usage::new(50, 51));
556        assert_eq!(
557            group.current().map(super::BudgetedModel::inner),
558            Some(&"fallback")
559        );
560
561        // Exhaust fallback
562        group.record_usage(&Usage::new(50, 51));
563        assert!(!group.try_advance());
564        assert!(group.all_exhausted());
565    }
566
567    #[test]
568    fn test_mark_exhausted() {
569        let group = ModelGroup::from_models(vec![
570            BudgetedModel::unlimited("primary"),
571            BudgetedModel::unlimited("fallback"),
572        ]);
573
574        assert_eq!(
575            group.current().map(super::BudgetedModel::inner),
576            Some(&"primary")
577        );
578
579        // Mark as exhausted (e.g., from API quota error)
580        assert!(group.mark_current_exhausted());
581        assert_eq!(
582            group.current().map(super::BudgetedModel::inner),
583            Some(&"fallback")
584        );
585    }
586
587    #[test]
588    fn current_advances_past_exhausted_models() {
589        let group = ModelGroup::from_models(vec![
590            BudgetedModel::new("primary", Budget::tokens(1)),
591            BudgetedModel::new("fallback", Budget::tokens(100)),
592        ]);
593        group.models[0].mark_exhausted();
594        assert_eq!(
595            group.current().map(super::BudgetedModel::inner),
596            Some(&"fallback")
597        );
598    }
599
600    #[tokio::test]
601    async fn stream_uses_fallback_after_primary_is_exhausted() {
602        let group = ModelGroup::from_models(vec![
603            BudgetedModel::new(DummyModel { name: "primary" }, Budget::tokens(1)),
604            BudgetedModel::new(DummyModel { name: "fallback" }, Budget::tokens(100)),
605        ]);
606        group.models[0].mark_exhausted();
607
608        let request = LLMRequest::new([aither_core::llm::Message::user("hello")]);
609        let mut stream = group.respond(request);
610        let first = stream.next().await;
611
612        match first {
613            Some(Ok(Event::Text(text))) => assert_eq!(text, "fallback"),
614            other => panic!("expected fallback model text event, got {other:?}"),
615        }
616    }
617}