graphrt-llm 0.9.0

Model providers (OpenAI-compatible, Anthropic, Gemini, AWS Bedrock, TypeSafe Jev) and LLM, classifier, extractor and agent nodes for the graphrt workflow runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
//! Failing over to fallback models when a provider is down.
//!
//! A node's `model` may list `fallbacks`, tried in order when a call fails for
//! a reason of the provider's infrastructure:
//!
//! ```yaml
//! model:
//!   provider: openai
//!   name: gpt-4o-mini
//!   fallbacks:
//!     - { provider: azure-openai, name: gpt-4o-mini }   # deployment name
//!     - { provider: anthropic, name: claude-haiku-4-5 }
//! ```
//!
//! - **What fails over** ([`fails_over`]): server errors (5xx), network errors
//!   (connection refused, TLS, timeouts, a stream cut before its first token)
//!   and a provider that does not answer within [`HEADERS_TIMEOUT`]. A rate
//!   limit (429) fails over only on the node's last attempt, after the node's
//!   own retries (`retry.max_retries`) are spent. Authentication, invalid
//!   requests, context length and content filtering never fail over: the
//!   caller gets that error, naming the model that gave it.
//! - **Streaming**: a candidate is only left before it streamed its first
//!   token (text, reasoning or a tool call). An error after that is the
//!   call's error, so nothing the user already saw is answered twice.
//! - **Circuit breaker** ([`Breakers`]): after [`BREAKER_THRESHOLD`] such
//!   failures in a row a provider is skipped for [`BREAKER_COOLDOWN`], then
//!   tried again (one success closes it). The last candidate is always tried.
//! - **Report**: the stream of a call that did not end at the first candidate
//!   starts with [`ChatDelta::Failover`], naming the model that answered and
//!   why each one before it was left (error texts are the providers' own,
//!   already scrubbed of credentials). Nodes charge the response at the price
//!   of the model that answered and report it as `model_failover` progress.

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use futures::StreamExt;
use futures::future::BoxFuture;
use graphrt_core::node::Clock;
use serde::{Deserialize, Serialize};

use crate::error::LlmError;
use crate::types::{ChatDelta, ChatModel, ChatRequest, ChatStream};

/// Failures in a row after which a provider is skipped.
pub const BREAKER_THRESHOLD: u32 = 3;
/// How long a provider is skipped once its breaker opened.
pub const BREAKER_COOLDOWN: Duration = Duration::from_secs(30);
/// How long a candidate with a fallback after it may take to answer a
/// request (its response headers) before the next one is tried. Streamed
/// tokens may take longer: reasoning models think before the first one.
pub const HEADERS_TIMEOUT: Duration = Duration::from_secs(30);

/// One model a call may be made with.
#[derive(Clone)]
pub struct Candidate {
    /// The provider name as configured (`model.provider`).
    pub provider: String,
    /// The model (or deployment) name sent to it.
    pub model: String,
    /// The provider's name in the registry, keying its breaker.
    pub breaker_key: String,
    pub chat: Arc<dyn ChatModel>,
}

impl std::fmt::Debug for Candidate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}/{}", self.provider, self.model)
    }
}

/// A model left during a call, and why.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FailedModel {
    pub provider: String,
    pub model: String,
    pub reason: String,
}

/// Which model answered a call that failed over, and the ones left before it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FailoverReport {
    pub provider: String,
    pub model: String,
    pub failed: Vec<FailedModel>,
}

/// Whether `error` moves a call on to the next candidate. A rate limit does
/// only when no retry of the node follows (`last_attempt`).
pub fn fails_over(error: &LlmError, last_attempt: bool) -> bool {
    match error {
        LlmError::Server { .. } | LlmError::Network(_) => true,
        LlmError::RateLimit { .. } => last_attempt,
        _ => false,
    }
}

/// Whether `error` counts against the provider's breaker (its service, not
/// the request, failed).
fn is_outage(error: &LlmError) -> bool {
    matches!(error, LlmError::Server { .. } | LlmError::Network(_) | LlmError::RateLimit { .. })
}

#[derive(Debug, Default, Clone, Copy)]
struct BreakerState {
    failures: u32,
    open_until: Option<Instant>,
}

/// Per-provider circuit breakers, shared by every clone of a
/// [`crate::ModelRegistry`] (so by every run of a process).
#[derive(Debug, Default)]
pub struct Breakers {
    states: Mutex<HashMap<String, BreakerState>>,
}

