From dd66a7e3073fd5fe2ad9bdecd32af7d7eebc3c20 Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:47 +0100 Subject: [PATCH] capri-llm: add openai module --- crates/capri-llm/src/openai.rs | 960 +++++++++++++++++++++++++++++++++ 1 file changed, 960 insertions(+) create mode 100644 crates/capri-llm/src/openai.rs diff --git a/crates/capri-llm/src/openai.rs b/crates/capri-llm/src/openai.rs new file mode 100644 index 0000000..177361f --- /dev/null +++ b/crates/capri-llm/src/openai.rs @@ -0,0 +1,960 @@ +//! OpenAI-compatible chat completions: external APIs and Lemonade (Capri `inference-api.mjs`). +use std::collections::HashSet; +use std::hash::{Hash, Hasher}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use futures::StreamExt; +use regex::Regex; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; +use url::Url; + +use crate::ollama::{ToolFunction, MAX_EVENT}; +use crate::{ChatDone, ChatRequest, LlmError, Message, ToolCall}; + +pub const DEFAULT_BASE_URL: &str = "https://openrouter.ai/api/v1"; +/// Settings presets, plus Anthropic's OpenAI-compatible endpoint. +pub const PRESETS: &[(&str, &str)] = &[ + ("OpenRouter", "https://openrouter.ai/api/v1"), + ("Hugging Face", "https://router.huggingface.co/v1"), + ("ProxyAPI", "https://api.proxyapi.ru/v1"), + ("DeepSeek", "https://api.deepseek.com"), + ("Google Gemini", "https://generativelanguage.googleapis.com/v1beta/openai"), + ("Anthropic", "https://api.anthropic.com/v1"), + ("Lemonade (local)", "http://127.0.0.1:13305/api/v1"), +]; +pub const INVALID_ENDPOINT: &str = + "Use HTTPS for remote APIs or HTTP for a loopback address. Omit credentials, query parameters and fragments."; +pub const IMAGES_UNSUPPORTED: &str = "The active model cannot read images or video frames."; +const MAX_RESPONSE: usize = 16 << 20; +const JSON_CONTRACT: &str = "\nReply with the raw JSON object only, as plain text. You have no tools: never write , XML or Markdown."; +/// Optional-parameter limit of strict grammars (provider 400: "… (limit: 24)"). +pub const OPTIONAL_PARAMETER_LIMIT: usize = 24; +const STRICT_SCHEMA_MAX_BYTES: usize = 16 * 1024; +/// Provider 400s caused by structured output or strict grammars (retried prompt-only). +static STRUCTURED_REJECTION: std::sync::LazyLock = std::sync::LazyLock::new(|| { + Regex::new(r"(?i)response_format|json_schema|compiled grammar is too large|too many optional parameters|strict tools").expect("valid regex") +}); + +/// A saved API connection. The key lives in the secret store under `id`, bound to `origin()`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[serde(default, rename_all = "camelCase")] +pub struct ApiConnection { + pub id: String, + pub name: String, + pub base_url: String, + pub model: String, + pub tools: bool, + pub vision: bool, + /// Provider accepts reasoning control (`reasoning_effort`, OpenRouter `reasoning`). + pub thinking: bool, + pub context_tokens: u32, +} + +impl Default for ApiConnection { + fn default() -> Self { + Self { + id: String::new(), + name: String::new(), + base_url: DEFAULT_BASE_URL.into(), + model: String::new(), + tools: true, + vision: false, + thinking: false, + context_tokens: 32768, + } + } +} + +fn loopback(url: &Url) -> bool { + url.scheme() == "http" && matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")) +} + +impl ApiConnection { + /// Validation and normalization (`localhost` → `127.0.0.1`, no trailing slash). + pub fn validated(mut self) -> Result { + let mut url = Url::parse(self.base_url.trim()).map_err(|_| INVALID_ENDPOINT)?; + let local = loopback(&url); + if url.as_str().len() > 512 + || (url.scheme() != "https" && !local) + || !url.username().is_empty() + || url.password().is_some() + || url.query().is_some() + || url.fragment().is_some() + { + return Err(INVALID_ENDPOINT); + } + if url.host_str() == Some("localhost") { + url.set_host(Some("127.0.0.1")).map_err(|_| INVALID_ENDPOINT)?; + } + let min_context = if local { 8192 } else { 32768 }; + self.model = self.model.trim().to_string(); + if !(min_context..=262_144).contains(&self.context_tokens) + || self.model.is_empty() + || self.model.len() > 128 + || self.model.chars().any(|c| c.is_whitespace() || c.is_control()) + { + return Err("Invalid API model settings."); + } + self.name = self.name.trim().chars().take(64).collect(); + self.base_url = url.as_str().trim_end_matches('/').to_string(); + // TODO: Lemonade NPU request shaping is not ported since NPU models are unavailable on Linux; port it if Lemonade ships Linux NPU support. + Ok(self) + } + + pub fn is_local(&self) -> bool { + Url::parse(&self.base_url).is_ok_and(|u| loopback(&u)) + } + + /// Origin a key is bound to (changing it requires a new key). + pub fn origin(&self) -> String { + Url::parse(&self.base_url).map(|u| u.origin().ascii_serialization()).unwrap_or_default() + } + + fn host(&self) -> String { + Url::parse(&self.base_url).ok().and_then(|u| u.host_str().map(str::to_string)).unwrap_or_default() + } + + /// Header label: `API · · `. + pub fn label(&self) -> String { + format!("API · {} · {}", self.host(), self.model) + } +} + +fn api(code: &'static str, message: impl Into) -> LlmError { + LlmError::Api { code, message: message.into(), status: None, detail: String::new() } +} + +/// Public message per provider status; provider prose is never shown. +pub fn provider_status_message(status: u16) -> String { + match status { + 401 => "API provider returned HTTP 401. Check that the key belongs to this provider.".into(), + 402 => "API provider returned HTTP 402. Check the account balance or key budget.".into(), + 403 => "API provider returned HTTP 403. Check the key permissions for this model.".into(), + 404 => "API provider returned HTTP 404. Check the base URL and the model ID for this provider.".into(), + 429 => "API provider returned HTTP 429. The provider rate limit was reached.".into(), + n => format!("API provider returned HTTP {n}. Check access, model availability and account balance."), + } +} + +/// Maps transport/stream errors of the API path onto Capri's API codes and texts. +fn api_error(error: LlmError) -> LlmError { + match error { + LlmError::Api { .. } => error, + LlmError::Network { code: "ETIMEDOUT" } => api("CAPRI_API_TIMEOUT", "API request cancelled or timed out."), + LlmError::Network { code } => { + api("CAPRI_API_NETWORK_ERROR", format!("API connection failed. Check the provider URL and network. ({code})")) + } + LlmError::StreamInvalid(_) | LlmError::StreamIncomplete => api("CAPRI_API_RESPONSE_INVALID", "API model returned no text."), + LlmError::Reported(_) | LlmError::Http { .. } => api("CAPRI_API_REQUEST_FAILED", "API request could not be completed."), + } +} + +/// Explicit image-modality rejection in a provider error body (regexes copied verbatim from Capri). +pub fn provider_rejects_images(body: &str) -> bool { + let Ok(packet) = serde_json::from_str::(body) else { return false }; + let detail = &packet["error"]; + let code = detail["code"].as_str().or(packet["code"].as_str()).unwrap_or(""); + let text = detail.as_str().or(detail["message"].as_str()).or(packet["message"].as_str()).unwrap_or(""); + let ci = |p: &str| Regex::new(&format!("(?i){p}")).expect("valid regex"); + if ci(r"(?:auth|api.?key|permission|billing|balance|credit|quota|rate.?limit|time.?out|timed out|\b(?:format|mime|size|dimensions|resolution|base64)\b|(?:invalid|malformed|corrupt)\s+(?:image\s+)?url|image[^.!?\n]{0,25}(?:too large|too small|corrupt|malformed))").is_match(text) + || ci(r"(?:auth|key|billing|credit|quota|limit|timeout|format|mime|size|dimensions|base64)").is_match(code) + { + return false; + } + if matches!(code, "image_input_not_supported" | "model_does_not_support_images" | "unsupported_image_modality") { + return true; + } + [ + r"\bno endpoints?\b[^\r\n]{0,120}\bsupport\b[^\r\n]{0,60}\bimage(?:s| input)?\b", + r"\b(?:model|endpoint|provider)\b[^\r\n]{0,100}\b(?:does not|do not|doesn't|cannot|can't)\s+(?:support|accept|process|read)\b[^\r\n]{0,60}\b(?:images?|image inputs?|image_url|vision)\b", + r"\b(?:images?|image inputs?|image_url|vision)\b[^\r\n]{0,60}\b(?:not supported|unsupported)\b", + r"\bunsupported\s+image\s+(?:modality|input)\b", + ] + .iter() + .any(|p| ci(p).is_match(text)) +} + +/// Data URL with the MIME sniffed from the base64 magic (Capri always said PNG). +pub fn image_data_url(b64: &str) -> String { + let mime = match b64.as_bytes() { + [b'/', b'9', b'j', ..] => "image/jpeg", + [b'U', b'k', b'l', b'G', ..] => "image/webp", + [b'R', b'0', b'l', b'G', ..] => "image/gif", + _ => "image/png", + }; + format!("data:{mime};base64,{b64}") +} + +/// Converts the shared session messages to OpenAI chat messages. Tool results are paired with the +/// preceding assistant tool calls by name (Ollama messages carry `tool_name`, not `tool_call_id`). +pub fn openai_messages(messages: &[Message], tools: bool) -> Vec { + let mut pending: Vec<(String, String)> = Vec::new(); + let mut out = Vec::new(); + for (n, m) in messages.iter().enumerate() { + match m.role.as_str() { + "tool" | "function" if !tools => {} + "tool" => { + let at = pending.iter().position(|(_, name)| Some(name) == m.tool_name.as_ref()).unwrap_or(0); + let id = if pending.is_empty() { format!("call_{n}") } else { pending.remove(at).0 }; + out.push(json!({"role": "tool", "tool_call_id": id, "content": m.content})); + } + "assistant" => { + if !tools && m.content.is_empty() { + continue; + } + let mut value = json!({"role": "assistant", "content": m.content}); + if tools && !m.tool_calls.is_empty() { + pending.clear(); + let calls: Vec = m + .tool_calls + .iter() + .enumerate() + .map(|(i, c)| { + let id = c.id.clone().filter(|s| !s.is_empty()).unwrap_or_else(|| format!("call_{n}_{i}")); + pending.push((id.clone(), c.function.name.clone())); + let arguments = match &c.function.arguments { + Value::String(s) => s.clone(), + Value::Null => "{}".into(), + other => other.to_string(), + }; + json!({"id": id, "type": "function", "function": {"name": c.function.name, "arguments": arguments}}) + }) + .collect(); + if m.content.is_empty() { + value["content"] = Value::Null; + } + value["tool_calls"] = Value::Array(calls); + } + out.push(value); + } + role => { + let content = if m.images.is_empty() { + Value::String(m.content.clone()) + } else { + let mut parts = vec![json!({"type": "text", "text": m.content})]; + parts.extend(m.images.iter().map(|b| json!({"type": "image_url", "image_url": {"url": image_data_url(b)}}))); + Value::Array(parts) + }; + out.push(json!({"role": role, "content": content})); + } + } + } + out +} + +/// Detects credential echoes in streamed text: the whole key or its first +/// `significant` characters aborts; a trailing partial match is withheld until resolved. +struct Redactor { + probe: Option, +} + +impl Redactor { + fn new(key: Option<&str>) -> Self { + let probe = key.filter(|k| !k.is_empty()).map(|k| { + let significant = (k.len().saturating_sub(2)).clamp(2, 8).min(k.len()); + k[..significant].to_string() + }); + Self { probe } + } + + fn leaked(&self, text: &str) -> bool { + self.probe.as_ref().is_some_and(|p| text.contains(p.as_str())) + } + + /// Length of `text` that can be shown now (excludes a suffix that starts the key). + fn safe_len(&self, text: &str) -> usize { + let Some(probe) = &self.probe else { return text.len() }; + (1..probe.len()).rev().find(|&n| text.ends_with(&probe[..n])).map_or(text.len(), |n| text.len() - n) + } +} + +fn scrub(text: &str, key: Option<&str>) -> String { + match key { + Some(k) if !k.is_empty() => text.replace(k, "[REDACTED]"), + _ => text.to_string(), + } +} + +/// Output strategy for structured requests. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Structured { + JsonObject, + JsonSchemaStrict, + PromptOnly, +} + +/// Number of non-required object properties anywhere in `schema` (what strict grammars count). +pub fn optional_parameter_count(schema: &Value) -> usize { + match schema { + Value::Object(map) => { + let required: HashSet<&str> = map.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); + let own = map.get("properties").and_then(Value::as_object).map_or(0, |p| p.keys().filter(|k| !required.contains(k.as_str())).count()); + own + map.values().map(optional_parameter_count).sum::() + } + Value::Array(items) => items.iter().map(optional_parameter_count).sum(), + _ => 0, + } +} + +/// Strict-grammar subset of a JSON schema with zero optional parameters: every property is +/// required, originally optional ones become nullable; unsupported keywords and enums > 12 dropped. +pub fn strict_schema(schema: &Value) -> Value { + match schema { + Value::Array(items) => Value::Array(items.iter().map(strict_schema).collect()), + Value::Object(map) => { + let mut out = Map::new(); + for (key, value) in map { + match key.as_str() { + "minLength" | "maxLength" | "minimum" | "maximum" | "maxItems" | "uniqueItems" | "pattern" | "required" => {} + "enum" if value.as_array().is_some_and(|a| a.len() > 12) => {} + "minItems" => { + out.insert(key.clone(), json!(value.as_u64().unwrap_or(0).min(1))); + } + "properties" => { + let required: HashSet<&str> = + map.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); + let props = value.as_object().into_iter().flatten().map(|(name, sub)| { + let strict = strict_schema(sub); + let strict = if required.contains(name.as_str()) { strict } else { json!({"anyOf": [strict, {"type": "null"}]}) }; + (name.clone(), strict) + }); + out.insert(key.clone(), Value::Object(props.collect())); + let names = value.as_object().map(|p| p.keys().cloned().map(Value::String).collect()).unwrap_or_default(); + out.insert("required".into(), Value::Array(names)); + } + _ => { + out.insert(key.clone(), strict_schema(value)); + } + } + } + if out.get("type").and_then(Value::as_str) == Some("object") || out.contains_key("properties") { + out.insert("additionalProperties".into(), Value::Bool(false)); + } + Value::Object(out) + } + other => other.clone(), + } +} + +/// Rewrites tool parameter schemas (OpenAI/Ollama tool shape) so the request stays under `limit` +/// optional parameters: tools with the most optional parameters become strict (nullable-required) +/// first. Also removes any `strict` flag. The model then sends `null` for unused options; +/// [`drop_optional_nulls`] restores the original shape before validation. +pub fn limit_optional_parameters(tools: &mut [Value], limit: usize) { + for tool in tools.iter_mut() { + if let Some(function) = tool.get_mut("function").and_then(Value::as_object_mut) { + function.remove("strict"); + } + } + let count = |t: &Value| optional_parameter_count(&t["function"]["parameters"]); + let mut total: usize = tools.iter().map(count).sum(); + let mut order: Vec = (0..tools.len()).collect(); + order.sort_by_key(|&i| std::cmp::Reverse(count(&tools[i]))); + for i in order { + if total <= limit { + break; + } + total -= count(&tools[i]); + let strict = strict_schema(&tools[i]["function"]["parameters"]); + tools[i]["function"]["parameters"] = strict; + } +} + +/// Removes `null` values of properties that the original schema did not require. +pub fn drop_optional_nulls(value: &mut Value, schema: &Value) { + let (Some(object), Some(props)) = (value.as_object_mut(), schema["properties"].as_object()) else { return }; + let required: HashSet<&str> = schema["required"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + object.retain(|k, v| !(v.is_null() && !required.contains(k.as_str()))); + for (k, v) in object.iter_mut() { + if let Some(sub) = props.get(k) { + drop_optional_nulls(v, sub); + } + } +} + +fn first_json_object(text: &str) -> Option<&str> { + if serde_json::from_str::(text).is_ok() { + return Some(text); + } + let start = text.find('{')?; + let (mut depth, mut quoted, mut escaped) = (0usize, false, false); + for (i, c) in text[start..].char_indices() { + if quoted { + match c { + _ if escaped => escaped = false, + '\\' => escaped = true, + '"' => quoted = false, + _ => {} + } + } else if c == '"' { + quoted = true; + } else if c == '{' { + depth += 1; + } else if c == '}' { + depth -= 1; + if depth == 0 { + let candidate = &text[start..start + i + 1]; + return serde_json::from_str::(candidate).is_ok().then_some(candidate); + } + } + } + None +} + +/// Recovers the JSON object a model meant (fences, trailing prose, XML tool-call imitation). +pub fn plain_json(content: &str) -> String { + let trimmed = content.trim(); + let fence = Regex::new(r"(?s)^```(?:json)?\s*(.*?)\s*```$").expect("valid regex"); + let text = fence.captures(trimmed).map_or(trimmed, |c| c.get(1).map_or("", |m| m.as_str())); + if !text.starts_with('<') { + return first_json_object(text).unwrap_or(text).to_string(); + } + let last = text.rfind('}'); + if let (Some(json), Some(last)) = (Regex::new(r#"\{\s*"action"\s*:"#).expect("valid regex").find(text), last) { + let candidate = &text[json.start()..=last.max(json.start())]; + if json.start() < last && serde_json::from_str::(candidate).is_ok() { + return candidate.to_string(); + } + } + let parameter = Regex::new(r#"]*?\bname\s*=\s*["']([^"']+)["'][^>]*>((?s:.*?))"#).expect("valid regex"); + let mut value = Map::new(); + for c in parameter.captures_iter(text) { + let raw = &c[2]; + value.insert(c[1].to_string(), serde_json::from_str(raw).unwrap_or_else(|_| Value::String(raw.trim().to_string()))); + } + if !value.is_empty() { + let invoke = Regex::new(r#"]*?\bname\s*=\s*["']([^"']+)["']"#).expect("valid regex"); + if let (false, Some(c)) = (value.contains_key("action"), invoke.captures(text)) { + value.insert("action".into(), Value::String(c[1].to_string())); + } + return Value::Object(value).to_string(); + } + match (text.find('{'), last) { + (Some(first), Some(last)) if last > first => text[first..=last].to_string(), + _ => text.to_string(), + } +} + +/// Client for one saved connection. The key never appears in `Debug`, logs or errors. +#[derive(Clone)] +pub struct OpenAi { + pub connection: ApiConnection, + key: Option, + http: reqwest::Client, + prompt_only: Arc>>, +} + +impl std::fmt::Debug for OpenAi { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("OpenAi").field("connection", &self.connection).field("has_key", &self.key.is_some()).finish() + } +} + +#[derive(Default)] +struct ToolAcc { + id: String, + name: String, + arguments: String, +} + +impl OpenAi { + pub fn new(connection: ApiConnection, key: Option) -> Self { + let mut builder = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()).connect_timeout(Duration::from_secs(15)); + if connection.is_local() { + builder = builder.no_proxy(); + } + // TODO: remote providers follow the env proxy (HTTPS_PROXY), reqwest's default; decide whether that is wanted. + let http = builder.build().expect("HTTP client"); + Self { connection, key: key.filter(|k| !k.is_empty()), http, prompt_only: Default::default() } + } + + pub fn has_key(&self) -> bool { + self.key.is_some() + } + + fn anthropic(&self) -> bool { + self.connection.host() == "api.anthropic.com" + } + + /// Common request body (vision gate, key check, tools stripping, temperature). + fn base_body(&self, request: &ChatRequest) -> Result { + if !self.connection.vision && request.messages.iter().any(|m| !m.images.is_empty()) { + return Err(LlmError::Api { code: "MODEL_IMAGES_UNSUPPORTED", message: IMAGES_UNSUPPORTED.into(), status: Some(422), detail: String::new() }); + } + if self.key.is_none() && !self.connection.is_local() { + return Err(api("CAPRI_API_REQUEST_FAILED", "API key is missing.")); + } + let mut body = json!({"model": self.connection.model, "messages": openai_messages(&request.messages, self.connection.tools)}); + if !self.anthropic() { + // Anthropic models reject non-default sampling over the compatibility endpoint. + body["temperature"] = json!(request.options.temperature); + } + Ok(body) + } + + /// One-turn reasoning control: `think == Some(true)` selects medium reasoning. + fn reasoning(&self, body: &mut Value, request: &ChatRequest, default_tokens: i32, cap: i32) -> bool { + let requested = request.options.num_predict.filter(|&n| n > 0); + let selected = request.think == Some(true) && self.connection.thinking; + if selected { + body["max_tokens"] = json!(requested.unwrap_or(8192).min(8192)); + if self.connection.origin() == "https://openrouter.ai" { + body["reasoning"] = json!({"effort": "medium", "exclude": true}); + } else { + body["reasoning_effort"] = json!("medium"); + } + } else { + body["max_tokens"] = json!(requested.unwrap_or(default_tokens).min(cap)); + } + selected + } + + async fn send(&self, body: &Value, timeout: Duration) -> Result { + let mut builder = self.http.post(format!("{}/chat/completions", self.connection.base_url)).json(body).timeout(timeout); + if let Some(key) = &self.key { + builder = builder.bearer_auth(key); + } + let response = builder.send().await.map_err(|e| api_error(crate::ollama::network(e)))?; + let status = response.status(); + if status.is_success() { + return Ok(response); + } + let mut raw = Vec::new(); + let mut stream = response.bytes_stream(); + let read = async { + while let Some(Ok(chunk)) = stream.next().await { + raw.extend_from_slice(&chunk); + if raw.len() > 8192 { + break; + } + } + }; + let _ = tokio::time::timeout(Duration::from_secs(1), read).await; + let text = scrub(&String::from_utf8_lossy(&raw[..raw.len().min(8192)]), self.key.as_deref()); + let has_images = body["messages"].as_array().into_iter().flatten().any(|m| m["content"].as_array().is_some_and(|p| p.iter().any(|p| p["type"] == "image_url"))); + if has_images && matches!(status.as_u16(), 400 | 404 | 415 | 422) && provider_rejects_images(&text) { + return Err(LlmError::Api { code: "MODEL_IMAGES_UNSUPPORTED", message: IMAGES_UNSUPPORTED.into(), status: Some(422), detail: String::new() }); + } + let detail = serde_json::from_str::(&text) + .ok() + .and_then(|v| v["error"]["message"].as_str().or(v["error"].as_str()).map(str::to_string)) + .unwrap_or_default() + .chars() + .take(400) + .collect::(); + tracing::debug!(status = status.as_u16(), "API provider error: {detail}"); + Err(LlmError::Api { code: "CAPRI_API_PROVIDER_ERROR", message: provider_status_message(status.as_u16()), status: Some(status.as_u16()), detail }) + } + + /// Streams a conversation turn; same contract as [`crate::Ollama::chat`]. + pub async fn chat(&self, request: &ChatRequest, on_text: impl FnMut(&str)) -> Result { + self.chat_inner(request, on_text).await.map_err(api_error) + } + + async fn chat_inner(&self, request: &ChatRequest, mut on_text: impl FnMut(&str)) -> Result { + let mut body = self.base_body(request)?; + body["stream"] = json!(true); + let selected = self.reasoning(&mut body, request, 2048, 2048); + if self.connection.tools && !request.tools.is_empty() { + let mut tools = request.tools.clone(); + for tool in &mut tools { + if let Some(f) = tool.get_mut("function").and_then(Value::as_object_mut) { + f.remove("strict"); // strict tools compile grammars that providers reject + } + } + body["tools"] = Value::Array(tools); + } + let timeout = Duration::from_secs(if selected { 300 } else { 180 }); + let response = self.send(&body, timeout).await?; + let buffered = response.headers().get(reqwest::header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.contains("json")); + let redactor = Redactor::new(self.key.as_deref()); + let mut done = ChatDone::default(); + let mut tools: Vec = Vec::new(); + let mut sent = 0usize; + let mut finished = false; + let mut total = 0usize; + let mut buffer: Vec = Vec::new(); + let mut stream = response.bytes_stream(); + let mut handle = |packet: &Value, done: &mut ChatDone, tools: &mut Vec| -> Result<(), LlmError> { + if packet.get("error").is_some_and(|e| !e.is_null()) { + return Err(api("CAPRI_API_PROVIDER_ERROR", "API request could not be completed.")); + } + if let Some(usage) = packet.get("usage").filter(|u| u.is_object()) { + done.prompt_eval_count = usage["prompt_tokens"].as_u64().unwrap_or(0); + done.eval_count = usage["completion_tokens"].as_u64().unwrap_or(0); + } + let Some(choice) = packet["choices"].get(0) else { return Ok(()) }; + // Buffered completions carry `message`, streamed ones `delta`; private reasoning fields are ignored. + let delta = if choice["delta"].is_object() { &choice["delta"] } else { &choice["message"] }; + if let Some(text) = delta["content"].as_str() { + done.content.push_str(text); + if redactor.leaked(&done.content) { + return Err(api("CAPRI_API_REQUEST_FAILED", "API request could not be completed.")); + } + let safe = redactor.safe_len(&done.content); + if safe > sent { + on_text(&done.content[sent..safe]); + sent = safe; + } + } + for (position, call) in delta["tool_calls"].as_array().into_iter().flatten().enumerate() { + let index = call["index"].as_u64().map_or(position, |i| i as usize).min(127); + if tools.len() <= index { + tools.resize_with(index + 1, ToolAcc::default); + } + let acc = &mut tools[index]; + if let Some(id) = call["id"].as_str() { + acc.id = id.into(); + } + if let Some(name) = call["function"]["name"].as_str() { + acc.name.push_str(name); + } + if let Some(args) = call["function"]["arguments"].as_str() { + acc.arguments.push_str(args); + } + } + if let Some(reason) = choice["finish_reason"].as_str() { + done.done_reason = Some(reason.into()); + } + Ok(()) + }; + while let Some(chunk) = stream.next().await { + let chunk = chunk.map_err(crate::ollama::network)?; + total += chunk.len(); + if total > MAX_RESPONSE { + return Err(api("CAPRI_API_RESPONSE_LIMIT", "API response exceeds limits.")); + } + buffer.extend(chunk.iter().filter(|&&b| b != b'\r')); + if buffered { + continue; + } + while let Some(pos) = buffer.windows(2).position(|w| w == b"\n\n") { + let frame: Vec = buffer.drain(..pos + 2).collect(); + let frame = std::str::from_utf8(&frame).map_err(|_| LlmError::StreamInvalid("not UTF-8".into()))?; + let data: Vec<&str> = frame.lines().filter_map(|l| l.strip_prefix("data:")).map(|d| d.strip_prefix(' ').unwrap_or(d)).collect(); + if data.is_empty() { + continue; + } + let data = data.join("\n"); + if data == "[DONE]" { + finished = true; + continue; + } + let packet: Value = serde_json::from_str(&data).map_err(|e| LlmError::StreamInvalid(e.to_string()))?; + handle(&packet, &mut done, &mut tools)?; + } + if buffer.len() > MAX_EVENT { + return Err(LlmError::StreamInvalid("event too large".into())); + } + } + if buffered { + let packet: Value = serde_json::from_slice(&buffer).map_err(|e| LlmError::StreamInvalid(e.to_string()))?; + if packet["choices"].as_array().is_none_or(Vec::is_empty) { + return Err(LlmError::StreamInvalid("no choices".into())); + } + handle(&packet, &mut done, &mut tools)?; + finished = true; + } + if !finished && done.done_reason.is_none() { + return Err(LlmError::StreamIncomplete); + } + if sent < done.content.len() { + on_text(&done.content[sent..]); + } + for (n, acc) in tools.into_iter().enumerate().filter(|(_, a)| !a.name.is_empty()) { + if redactor.leaked(&acc.arguments) { + return Err(api("CAPRI_API_REQUEST_FAILED", "API request could not be completed.")); + } + let arguments = serde_json::from_str(&acc.arguments).unwrap_or(Value::String(acc.arguments)); + let id = if acc.id.is_empty() { format!("call_{}", n + 1) } else { acc.id }; + done.tool_calls.push(ToolCall { id: Some(id), function: ToolFunction { name: acc.name, arguments } }); + } + if done.content.trim().is_empty() && done.tool_calls.is_empty() { + return Err(LlmError::StreamInvalid("no text".into())); + } + Ok(done) + } + + fn memo_key(&self, schema: Option<&Value>) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + (self.connection.origin(), &self.connection.model, schema.map(Value::to_string)).hash(&mut h); + h.finish() + } + + /// Auxiliary JSON request in Ollama shape: `schema = None` asks for any JSON object. + /// Returns the decoded object with optional `null`s removed; callers still validate it. + pub async fn chat_json(&self, request: &ChatRequest, schema: Option<&Value>) -> Result { + let memo = self.memo_key(schema); + let mut strategy = match schema { + _ if self.prompt_only.lock().expect("memo").contains(&memo) => Structured::PromptOnly, + Some(s) if self.anthropic() && s["type"] == "object" => { + let strict = strict_schema(s); + if optional_parameter_count(&strict) <= OPTIONAL_PARAMETER_LIMIT && strict.to_string().len() <= STRICT_SCHEMA_MAX_BYTES { + Structured::JsonSchemaStrict + } else { + Structured::PromptOnly + } + } + _ if self.anthropic() => Structured::PromptOnly, + _ => Structured::JsonObject, + }; + loop { + let mut body = self.base_body(request).map_err(api_error)?; + body["stream"] = json!(false); + self.reasoning(&mut body, request, 768, if request.think == Some(true) { 8192 } else { 4096 }); + let contract = format!("Return JSON matching this output schema: {}{JSON_CONTRACT}", schema.map_or("{}".into(), Value::to_string)); + body["messages"].as_array_mut().expect("messages").insert(0, json!({"role": "system", "content": contract})); + match strategy { + Structured::JsonObject => body["response_format"] = json!({"type": "json_object"}), + Structured::JsonSchemaStrict => { + body["response_format"] = json!({"type": "json_schema", "json_schema": {"name": "capri_output", "strict": true, "schema": strict_schema(schema.expect("schema"))}}) + } + Structured::PromptOnly => {} + } + let response = match self.send(&body, Duration::from_secs(180)).await { + Err(LlmError::Api { status: Some(400), ref detail, .. }) + if strategy != Structured::PromptOnly + && STRUCTURED_REJECTION.is_match(detail) => + { + self.prompt_only.lock().expect("memo").insert(memo); + strategy = Structured::PromptOnly; + continue; + } + other => other?, + }; + let bytes = response.bytes().await.map_err(|e| api_error(crate::ollama::network(e)))?; + if bytes.len() > MAX_RESPONSE { + return Err(api("CAPRI_API_RESPONSE_LIMIT", "API response exceeds limits.")); + } + let packet: Value = serde_json::from_slice(&bytes).map_err(|_| api("CAPRI_API_RESPONSE_INVALID", "API model returned no text."))?; + let message = &packet["choices"][0]["message"]; + if !message.is_object() || message["tool_calls"].as_array().is_some_and(|c| !c.is_empty()) { + return Err(api("CAPRI_API_RESPONSE_INVALID", "API model returned an invalid tool-free response.")); + } + let text = message["content"].as_str().unwrap_or(""); + if Redactor::new(self.key.as_deref()).leaked(text) { + return Err(api("CAPRI_API_REQUEST_FAILED", "API request could not be completed.")); + } + let mut value: Value = serde_json::from_str(&plain_json(text)).map_err(|_| api("CAPRI_API_RESPONSE_INVALID", "API model returned no text."))?; + if let Some(schema) = schema { + drop_optional_nulls(&mut value, schema); + } + // TODO: no local JSON-schema validation; callers re-validate the result as Capri's planners do. + return Ok(value); + } + } + + /// Connection test: "Reply with only OK." and the elapsed time. + pub async fn test(&self) -> Result { + let started = Instant::now(); + let request = ChatRequest { + model: self.connection.model.clone(), + messages: vec![Message::new("user", "Reply with only OK.")], + tools: vec![], + options: crate::Options { temperature: 0.0, num_predict: Some(256), ..Default::default() }, + keep_alive: 0, + stream: true, + think: None, + }; + let limit = Duration::from_secs(if self.key.is_some() { 15 } else { 60 }); + // TODO: Capri's retry with `reasoning_effort: none` for reasoning-only Ollama replies is not ported; add it if tests against Ollama in OpenAI mode fail. + match tokio::time::timeout(limit, self.chat(&request, |_| {})).await { + Err(_) => Err(api("CAPRI_API_TIMEOUT", "API request cancelled or timed out.")), + Ok(result) => result.map(|_| started.elapsed()), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use wiremock::matchers::{header, method, path}; + use wiremock::{Mock, MockServer, Request, ResponseTemplate}; + + fn connection(base: &str) -> ApiConnection { + ApiConnection { id: "c".into(), base_url: base.into(), model: "vendor/m".into(), ..Default::default() } + } + + fn request(messages: Vec) -> ChatRequest { + ChatRequest { model: "local".into(), messages, tools: vec![], options: crate::Options { temperature: 0.5, num_predict: Some(4096), ..Default::default() }, keep_alive: 0, stream: true, think: Some(false) } + } + + fn sse(frames: &[Value]) -> String { + frames.iter().map(|f| format!("data: {f}\r\n\r\n")).collect::() + "data: [DONE]\n\n" + } + + #[test] + fn validates_and_normalizes_connections() { + let c = ApiConnection { base_url: "http://localhost:13305/api/v1/".into(), model: "m".into(), context_tokens: 8192, ..Default::default() }.validated().unwrap(); + assert_eq!(c.base_url, "http://127.0.0.1:13305/api/v1"); + assert!(c.is_local()); + for bad in ["http://example.com/v1", "https://u:p@example.com", "https://example.com/?a=1", "https://example.com/#x", "nope"] { + assert_eq!(ApiConnection { base_url: bad.into(), model: "m".into(), ..Default::default() }.validated(), Err(INVALID_ENDPOINT), "{bad}"); + } + let remote = |ctx, model: &str| ApiConnection { model: model.into(), context_tokens: ctx, ..Default::default() }.validated(); + assert!(remote(16384, "m").is_err(), "remote minimum is 32768"); + assert!(remote(32768, "a b").is_err()); + assert!(remote(32768, "").is_err()); + assert_eq!(remote(32768, "m").unwrap().origin(), "https://openrouter.ai"); + } + + #[test] + fn converts_messages_with_tools_and_images() { + let mut assistant = Message::new("assistant", ""); + assistant.tool_calls = vec![ToolCall { id: Some("call_1".into()), function: ToolFunction { name: "clock".into(), arguments: json!({"tz": "utc"}) } }]; + let tool = Message { role: "tool".into(), content: "12:00".into(), tool_name: Some("clock".into()), ..Default::default() }; + let mut user = Message::new("user", "look"); + user.images = vec!["/9j/abc".into()]; + let msgs = [Message::new("system", "s"), user, assistant, tool]; + let out = openai_messages(&msgs, true); + assert_eq!(out[1]["content"][1]["image_url"]["url"], "data:image/jpeg;base64,/9j/abc"); + assert_eq!(out[2]["content"], Value::Null); + assert_eq!(out[2]["tool_calls"][0]["function"]["arguments"], r#"{"tz":"utc"}"#); + assert_eq!(out[3]["tool_call_id"], "call_1"); + let without = openai_messages(&msgs, false); + assert_eq!(without.len(), 2, "tool messages and empty assistant turns are dropped"); + } + + #[tokio::test] + async fn streams_text_tool_calls_and_caps_tokens() { + let server = MockServer::start().await; + let body = sse(&[ + json!({"choices":[{"index":0,"delta":{"content":"Hel","reasoning":"secret thoughts"}}]}), + json!({"choices":[{"index":0,"delta":{"content":"lo","tool_calls":[{"index":0,"id":"x1","type":"function","function":{"name":"clock","arguments":"{\"a\""}}]}}]}), + json!({"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":":1}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":5,"completion_tokens":2}}), + ]); + Mock::given(method("POST")).and(path("/v1/chat/completions")).and(header("authorization", "Bearer sk-test-123456")) + .respond_with(ResponseTemplate::new(200).insert_header("content-type", "text/event-stream").set_body_string(body)).mount(&server).await; + let client = OpenAi::new(connection(&format!("{}/v1", server.uri())), Some("sk-test-123456".into())); + let mut req = request(vec![Message::new("user", "hi")]); + req.tools = vec![json!({"type":"function","function":{"name":"clock","strict":true,"parameters":{"type":"object"}}})]; + let mut seen = String::new(); + let done = client.chat(&req, |t| seen.push_str(t)).await.unwrap(); + assert_eq!(seen, "Hello"); + assert!(done.thinking.is_empty(), "private reasoning is dropped"); + assert_eq!(done.tool_calls[0].id.as_deref(), Some("x1")); + assert_eq!(done.tool_calls[0].function.arguments, json!({"a": 1})); + assert_eq!((done.prompt_eval_count, done.eval_count), (5, 2)); + let sent: Value = serde_json::from_slice(&server.received_requests().await.unwrap()[0].body).unwrap(); + assert_eq!(sent["max_tokens"], 2048); + assert_eq!(sent["model"], "vendor/m"); + assert!(sent["tools"][0]["function"].get("strict").is_none()); + assert!(sent.get("reasoning_effort").is_none()); + } + + #[tokio::test] + async fn reasoning_images_errors_and_credential_echo() { + let server = MockServer::start().await; + Mock::given(method("POST")).respond_with(|r: &Request| { + let body: Value = serde_json::from_slice(&r.body).unwrap(); + match body["messages"][0]["content"].as_str() { + Some("echo") => ResponseTemplate::new(200).set_body_string(sse(&[json!({"choices":[{"delta":{"content":"your key sk-te"}}]}), json!({"choices":[{"delta":{"content":"st-123456"},"finish_reason":"stop"}]})])), + Some("think") => ResponseTemplate::new(200).set_body_string(sse(&[json!({"choices":[{"delta":{"content":"ok"},"finish_reason":"stop"}]})])), + _ => ResponseTemplate::new(402).set_body_string(r#"{"error":{"message":"no credit for sk-test-123456"}}"#), + } + }).mount(&server).await; + let mut c = connection(&server.uri()); + c.thinking = true; + let client = OpenAi::new(c, Some("sk-test-123456".into())); + let mut seen = String::new(); + let err = client.chat(&request(vec![Message::new("user", "echo")]), |t| seen.push_str(t)).await.unwrap_err(); + assert!(!seen.contains("sk-te"), "partial key prefix withheld: {seen}"); + assert_eq!(err.code(), "CAPRI_API_REQUEST_FAILED"); + + let mut req = request(vec![Message::new("user", "think")]); + req.think = Some(true); + client.chat(&req, |_| {}).await.unwrap(); + let sent: Value = serde_json::from_slice(&server.received_requests().await.unwrap()[1].body).unwrap(); + assert_eq!((sent["max_tokens"].as_i64(), sent["reasoning_effort"].as_str()), (Some(4096), Some("medium"))); + + let err = client.chat(&request(vec![Message::new("user", "pay")]), |_| {}).await.unwrap_err(); + assert_eq!(err.public_message(), Some("API provider returned HTTP 402. Check the account balance or key budget.")); + assert!(!format!("{err:?}").contains("sk-test-123456"), "key redacted from detail"); + + let mut user = Message::new("user", "img"); + user.images = vec!["iVBOR".into()]; + let err = client.chat(&request(vec![user]), |_| {}).await.unwrap_err(); + assert_eq!(err.public_message(), Some(IMAGES_UNSUPPORTED)); + assert_eq!(server.received_requests().await.unwrap().len(), 3, "images rejected before network I/O"); + + let keyless = OpenAi::new(connection(&server.uri().replace("127.0.0.1", "203.0.113.1").replace("http:", "https:")), None); + assert_eq!(keyless.chat(&request(vec![Message::new("user", "x")]), |_| {}).await.unwrap_err().public_message(), Some("API key is missing.")); + } + + #[tokio::test] + async fn json_schema_falls_back_to_prompt_only_once_and_memoizes() { + let server = MockServer::start().await; + Mock::given(method("POST")).respond_with(|r: &Request| { + let body: Value = serde_json::from_slice(&r.body).unwrap(); + if body.get("response_format").is_some() { + ResponseTemplate::new(400).set_body_string(r#"{"error":{"type":"invalid_request_error","message":"Schemas contains too many optional parameters (36), which would make grammar compilation inefficient."}}"#) + } else { + ResponseTemplate::new(200).set_body_json(json!({"choices":[{"message":{"role":"assistant","content":"```json\n{\"action\":\"click\",\"x\":null}\n```"},"finish_reason":"stop"}]})) + } + }).mount(&server).await; + let client = OpenAi::new(connection(&server.uri()), None); + let schema = json!({"type":"object","required":["action"],"properties":{"action":{"type":"string"},"x":{"type":"integer"}}}); + let req = request(vec![Message::new("user", "plan")]); + assert_eq!(client.chat_json(&req, Some(&schema)).await.unwrap(), json!({"action": "click"})); + assert_eq!(client.chat_json(&req, Some(&schema)).await.unwrap(), json!({"action": "click"})); + let requests = server.received_requests().await.unwrap(); + assert_eq!(requests.len(), 3, "one failing attempt, then prompt-only is remembered"); + let first: Value = serde_json::from_slice(&requests[0].body).unwrap(); + assert_eq!(first["response_format"]["type"], "json_object"); + assert!(first["messages"][0]["content"].as_str().unwrap().starts_with("Return JSON matching this output schema: ")); + assert_eq!(first["max_tokens"], 4096); + } + + #[test] + fn strict_schema_has_no_optional_parameters() { + let props: Map = (0..36).map(|i| (format!("p{i}"), json!({"type": "string", "maxLength": 5}))).collect(); + let schema = json!({"type": "object", "required": ["p0"], "properties": props, "anyOf": [{"properties": {"e": {"enum": (0..20).collect::>()}}}]}); + assert_eq!(optional_parameter_count(&schema), 36); + let strict = strict_schema(&schema); + assert_eq!(optional_parameter_count(&strict), 0); + assert_eq!(strict["additionalProperties"], false); + assert_eq!(strict["properties"]["p1"]["anyOf"][1]["type"], "null"); + assert!(strict["properties"]["p0"].get("maxLength").is_none()); + assert!(strict["anyOf"][0]["properties"]["e"].get("enum").is_none()); + + let tool = |n: usize| json!({"type":"function","function":{"name":"t","strict":true,"parameters":{"type":"object","properties": (0..n).map(|i| (format!("o{i}"), json!({"type":"string"}))).collect::>()}}}); + let mut tools = vec![tool(20), tool(16), tool(3)]; + limit_optional_parameters(&mut tools, OPTIONAL_PARAMETER_LIMIT); + let total: usize = tools.iter().map(|t| optional_parameter_count(&t["function"]["parameters"])).sum(); + assert_eq!(total, 19, "only the largest tool was rewritten"); + assert!(tools.iter().all(|t| t["function"].get("strict").is_none())); + let mut value = json!({"o1": null, "keep": 1}); + drop_optional_nulls(&mut value, &tool(2)["function"]["parameters"]); + assert_eq!(value, json!({"keep": 1})); + } + + #[test] + fn plain_json_recovers_objects() { + assert_eq!(plain_json("```json\n{\"a\":1}\n```"), r#"{"a":1}"#); + assert_eq!(plain_json(r#"Sure: {"a":"}"} and {"b":2}"#), r#"{"a":"}"}"#); + assert_eq!(plain_json(r#"5OK "#), r#"{"action":"click","label":"OK","x":5}"#); + assert_eq!(plain_json(r#" Correction: {"action":"type","text":"hi"}"#), r#"{"action":"type","text":"hi"}"#); + assert_eq!(plain_json("plain"), "plain"); + } + + #[test] + fn image_rejection_classification() { + assert!(provider_rejects_images(r#"{"error":{"message":"No endpoints found that support image input"}}"#)); + assert!(provider_rejects_images(r#"{"error":{"code":"image_input_not_supported","message":"x"}}"#)); + assert!(!provider_rejects_images(r#"{"error":{"message":"Image too large for this model"}}"#)); + assert!(!provider_rejects_images(r#"{"error":{"message":"Invalid API key"}}"#)); + assert!(!provider_rejects_images("not json")); + } + + #[test] + fn redactor_withholds_partial_prefixes() { + let r = Redactor::new(Some("sk-abcdefgh")); + assert!(r.leaked("xx sk-abcde")); + assert!(!r.leaked("sk-abcd")); + assert_eq!(r.safe_len("hello sk-ab"), 6); + assert_eq!(r.safe_len("hello"), 5); + assert_eq!(scrub("a sk-abcdefgh b", Some("sk-abcdefgh")), "a [REDACTED] b"); + } +}