use axum::{ Json, http::StatusCode, response::{IntoResponse, Response}, }; use serde_json::json; pub struct ApiError { status: StatusCode, kind: &'static str, message: String, } impl ApiError { pub fn bad(message: impl Into) -> Self { Self { status: StatusCode::BAD_REQUEST, kind: "invalid_request_error", message: message.into(), } } pub fn busy() -> Self { Self { status: StatusCode::TOO_MANY_REQUESTS, kind: "rate_limit_error", message: "All model workers are busy; retry after the current stream finishes".into(), } } pub fn not_found(message: impl Into) -> Self { Self { status: StatusCode::NOT_FOUND, kind: "invalid_request_error", message: message.into(), } } pub fn forbidden(message: impl Into) -> Self { Self { status: StatusCode::FORBIDDEN, kind: "permission_error", message: message.into(), } } pub fn unauthorized() -> Self { Self { status: StatusCode::UNAUTHORIZED, kind: "authentication_error", message: "A valid Bearer API key is required".into(), } } pub fn internal(error: impl std::fmt::Display) -> Self { tracing::error!(error = %error, "inference failed"); Self { status: StatusCode::INTERNAL_SERVER_ERROR, kind: "server_error", message: "Inference failed; see server logs".into(), } } } impl IntoResponse for ApiError { fn into_response(self) -> Response { let mut response = ( self.status, Json( json!({"error":{"message":self.message,"type":self.kind,"param":null,"code":null}}), ), ) .into_response(); if self.status == StatusCode::TOO_MANY_REQUESTS { response .headers_mut() .insert("retry-after", "1".parse().unwrap()); } response } }