use std::path::PathBuf;
use std::time::Duration;
use adk_core::{AdkError, ErrorCategory, ErrorComponent, RetryHint};
use crate::digest::Digest;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum VisionError {
#[error(
"unsupported image format {detected}; accepted formats are PNG, JPEG, WebP and the first frame of a GIF"
)]
UnsupportedFormat {
detected: String,
},
#[error(
"the image is {actual} bytes, over the {limit}-byte cap; downscale or recompress it before handing it over"
)]
TooManyBytes {
limit: u64,
actual: u64,
},
#[error(
"the image has {actual} pixels, over the {limit}-pixel cap; downscale it before handing it over"
)]
TooManyPixels {
limit: u64,
actual: u64,
},
#[error("the image could not be decoded: {0}")]
Decode(String),
#[error(
"backend `{backend}` accepts at most {limit}; the image is {actual}. Crop or downscale it first"
)]
InputTooLarge {
backend: String,
limit: String,
actual: String,
},
#[error(
"backend `{backend}` is remote and only takes images released by the egress gate; configure an `EgressGate` on the runtime"
)]
NotReleased {
backend: String,
},
#[error("the image was not released to {host}: {reason}")]
EgressRefused {
host: String,
reason: String,
},
#[error(
"sending image {egress} to {host} as `{data_class}` needs a person's approval; approve that digest and retry"
)]
EgressHeld {
host: String,
data_class: String,
egress: Digest,
},
#[error(
"the egress policy requires `{class}` redaction and no redactor for it is installed; add one to the egress gate or remove the class from the policy"
)]
RedactionUnavailable {
class: String,
},
#[error(
"licence acceptance required for model `{model}`: read {licence_url}, then run `adk-rust vision models accept {model}`"
)]
LicenceAcceptanceRequired {
model: String,
licence_url: String,
},
#[error(
"model `{model}` is licensed {class} ({licence_url}); name it in the licence policy to allow it"
)]
LicenceNotAllowed {
model: String,
class: String,
licence_url: String,
},
#[error(
"model file {path} does not match its manifest: expected {expected}, found {actual}; delete it and fetch again"
)]
DigestMismatch {
path: PathBuf,
expected: Digest,
actual: Digest,
},
#[error(
"model file {path} is {actual} bytes, but its manifest pins {expected}; delete it and fetch again"
)]
SizeMismatch {
path: PathBuf,
expected: u64,
actual: u64,
},
#[error(
"`{file}` of model `{model}` is not in the cache and HF_HUB_OFFLINE is set; fetch it once with network access"
)]
Offline {
model: String,
file: String,
},
#[error("fetching `{file}` of model `{model}` failed: {message}")]
Fetch {
model: String,
file: String,
message: String,
},
#[error("model manifest `{id}` is invalid: {reason}")]
Manifest {
id: String,
reason: String,
},
#[error("backend `{backend}` is rate limited; retry later")]
RateLimited {
backend: String,
retry_after: Option<Duration>,
},
#[error("backend `{backend}` timed out")]
Timeout {
backend: String,
},
#[error("the vision call was cancelled")]
Cancelled,
#[error("backend `{backend}` is unavailable: {message}")]
Unavailable {
backend: String,
message: String,
},
#[error("unsupported: {0}")]
Unsupported(String),
#[error("invalid input: {0}")]
InvalidInput(String),
#[error("no vision backend `{0}` is registered for this task")]
BackendNotFound(String),
#[error("backend `{backend}` returned output that could not be parsed: {message}")]
Parse {
backend: String,
message: String,
},
#[error("backend `{backend}` failed: {message}")]
Backend {
backend: String,
message: String,
},
#[error("{action} {path}: {source}")]
Io {
action: &'static str,
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error(
"collection `{collection}` holds vectors of embedding space {recorded}, not {offered}; \
re-index into a new collection with this embedder, or use the embedder the collection \
was built with"
)]
SpaceMismatch {
collection: String,
recorded: String,
offered: String,
},
#[error(transparent)]
Core(#[from] AdkError),
}
impl VisionError {
pub fn code(&self) -> &'static str {
match self {
Self::UnsupportedFormat { .. } => "vision.unsupported_format",
Self::TooManyBytes { .. } => "vision.too_many_bytes",
Self::TooManyPixels { .. } => "vision.too_many_pixels",
Self::Decode(_) => "vision.decode",
Self::InputTooLarge { .. } => "vision.input_too_large",
Self::NotReleased { .. } => "vision.not_released",
Self::EgressRefused { .. } => "vision.egress.refused",
Self::EgressHeld { .. } => "vision.egress.held",
Self::RedactionUnavailable { .. } => "vision.egress.redaction_unavailable",
Self::LicenceAcceptanceRequired { .. } => "vision.model.licence_acceptance_required",
Self::LicenceNotAllowed { .. } => "vision.model.licence_not_allowed",
Self::DigestMismatch { .. } => "vision.model.digest_mismatch",
Self::SizeMismatch { .. } => "vision.model.size_mismatch",
Self::Offline { .. } => "vision.model.offline",
Self::Fetch { .. } => "vision.model.fetch",
Self::Manifest { .. } => "vision.model.manifest",
Self::RateLimited { .. } => "vision.rate_limited",
Self::Timeout { .. } => "vision.timeout",
Self::Cancelled => "vision.cancelled",
Self::Unavailable { .. } => "vision.unavailable",
Self::Unsupported(_) => "vision.unsupported",
Self::InvalidInput(_) => "vision.invalid_input",
Self::BackendNotFound(_) => "vision.backend_not_found",
Self::Parse { .. } => "vision.parse",
Self::Backend { .. } => "vision.backend",
Self::Io { .. } => "vision.io",
Self::SpaceMismatch { .. } => "vision.memory.space_mismatch",
Self::Core(_) => "vision.core",
}
}
pub fn category(&self) -> ErrorCategory {
match self {
Self::UnsupportedFormat { .. }
| Self::TooManyBytes { .. }
| Self::TooManyPixels { .. }
| Self::Decode(_)
| Self::InputTooLarge { .. }
| Self::Manifest { .. }
| Self::SpaceMismatch { .. }
| Self::InvalidInput(_) => ErrorCategory::InvalidInput,
Self::NotReleased { .. }
| Self::EgressRefused { .. }
| Self::EgressHeld { .. }
| Self::RedactionUnavailable { .. }
| Self::LicenceNotAllowed { .. }
| Self::DigestMismatch { .. }
| Self::SizeMismatch { .. } => ErrorCategory::Forbidden,
Self::LicenceAcceptanceRequired { .. } => ErrorCategory::Unauthorized,
Self::Offline { .. } | Self::BackendNotFound(_) => ErrorCategory::NotFound,
Self::Fetch { .. } | Self::Unavailable { .. } => ErrorCategory::Unavailable,
Self::RateLimited { .. } => ErrorCategory::RateLimited,
Self::Timeout { .. } => ErrorCategory::Timeout,
Self::Cancelled => ErrorCategory::Cancelled,
Self::Unsupported(_) => ErrorCategory::Unsupported,
Self::Parse { .. } | Self::Backend { .. } | Self::Io { .. } => ErrorCategory::Internal,
Self::Core(err) => err.category,
}
}
pub(crate) fn io(
action: &'static str,
path: impl Into<PathBuf>,
source: std::io::Error,
) -> Self {
Self::Io { action, path: path.into(), source }
}
}
impl From<VisionError> for AdkError {
fn from(err: VisionError) -> Self {
let code = err.code();
let category = err.category();
match err {
VisionError::Core(inner) => inner,
VisionError::RateLimited { ref backend, retry_after } => {
let mut retry = RetryHint::for_category(category);
if let Some(after) = retry_after {
retry = retry.with_retry_after(after);
}
let provider = backend.clone();
AdkError::new(ErrorComponent::Tool, category, code, err.to_string())
.with_retry(retry)
.with_provider(provider)
}
other => AdkError::new(ErrorComponent::Tool, category, code, other.to_string()),
}
}
}
pub type Result<T, E = VisionError> = std::result::Result<T, E>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rate_limits_carry_the_retry_hint() {
let err: AdkError = VisionError::RateLimited {
backend: "sam-3.1".into(),
retry_after: Some(Duration::from_secs(3)),
}
.into();
assert_eq!(err.category, ErrorCategory::RateLimited);
assert_eq!(err.code, "vision.rate_limited");
assert_eq!(err.retry.retry_after(), Some(Duration::from_secs(3)));
assert!(err.retry.should_retry);
}
#[test]
fn licence_gate_names_the_url_and_the_command() {
let err: AdkError = VisionError::LicenceAcceptanceRequired {
model: "sam3-local".into(),
licence_url: "https://example.org/sam-license".into(),
}
.into();
assert_eq!(err.category, ErrorCategory::Unauthorized);
assert!(err.message.contains("licence acceptance required"));
assert!(err.message.contains("https://example.org/sam-license"));
assert!(err.message.contains("adk-rust vision models accept sam3-local"));
}
#[test]
fn unreleased_images_are_forbidden() {
let err: AdkError = VisionError::NotReleased { backend: "gemini".into() }.into();
assert_eq!(err.category, ErrorCategory::Forbidden);
}
#[test]
fn platform_errors_pass_through_unchanged() {
let inner = AdkError::new(
ErrorComponent::Model,
ErrorCategory::ResourceExhausted,
"budget.exceeded",
"over budget",
);
let err: AdkError = VisionError::Core(inner).into();
assert_eq!(err.code, "budget.exceeded");
assert_eq!(err.category, ErrorCategory::ResourceExhausted);
}
}