use std::time::Duration;
use async_trait::async_trait;
use futures::stream::{self, BoxStream, StreamExt};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::message::{Message, ToolCall};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolSpec {
pub name: String,
pub description: String,
pub parameters: Value,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub enum ToolChoice {
#[default]
Auto,
None,
Required,
Specific(String),
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ResponseFormat {
#[default]
Text,
JsonObject,
JsonSchema {
name: String,
schema: Value,
strict: bool,
},
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct RequestOptions {
pub response_format: ResponseFormat,
pub reasoning_effort: Option<String>,
pub single_attempt: bool,
pub fallback_when_unspent: bool,
pub cache_key: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ToolSurfacing {
pub deferred: Vec<ToolSpec>,
pub loads: Vec<ToolLoad>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolLoad {
pub after_tool_call: String,
pub names: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ModelRequest {
pub model: String,
pub messages: Vec<Message>,
pub tools: Vec<ToolSpec>,
pub tool_choice: ToolChoice,
pub max_output_tokens: Option<u32>,
pub options: RequestOptions,
pub tool_surfacing: Option<ToolSurfacing>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Usage {
pub input_tokens: u64,
pub output_tokens: u64,
pub cached_input_tokens: u64,
pub cache_creation_tokens: u64,
}
impl Usage {
pub fn add(&mut self, other: Usage) {
self.input_tokens += other.input_tokens;
self.output_tokens += other.output_tokens;
self.cached_input_tokens += other.cached_input_tokens;
self.cache_creation_tokens += other.cache_creation_tokens;
}
pub fn billable_tokens(&self) -> u64 {
self.input_tokens.saturating_sub(self.cached_input_tokens) + self.output_tokens
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ModelResponse {
pub text: String,
pub tool_calls: Vec<ToolCall>,
pub usage: Usage,
pub reasoning: Option<String>,
pub note: Option<String>,
pub cut_off: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub enum StreamEvent {
TextDelta(String),
Done(ModelResponse),
Switched(crate::ProviderSwitch),
}
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum ProviderError {
#[error("rate limited")]
RateLimited { retry_after: Option<Duration> },
#[error("transient provider error: {0}")]
Transient(String),
#[error("invalid request: {0}")]
InvalidRequest(String),
#[error("invalid tool definitions: {0}")]
InvalidTools(String),
#[error("authentication failed: {0}")]
Auth(String),
#[error("billing: {message}")]
Billing {
message: String,
affordable_tokens: Option<u64>,
},
#[error("quota exhausted: {message}")]
QuotaExhausted {
message: String,
resets_at: Option<std::time::SystemTime>,
per_model: bool,
in_stream: bool,
},
#[error("not found: {0}")]
NotFound(String),
#[error("context window exceeded: {message}")]
ContextOverflow { message: String, limit: Option<u64> },
#[error("malformed reply: {message}")]
Malformed { message: String, parse: bool },
#[error("provider error: {0}")]
Other(String),
#[error("no model is connected")]
NotConfigured,
}
impl ProviderError {
pub fn proves_nothing_spent(&self) -> bool {
match self {
Self::Auth(_) | Self::NotFound(_) | Self::Billing { .. } | Self::NotConfigured => true,
Self::QuotaExhausted { in_stream, .. } => !in_stream,
_ => false,
}
}
pub fn is_retryable(&self) -> bool {
matches!(
self,
Self::RateLimited { .. } | Self::Transient(_) | Self::Malformed { parse: true, .. }
)
}
}
#[async_trait]
pub trait Provider: Send + Sync {
fn name(&self) -> &str;
async fn complete(&self, request: &ModelRequest) -> Result<ModelResponse, ProviderError>;
fn stream<'a>(
&'a self,
request: &'a ModelRequest,
) -> BoxStream<'a, Result<StreamEvent, ProviderError>> {
Box::pin(stream::once(async move {
self.complete(request).await.map(StreamEvent::Done)
}))
}
fn unavailable_until(&self, _model: &str) -> Option<std::time::SystemTime> {
None
}
fn default_model(&self) -> Option<&str> {
None
}
}
pub async fn collect_stream(
mut events: BoxStream<'_, Result<StreamEvent, ProviderError>>,
) -> Result<ModelResponse, ProviderError> {
while let Some(event) = events.next().await {
if let StreamEvent::Done(response) = event? {
return Ok(response);
}
}
Err(ProviderError::Transient(
"stream ended without a final response".into(),
))
}
#[async_trait]
impl<P: Provider + ?Sized> Provider for std::sync::Arc<P> {
fn name(&self) -> &str {
(**self).name()
}
async fn complete(&self, request: &ModelRequest) -> Result<ModelResponse, ProviderError> {
(**self).complete(request).await
}
fn stream<'a>(
&'a self,
request: &'a ModelRequest,
) -> BoxStream<'a, Result<StreamEvent, ProviderError>> {
(**self).stream(request)
}
fn unavailable_until(&self, model: &str) -> Option<std::time::SystemTime> {
(**self).unavailable_until(model)
}
fn default_model(&self) -> Option<&str> {
(**self).default_model()
}
}
pub struct Retry<P> {
inner: P,
max_attempts: u32,
base_delay: Duration,
}
impl<P: Provider> Retry<P> {
fn delay_for(&self, err: &ProviderError, attempt: u32) -> Duration {
match err {
ProviderError::RateLimited {
retry_after: Some(after),
} => *after,
_ => self.base_delay * 2u32.saturating_pow(attempt.saturating_sub(1)),
}
}
pub fn new(inner: P) -> Self {
Self {
inner,
max_attempts: 3,
base_delay: Duration::from_millis(500),
}
}
pub fn max_attempts(mut self, attempts: u32) -> Self {
self.max_attempts = attempts.max(1);
self
}
pub fn base_delay(mut self, delay: Duration) -> Self {
self.base_delay = delay;
self
}
}
#[async_trait]
impl<P: Provider> Provider for Retry<P> {
fn name(&self) -> &str {
self.inner.name()
}
fn unavailable_until(&self, model: &str) -> Option<std::time::SystemTime> {
self.inner.unavailable_until(model)
}
fn default_model(&self) -> Option<&str> {
self.inner.default_model()
}
async fn complete(&self, request: &ModelRequest) -> Result<ModelResponse, ProviderError> {
let mut attempt = 0;
loop {
attempt += 1;
match self.inner.complete(request).await {
Ok(response) => return Ok(response),
Err(err)
if err.is_retryable()
&& attempt < self.max_attempts
&& !request.options.single_attempt =>
{
tokio::time::sleep(self.delay_for(&err, attempt)).await;
}
Err(err) => return Err(err),
}
}
}
fn stream<'a>(
&'a self,
request: &'a ModelRequest,
) -> BoxStream<'a, Result<StreamEvent, ProviderError>> {
let opened = async move {
let mut attempt = 0;
loop {
attempt += 1;
let mut events = self.inner.stream(request);
match events.next().await {
Some(Err(err))
if err.is_retryable()
&& attempt < self.max_attempts
&& !request.options.single_attempt =>
{
tokio::time::sleep(self.delay_for(&err, attempt)).await;
}
first => return (first, events),
}
}
};
Box::pin(stream::once(opened).flat_map(|(first, rest)| stream::iter(first).chain(rest)))
}
}