troupekit-providers 0.4.0

Model providers for the Troupekit LLM agent framework: wire protocols, catalog, transports and middleware.
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
use crate::catalog::Price;
use crate::model::{FailedCall, Model};
use crate::request::{CompletionRequest, CompletionResponse, Delta};
use crate::status::bad_request;
use async_trait::async_trait;
use std::sync::Arc;
use std::time::Duration;
use troupekit_core::error::ProviderError;
use troupekit_core::event::Usage;
use troupekit_trace::{trace, Trace};

/// Waits between retries. `TokioSleep` is the real clock; tests inject a
/// recorder so no test sleeps.
/// `ms` is the wait in milliseconds.
#[async_trait]
pub trait Sleep: Send + Sync {
    async fn sleep(&self, ms: u64);
}

/// Sleeps on the tokio timer, the default for `RetryModel`.
/// Needs a running tokio runtime with the timer enabled.
/// Holds no state.
#[derive(Debug, Clone, Copy, Default)]
pub struct TokioSleep;

#[async_trait]
impl Sleep for TokioSleep {
    async fn sleep(&self, ms: u64) {
        tokio::time::sleep(Duration::from_millis(ms)).await;
    }
}

/// How often and how long `RetryModel` retries: `max_attempts` tries in
/// all, exponential waits from `base_delay_ms`, never waiting longer than
/// `max_delay_ms`. Defaults to 3 tries, 500 ms base, 30 s cap.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RetryPolicy {
    pub max_attempts: u32,
    pub base_delay_ms: u64,
    pub max_delay_ms: u64,
}

impl Default for RetryPolicy {
    fn default() -> Self {
        Self {
            max_attempts: 3,
            base_delay_ms: 500,
            max_delay_ms: 30_000,
        }
    }
}

impl RetryPolicy {
    /// Wait before the next try after `failures` failed tries, the last
    /// ending in `err`. Returns `None` to give up: not retryable, tries
    /// used up, or the server asked to wait past `max_delay_ms`.
    pub fn next_delay_ms(&self, failures: u32, err: &ProviderError) -> Option<u64> {
        assert!(failures >= 1, "asked for a retry delay before any failure");
        if !err.is_retryable() || failures >= self.max_attempts {
            return None;
        }
        match err.retry_after_ms {
            Some(ms) if ms <= self.max_delay_ms => Some(ms),
            Some(_) => None,
            None => Some(
                self.base_delay_ms
                    .saturating_mul(1u64 << (failures - 1).min(32))
                    .min(self.max_delay_ms),
            ),
        }
    }
}

/// Retries an inner model on transient failures, honouring server retry
/// delays. A stream is retried only while no delta has reached the
/// caller, so a UI never sees a reply twice.
pub struct RetryModel {
    inner: Box<dyn Model>,
    policy: RetryPolicy,
    sleep: Arc<dyn Sleep>,
}

impl RetryModel {
    /// Wraps `inner` with `policy`, waiting on the tokio clock.
    /// Returns `BadRequest` when `max_attempts` is not 1 to 10 or the
    /// base delay is above the max delay.
    pub fn new(inner: Box<dyn Model>, policy: RetryPolicy) -> Result<Self, ProviderError> {
        if !(1..=10).contains(&policy.max_attempts) {
            return Err(bad_request("retry max_attempts must be 1 to 10"));
        }
        if policy.base_delay_ms > policy.max_delay_ms {
            return Err(bad_request("retry base delay is above its max delay"));
        }
        Ok(Self {
            inner,
            policy,
            sleep: Arc::new(TokioSleep),
        })
    }

    /// Replaces the clock with `sleep`, so tests record waits instead of
    /// waiting. Returns the model.
    /// The policy is unchanged.
    pub fn with_sleep(mut self, sleep: Arc<dyn Sleep>) -> Self {
        self.sleep = sleep;
        self
    }

    fn trace_retry(&self, failures: u32, wait_ms: u64, err: &ProviderError) {
        trace!(
            Trace::Models,
            "model.retry",
            model = self.inner.id(),
            failures = failures,
            wait_ms = wait_ms,
            kind = format!("{:?}", err.kind),
        );
    }
}

