174 lines
6.7 KiB
Rust
174 lines
6.7 KiB
Rust
|
|
//! 語意搜尋的地基 (P6, step 2): embeddings from the person's own Ollama.
|
||
|
|
//!
|
||
|
|
//! Memories and indexed documents carry a vector beside their words, so 「那篇講語法的筆記」
|
||
|
|
//! finds a file whose text never says 筆記. Local first: Ollama's embedding endpoint, no key,
|
||
|
|
//! nothing leaves the machine. No Ollama (or no embedding model in it) is a normal state:
|
||
|
|
//! every search just answers with words (FTS + LIKE), a little dumber, fully working.
|
||
|
|
//!
|
||
|
|
//! One background thread does the slow work — finding the model once, embedding new
|
||
|
|
//! memories and document chunks in small batches. The turn never waits on it.
|
||
|
|
|
||
|
|
use std::sync::Mutex;
|
||
|
|
use std::time::{Duration, Instant};
|
||
|
|
|
||
|
|
struct Cfg {
|
||
|
|
/// Ollama's root, e.g. http://localhost:11434 (chat's /v1 is stripped).
|
||
|
|
base: String,
|
||
|
|
model: String,
|
||
|
|
}
|
||
|
|
|
||
|
|
static CFG: Mutex<Option<Option<Cfg>>> = Mutex::new(None);
|
||
|
|
/// Last probe/embed failure: retry only after a while, the turn must not pay for it twice.
|
||
|
|
static DOWN: Mutex<Option<Instant>> = Mutex::new(None);
|
||
|
|
static STARTED: std::sync::Once = std::sync::Once::new();
|
||
|
|
|
||
|
|
/// From the app's settings: Ollama's address (the chat provider's, /v1 stripped) and the
|
||
|
|
/// model picked ("" = find one installed; "off" = semantic search off).
|
||
|
|
pub fn configure(base: &str, model: &str) {
|
||
|
|
let root = base.trim_end_matches("/v1").trim_end_matches('/').to_string();
|
||
|
|
let mut cfg = CFG.lock().unwrap();
|
||
|
|
*cfg = Some(if model == "off" {
|
||
|
|
None
|
||
|
|
} else if !model.is_empty() {
|
||
|
|
Some(Cfg { base: root, model: model.to_string() })
|
||
|
|
} else {
|
||
|
|
probe(&root).map(|model| Cfg { base: root, model })
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
/// An installed embedding model, by the names people use (bge-m3, nomic-embed-text…).
|
||
|
|
fn agent(secs: u64) -> ureq::Agent {
|
||
|
|
ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(secs))).build().into()
|
||
|
|
}
|
||
|
|
|
||
|
|
fn probe(root: &str) -> Option<String> {
|
||
|
|
let v: serde_json::Value = agent(3).get(&format!("{root}/api/tags")).call().ok()?.body_mut().read_json().ok()?;
|
||
|
|
v["models"]
|
||
|
|
.as_array()?
|
||
|
|
.iter()
|
||
|
|
.filter_map(|m| m["name"].as_str())
|
||
|
|
.find(|n| {
|
||
|
|
let n = n.to_lowercase();
|
||
|
|
n.contains("embed") || n.contains("bge") || n.starts_with("m3")
|
||
|
|
})
|
||
|
|
.map(String::from)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Semantic search is on and worth a call right now.
|
||
|
|
pub fn enabled() -> bool {
|
||
|
|
CFG.lock().unwrap().as_ref().is_some_and(|c| c.is_some()) && DOWN.lock().unwrap().map(|t| t.elapsed() > Duration::from_secs(120)).unwrap_or(true)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The chat provider's Ollama address, ready for embedding (the /v1 chat suffix stripped).
|
||
|
|
pub fn ollama_base(stored: &str) -> String {
|
||
|
|
let d = crate::providers::ProviderKind::Ollama.default_base_url();
|
||
|
|
let b = if stored.trim().is_empty() { d.to_string() } else { stored.trim().to_string() };
|
||
|
|
b.trim_end_matches("/v1").trim_end_matches('/').to_string()
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn model() -> String {
|
||
|
|
CFG.lock().unwrap().as_ref().and_then(|c| c.as_ref().map(|c| c.model.clone())).unwrap_or_default()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// One batch of vectors, None when Ollama is not answering (marked down for a while).
|
||
|
|
/// Ollama's /api/embed takes the whole list at once.
|
||
|
|
pub fn embed(texts: &[String]) -> Option<Vec<Vec<f32>>> {
|
||
|
|
if texts.is_empty() {
|
||
|
|
return Some(vec![]);
|
||
|
|
}
|
||
|
|
let (base, model) = CFG.lock().unwrap().as_ref().as_ref().and_then(|c| c.as_ref()).map(|c| (c.base.clone(), c.model.clone()))?;
|
||
|
|
let body = serde_json::json!({"model": model, "input": texts});
|
||
|
|
let out: Result<serde_json::Value, String> = agent(20).post(&format!("{base}/api/embed")).send_json(body).and_then(|mut r| r.body_mut().read_json()).map_err(|e| e.to_string());
|
||
|
|
match out {
|
||
|
|
Ok(v) => {
|
||
|
|
*DOWN.lock().unwrap() = None;
|
||
|
|
let embs = v["embeddings"].as_array()?;
|
||
|
|
if embs.len() != texts.len() {
|
||
|
|
return None;
|
||
|
|
}
|
||
|
|
Some(embs.iter().map(|e| e.as_array().map(|row| row.iter().filter_map(|x| x.as_f64()).map(|x| x as f32).collect()).unwrap_or_default()).collect())
|
||
|
|
}
|
||
|
|
Err(_) => {
|
||
|
|
*DOWN.lock().unwrap() = Some(Instant::now());
|
||
|
|
None
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The slow lane, once per app: index the person's document folders, then keep memory and
|
||
|
|
/// document vectors filled in small batches. Folders move with the settings.
|
||
|
|
pub fn start() {
|
||
|
|
STARTED.call_once(|| {
|
||
|
|
std::thread::spawn(move || loop {
|
||
|
|
std::thread::sleep(Duration::from_secs(20));
|
||
|
|
let folders = crate::app::doc_folders();
|
||
|
|
crate::docindex::sweep(&folders);
|
||
|
|
// New memories and new chunks, a batch at a time.
|
||
|
|
let rows = crate::store::memory_pending(24);
|
||
|
|
if !rows.is_empty() {
|
||
|
|
if let Some(vs) = embed(&rows.iter().map(|(_, t)| t.clone()).collect::<Vec<_>>()) {
|
||
|
|
for ((id, _), v) in rows.iter().zip(vs) {
|
||
|
|
crate::store::memory_set_vec(*id, &v);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
let rows = crate::store::doc_pending(24);
|
||
|
|
if !rows.is_empty() {
|
||
|
|
if let Some(vs) = embed(&rows.iter().map(|(_, t)| t.clone()).collect::<Vec<_>>()) {
|
||
|
|
for ((id, _), v) in rows.iter().zip(vs) {
|
||
|
|
crate::store::doc_set_vec(*id, &v);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
});
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn f32s_to_blob(v: &[f32]) -> Vec<u8> {
|
||
|
|
let mut b = Vec::with_capacity(v.len() * 4);
|
||
|
|
for x in v {
|
||
|
|
b.extend_from_slice(&x.to_le_bytes());
|
||
|
|
}
|
||
|
|
b
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn blob_to_f32s(b: &[u8]) -> Vec<f32> {
|
||
|
|
b.chunks_exact(4).map(|c| f32::from_le_bytes(c.try_into().unwrap())).collect()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Cosine, with the guards a shelf of half-filled vectors deserves.
|
||
|
|
pub fn cosine(a: &[f32], b: &[f32]) -> f32 {
|
||
|
|
let n = a.len().min(b.len());
|
||
|
|
let (mut d, mut x, mut y) = (0f32, 0f32, 0f32);
|
||
|
|
for i in 0..n {
|
||
|
|
d += a[i] * b[i];
|
||
|
|
x += a[i] * a[i];
|
||
|
|
y += b[i] * b[i];
|
||
|
|
}
|
||
|
|
if x == 0.0 || y == 0.0 {
|
||
|
|
return 0.0;
|
||
|
|
}
|
||
|
|
d / (x.sqrt() * y.sqrt())
|
||
|
|
}
|
||
|
|
|
||
|
|
#[cfg(test)]
|
||
|
|
mod tests {
|
||
|
|
use super::*;
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn offline_ollama_is_a_normal_state() {
|
||
|
|
// No Ollama in CI: embedding says "no", searches keep working with words.
|
||
|
|
configure("http://127.0.0.1:1/v1", "");
|
||
|
|
assert!(!enabled(), "a port with nothing behind it means no semantic search");
|
||
|
|
assert!(embed(&vec!["test".to_string()]).is_none());
|
||
|
|
// Off is off, and geometry is sane.
|
||
|
|
configure("http://127.0.0.1:11434", "off");
|
||
|
|
assert!(!enabled());
|
||
|
|
let a = vec![1f32, 0.0, 0.0];
|
||
|
|
let b = vec![0f32, 1.0, 0.0];
|
||
|
|
assert!(cosine(&a, &b) < 1e-6);
|
||
|
|
assert!((cosine(&a, &a) - 1.0).abs() < 1e-6);
|
||
|
|
assert_eq!(blob_to_f32s(&f32s_to_blob(&a)), a);
|
||
|
|
}
|
||
|
|
}
|