Skip to main content

adk_vision/cloud/
claude.rs

1//! [`ClaudePixels`]: Claude answers in pixels of the image it processed.
2
3use serde_json::{Value, json};
4
5use super::adapter::{RegionAdapter, boxed, image_index, quad};
6use crate::backend::InputLimits;
7use crate::budget::ImageTokens;
8use crate::geometry::CoordFrame;
9use crate::traits::ImageRegion;
10
11/// Claude's image tiers: how large an image it takes before resizing it itself.
12#[non_exhaustive]
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum ClaudeVisionTier {
15    /// Claude Opus 4.7 and later, Sonnet 5 and later, Haiku 5.5, Fable and Mythos: 2,576 px
16    /// on the long edge and 4,784 visual tokens of `⌈w/28⌉ × ⌈h/28⌉`.
17    High,
18    /// Earlier models: 1,568 px on the long edge and about 1,568 tokens of `w × h / 750`.
19    Standard,
20}
21
22/// Claude's frame: pixels of the image it processed after its own resize.
23///
24/// Claude resizes an image above its tier's limit and then answers in the resized pixels.
25/// The adapter's [`limits`](RegionAdapter::limits) keep every released image inside the
26/// tier, so Claude never resizes and its answer is in pixels of the image as sent
27/// ([`CoordFrame::SentPixels`]); the egress gate's resize is in the transform chain.
28///
29/// The high tier's limit is 2,576 px on the long edge and 3,605,000 pixels, the most for
30/// which `⌈w/28⌉ × ⌈h/28⌉` stays within 4,784 tokens on any aspect ratio. Counted with
31/// `count_tokens` on 2026-11-19: a 2356×1530 image costs 4,675 visual tokens (and 3 for the
32/// image block) on `claude-sonnet-5-5` and `claude-haiku-5-5`, and a 2576×1673 one is
33/// resized by the API.
34///
35/// # Example
36///
37/// ```
38/// use adk_vision::cloud::{ClaudePixels, RegionAdapter};
39///
40/// let claude = ClaudePixels::for_model("claude-sonnet-5-5");
41/// // 35 × 20 visual tokens.
42/// assert_eq!(claude.image_tokens().tokens((960, 540)), 700);
43/// // A 3024×1964 screenshot is downscaled until Claude would not resize it.
44/// let (w, h) = claude.limits().fit((3024, 1964)).unwrap();
45/// assert!(w.div_ceil(28) * h.div_ceil(28) <= 4784);
46/// ```
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub struct ClaudePixels {
49    tier: ClaudeVisionTier,
50}
51
52impl ClaudePixels {
53    /// The adapter for a tier.
54    pub fn new(tier: ClaudeVisionTier) -> Self {
55        Self { tier }
56    }
57
58    /// The adapter for a Claude model ID, first-party, Bedrock or Vertex.
59    pub fn for_model(model: &str) -> Self {
60        Self::new(tier_for_model(model))
61    }
62
63    /// The tier.
64    pub fn tier(&self) -> ClaudeVisionTier {
65        self.tier
66    }
67}
68
69fn tier_for_model(model: &str) -> ClaudeVisionTier {
70    if crate::screen::claude_high_tier(model) {
71        ClaudeVisionTier::High
72    } else {
73        ClaudeVisionTier::Standard
74    }
75}
76
77impl RegionAdapter for ClaudePixels {
78    fn name(&self) -> &str {
79        "claude-pixels"
80    }
81
82    fn frame(&self) -> CoordFrame {
83        CoordFrame::SentPixels
84    }
85
86    fn limits(&self) -> InputLimits {
87        match self.tier {
88            ClaudeVisionTier::High => InputLimits::long_edge(2576).with_max_pixels(3_605_000),
89            ClaudeVisionTier::Standard => InputLimits::long_edge(1568).with_max_pixels(1_150_000),
90        }
91    }
92
93    fn image_tokens(&self) -> ImageTokens {
94        match self.tier {
95            ClaudeVisionTier::High => ImageTokens::Claude,
96            // `w × h / 750` within the tier's 1,150,000-pixel limit stays under 1,568.
97            ClaudeVisionTier::Standard => ImageTokens::Fixed { tokens: 1_568 },
98        }
99    }
100
101    fn region_schema(&self) -> Value {
102        json!({
103            "type": "object",
104            "properties": {
105                "label": {"type": "string", "description": "What the region is."},
106                "box": {
107                    "type": "array",
108                    "items": {"type": "number"},
109                    "description": "[x_min, y_min, x_max, y_max] in pixels of the image."
110                }
111            },
112            "required": ["label", "box"],
113            "additionalProperties": false
114        })
115    }
116
117    fn instructions(&self, sizes: &[(u32, u32)]) -> String {
118        let images = match sizes {
119            [(w, h)] => format!("The image is {w}x{h} pixels."),
120            many => many
121                .iter()
122                .enumerate()
123                .map(|(i, (w, h))| format!("Image {i} is {w}x{h} pixels."))
124                .collect::<Vec<_>>()
125                .join(" "),
126        };
127        format!(
128            "{images} Give each region's `box` as [x_min, y_min, x_max, y_max] in pixels of \
129             that image, origin at the top-left corner, x to the right and y down, the box \
130             tight around the region."
131        )
132    }
133
134    fn parse_region(
135        &self,
136        item: &Value,
137        sizes: &[(u32, u32)],
138    ) -> Result<Option<ImageRegion>, String> {
139        let image = image_index(item, sizes)?;
140        let Some(raw) = quad(item, &["box", "bbox", "bbox_2d"])? else {
141            return Ok(None);
142        };
143        Ok(Some(boxed(self.frame(), raw, item, image)))
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    #[test]
152    fn tiers_follow_the_model() {
153        for high in [
154            "claude-sonnet-5-5",
155            "claude-haiku-5-5",
156            "claude-opus-5-5",
157            "claude-opus-4-7",
158            "claude-opus-4-8",
159            "claude-sonnet-5",
160            "claude-fable-5-2",
161            "anthropic.claude-sonnet-5-5",
162            "claude-opus-4-7@20260101",
163        ] {
164            assert_eq!(tier_for_model(high), ClaudeVisionTier::High, "{high}");
165        }
166        for standard in ["claude-haiku-4-5", "claude-sonnet-4-6", "claude-opus-4-6", "claude-3-7"] {
167            assert_eq!(tier_for_model(standard), ClaudeVisionTier::Standard, "{standard}");
168        }
169    }
170
171    #[test]
172    fn token_formula_matches_count_tokens() {
173        let claude = ClaudePixels::new(ClaudeVisionTier::High);
174        // Measured with count_tokens on claude-sonnet-5-5 and claude-haiku-5-5, less the
175        // nine tokens of the text block and the three of the image block.
176        for (size, measured) in [
177            ((960, 540), 712),
178            ((1000, 1000), 1308),
179            ((1001, 1001), 1308),
180            ((1568, 1018), 2084),
181            ((2356, 1530), 4687),
182        ] {
183            assert_eq!(claude.image_tokens().tokens(size), measured - 12, "{size:?}");
184        }
185    }
186
187    #[test]
188    fn the_limit_keeps_every_aspect_within_the_token_cap() {
189        let limits = ClaudePixels::new(ClaudeVisionTier::High).limits();
190        for (w, h) in [(3024, 1964), (5000, 5000), (2576, 2576), (8000, 1000), (2000, 2000)] {
191            let (fw, fh) = limits.fit((w, h)).unwrap_or((w, h));
192            assert!(fw.max(fh) <= 2576);
193            assert!(u64::from(fw.div_ceil(28)) * u64::from(fh.div_ceil(28)) <= 4784, "{w}x{h}");
194        }
195    }
196}