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
use crate::catalog::Price;
use crate::fold::Fold;
use crate::request::{CompletionRequest, CompletionResponse, Delta};
use crate::sse::{SseEvent, SseParser};
use crate::status::{bad_request, decode_error, redact_secret, redacted_status_error};
use crate::transport::{read_body, HttpRequest, Transport};
use crate::wire::{self, anthropic, AuthStyle, Decoder, Protocol, Quirks};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::Arc;
use troupekit_core::error::{ProviderError, ProviderErrorKind};
use troupekit_core::event::Usage;
use troupekit_core::secret::Secret;
use troupekit_trace::{trace_span, url_for_trace, Span, Trace};

/// Largest reply body or stream, in bytes, a model reads before failing
/// with `Decode`. Bounds memory against a runaway or hostile server.
/// Applies to unary bodies and to the total bytes of a stream.
pub const MAX_REPLY_BYTES: usize = 32 * 1024 * 1024;

/// Most bytes of note a model may add to a request it resends after its
/// first reply, such as a repair prompt. A run budgets each extra call
/// from `Model::extra_calls` with this many input bytes on top.
pub const RESEND_NOTE_BYTES: usize = 512;

/// A chat model behind one object-safe interface. Providers, fakes and
/// middleware all implement it, so callers hold `Box<dyn Model>`.
/// `stream` hands each delta to `on_delta` and returns what `complete` would.
#[async_trait]
pub trait Model: Send + Sync {
    fn id(&self) -> &str;
    async fn complete(&self, req: &CompletionRequest) -> Result<CompletionResponse, ProviderError>;
    async fn stream(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<CompletionResponse, ProviderError>;

    /// Reports whether each reply's `usage.cost_usd_micros` is already the
    /// cost of the model that served it, as a routed or metered model's is.
    /// A run then bills that cost instead of its own price, so a retry or
    /// fallback that sums priced tries is billed that sum. Default false.
    fn prices_replies(&self) -> bool {
        false
    }

    /// Returns the price that meters each try when every reply is priced
    /// at one price, as a metered model and a retry over one are.
    /// A caller trusts the reply cost only when it equals its own declared
    /// price. Default `None`.
    fn meter_price(&self) -> Option<Price> {
        None
    }

    /// Returns how many more provider calls one call with `req` can make
    /// after the first, each resending `req` with the previous reply and
    /// at most `RESEND_NOTE_BYTES` of note. A run budgets them before the
    /// call. Default 0.
    fn extra_calls(&self, req: &CompletionRequest) -> u32 {
        let _ = req;
        0
    }

    /// Runs `complete` and, when the call fails, keeps the usage the
    /// provider reported before it failed, so a caller can bill it.
    /// Default: `complete` with zero usage. A model that sees usage
    /// overrides it, and a wrapper forwards it to its inner model.
    async fn complete_billed(
        &self,
        req: &CompletionRequest,
    ) -> Result<CompletionResponse, FailedCall> {
        self.complete(req).await.map_err(FailedCall::from)
    }

    /// Runs `stream` and, when the call fails, keeps the usage the
    /// provider reported before it failed, as `complete_billed` does.
    /// Default: `stream` with zero usage.
    async fn stream_billed(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<CompletionResponse, FailedCall> {
        self.stream(req, on_delta).await.map_err(FailedCall::from)
    }
}

/// A failed model call and the usage its provider reported before it
/// failed, zero when none arrived. `cost_usd_micros` is set by whatever
/// prices the call, as for a reply. Returned by the `*_billed` calls.
#[derive(Debug, Clone, PartialEq)]
pub struct FailedCall {
    pub error: ProviderError,
    pub usage: Usage,
}

impl From<ProviderError> for FailedCall {
    fn from(error: ProviderError) -> Self {
        Self {
            error,
            usage: Usage::default(),
        }
    }
}

/// Where and how to reach one vendor: protocol, base URL, auth style and
/// quirks. Catalog vendors turn into one; hosts may also build one for
/// a self-hosted server.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Endpoint {
    pub protocol: Protocol,
    pub base_url: String,
    pub auth: AuthStyle,
    pub quirks: Quirks,
}

impl Endpoint {
    /// Builds the HTTP request for one call of wire `model` with `req`:
    /// URL, content and auth headers, encoded body. Pure, no I/O. Returns
    /// `Auth` when a key is needed and `key` is `None`.
    pub fn request(
        &self,
        model: &str,
        key: Option<&Secret>,
        req: &CompletionRequest,
        stream: bool,
    ) -> Result<HttpRequest, ProviderError> {
        let body = wire::encode(self.protocol, &self.quirks, model, req, stream)?;
        let base = self.base_url.trim_end_matches('/');
        let url = match (self.protocol, stream) {
            (Protocol::Anthropic, _) => format!("{base}/v1/messages"),
            (Protocol::OpenAi | Protocol::OpenAiCompatible, _) => {
                format!("{base}/chat/completions")
            }
            (Protocol::Gemini, false) => format!("{base}/models/{model}:generateContent"),
            (Protocol::Gemini, true) => {
                format!("{base}/models/{model}:streamGenerateContent?alt=sse")
            }
        };
        let mut headers = vec![("content-type".to_owned(), "application/json".to_owned())];
        if stream {
            headers.push(("accept".into(), "text/event-stream".into()));
        }
        if self.protocol == Protocol::Anthropic {
            headers.push(("anthropic-version".into(), anthropic::API_VERSION.into()));
        }
        let auth = match (self.auth, key) {
            (AuthStyle::NoKey, _) => None,
            (_, None) => {
                return Err(ProviderError::new(
                    ProviderErrorKind::Auth,
                    "this endpoint needs an API key",
                ))
            }
            (AuthStyle::Bearer, Some(k)) => {
                Some(("authorization", format!("Bearer {}", k.expose())))
            }
            (AuthStyle::XApiKey, Some(k)) => Some(("x-api-key", k.expose().to_owned())),
            (AuthStyle::XGoogApiKey, Some(k)) => Some(("x-goog-api-key", k.expose().to_owned())),
        };
        if let Some((name, value)) = auth {
            headers.push((name.to_owned(), value));
        }
        let body = serde_json::to_vec(&body)
            .map_err(|e| bad_request(format!("request does not serialize: {e}")))?;
        Ok(HttpRequest::post(url, headers, body))
    }
}

/// Reports whether `id` is safe to place in a URL path as a model id:
/// 1 to 200 ASCII letters, digits and `._:/-`, with no `..` segment.
/// Catalog and `HttpModel` both check it.
pub fn valid_model_id(id: &str) -> bool {
    !id.is_empty()
        && id.len() <= 200
        && !id.contains("..")
        && id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"._:/-".contains(&b))
}

