1use std::time::Duration;
2
3use async_trait::async_trait;
4use futures::stream::{self, BoxStream, StreamExt};
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7
8use crate::message::{Message, ToolCall};
9
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12pub struct ToolSpec {
13 pub name: String,
14 pub description: String,
15 pub parameters: Value,
17}
18
19#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
21pub enum ToolChoice {
22 #[default]
23 Auto,
24 None,
25 Required,
26 Specific(String),
27}
28
29#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
31#[serde(tag = "type", rename_all = "snake_case")]
32pub enum ResponseFormat {
33 #[default]
34 Text,
35 JsonObject,
37 JsonSchema {
39 name: String,
40 schema: Value,
41 strict: bool,
42 },
43}
44
45#[derive(Debug, Clone, PartialEq, Default)]
48pub struct RequestOptions {
49 pub response_format: ResponseFormat,
50 pub reasoning_effort: Option<String>,
53 pub single_attempt: bool,
57 pub fallback_when_unspent: bool,
64 pub cache_key: Option<String>,
68}
69
70#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
75pub struct ToolSurfacing {
76 pub deferred: Vec<ToolSpec>,
79 pub loads: Vec<ToolLoad>,
81}
82
83#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
86pub struct ToolLoad {
87 pub after_tool_call: String,
88 pub names: Vec<String>,
89}
90
91#[derive(Debug, Clone, PartialEq, Default)]
93pub struct ModelRequest {
94 pub model: String,
95 pub messages: Vec<Message>,
97 pub tools: Vec<ToolSpec>,
98 pub tool_choice: ToolChoice,
99 pub max_output_tokens: Option<u32>,
100 pub options: RequestOptions,
101 pub tool_surfacing: Option<ToolSurfacing>,
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
109pub struct Usage {
110 pub input_tokens: u64,
111 pub output_tokens: u64,
112 pub cached_input_tokens: u64,
114 pub cache_creation_tokens: u64,
115}
116
117impl Usage {
118 pub fn add(&mut self, other: Usage) {
119 self.input_tokens += other.input_tokens;
120 self.output_tokens += other.output_tokens;
121 self.cached_input_tokens += other.cached_input_tokens;
122 self.cache_creation_tokens += other.cache_creation_tokens;
123 }
124
125 pub fn billable_tokens(&self) -> u64 {
127 self.input_tokens.saturating_sub(self.cached_input_tokens) + self.output_tokens
128 }
129}
130
131#[derive(Debug, Clone, PartialEq, Default)]
133pub struct ModelResponse {
134 pub text: String,
135 pub tool_calls: Vec<ToolCall>,
136 pub usage: Usage,
137 pub reasoning: Option<String>,
140 pub note: Option<String>,
143 pub cut_off: bool,
146}
147
148#[derive(Debug, Clone, PartialEq)]
151pub enum StreamEvent {
152 TextDelta(String),
154 Done(ModelResponse),
156 Switched(crate::ProviderSwitch),
159}
160
161#[derive(Debug, Clone, PartialEq, thiserror::Error)]
162pub enum ProviderError {
163 #[error("rate limited")]
164 RateLimited { retry_after: Option<Duration> },
165 #[error("transient provider error: {0}")]
166 Transient(String),
167 #[error("invalid request: {0}")]
168 InvalidRequest(String),
169 #[error("invalid tool definitions: {0}")]
173 InvalidTools(String),
174 #[error("authentication failed: {0}")]
175 Auth(String),
176 #[error("billing: {message}")]
179 Billing {
180 message: String,
181 affordable_tokens: Option<u64>,
182 },
183 #[error("quota exhausted: {message}")]
192 QuotaExhausted {
193 message: String,
194 resets_at: Option<std::time::SystemTime>,
195 per_model: bool,
196 in_stream: bool,
197 },
198 #[error("not found: {0}")]
200 NotFound(String),
201 #[error("context window exceeded: {message}")]
204 ContextOverflow { message: String, limit: Option<u64> },
205 #[error("malformed reply: {message}")]
209 Malformed { message: String, parse: bool },
210 #[error("provider error: {0}")]
211 Other(String),
212 #[error("no model is connected")]
215 NotConfigured,
216}
217
218impl ProviderError {
219 pub fn proves_nothing_spent(&self) -> bool {
225 match self {
226 Self::Auth(_) | Self::NotFound(_) | Self::Billing { .. } | Self::NotConfigured => true,
227 Self::QuotaExhausted { in_stream, .. } => !in_stream,
228 _ => false,
229 }
230 }
231
232 pub fn is_retryable(&self) -> bool {
234 matches!(
235 self,
236 Self::RateLimited { .. } | Self::Transient(_) | Self::Malformed { parse: true, .. }
237 )
238 }
239}
240
241#[async_trait]
250pub trait Provider: Send + Sync {
251 fn name(&self) -> &str;
252
253 async fn complete(&self, request: &ModelRequest) -> Result<ModelResponse, ProviderError>;
254
255 fn stream<'a>(
256 &'a self,
257 request: &'a ModelRequest,
258 ) -> BoxStream<'a, Result<StreamEvent, ProviderError>> {
259 Box::pin(stream::once(async move {
260 self.complete(request).await.map(StreamEvent::Done)
261 }))
262 }
263
264 fn unavailable_until(&self, _model: &str) -> Option<std::time::SystemTime> {
268 None
269 }
270
271 fn default_model(&self) -> Option<&str> {
275 None
276 }
277}
278
279pub async fn collect_stream(
282 mut events: BoxStream<'_, Result<StreamEvent, ProviderError>>,
283) -> Result<ModelResponse, ProviderError> {
284 while let Some(event) = events.next().await {
285 if let StreamEvent::Done(response) = event? {
286 return Ok(response);
287 }
288 }
289 Err(ProviderError::Transient(
290 "stream ended without a final response".into(),
291 ))
292}
293
294#[async_trait]
295impl<P: Provider + ?Sized> Provider for std::sync::Arc<P> {
296 fn name(&self) -> &str {
297 (**self).name()
298 }
299 async fn complete(&self, request: &ModelRequest) -> Result<ModelResponse, ProviderError> {
300 (**self).complete(request).await
301 }
302 fn stream<'a>(
303 &'a self,
304 request: &'a ModelRequest,
305 ) -> BoxStream<'a, Result<StreamEvent, ProviderError>> {
306 (**self).stream(request)
307 }
308 fn unavailable_until(&self, model: &str) -> Option<std::time::SystemTime> {
311 (**self).unavailable_until(model)
312 }
313 fn default_model(&self) -> Option<&str> {
314 (**self).default_model()
315 }
316}
317
318pub struct Retry<P> {
320 inner: P,
321 max_attempts: u32,
322 base_delay: Duration,
323}
324
325impl<P: Provider> Retry<P> {
326 fn delay_for(&self, err: &ProviderError, attempt: u32) -> Duration {
327 match err {
328 ProviderError::RateLimited {
329 retry_after: Some(after),
330 } => *after,
331 _ => self.base_delay * 2u32.saturating_pow(attempt.saturating_sub(1)),
332 }
333 }
334
335 pub fn new(inner: P) -> Self {
336 Self {
337 inner,
338 max_attempts: 3,
339 base_delay: Duration::from_millis(500),
340 }
341 }
342
343 pub fn max_attempts(mut self, attempts: u32) -> Self {
344 self.max_attempts = attempts.max(1);
345 self
346 }
347
348 pub fn base_delay(mut self, delay: Duration) -> Self {
349 self.base_delay = delay;
350 self
351 }
352}
353
354#[async_trait]
355impl<P: Provider> Provider for Retry<P> {
356 fn name(&self) -> &str {
357 self.inner.name()
358 }
359 fn unavailable_until(&self, model: &str) -> Option<std::time::SystemTime> {
360 self.inner.unavailable_until(model)
361 }
362 fn default_model(&self) -> Option<&str> {
363 self.inner.default_model()
364 }
365
366 async fn complete(&self, request: &ModelRequest) -> Result<ModelResponse, ProviderError> {
367 let mut attempt = 0;
368 loop {
369 attempt += 1;
370 match self.inner.complete(request).await {
371 Ok(response) => return Ok(response),
372 Err(err)
373 if err.is_retryable()
374 && attempt < self.max_attempts
375 && !request.options.single_attempt =>
376 {
377 tokio::time::sleep(self.delay_for(&err, attempt)).await;
378 }
379 Err(err) => return Err(err),
380 }
381 }
382 }
383
384 fn stream<'a>(
387 &'a self,
388 request: &'a ModelRequest,
389 ) -> BoxStream<'a, Result<StreamEvent, ProviderError>> {
390 let opened = async move {
391 let mut attempt = 0;
392 loop {
393 attempt += 1;
394 let mut events = self.inner.stream(request);
395 match events.next().await {
396 Some(Err(err))
397 if err.is_retryable()
398 && attempt < self.max_attempts
399 && !request.options.single_attempt =>
400 {
401 tokio::time::sleep(self.delay_for(&err, attempt)).await;
402 }
403 first => return (first, events),
404 }
405 }
406 };
407 Box::pin(stream::once(opened).flat_map(|(first, rest)| stream::iter(first).chain(rest)))
408 }
409}