Skip to main content

adk_model/
fallback.rs

1//! A provider-neutral fallback chain: an ordered list of models, each tried when the one
2//! before it fails.
3//!
4//! [`FallbackLlm`] is an [`Llm`], so an agent takes it wherever it takes any other model. It
5//! sends the request to its first model and moves to the next one only on a configured
6//! [`FallbackTrigger`]; the first model that answers keeps the turn.
7//!
8//! | Step | What happens |
9//! |------|--------------|
10//! | Each attempt | The request goes out with `model` set to that model's name |
11//! | The attempt fails before its first response | On a configured trigger the next model is tried; otherwise the error is returned |
12//! | The attempt's first response is a refusal | With [`FallbackTrigger::Refusal`] the next model is tried |
13//! | The attempt has yielded a response | The turn belongs to that model: a later error reaches the caller |
14//! | Every model failed | The last model's error, or its refusal, is returned |
15//!
16//! Under a [`ModelCallScope`] (an agent's run) every attempt is its own metered call: it
17//! counts against the run budget as a model call and is reserved and committed in the
18//! spend ledger under the provider and model that served it, a refused attempt included.
19
20use std::sync::Arc;
21
22use adk_core::{
23    AdkError, ErrorCategory, ErrorComponent, FinishReason, Llm, LlmRequest, LlmResponse,
24    LlmResponseStream, ModelCallScope, NativeWebSearch, Result, SchemaAdapter,
25    intra_compaction::is_context_limit_error,
26};
27use async_trait::async_trait;
28use futures::StreamExt;
29use serde_json::{Value, json};
30
31/// The `provider_metadata` key a [`FallbackLlm`] response carries when a model after the
32/// first one answered.
33///
34/// Its value names the model that answered, its position in the chain (1 is the first
35/// fallback), and each model skipped before it with the trigger and error code that moved the
36/// chain on.
37///
38/// # Example
39///
40/// ```rust
41/// use adk_model::fallback::FALLBACK_METADATA_KEY;
42///
43/// assert_eq!(FALLBACK_METADATA_KEY, "fallback");
44/// ```
45pub const FALLBACK_METADATA_KEY: &str = "fallback";
46
47/// A condition that moves a [`FallbackLlm`] on to its next model.
48///
49/// Only a failure the model reports counts: an error from the run's budget, spend ledger or
50/// kill switch is never a reason to try another model, and is returned as is.
51///
52/// | Trigger | Default | Matches |
53/// |---------|---------|---------|
54/// | [`Retryable`](Self::Retryable) | on | Rate limiting, timeouts, server errors and provider outages ([`AdkError::is_retryable`]), once the model's own retries are used up |
55/// | [`ModelNotFound`](Self::ModelNotFound) | on | The provider does not serve the model: an unknown, retired or unavailable model id ([`ErrorCategory::NotFound`]) |
56/// | [`QuotaExhausted`](Self::QuotaExhausted) | on | The provider account's quota, credit balance or spend limit is used up ([`ErrorCategory::ResourceExhausted`]) |
57/// | [`Refusal`](Self::Refusal) | off | The model declined the request ([`FinishReason::Refusal`]) before any output |
58/// | [`ContextOverflow`](Self::ContextOverflow) | off | The request is longer than the model's context window |
59/// | [`AuthFailure`](Self::AuthFailure) | off | The provider refused the credentials or the permission ([`ErrorCategory::Unauthorized`], [`ErrorCategory::Forbidden`]) |
60///
61/// # Example
62///
63/// ```rust
64/// use adk_model::fallback::FallbackTrigger;
65///
66/// assert!(FallbackTrigger::DEFAULT.contains(&FallbackTrigger::Retryable));
67/// assert!(!FallbackTrigger::DEFAULT.contains(&FallbackTrigger::Refusal));
68/// assert_eq!(FallbackTrigger::ModelNotFound.as_str(), "model_not_found");
69/// ```
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71#[non_exhaustive]
72pub enum FallbackTrigger {
73    /// A transient failure the model's own retries did not clear.
74    Retryable,
75    /// The provider does not serve the requested model.
76    ModelNotFound,
77    /// The provider account's quota or credit is used up.
78    QuotaExhausted,
79    /// The model declined the request before producing any output.
80    Refusal,
81    /// The request does not fit the model's context window.
82    ContextOverflow,
83    /// The provider refused the credentials or the permission.
84    AuthFailure,
85}
86
87impl FallbackTrigger {
88    /// The triggers a [`FallbackLlm`] uses unless configured otherwise: the failures another
89    /// model can serve without a change to the request or to its permissions.
90    pub const DEFAULT: [FallbackTrigger; 3] = [
91        FallbackTrigger::Retryable,
92        FallbackTrigger::ModelNotFound,
93        FallbackTrigger::QuotaExhausted,
94    ];
95
96    /// The trigger's name in tracing and in [`FALLBACK_METADATA_KEY`] metadata.
97    pub fn as_str(self) -> &'static str {
98        match self {
99            FallbackTrigger::Retryable => "retryable",
100            FallbackTrigger::ModelNotFound => "model_not_found",
101            FallbackTrigger::QuotaExhausted => "quota_exhausted",
102            FallbackTrigger::Refusal => "refusal",
103            FallbackTrigger::ContextOverflow => "context_overflow",
104            FallbackTrigger::AuthFailure => "auth_failure",
105        }
106    }
107
108    /// The trigger `error` matches, if any.
109    ///
110    /// Only an error from the model ([`ErrorComponent::Model`]) matches, so a refusal by the
111    /// run's budget, spend ledger or kill switch never moves a chain on.
112    ///
113    /// # Example
114    ///
115    /// ```rust
116    /// use adk_core::{AdkError, ErrorCategory, ErrorComponent};
117    /// use adk_model::fallback::FallbackTrigger;
118    ///
119    /// let overloaded = AdkError::new(
120    ///     ErrorComponent::Model,
121    ///     ErrorCategory::Unavailable,
122    ///     "model.anthropic.api_error",
123    ///     "overloaded",
124    /// );
125    /// assert_eq!(FallbackTrigger::for_error(&overloaded), Some(FallbackTrigger::Retryable));
126    ///
127    /// let budget = AdkError::new(
128    ///     ErrorComponent::Agent,
129    ///     ErrorCategory::ResourceExhausted,
130    ///     "budget.model_calls_exceeded",
131    ///     "the run's model-call budget is spent",
132    /// );
133    /// assert_eq!(FallbackTrigger::for_error(&budget), None);
134    /// ```
135    pub fn for_error(error: &AdkError) -> Option<Self> {
136        if error.component != ErrorComponent::Model {
137            return None;
138        }
139        if is_context_limit_error(error) {
140            return Some(FallbackTrigger::ContextOverflow);
141        }
142        match error.category {
143            ErrorCategory::RateLimited | ErrorCategory::Timeout | ErrorCategory::Unavailable => {
144                Some(FallbackTrigger::Retryable)
145            }
146            ErrorCategory::NotFound => Some(FallbackTrigger::ModelNotFound),
147            ErrorCategory::ResourceExhausted => Some(FallbackTrigger::QuotaExhausted),
148            ErrorCategory::Unauthorized | ErrorCategory::Forbidden => {
149                Some(FallbackTrigger::AuthFailure)
150            }
151            ErrorCategory::InvalidInput
152            | ErrorCategory::Cancelled
153            | ErrorCategory::Internal
154            | ErrorCategory::Unsupported
155            | ErrorCategory::Conflict => error.is_retryable().then_some(FallbackTrigger::Retryable),
156        }
157    }
158}
159
160impl std::fmt::Display for FallbackTrigger {
161    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162        f.write_str(self.as_str())
163    }
164}
165
166/// An ordered chain of models: each request goes to the first model, and to the next one
167/// whenever the one before it fails on a configured [`FallbackTrigger`].
168///
169/// The counterpart of Google ADK's `FallbackModel`, for any mix of providers. The first
170/// model that yields a response keeps the turn, so a streamed turn never splices two
171/// models' output: a failure after the first response reaches the caller. When every model
172/// fails, the last model's error (or refusal) is returned, and `LlmAgent`'s
173/// `on_model_error` hooks see it as they see any model error.
174///
175/// | Signal | Where |
176/// |--------|-------|
177/// | Which model answered | [`LlmResponse::model`] and [`LlmResponse::provider`], set by the provider that answered |
178/// | That a fallback happened | `provider_metadata["fallback"]` ([`FALLBACK_METADATA_KEY`]) on every complete response, and a `warn` tracing event per skipped model |
179/// | What each attempt cost | Under a run, one spend-ledger entry and one budget model call per attempt, under the attempt's own provider |
180///
181/// For a mix of models, the chain reports:
182///
183/// - [`name`](Llm::name): the first model's name.
184/// - [`context_window`](Llm::context_window): the smallest window among the models that
185///   report one, so auto-compaction keeps a request within every model it may reach; with
186///   [`FallbackTrigger::ContextOverflow`], the largest, since the chain is then built to move
187///   a long request to a larger model.
188/// - [`schema_adapter`](Llm::schema_adapter): the first model's. Tool schemas are normalized
189///   once, before any attempt, so keep the chain's providers schema-compatible or put the
190///   strictest one first.
191/// - [`max_cost_micro_usd`](Llm::max_cost_micro_usd): the largest bound in the chain (a
192///   failed call bills nothing), or the sum of the bounds with [`FallbackTrigger::Refusal`],
193///   since a refused attempt is billed; `None` when a model has no bound. A run meters each
194///   attempt on its own bound, so this applies only where the chain is metered as one call.
195/// - [`native_web_search`](Llm::native_web_search): the search every model serves, or `None`
196///   when they differ, since a provider's built-in search tool breaks another provider's
197///   request.
198///
199/// A model's own retries ([`RetryConfig`](crate::RetryConfig)) run first: the chain sees a
200/// failure only once they are used up, and it tries each model once.
201///
202/// # Example
203///
204/// ```rust
205/// use std::sync::Arc;
206/// use adk_core::{AdkError, Content, ErrorCategory, ErrorComponent, Llm, LlmRequest};
207/// use adk_model::fallback::{FallbackLlm, FallbackTrigger};
208/// use adk_model::{ScriptedLlm, ScriptedResponse};
209/// use futures::StreamExt;
210///
211/// # #[tokio::main(flavor = "current_thread")]
212/// # async fn main() -> Result<(), AdkError> {
213/// let overloaded = AdkError::new(
214///     ErrorComponent::Model,
215///     ErrorCategory::Unavailable,
216///     "model.anthropic.api_error",
217///     "overloaded",
218/// );
219/// let primary = Arc::new(ScriptedLlm::new("claude-sonnet-5-5", [ScriptedResponse::error(overloaded)]));
220/// let backup = Arc::new(ScriptedLlm::new("gemini-3.7-flash", [ScriptedResponse::text("Mars.")]));
221///
222/// let model = FallbackLlm::builder(primary)
223///     .fallback(backup.clone())
224///     .fall_back_on(FallbackTrigger::Refusal)
225///     .build();
226///
227/// let request = LlmRequest::new(model.name(), vec![Content::new("user").with_text("Name a planet.")]);
228/// let response = model.generate_content(request, false).await?.next().await.unwrap()?;
229/// assert_eq!(response.content.unwrap().parts[0].text(), Some("Mars."));
230/// assert_eq!(response.provider_metadata.unwrap()["fallback"]["model"], "gemini-3.7-flash");
231/// assert_eq!(backup.last_request().unwrap().model, "gemini-3.7-flash");
232/// # Ok(())
233/// # }
234/// ```
235pub struct FallbackLlm {
236    models: Vec<Arc<dyn Llm>>,
237    triggers: Vec<FallbackTrigger>,
238}
239
240impl std::fmt::Debug for FallbackLlm {
241    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242        f.debug_struct("FallbackLlm")
243            .field("models", &self.models.iter().map(|model| model.name()).collect::<Vec<_>>())
244            .field("triggers", &self.triggers)
245            .finish()
246    }
247}
248
249/// Builds a [`FallbackLlm`]: the first model, the models to fall back to in order, and the
250/// triggers that move the chain on.
251///
252/// # Example
253///
254/// ```rust
255/// use std::sync::Arc;
256/// use adk_core::Llm;
257/// use adk_model::fallback::{FallbackLlm, FallbackTrigger};
258/// use adk_model::{ScriptedLlm, ScriptedResponse};
259///
260/// let primary = Arc::new(ScriptedLlm::new("claude-sonnet-5-5", Vec::<ScriptedResponse>::new()));
261/// let backup = Arc::new(ScriptedLlm::new("claude-haiku-5-5", Vec::<ScriptedResponse>::new()));
262/// let model = FallbackLlm::builder(primary)
263///     .fallback(backup)
264///     .never_fall_back_on(FallbackTrigger::ModelNotFound)
265///     .build();
266/// assert_eq!(model.name(), "claude-sonnet-5-5");
267/// assert_eq!(model.triggers(), [FallbackTrigger::Retryable, FallbackTrigger::QuotaExhausted]);
268/// ```
269pub struct FallbackLlmBuilder {
270    models: Vec<Arc<dyn Llm>>,
271    triggers: Vec<FallbackTrigger>,
272}
273
274impl FallbackLlm {
275    /// Starts a chain whose first model is `primary`, with the [default
276    /// triggers](FallbackTrigger::DEFAULT).
277    pub fn builder(primary: Arc<dyn Llm>) -> FallbackLlmBuilder {
278        FallbackLlmBuilder { models: vec![primary], triggers: FallbackTrigger::DEFAULT.to_vec() }
279    }
280
281    /// The models of the chain, first model first.
282    pub fn models(&self) -> &[Arc<dyn Llm>] {
283        &self.models
284    }
285
286    /// The triggers that move the chain to its next model.
287    pub fn triggers(&self) -> &[FallbackTrigger] {
288        &self.triggers
289    }
290
291    fn falls_back_on(&self, trigger: FallbackTrigger) -> bool {
292        self.triggers.contains(&trigger)
293    }
294
295    /// Tries each model in turn, metering every attempt against `scope` when there is one.
296    async fn generate(
297        &self,
298        scope: Option<&ModelCallScope>,
299        request: LlmRequest,
300        stream: bool,
301    ) -> Result<LlmResponseStream> {
302        let mut skipped: Vec<Value> = Vec::new();
303        let mut models = self.models.iter().enumerate().peekable();
304        while let Some((position, model)) = models.next() {
305            let has_next = models.peek().is_some();
306            let mut attempt = request.clone();
307            attempt.model = model.name().to_string();
308            let started = match scope {
309                Some(scope) => scope.generate(model.as_ref(), attempt, stream).await,
310                None => model.generate_content(attempt, stream).await,
311            };
312            let mut responses = match started {
313                Ok(responses) => responses,
314                Err(error) => {
315                    let trigger =
316                        FallbackTrigger::for_error(&error).filter(|t| self.falls_back_on(*t));
317                    match trigger {
318                        Some(trigger) if has_next => {
319                            skipped.push(self.skip(model.as_ref(), trigger, Some(error.code)));
320                            continue;
321                        }
322                        _ => return Err(error),
323                    }
324                }
325            };
326            let first = responses.next().await;
327            let trigger = match &first {
328                Some(Err(error)) => {
329                    FallbackTrigger::for_error(error).filter(|t| self.falls_back_on(*t))
330                }
331                Some(Ok(response)) => (response.finish_reason == Some(FinishReason::Refusal)
332                    && self.falls_back_on(FallbackTrigger::Refusal))
333                .then_some(FallbackTrigger::Refusal),
334                None => None,
335            };
336            if let Some(trigger) = trigger
337                && has_next
338            {
339                let code = match &first {
340                    Some(Err(error)) => Some(error.code),
341                    _ => None,
342                };
343                // Read to the end so the attempt's spend settles — a refusal is billed —
344                // before the next model reserves.
345                while responses.next().await.is_some() {}
346                skipped.push(self.skip(model.as_ref(), trigger, code));
347                continue;
348            }
349            let responses: LlmResponseStream = match first {
350                Some(first) => Box::pin(futures::stream::iter([first]).chain(responses)),
351                None => responses,
352            };
353            if skipped.is_empty() {
354                return Ok(responses);
355            }
356            tracing::info!(
357                fallback.model = %model.name(),
358                fallback.position = position,
359                "fallback model answered"
360            );
361            let marker = json!({
362                "model": model.name(),
363                "position": position,
364                "skipped": skipped,
365            });
366            return Ok(Box::pin(responses.map(move |item| {
367                item.map(|mut response| {
368                    if !response.partial {
369                        mark(&mut response, &marker);
370                    }
371                    response
372                })
373            })));
374        }
375        Err(AdkError::new(
376            ErrorComponent::Model,
377            ErrorCategory::InvalidInput,
378            "model.fallback.empty",
379            "the fallback chain has no model; build it with FallbackLlm::builder",
380        ))
381    }
382
383    /// Records one skipped model: a `warn` event and its entry in the response metadata.
384    fn skip(&self, model: &dyn Llm, trigger: FallbackTrigger, code: Option<&str>) -> Value {
385        tracing::warn!(
386            fallback.from = %model.name(),
387            fallback.reason = trigger.as_str(),
388            error.code = code.unwrap_or(""),
389            "model failed; trying the next model in the fallback chain"
390        );
391        let mut entry = json!({ "model": model.name(), "reason": trigger.as_str() });
392        if let Some(code) = code {
393            entry["error_code"] = json!(code);
394        }
395        entry
396    }
397}
398
399/// Adds the fallback marker to `response`'s provider metadata, keeping what the provider set.
400fn mark(response: &mut LlmResponse, marker: &Value) {
401    match response.provider_metadata.get_or_insert_with(|| json!({})) {
402        Value::Object(fields) => {
403            fields.insert(FALLBACK_METADATA_KEY.to_string(), marker.clone());
404        }
405        other => {
406            let original = std::mem::take(other);
407            *other = json!({ "provider": original, FALLBACK_METADATA_KEY: marker.clone() });
408        }
409    }
410}
411
412impl FallbackLlmBuilder {
413    /// Appends `model` to the chain, after the models already in it.
414    pub fn fallback(mut self, model: Arc<dyn Llm>) -> Self {
415        self.models.push(model);
416        self
417    }
418
419    /// Moves the chain on when `trigger` matches.
420    pub fn fall_back_on(mut self, trigger: FallbackTrigger) -> Self {
421        if !self.triggers.contains(&trigger) {
422            self.triggers.push(trigger);
423        }
424        self
425    }
426
427    /// Returns the error, or the refusal, when `trigger` matches, instead of moving on.
428    pub fn never_fall_back_on(mut self, trigger: FallbackTrigger) -> Self {
429        self.triggers.retain(|existing| *existing != trigger);
430        self
431    }
432
433    /// Replaces the triggers with `triggers`.
434    pub fn triggers(mut self, triggers: impl IntoIterator<Item = FallbackTrigger>) -> Self {
435        self.triggers.clear();
436        for trigger in triggers {
437            self = self.fall_back_on(trigger);
438        }
439        self
440    }
441
442    /// Builds the chain.
443    pub fn build(self) -> FallbackLlm {
444        FallbackLlm { models: self.models, triggers: self.triggers }
445    }
446}
447
448#[async_trait]
449impl Llm for FallbackLlm {
450    fn name(&self) -> &str {
451        self.models.first().map_or("fallback", |model| model.name())
452    }
453
454    async fn generate_content(&self, req: LlmRequest, stream: bool) -> Result<LlmResponseStream> {
455        self.generate(None, req, stream).await
456    }
457
458    async fn generate_content_metered(
459        &self,
460        scope: &ModelCallScope,
461        req: LlmRequest,
462        stream: bool,
463    ) -> Result<LlmResponseStream> {
464        self.generate(Some(scope), req, stream).await
465    }
466
467    fn schema_adapter(&self) -> &dyn SchemaAdapter {
468        match self.models.first() {
469            Some(model) => model.schema_adapter(),
470            None => &adk_core::GenericSchemaAdapter,
471        }
472    }
473
474    fn uses_interactions_api(&self) -> bool {
475        self.models.iter().any(|model| model.uses_interactions_api())
476    }
477
478    fn max_cost_micro_usd(&self, request: &LlmRequest) -> Option<u64> {
479        let bounds = self
480            .models
481            .iter()
482            .map(|model| {
483                let mut attempt = request.clone();
484                attempt.model = model.name().to_string();
485                model.max_cost_micro_usd(&attempt)
486            })
487            .collect::<Option<Vec<u64>>>()?;
488        if self.falls_back_on(FallbackTrigger::Refusal) {
489            Some(bounds.into_iter().fold(0u64, u64::saturating_add))
490        } else {
491            bounds.into_iter().max()
492        }
493    }
494
495    fn context_window(&self) -> Option<u64> {
496        let windows = self.models.iter().filter_map(|model| model.context_window());
497        if self.falls_back_on(FallbackTrigger::ContextOverflow) {
498            windows.max()
499        } else {
500            windows.min()
501        }
502    }
503
504    fn native_web_search(&self) -> Option<NativeWebSearch> {
505        let mut searches = self.models.iter().map(|model| model.native_web_search());
506        let first = searches.next()??;
507        searches.all(|search| search == Some(first)).then_some(first)
508    }
509
510    // A compaction request may fall back to any model in the chain, so it is native only when
511    // every model compacts the same way.
512    fn native_compaction(&self) -> Option<adk_core::NativeCompaction> {
513        let mut compactions = self.models.iter().map(|model| model.native_compaction());
514        let first = compactions.next()??;
515        compactions.all(|compaction| compaction == Some(first)).then_some(first)
516    }
517
518    // A call may fall back to any model in the chain, so its data goes as far as the least
519    // local of them.
520    fn data_locality(&self) -> adk_core::DataLocality {
521        adk_core::DataLocality::least_local(self.models.iter().map(|model| model.data_locality()))
522    }
523
524    // Every model's destinations, since a call may reach any of them; none when any model's
525    // destination is unknown.
526    fn data_destinations(&self) -> Vec<adk_core::DataDestination> {
527        let mut destinations = Vec::new();
528        for model in &self.models {
529            let theirs = model.data_destinations();
530            if theirs.is_empty() {
531                return Vec::new();
532            }
533            for destination in theirs {
534                if !destinations.contains(&destination) {
535                    destinations.push(destination);
536                }
537            }
538        }
539        destinations
540    }
541
542    /// Prewarms the first model, which serves the next call; the fallbacks are prewarmed too,
543    /// and their failures only logged.
544    async fn prewarm(&self) -> Result<()> {
545        let mut models = self.models.iter();
546        let Some(first) = models.next() else { return Ok(()) };
547        for model in models {
548            if let Err(error) = model.prewarm().await {
549                tracing::debug!(model = model.name(), error = %error, "a fallback model did not prewarm");
550            }
551        }
552        first.prewarm().await
553    }
554}
555
556#[cfg(test)]
557mod tests {
558    use super::*;
559    use crate::{ScriptedLlm, ScriptedResponse};
560    use adk_core::{
561        BudgetTracker, Content, GovernanceControl, InMemorySpendLedger, NativeWebSearchTool,
562        RunBudget, SpendKey, SpendLedger, SpendLimits, SpendPeriod, UsageMetadata,
563    };
564
565    fn error(category: ErrorCategory, code: &'static str) -> AdkError {
566        AdkError::new(ErrorComponent::Model, category, code, format!("{code} failure"))
567    }
568
569    fn unavailable() -> AdkError {
570        error(ErrorCategory::Unavailable, "model.test.unavailable")
571    }
572
573    /// A complete answer `text` from `model` at `provider`, reporting `cost` in USD.
574    fn answer(text: &str, model: &str, provider: &str, cost: f64) -> ScriptedResponse {
575        let mut response = LlmResponse::new(Content::new("model").with_text(text));
576        response.model = Some(model.to_string());
577        response.provider = Some(provider.to_string());
578        response.usage_metadata = Some(UsageMetadata {
579            prompt_token_count: 10,
580            candidates_token_count: 5,
581            total_token_count: 15,
582            cost: Some(cost),
583            ..Default::default()
584        });
585        ScriptedResponse::response(response)
586    }
587
588    /// A refusal before any output, as Anthropic's classifiers return one.
589    fn refusal(model: &str, provider: &str, cost: f64) -> ScriptedResponse {
590        let response = LlmResponse {
591            finish_reason: Some(FinishReason::Refusal),
592            turn_complete: true,
593            model: Some(model.to_string()),
594            provider: Some(provider.to_string()),
595            usage_metadata: Some(UsageMetadata {
596                prompt_token_count: 10,
597                total_token_count: 10,
598                cost: Some(cost),
599                ..Default::default()
600            }),
601            ..Default::default()
602        };
603        ScriptedResponse::response(response)
604    }
605
606    fn partial(text: &str) -> LlmResponse {
607        let mut response = LlmResponse::new(Content::new("model").with_text(text));
608        response.partial = true;
609        response.turn_complete = false;
610        response.finish_reason = None;
611        response
612    }
613
614    fn scripted<R: Into<ScriptedResponse>>(
615        name: &str,
616        script: impl IntoIterator<Item = R>,
617    ) -> Arc<ScriptedLlm> {
618        Arc::new(ScriptedLlm::new(name, script))
619    }
620
621    fn request() -> LlmRequest {
622        LlmRequest::new("claude-sonnet-5-5", vec![Content::new("user").with_text("hello")])
623    }
624
625    async fn collect(model: &FallbackLlm, stream: bool) -> Vec<Result<LlmResponse>> {
626        model.generate_content(request(), stream).await.unwrap().collect().await
627    }
628
629    fn text(response: &LlmResponse) -> String {
630        response.content.iter().flat_map(|c| c.parts.iter()).filter_map(|p| p.text()).collect()
631    }
632
633    #[tokio::test]
634    async fn a_retryable_error_moves_to_the_next_model() {
635        let primary = scripted("claude-sonnet-5-5", [ScriptedResponse::error(unavailable())]);
636        let backup =
637            scripted("gemini-3.7-flash", [answer("hi", "gemini-3.7-flash", "gemini", 0.0)]);
638        let model = FallbackLlm::builder(primary.clone()).fallback(backup.clone()).build();
639
640        let responses = collect(&model, false).await;
641        let response = responses[0].as_ref().unwrap();
642        assert_eq!(text(response), "hi");
643        assert_eq!(response.model.as_deref(), Some("gemini-3.7-flash"));
644        assert_eq!(
645            response.provider_metadata.as_ref().unwrap()[FALLBACK_METADATA_KEY],
646            json!({
647                "model": "gemini-3.7-flash",
648                "position": 1,
649                "skipped": [{
650                    "model": "claude-sonnet-5-5",
651                    "reason": "retryable",
652                    "error_code": "model.test.unavailable",
653                }],
654            })
655        );
656        assert_eq!(primary.last_request().unwrap().model, "claude-sonnet-5-5");
657        assert_eq!(backup.last_request().unwrap().model, "gemini-3.7-flash");
658    }
659
660    #[tokio::test]
661    async fn rate_limits_timeouts_unknown_models_and_spent_quotas_fall_back_by_default() {
662        for (category, reason) in [
663            (ErrorCategory::RateLimited, "retryable"),
664            (ErrorCategory::Timeout, "retryable"),
665            (ErrorCategory::NotFound, "model_not_found"),
666            (ErrorCategory::ResourceExhausted, "quota_exhausted"),
667        ] {
668            let primary =
669                scripted("claude-sonnet-5-5", [ScriptedResponse::error(error(category, "x"))]);
670            let backup = scripted("claude-haiku-5-5", [ScriptedResponse::text("ok")]);
671            let model = FallbackLlm::builder(primary).fallback(backup).build();
672            let responses = collect(&model, false).await;
673            let marker = &responses[0].as_ref().unwrap().provider_metadata.as_ref().unwrap()
674                [FALLBACK_METADATA_KEY];
675            assert_eq!(marker["skipped"][0]["reason"], reason, "{category:?}");
676        }
677    }
678
679    #[tokio::test]
680    async fn an_error_at_the_start_of_the_stream_falls_back() {
681        let primary = scripted(
682            "claude-sonnet-5-5",
683            [ScriptedResponse::stream(Vec::<LlmResponse>::new()).then_error(unavailable())],
684        );
685        let backup = scripted("claude-haiku-5-5", [ScriptedResponse::text("ok")]);
686        let model = FallbackLlm::builder(primary).fallback(backup).build();
687
688        let responses = collect(&model, true).await;
689        assert_eq!(responses.len(), 1);
690        assert_eq!(text(responses[0].as_ref().unwrap()), "ok");
691    }
692
693    #[tokio::test]
694    async fn auth_and_permission_errors_are_returned_unless_configured() {
695        for category in [ErrorCategory::Unauthorized, ErrorCategory::Forbidden] {
696            let primary =
697                scripted("claude-sonnet-5-5", [ScriptedResponse::error(error(category, "auth"))]);
698            let backup = scripted("claude-haiku-5-5", [ScriptedResponse::text("ok")]);
699            let model = FallbackLlm::builder(primary).fallback(backup.clone()).build();
700            let failed = model.generate_content(request(), false).await.err().unwrap();
701            assert_eq!(failed.category, category);
702            assert!(backup.requests().is_empty());
703
704            let primary =
705                scripted("claude-sonnet-5-5", [ScriptedResponse::error(error(category, "auth"))]);
706            let backup = scripted("claude-haiku-5-5", [ScriptedResponse::text("ok")]);
707            let model = FallbackLlm::builder(primary)
708                .fallback(backup)
709                .fall_back_on(FallbackTrigger::AuthFailure)
710                .build();
711            assert_eq!(text(collect(&model, false).await[0].as_ref().unwrap()), "ok");
712        }
713    }
714
715    #[tokio::test]
716    async fn a_refusal_falls_back_only_when_configured() {
717        let primary =
718            scripted("claude-sonnet-5-5", [refusal("claude-sonnet-5-5", "anthropic", 0.0)]);
719        let backup = scripted("claude-opus-5-5", [ScriptedResponse::text("ok")]);
720        let model = FallbackLlm::builder(primary).fallback(backup.clone()).build();
721        let responses = collect(&model, false).await;
722        assert_eq!(responses[0].as_ref().unwrap().finish_reason, Some(FinishReason::Refusal));
723        assert!(backup.requests().is_empty());
724
725        let primary =
726            scripted("claude-sonnet-5-5", [refusal("claude-sonnet-5-5", "anthropic", 0.0)]);
727        let backup = scripted("claude-opus-5-5", [ScriptedResponse::text("ok")]);
728        let model = FallbackLlm::builder(primary)
729            .fallback(backup)
730            .fall_back_on(FallbackTrigger::Refusal)
731            .build();
732        let responses = collect(&model, false).await;
733        let response = responses[0].as_ref().unwrap();
734        assert_eq!(text(response), "ok");
735        assert_eq!(
736            response.provider_metadata.as_ref().unwrap()[FALLBACK_METADATA_KEY]["skipped"][0],
737            json!({ "model": "claude-sonnet-5-5", "reason": "refusal" })
738        );
739    }
740
741    #[tokio::test]
742    async fn context_overflow_falls_back_only_when_configured() {
743        let invalid = || {
744            ScriptedResponse::error(error(ErrorCategory::InvalidInput, "model.anthropic.api_error"))
745        };
746        let overflow = || {
747            AdkError::new(
748                ErrorComponent::Model,
749                ErrorCategory::InvalidInput,
750                "model.anthropic.api_error",
751                "400: prompt is too long: 1048577 tokens > 1000000 maximum",
752            )
753        };
754        assert_eq!(FallbackTrigger::for_error(&overflow()), Some(FallbackTrigger::ContextOverflow));
755        // An invalid request that is not about length never falls back.
756        let primary = scripted("claude-haiku-4-5", [invalid()]);
757        let backup = scripted("claude-sonnet-5-5", [ScriptedResponse::text("ok")]);
758        let model = FallbackLlm::builder(primary)
759            .fallback(backup.clone())
760            .fall_back_on(FallbackTrigger::ContextOverflow)
761            .build();
762        assert!(model.generate_content(request(), false).await.is_err());
763        assert!(backup.requests().is_empty());
764
765        let primary = scripted("claude-haiku-4-5", [ScriptedResponse::error(overflow())]);
766        let backup = scripted("claude-sonnet-5-5", [ScriptedResponse::text("ok")]);
767        let model = FallbackLlm::builder(primary).fallback(backup.clone()).build();
768        assert!(model.generate_content(request(), false).await.is_err());
769        assert!(backup.requests().is_empty());
770
771        let primary = scripted("claude-haiku-4-5", [ScriptedResponse::error(overflow())]);
772        let backup = scripted("claude-sonnet-5-5", [ScriptedResponse::text("ok")]);
773        let model = FallbackLlm::builder(primary)
774            .fallback(backup)
775            .fall_back_on(FallbackTrigger::ContextOverflow)
776            .build();
777        assert_eq!(text(collect(&model, false).await[0].as_ref().unwrap()), "ok");
778    }
779
780    #[tokio::test]
781    async fn after_the_first_chunk_an_error_reaches_the_caller() {
782        let primary = scripted(
783            "claude-sonnet-5-5",
784            [ScriptedResponse::stream([partial("Hel")]).then_error(unavailable())],
785        );
786        let backup = scripted("claude-haiku-5-5", [ScriptedResponse::text("ok")]);
787        let model = FallbackLlm::builder(primary).fallback(backup.clone()).build();
788
789        let responses = collect(&model, true).await;
790        assert_eq!(text(responses[0].as_ref().unwrap()), "Hel");
791        assert_eq!(responses[1].as_ref().unwrap_err().code, "model.test.unavailable");
792        assert!(backup.requests().is_empty());
793    }
794
795    #[tokio::test]
796    async fn a_refusal_after_streamed_output_reaches_the_caller() {
797        let refused = LlmResponse {
798            finish_reason: Some(FinishReason::Refusal),
799            turn_complete: true,
800            ..Default::default()
801        };
802        let primary =
803            scripted("claude-sonnet-5-5", [ScriptedResponse::stream([partial("Sure"), refused])]);
804        let backup = scripted("claude-opus-5-5", [ScriptedResponse::text("ok")]);
805        let model = FallbackLlm::builder(primary)
806            .fallback(backup.clone())
807            .fall_back_on(FallbackTrigger::Refusal)
808            .build();
809
810        let responses = collect(&model, true).await;
811        assert_eq!(responses.len(), 2);
812        assert_eq!(responses[1].as_ref().unwrap().finish_reason, Some(FinishReason::Refusal));
813        assert!(backup.requests().is_empty());
814    }
815
816    #[tokio::test]
817    async fn when_every_model_fails_the_last_error_is_returned() {
818        let primary = scripted("claude-sonnet-5-5", [ScriptedResponse::error(unavailable())]);
819        let backup = scripted(
820            "claude-haiku-5-5",
821            [ScriptedResponse::error(error(ErrorCategory::RateLimited, "model.test.limited"))],
822        );
823        let model = FallbackLlm::builder(primary).fallback(backup).build();
824        let failed = model.generate_content(request(), false).await.err().unwrap();
825        assert_eq!(failed.code, "model.test.limited");
826
827        // The last model's refusal is its answer.
828        let primary = scripted("claude-sonnet-5-5", [ScriptedResponse::error(unavailable())]);
829        let backup = scripted("claude-opus-5-5", [refusal("claude-opus-5-5", "anthropic", 0.0)]);
830        let model = FallbackLlm::builder(primary)
831            .fallback(backup)
832            .fall_back_on(FallbackTrigger::Refusal)
833            .build();
834        let responses = collect(&model, false).await;
835        assert_eq!(responses[0].as_ref().unwrap().finish_reason, Some(FinishReason::Refusal));
836    }
837
838    #[tokio::test]
839    async fn a_model_that_answers_first_time_is_not_marked() {
840        let primary = scripted("claude-sonnet-5-5", [ScriptedResponse::text("ok")]);
841        let backup = scripted("claude-haiku-5-5", Vec::<ScriptedResponse>::new());
842        let model = FallbackLlm::builder(primary).fallback(backup).build();
843        let responses = collect(&model, false).await;
844        assert!(responses[0].as_ref().unwrap().provider_metadata.is_none());
845    }
846
847    fn ledger() -> Arc<InMemorySpendLedger> {
848        Arc::new(InMemorySpendLedger::new(SpendLimits::new()))
849    }
850
851    async fn spent(ledger: &InMemorySpendLedger, vendor: &str) -> u64 {
852        ledger.spent(&SpendKey::org("acme").with_vendor(vendor), SpendPeriod::Day).await.unwrap()
853    }
854
855    #[tokio::test]
856    async fn every_attempt_is_metered_under_its_own_provider() {
857        let ledger = ledger();
858        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
859        let scope = ModelCallScope::new()
860            .with_budget(tracker.clone())
861            .with_spend_ledger(ledger.clone(), "acme");
862        // A billed refusal on OpenAI, an outage on Gemini, the answer on Anthropic.
863        let refused = scripted("gpt-6.1-sol", [refusal("gpt-6.1-sol", "openai", 0.001)]);
864        let down = scripted("gemini-3.7-flash", [ScriptedResponse::error(unavailable())]);
865        let answers =
866            scripted("claude-haiku-5-5", [answer("ok", "claude-haiku-5-5", "anthropic", 0.002)]);
867        let model = FallbackLlm::builder(refused)
868            .fallback(down)
869            .fallback(answers)
870            .fall_back_on(FallbackTrigger::Refusal)
871            .build();
872
873        let mut responses = scope.generate(&model, request(), false).await.unwrap();
874        let response = responses.next().await.unwrap().unwrap();
875        assert!(responses.next().await.is_none());
876        assert_eq!(response.model.as_deref(), Some("claude-haiku-5-5"));
877
878        assert_eq!(spent(&ledger, "openai").await, 1_000);
879        assert_eq!(spent(&ledger, "gemini").await, 0);
880        assert_eq!(spent(&ledger, "anthropic").await, 2_000);
881        assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await.unwrap(), 3_000);
882        let usage = tracker.usage();
883        assert_eq!((usage.model_calls, usage.cost_micro_usd, usage.total_tokens), (3, 3_000, 25));
884    }
885
886    #[tokio::test]
887    async fn a_budget_refusal_ends_the_chain_without_falling_back() {
888        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(1)));
889        let scope = ModelCallScope::new().with_budget(tracker.clone());
890        let primary = scripted("claude-sonnet-5-5", [ScriptedResponse::error(unavailable())]);
891        let backup = scripted("claude-haiku-5-5", [ScriptedResponse::text("ok")]);
892        let model = FallbackLlm::builder(primary).fallback(backup.clone()).build();
893
894        let refused = scope.generate(&model, request(), false).await.err().unwrap();
895        assert_eq!(refused.category, ErrorCategory::ResourceExhausted);
896        assert!(backup.requests().is_empty());
897        assert_eq!(tracker.usage().model_calls, 1);
898    }
899
900    #[tokio::test]
901    async fn a_frozen_kill_switch_stops_the_chain_before_the_next_model() {
902        let control = GovernanceControl::new();
903        let scope = ModelCallScope::new().with_governance(control.clone());
904        let freezes = control.clone();
905        // The first model's failure is the moment an operator freezes the run.
906        struct FreezesOnCall {
907            inner: Arc<ScriptedLlm>,
908            control: GovernanceControl,
909        }
910        #[async_trait]
911        impl Llm for FreezesOnCall {
912            fn name(&self) -> &str {
913                self.inner.name()
914            }
915            async fn generate_content(
916                &self,
917                req: LlmRequest,
918                stream: bool,
919            ) -> Result<LlmResponseStream> {
920                self.control.freeze("incident");
921                self.inner.generate_content(req, stream).await
922            }
923        }
924        let primary = Arc::new(FreezesOnCall {
925            inner: scripted("claude-sonnet-5-5", [ScriptedResponse::error(unavailable())]),
926            control: freezes,
927        });
928        let backup = scripted("claude-haiku-5-5", [ScriptedResponse::text("ok")]);
929        let model = FallbackLlm::builder(primary).fallback(backup.clone()).build();
930
931        let refused = scope.generate(&model, request(), false).await.err().unwrap();
932        assert_eq!(refused.code, adk_core::GOVERNANCE_FROZEN_CODE);
933        assert!(backup.requests().is_empty());
934    }
935
936    struct Described {
937        name: &'static str,
938        window: Option<u64>,
939        bound: Option<u64>,
940        search: Option<NativeWebSearch>,
941    }
942
943    #[async_trait]
944    impl Llm for Described {
945        fn name(&self) -> &str {
946            self.name
947        }
948        async fn generate_content(&self, _: LlmRequest, _: bool) -> Result<LlmResponseStream> {
949            Ok(Box::pin(futures::stream::empty()))
950        }
951        fn context_window(&self) -> Option<u64> {
952            self.window
953        }
954        fn max_cost_micro_usd(&self, _: &LlmRequest) -> Option<u64> {
955            self.bound
956        }
957        fn native_web_search(&self) -> Option<NativeWebSearch> {
958            self.search
959        }
960    }
961
962    #[test]
963    fn a_mixed_chain_reports_the_limits_every_model_can_serve() {
964        let search =
965            NativeWebSearch::new("anthropic", NativeWebSearchTool::AnthropicWebSearch, true);
966        let small = Arc::new(Described {
967            name: "claude-haiku-4-5",
968            window: Some(200_000),
969            bound: Some(10_000),
970            search: Some(search),
971        });
972        let large = Arc::new(Described {
973            name: "claude-sonnet-5-5",
974            window: Some(1_000_000),
975            bound: Some(40_000),
976            search: Some(search),
977        });
978        let unknown =
979            Arc::new(Described { name: "local", window: None, bound: None, search: None });
980
981        let model = FallbackLlm::builder(small.clone()).fallback(large.clone()).build();
982        assert_eq!(model.name(), "claude-haiku-4-5");
983        assert_eq!(model.context_window(), Some(200_000));
984        assert_eq!(model.max_cost_micro_usd(&request()), Some(40_000));
985        assert_eq!(model.native_web_search(), Some(search));
986
987        let model = FallbackLlm::builder(small.clone())
988            .fallback(large.clone())
989            .fall_back_on(FallbackTrigger::ContextOverflow)
990            .fall_back_on(FallbackTrigger::Refusal)
991            .build();
992        assert_eq!(model.context_window(), Some(1_000_000));
993        assert_eq!(model.max_cost_micro_usd(&request()), Some(50_000));
994
995        let model = FallbackLlm::builder(small).fallback(large).fallback(unknown).build();
996        assert_eq!(model.context_window(), Some(200_000));
997        assert_eq!(model.max_cost_micro_usd(&request()), None);
998        assert_eq!(model.native_web_search(), None);
999    }
1000
1001    #[test]
1002    fn the_builder_edits_the_trigger_set() {
1003        let primary = scripted("claude-sonnet-5-5", Vec::<ScriptedResponse>::new());
1004        let model = FallbackLlm::builder(primary.clone())
1005            .triggers([FallbackTrigger::Refusal, FallbackTrigger::Refusal])
1006            .fall_back_on(FallbackTrigger::Retryable)
1007            .build();
1008        assert_eq!(model.triggers(), [FallbackTrigger::Refusal, FallbackTrigger::Retryable]);
1009        assert_eq!(model.models().len(), 1);
1010        assert_eq!(
1011            format!("{model:?}"),
1012            "FallbackLlm { models: [\"claude-sonnet-5-5\"], triggers: [Refusal, Retryable] }"
1013        );
1014    }
1015
1016    #[cfg(all(feature = "anthropic", feature = "gemini"))]
1017    #[test]
1018    fn a_chain_sends_to_every_models_destination_or_names_none() {
1019        use adk_core::DataDestination;
1020        let claude = Arc::new(
1021            crate::AnthropicClient::new(crate::anthropic::AnthropicConfig::new(
1022                "key",
1023                "claude-sonnet-5-5",
1024            ))
1025            .unwrap(),
1026        );
1027        let gemini = Arc::new(crate::GeminiModel::new("key", "gemini-3.8-flash").unwrap());
1028        let chain = FallbackLlm::builder(claude.clone()).fallback(gemini).build();
1029        assert_eq!(
1030            chain.data_destinations(),
1031            [
1032                DataDestination::new("anthropic", ["api.anthropic.com"]),
1033                DataDestination::new("gemini", ["generativelanguage.googleapis.com"]),
1034            ]
1035        );
1036
1037        let unknown = scripted("local", Vec::<ScriptedResponse>::new());
1038        let chain = FallbackLlm::builder(claude).fallback(unknown).build();
1039        assert!(chain.data_destinations().is_empty());
1040    }
1041}