/// A model reached over HTTP through an injected `Transport`.
/// Unary and streamed calls share one encoder, one decoder per protocol
/// and one `Fold`, so both return the same response for the same reply.
pub struct HttpModel {
    id: String,
    model: String,
    endpoint: Endpoint,
    key: Option<Secret>,
    transport: Arc<dyn Transport>,
}

impl HttpModel {
    /// Builds a model named `id` (usually `vendor/model`) that sends wire
    /// `model` to `endpoint` with an optional `key` through `transport`.
    /// Returns `BadRequest` when `model` fails `valid_model_id`.
    pub fn new(
        id: impl Into<String>,
        model: impl Into<String>,
        endpoint: Endpoint,
        key: Option<Secret>,
        transport: Arc<dyn Transport>,
    ) -> Result<Self, ProviderError> {
        let model = model.into();
        if !valid_model_id(&model) {
            return Err(bad_request(format!("model id {model:?} is not allowed")));
        }
        Ok(Self {
            id: id.into(),
            model,
            endpoint,
            key,
            transport,
        })
    }

    /// Builds the error for a non-success reply with this model's API key
    /// replaced by `[redacted]` before the detail is cut, since error
    /// bodies can echo the request. Input: status, headers and body.
    /// Output: the error.
    fn status_error(&self, status: u16, headers: &[(String, String)], body: &[u8]) -> ProviderError {
        redacted_status_error(status, headers, body, self.exposed_key())
    }

    /// Replaces this model's API key with `[redacted]` in a failed call's
    /// message, so no error leaving the HTTP paths, status or in-band,
    /// carries the key. Input: the failed call. Output: the same, scrubbed.
    fn redact_failed(&self, mut failed: FailedCall) -> FailedCall {
        if let Some(key) = self.exposed_key() {
            failed.error.message = redact_secret(&failed.error.message, key);
        }
        failed
    }

    fn exposed_key(&self) -> Option<&str> {
        self.key
            .as_ref()
            .map(Secret::expose)
            .filter(|k| !k.is_empty())
    }

