capri-memory: add embed module

This commit is contained in:
nocode committed 2026-11-11 20:20:48 +01:00
1 parent 15bb19eaad
commit 9fc9cdd30b
1 file changed
+140
+140
View File
@@ -0,0 +1,140 @@
//! Memory embeddings through Ollama (Capri `embedding-model.mjs`, `config/Embedding.Modelfile`).
use std::time::Duration;
use anyhow::{bail, Context, Result};
use serde_json::{json, Value};
pub const EMBED_MODEL: &str = "capri-embed:latest";
const BASE_MODEL: &str = "bge-m3:latest";
pub struct Embedder {
http: reqwest::Client,
base: String,
}
fn repair_message() -> String {
format!("Memory model {EMBED_MODEL} is missing. Run Capri Setup again to repair the installation.")
}
impl Embedder {
pub fn new(base_url: &str) -> Self {
let http = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(120))
.build()
.expect("reqwest client");
Self { http, base: base_url.trim_end_matches('/').to_string() }
}
async fn has(&self, name: &str) -> Result<bool> {
let tags: Value = self.http.get(format!("{}/api/tags", self.base)).send().await?.error_for_status()?.json().await?;
Ok(tags["models"].as_array().is_some_and(|m| m.iter().any(|m| m["name"] == name)))
}
/// Creates the CPU alias `capri-embed:latest` from `bge-m3:latest` weights already in the store.
pub async fn ensure_model(&self) -> Result<()> {
if self.has(EMBED_MODEL).await? {
return Ok(());
}
if !self.has(BASE_MODEL).await? {
bail!(repair_message());
}
let created: Value = self
.http
.post(format!("{}/api/create", self.base))
.timeout(Duration::from_secs(60))
.json(&json!({"model": EMBED_MODEL, "from": BASE_MODEL, "parameters": {"num_gpu": 0}, "stream": false}))
.send()
.await
.and_then(|r| r.error_for_status())
.context(repair_message())?
.json()
.await
.unwrap_or(Value::Null);
if created.get("error").is_some() || !self.has(EMBED_MODEL).await? {
bail!(repair_message());
}
Ok(())
}
/// L2-normalized embeddings, one per input.
pub async fn embed(&self, input: &[String]) -> Result<Vec<Vec<f32>>> {
let response = self.http.post(format!("{}/api/embed", self.base)).json(&json!({"model": EMBED_MODEL, "input": input})).send().await?;
let status = response.status();
if !status.is_success() {
bail!("Ollama embed HTTP {}", status.as_u16());
}
let body: Value = response.json().await?;
let Some(list) = body["embeddings"].as_array() else { bail!("Ollama embed response missing embeddings[]") };
if list.len() != input.len() {
bail!("Ollama embed response returned {} embeddings for {} inputs", list.len(), input.len());
}
list.iter()
.map(|e| {
let v: Vec<f32> = e.as_array().context("Ollama embed response contains a non-array embedding")?.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect();
Ok(normalize(v))
})
.collect()
}
}
pub fn normalize(mut v: Vec<f32>) -> Vec<f32> {
let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();
if norm > 0.0 && norm.is_finite() {
v.iter_mut().for_each(|x| *x /= norm);
}
v
}
pub fn to_blob(v: &[f32]) -> Vec<u8> {
v.iter().flat_map(|x| x.to_le_bytes()).collect()
}
pub fn from_blob(b: &[u8]) -> Vec<f32> {
b.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect()
}
pub fn dot(a: &[f32], b: &[f32]) -> f32 {
a.iter().zip(b).map(|(x, y)| x * y).sum()
}
#[cfg(test)]
mod tests {
use super::*;
use wiremock::matchers::{body_partial_json, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
#[tokio::test]
async fn creates_alias_then_embeds_normalized() {
let server = MockServer::start().await;
Mock::given(method("GET")).and(path("/api/tags"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": [{"name": "bge-m3:latest"}]})))
.up_to_n_times(2).mount(&server).await;
Mock::given(method("GET")).and(path("/api/tags"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": [{"name": "bge-m3:latest"}, {"name": EMBED_MODEL}]})))
.mount(&server).await;
Mock::given(method("POST")).and(path("/api/create"))
.and(body_partial_json(json!({"model": EMBED_MODEL, "from": "bge-m3:latest", "parameters": {"num_gpu": 0}, "stream": false})))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"status": "success"}))).expect(1).mount(&server).await;
Mock::given(method("POST")).and(path("/api/embed"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"embeddings": [[3.0, 4.0]]}))).mount(&server).await;
let e = Embedder::new(&server.uri());
e.ensure_model().await.unwrap();
assert_eq!(e.embed(&["x".into()]).await.unwrap(), vec![vec![0.6, 0.8]]);
assert!(e.embed(&["x".into(), "y".into()]).await.is_err(), "count must match");
}
#[tokio::test]
async fn missing_base_model_reports_repair() {
let server = MockServer::start().await;
Mock::given(method("GET")).and(path("/api/tags")).respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": []}))).mount(&server).await;
let err = Embedder::new(&server.uri()).ensure_model().await.unwrap_err().to_string();
assert!(err.contains("Run Capri Setup again"), "{err}");
}
#[test]
fn blob_roundtrip() {
let v = vec![0.25f32, -1.5];
assert_eq!(from_blob(&to_blob(&v)), v);
}
}