clawft-llm 0.5.1

LLM provider abstraction for clawft (OpenAI-compatible + native providers)
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
//! Provider failover: try the next provider when all retries are exhausted.
//!
//! [`FailoverChain`] takes a list of providers (each typically wrapped in
//! [`RetryPolicy`](crate::retry::RetryPolicy)) and calls them in order.
//! If one provider fails with a retryable error after exhausting its retries,
//! the chain moves to the next provider. Non-retryable errors (auth failure,
//! model not found) are returned immediately.

use async_trait::async_trait;
use tokio::sync::mpsc;
use tracing::warn;

use crate::error::{ProviderError, Result};
use crate::provider::Provider;
use crate::retry::is_retryable;
use crate::types::{ChatRequest, ChatResponse, StreamChunk};

/// A chain of providers that fails over to the next on transient errors.
///
/// # Example
///
/// ```rust,ignore
/// use clawft_llm::failover::FailoverChain;
/// use clawft_llm::retry::{RetryPolicy, RetryConfig};
/// use clawft_llm::OpenAiCompatProvider;
///
/// let providers: Vec<Box<dyn Provider>> = vec![
///     Box::new(RetryPolicy::new(primary, RetryConfig::default())),
///     Box::new(RetryPolicy::new(fallback, RetryConfig::default())),
/// ];
/// let chain = FailoverChain::new(providers);
/// let response = chain.complete(&request).await?;
/// ```
pub struct FailoverChain {
    providers: Vec<Box<dyn Provider>>,
}

impl FailoverChain {
    /// Create a failover chain from an ordered list of providers.
    ///
    /// The first provider is the primary; subsequent providers are fallbacks.
    /// Returns `None` if the list is empty.
    pub fn new(providers: Vec<Box<dyn Provider>>) -> Option<Self> {
        if providers.is_empty() {
            return None;
        }
        Some(Self { providers })
    }

    /// Returns the number of providers in the chain.
    pub fn len(&self) -> usize {
        self.providers.len()
    }

    /// Returns `true` if the chain has no providers.
    pub fn is_empty(&self) -> bool {
        self.providers.is_empty()
    }

    /// Returns the names of all providers in the chain, in order.
    pub fn provider_names(&self) -> Vec<&str> {
        self.providers.iter().map(|p| p.name()).collect()
    }
}

#[async_trait]
impl Provider for FailoverChain {
    fn name(&self) -> &str {
        // Report the primary provider's name
        self.providers
            .first()
            .map(|p| p.name())
            .unwrap_or("failover-chain")
    }

    async fn complete(&self, request: &ChatRequest) -> Result<ChatResponse> {
        let mut errors: Vec<(String, ProviderError)> = Vec::new();

        for (idx, provider) in self.providers.iter().enumerate() {
            match provider.complete(request).await {
                Ok(response) => return Ok(response),
                Err(err) => {
                    let provider_name = provider.name().to_owned();

                    // If the error is not retryable, don't try fallback providers
                    // for certain error classes
                    if !is_retryable(&err) && !is_failover_eligible(&err) {
                        return Err(err);
                    }

                    warn!(
                        provider = %provider_name,
                        provider_index = idx,
                        total_providers = self.providers.len(),
                        error = %err,
                        "provider failed, trying next in failover chain"
                    );

                    errors.push((provider_name, err));
                }
            }
        }

        // All providers exhausted
        let summary: Vec<String> = errors
            .iter()
            .map(|(name, err)| format!("{name}: {err}"))
            .collect();

        Err(ProviderError::AllProvidersExhausted { attempts: summary })
    }

    async fn complete_stream(
        &self,
        request: &ChatRequest,
        tx: mpsc::Sender<StreamChunk>,
    ) -> Result<()> {
        let mut errors: Vec<(String, ProviderError)> = Vec::new();

        for (idx, provider) in self.providers.iter().enumerate() {
            // Buffer chunks per attempt to prevent partial output concatenation.
            // Only forward buffered chunks to the real sender on success.
            let (attempt_tx, mut attempt_rx) = mpsc::channel::<StreamChunk>(256);

            match provider.complete_stream(request, attempt_tx).await {
                Ok(()) => {
                    // Success: forward all buffered chunks to the real sender.
                    while let Some(chunk) = attempt_rx.recv().await {
                        if tx.send(chunk).await.is_err() {
                            break;
                        }
                    }
                    return Ok(());
                }
                Err(err) => {
                    let provider_name = provider.name().to_owned();

                    // Discard buffered chunks from this failed attempt by
                    // dropping attempt_rx (already moved out of scope).

                    if !is_retryable(&err) && !is_failover_eligible(&err) {
                        return Err(err);
                    }

                    warn!(
                        provider = %provider_name,
                        provider_index = idx,
                        total_providers = self.providers.len(),
                        error = %err,
                        "provider streaming failed, trying next in failover chain"
                    );

                    errors.push((provider_name, err));
                }
            }
        }

        let summary: Vec<String> = errors
            .iter()
            .map(|(name, err)| format!("{name}: {err}"))
            .collect();

        Err(ProviderError::AllProvidersExhausted { attempts: summary })
    }
}

