1use crate::config::{Config, NamedRoute, ProviderConfig, VisionMode};
25use crate::provider::ProviderProfile;
26
27#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct Describe {
30 pub route: String,
32 pub profile: String,
34 pub sees: bool,
36 pub local: bool,
38}
39
40impl Describe {
41 pub fn of(route: &NamedRoute, profiles: &[ProviderProfile]) -> Self {
47 Self {
48 route: route.name.clone(),
49 profile: route
50 .config
51 .profile
52 .as_deref()
53 .unwrap_or("openai")
54 .to_string(),
55 sees: route_sees(&route.config, profiles),
56 local: is_local_url(&route.config.base_url),
57 }
58 }
59
60 pub fn resolve(cfg: &Config, profiles: &[ProviderProfile]) -> Option<Self> {
67 let name = cfg.vision.route.trim();
68 if name.is_empty() {
69 return None;
70 }
71 let route = resolve_route(cfg, name)?;
72 Some(Self::of(&route, profiles))
73 }
74}
75
76fn resolve_route(cfg: &Config, name: &str) -> Option<NamedRoute> {
81 cfg.declared_routes().into_iter().find(|r| r.name == name)
82}
83
84pub fn route_sees(config: &ProviderConfig, profiles: &[ProviderProfile]) -> bool {
94 if let Some(vision) = config.vision {
95 return vision;
96 }
97 ProviderProfile::resolve(config.profile.as_deref().unwrap_or("openai"), profiles)
98 .map(|profile| profile.vision == Some(true))
99 .unwrap_or(false)
100}
101
102pub fn is_local_url(url: &str) -> bool {
109 let Ok(url) = reqwest::Url::parse(url.trim()) else {
110 return false;
111 };
112 url.host_str().map(host_is_local).unwrap_or(false)
113}
114
115const DESCRIPTION_CAP: usize = 8_000;
119
120pub fn asked_text(content: Option<&str>) -> String {
127 let Some(text) = content else {
128 return String::new();
129 };
130 text.lines()
131 .filter(|line| !is_marker_line(line))
132 .collect::<Vec<_>>()
133 .join("\n")
134 .trim()
135 .to_string()
136}
137
138fn is_marker_line(line: &str) -> bool {
139 let t = line.trim();
140 (t.starts_with("--- attached picture:") || t.starts_with("--- end of ")) && t.ends_with("---")
141}
142
143pub fn describe_text(raw: &str) -> String {
149 let redacted = crate::redact::redact(raw.trim(), &[]).text;
150 if redacted.chars().count() <= DESCRIPTION_CAP {
151 return redacted;
152 }
153 let mut cut: String = redacted.chars().take(DESCRIPTION_CAP).collect();
154 cut.push('…');
155 cut
156}
157
158fn host_is_local(host: &str) -> bool {
159 let host = host.trim_end_matches('.').to_ascii_lowercase();
160 let bare = host.trim_start_matches('[').trim_end_matches(']');
161 if let Ok(ip) = bare.parse::<std::net::IpAddr>() {
162 return crate::netguard::blocked_reason(ip).is_some();
163 }
164 host == "localhost"
165 || !host.contains('.')
166 || host.ends_with(".local")
167 || host.ends_with(".lan")
168 || host.ends_with(".home.arpa")
169}
170
171#[derive(Debug, Clone, PartialEq, Eq)]
173pub enum Plan {
174 Native,
176 Describe { route: String },
178 Refuse { sentence: String },
180}
181
182impl Plan {
183 pub fn refusal(&self) -> Option<&str> {
184 match self {
185 Plan::Refuse { sentence } => Some(sentence),
186 _ => None,
187 }
188 }
189}
190
191#[derive(Debug, Clone)]
193pub struct Choice<'a> {
194 pub mode: VisionMode,
195 pub model: &'a str,
197 pub route: &'a str,
199 pub profile: &'a str,
201 pub pictures: usize,
203 pub turn_sees: bool,
205 pub describe: Option<Describe>,
207 pub allow_cloud: bool,
209}
210
211impl Choice<'_> {
212 pub fn plan(&self) -> Plan {
213 if self.pictures == 0 {
214 return Plan::Native;
215 }
216 match self.mode {
217 VisionMode::Native => {
218 if self.turn_sees {
219 Plan::Native
220 } else {
221 Plan::Refuse {
222 sentence: no_native(self.model),
223 }
224 }
225 }
226 VisionMode::Auto if self.turn_sees => Plan::Native,
227 VisionMode::Text | VisionMode::Auto => {
228 let Some(describe) = &self.describe else {
229 return Plan::Refuse {
230 sentence: no_route(self.mode, self.model, self.route, self.profile),
231 };
232 };
233 if !describe.sees {
234 return Plan::Refuse {
235 sentence: route_blind(self.mode, describe),
236 };
237 }
238 if !describe.local && !self.allow_cloud {
239 return Plan::Refuse {
240 sentence: cloud(&describe.route),
241 };
242 }
243 Plan::Describe {
244 route: describe.route.clone(),
245 }
246 }
247 }
248 }
249}
250
251pub fn no_native(model: &str) -> String {
254 format!(
255 "{model} cannot see images — `/model` to one that can, or set `[vision] mode = \"text\"` \
256 and name a route that describes pictures in `[vision] route`"
257 )
258}
259
260fn no_route(mode: VisionMode, model: &str, route: &str, profile: &str) -> String {
261 match mode {
262 VisionMode::Auto => format!(
263 "{model} (route `{route}`, profile `{profile}`) does not declare vision and no \
264 `[vision] route` is set to describe the picture instead — add `vision = true` under \
265 route `{route}` if it can see, or configure `[vision] route` to a route with \
266 `vision = true`"
267 ),
268 _ => format!(
269 "`[vision] mode = \"text\"` needs a describe route: configure `[vision] route` to a \
270 route that declares `vision = true` (current route `{route}` uses profile \
271 `{profile}`)"
272 ),
273 }
274}
275
276fn route_blind(mode: VisionMode, describe: &Describe) -> String {
277 let route = &describe.route;
278 let profile = &describe.profile;
279 let why = if mode == VisionMode::Auto {
280 "and `auto` fell back to it because the turn's model does not declare vision "
281 } else {
282 ""
283 };
284 format!(
285 "`[vision] route = \"{route}\"` {why}(profile `{profile}`) does not declare vision — \
286 add `vision = true` under route `{route}` (or in profile `{profile}`) if it can see"
287 )
288}
289
290pub fn cloud(route: &str) -> String {
293 format!(
294 "`[vision] route = \"{route}\"` is not on this machine, and describing a picture there \
295 would send it off it — set `[vision] allow_cloud = true` if that is what you want"
296 )
297}
298
299pub fn describe_request(
305 asked: &str,
306 images: &[crate::message::ImagePart],
307) -> Vec<crate::message::Message> {
308 let system = crate::message::Message::system(
309 "You describe images for another model that cannot see them. Say what is in the picture \
310 and answer what is asked about it. Quote text in the picture verbatim, in the language it \
311 is written in. Do not guess: if the picture does not show something, say that it does not. \
312 Keep it under 250 words unless the question needs more.",
313 );
314 let question = if asked.trim().is_empty() {
315 "Describe this picture in enough detail for someone who cannot see it."
316 } else {
317 asked.trim()
318 };
319 let mut user = crate::message::Message::user(question);
320 for image in images {
321 user = user.with_image(image.clone());
322 }
323 vec![system, user]
324}
325
326pub fn described_block(route: &str, asked: &str, lines: &[String]) -> String {
329 let head = if asked.trim().is_empty() {
330 String::new()
331 } else {
332 format!("{}\n\n", asked.trim())
333 };
334 let (what, it) = if lines.len() == 1 {
335 ("The attached picture was", "it")
336 } else {
337 ("The attached pictures were", "them")
338 };
339 format!(
340 "{head}[{what} described by `{route}`, which can see {it}. You cannot see {it} yourself — \
341 this is a description, not the picture.]\n\n{}",
342 lines.join("\n\n")
343 )
344}
345
346pub fn refuses_images(failure: &crate::error::ProviderFailure) -> bool {
352 use crate::error::ProviderFailure;
353 let body = match failure {
354 ProviderFailure::InvalidRequest(http) => http.body.to_ascii_lowercase(),
355 ProviderFailure::Routed { cause, .. } => return refuses_images(cause),
356 _ => return false,
357 };
358 body.contains("image_url")
359 || body.contains("image url")
360 || body.contains("image content")
361 || body.contains("multimodal")
362 || (body.contains("image") && body.contains("support"))
364}
365
366#[cfg(test)]
367mod tests {
368 use super::*;
369
370 fn describe(sees: bool, local: bool) -> Option<Describe> {
371 Some(Describe {
372 route: "sight".into(),
373 profile: "llamacpp".into(),
374 sees,
375 local,
376 })
377 }
378
379 fn choice(mode: VisionMode, turn_sees: bool, describe: Option<Describe>) -> Choice<'static> {
380 Choice {
381 mode,
382 model: "stub-stream",
383 route: "default",
384 profile: "llamacpp",
385 pictures: 1,
386 turn_sees,
387 describe,
388 allow_cloud: false,
389 }
390 }
391
392 #[test]
393 fn native_sends_the_picture_to_a_model_that_declares_vision() {
394 let plan = choice(VisionMode::Native, true, None).plan();
395 assert_eq!(plan, Plan::Native);
396 }
397
398 #[test]
399 fn native_refuses_before_the_turn_when_the_model_cannot_see() {
400 let plan = choice(VisionMode::Native, false, describe(true, true)).plan();
401 let sentence = plan.refusal().expect("a refusal");
402 assert!(
403 sentence.starts_with("stub-stream cannot see images"),
404 "{sentence}"
405 );
406 assert!(sentence.contains("mode = \"text\""), "{sentence}");
407 }
408
409 #[test]
410 fn text_never_uses_the_turn_model_even_when_it_could_see() {
411 let plan = choice(VisionMode::Text, true, describe(true, true)).plan();
413 assert_eq!(
414 plan,
415 Plan::Describe {
416 route: "sight".into()
417 }
418 );
419 }
420
421 #[test]
422 fn auto_is_native_when_the_turn_model_declares_vision_and_says_nothing_about_the_route() {
423 let plan = choice(VisionMode::Auto, true, None).plan();
425 assert_eq!(plan, Plan::Native);
426 }
427
428 #[test]
429 fn auto_falls_back_to_the_description() {
430 let plan = choice(VisionMode::Auto, false, describe(true, true)).plan();
431 assert_eq!(
432 plan,
433 Plan::Describe {
434 route: "sight".into()
435 }
436 );
437 }
438
439 #[test]
440 fn a_mode_that_needs_a_route_says_which_key_is_missing() {
441 let sentence = choice(VisionMode::Text, false, None)
442 .plan()
443 .refusal()
444 .expect("a refusal")
445 .to_string();
446 assert!(sentence.contains("[vision] route"), "{sentence}");
447 let auto = choice(VisionMode::Auto, false, None)
448 .plan()
449 .refusal()
450 .expect("a refusal")
451 .to_string();
452 assert!(auto.contains("does not declare vision"), "{auto}");
454 assert!(auto.contains("[vision] route"), "{auto}");
455 }
456
457 #[test]
458 fn a_describe_route_that_cannot_see_is_refused_by_name() {
459 let sentence = choice(VisionMode::Text, false, describe(false, true))
460 .plan()
461 .refusal()
462 .expect("a refusal")
463 .to_string();
464 assert!(sentence.contains("vision = true"), "{sentence}");
465 assert!(sentence.contains("sight"), "{sentence}");
466 }
467
468 #[test]
469 fn a_route_off_this_machine_is_refused_until_allow_cloud() {
470 let plan = choice(VisionMode::Text, false, describe(true, false)).plan();
471 let sentence = plan.refusal().expect("a refusal").to_string();
472 assert!(sentence.contains("allow_cloud = true"), "{sentence}");
473
474 let mut allowing = choice(VisionMode::Text, false, describe(true, false));
475 allowing.allow_cloud = true;
476 assert_eq!(
477 allowing.plan(),
478 Plan::Describe {
479 route: "sight".into()
480 }
481 );
482 }
483
484 #[test]
485 fn no_pictures_means_no_decision_and_no_refusal() {
486 for mode in [VisionMode::Native, VisionMode::Text, VisionMode::Auto] {
487 let mut c = choice(mode, false, None);
488 c.pictures = 0;
489 assert_eq!(c.plan(), Plan::Native, "{mode:?}");
490 }
491 }
492
493 #[test]
496 fn a_describes_locality_is_read_from_its_own_url() {
497 let profiles: Vec<ProviderProfile> = Vec::new();
498 let route = |base: &str| NamedRoute {
499 name: "sight".into(),
500 max_parallel: None,
501 group: None,
502 config: ProviderConfig {
503 base_url: base.into(),
504 model: "m".into(),
505 ..Default::default()
506 },
507 };
508 assert!(Describe::of(&route("http://127.0.0.1:18011/v1"), &profiles).local);
509 assert!(!Describe::of(&route("https://api.openai.com/v1"), &profiles).local);
510 }
511
512 #[test]
513 fn local_means_this_machine_or_the_lan_and_nothing_else() {
514 for local in [
515 "http://127.0.0.1:18045/v1",
516 "http://localhost:18011/v1",
517 "http://[::1]:8080/v1",
518 "http://192.168.1.120:8080/v1",
519 "http://172.17.0.1:8899/",
520 "http://mmnuc:8080/v1",
521 "http://eclipse.local:8080/v1",
522 "http://box.lan/v1",
523 ] {
524 assert!(is_local_url(local), "{local} is local");
525 }
526 for remote in [
527 "https://api.openai.com/v1",
528 "https://ollama.com/v1",
529 "https://openrouter.ai/api/v1",
530 "not a url",
531 "",
532 ] {
533 assert!(!is_local_url(remote), "{remote} is not local");
534 }
535 }
536
537 #[test]
539 fn a_message_made_only_of_markers_has_no_words() {
540 assert_eq!(
541 asked_text(Some("--- attached picture: shot.png (image/png) ---")),
542 ""
543 );
544 assert_eq!(asked_text(None), "");
545 assert_eq!(asked_text(Some(" \n ")), "");
546 assert_eq!(
548 asked_text(Some(
549 "what is this?\n--- attached picture: a.png (image/png) ---\nand this one"
550 )),
551 "what is this?\nand this one"
552 );
553 assert_eq!(
555 asked_text(Some("--- attached picture: a.png (image/png)")),
556 "--- attached picture: a.png (image/png)"
557 );
558 }
559
560 #[test]
563 fn a_description_is_capped_and_redacted() {
564 let long = "x".repeat(DESCRIPTION_CAP + 500);
565 let kept = describe_text(&long);
566 assert_eq!(
567 kept.chars().count(),
568 DESCRIPTION_CAP + 1,
569 "the cut is marked"
570 );
571 assert!(kept.ends_with('…'));
572 let leaked = describe_text(
574 "the screen shows api_key = sk-live-4f9d8e7c6b5a39281706f5e4d3c2b1a0 and a chart",
575 );
576 assert!(
577 !leaked.contains("sk-live-4f9d8e7c6b5a39281706f5e4d3c2b1a0"),
578 "the description was stored unredacted: {leaked}"
579 );
580 assert!(leaked.contains("and a chart"), "{leaked}");
581 }
582
583 #[test]
584 fn route_sees_gives_route_vision_precedence_over_the_profile() {
585 let mut seeing_profile = ProviderProfile::builtin("llamacpp").unwrap();
586 seeing_profile.name = "seeing".into();
587 seeing_profile.vision = Some(true);
588
589 let mut blind_profile = ProviderProfile::builtin("llamacpp").unwrap();
590 blind_profile.name = "blind".into();
591 blind_profile.vision = Some(false);
592
593 let profiles = [seeing_profile, blind_profile];
594
595 let mut cfg = ProviderConfig {
597 base_url: "http://127.0.0.1:18011/v1".into(),
598 model: "m".into(),
599 profile: Some("llamacpp".into()),
600 ..Default::default()
601 };
602 assert!(!route_sees(&cfg, &profiles));
603
604 cfg.profile = Some("seeing".into());
605 assert!(route_sees(&cfg, &profiles));
606
607 cfg.profile = Some("llamacpp".into());
609 cfg.vision = Some(true);
610 assert!(route_sees(&cfg, &profiles));
611
612 cfg.profile = Some("blind".into());
613 assert!(route_sees(&cfg, &profiles));
614
615 cfg.profile = Some("seeing".into());
617 cfg.vision = Some(false);
618 assert!(!route_sees(&cfg, &profiles));
619 }
620
621 #[test]
622 fn refusals_name_the_route_profile_and_key_instead_of_set_one() {
623 let auto_no_route = choice(VisionMode::Auto, false, None)
624 .plan()
625 .refusal()
626 .expect("a refusal")
627 .to_string();
628 assert!(auto_no_route.contains("default"), "{auto_no_route}");
629 assert!(auto_no_route.contains("llamacpp"), "{auto_no_route}");
630 assert!(auto_no_route.contains("vision = true"), "{auto_no_route}");
631 assert!(!auto_no_route.contains("set one"), "{auto_no_route}");
632
633 let text_no_route = choice(VisionMode::Text, false, None)
634 .plan()
635 .refusal()
636 .expect("a refusal")
637 .to_string();
638 assert!(text_no_route.contains("default"), "{text_no_route}");
639 assert!(text_no_route.contains("llamacpp"), "{text_no_route}");
640 assert!(text_no_route.contains("vision = true"), "{text_no_route}");
641 assert!(!text_no_route.contains("set one"), "{text_no_route}");
642
643 for mode in [VisionMode::Auto, VisionMode::Text] {
644 let blind = choice(mode, false, describe(false, true))
645 .plan()
646 .refusal()
647 .expect("a refusal")
648 .to_string();
649 assert!(blind.contains("sight"), "{blind}");
650 assert!(blind.contains("llamacpp"), "{blind}");
651 assert!(blind.contains("vision = true"), "{blind}");
652 assert!(!blind.contains("set one"), "{blind}");
653 }
654 }
655}