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}
213
214impl ProviderError {
215 pub fn proves_nothing_spent(&self) -> bool {
221 match self {
222 Self::Auth(_) | Self::NotFound(_) | Self::Billing { .. } => true,
223 Self::QuotaExhausted { in_stream, .. } => !in_stream,
224 _ => false,
225 }
226 }
227
228 pub fn is_retryable(&self) -> bool {
230 matches!(
231 self,
232 Self::RateLimited { .. } | Self::Transient(_) | Self::Malformed { parse: true, .. }
233 )
234 }
235}
236
237#[async_trait]
246pub trait Provider: Send + Sync {
247 fn name(&self) -> &str;
248
249 async fn complete(&self, request: &ModelRequest) -> Result<ModelResponse, ProviderError>;
250
251 fn stream<'a>(
252 &'a self,
253 request: &'a ModelRequest,
254 ) -> BoxStream<'a, Result<StreamEvent, ProviderError>> {
255 Box::pin(stream::once(async move {
256 self.complete(request).await.map(StreamEvent::Done)
257 }))
258 }
259
260 fn unavailable_until(&self, _model: &str) -> Option<std::time::SystemTime> {
264 None
265 }
266
267 fn default_model(&self) -> Option<&str> {
271 None
272 }
273}
274
275pub async fn collect_stream(
278 mut events: BoxStream<'_, Result<StreamEvent, ProviderError>>,
279) -> Result<ModelResponse, ProviderError> {
280 while let Some(event) = events.next().await {
281 if let StreamEvent::Done(response) = event? {
282 return Ok(response);
283 }
284 }
285 Err(ProviderError::Transient(
286 "stream ended without a final response".into(),
287 ))
288}
289
290#[async_trait]
291impl<P: Provider + ?Sized> Provider for std::sync::Arc<P> {
292 fn name(&self) -> &str {
293 (**self).name()
294 }
295 async fn complete(&self, request: &ModelRequest) -> Result<ModelResponse, ProviderError> {
296 (**self).complete(request).await
297 }
298 fn stream<'a>(
299 &'a self,
300 request: &'a ModelRequest,
301 ) -> BoxStream<'a, Result<StreamEvent, ProviderError>> {
302 (**self).stream(request)
303 }
304 fn unavailable_until(&self, model: &str) -> Option<std::time::SystemTime> {
307 (**self).unavailable_until(model)
308 }
309 fn default_model(&self) -> Option<&str> {
310 (**self).default_model()
311 }
312}
313
314pub struct Retry<P> {
316 inner: P,
317 max_attempts: u32,
318 base_delay: Duration,
319}
320
321impl<P: Provider> Retry<P> {
322 fn delay_for(&self, err: &ProviderError, attempt: u32) -> Duration {
323 match err {
324 ProviderError::RateLimited {
325 retry_after: Some(after),
326 } => *after,
327 _ => self.base_delay * 2u32.saturating_pow(attempt.saturating_sub(1)),
328 }
329 }
330
331 pub fn new(inner: P) -> Self {
332 Self {
333 inner,
334 max_attempts: 3,
335 base_delay: Duration::from_millis(500),
336 }
337 }
338
339 pub fn max_attempts(mut self, attempts: u32) -> Self {
340 self.max_attempts = attempts.max(1);
341 self
342 }
343
344 pub fn base_delay(mut self, delay: Duration) -> Self {
345 self.base_delay = delay;
346 self
347 }
348}
349
350#[async_trait]
351impl<P: Provider> Provider for Retry<P> {
352 fn name(&self) -> &str {
353 self.inner.name()
354 }
355 fn unavailable_until(&self, model: &str) -> Option<std::time::SystemTime> {
356 self.inner.unavailable_until(model)
357 }
358 fn default_model(&self) -> Option<&str> {
359 self.inner.default_model()
360 }
361
362 async fn complete(&self, request: &ModelRequest) -> Result<ModelResponse, ProviderError> {
363 let mut attempt = 0;
364 loop {
365 attempt += 1;
366 match self.inner.complete(request).await {
367 Ok(response) => return Ok(response),
368 Err(err)
369 if err.is_retryable()
370 && attempt < self.max_attempts
371 && !request.options.single_attempt =>
372 {
373 tokio::time::sleep(self.delay_for(&err, attempt)).await;
374 }
375 Err(err) => return Err(err),
376 }
377 }
378 }
379
380 fn stream<'a>(
383 &'a self,
384 request: &'a ModelRequest,
385 ) -> BoxStream<'a, Result<StreamEvent, ProviderError>> {
386 let opened = async move {
387 let mut attempt = 0;
388 loop {
389 attempt += 1;
390 let mut events = self.inner.stream(request);
391 match events.next().await {
392 Some(Err(err))
393 if err.is_retryable()
394 && attempt < self.max_attempts
395 && !request.options.single_attempt =>
396 {
397 tokio::time::sleep(self.delay_for(&err, attempt)).await;
398 }
399 first => return (first, events),
400 }
401 }
402 };
403 Box::pin(stream::once(opened).flat_map(|(first, rest)| stream::iter(first).chain(rest)))
404 }
405}