From 13f5016f9d689c0e137109a59207e25a1001a89a Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:48 +0100 Subject: [PATCH] capri-models: add router module --- crates/capri-models/src/router.rs | 213 ++++++++++++++++++++++++++++++ 1 file changed, 213 insertions(+) create mode 100644 crates/capri-models/src/router.rs diff --git a/crates/capri-models/src/router.rs b/crates/capri-models/src/router.rs new file mode 100644 index 0000000..18ae706 --- /dev/null +++ b/crates/capri-models/src/router.rs @@ -0,0 +1,213 @@ +//! Request router (Capri `integrations/request_router`): decides whether a turn is +//! plain English small talk (`fast`: dialogue-only, no action tools) or `normal`. Conservative: +//! any guard hit, error or timeout means `normal`. Embeddings come from the owned Ollama +//! (MiniLM-L6-v2 CPU alias) instead of Python + ONNX; the linear head is Capri's, embedded verbatim. +use std::sync::LazyLock; +use std::time::{Duration, Instant}; + +use anyhow::{ensure, Result}; +use capri_llm::{Ollama, RouterSection}; +use regex::Regex; +use serde::Deserialize; + +static PROTECTED: LazyLock = LazyLock::new(|| { + Regex::new(concat!( + r"(?i)\b(?:remember|forget|save|store|record|recall|notes?|files?|documents?|workspace|", + r"read|write|edit|create|delete|remove|open|copy|move|search|find|check|lookup|", + r"calculate|solve|explain|compare|research|debug|analy[sz]e|plan|prove|translate|", + r"summari[sz]e|count|probability|equation|code|program|algorithm|database|", + r"spotify|songs?|tracks?|playlists?|music|volume|pause|resume|play|skip|repeat|", + r"shuffle|louder|quieter|turn|stop|settings?|screen|microphone|remind|schedule|", + r"timers?|stopwatch|alarms?|elapsed|glitch|enable|disable|appointment|address|birthday|name|weather|news|time|date|price|plus|minus|times|", + r"launch|browser|chrome|firefox|keys?|keyboard|press|click|hold|pointer|cursor|mouse|scroll|discord)\b", + )) + .expect("valid regex") +}); +static CUE: LazyLock = LazyLock::new(|| Regex::new(r"(?i)[0-9`{}=<>/\\]|https?:|\blook\s+up\b").expect("valid regex")); +static REFERENCE: LazyLock = LazyLock::new(|| { + Regex::new(r"(?i)\b(?:it|that|those|these|them|again|same|other|instead|earlier|yesterday|continue|previous|before|next|last|there|which|why|how much|how many)\b").expect("valid regex") +}); + +/// Rule-based abstention evaluated before any embedding; `Some(reason)` means `normal`. +pub fn guard(text: &str, context: &[&str]) -> Option<&'static str> { + if text.trim().is_empty() || text.chars().count() > 400 { + return Some("input-scope"); + } + if text.chars().any(|c| c.is_alphabetic() && !c.is_ascii()) { + return Some("language"); + } + if PROTECTED.is_match(text) || CUE.is_match(text) { + return Some("task-cue"); + } + if REFERENCE.is_match(text) { + return Some("context-required"); + } + // Short replies after a task can refer to its arguments ("a little less", "yes please"). + if text.split_whitespace().count() <= 4 && context.iter().any(|c| PROTECTED.is_match(c)) { + return Some("task-follow-up"); + } + None +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct HeadFile { + schema_version: u32, + threshold: f32, + minimum_similarity: f32, + weights: Vec, + bias: f32, + anchors: Vec>, +} + +/// Logistic head over 384-dim MiniLM embeddings plus nearest-anchor similarity. +pub struct Head(HeadFile); + +pub const DIMENSIONS: usize = 384; +static HEAD: LazyLock = LazyLock::new(|| Head::parse(include_str!("../data/request-router-head.json")).expect("valid router head")); + +impl Head { + pub fn parse(json: &str) -> Result { + let h: HeadFile = serde_json::from_str(json)?; + let finite = |v: &[f32]| v.iter().all(|x| x.is_finite()); + ensure!( + h.schema_version == 1 + && h.weights.len() == DIMENSIONS + && finite(&h.weights) + && h.bias.is_finite() + && (1..=64).contains(&h.anchors.len()) + && h.anchors.iter().all(|a| a.len() == DIMENSIONS && finite(a)) + && (0.5..=1.0).contains(&h.threshold) + && (0.4..=1.0).contains(&h.minimum_similarity), + "Invalid request router head" + ); + Ok(Self(h)) + } + + /// `(fast, score, similarity)` for an embedding (L2-normalized here, ε 1e-9). + pub fn decide(&self, embedding: &[f32]) -> (bool, f32, f32) { + let norm = embedding.iter().map(|x| x * x).sum::().sqrt().max(1e-9); + let v: Vec = embedding.iter().map(|x| x / norm).collect(); + let dot = |a: &[f32]| a.iter().zip(&v).map(|(x, y)| x * y).sum::(); + let logit = (dot(&self.0.weights) + self.0.bias).clamp(-60.0, 60.0); + let score = 1.0 / (1.0 + (-logit).exp()); + let similarity = self.0.anchors.iter().map(|a| dot(a)).fold(f32::MIN, f32::max); + let round = |x: f32| (x * 10_000.0).round() / 10_000.0; + (score >= self.0.threshold && similarity >= self.0.minimum_similarity, round(score), round(similarity)) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// Social small talk: answer with dialogue-only instructions and no action tools. + Fast, + Normal, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Routing { + pub mode: Mode, + /// `simple-dialogue`, `uncertain`, a guard reason, `timeout`, `unavailable`, `disabled`. + pub reason: String, + pub score: Option, + pub similarity: Option, + pub elapsed_ms: u64, +} + +pub struct Router { + client: Ollama, + settings: RouterSection, +} + +impl Router { + pub fn new(client: Ollama, settings: RouterSection) -> Self { + Self { client, settings } + } + + /// Classifies the owner's text with at most the 2 previous user messages (each ≤ 400 chars). + pub async fn classify(&self, text: &str, context: &[&str]) -> Routing { + let started = Instant::now(); + let routing = |mode, reason: &str, score, similarity| Routing { mode, reason: reason.into(), score, similarity, elapsed_ms: started.elapsed().as_millis() as u64 }; + if !self.settings.enabled { + return routing(Mode::Normal, "disabled", None, None); + } + let context: Vec = context.iter().rev().take(2).rev().map(|c| c.chars().take(400).collect()).collect(); + let refs: Vec<&str> = context.iter().map(String::as_str).collect(); + if let Some(reason) = guard(text, &refs) { + return routing(Mode::Normal, reason, None, None); + } + let budget = Duration::from_millis(self.settings.timeout_ms.clamp(25, 250)); + // TODO: the head was fitted on INT8 ONNX embeddings. Ollama's F16 MiniLM is close, but it should + // be re-validated on the 52-case test set before trusting `fast` rates. + match tokio::time::timeout(budget, self.client.embed(&self.settings.model, &[text], -1, budget * 4)).await { + Err(_) => routing(Mode::Normal, "timeout", None, None), + Ok(Ok(vectors)) if vectors.first().is_some_and(|v| v.len() == DIMENSIONS) => { + let (fast, score, similarity) = HEAD.decide(&vectors[0]); + routing(if fast { Mode::Fast } else { Mode::Normal }, if fast { "simple-dialogue" } else { "uncertain" }, Some(score), Some(similarity)) + } + Ok(_) => routing(Mode::Normal, "unavailable", None, None), + } + } + + /// Loads the router alias (one embed of the warm-up text, 15 s). + pub async fn warm_up(&self) -> Result<()> { + self.client.embed(&self.settings.model, &["Hello, how are you?"], -1, Duration::from_secs(15)).await?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + #[test] + fn guard_keeps_tasks_context_and_other_languages_normal() { + let corpus: serde_json::Value = serde_json::from_str(include_str!("../data/request-router-corpus.json")).unwrap(); + // Every protected/mixed test phrase that names a task is stopped before the model. + for text in ["Tell me something cheerful and save it in my notes.", "Good night, pause the music too.", "No, the other one.", "Do that again.", "What is seventeen times twenty-three?", "Hello. Lower Spotify to 25%.", "Привет Капри, как дела?", "Hello, could you calculate 17 / 40 for me?", "TELL ME SOMETHING NICE AND SAVE IT"] { + assert!(guard(text, &[]).is_some(), "{text}"); + } + assert_eq!(guard("Привет", &[]), Some("language")); + assert_eq!(guard("Same as yesterday, please.", &[]), Some("context-required")); + assert_eq!(guard("Yes, please.", &["Play some music"]), Some("task-follow-up")); + assert_eq!(guard("Yes, please.", &["Hi there"]), None); + assert_eq!(guard(&"a".repeat(401), &[]), Some("input-scope")); + let fast_passed = corpus["test"]["fast"].as_array().unwrap().iter().filter(|t| guard(t.as_str().unwrap(), &[]).is_none()).count(); + assert!(fast_passed >= 8, "social phrases reach the classifier ({fast_passed}/16)"); + assert_eq!(guard("Hey Capri, how are you?", &[]), None); + } + + #[test] + fn head_math() { + let head = &*HEAD; + let anchor = head.0.anchors[0].clone(); + let (_, _, similarity) = head.decide(&anchor.iter().map(|x| x * 3.0).collect::>()); + assert!(similarity > 0.999, "scale-invariant similarity {similarity}"); + let away: Vec = head.0.weights.iter().map(|w| -w).collect(); + let (fast, score, _) = head.decide(&away); + assert!(!fast && score < 0.01); + assert!(Head::parse(r#"{"schemaVersion":1,"threshold":0.85,"minimumSimilarity":0.5,"weights":[1],"bias":0,"anchors":[[1]]}"#).is_err()); + } + + #[tokio::test] + async fn classify_via_ollama_embeddings_with_timeout() { + let fast_vector: Vec = HEAD.0.anchors.iter().find(|a| HEAD.decide(a).0).expect("a fast anchor").clone(); + let server = MockServer::start().await; + Mock::given(method("POST")).and(path("/api/embed")).respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"embeddings": [fast_vector]}))).mount(&server).await; + let router = Router::new(Ollama::new(server.uri()), RouterSection::default()); + let r = router.classify("Hey Capri, how are you?", &["older", "Hi", "there friend"]).await; + assert_eq!((r.mode, r.reason.as_str()), (Mode::Fast, "simple-dialogue")); + assert_eq!(router.classify("Open my notes", &[]).await.reason, "task-cue"); + let sent: serde_json::Value = serde_json::from_slice(&server.received_requests().await.unwrap()[0].body).unwrap(); + assert_eq!((sent["model"].as_str(), sent["options"]["num_gpu"].as_i64()), (Some("capri-router:latest"), Some(0))); + + let slow = MockServer::start().await; + Mock::given(method("POST")).respond_with(ResponseTemplate::new(200).set_delay(Duration::from_millis(400)).set_body_string("{}")).mount(&slow).await; + let router = Router::new(Ollama::new(slow.uri()), RouterSection { timeout_ms: 30, ..Default::default() }); + assert_eq!(router.classify("Hey Capri, how are you?", &[]).await.reason, "timeout"); + let off = Router::new(Ollama::new(slow.uri()), RouterSection { enabled: false, ..Default::default() }); + assert_eq!(off.classify("Hi", &[]).await.mode, Mode::Normal); + } +}