Skip to main content

open_agent/types/
image.rs

1/// Image detail level for vision API calls.
2///
3/// Controls the resolution and token cost of image processing.
4///
5/// # Token Costs Vary by Model ⚠️
6///
7/// **OpenAI Vision API** (reference values):
8/// - `Low`: ~85 tokens (512x512 max resolution)
9/// - `High`: Variable tokens based on image dimensions
10/// - `Auto`: Model decides (balanced default)
11///
12/// **Local models** (llama.cpp, Ollama, vLLM):
13/// - May have **completely different** token calculations
14/// - Some models don't charge tokens for images at all
15/// - The `ImageDetail` setting may be ignored entirely
16///
17/// **Anthropic messages protocol**: the API has no equivalent field, so the setting is
18/// dropped in translation rather than mapped onto something approximate.
19///
20/// **Recommendation:** Always benchmark your specific model to understand
21/// actual token consumption. Do not rely on OpenAI's values for capacity planning
22/// with local models.
23///
24/// # Examples
25///
26/// ```
27/// use open_agent::ImageDetail;
28///
29/// let detail = ImageDetail::High;
30/// assert_eq!(detail.to_string(), "high");
31/// ```
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(rename_all = "lowercase")]
34#[derive(Default)]
35pub enum ImageDetail {
36    /// Low resolution (512x512), fixed 85 tokens
37    Low,
38    /// High resolution, variable tokens based on dimensions
39    High,
40    /// Automatic selection (default)
41    #[default]
42    Auto,
43}
44
45impl std::fmt::Display for ImageDetail {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        match self {
48            ImageDetail::Low => write!(f, "low"),
49            ImageDetail::High => write!(f, "high"),
50            ImageDetail::Auto => write!(f, "auto"),
51        }
52    }
53}
54
55/// Image content block for vision-capable models.
56///
57/// Supports both URL-based images and base64-encoded images.
58///
59/// # Examples
60///
61/// ```
62/// use open_agent::{ImageBlock, ImageDetail};
63///
64/// // From URL
65/// let image = ImageBlock::from_url("https://example.com/image.jpg")?;
66///
67/// // From base64 (use properly formatted base64)
68/// let image = ImageBlock::from_base64("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==", "image/png")?;
69///
70/// // With detail level
71/// let image = ImageBlock::from_url("https://example.com/image.jpg")?
72///     .with_detail(ImageDetail::High);
73/// # Ok::<(), open_agent::Error>(())
74/// ```
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct ImageBlock {
77    url: String,
78    #[serde(default)]
79    detail: ImageDetail,
80}
81
82impl ImageBlock {
83    /// Creates a new image block from a URL.
84    ///
85    /// # Arguments
86    ///
87    /// * `url` - The image URL (must be HTTP, HTTPS, or data URI)
88    ///
89    /// # Errors
90    ///
91    /// Returns `Error::InvalidInput` if:
92    /// - URL is empty
93    /// - URL contains control characters (newline, tab, null, etc.)
94    /// - URL scheme is not `http://`, `https://`, or `data:`
95    /// - Data URI is malformed (missing MIME type or base64 encoding)
96    /// - Data URI base64 portion has invalid characters, length, or padding
97    ///
98    /// # Warnings
99    ///
100    /// - Logs a warning if URL exceeds 2000 characters
101    ///
102    /// # Example
103    ///
104    /// ```
105    /// use open_agent::ImageBlock;
106    ///
107    /// let image = ImageBlock::from_url("https://example.com/cat.jpg")?;
108    /// assert_eq!(image.url(), "https://example.com/cat.jpg");
109    /// # Ok::<(), open_agent::Error>(())
110    /// ```
111    pub fn from_url(url: impl Into<String>) -> crate::Result<Self> {
112        let url = url.into();
113
114        // Validate URL is not empty
115        if url.is_empty() {
116            return Err(crate::Error::invalid_input("Image URL cannot be empty"));
117        }
118
119        // Check for control characters in URL
120        if url.contains(char::is_control) {
121            return Err(crate::Error::invalid_input(
122                "Image URL contains invalid control characters",
123            ));
124        }
125
126        // Warn about very long URLs (>2000 chars)
127        if url.len() > 2000 {
128            log::warn!(
129                "Very long image URL ({} chars). Some APIs may have URL length limits.",
130                url.len()
131            );
132        }
133
134        // Validate URL scheme
135        if url.starts_with("http://") || url.starts_with("https://") {
136            // Valid HTTP/HTTPS URL
137            Ok(Self {
138                url,
139                detail: ImageDetail::default(),
140            })
141        } else if let Some(mime_part) = url.strip_prefix("data:") {
142            // Validate data URI format: data:MIME;base64,DATA
143            let Some((meta, base64_data)) = mime_part.split_once(";base64,") else {
144                return Err(crate::Error::invalid_input(
145                    "Data URI must be in format: data:image/TYPE;base64,DATA",
146                ));
147            };
148
149            // Extract MIME type (before any optional parameters like `;charset=...`)
150            let mime_type = meta.split_once(';').map_or(meta, |(mime, _)| mime);
151            if mime_type.is_empty() || !mime_type.starts_with("image/") {
152                return Err(crate::Error::invalid_input(
153                    "Data URI MIME type must start with 'image/'",
154                ));
155            }
156
157            Self::validate_base64(base64_data, "Data URI base64 data")?;
158
159            Ok(Self {
160                url,
161                detail: ImageDetail::default(),
162            })
163        } else {
164            Err(crate::Error::invalid_input(
165                "Image URL must start with http://, https://, or data:",
166            ))
167        }
168    }
169
170    /// Validates base64 characters, length, and trailing padding in a single byte pass.
171    fn validate_base64(data: &str, label: &str) -> crate::Result<()> {
172        if data.is_empty() {
173            return Err(crate::Error::invalid_input(format!(
174                "{label} cannot be empty"
175            )));
176        }
177
178        if data.len() % 4 != 0 {
179            return Err(crate::Error::invalid_input(format!(
180                "{label} has invalid length (must be multiple of 4)"
181            )));
182        }
183
184        let mut equals_count = 0usize;
185        for &byte in data.as_bytes() {
186            if byte == b'=' {
187                equals_count += 1;
188                if equals_count > 2 {
189                    return Err(crate::Error::invalid_input(format!(
190                        "{label} has invalid padding (max 2 '=' characters allowed)"
191                    )));
192                }
193            } else if byte.is_ascii_alphanumeric() || byte == b'+' || byte == b'/' {
194                if equals_count > 0 {
195                    return Err(crate::Error::invalid_input(format!(
196                        "{label} padding characters must be at the end"
197                    )));
198                }
199            } else {
200                return Err(crate::Error::invalid_input(format!(
201                    "{label} contains invalid characters. Valid characters: A-Z, a-z, 0-9, +, /, ="
202                )));
203            }
204        }
205
206        Ok(())
207    }
208
209    /// Creates a new image block from base64-encoded data.
210    ///
211    /// # Arguments
212    ///
213    /// * `base64_data` - The base64-encoded image data
214    /// * `mime_type` - The MIME type (e.g., "image/jpeg", "image/png")
215    ///
216    /// # Errors
217    ///
218    /// Returns `Error::InvalidInput` if:
219    /// - Base64 data is empty
220    /// - Base64 contains invalid characters (only A-Z, a-z, 0-9, +, /, = allowed)
221    /// - Base64 length is not a multiple of 4
222    /// - Base64 has invalid padding (more than 2 '=' characters or not at end)
223    /// - MIME type is empty
224    /// - MIME type does not start with "image/"
225    /// - MIME type contains injection characters (;, \\n, \\r, ,)
226    ///
227    /// # Warnings
228    ///
229    /// - Logs a warning if base64 data exceeds 10MB (~7.5MB decoded)
230    ///
231    /// # Example
232    ///
233    /// ```
234    /// use open_agent::ImageBlock;
235    ///
236    /// let base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
237    /// let image = ImageBlock::from_base64(base64, "image/png")?;
238    /// assert!(image.url().starts_with("data:image/png;base64,"));
239    /// # Ok::<(), open_agent::Error>(())
240    /// ```
241    pub fn from_base64(
242        base64_data: impl AsRef<str>,
243        mime_type: impl AsRef<str>,
244    ) -> crate::Result<Self> {
245        let data = base64_data.as_ref();
246        let mime = mime_type.as_ref();
247
248        Self::validate_base64(data, "Base64 image data")?;
249
250        // Validate MIME type is not empty
251        if mime.is_empty() {
252            return Err(crate::Error::invalid_input("MIME type cannot be empty"));
253        }
254
255        // Validate MIME type starts with "image/"
256        if !mime.starts_with("image/") {
257            return Err(crate::Error::invalid_input(
258                "MIME type must start with 'image/' (e.g., 'image/png', 'image/jpeg')",
259            ));
260        }
261
262        // Check for MIME type injection characters
263        if mime.contains([';', ',', '\n', '\r']) {
264            return Err(crate::Error::invalid_input(
265                "MIME type contains invalid characters (;, \\n, \\r not allowed)",
266            ));
267        }
268
269        // Warn about extremely large base64 data (>10MB)
270        if data.len() > 10_000_000 {
271            log::warn!(
272                "Very large base64 image data ({} chars, ~{:.1}MB). \
273                 This may exceed API limits or cause performance issues.",
274                data.len(),
275                (data.len() as f64 * 0.75) / 1_000_000.0
276            );
277        }
278
279        let url = format!("data:{};base64,{}", mime, data);
280        Ok(Self {
281            url,
282            detail: ImageDetail::default(),
283        })
284    }
285
286    /// Creates a new image block from a local file path.
287    ///
288    /// This is a convenience method that reads the file from disk, encodes it as
289    /// base64, and creates an ImageBlock with a data URI. The MIME type is inferred
290    /// from the file extension.
291    ///
292    /// # Arguments
293    ///
294    /// * `path` - Path to the image file on the local filesystem
295    ///
296    /// # Errors
297    ///
298    /// Returns `Error::InvalidInput` if:
299    /// - File cannot be read
300    /// - File extension is missing or unsupported
301    /// - File is empty
302    ///
303    /// # Supported Formats
304    ///
305    /// - `.jpg`, `.jpeg` → `image/jpeg`
306    /// - `.png` → `image/png`
307    /// - `.gif` → `image/gif`
308    /// - `.webp` → `image/webp`
309    /// - `.bmp` → `image/bmp`
310    /// - `.svg` → `image/svg+xml`
311    ///
312    /// # Example
313    ///
314    /// ```no_run
315    /// use open_agent::ImageBlock;
316    ///
317    /// let image = ImageBlock::from_file_path("/path/to/photo.jpg")?;
318    /// # Ok::<(), open_agent::Error>(())
319    /// ```
320    ///
321    /// # Security Note
322    ///
323    /// This method reads files from the local filesystem. Ensure the path comes from
324    /// a trusted source to prevent unauthorized file access.
325    pub fn from_file_path(path: impl AsRef<std::path::Path>) -> crate::Result<Self> {
326        use base64::{Engine as _, engine::general_purpose};
327
328        let path = path.as_ref();
329
330        // Validate extension before reading potentially large files from disk
331        let mime_type = match path.extension().and_then(|e| e.to_str()) {
332            Some("jpg") | Some("jpeg") => "image/jpeg",
333            Some("png") => "image/png",
334            Some("gif") => "image/gif",
335            Some("webp") => "image/webp",
336            Some("bmp") => "image/bmp",
337            Some("svg") => "image/svg+xml",
338            Some(ext) => {
339                return Err(crate::Error::invalid_input(format!(
340                    "Unsupported image file extension: .{}. Supported: jpg, jpeg, png, gif, webp, bmp, svg",
341                    ext
342                )));
343            }
344            None => {
345                return Err(crate::Error::invalid_input(
346                    "Image file path must have a file extension (e.g., .jpg, .png)",
347                ));
348            }
349        };
350
351        // Read file bytes
352        let bytes = std::fs::read(path).map_err(|e| {
353            crate::Error::invalid_input(format!(
354                "Failed to read image file '{}': {}",
355                path.display(),
356                e
357            ))
358        })?;
359
360        if bytes.is_empty() {
361            return Err(crate::Error::invalid_input(
362                "Base64 image data cannot be empty",
363            ));
364        }
365
366        // Encode directly into the final data URI buffer without intermediate copies or re-scans
367        let encoded_len = base64::encoded_len(bytes.len(), true).unwrap_or(0);
368        if encoded_len > 10_000_000 {
369            log::warn!(
370                "Very large base64 image data ({} chars, ~{:.1}MB). \
371                 This may exceed API limits or cause performance issues.",
372                encoded_len,
373                (encoded_len as f64 * 0.75) / 1_000_000.0
374            );
375        }
376
377        let mut url = String::with_capacity("data:".len() + mime_type.len() + ";base64,".len() + encoded_len);
378        url.push_str("data:");
379        url.push_str(mime_type);
380        url.push_str(";base64,");
381        general_purpose::STANDARD.encode_string(&bytes, &mut url);
382
383        Ok(Self {
384            url,
385            detail: ImageDetail::default(),
386        })
387    }
388
389    /// Sets the image detail level.
390    ///
391    /// # Example
392    ///
393    /// ```
394    /// use open_agent::{ImageBlock, ImageDetail};
395    ///
396    /// let image = ImageBlock::from_url("https://example.com/image.jpg")?
397    ///     .with_detail(ImageDetail::High);
398    /// # Ok::<(), open_agent::Error>(())
399    /// ```
400    pub fn with_detail(mut self, detail: ImageDetail) -> Self {
401        self.detail = detail;
402        self
403    }
404
405    /// Returns the image URL (or data URI for base64 images).
406    pub fn url(&self) -> &str {
407        &self.url
408    }
409
410    /// Returns the image detail level.
411    pub fn detail(&self) -> ImageDetail {
412        self.detail
413    }
414}