adk_vision/budget.rs
1//! Preflight estimates for token-billed backends (spec 3.7 §7.9).
2//!
3//! Before a priced call, the runtime opens a hold capped at the call's estimated cost; a hold
4//! the run's budget cannot cover refuses the call before any image is released (V-I6). A
5//! per-unit backend's estimate is its price ([`PriceRef::PerUnit`](crate::PriceRef)). A
6//! token-billed backend declares a [`TokenEstimate`]: visual tokens from the sent
7//! dimensions, prompt tokens, and output tokens up to the call's cap, at its rates. Its model
8//! call then meters the tokens it used, so the vision hold commits units at zero cost.
9
10use serde::{Deserialize, Serialize};
11
12/// How a provider counts an image's input tokens.
13///
14/// # Example
15///
16/// ```
17/// use adk_vision::ImageTokens;
18///
19/// // Claude: one token per 28-pixel patch.
20/// assert_eq!(ImageTokens::Claude.tokens((1024, 768)), 37 * 28);
21/// // Gemini: 258 tokens up to 384 px a side, then 258 per 768-pixel tile.
22/// assert_eq!(ImageTokens::GeminiTiles.tokens((384, 300)), 258);
23/// assert_eq!(ImageTokens::GeminiTiles.tokens((1600, 900)), 258 * 3 * 2);
24/// ```
25#[non_exhaustive]
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
27#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
28pub enum ImageTokens {
29 /// `⌈w/28⌉ × ⌈h/28⌉` visual tokens of the image the model processes.
30 Claude,
31 /// 258 tokens for an image whose sides are at most 384 px, otherwise 258 per 768×768 tile.
32 GeminiTiles,
33 /// A fixed number of tokens per image.
34 Fixed {
35 /// Tokens per image.
36 tokens: u64,
37 },
38 /// `⌈w/side⌉ × ⌈h/side⌉` tiles of one token each: NVIDIA's Nemotron VL and Nano Omni,
39 /// and Muse, with 32-pixel tiles.
40 Tiles {
41 /// The tile side in pixels.
42 side: u32,
43 },
44}
45
46impl ImageTokens {
47 /// The input tokens of one image of `size` pixels.
48 pub fn tokens(&self, (width, height): (u32, u32)) -> u64 {
49 let (w, h) = (u64::from(width), u64::from(height));
50 match self {
51 Self::Claude => w.div_ceil(28) * h.div_ceil(28),
52 Self::GeminiTiles if w <= 384 && h <= 384 => 258,
53 Self::GeminiTiles => 258 * w.div_ceil(768) * h.div_ceil(768),
54 Self::Fixed { tokens } => *tokens,
55 Self::Tiles { side } => {
56 let side = u64::from((*side).max(1));
57 w.div_ceil(side) * h.div_ceil(side)
58 }
59 }
60 }
61}
62
63/// A token-billed backend's preflight: how its images count, its rates, and the output cap
64/// assumed when a call sets none.
65///
66/// # Example
67///
68/// ```
69/// use adk_vision::{ImageTokens, TokenEstimate};
70///
71/// // $3 per million input tokens, $15 per million output tokens.
72/// let sonnet = TokenEstimate::new(ImageTokens::Claude, 3_000_000, 15_000_000).with_max_output_tokens(1_024);
73/// // One 560×280 crop (200 visual tokens), a 400-character prompt (100 tokens), 1,024 output tokens.
74/// assert_eq!(sonnet.estimate_micro_usd(&[(560, 280)], 400, None), 900 + 15_360);
75/// // A call that caps its own output at 100 tokens.
76/// assert_eq!(sonnet.estimate_micro_usd(&[(560, 280)], 400, Some(100)), 900 + 1_500);
77/// ```
78#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
79#[serde(rename_all = "camelCase")]
80#[non_exhaustive]
81pub struct TokenEstimate {
82 /// How the provider counts image tokens.
83 pub image_tokens: ImageTokens,
84 /// Input price in micro-USD per million tokens.
85 pub input_micro_usd_per_million: u64,
86 /// Output price in micro-USD per million tokens.
87 pub output_micro_usd_per_million: u64,
88 /// The output tokens assumed when a call sets no cap.
89 pub max_output_tokens: u32,
90}
91
92impl TokenEstimate {
93 /// Characters per prompt token assumed for the estimate.
94 pub const CHARS_PER_TOKEN: u64 = 4;
95
96 /// An estimate at these rates, assuming 4,096 output tokens when a call sets no cap.
97 pub fn new(
98 image_tokens: ImageTokens,
99 input_micro_usd_per_million: u64,
100 output_micro_usd_per_million: u64,
101 ) -> Self {
102 Self {
103 image_tokens,
104 input_micro_usd_per_million,
105 output_micro_usd_per_million,
106 max_output_tokens: 4_096,
107 }
108 }
109
110 /// Sets the output tokens assumed when a call sets no cap.
111 pub fn with_max_output_tokens(mut self, tokens: u32) -> Self {
112 self.max_output_tokens = tokens;
113 self
114 }
115
116 /// The input tokens of `images` (sent sizes) and a prompt of `prompt_chars` characters.
117 pub fn input_tokens(&self, images: &[(u32, u32)], prompt_chars: usize) -> u64 {
118 let visual: u64 = images.iter().map(|size| self.image_tokens.tokens(*size)).sum();
119 visual + (prompt_chars as u64).div_ceil(Self::CHARS_PER_TOKEN)
120 }
121
122 /// The most the call can cost, in micro-USD, rounded up.
123 pub fn estimate_micro_usd(
124 &self,
125 images: &[(u32, u32)],
126 prompt_chars: usize,
127 max_output_tokens: Option<u32>,
128 ) -> u64 {
129 let input = self.input_tokens(images, prompt_chars);
130 let output = u64::from(max_output_tokens.unwrap_or(self.max_output_tokens));
131 (input.saturating_mul(self.input_micro_usd_per_million)
132 + output.saturating_mul(self.output_micro_usd_per_million))
133 .div_ceil(1_000_000)
134 }
135}