Skip to main content

aidaemon_core/
provider.rs

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/// What the model sees about a tool: the OpenAI-style function object.
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12pub struct ToolSpec {
13    pub name: String,
14    pub description: String,
15    /// JSON Schema for the arguments object.
16    pub parameters: Value,
17}
18
19/// How the model may use tools on this call.
20#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
21pub enum ToolChoice {
22    #[default]
23    Auto,
24    None,
25    Required,
26    Specific(String),
27}
28
29/// The shape a reply must take.
30#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
31#[serde(tag = "type", rename_all = "snake_case")]
32pub enum ResponseFormat {
33    #[default]
34    Text,
35    /// Any JSON object.
36    JsonObject,
37    /// JSON matching `schema`.
38    JsonSchema {
39        name: String,
40        schema: Value,
41        strict: bool,
42    },
43}
44
45/// How a provider should answer, beyond the messages and tools. Providers
46/// map what their API supports and ignore the rest.
47#[derive(Debug, Clone, PartialEq, Default)]
48pub struct RequestOptions {
49    pub response_format: ResponseFormat,
50    /// Provider-neutral reasoning effort: `"low"`, `"medium"` or `"high"`;
51    /// `"off"` turns reasoning off. `None` keeps the provider's default.
52    pub reasoning_effort: Option<String>,
53    /// Exactly one attempt: providers skip their own internal retries, and
54    /// [`Retry`] and [`crate::Failover`] give up at the first error. For a
55    /// call that must not run twice.
56    pub single_attempt: bool,
57    /// With `single_attempt`, lets a [`crate::Failover`] chain move on to
58    /// its next step after an error that proves the attempt used nothing
59    /// ([`ProviderError::proves_nothing_spent`]) or after the policy
60    /// refused the attempt before sending it. Any other error still ends
61    /// the chain, and no step is retried. For a call charged against a
62    /// fixed budget, where unknown spend must not be repeated.
63    pub fallback_when_unspent: bool,
64    /// Identifies the conversation for providers that route prompt-cache
65    /// lookups by key, so its calls reach the same cache. Only a routing
66    /// hint: providers that do not route by key ignore it.
67    pub cache_key: Option<String>,
68}
69
70/// Deferred tools as a provider that can surface tools mid-conversation
71/// sends them, so loading one never changes the request's tool block (and
72/// with it the whole cached prefix). Providers without that ignore it:
73/// [`ModelRequest::tools`] already holds every tool the model may call.
74#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
75pub struct ToolSurfacing {
76    /// Every deferred tool not loaded when the run segment started,
77    /// name-sorted: declared hidden on every call of the segment.
78    pub deferred: Vec<ToolSpec>,
79    /// Those loaded since, in load order.
80    pub loads: Vec<ToolLoad>,
81}
82
83/// Deferred tools a run loaded, surfaced after the result of the call
84/// that answers `after_tool_call` (the batch whose call loaded them).
85#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
86pub struct ToolLoad {
87    pub after_tool_call: String,
88    pub names: Vec<String>,
89}
90
91/// One provider call. Hooks may edit it in [`crate::Hook::before_model`].
92#[derive(Debug, Clone, PartialEq, Default)]
93pub struct ModelRequest {
94    pub model: String,
95    /// Instructions first (stable, cacheable), then the transcript.
96    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    /// The run's deferred tools, for providers that keep a fixed tool block
102    /// and surface loaded tools in the transcript; `None` for a run with no
103    /// deferred tools.
104    pub tool_surfacing: Option<ToolSurfacing>,
105}
106
107/// Token accounting for one call or a whole run.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
109pub struct Usage {
110    pub input_tokens: u64,
111    pub output_tokens: u64,
112    /// Input tokens served from the provider's prompt cache.
113    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    /// Tokens that count toward a budget: cached input is excluded.
126    pub fn billable_tokens(&self) -> u64 {
127        self.input_tokens.saturating_sub(self.cached_input_tokens) + self.output_tokens
128    }
129}
130
131/// A complete (non-streamed) model reply.
132#[derive(Debug, Clone, PartialEq, Default)]
133pub struct ModelResponse {
134    pub text: String,
135    pub tool_calls: Vec<ToolCall>,
136    pub usage: Usage,
137    /// The model's visible reasoning, when the provider returns it apart
138    /// from the answer.
139    pub reasoning: Option<String>,
140    /// Why the reply may be incomplete (cut off at the token limit, held
141    /// back by a safety filter), in the provider's words.
142    pub note: Option<String>,
143    /// The reply stopped at the output-token limit, not where the model
144    /// ended it: its text is cut short.
145    pub cut_off: bool,
146}
147
148/// One item of a streamed reply. A well-formed stream yields any number of
149/// deltas and ends with exactly one `Done` carrying the complete response.
150#[derive(Debug, Clone, PartialEq)]
151pub enum StreamEvent {
152    /// Visible text as it is generated.
153    TextDelta(String),
154    /// The full reply, with tool calls and usage.
155    Done(ModelResponse),
156    /// A [`crate::Failover`] chain gave up on one provider and is trying
157    /// the next. Comes before any text of the reply.
158    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    /// The provider refused the request's tool definitions (a schema it
170    /// does not compile). Dropping media or options cannot cure it: the
171    /// same tools are refused again, so only another model may answer.
172    #[error("invalid tool definitions: {0}")]
173    InvalidTools(String),
174    #[error("authentication failed: {0}")]
175    Auth(String),
176    /// The account cannot pay for the request. `affordable_tokens` is the
177    /// output the provider says it could still pay for, when it says.
178    #[error("billing: {message}")]
179    Billing {
180        message: String,
181        affordable_tokens: Option<u64>,
182    },
183    /// A usage quota (a subscription plan's cap, a daily allowance) is
184    /// used up until `resets_at`, when the provider says. Unlike
185    /// [`ProviderError::RateLimited`], waiting seconds does not help.
186    /// `per_model` is true when the quota covers only the requested model;
187    /// otherwise it covers every model on the account. `in_stream` is true
188    /// when the provider reported it inside a response it had already
189    /// started, so the request was admitted and may have used tokens;
190    /// false when the request was refused before any answer.
191    #[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    /// The model or endpoint does not exist here.
199    #[error("not found: {0}")]
200    NotFound(String),
201    /// The request does not fit the model's context window. `limit` is
202    /// the window in tokens, when the provider states it.
203    #[error("context window exceeded: {message}")]
204    ContextOverflow { message: String, limit: Option<u64> },
205    /// The reply could not be read. `parse` is true when it was not valid
206    /// at all (often a cut-off stream, worth another attempt), false when it
207    /// parsed but had the wrong shape.
208    #[error("malformed reply: {message}")]
209    Malformed { message: String, parse: bool },
210    #[error("provider error: {0}")]
211    Other(String),
212}
213
214impl ProviderError {
215    /// The provider refused the request before doing any work, so the call
216    /// used no tokens: bad credentials, an unknown model, no credit, or a
217    /// used-up quota reported as a refusal. Anything else (a timeout, a
218    /// server error, a cut-off or malformed reply, a quota reported inside
219    /// an answer already started) may have been paid for.
220    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    /// Worth another attempt at the same provider.
229    pub fn is_retryable(&self) -> bool {
230        matches!(
231            self,
232            Self::RateLimited { .. } | Self::Transient(_) | Self::Malformed { parse: true, .. }
233        )
234    }
235}
236
237/// A model backend. Implementations translate [`ModelRequest`] to their wire
238/// format and back. Retries and fallbacks are wrappers ([`Retry`]), not loop
239/// logic.
240///
241/// The loop always calls [`Provider::stream`]. Providers without native
242/// streaming implement only `complete`; the default `stream` wraps it in a
243/// single `Done` event. Streaming providers implement both, usually with
244/// `complete` as a fold over `stream` (see [`collect_stream`]).
245#[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    /// When `model` can next be asked, if this provider already knows it
261    /// cannot answer now (a used-up quota, a rejected credential, no
262    /// credit; see [`crate::QuotaGuard`]). `None`: it may answer now.
263    fn unavailable_until(&self, _model: &str) -> Option<std::time::SystemTime> {
264        None
265    }
266
267    /// The model to use when the agent names none. `None` (the default)
268    /// means the agent must name one with [`crate::AgentBuilder::model`];
269    /// a provider that serves one model, or a test double, says which.
270    fn default_model(&self) -> Option<&str> {
271        None
272    }
273}
274
275/// Drain a stream into its final response. Useful for implementing
276/// `complete` on a streaming provider.
277pub 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    // Forwarded like the calls: without it every `Arc<dyn Provider>` (the
305    // daemon's model backends) reported a used-up model as available.
306    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
314/// Retry layer: exponential backoff on retryable errors.
315pub 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    /// Retries only while nothing has been streamed yet: once a delta has
381    /// reached the caller, a retry would duplicate visible output.
382    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}