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};
pub const MAX_REPLY_BYTES: usize = 32 * 1024 * 1024;
pub const RESEND_NOTE_BYTES: usize = 512;
#[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>;
fn prices_replies(&self) -> bool {
false
}
fn meter_price(&self) -> Option<Price> {
None
}
fn extra_calls(&self, req: &CompletionRequest) -> u32 {
let _ = req;
0
}
async fn complete_billed(
&self,
req: &CompletionRequest,
) -> Result<CompletionResponse, FailedCall> {
self.complete(req).await.map_err(FailedCall::from)
}
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)
}
}
#[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(),
}
}
}
#[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 {
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))
}
}
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))
}
pub struct HttpModel {
id: String,
model: String,
endpoint: Endpoint,
key: Option<Secret>,
transport: Arc<dyn Transport>,
}
impl HttpModel {
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,
})
}
fn status_error(&self, status: u16, headers: &[(String, String)], body: &[u8]) -> ProviderError {
redacted_status_error(status, headers, body, self.exposed_key())
}
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 })
}
}
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(())
}