    fn prepare(&self, req: &CompletionRequest, stream: bool) -> Result<HttpRequest, ProviderError> {
        req.validate()?;
        if let Some(asked) = req.model.as_deref().filter(|m| *m != self.model) {
            return Err(bad_request(format!(
                "request names model {asked}, this handle serves {}",
                self.model
            )));
        }
        self.endpoint
            .request(&self.model, self.key.as_ref(), req, stream)
    }
}

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

    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 span = self.http_span(false);
        let mut stats = HttpStats::default();
        let result = span
            .instrument(self.complete_http(req, &mut stats))
            .await
            .map_err(|failed| self.redact_failed(failed));
        stats.finish(&mut span, result.as_ref().err().map(|f| &f.error));
        result
    }

    async fn stream_billed(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<CompletionResponse, FailedCall> {
        let mut span = self.http_span(true);
        let mut stats = HttpStats::default();
        let result = span
            .instrument(self.stream_http(req, on_delta, &mut stats))
            .await
            .map_err(|failed| self.redact_failed(failed));
        stats.finish(&mut span, result.as_ref().err().map(|f| &f.error));
        result
    }
}

#[derive(Default)]
struct HttpStats {
    status: Option<u16>,
    reply_bytes: usize,
}

impl HttpStats {
    fn finish(&self, span: &mut Span, error: Option<&ProviderError>) {
        if !span.is_enabled() {
            return;
        }
        if let Some(status) = self.status {
            span.record("status", status);
        }
        span.record("reply_bytes", self.reply_bytes);
        if let Some(e) = error {
            span.fail("http call failed");
            span.record("kind", format!("{:?}", e.kind));
        }
    }
}

impl HttpModel {
    fn http_span(&self, stream: bool) -> Span {
        trace_span!(
            Trace::Models,
            "model.http",
            model = self.id.as_str(),
            url = url_for_trace(&self.endpoint.base_url),
            stream = stream,
        )
    }

    async fn complete_http(
        &self,
        req: &CompletionRequest,
        stats: &mut HttpStats,
    ) -> Result<CompletionResponse, FailedCall> {
        let request = self.prepare(req, false)?;
        let mut reply = self.transport.send(request).await.map_err(ProviderError::from)?;
        stats.status = Some(reply.status);
        let body = read_body(reply.body.as_mut(), MAX_REPLY_BYTES).await?;
        stats.reply_bytes = body.len();
        if !(200..300).contains(&reply.status) {
            return Err(self.status_error(reply.status, &reply.headers, &body).into());
        }
        let value: Value = serde_json::from_slice(&body)
            .map_err(|e| decode_error(format!("reply is not JSON: {e}")))?;
        let deltas = wire::decode_body(self.endpoint.protocol, &value)?;
        let usage = reported(&deltas);
        let mut fold = Fold::new();
        let folded = deltas.iter().try_for_each(|delta| fold.push(delta));
        folded
            .and_then(|()| fold.finish())
            .map_err(|error| FailedCall { error, usage })
    }

    async fn stream_http(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
        stats: &mut HttpStats,
    ) -> Result<CompletionResponse, FailedCall> {
        let request = self.prepare(req, true)?;
        let mut reply = self.transport.send(request).await.map_err(ProviderError::from)?;
        stats.status = Some(reply.status);
        if !(200..300).contains(&reply.status) {
            let body = read_body(reply.body.as_mut(), MAX_REPLY_BYTES)
                .await
                .unwrap_or_default();
            stats.reply_bytes = body.len();
            return Err(self.status_error(reply.status, &reply.headers, &body).into());
        }
        let mut parser = SseParser::new();
        let mut decoder = Decoder::new(self.endpoint.protocol);
        let mut fold = Fold::new();
        let read: Result<(), ProviderError> = async {
            let mut received = 0usize;
            while let Some(chunk) = reply.body.chunk().await? {
                received += chunk.len();
                stats.reply_bytes = received;
                if received > MAX_REPLY_BYTES {
                    return Err(decode_error("reply stream is too large"));
                }
                apply(parser.push(&chunk)?, &mut decoder, &mut fold, on_delta)?;
            }
            apply(parser.finish()?, &mut decoder, &mut fold, on_delta)
        }
        .await;
        let usage = fold.usage();
        read.and_then(|()| fold.finish())
            .map_err(|error| FailedCall { error, usage })
    }
}

/// The usage the deltas of one reply report, totalled as a fold totals
/// it. Input: the decoded deltas. Output: the usage, zero cost, so a
/// unary reply that fails to fold is still billed for what it reported.
fn reported(deltas: &[Delta]) -> Usage {
    let mut fold = Fold::new();
    for delta in deltas.iter().filter(|d| matches!(d, Delta::Usage { .. })) {
        fold.push(delta).expect("a usage delta always folds");
    }
    fold.usage()
}

fn apply(
    events: Vec<SseEvent>,
    decoder: &mut Decoder,
    fold: &mut Fold,
    on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
) -> Result<(), ProviderError> {
    for event in &events {
        for delta in decoder.sse(event)? {
            fold.push(&delta)?;
            on_delta(&delta);
        }
    }
    Ok(())
}