use crate::config::{Config, NamedRoute, ProviderConfig, VisionMode};
use crate::provider::ProviderProfile;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Describe {
pub route: String,
pub profile: String,
pub sees: bool,
pub local: bool,
}
impl Describe {
pub fn of(route: &NamedRoute, profiles: &[ProviderProfile]) -> Self {
Self {
route: route.name.clone(),
profile: route
.config
.profile
.as_deref()
.unwrap_or("openai")
.to_string(),
sees: route_sees(&route.config, profiles),
local: is_local_url(&route.config.base_url),
}
}
pub fn resolve(cfg: &Config, profiles: &[ProviderProfile]) -> Option<Self> {
let name = cfg.vision.route.trim();
if name.is_empty() {
return None;
}
let route = resolve_route(cfg, name)?;
Some(Self::of(&route, profiles))
}
}
fn resolve_route(cfg: &Config, name: &str) -> Option<NamedRoute> {
cfg.declared_routes().into_iter().find(|r| r.name == name)
}
pub fn route_sees(config: &ProviderConfig, profiles: &[ProviderProfile]) -> bool {
if let Some(vision) = config.vision {
return vision;
}
ProviderProfile::resolve(config.profile.as_deref().unwrap_or("openai"), profiles)
.map(|profile| profile.vision == Some(true))
.unwrap_or(false)
}
pub fn is_local_url(url: &str) -> bool {
let Ok(url) = reqwest::Url::parse(url.trim()) else {
return false;
};
url.host_str().map(host_is_local).unwrap_or(false)
}
const DESCRIPTION_CAP: usize = 8_000;
pub fn asked_text(content: Option<&str>) -> String {
let Some(text) = content else {
return String::new();
};
text.lines()
.filter(|line| !is_marker_line(line))
.collect::<Vec<_>>()
.join("\n")
.trim()
.to_string()
}
fn is_marker_line(line: &str) -> bool {
let t = line.trim();
(t.starts_with("--- attached picture:") || t.starts_with("--- end of ")) && t.ends_with("---")
}
pub fn describe_text(raw: &str) -> String {
let redacted = crate::redact::redact(raw.trim(), &[]).text;
if redacted.chars().count() <= DESCRIPTION_CAP {
return redacted;
}
let mut cut: String = redacted.chars().take(DESCRIPTION_CAP).collect();
cut.push('…');
cut
}
fn host_is_local(host: &str) -> bool {
let host = host.trim_end_matches('.').to_ascii_lowercase();
let bare = host.trim_start_matches('[').trim_end_matches(']');
if let Ok(ip) = bare.parse::<std::net::IpAddr>() {
return crate::netguard::blocked_reason(ip).is_some();
}
host == "localhost"
|| !host.contains('.')
|| host.ends_with(".local")
|| host.ends_with(".lan")
|| host.ends_with(".home.arpa")
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Plan {
Native,
Describe { route: String },
Refuse { sentence: String },
}
impl Plan {
pub fn refusal(&self) -> Option<&str> {
match self {
Plan::Refuse { sentence } => Some(sentence),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct Choice<'a> {
pub mode: VisionMode,
pub model: &'a str,
pub route: &'a str,
pub profile: &'a str,
pub pictures: usize,
pub turn_sees: bool,
pub describe: Option<Describe>,
pub allow_cloud: bool,
}
impl Choice<'_> {
pub fn plan(&self) -> Plan {
if self.pictures == 0 {
return Plan::Native;
}
match self.mode {
VisionMode::Native => {
if self.turn_sees {
Plan::Native
} else {
Plan::Refuse {
sentence: no_native(self.model),
}
}
}
VisionMode::Auto if self.turn_sees => Plan::Native,
VisionMode::Text | VisionMode::Auto => {
let Some(describe) = &self.describe else {
return Plan::Refuse {
sentence: no_route(self.mode, self.model, self.route, self.profile),
};
};
if !describe.sees {
return Plan::Refuse {
sentence: route_blind(self.mode, describe),
};
}
if !describe.local && !self.allow_cloud {
return Plan::Refuse {
sentence: cloud(&describe.route),
};
}
Plan::Describe {
route: describe.route.clone(),
}
}
}
}
}
pub fn no_native(model: &str) -> String {
format!(
"{model} cannot see images — `/model` to one that can, or set `[vision] mode = \"text\"` \
and name a route that describes pictures in `[vision] route`"
)
}
fn no_route(mode: VisionMode, model: &str, route: &str, profile: &str) -> String {
match mode {
VisionMode::Auto => format!(
"{model} (route `{route}`, profile `{profile}`) does not declare vision and no \
`[vision] route` is set to describe the picture instead — add `vision = true` under \
route `{route}` if it can see, or configure `[vision] route` to a route with \
`vision = true`"
),
_ => format!(
"`[vision] mode = \"text\"` needs a describe route: configure `[vision] route` to a \
route that declares `vision = true` (current route `{route}` uses profile \
`{profile}`)"
),
}
}
fn route_blind(mode: VisionMode, describe: &Describe) -> String {
let route = &describe.route;
let profile = &describe.profile;
let why = if mode == VisionMode::Auto {
"and `auto` fell back to it because the turn's model does not declare vision "
} else {
""
};
format!(
"`[vision] route = \"{route}\"` {why}(profile `{profile}`) does not declare vision — \
add `vision = true` under route `{route}` (or in profile `{profile}`) if it can see"
)
}
pub fn cloud(route: &str) -> String {
format!(
"`[vision] route = \"{route}\"` is not on this machine, and describing a picture there \
would send it off it — set `[vision] allow_cloud = true` if that is what you want"
)
}
pub fn describe_request(
asked: &str,
images: &[crate::message::ImagePart],
) -> Vec<crate::message::Message> {
let system = crate::message::Message::system(
"You describe images for another model that cannot see them. Say what is in the picture \
and answer what is asked about it. Quote text in the picture verbatim, in the language it \
is written in. Do not guess: if the picture does not show something, say that it does not. \
Keep it under 250 words unless the question needs more.",
);
let question = if asked.trim().is_empty() {
"Describe this picture in enough detail for someone who cannot see it."
} else {
asked.trim()
};
let mut user = crate::message::Message::user(question);
for image in images {
user = user.with_image(image.clone());
}
vec![system, user]
}
pub fn described_block(route: &str, asked: &str, lines: &[String]) -> String {
let head = if asked.trim().is_empty() {
String::new()
} else {
format!("{}\n\n", asked.trim())
};
let (what, it) = if lines.len() == 1 {
("The attached picture was", "it")
} else {
("The attached pictures were", "them")
};
format!(
"{head}[{what} described by `{route}`, which can see {it}. You cannot see {it} yourself — \
this is a description, not the picture.]\n\n{}",
lines.join("\n\n")
)
}
pub fn refuses_images(failure: &crate::error::ProviderFailure) -> bool {
use crate::error::ProviderFailure;
let body = match failure {
ProviderFailure::InvalidRequest(http) => http.body.to_ascii_lowercase(),
ProviderFailure::Routed { cause, .. } => return refuses_images(cause),
_ => return false,
};
body.contains("image_url")
|| body.contains("image url")
|| body.contains("image content")
|| body.contains("multimodal")
|| (body.contains("image") && body.contains("support"))
}
#[cfg(test)]
mod tests {
use super::*;
fn describe(sees: bool, local: bool) -> Option<Describe> {
Some(Describe {
route: "sight".into(),
profile: "llamacpp".into(),
sees,
local,
})
}
fn choice(mode: VisionMode, turn_sees: bool, describe: Option<Describe>) -> Choice<'static> {
Choice {
mode,
model: "stub-stream",
route: "default",
profile: "llamacpp",
pictures: 1,
turn_sees,
describe,
allow_cloud: false,
}
}
#[test]
fn native_sends_the_picture_to_a_model_that_declares_vision() {
let plan = choice(VisionMode::Native, true, None).plan();
assert_eq!(plan, Plan::Native);
}
#[test]
fn native_refuses_before_the_turn_when_the_model_cannot_see() {
let plan = choice(VisionMode::Native, false, describe(true, true)).plan();
let sentence = plan.refusal().expect("a refusal");
assert!(
sentence.starts_with("stub-stream cannot see images"),
"{sentence}"
);
assert!(sentence.contains("mode = \"text\""), "{sentence}");
}
#[test]
fn text_never_uses_the_turn_model_even_when_it_could_see() {
let plan = choice(VisionMode::Text, true, describe(true, true)).plan();
assert_eq!(
plan,
Plan::Describe {
route: "sight".into()
}
);
}
#[test]
fn auto_is_native_when_the_turn_model_declares_vision_and_says_nothing_about_the_route() {
let plan = choice(VisionMode::Auto, true, None).plan();
assert_eq!(plan, Plan::Native);
}
#[test]
fn auto_falls_back_to_the_description() {
let plan = choice(VisionMode::Auto, false, describe(true, true)).plan();
assert_eq!(
plan,
Plan::Describe {
route: "sight".into()
}
);
}
#[test]
fn a_mode_that_needs_a_route_says_which_key_is_missing() {
let sentence = choice(VisionMode::Text, false, None)
.plan()
.refusal()
.expect("a refusal")
.to_string();
assert!(sentence.contains("[vision] route"), "{sentence}");
let auto = choice(VisionMode::Auto, false, None)
.plan()
.refusal()
.expect("a refusal")
.to_string();
assert!(auto.contains("does not declare vision"), "{auto}");
assert!(auto.contains("[vision] route"), "{auto}");
}
#[test]
fn a_describe_route_that_cannot_see_is_refused_by_name() {
let sentence = choice(VisionMode::Text, false, describe(false, true))
.plan()
.refusal()
.expect("a refusal")
.to_string();
assert!(sentence.contains("vision = true"), "{sentence}");
assert!(sentence.contains("sight"), "{sentence}");
}
#[test]
fn a_route_off_this_machine_is_refused_until_allow_cloud() {
let plan = choice(VisionMode::Text, false, describe(true, false)).plan();
let sentence = plan.refusal().expect("a refusal").to_string();
assert!(sentence.contains("allow_cloud = true"), "{sentence}");
let mut allowing = choice(VisionMode::Text, false, describe(true, false));
allowing.allow_cloud = true;
assert_eq!(
allowing.plan(),
Plan::Describe {
route: "sight".into()
}
);
}
#[test]
fn no_pictures_means_no_decision_and_no_refusal() {
for mode in [VisionMode::Native, VisionMode::Text, VisionMode::Auto] {
let mut c = choice(mode, false, None);
c.pictures = 0;
assert_eq!(c.plan(), Plan::Native, "{mode:?}");
}
}
#[test]
fn a_describes_locality_is_read_from_its_own_url() {
let profiles: Vec<ProviderProfile> = Vec::new();
let route = |base: &str| NamedRoute {
name: "sight".into(),
max_parallel: None,
group: None,
config: ProviderConfig {
base_url: base.into(),
model: "m".into(),
..Default::default()
},
};
assert!(Describe::of(&route("http://127.0.0.1:18011/v1"), &profiles).local);
assert!(!Describe::of(&route("https://api.openai.com/v1"), &profiles).local);
}
#[test]
fn local_means_this_machine_or_the_lan_and_nothing_else() {
for local in [
"http://127.0.0.1:18045/v1",
"http://localhost:18011/v1",
"http://[::1]:8080/v1",
"http://192.168.1.120:8080/v1",
"http://172.17.0.1:8899/",
"http://mmnuc:8080/v1",
"http://eclipse.local:8080/v1",
"http://box.lan/v1",
] {
assert!(is_local_url(local), "{local} is local");
}
for remote in [
"https://api.openai.com/v1",
"https://ollama.com/v1",
"https://openrouter.ai/api/v1",
"not a url",
"",
] {
assert!(!is_local_url(remote), "{remote} is not local");
}
}
#[test]
fn a_message_made_only_of_markers_has_no_words() {
assert_eq!(
asked_text(Some("--- attached picture: shot.png (image/png) ---")),
""
);
assert_eq!(asked_text(None), "");
assert_eq!(asked_text(Some(" \n ")), "");
assert_eq!(
asked_text(Some(
"what is this?\n--- attached picture: a.png (image/png) ---\nand this one"
)),
"what is this?\nand this one"
);
assert_eq!(
asked_text(Some("--- attached picture: a.png (image/png)")),
"--- attached picture: a.png (image/png)"
);
}
#[test]
fn a_description_is_capped_and_redacted() {
let long = "x".repeat(DESCRIPTION_CAP + 500);
let kept = describe_text(&long);
assert_eq!(
kept.chars().count(),
DESCRIPTION_CAP + 1,
"the cut is marked"
);
assert!(kept.ends_with('…'));
let leaked = describe_text(
"the screen shows api_key = sk-live-4f9d8e7c6b5a39281706f5e4d3c2b1a0 and a chart",
);
assert!(
!leaked.contains("sk-live-4f9d8e7c6b5a39281706f5e4d3c2b1a0"),
"the description was stored unredacted: {leaked}"
);
assert!(leaked.contains("and a chart"), "{leaked}");
}
#[test]
fn route_sees_gives_route_vision_precedence_over_the_profile() {
let mut seeing_profile = ProviderProfile::builtin("llamacpp").unwrap();
seeing_profile.name = "seeing".into();
seeing_profile.vision = Some(true);
let mut blind_profile = ProviderProfile::builtin("llamacpp").unwrap();
blind_profile.name = "blind".into();
blind_profile.vision = Some(false);
let profiles = [seeing_profile, blind_profile];
let mut cfg = ProviderConfig {
base_url: "http://127.0.0.1:18011/v1".into(),
model: "m".into(),
profile: Some("llamacpp".into()),
..Default::default()
};
assert!(!route_sees(&cfg, &profiles));
cfg.profile = Some("seeing".into());
assert!(route_sees(&cfg, &profiles));
cfg.profile = Some("llamacpp".into());
cfg.vision = Some(true);
assert!(route_sees(&cfg, &profiles));
cfg.profile = Some("blind".into());
assert!(route_sees(&cfg, &profiles));
cfg.profile = Some("seeing".into());
cfg.vision = Some(false);
assert!(!route_sees(&cfg, &profiles));
}
#[test]
fn refusals_name_the_route_profile_and_key_instead_of_set_one() {
let auto_no_route = choice(VisionMode::Auto, false, None)
.plan()
.refusal()
.expect("a refusal")
.to_string();
assert!(auto_no_route.contains("default"), "{auto_no_route}");
assert!(auto_no_route.contains("llamacpp"), "{auto_no_route}");
assert!(auto_no_route.contains("vision = true"), "{auto_no_route}");
assert!(!auto_no_route.contains("set one"), "{auto_no_route}");
let text_no_route = choice(VisionMode::Text, false, None)
.plan()
.refusal()
.expect("a refusal")
.to_string();
assert!(text_no_route.contains("default"), "{text_no_route}");
assert!(text_no_route.contains("llamacpp"), "{text_no_route}");
assert!(text_no_route.contains("vision = true"), "{text_no_route}");
assert!(!text_no_route.contains("set one"), "{text_no_route}");
for mode in [VisionMode::Auto, VisionMode::Text] {
let blind = choice(mode, false, describe(false, true))
.plan()
.refusal()
.expect("a refusal")
.to_string();
assert!(blind.contains("sight"), "{blind}");
assert!(blind.contains("llamacpp"), "{blind}");
assert!(blind.contains("vision = true"), "{blind}");
assert!(!blind.contains("set one"), "{blind}");
}
}
}