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    /// No model is connected: the daemon holds a stand-in provider that
213    /// answers every call with this, without any network call.
214    #[error("no model is connected")]
215    NotConfigured,
216}
217
218impl ProviderError {
219    /// The provider refused the request before doing any work, so the call
220    /// used no tokens: bad credentials, an unknown model, no credit, or a
221    /// used-up quota reported as a refusal. Anything else (a timeout, a
222    /// server error, a cut-off or malformed reply, a quota reported inside
223    /// an answer already started) may have been paid for.
224    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    /// Worth another attempt at the same provider.
233    pub fn is_retryable(&self) -> bool {
234        matches!(
235            self,
236            Self::RateLimited { .. } | Self::Transient(_) | Self::Malformed { parse: true, .. }
237        )
238    }
239}
240
241/// A model backend. Implementations translate [`ModelRequest`] to their wire
242/// format and back. Retries and fallbacks are wrappers ([`Retry`]), not loop
243/// logic.
244///
245/// The loop always calls [`Provider::stream`]. Providers without native
246/// streaming implement only `complete`; the default `stream` wraps it in a
247/// single `Done` event. Streaming providers implement both, usually with
248/// `complete` as a fold over `stream` (see [`collect_stream`]).
249#[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    /// When `model` can next be asked, if this provider already knows it
265    /// cannot answer now (a used-up quota, a rejected credential, no
266    /// credit; see [`crate::QuotaGuard`]). `None`: it may answer now.
267    fn unavailable_until(&self, _model: &str) -> Option<std::time::SystemTime> {
268        None
269    }
270
271    /// The model to use when the agent names none. `None` (the default)
272    /// means the agent must name one with [`crate::AgentBuilder::model`];
273    /// a provider that serves one model, or a test double, says which.
274    fn default_model(&self) -> Option<&str> {
275        None
276    }
277}
278
279/// Drain a stream into its final response. Useful for implementing
280/// `complete` on a streaming provider.
281pub 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    // Forwarded like the calls: without it every `Arc<dyn Provider>` (the
309    // daemon's model backends) reported a used-up model as available.
310    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
318/// Retry layer: exponential backoff on retryable errors.
319pub 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    /// Retries only while nothing has been streamed yet: once a delta has
385    /// reached the caller, a retry would duplicate visible output.
386    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}