Skip to main content

adk_vision/cloud/
preflight.rs

1//! [`Preflight`]: what a describer call can cost, estimated before its request (spec 3.7
2//! ยง7.9).
3
4use std::sync::Arc;
5
6use adk_core::{Llm, LlmRequest, LlmResponseStream, Part, SchemaAdapter};
7use adk_model::pricing::{PricingCatalog, request_input_token_bound};
8use async_trait::async_trait;
9
10use super::adapter::RegionAdapter;
11
12/// The estimate a describer call holds against the run's budget before its request.
13///
14/// Images count by the provider's formula ([`RegionAdapter::image_tokens`]) instead of
15/// one token per byte of the encoded image, so a screenshot is held at the thousands of
16/// tokens it costs rather than the millions its PNG bytes would bound.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18#[non_exhaustive]
19pub struct Preflight {
20    /// Input tokens of the images, by the provider's formula.
21    pub image_tokens: u64,
22    /// Input tokens of the whole request: the images, and the text bounded at one token
23    /// per byte.
24    pub input_tokens: u64,
25    /// The output cap the estimate assumes: the request's, else the model's maximum.
26    pub output_tokens: Option<u64>,
27    /// The cost bound in micro-USD, or `None` when the catalog does not price the model.
28    pub max_cost_micro_usd: Option<u64>,
29}
30
31impl Preflight {
32    pub(crate) fn estimate(
33        model: &str,
34        request: &LlmRequest,
35        adapter: Option<&dyn RegionAdapter>,
36        sizes: &[(u32, u32)],
37    ) -> Self {
38        let image_tokens: u64 = match adapter {
39            Some(adapter) => {
40                let formula = adapter.image_tokens();
41                sizes.iter().map(|s| formula.tokens(*s)).sum()
42            }
43            // No formula: the generic bound of one token per byte stands.
44            None => 0,
45        };
46        let mut text_only = request.clone();
47        for content in &mut text_only.contents {
48            content.parts.retain(|p| !matches!(p, Part::InlineData { .. }));
49        }
50        let text_tokens = request_input_token_bound(&text_only).unwrap_or(0);
51        let input_tokens = text_tokens.saturating_add(image_tokens);
52        let catalog = PricingCatalog::standard();
53        let price = catalog.lookup(None, model);
54        let output_tokens = request
55            .config
56            .as_ref()
57            .and_then(|c| c.max_output_tokens)
58            .and_then(|t| u64::try_from(t).ok())
59            .or_else(|| price.and_then(|p| p.max_output_tokens));
60        let max_cost_micro_usd =
61            match (adapter, price, output_tokens) {
62                (Some(_), Some(price), Some(output)) => {
63                    let today = chrono::Utc::now().date_naive();
64                    let tomorrow = today.succ_opt().unwrap_or(today);
65                    let usd = price
66                        .max_cost_usd(input_tokens, output, today)
67                        .max(price.max_cost_usd(input_tokens, output, tomorrow));
68                    adk_core::usd_to_micro_usd(usd).map(|m| m.saturating_add(1))
69                }
70                _ => None,
71            };
72        Self { image_tokens, input_tokens, output_tokens, max_cost_micro_usd }
73    }
74}
75
76/// The runtime's preflight for a priced model: its image-token formula and catalog rates,
77/// at the highest input rate (cache writes included) so the hold bounds the call. `None`
78/// when the catalog does not price the model.
79pub(crate) fn token_estimate(
80    model: &str,
81    images: crate::ImageTokens,
82    max_output_tokens: Option<u32>,
83) -> Option<crate::TokenEstimate> {
84    let price = PricingCatalog::standard().lookup(None, model)?;
85    let rates = price.rates_for(0, chrono::Utc::now().date_naive());
86    let input = rates.input.max(rates.cache_write_5m).max(rates.cache_write_1h);
87    let per_million = |usd: f64| (usd * 1_000_000.0).ceil() as u64;
88    Some(
89        crate::TokenEstimate::new(images, per_million(input), per_million(rates.output))
90            .with_max_output_tokens(max_output_tokens.unwrap_or(4_096)),
91    )
92}
93
94/// The describer's model, with its spend hold sized by the preflight estimate.
95pub(crate) struct Preflighted {
96    inner: Arc<dyn Llm>,
97    bound: Option<u64>,
98}
99
100impl Preflighted {
101    pub(crate) fn new(inner: Arc<dyn Llm>, bound: Option<u64>) -> Self {
102        Self { inner, bound }
103    }
104}
105
106#[async_trait]
107impl Llm for Preflighted {
108    fn name(&self) -> &str {
109        self.inner.name()
110    }
111
112    async fn generate_content(
113        &self,
114        req: LlmRequest,
115        stream: bool,
116    ) -> adk_core::Result<LlmResponseStream> {
117        self.inner.generate_content(req, stream).await
118    }
119
120    fn schema_adapter(&self) -> &dyn SchemaAdapter {
121        self.inner.schema_adapter()
122    }
123
124    fn uses_interactions_api(&self) -> bool {
125        self.inner.uses_interactions_api()
126    }
127
128    fn max_cost_micro_usd(&self, request: &LlmRequest) -> Option<u64> {
129        self.bound.or_else(|| self.inner.max_cost_micro_usd(request))
130    }
131
132    fn context_window(&self) -> Option<u64> {
133        self.inner.context_window()
134    }
135
136    fn data_locality(&self) -> adk_core::DataLocality {
137        self.inner.data_locality()
138    }
139
140    fn data_destinations(&self) -> Vec<adk_core::DataDestination> {
141        self.inner.data_destinations()
142    }
143}