Skip to main content

aither_agent/
model_group.rs

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