use std::time::Duration; use futures::StreamExt; use serde::{Deserialize, Serialize}; use serde_json::Value; /// Any single NDJSON line longer than this is rejected. pub const MAX_EVENT: usize = 262_144; #[derive(Debug, thiserror::Error)] pub enum LlmError { #[error("HTTP {status}: {body}")] Http { status: u16, body: String }, #[error("Network error ({code})")] Network { code: &'static str }, #[error("Invalid model stream: {0}")] StreamInvalid(String), #[error("Model reported an error: {0}")] Reported(String), #[error("Model stream ended before completion")] StreamIncomplete, /// External API failure: `message` is Capri's public text; `detail` is the redacted /// provider error message for debug logs only, never shown. #[error("{message}")] Api { code: &'static str, message: String, status: Option, detail: String }, } impl LlmError { /// Closed set of error codes kept from Capri, with `GATEWAY` renamed to `LLM`. pub fn code(&self) -> &'static str { match self { Self::Http { .. } => "CAPRI_LLM_HTTP_ERROR", Self::Network { .. } => "CAPRI_LLM_NETWORK_ERROR", Self::StreamInvalid(_) => "CAPRI_LLM_STREAM_INVALID", Self::Reported(_) => "CAPRI_LLM_REPORTED_ERROR", Self::StreamIncomplete => "CAPRI_LLM_STREAM_INCOMPLETE", Self::Api { code, .. } => code, } } /// Text to show the owner as is (API failures); `None` means the caller picks its local-core text. pub fn public_message(&self) -> Option<&str> { match self { Self::Api { message, .. } => Some(message), _ => None, } } } pub(crate) fn network(e: reqwest::Error) -> LlmError { let code = if e.is_timeout() { "ETIMEDOUT" } else if e.is_connect() { "ECONNREFUSED" } else if e.is_body() || e.is_decode() { "ECONNRESET" } else { "UND_ERR_SOCKET" }; LlmError::Network { code } } #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct ToolCall { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option, pub function: ToolFunction, } #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct ToolFunction { pub name: String, #[serde(default)] pub arguments: Value, } #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct Message { pub role: String, #[serde(default)] pub content: String, /// Private reasoning; never shown and never stored in the session. #[serde(default, skip_serializing_if = "String::is_empty")] pub thinking: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tool_calls: Vec, /// Base64 images for vision models. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub images: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub tool_name: Option, } impl Message { pub fn new(role: &str, content: impl Into) -> Self { Self { role: role.into(), content: content.into(), ..Default::default() } } } #[derive(Clone, Debug, Default, Serialize)] pub struct Options { pub num_ctx: u32, pub temperature: f32, pub repeat_last_n: i32, #[serde(skip_serializing_if = "Option::is_none")] pub num_gpu: Option, #[serde(skip_serializing_if = "Option::is_none")] pub num_thread: Option, #[serde(skip_serializing_if = "Option::is_none")] pub num_predict: Option, } #[derive(Clone, Debug, Serialize)] pub struct ChatRequest { pub model: String, pub messages: Vec, #[serde(skip_serializing_if = "Vec::is_empty")] pub tools: Vec, pub options: Options, pub keep_alive: i64, pub stream: bool, #[serde(skip_serializing_if = "Option::is_none")] pub think: Option, } const MAX_METADATA: usize = 2 << 20; /// `/api/tags` row. #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct ModelEntry { #[serde(default)] pub name: String, #[serde(default)] pub model: String, #[serde(default)] pub size: u64, #[serde(default)] pub digest: String, } /// `/api/ps` row. #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct RunningModel { #[serde(default)] pub name: String, #[serde(default)] pub model: String, #[serde(default)] pub size: u64, #[serde(default)] pub size_vram: u64, #[serde(default)] pub context_length: u64, } #[derive(Debug, Default, Clone)] pub struct ChatDone { pub content: String, pub thinking: String, pub tool_calls: Vec, pub done_reason: Option, pub prompt_eval_count: u64, pub eval_count: u64, } #[derive(Deserialize)] struct Line { #[serde(default)] message: Option, #[serde(default)] done: bool, #[serde(default)] done_reason: Option, #[serde(default)] prompt_eval_count: u64, #[serde(default)] eval_count: u64, #[serde(default)] error: Option, } #[derive(Clone, Debug)] pub struct Ollama { base: String, http: reqwest::Client, } impl Ollama { /// `base` must be a loopback URL such as `http://127.0.0.1:11435`. Redirects are refused. pub fn new(base: impl Into) -> Self { let http = reqwest::Client::builder() .redirect(reqwest::redirect::Policy::none()) .connect_timeout(Duration::from_secs(5)) .build() .expect("HTTP client"); Self { base: base.into().trim_end_matches('/').to_string(), http } } pub fn base(&self) -> &str { &self.base } pub async fn version(&self) -> Result { #[derive(Deserialize)] struct V { version: String, } let v: V = self .http .get(format!("{}/api/version", self.base)) .timeout(Duration::from_secs(2)) .send() .await .map_err(network)? .json() .await .map_err(network)?; Ok(v.version) } /// Returns the model's capabilities (`completion`, `tools`, `thinking`, `vision`...) or `None` if absent. pub async fn show(&self, model: &str) -> Result>, LlmError> { #[derive(Deserialize)] struct Show { #[serde(default)] capabilities: Vec, } let response = self .http .post(format!("{}/api/show", self.base)) .json(&serde_json::json!({ "model": model })) .timeout(Duration::from_secs(15)) .send() .await .map_err(network)?; if response.status() == reqwest::StatusCode::NOT_FOUND { return Ok(None); } let response = check(response).await?; Ok(Some(response.json::().await.map_err(network)?.capabilities)) } /// Loads the model into memory without generating (empty `/api/chat`). pub async fn load(&self, model: &str, keep_alive: i64) -> Result<(), LlmError> { let response = self .http .post(format!("{}/api/chat", self.base)) .json(&serde_json::json!({ "model": model, "messages": [], "keep_alive": keep_alive, "stream": false })) .send() .await .map_err(network)?; check(response).await.map(|_| ()) } /// Streams `/api/chat`; `on_text` receives visible content deltas in order. pub async fn chat(&self, request: &ChatRequest, mut on_text: impl FnMut(&str)) -> Result { let response = self .http .post(format!("{}/api/chat", self.base)) .json(request) .send() .await .map_err(network)?; let response = check(response).await?; let mut done = ChatDone::default(); let mut buffer: Vec = Vec::new(); let mut stream = response.bytes_stream(); let mut finished = false; while let Some(chunk) = stream.next().await { buffer.extend_from_slice(&chunk.map_err(network)?); while let Some(pos) = buffer.iter().position(|&b| b == b'\n') { let line: Vec = buffer.drain(..=pos).collect(); finished |= handle_line(&line[..line.len() - 1], &mut done, &mut on_text)?; } if buffer.len() > MAX_EVENT { return Err(LlmError::StreamInvalid("event too large".into())); } } if !buffer.is_empty() { finished |= handle_line(&buffer, &mut done, &mut on_text)?; } if !finished { return Err(LlmError::StreamIncomplete); } for (n, call) in done.tool_calls.iter_mut().enumerate() { if call.id.as_deref().unwrap_or("").is_empty() { call.id = Some(format!("call_{}", n + 1)); } } Ok(done) } async fn read_json(response: reqwest::Response) -> Result { let bytes = check(response).await?.bytes().await.map_err(network)?; if bytes.len() > MAX_METADATA { return Err(LlmError::StreamInvalid("Service response exceeds limit".into())); } if bytes.iter().all(u8::is_ascii_whitespace) { return Ok(Value::Null); } let value: Value = serde_json::from_slice(&bytes).map_err(|e| LlmError::StreamInvalid(e.to_string()))?; match value["error"].as_str() { Some(error) => Err(LlmError::Reported(error.into())), None => Ok(value), } } async fn post_json(&self, path: &str, body: &Value, timeout: Duration) -> Result { let response = self.http.post(format!("{}{path}", self.base)).json(body).timeout(timeout).send().await.map_err(network)?; Self::read_json(response).await } async fn get_json(&self, path: &str, timeout: Duration) -> Result { let response = self.http.get(format!("{}{path}", self.base)).timeout(timeout).send().await.map_err(network)?; Self::read_json(response).await } /// Installed models (`/api/tags`). pub async fn tags(&self) -> Result, LlmError> { let v = self.get_json("/api/tags", Duration::from_secs(10)).await?; serde_json::from_value(v["models"].clone()).map_err(|e| LlmError::StreamInvalid(e.to_string())) } /// Resident models (`/api/ps`). pub async fn ps(&self) -> Result, LlmError> { let v = self.get_json("/api/ps", Duration::from_secs(3)).await?; serde_json::from_value(v["models"].clone()).map_err(|e| LlmError::StreamInvalid(e.to_string())) } /// Full `/api/show` record (`template_source`, `capabilities`, `model_info`…) or `None` if absent. pub async fn show_info(&self, model: &str) -> Result, LlmError> { match self.post_json("/api/show", &serde_json::json!({ "model": model }), Duration::from_secs(10)).await { Err(LlmError::Http { status: 404, .. }) => Ok(None), other => other.map(Some), } } /// `/api/create` without streaming (`files`/`from`/`parameters`…); `model` is in `body`. pub async fn create(&self, mut body: Value) -> Result<(), LlmError> { body["stream"] = Value::Bool(false); self.post_json("/api/create", &body, Duration::from_secs(120)).await.map(|_| ()) } /// Deletes a model; `false` when it did not exist. pub async fn delete(&self, model: &str) -> Result { let response = self .http .delete(format!("{}/api/delete", self.base)) .json(&serde_json::json!({ "model": model })) .timeout(Duration::from_secs(120)) .send() .await .map_err(network)?; if response.status() == reqwest::StatusCode::NOT_FOUND { return Ok(false); } check(response).await.map(|_| true) } /// Unloads a resident model (`keep_alive: 0`); fails unless Ollama confirms `done`. pub async fn unload(&self, model: &str) -> Result<(), LlmError> { let body = serde_json::json!({ "model": model, "keep_alive": 0, "stream": false }); let v = self.post_json("/api/generate", &body, Duration::from_secs(30)).await?; if v["done"] == true { Ok(()) } else { Err(LlmError::StreamIncomplete) } } /// `/api/embed` on the CPU (`num_gpu: 0`, embeddings never compete for VRAM). pub async fn embed(&self, model: &str, input: &[&str], keep_alive: i64, timeout: Duration) -> Result>, LlmError> { let body = serde_json::json!({ "model": model, "input": input, "truncate": true, "keep_alive": keep_alive, "options": { "num_gpu": 0 } }); let v = self.post_json("/api/embed", &body, timeout).await?; serde_json::from_value(v["embeddings"].clone()).map_err(|e| LlmError::StreamInvalid(e.to_string())) } /// Uploads a local file as blob `sha256:` (streamed, exact length). pub async fn upload_blob(&self, digest: &str, file: &std::path::Path) -> Result<(), LlmError> { let handle = tokio::fs::File::open(file).await.map_err(|e| LlmError::Reported(e.to_string()))?; let len = handle.metadata().await.map_err(|e| LlmError::Reported(e.to_string()))?.len(); let response = self .http .post(format!("{}/api/blobs/{digest}", self.base)) .header(reqwest::header::CONTENT_TYPE, "application/octet-stream") .header(reqwest::header::CONTENT_LENGTH, len) .body(reqwest::Body::wrap_stream(tokio_util::io::ReaderStream::new(handle))) .timeout(Duration::from_secs(3600)) .send() .await .map_err(network)?; check(response).await.map(|_| ()) } /// Non-streamed `/api/chat` with a caller-built body (warm-ups); fails unless `done` is true. pub async fn raw_chat(&self, body: &Value, timeout: Duration) -> Result { let v = self.post_json("/api/chat", body, timeout).await?; if v["done"] == true { Ok(v) } else { Err(LlmError::StreamIncomplete) } } /// Non-streamed structured request: native `format` (schema, or `"json"` when `None`). pub async fn chat_json(&self, request: &ChatRequest, schema: Option<&Value>) -> Result { let mut body = serde_json::to_value(request).map_err(|e| LlmError::StreamInvalid(e.to_string()))?; body["stream"] = Value::Bool(false); body["format"] = schema.cloned().unwrap_or_else(|| Value::String("json".into())); let v = self.post_json("/api/chat", &body, Duration::from_secs(180)).await?; let content = v["message"]["content"].as_str().unwrap_or(""); serde_json::from_str(&crate::openai::plain_json(content)).map_err(|e| LlmError::StreamInvalid(e.to_string())) } /// `/api/pull` with progress callback `(status, completed, total)`. pub async fn pull(&self, model: &str, mut progress: impl FnMut(&str, u64, u64)) -> Result<(), LlmError> { #[derive(Deserialize)] struct P { #[serde(default)] status: String, #[serde(default)] completed: u64, #[serde(default)] total: u64, #[serde(default)] error: Option, } let response = self .http .post(format!("{}/api/pull", self.base)) .json(&serde_json::json!({ "model": model, "stream": true })) .send() .await .map_err(network)?; let mut stream = check(response).await?.bytes_stream(); let mut buffer = Vec::new(); let mut success = false; while let Some(chunk) = stream.next().await { buffer.extend_from_slice(&chunk.map_err(network)?); if buffer.len() > 65_536 && !buffer.contains(&b'\n') { return Err(LlmError::StreamInvalid("Model pull metadata exceeds limit".into())); } while let Some(pos) = buffer.iter().position(|&b| b == b'\n') { let line: Vec = buffer.drain(..=pos).collect(); let p: P = serde_json::from_slice(&line).map_err(|e| LlmError::StreamInvalid(e.to_string()))?; if let Some(error) = p.error { return Err(LlmError::Reported(error)); } success |= p.status == "success"; progress(&p.status, p.completed, p.total); } } if success { Ok(()) } else { Err(LlmError::StreamIncomplete) } } } async fn check(response: reqwest::Response) -> Result { let status = response.status(); if status.is_success() { return Ok(response); } let body: String = response.text().await.unwrap_or_default().chars().take(400).collect(); Err(LlmError::Http { status: status.as_u16(), body }) } /// Returns true when the line is the terminal `done` record. fn handle_line(line: &[u8], done: &mut ChatDone, on_text: &mut impl FnMut(&str)) -> Result { if line.iter().all(u8::is_ascii_whitespace) { return Ok(false); } if line.len() > MAX_EVENT { return Err(LlmError::StreamInvalid("event too large".into())); } let text = std::str::from_utf8(line).map_err(|_| LlmError::StreamInvalid("not UTF-8".into()))?; let parsed: Line = serde_json::from_str(text).map_err(|e| LlmError::StreamInvalid(e.to_string()))?; if let Some(error) = parsed.error { return Err(LlmError::Reported(error)); } if let Some(message) = parsed.message { if !message.content.is_empty() { on_text(&message.content); done.content.push_str(&message.content); } done.thinking.push_str(&message.thinking); done.tool_calls.extend(message.tool_calls); } if parsed.done { done.done_reason = parsed.done_reason; done.prompt_eval_count = parsed.prompt_eval_count; done.eval_count = parsed.eval_count; return Ok(true); } Ok(false) } #[cfg(test)] mod tests { use super::*; use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; fn request() -> ChatRequest { ChatRequest { model: "m".into(), messages: vec![Message::new("user", "hi")], tools: vec![], options: Options::default(), keep_alive: 300, stream: true, think: Some(false), } } #[tokio::test] async fn streams_text_and_tool_calls() { let server = MockServer::start().await; let body = concat!( r#"{"message":{"role":"assistant","content":"Hel","thinking":"hmm"},"done":false}"#, "\n", r#"{"message":{"role":"assistant","content":"lo","tool_calls":[{"function":{"name":"t","arguments":{"a":1}}}]},"done":false}"#, "\n", r#"{"message":{"role":"assistant","content":""},"done":true,"done_reason":"stop","prompt_eval_count":7,"eval_count":3}"#, "\n" ); Mock::given(method("POST")).and(path("/api/chat")).respond_with(ResponseTemplate::new(200).set_body_string(body)).mount(&server).await; let mut seen = String::new(); let done = Ollama::new(server.uri()).chat(&request(), |t| seen.push_str(t)).await.unwrap(); assert_eq!(seen, "Hello"); assert_eq!(done.thinking, "hmm"); assert_eq!(done.tool_calls[0].function.name, "t"); assert_eq!(done.tool_calls[0].id.as_deref(), Some("call_1")); assert_eq!((done.prompt_eval_count, done.eval_count), (7, 3)); } #[tokio::test] async fn incomplete_and_http_errors() { let server = MockServer::start().await; Mock::given(method("POST")).and(path("/api/chat")) .respond_with(ResponseTemplate::new(200).set_body_string("{\"message\":{\"role\":\"assistant\",\"content\":\"x\"},\"done\":false}\n")) .mount(&server).await; let err = Ollama::new(server.uri()).chat(&request(), |_| {}).await.unwrap_err(); assert!(matches!(err, LlmError::StreamIncomplete)); let server = MockServer::start().await; Mock::given(method("POST")).and(path("/api/chat")).respond_with(ResponseTemplate::new(500).set_body_string("boom")).mount(&server).await; let err = Ollama::new(server.uri()).chat(&request(), |_| {}).await.unwrap_err(); assert!(matches!(err, LlmError::Http { status: 500, .. })); } }