//! 語意搜尋: vectors for memories and indexed documents, so 「那篇講語法的筆記」 finds a file
//! whose text never says 筆記.
//!
//! Local by default: a Model2Vec static model (minishlab/potion-multilingual-128M, distilled from
//! bge-m3, 100+ languages) runs inside AnyBot (m2v.rs) — no key, no service, nothing leaves the
//! machine. It is fetched once (530 MB from Hugging Face, kept as 130 MB of int8: converted while
//! it downloads), loaded when needed (~0.03 s, ~220 MB) and let go after ten idle minutes.
//! The person's Ollama can be chosen instead ("ollama" or a model name in `embed_model`).
//! Without vectors every search still answers with words (memstore.rs), a little dumber.
//!
//! One background thread does the slow work — the download, the document sweep, embedding new
//! memories and chunks in batches. A turn never waits on it.
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
/// The local model, by its Hugging Face name.
pub const LOCAL_MODEL: &str = "minishlab/potion-multilingual-128M";
/// Hugging Face, or a mirror of it (ANYBOT_HF_BASE, e.g. https://hf-mirror.com).
fn hub() -> String {
std::env::var("ANYBOT_HF_BASE").ok().map(|s| s.trim().trim_end_matches('/').to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| "https://huggingface.co".into())
}
/// Let the model go after this long unused (it comes back in 0.03 s).
const IDLE_UNLOAD: Duration = Duration::from_secs(600);
#[derive(Clone, Debug, PartialEq)]
enum Engine {
Off,
Local,
/// Ollama's root (http://localhost:11434) and its embedding model ("" = not found yet).
Ollama { base: String, model: String },
}
static ENGINE: Mutex> = Mutex::new(None);
/// Last Ollama failure: retry only after a while, the turn must not pay for it twice.
static DOWN: Mutex > = Mutex::new(None);
static STARTED: std::sync::Once = std::sync::Once::new();
// The local model: loaded on use, dropped when idle.
static MODEL: Mutex , Instant)>> = Mutex::new(None);
static FETCHING: AtomicBool = AtomicBool::new(false);
static GOT: AtomicU64 = AtomicU64::new(0);
static TOTAL: AtomicU64 = AtomicU64::new(0);
static FETCH_ERR: Mutex > = Mutex::new(None);
/// How long the last load took (ms), for the settings and `make doctor`.
static LOAD_MS: Mutex > = Mutex::new(None);
/// Loaded now, and how long its last load took.
pub fn local_info() -> (bool, Option) {
(MODEL.lock().unwrap().is_some(), *LOAD_MS.lock().unwrap())
}
/// From the app's settings: Ollama's address (the chat provider's, /v1 stripped) and the choice
/// ("" or "local" = the local model; "off"; "ollama" = find one in Ollama; anything else = that
/// Ollama model). A different engine makes different vectors: they are all made again.
pub fn configure(base: &str, choice: &str) {
let root = base.trim_end_matches("/v1").trim_end_matches('/').to_string();
let e = match choice.trim() {
"off" => Engine::Off,
"" | "local" => Engine::Local,
"ollama" => Engine::Ollama { model: probe(&root).unwrap_or_default(), base: root },
m => Engine::Ollama { base: root, model: m.to_string() },
};
let id = engine_id(&e);
*ENGINE.lock().unwrap() = Some(e);
crate::store::ensure_engine(&id);
}
/// Whether this AnyBot needs the local model at all: the brain does (memories live there); a
/// screen only for its own document folders; hands and a phone never. Not wanted: never fetched
/// nor loaded here, and a loaded one is let go.
static WANTED: AtomicBool = AtomicBool::new(true);
pub fn set_wanted(on: bool) {
if WANTED.swap(on, Ordering::Relaxed) && !on {
*MODEL.lock().unwrap() = None;
}
}
fn wanted() -> bool {
WANTED.load(Ordering::Relaxed)
}
fn engine() -> Engine {
ENGINE.lock().unwrap().clone().unwrap_or(Engine::Off)
}
fn engine_id(e: &Engine) -> String {
match e {
Engine::Off => String::new(),
Engine::Local => format!("m2v:{LOCAL_MODEL}"),
Engine::Ollama { model, .. } if !model.is_empty() => format!("ollama:{model}"),
Engine::Ollama { .. } => String::new(),
}
}
fn agent(secs: u64) -> ureq::Agent {
ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(secs))).build().into()
}
/// An installed embedding model in Ollama, by the names people use (bge-m3, nomic-embed-text…).
fn probe(root: &str) -> Option {
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)
}
/// 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()
}
/// Semantic search is on and worth a call right now.
pub fn enabled() -> bool {
match engine() {
Engine::Off => false,
Engine::Local => local_ready(),
Engine::Ollama { model, .. } => !model.is_empty() && DOWN.lock().unwrap().map(|t| t.elapsed() > Duration::from_secs(120)).unwrap_or(true),
}
}
/// What the settings show, in the person's words.
pub fn status() -> String {
match engine() {
Engine::Off => "關著:搜尋只用關鍵字(一樣能用,只是聽不懂換句話說)".into(),
Engine::Ollama { model, .. } if model.is_empty() => "用 Ollama:沒找到 embedding 模型(裝一個 bge-m3 或 nomic-embed-text),現在只用關鍵字".into(),
Engine::Ollama { model, .. } => format!("用你的 Ollama({model})"),
Engine::Local if !wanted() => "本機模型:這台不用載(記憶在大腦上算;這台設了文件索引資料夾才會載入)".into(),
Engine::Local if local_ready() => match local_info() {
(true, Some(ms)) => format!("本機模型就緒,已載入({ms:.0} 毫秒):在這台電腦上算,什麼都不上傳"),
_ => "本機模型就緒:要用時才載入(約 0.03 秒),閒置 10 分鐘放掉".into(),
},
Engine::Local if FETCHING.load(Ordering::Relaxed) => {
let (got, total) = (GOT.load(Ordering::Relaxed), TOTAL.load(Ordering::Relaxed));
if total > 0 {
format!("正在下載本機模型:{}%({} / {} MB),好了會自己開始", got * 100 / total, got >> 20, total >> 20)
} else {
"正在下載本機模型…".into()
}
}
Engine::Local => match FETCH_ERR.lock().unwrap().clone() {
Some((e, _)) => format!("本機模型還沒下載成功({e}),過幾分鐘會再試;這段時間只用關鍵字"),
None => "準備下載本機模型(約 530 MB,一次就好)".into(),
},
}
}
// ---------- the local model ----------
fn model_dir() -> std::path::PathBuf {
let base = if cfg!(test) { std::env::temp_dir().join(format!("anybot-models-test-{}", std::process::id())) } else { crate::model::State::path().parent().map(|p| p.join("models")).unwrap_or_else(|| std::env::temp_dir().join("anybot-models")) };
base.join(LOCAL_MODEL.rsplit('/').next().unwrap_or("model"))
}
fn local_ready() -> bool {
wanted() && (MODEL.lock().unwrap().is_some() || model_dir().join("dims.json").is_file())
}
/// The loaded model (loading it if it's on disk).
fn local() -> Option> {
let mut g = MODEL.lock().unwrap();
if let Some((m, t)) = g.as_mut() {
*t = Instant::now();
return Some(m.clone());
}
let dir = model_dir();
if !wanted() || !dir.join("dims.json").is_file() {
return None;
}
let t = Instant::now();
match crate::m2v::Model::load(&dir) {
Ok(m) => {
let m = Arc::new(m);
*LOAD_MS.lock().unwrap() = Some(t.elapsed().as_secs_f64() * 1000.0);
*g = Some((m.clone(), Instant::now()));
Some(m)
}
Err(e) => {
// A broken copy (a disk filled up halfway): fetch it again.
eprintln!("AnyBot:本機語意模型讀不了({e}),重新下載");
let _ = std::fs::remove_file(dir.join("dims.json"));
None
}
}
}
fn unload_if_idle() {
let mut g = MODEL.lock().unwrap();
if g.as_ref().map(|(_, t)| t.elapsed() > IDLE_UNLOAD).unwrap_or(false) {
*g = None;
}
}
/// Download the model once: the vocabulary into vocab.bin, the table straight from the stream
/// into int8 (table.i8). dims.json last: it says the rest is complete.
fn fetch_local() -> Result<(), String> {
let dir = model_dir();
std::fs::create_dir_all(&dir).map_err(|e| format!("建不了資料夾:{e}"))?;
let url = |f: &str| format!("{}/{LOCAL_MODEL}/resolve/main/{f}", hub());
// No limit on the whole download (512 MB on a slow line takes a while): only on silence.
let net: ureq::Agent = ureq::Agent::config_builder().timeout_connect(Some(Duration::from_secs(30))).timeout_recv_response(Some(Duration::from_secs(60))).timeout_per_read(Some(Duration::from_secs(60))).build().into();
let why = |e: ureq::Error| format!("連不到 Hugging Face:{e}");
let mut r = net.get(&url("tokenizer.json")).call().map_err(why)?;
let tok = r.body_mut().with_config().limit(64 << 20).read_to_vec().map_err(|e| format!("字表沒下載完:{e}"))?;
let part = dir.join("vocab.bin.part");
let mut f = std::io::BufWriter::new(std::fs::File::create(&part).map_err(|e| e.to_string())?);
let (count, unk, median) = crate::m2v::convert_vocab(&tok, &mut f)?;
drop(f);
drop(tok);
std::fs::rename(&part, dir.join("vocab.bin")).map_err(|e| e.to_string())?;
let mut r = net.get(&url("model.safetensors")).call().map_err(why)?;
TOTAL.store(r.headers().get("content-length").and_then(|v| v.to_str().ok()).and_then(|v| v.parse().ok()).unwrap_or(0), Ordering::Relaxed);
GOT.store(0, Ordering::Relaxed);
struct Counted(R);
impl std::io::Read for Counted {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result {
let n = self.0.read(buf)?;
GOT.fetch_add(n as u64, Ordering::Relaxed);
Ok(n)
}
}
let part = dir.join("table.i8.part");
let mut f = std::io::BufWriter::with_capacity(1 << 20, std::fs::File::create(&part).map_err(|e| e.to_string())?);
let body = Counted(std::io::BufReader::with_capacity(1 << 20, r.body_mut().with_config().limit(u64::MAX).reader()));
let (rows, dim) = crate::m2v::quantize(body, &mut f).map_err(|e| format!("模型沒下載完:{e}"))?;
use std::io::Write;
f.flush().map_err(|e| e.to_string())?;
drop(f);
if rows != count {
return Err("模型的字表和向量表對不上".into());
}
std::fs::rename(&part, dir.join("table.i8")).map_err(|e| e.to_string())?;
std::fs::write(dir.join("dims.json"), serde_json::json!({"model": LOCAL_MODEL, "rows": rows, "dim": dim, "median": median, "unk": unk}).to_string()).map_err(|e| e.to_string())?;
Ok(())
}
/// Start the download once (and again after a failure, five minutes later).
fn ensure_local() {
if engine() != Engine::Local || !wanted() || local_ready() || FETCHING.load(Ordering::SeqCst) {
return;
}
if FETCH_ERR.lock().unwrap().as_ref().map(|(_, t)| t.elapsed() < Duration::from_secs(300)).unwrap_or(false) {
return;
}
if cfg!(test) {
return;
}
FETCHING.store(true, Ordering::SeqCst);
std::thread::spawn(|| {
let r = fetch_local();
match &r {
Ok(()) => {
*FETCH_ERR.lock().unwrap() = None;
eprintln!("AnyBot:本機語意模型就緒({})", model_dir().display());
}
Err(e) => {
eprintln!("AnyBot:本機語意模型下載失敗:{e}");
*FETCH_ERR.lock().unwrap() = Some((e.clone(), Instant::now()));
}
}
FETCHING.store(false, Ordering::SeqCst);
});
}
// ---------- embedding ----------
/// One batch of vectors; None when the engine can't answer now (off, downloading, Ollama away).
pub fn embed(texts: &[String]) -> Option>> {
if texts.is_empty() {
return Some(vec![]);
}
match engine() {
Engine::Off => None,
Engine::Local => {
let m = local()?;
Some(texts.iter().map(|t| m.encode(t)).collect())
}
Engine::Ollama { base, model } => {
if model.is_empty() {
return None;
}
// Ollama's /api/embed takes the whole list at once.
let body = serde_json::json!({"model": model, "input": texts});
let out: Result = 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: fetch the local model, index the person's document folders,
/// then keep memory and document vectors filled in batches. Folders move with the settings.
pub fn start() {
STARTED.call_once(|| {
// The daily compaction (store::compact): ten minutes after start, then once a day.
let mut next_compact = Instant::now() + Duration::from_secs(600);
std::thread::spawn(move || loop {
std::thread::sleep(Duration::from_secs(20));
if Instant::now() >= next_compact {
next_compact = Instant::now() + Duration::from_secs(86_400);
crate::store::compact();
}
ensure_local();
let folders = crate::app::doc_folders();
crate::docindex::sweep(&folders);
// The local model takes thousands a second; Ollama a few dozen a call.
let batch = if engine() == Engine::Local { 2000 } else { 24 };
if enabled() {
let rows = crate::store::memory_pending(batch);
if !rows.is_empty() {
if let Some(vs) = embed(&rows.iter().map(|(_, t)| t.clone()).collect::>()) {
crate::memstore::set_vecs(&rows.iter().map(|(id, _)| *id).zip(vs).collect::>());
}
}
let rows = crate::store::doc_pending(batch);
if !rows.is_empty() {
if let Some(vs) = embed(&rows.iter().map(|(_, t)| t.clone()).collect::>()) {
crate::store::doc_set_vecs(&rows.iter().map(|(id, _)| *id).zip(vs).collect::>());
}
}
}
unload_if_idle();
});
});
}
pub fn f32s_to_blob(v: &[f32]) -> Vec {
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 {
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 no_model_is_a_normal_state() {
// No Ollama in CI, and the local model is never fetched in tests: searches keep working
// with words.
configure("http://127.0.0.1:1/v1", "ollama");
assert!(!enabled(), "a port with nothing behind it means no semantic search");
assert!(embed(&vec!["test".to_string()]).is_none());
configure("http://127.0.0.1:11434", "off");
assert!(!enabled());
configure("http://127.0.0.1:11434", "");
assert!(!enabled() && status().contains("本機模型"), "{}", status());
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);
configure("http://127.0.0.1:11434", "off");
}
}