#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum ImageDetail {
Low,
High,
#[default]
Auto,
}
impl std::fmt::Display for ImageDetail {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ImageDetail::Low => write!(f, "low"),
ImageDetail::High => write!(f, "high"),
ImageDetail::Auto => write!(f, "auto"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageBlock {
url: String,
#[serde(default)]
detail: ImageDetail,
}
impl ImageBlock {
pub fn from_url(url: impl Into<String>) -> crate::Result<Self> {
let url = url.into();
if url.is_empty() {
return Err(crate::Error::invalid_input("Image URL cannot be empty"));
}
if url.contains(char::is_control) {
return Err(crate::Error::invalid_input(
"Image URL contains invalid control characters",
));
}
if url.len() > 2000 {
log::warn!(
"Very long image URL ({} chars). Some APIs may have URL length limits.",
url.len()
);
}
if url.starts_with("http://") || url.starts_with("https://") {
Ok(Self {
url,
detail: ImageDetail::default(),
})
} else if let Some(mime_part) = url.strip_prefix("data:") {
let Some((meta, base64_data)) = mime_part.split_once(";base64,") else {
return Err(crate::Error::invalid_input(
"Data URI must be in format: data:image/TYPE;base64,DATA",
));
};
let mime_type = meta.split_once(';').map_or(meta, |(mime, _)| mime);
if mime_type.is_empty() || !mime_type.starts_with("image/") {
return Err(crate::Error::invalid_input(
"Data URI MIME type must start with 'image/'",
));
}
Self::validate_base64(base64_data, "Data URI base64 data")?;
Ok(Self {
url,
detail: ImageDetail::default(),
})
} else {
Err(crate::Error::invalid_input(
"Image URL must start with http://, https://, or data:",
))
}
}
fn validate_base64(data: &str, label: &str) -> crate::Result<()> {
if data.is_empty() {
return Err(crate::Error::invalid_input(format!(
"{label} cannot be empty"
)));
}
if data.len() % 4 != 0 {
return Err(crate::Error::invalid_input(format!(
"{label} has invalid length (must be multiple of 4)"
)));
}
let mut equals_count = 0usize;
for &byte in data.as_bytes() {
if byte == b'=' {
equals_count += 1;
if equals_count > 2 {
return Err(crate::Error::invalid_input(format!(
"{label} has invalid padding (max 2 '=' characters allowed)"
)));
}
} else if byte.is_ascii_alphanumeric() || byte == b'+' || byte == b'/' {
if equals_count > 0 {
return Err(crate::Error::invalid_input(format!(
"{label} padding characters must be at the end"
)));
}
} else {
return Err(crate::Error::invalid_input(format!(
"{label} contains invalid characters. Valid characters: A-Z, a-z, 0-9, +, /, ="
)));
}
}
Ok(())
}
pub fn from_base64(
base64_data: impl AsRef<str>,
mime_type: impl AsRef<str>,
) -> crate::Result<Self> {
let data = base64_data.as_ref();
let mime = mime_type.as_ref();
Self::validate_base64(data, "Base64 image data")?;
if mime.is_empty() {
return Err(crate::Error::invalid_input("MIME type cannot be empty"));
}
if !mime.starts_with("image/") {
return Err(crate::Error::invalid_input(
"MIME type must start with 'image/' (e.g., 'image/png', 'image/jpeg')",
));
}
if mime.contains([';', ',', '\n', '\r']) {
return Err(crate::Error::invalid_input(
"MIME type contains invalid characters (;, \\n, \\r not allowed)",
));
}
if data.len() > 10_000_000 {
log::warn!(
"Very large base64 image data ({} chars, ~{:.1}MB). \
This may exceed API limits or cause performance issues.",
data.len(),
(data.len() as f64 * 0.75) / 1_000_000.0
);
}
let url = format!("data:{};base64,{}", mime, data);
Ok(Self {
url,
detail: ImageDetail::default(),
})
}
pub fn from_file_path(path: impl AsRef<std::path::Path>) -> crate::Result<Self> {
use base64::{Engine as _, engine::general_purpose};
let path = path.as_ref();
let mime_type = match path.extension().and_then(|e| e.to_str()) {
Some("jpg") | Some("jpeg") => "image/jpeg",
Some("png") => "image/png",
Some("gif") => "image/gif",
Some("webp") => "image/webp",
Some("bmp") => "image/bmp",
Some("svg") => "image/svg+xml",
Some(ext) => {
return Err(crate::Error::invalid_input(format!(
"Unsupported image file extension: .{}. Supported: jpg, jpeg, png, gif, webp, bmp, svg",
ext
)));
}
None => {
return Err(crate::Error::invalid_input(
"Image file path must have a file extension (e.g., .jpg, .png)",
));
}
};
let bytes = std::fs::read(path).map_err(|e| {
crate::Error::invalid_input(format!(
"Failed to read image file '{}': {}",
path.display(),
e
))
})?;
if bytes.is_empty() {
return Err(crate::Error::invalid_input(
"Base64 image data cannot be empty",
));
}
let encoded_len = base64::encoded_len(bytes.len(), true).unwrap_or(0);
if encoded_len > 10_000_000 {
log::warn!(
"Very large base64 image data ({} chars, ~{:.1}MB). \
This may exceed API limits or cause performance issues.",
encoded_len,
(encoded_len as f64 * 0.75) / 1_000_000.0
);
}
let mut url = String::with_capacity("data:".len() + mime_type.len() + ";base64,".len() + encoded_len);
url.push_str("data:");
url.push_str(mime_type);
url.push_str(";base64,");
general_purpose::STANDARD.encode_string(&bytes, &mut url);
Ok(Self {
url,
detail: ImageDetail::default(),
})
}
pub fn with_detail(mut self, detail: ImageDetail) -> Self {
self.detail = detail;
self
}
pub fn url(&self) -> &str {
&self.url
}
pub fn detail(&self) -> ImageDetail {
self.detail
}
}