/// Determines whether a non-retryable error should still trigger failover
/// to the next provider (as opposed to immediately returning the error).
///
/// For example, if provider A is not configured but provider B is, we should
/// try provider B. Similarly, if provider A has exhausted credits/billing
/// but provider B is a free tier, we should try provider B.
fn is_failover_eligible(err: &ProviderError) -> bool {
    matches!(
        err,
        ProviderError::NotConfigured(_)
            | ProviderError::ModelNotFound(_)
            | ProviderError::RequestFailed(_)
            | ProviderError::InvalidResponse(_)
    )
}

impl std::fmt::Debug for FailoverChain {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FailoverChain")
            .field("providers", &self.provider_names())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{ChatMessage, ChatResponse, Choice, Usage};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU32, Ordering};

    fn test_request() -> ChatRequest {
        ChatRequest::new("test-model", vec![ChatMessage::user("Hi")])
    }

    fn success_response(model: &str) -> ChatResponse {
        ChatResponse {
            id: "resp-1".into(),
            choices: vec![Choice {
                index: 0,
                message: ChatMessage::assistant(format!("Hello from {model}")),
                finish_reason: Some("stop".into()),
            }],
            usage: Some(Usage {
                input_tokens: 10,
                output_tokens: 5,
                total_tokens: 15,
            }),
            model: model.into(),
        }
    }

    struct SuccessProvider {
        name: String,
    }

    #[async_trait]
    impl Provider for SuccessProvider {
        fn name(&self) -> &str {
            &self.name
        }
        async fn complete(&self, _req: &ChatRequest) -> Result<ChatResponse> {
            Ok(success_response(&self.name))
        }
    }

    struct FailProvider {
        name: String,
        error: fn() -> ProviderError,
    }

    #[async_trait]
    impl Provider for FailProvider {
        fn name(&self) -> &str {
            &self.name
        }
        async fn complete(&self, _req: &ChatRequest) -> Result<ChatResponse> {
            Err((self.error)())
        }
    }

    #[test]
    fn new_empty_returns_none() {
        assert!(FailoverChain::new(vec![]).is_none());
    }

    #[test]
    fn len_and_names() {
        let chain = FailoverChain::new(vec![
            Box::new(SuccessProvider { name: "a".into() }),
            Box::new(SuccessProvider { name: "b".into() }),
        ])
        .unwrap();
        assert_eq!(chain.len(), 2);
        assert!(!chain.is_empty());
        assert_eq!(chain.provider_names(), vec!["a", "b"]);
    }

    #[test]
    fn name_returns_primary() {
        let chain = FailoverChain::new(vec![
            Box::new(SuccessProvider {
                name: "primary".into(),
            }),
            Box::new(SuccessProvider {
                name: "fallback".into(),
            }),
        ])
        .unwrap();
        assert_eq!(chain.name(), "primary");
    }

    #[tokio::test]
    async fn primary_succeeds() {
        let chain = FailoverChain::new(vec![
            Box::new(SuccessProvider {
                name: "primary".into(),
            }),
            Box::new(SuccessProvider {
                name: "fallback".into(),
            }),
        ])
        .unwrap();

        let resp = chain.complete(&test_request()).await.unwrap();
        assert!(resp.choices[0].message.content.as_deref().unwrap().contains("primary"));
    }

    #[tokio::test]
    async fn failover_to_second_on_retryable_error() {
        let chain = FailoverChain::new(vec![
            Box::new(FailProvider {
                name: "broken".into(),
                error: || ProviderError::ServerError {
                    status: 503,
                    body: "unavailable".into(),
                },
            }),
            Box::new(SuccessProvider {
                name: "backup".into(),
            }),
        ])
        .unwrap();

        let resp = chain.complete(&test_request()).await.unwrap();
        assert!(resp.choices[0].message.content.as_deref().unwrap().contains("backup"));
    }

    #[tokio::test]
    async fn failover_on_not_configured() {
        let chain = FailoverChain::new(vec![
            Box::new(FailProvider {
                name: "unconfigured".into(),
                error: || ProviderError::NotConfigured("no API key".into()),
            }),
            Box::new(SuccessProvider {
                name: "configured".into(),
            }),
        ])
        .unwrap();

        let resp = chain.complete(&test_request()).await.unwrap();
        assert!(resp.choices[0].message.content.as_deref().unwrap().contains("configured"));
    }

    #[tokio::test]
    async fn no_failover_on_auth_error() {
        let call_count = Arc::new(AtomicU32::new(0));
        let count = call_count.clone();

        struct CountingSuccess {
            count: Arc<AtomicU32>,
        }
        #[async_trait]
        impl Provider for CountingSuccess {
            fn name(&self) -> &str {
                "counter"
            }
            async fn complete(&self, _req: &ChatRequest) -> Result<ChatResponse> {
                self.count.fetch_add(1, Ordering::SeqCst);
                Ok(success_response("counter"))
            }
        }

        let chain = FailoverChain::new(vec![
            Box::new(FailProvider {
                name: "authed".into(),
                error: || ProviderError::AuthFailed("bad key".into()),
            }),
            Box::new(CountingSuccess { count }),
        ])
        .unwrap();

        let err = chain.complete(&test_request()).await.unwrap_err();
        assert!(matches!(err, ProviderError::AuthFailed(_)));
        // The second provider should NOT have been called
        assert_eq!(call_count.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn all_providers_exhausted() {
        let chain = FailoverChain::new(vec![
            Box::new(FailProvider {
                name: "p1".into(),
                error: || ProviderError::ServerError {
                    status: 500,
                    body: "error".into(),
                },
            }),
            Box::new(FailProvider {
                name: "p2".into(),
                error: || ProviderError::Timeout,
            }),
        ])
        .unwrap();

        let err = chain.complete(&test_request()).await.unwrap_err();
        match err {
            ProviderError::AllProvidersExhausted { attempts } => {
                assert_eq!(attempts.len(), 2);
                assert!(attempts[0].contains("p1"));
                assert!(attempts[1].contains("p2"));
            }
            other => panic!("expected AllProvidersExhausted, got: {other}"),
        }
    }

    #[tokio::test]
    async fn failover_through_three_providers() {
        let chain = FailoverChain::new(vec![
            Box::new(FailProvider {
                name: "p1".into(),
                error: || ProviderError::ServerError {
                    status: 502,
                    body: "bad gateway".into(),
                },
            }),
            Box::new(FailProvider {
                name: "p2".into(),
                error: || ProviderError::NotConfigured("no key".into()),
            }),
            Box::new(SuccessProvider { name: "p3".into() }),
        ])
        .unwrap();

        let resp = chain.complete(&test_request()).await.unwrap();
        assert!(resp.choices[0].message.content.as_deref().unwrap().contains("p3"));
    }

    #[test]
    fn is_failover_eligible_not_configured() {
        assert!(super::is_failover_eligible(&ProviderError::NotConfigured(
            "missing".into()
        )));
    }

    #[test]
    fn is_failover_eligible_model_not_found() {
        assert!(super::is_failover_eligible(&ProviderError::ModelNotFound(
            "gpt-5".into()
        )));
    }

    #[test]
    fn is_failover_eligible_request_failed() {
        assert!(super::is_failover_eligible(&ProviderError::RequestFailed(
            "credits exhausted".into()
        )));
    }

    #[test]
    fn is_failover_eligible_invalid_response() {
        assert!(super::is_failover_eligible(
            &ProviderError::InvalidResponse("bad json".into())
        ));
    }

    #[tokio::test]
    async fn failover_on_billing_error() {
        let chain = FailoverChain::new(vec![
            Box::new(FailProvider {
                name: "paid".into(),
                error: || ProviderError::RequestFailed("credits exhausted".into()),
            }),
            Box::new(SuccessProvider {
                name: "free".into(),
            }),
        ])
        .unwrap();

        let resp = chain.complete(&test_request()).await.unwrap();
        assert!(resp.choices[0].message.content.as_deref().unwrap().contains("free"));
    }

    #[test]
    fn is_not_failover_eligible_auth() {
        assert!(!super::is_failover_eligible(&ProviderError::AuthFailed(
            "bad key".into()
        )));
    }
}