impl Breakers {
    fn states(&self) -> std::sync::MutexGuard<'_, HashMap<String, BreakerState>> {
        self.states.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Whether `provider` may be called at `now`: its breaker is closed, or
    /// its cooldown ended (the next call is the trial).
    pub fn allows(&self, provider: &str, now: Instant) -> bool {
        self.states().get(provider).and_then(|s| s.open_until).is_none_or(|until| now >= until)
    }

    /// A call to `provider` succeeded: its breaker closes.
    pub fn record_success(&self, provider: &str) {
        self.states().remove(provider);
    }

    /// A call to `provider` failed for an outage. Returns whether its breaker
    /// is open now.
    pub fn record_failure(&self, provider: &str, now: Instant) -> bool {
        let mut states = self.states();
        let state = states.entry(provider.to_owned()).or_default();
        state.failures = state.failures.saturating_add(1);
        if state.failures >= BREAKER_THRESHOLD {
            state.open_until = Some(now + BREAKER_COOLDOWN);
            return true;
        }
        false
    }
}

/// A chat model that tries its candidates in order (see the module docs).
/// `request.model` is replaced by each candidate's model.
pub struct FailoverModel {
    candidates: Vec<Candidate>,
    breakers: Arc<Breakers>,
    clock: Arc<dyn Clock>,
    last_attempt: bool,
    headers_timeout: Duration,
}

impl std::fmt::Debug for FailoverModel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FailoverModel").field("candidates", &self.candidates).finish_non_exhaustive()
    }
}

impl FailoverModel {
    /// `candidates`: the primary first. `last_attempt`: whether the node
    /// retries no more after this attempt (rate limits then fail over).
    pub fn new(candidates: Vec<Candidate>, breakers: Arc<Breakers>, clock: Arc<dyn Clock>, last_attempt: bool) -> Self {
        Self { candidates, breakers, clock, last_attempt, headers_timeout: HEADERS_TIMEOUT }
    }

    /// Change how long a candidate may take to answer (tests).
    pub fn with_headers_timeout(mut self, timeout: Duration) -> Self {
        self.headers_timeout = timeout;
        self
    }

    /// Start the call on `candidate`, up to its first token. `Ok` holds the
    /// deltas seen before it (usage, warnings) and the rest of the stream.
    async fn start(
        &self,
        candidate: &Candidate,
        request: ChatRequest,
        has_next: bool,
    ) -> Result<(Vec<ChatDelta>, ChatStream), LlmError> {
        let call = candidate.chat.chat(request);
        let mut stream = if has_next && self.clock.supports_timers() {
            let timeout = self.clock.sleep(self.headers_timeout);
            match futures::future::select(call, timeout).await {
                futures::future::Either::Left((result, _)) => result?,
                futures::future::Either::Right(((), _)) => {
                    return Err(LlmError::Network(format!(
                        "no answer within {} s",
                        self.headers_timeout.as_secs_f64()
                    )));
                }
            }
        } else {
            call.await?
        };
        let mut before = Vec::new();
        while let Some(item) = stream.next().await {
            let delta = item?;
            let token = matches!(delta, ChatDelta::Text(_) | ChatDelta::Reasoning(_) | ChatDelta::ToolCall { .. });
            before.push(delta);
            if token {
                break;
            }
        }
        Ok((before, stream))
    }
}