#[async_trait]
impl Model for RetryModel {
    fn id(&self) -> &str {
        self.inner.id()
    }

    fn prices_replies(&self) -> bool {
        self.inner.prices_replies()
    }

    fn meter_price(&self) -> Option<Price> {
        self.inner.meter_price()
    }

    fn extra_calls(&self, req: &CompletionRequest) -> u32 {
        self.inner.extra_calls(req)
    }

    async fn complete(&self, req: &CompletionRequest) -> Result<CompletionResponse, ProviderError> {
        self.complete_billed(req).await.map_err(|failed| failed.error)
    }

    async fn stream(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<CompletionResponse, ProviderError> {
        self.stream_billed(req, on_delta)
            .await
            .map_err(|failed| failed.error)
    }

    async fn complete_billed(
        &self,
        req: &CompletionRequest,
    ) -> Result<CompletionResponse, FailedCall> {
        let mut failures = 0;
        let mut spent = Usage::default();
        loop {
            let failed = match self.inner.complete_billed(req).await {
                Ok(reply) => return Ok(with_spent(reply, spent)),
                Err(failed) => failed,
            };
            spent += failed.usage;
            failures += 1;
            match self.policy.next_delay_ms(failures, &failed.error) {
                Some(ms) => {
                    self.trace_retry(failures, ms, &failed.error);
                    self.sleep.sleep(ms).await
                }
                None => return Err(spent_on(failed.error, spent)),
            }
        }
    }

    async fn stream_billed(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<CompletionResponse, FailedCall> {
        let mut failures = 0;
        let mut spent = Usage::default();
        loop {
            let mut emitted = false;
            let result = self
                .inner
                .stream_billed(req, &mut |d: &Delta| {
                    emitted = true;
                    on_delta(d);
                })
                .await;
            let failed = match result {
                Ok(reply) => return Ok(with_spent(reply, spent)),
                Err(failed) => failed,
            };
            spent += failed.usage;
            if emitted {
                return Err(spent_on(failed.error, spent));
            }
            failures += 1;
            match self.policy.next_delay_ms(failures, &failed.error) {
                Some(ms) => {
                    self.trace_retry(failures, ms, &failed.error);
                    self.sleep.sleep(ms).await
                }
                None => return Err(spent_on(failed.error, spent)),
            }
        }
    }
}

/// Adds `spent`, the usage of the failed tries before `reply`, to the
/// reply, so a caller bills every try a wrapper made. Output: the reply.
fn with_spent(mut reply: CompletionResponse, spent: Usage) -> CompletionResponse {
    reply.usage += spent;
    reply
}

/// The failure a wrapper returns after its last try: `error`, billed
/// with `spent`, the usage every failed try reported. Output: the call.
fn spent_on(error: ProviderError, spent: Usage) -> FailedCall {
    FailedCall {
        error,
        usage: spent,
    }
}

/// Tries an ordered list of models and returns the first success, or
/// the last error when all fail. A stream moves on only while no delta
/// has reached the caller.
pub struct FallbackModel {
    id: String,
    models: Vec<Box<dyn Model>>,
}

impl FallbackModel {
    /// Builds a fallback chain from `first` then each of `rest`, so the
    /// chain is never empty. Its id is the model ids joined by commas.
    /// Returns the chain.
    pub fn new(first: Box<dyn Model>, rest: Vec<Box<dyn Model>>) -> Self {
        let mut models = vec![first];
        models.extend(rest);
        let id = models.iter().map(|m| m.id()).collect::<Vec<_>>().join(",");
        Self { id, models }
    }
}

#[async_trait]
impl Model for FallbackModel {
    fn id(&self) -> &str {
        &self.id
    }

    fn prices_replies(&self) -> bool {
        self.models.iter().all(|m| m.prices_replies())
    }

    fn meter_price(&self) -> Option<Price> {
        let first = self.models.first()?.meter_price()?;
        let same = self.models.iter().all(|m| m.meter_price() == Some(first));
        same.then_some(first)
    }

    fn extra_calls(&self, req: &CompletionRequest) -> u32 {
        self.models
            .iter()
            .map(|m| m.extra_calls(req))
            .max()
            .unwrap_or(0)
    }

    async fn complete(&self, req: &CompletionRequest) -> Result<CompletionResponse, ProviderError> {
        self.complete_billed(req).await.map_err(|failed| failed.error)
    }

    async fn stream(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<CompletionResponse, ProviderError> {
        self.stream_billed(req, on_delta)
            .await
            .map_err(|failed| failed.error)
    }

    async fn complete_billed(
        &self,
        req: &CompletionRequest,
    ) -> Result<CompletionResponse, FailedCall> {
        assert!(
            !self.models.is_empty(),
            "a fallback chain always holds a model"
        );
        let mut spent = Usage::default();
        let mut last = None;
        for model in &self.models {
            match model.complete_billed(req).await {
                Ok(reply) => return Ok(with_spent(reply, spent)),
                Err(failed) => {
                    spent += failed.usage;
                    last = Some(failed.error);
                }
            }
        }
        Err(spent_on(last.expect("the loop ran at least once"), spent))
    }

    async fn stream_billed(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<CompletionResponse, FailedCall> {
        assert!(
            !self.models.is_empty(),
            "a fallback chain always holds a model"
        );
        let mut spent = Usage::default();
        let mut last = None;
        for model in &self.models {
            let mut emitted = false;
            let result = model
                .stream_billed(req, &mut |d: &Delta| {
                    emitted = true;
                    on_delta(d);
                })
                .await;
            match result {
                Ok(reply) => return Ok(with_spent(reply, spent)),
                Err(failed) => {
                    spent += failed.usage;
                    if emitted {
                        return Err(spent_on(failed.error, spent));
                    }
                    last = Some(failed.error);
                }
            }
        }
        Err(spent_on(last.expect("the loop ran at least once"), spent))
    }
}

/// Fills in `usage.cost_usd_micros` from catalog prices on every reply.
/// `Catalog::connect` wraps each model in one; `price` exposes the rates
/// and whether they were verified. It prices its own replies, so a retry
/// or fallback over it bills the sum of its priced tries.
pub struct MeteredModel {
    inner: Box<dyn Model>,
    price: Price,
}

impl MeteredModel {
    /// Wraps `inner`, pricing its replies with `price`.
    /// Returns the metered model.
    /// The inner model's id is kept.
    pub fn new(inner: Box<dyn Model>, price: Price) -> Self {
        Self { inner, price }
    }

    /// Returns the price this meter applies, including `verified`, so a
    /// budget can refuse to treat an unverified zero as free.
    /// Never changes after `new`.
    pub fn price(&self) -> Price {
        self.price
    }

    fn priced(&self, mut reply: CompletionResponse) -> CompletionResponse {
        reply.usage.cost_usd_micros = self.price.reply_cost_usd_micros(&reply);
        reply
    }

    fn priced_failure(&self, mut failed: FailedCall) -> FailedCall {
        failed.usage.cost_usd_micros = self.price.cost_usd_micros(&failed.usage);
        failed
    }
}

#[async_trait]
impl Model for MeteredModel {
    fn id(&self) -> &str {
        self.inner.id()
    }

    fn prices_replies(&self) -> bool {
        true
    }

    fn meter_price(&self) -> Option<Price> {
        Some(self.price)
    }

    fn extra_calls(&self, req: &CompletionRequest) -> u32 {
        self.inner.extra_calls(req)
    }

    async fn complete(&self, req: &CompletionRequest) -> Result<CompletionResponse, ProviderError> {
        self.complete_billed(req).await.map_err(|failed| failed.error)
    }

    async fn stream(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<CompletionResponse, ProviderError> {
        self.stream_billed(req, on_delta)
            .await
            .map_err(|failed| failed.error)
    }

    async fn complete_billed(
        &self,
        req: &CompletionRequest,
    ) -> Result<CompletionResponse, FailedCall> {
        self.inner
            .complete_billed(req)
            .await
            .map(|reply| self.priced(reply))
            .map_err(|failed| self.priced_failure(failed))
    }

    async fn stream_billed(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<CompletionResponse, FailedCall> {
        self.inner
            .stream_billed(req, on_delta)
            .await
            .map(|reply| self.priced(reply))
            .map_err(|failed| self.priced_failure(failed))
    }
}