1use crate::catalog::Price;
2use crate::fold::Fold;
3use crate::request::{CompletionRequest, CompletionResponse, Delta};
4use crate::sse::{SseEvent, SseParser};
5use crate::status::{bad_request, decode_error, redact_secret, redacted_status_error};
6use crate::transport::{read_body, HttpRequest, Transport};
7use crate::wire::{self, anthropic, AuthStyle, Decoder, Protocol, Quirks};
8use async_trait::async_trait;
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11use std::sync::Arc;
12use troupekit_core::error::{ProviderError, ProviderErrorKind};
13use troupekit_core::event::Usage;
14use troupekit_core::secret::Secret;
15use troupekit_trace::{trace_span, url_for_trace, Span, Trace};
16
17pub const MAX_REPLY_BYTES: usize = 32 * 1024 * 1024;
21
22pub const RESEND_NOTE_BYTES: usize = 512;
26
27#[async_trait]
31pub trait Model: Send + Sync {
32 fn id(&self) -> &str;
33 async fn complete(&self, req: &CompletionRequest) -> Result<CompletionResponse, ProviderError>;
34 async fn stream(
35 &self,
36 req: &CompletionRequest,
37 on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
38 ) -> Result<CompletionResponse, ProviderError>;
39
40 fn prices_replies(&self) -> bool {
45 false
46 }
47
48 fn meter_price(&self) -> Option<Price> {
53 None
54 }
55
56 fn extra_calls(&self, req: &CompletionRequest) -> u32 {
61 let _ = req;
62 0
63 }
64
65 async fn complete_billed(
70 &self,
71 req: &CompletionRequest,
72 ) -> Result<CompletionResponse, FailedCall> {
73 self.complete(req).await.map_err(FailedCall::from)
74 }
75
76 async fn stream_billed(
80 &self,
81 req: &CompletionRequest,
82 on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
83 ) -> Result<CompletionResponse, FailedCall> {
84 self.stream(req, on_delta).await.map_err(FailedCall::from)
85 }
86}
87
88#[derive(Debug, Clone, PartialEq)]
92pub struct FailedCall {
93 pub error: ProviderError,
94 pub usage: Usage,
95}
96
97impl From<ProviderError> for FailedCall {
98 fn from(error: ProviderError) -> Self {
99 Self {
100 error,
101 usage: Usage::default(),
102 }
103 }
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110pub struct Endpoint {
111 pub protocol: Protocol,
112 pub base_url: String,
113 pub auth: AuthStyle,
114 pub quirks: Quirks,
115}
116
117impl Endpoint {
118 pub fn request(
122 &self,
123 model: &str,
124 key: Option<&Secret>,
125 req: &CompletionRequest,
126 stream: bool,
127 ) -> Result<HttpRequest, ProviderError> {
128 let body = wire::encode(self.protocol, &self.quirks, model, req, stream)?;
129 let base = self.base_url.trim_end_matches('/');
130 let url = match (self.protocol, stream) {
131 (Protocol::Anthropic, _) => format!("{base}/v1/messages"),
132 (Protocol::OpenAi | Protocol::OpenAiCompatible, _) => {
133 format!("{base}/chat/completions")
134 }
135 (Protocol::Gemini, false) => format!("{base}/models/{model}:generateContent"),
136 (Protocol::Gemini, true) => {
137 format!("{base}/models/{model}:streamGenerateContent?alt=sse")
138 }
139 };
140 let mut headers = vec![("content-type".to_owned(), "application/json".to_owned())];
141 if stream {
142 headers.push(("accept".into(), "text/event-stream".into()));
143 }
144 if self.protocol == Protocol::Anthropic {
145 headers.push(("anthropic-version".into(), anthropic::API_VERSION.into()));
146 }
147 let auth = match (self.auth, key) {
148 (AuthStyle::NoKey, _) => None,
149 (_, None) => {
150 return Err(ProviderError::new(
151 ProviderErrorKind::Auth,
152 "this endpoint needs an API key",
153 ))
154 }
155 (AuthStyle::Bearer, Some(k)) => {
156 Some(("authorization", format!("Bearer {}", k.expose())))
157 }
158 (AuthStyle::XApiKey, Some(k)) => Some(("x-api-key", k.expose().to_owned())),
159 (AuthStyle::XGoogApiKey, Some(k)) => Some(("x-goog-api-key", k.expose().to_owned())),
160 };
161 if let Some((name, value)) = auth {
162 headers.push((name.to_owned(), value));
163 }
164 let body = serde_json::to_vec(&body)
165 .map_err(|e| bad_request(format!("request does not serialize: {e}")))?;
166 Ok(HttpRequest::post(url, headers, body))
167 }
168}
169
170pub fn valid_model_id(id: &str) -> bool {
174 !id.is_empty()
175 && id.len() <= 200
176 && !id.contains("..")
177 && id
178 .bytes()
179 .all(|b| b.is_ascii_alphanumeric() || b"._:/-".contains(&b))
180}
181
182pub struct HttpModel {
186 id: String,
187 model: String,
188 endpoint: Endpoint,
189 key: Option<Secret>,
190 transport: Arc<dyn Transport>,
191}
192
193impl HttpModel {
194 pub fn new(
198 id: impl Into<String>,
199 model: impl Into<String>,
200 endpoint: Endpoint,
201 key: Option<Secret>,
202 transport: Arc<dyn Transport>,
203 ) -> Result<Self, ProviderError> {
204 let model = model.into();
205 if !valid_model_id(&model) {
206 return Err(bad_request(format!("model id {model:?} is not allowed")));
207 }
208 Ok(Self {
209 id: id.into(),
210 model,
211 endpoint,
212 key,
213 transport,
214 })
215 }
216
217 fn status_error(&self, status: u16, headers: &[(String, String)], body: &[u8]) -> ProviderError {
222 redacted_status_error(status, headers, body, self.exposed_key())
223 }
224
225 fn redact_failed(&self, mut failed: FailedCall) -> FailedCall {
229 if let Some(key) = self.exposed_key() {
230 failed.error.message = redact_secret(&failed.error.message, key);
231 }
232 failed
233 }
234
235 fn exposed_key(&self) -> Option<&str> {
236 self.key
237 .as_ref()
238 .map(Secret::expose)
239 .filter(|k| !k.is_empty())
240 }
241
242 fn prepare(&self, req: &CompletionRequest, stream: bool) -> Result<HttpRequest, ProviderError> {
243 req.validate()?;
244 if let Some(asked) = req.model.as_deref().filter(|m| *m != self.model) {
245 return Err(bad_request(format!(
246 "request names model {asked}, this handle serves {}",
247 self.model
248 )));
249 }
250 self.endpoint
251 .request(&self.model, self.key.as_ref(), req, stream)
252 }
253}
254
255#[async_trait]
256impl Model for HttpModel {
257 fn id(&self) -> &str {
258 &self.id
259 }
260
261 async fn complete(&self, req: &CompletionRequest) -> Result<CompletionResponse, ProviderError> {
262 self.complete_billed(req).await.map_err(|failed| failed.error)
263 }
264
265 async fn stream(
266 &self,
267 req: &CompletionRequest,
268 on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
269 ) -> Result<CompletionResponse, ProviderError> {
270 self.stream_billed(req, on_delta)
271 .await
272 .map_err(|failed| failed.error)
273 }
274
275 async fn complete_billed(
276 &self,
277 req: &CompletionRequest,
278 ) -> Result<CompletionResponse, FailedCall> {
279 let mut span = self.http_span(false);
280 let mut stats = HttpStats::default();
281 let result = span
282 .instrument(self.complete_http(req, &mut stats))
283 .await
284 .map_err(|failed| self.redact_failed(failed));
285 stats.finish(&mut span, result.as_ref().err().map(|f| &f.error));
286 result
287 }
288
289 async fn stream_billed(
290 &self,
291 req: &CompletionRequest,
292 on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
293 ) -> Result<CompletionResponse, FailedCall> {
294 let mut span = self.http_span(true);
295 let mut stats = HttpStats::default();
296 let result = span
297 .instrument(self.stream_http(req, on_delta, &mut stats))
298 .await
299 .map_err(|failed| self.redact_failed(failed));
300 stats.finish(&mut span, result.as_ref().err().map(|f| &f.error));
301 result
302 }
303}
304
305#[derive(Default)]
306struct HttpStats {
307 status: Option<u16>,
308 reply_bytes: usize,
309}
310
311impl HttpStats {
312 fn finish(&self, span: &mut Span, error: Option<&ProviderError>) {
313 if !span.is_enabled() {
314 return;
315 }
316 if let Some(status) = self.status {
317 span.record("status", status);
318 }
319 span.record("reply_bytes", self.reply_bytes);
320 if let Some(e) = error {
321 span.fail("http call failed");
322 span.record("kind", format!("{:?}", e.kind));
323 }
324 }
325}
326
327impl HttpModel {
328 fn http_span(&self, stream: bool) -> Span {
329 trace_span!(
330 Trace::Models,
331 "model.http",
332 model = self.id.as_str(),
333 url = url_for_trace(&self.endpoint.base_url),
334 stream = stream,
335 )
336 }
337
338 async fn complete_http(
339 &self,
340 req: &CompletionRequest,
341 stats: &mut HttpStats,
342 ) -> Result<CompletionResponse, FailedCall> {
343 let request = self.prepare(req, false)?;
344 let mut reply = self.transport.send(request).await.map_err(ProviderError::from)?;
345 stats.status = Some(reply.status);
346 let body = read_body(reply.body.as_mut(), MAX_REPLY_BYTES).await?;
347 stats.reply_bytes = body.len();
348 if !(200..300).contains(&reply.status) {
349 return Err(self.status_error(reply.status, &reply.headers, &body).into());
350 }
351 let value: Value = serde_json::from_slice(&body)
352 .map_err(|e| decode_error(format!("reply is not JSON: {e}")))?;
353 let deltas = wire::decode_body(self.endpoint.protocol, &value)?;
354 let usage = reported(&deltas);
355 let mut fold = Fold::new();
356 let folded = deltas.iter().try_for_each(|delta| fold.push(delta));
357 folded
358 .and_then(|()| fold.finish())
359 .map_err(|error| FailedCall { error, usage })
360 }
361
362 async fn stream_http(
363 &self,
364 req: &CompletionRequest,
365 on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
366 stats: &mut HttpStats,
367 ) -> Result<CompletionResponse, FailedCall> {
368 let request = self.prepare(req, true)?;
369 let mut reply = self.transport.send(request).await.map_err(ProviderError::from)?;
370 stats.status = Some(reply.status);
371 if !(200..300).contains(&reply.status) {
372 let body = read_body(reply.body.as_mut(), MAX_REPLY_BYTES)
373 .await
374 .unwrap_or_default();
375 stats.reply_bytes = body.len();
376 return Err(self.status_error(reply.status, &reply.headers, &body).into());
377 }
378 let mut parser = SseParser::new();
379 let mut decoder = Decoder::new(self.endpoint.protocol);
380 let mut fold = Fold::new();
381 let read: Result<(), ProviderError> = async {
382 let mut received = 0usize;
383 while let Some(chunk) = reply.body.chunk().await? {
384 received += chunk.len();
385 stats.reply_bytes = received;
386 if received > MAX_REPLY_BYTES {
387 return Err(decode_error("reply stream is too large"));
388 }
389 apply(parser.push(&chunk)?, &mut decoder, &mut fold, on_delta)?;
390 }
391 apply(parser.finish()?, &mut decoder, &mut fold, on_delta)
392 }
393 .await;
394 let usage = fold.usage();
395 read.and_then(|()| fold.finish())
396 .map_err(|error| FailedCall { error, usage })
397 }
398}
399
400fn reported(deltas: &[Delta]) -> Usage {
404 let mut fold = Fold::new();
405 for delta in deltas.iter().filter(|d| matches!(d, Delta::Usage { .. })) {
406 fold.push(delta).expect("a usage delta always folds");
407 }
408 fold.usage()
409}
410
411fn apply(
412 events: Vec<SseEvent>,
413 decoder: &mut Decoder,
414 fold: &mut Fold,
415 on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
416) -> Result<(), ProviderError> {
417 for event in &events {
418 for delta in decoder.sse(event)? {
419 fold.push(&delta)?;
420 on_delta(&delta);
421 }
422 }
423 Ok(())
424}