impl ChatModel for FailoverModel {
    fn chat(&self, request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>> {
        Box::pin(async move {
            let mut failed: Vec<FailedModel> = Vec::new();
            let last = self.candidates.len().saturating_sub(1);
            for (index, candidate) in self.candidates.iter().enumerate() {
                let has_next = index < last;
                if has_next && !self.breakers.allows(&candidate.breaker_key, Instant::now()) {
                    failed.push(FailedModel {
                        provider: candidate.provider.clone(),
                        model: candidate.model.clone(),
                        reason: format!("skipped: `{}` failed repeatedly just before", candidate.provider),
                    });
                    continue;
                }
                let mut attempt = request.clone();
                attempt.model.clone_from(&candidate.model);
                match self.start(candidate, attempt, has_next).await {
                    Ok((before, rest)) => {
                        self.breakers.record_success(&candidate.breaker_key);
                        let report = (!failed.is_empty()).then(|| {
                            ChatDelta::Failover(FailoverReport {
                                provider: candidate.provider.clone(),
                                model: candidate.model.clone(),
                                failed: std::mem::take(&mut failed),
                            })
                        });
                        let head = report.into_iter().chain(before).map(Ok);
                        return Ok(Box::pin(futures::stream::iter(head).chain(rest)) as ChatStream);
                    }
                    Err(error) => {
                        if is_outage(&error) {
                            self.breakers.record_failure(&candidate.breaker_key, Instant::now());
                        }
                        if !has_next || !fails_over(&error, self.last_attempt) {
                            return Err(explain(error, candidate, &failed));
                        }
                        failed.push(FailedModel {
                            provider: candidate.provider.clone(),
                            model: candidate.model.clone(),
                            reason: error.to_string(),
                        });
                    }
                }
            }
            Err(LlmError::Config("no model to call".into()))
        })
    }

    fn default_max_tokens(&self) -> Option<u32> {
        self.candidates.first().and_then(|c| c.chat.default_max_tokens())
    }
}

/// `error` of `candidate`, naming it and the models left before it.
fn explain(error: LlmError, candidate: &Candidate, failed: &[FailedModel]) -> LlmError {
    let mut prefix = format!("{}/{}: ", candidate.provider, candidate.model);
    if !failed.is_empty() {
        let earlier: Vec<String> =
            failed.iter().map(|f| format!("{}/{} ({})", f.provider, f.model, f.reason)).collect();
        prefix = format!("after {}; {prefix}", earlier.join("; "));
    }
    let with = |message: String| format!("{prefix}{message}");
    match error {
        LlmError::Auth(m) => LlmError::Auth(with(m)),
        LlmError::RateLimit { message, retry_after_ms } => {
            LlmError::RateLimit { message: with(message), retry_after_ms }
        }
        LlmError::ContextLength(m) => LlmError::ContextLength(with(m)),
        LlmError::BadRequest(m) => LlmError::BadRequest(with(m)),
        LlmError::Server { status, message } => LlmError::Server { status, message: with(message) },
        LlmError::Network(m) => LlmError::Network(with(m)),
        LlmError::Decode(m) => LlmError::Decode(with(m)),
        LlmError::Config(m) => LlmError::Config(with(m)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mock::MockModel;
    use crate::types::collect;
    use graphrt_core::node::NoTimerClock;

    fn candidate(provider: &str, model: &str, chat: Arc<dyn ChatModel>) -> Candidate {
        Candidate { provider: provider.into(), model: model.into(), breaker_key: provider.into(), chat }
    }

    fn failover(candidates: Vec<Candidate>, breakers: &Arc<Breakers>, last_attempt: bool) -> FailoverModel {
        FailoverModel::new(candidates, Arc::clone(breakers), Arc::new(NoTimerClock), last_attempt)
    }

    fn server_error() -> LlmError {
        LlmError::Server { status: 503, message: "unavailable".into() }
    }

    async fn ask(model: &FailoverModel) -> Result<crate::ChatResponse, LlmError> {
        let stream = model.chat(ChatRequest::new("ignored", vec![crate::Message::user("hi")])).await?;
        collect(stream, |_| {}).await
    }

    #[tokio::test]
    async fn infrastructure_errors_move_on_and_name_the_model_that_answered() {
        for error in [server_error(), LlmError::Network("connection refused".into())] {
            let primary = Arc::new(MockModel::default());
            primary.push_error(error.clone());
            let backup = Arc::new(MockModel::new(vec![MockModel::text("from backup")]));
            let breakers = Arc::new(Breakers::default());
            let model = failover(
                vec![
                    candidate("openai", "gpt-4o-mini", primary.clone()),
                    candidate("azure-openai", "dep", backup.clone()),
                ],
                &breakers,
                false,
            );
            let response = ask(&model).await.unwrap();
            assert_eq!(response.text, "from backup");
            let report = response.failover.unwrap();
            assert_eq!((report.provider.as_str(), report.model.as_str()), ("azure-openai", "dep"));
            assert_eq!(report.failed[0].reason, error.to_string());
            assert_eq!(primary.requests()[0].model, "gpt-4o-mini");
            assert_eq!(backup.requests()[0].model, "dep");
        }
    }

    #[tokio::test]
    async fn request_errors_never_move_on() {
        for error in [
            LlmError::Auth("invalid api key".into()),
            LlmError::BadRequest("invalid schema".into()),
            LlmError::ContextLength("too long".into()),
        ] {
            let primary = Arc::new(MockModel::default());
            primary.push_error(error.clone());
            let backup = Arc::new(MockModel::new(vec![MockModel::text("unused")]));
            let breakers = Arc::new(Breakers::default());
            let model = failover(
                vec![candidate("openai", "m", primary), candidate("anthropic", "c", backup.clone())],
                &breakers,
                true,
            );
            let got = ask(&model).await.unwrap_err();
            assert_eq!(got.kind(), error.kind());
            assert!(got.to_string().contains("openai/m: "), "{got}");
            assert!(backup.requests().is_empty());
            assert!(breakers.allows("openai", Instant::now()));
        }
    }

    #[tokio::test]
    async fn a_rate_limit_moves_on_only_when_the_node_retries_no_more() {
        let limited = || LlmError::RateLimit { message: "slow down".into(), retry_after_ms: Some(1000) };
        let primary = Arc::new(MockModel::default());
        primary.push_error(limited());
        let backup = Arc::new(MockModel::new(vec![MockModel::text("b")]));
        let breakers = Arc::new(Breakers::default());
        let retried = failover(
            vec![candidate("openai", "m", primary.clone()), candidate("b", "m", backup.clone())],
            &breakers,
            false,
        );
        let error = ask(&retried).await.unwrap_err();
        assert!(matches!(error, LlmError::RateLimit { retry_after_ms: Some(1000), .. }), "{error:?}");
        assert!(backup.requests().is_empty());

        primary.push_error(limited());
        let last = failover(vec![candidate("openai", "m", primary), candidate("b", "m", backup)], &breakers, true);
        assert_eq!(ask(&last).await.unwrap().text, "b");
    }

    #[tokio::test]
    async fn every_candidate_failing_names_them_all() {
        let primary = Arc::new(MockModel::default());
        primary.push_error(server_error());
        let backup = Arc::new(MockModel::default());
        backup.push_error(LlmError::Network("timed out".into()));
        let breakers = Arc::new(Breakers::default());
        let model =
            failover(vec![candidate("openai", "a", primary), candidate("anthropic", "b", backup)], &breakers, true);
        let error = ask(&model).await.unwrap_err();
        assert_eq!(error.kind(), "model_network");
        let text = error.to_string();
        assert!(text.contains("after openai/a (server error (503): unavailable); anthropic/b: timed out"), "{text}");
    }

    #[tokio::test]
    async fn the_breaker_skips_a_failing_provider_until_its_cooldown_ends() {
        let breakers = Arc::new(Breakers::default());
        let primary = Arc::new(MockModel::default());
        let backup = Arc::new(MockModel::default());
        for _ in 0..BREAKER_THRESHOLD {
            primary.push_error(server_error());
            backup.push(MockModel::text("b"));
            let model = failover(
                vec![candidate("openai", "a", primary.clone()), candidate("azure", "b", backup.clone())],
                &breakers,
                true,
            );
            assert_eq!(ask(&model).await.unwrap().text, "b");
        }
        assert_eq!(primary.requests().len(), 3);
        assert!(!breakers.allows("openai", Instant::now()));

        // Open: the primary is not called at all.
        backup.push(MockModel::text("b"));
        let model = failover(
            vec![candidate("openai", "a", primary.clone()), candidate("azure", "b", backup.clone())],
            &breakers,
            true,
        );
        let response = ask(&model).await.unwrap();
        assert_eq!(primary.requests().len(), 3);
        assert!(response.failover.unwrap().failed[0].reason.starts_with("skipped"));

        // After the cooldown one trial is let through; a success closes the breaker.
        assert!(breakers.allows("openai", Instant::now() + BREAKER_COOLDOWN));
        breakers.record_success("openai");
        primary.push(MockModel::text("a"));
        let model =
            failover(vec![candidate("openai", "a", primary.clone()), candidate("azure", "b", backup)], &breakers, true);
        let response = ask(&model).await.unwrap();
        assert_eq!(response.text, "a");
        assert!(response.failover.is_none());
    }

    #[tokio::test]
    async fn a_failed_trial_reopens_the_breaker_at_once() {
        let breakers = Breakers::default();
        let now = Instant::now();
        for _ in 0..BREAKER_THRESHOLD {
            breakers.record_failure("p", now);
        }
        let later = now + BREAKER_COOLDOWN;
        assert!(breakers.allows("p", later));
        assert!(breakers.record_failure("p", later));
        assert!(!breakers.allows("p", later + Duration::from_secs(1)));
    }

    #[tokio::test]
    async fn the_last_candidate_is_tried_even_with_its_breaker_open() {
        let breakers = Arc::new(Breakers::default());
        for _ in 0..BREAKER_THRESHOLD {
            breakers.record_failure("openai", Instant::now());
        }
        let only = Arc::new(MockModel::new(vec![MockModel::text("ok")]));
        let model = failover(vec![candidate("openai", "a", only)], &breakers, true);
        assert_eq!(ask(&model).await.unwrap().text, "ok");
        assert!(breakers.allows("openai", Instant::now()));
    }

    fn broken_after(deltas: Vec<ChatDelta>) -> Arc<dyn ChatModel> {
        #[derive(Debug)]
        struct Broken(Mutex<Option<Vec<ChatDelta>>>);
        impl ChatModel for Broken {
            fn chat(&self, _request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>> {
                let deltas = self.0.lock().unwrap().take().unwrap_or_default();
                Box::pin(async move {
                    let items = deltas.into_iter().map(Ok).chain([Err(LlmError::Network("connection reset".into()))]);
                    Ok(Box::pin(futures::stream::iter(items)) as ChatStream)
                })
            }
        }
        Arc::new(Broken(Mutex::new(Some(deltas))))
    }

    #[tokio::test]
    async fn a_stream_cut_before_its_first_token_moves_on() {
        let usage = graphrt_core::event::Usage { prompt_tokens: 3, completion_tokens: 0, total_tokens: 3 };
        let primary = broken_after(vec![ChatDelta::Usage(usage)]);
        let backup = Arc::new(MockModel::new(vec![MockModel::text("b")]));
        let breakers = Arc::new(Breakers::default());
        let model = failover(vec![candidate("openai", "a", primary), candidate("azure", "b", backup)], &breakers, true);
        let mut streamed = Vec::new();
        let stream = model.chat(ChatRequest::new("x", vec![])).await.unwrap();
        let response = collect(stream, |d| streamed.push(d)).await.unwrap();
        assert_eq!(response.text, "b");
        // Nothing of the cut stream reached the caller.
        assert!(matches!(streamed[0], ChatDelta::Failover(_)));
        assert_eq!(response.usage.prompt_tokens, 1);
    }

    #[tokio::test]
    async fn a_stream_cut_after_its_first_token_is_the_calls_error() {
        let primary = broken_after(vec![ChatDelta::Text("Hel".into())]);
        let backup = Arc::new(MockModel::new(vec![MockModel::text("b")]));
        let breakers = Arc::new(Breakers::default());
        let model =
            failover(vec![candidate("openai", "a", primary), candidate("azure", "b", backup.clone())], &breakers, true);
        let mut streamed = Vec::new();
        let stream = model.chat(ChatRequest::new("x", vec![])).await.unwrap();
        let error = collect(stream, |d| streamed.push(d)).await.unwrap_err();
        assert_eq!(error, LlmError::Network("connection reset".into()));
        assert_eq!(streamed, vec![ChatDelta::Text("Hel".into())]);
        assert!(backup.requests().is_empty());
    }

    #[tokio::test]
    async fn a_provider_that_does_not_answer_in_time_is_left() {
        #[derive(Debug)]
        struct Hangs;
        impl ChatModel for Hangs {
            fn chat(&self, _request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>> {
                Box::pin(futures::future::pending())
            }
        }
        #[derive(Debug)]
        struct TokioClock;
        impl Clock for TokioClock {
            fn now_ms(&self) -> u64 {
                0
            }
            fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()> {
                Box::pin(tokio::time::sleep(duration))
            }
        }
        let backup = Arc::new(MockModel::new(vec![MockModel::text("b")]));
        let model = FailoverModel::new(
            vec![candidate("openai", "a", Arc::new(Hangs)), candidate("azure", "b", backup)],
            Arc::new(Breakers::default()),
            Arc::new(TokioClock),
            true,
        )
        .with_headers_timeout(Duration::from_millis(20));
        let response = ask(&model).await.unwrap();
        assert_eq!(response.text, "b");
        assert!(response.failover.unwrap().failed[0].reason.contains("no answer within"));
    }
}