//! Tool-free, non-streaming JSON requests to the local Ollama `/api/chat` (scene summaries, //! initiative, computer vision and planning). Loopback only, redirects refused, sizes bounded, //! provider error bodies never reflected. use std::time::Duration; use serde_json::{json, Value}; use tokio_util::sync::CancellationToken; #[derive(Debug)] pub enum ModelError { /// The model cannot read images (typed `model_images_unsupported`). ImagesUnsupported, /// Non-2xx status; `body` holds at most 4 KiB, for the planner JSON-mode fallback only. Http { status: u16, body: String }, Truncated, Invalid(&'static str), Timeout, Cancelled, Network, } impl std::fmt::Display for ModelError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::ImagesUnsupported => f.write_str(MODEL_IMAGES_UNSUPPORTED), Self::Http { status, .. } => write!(f, "Local model HTTP {status}"), Self::Truncated => f.write_str("The model reached its output limit"), Self::Invalid(m) => f.write_str(m), Self::Timeout => f.write_str("The local model took too long"), Self::Cancelled => f.write_str("Cancelled"), Self::Network => f.write_str("The local model is unreachable"), } } } impl std::error::Error for ModelError {} pub const MODEL_IMAGES_UNSUPPORTED: &str = "The active model cannot read images or video frames."; pub const SCREEN_VISION_REQUIRED: &str = "Enable vision for a compatible API model before sharing images."; /// The local model as configured by the app. `options` holds `num_ctx`, `num_gpu`, `num_thread`... #[derive(Clone, Debug)] pub struct LocalModel { pub url: String, pub model: String, /// `None` = unknown (Capri then sends `think:false` and assumes vision). pub capabilities: Option>, pub options: Value, client: reqwest::Client, } impl LocalModel { pub fn new(url: &str, model: &str, capabilities: Option>, options: Value) -> anyhow::Result { let parsed = url::Url::parse(url)?; anyhow::ensure!( parsed.scheme() == "http" && parsed.host_str() == Some("127.0.0.1") && parsed.username().is_empty() && parsed.password().is_none(), "Inference must remain local" ); let client = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()).build()?; Ok(Self { url: url.trim_end_matches('/').into(), model: model.into(), capabilities, options, client }) } fn has(&self, capability: &str) -> bool { self.capabilities.as_ref().is_none_or(|c| c.iter().any(|x| x == capability)) } /// `screenVisionAvailable`: unknown capabilities or `vision`. pub fn vision_available(&self) -> bool { self.has("vision") } /// Completes `body` (messages, format, `options.num_predict`) with Capri's runner policy and sends it. /// Returns the response packet after the common checks; the caller parses `message.content`. pub async fn chat(&self, body: Value, max_bytes: usize, timeout: Duration, cancel: &CancellationToken) -> Result { let request = self.body(body); let send = async { let response = self.client.post(format!("{}/api/chat", self.url)).json(&request).send().await.map_err(|_| ModelError::Network)?; let status = response.status().as_u16(); let bytes = response.bytes().await.map_err(|_| ModelError::Network)?; if !(200..300).contains(&status) { return Err(http_error(status, &bytes)); } if bytes.len() > max_bytes { return Err(ModelError::Invalid("The model response exceeded its limit")); } check_packet(serde_json::from_slice(&bytes).map_err(|_| ModelError::Invalid("Invalid model response"))?) }; tokio::select! { _ = cancel.cancelled() => Err(ModelError::Cancelled), r = tokio::time::timeout(timeout, send) => r.unwrap_or(Err(ModelError::Timeout)), } } /// Request body with `model`, `stream:false`, `keep_alive:-1`, `truncate/shift:false`, `tools:[]`, /// `think:false` (unless the model is known to lack thinking) and the base options. pub fn body(&self, mut body: Value) -> Value { let mut options = self.options.clone(); if let (Some(base), Some(extra)) = (options.as_object_mut(), body.get("options").and_then(Value::as_object)) { base.extend(extra.clone()); } let map = body.as_object_mut().expect("request body is an object"); map.insert("model".into(), json!(self.model)); map.insert("stream".into(), json!(false)); map.insert("truncate".into(), json!(false)); map.insert("shift".into(), json!(false)); map.insert("keep_alive".into(), json!(-1)); map.entry("tools").or_insert(json!([])); map.insert("options".into(), options); if self.has("thinking") { map.insert("think".into(), json!(false)); } body } } fn http_error(status: u16, bytes: &[u8]) -> ModelError { let head = &bytes[..bytes.len().min(8192)]; let unsupported = bytes.len() <= 8192 && serde_json::from_slice::(head).ok().and_then(|v| v.pointer("/error/code").and_then(Value::as_str).map(|c| c == "model_images_unsupported")) == Some(true); if unsupported { return ModelError::ImagesUnsupported; } let body = if bytes.len() <= 4096 { String::from_utf8_lossy(bytes).into_owned() } else { String::new() }; ModelError::Http { status, body } } /// `done:true`, not truncated, no tool calls. pub fn check_packet(packet: Value) -> Result { if packet.pointer("/message/tool_calls").and_then(Value::as_array).is_some_and(|a| !a.is_empty()) { return Err(ModelError::Invalid("Action output is not permitted")); } if packet.get("done_reason").and_then(Value::as_str) == Some("length") { return Err(ModelError::Truncated); } if packet.get("done") != Some(&json!(true)) { return Err(ModelError::Invalid("Incomplete model response")); } Ok(packet) } /// Parses `message.content` as JSON, accepting one surrounding ```json fence. pub fn content_json(packet: &Value) -> Result { let content = packet.pointer("/message/content").and_then(Value::as_str).ok_or(ModelError::Invalid("No structured output"))?; let trimmed = content.trim(); let inner = trimmed .strip_prefix("```json") .or_else(|| trimmed.strip_prefix("```")) .and_then(|s| s.strip_suffix("```")) .unwrap_or(trimmed); serde_json::from_str(inner.trim()).map_err(|_| ModelError::Invalid("Invalid structured output")) } #[cfg(test)] mod tests { use super::*; use wiremock::matchers::{body_partial_json, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; #[test] fn loopback_only_and_policy() { assert!(LocalModel::new("http://localhost:1", "m", None, json!({})).is_err()); assert!(LocalModel::new("https://127.0.0.1:1", "m", None, json!({})).is_err()); let m = LocalModel::new("http://127.0.0.1:1", "m", Some(vec!["completion".into()]), json!({"num_ctx": 8})).unwrap(); let body = m.body(json!({"messages": [], "options": {"num_predict": 5}})); assert_eq!(body["options"], json!({"num_ctx": 8, "num_predict": 5})); assert!(body.get("think").is_none(), "no think flag for models known to lack thinking"); assert_eq!(body["tools"], json!([])); assert!(!m.vision_available()); } #[test] fn packets_and_fences() { assert!(matches!(check_packet(json!({"done": true, "done_reason": "length"})), Err(ModelError::Truncated))); assert!(check_packet(json!({"done": true, "message": {"tool_calls": [{}]}})).is_err()); let p = json!({"done": true, "message": {"content": "```json\n{\"a\":1}\n```"}}); assert_eq!(content_json(&p).unwrap(), json!({"a": 1})); } #[tokio::test] async fn typed_unsupported_images() { let server = MockServer::start().await; Mock::given(method("POST")) .and(path("/api/chat")) .and(body_partial_json(json!({"stream": false, "keep_alive": -1}))) .respond_with(ResponseTemplate::new(400).set_body_json(json!({"error": {"code": "model_images_unsupported", "message": "secret provider text"}}))) .mount(&server) .await; let m = LocalModel::new(&server.uri(), "m", None, json!({})).unwrap(); let r = m.chat(json!({"messages": []}), 32768, Duration::from_secs(5), &CancellationToken::new()).await; assert!(matches!(r, Err(ModelError::ImagesUnsupported))); } }