Repository navigation
Closed
Labels
Description
Overview
Implement a unified vector embedding service using Candle + ONNX for semantic search across NodeSpace knowledge graphs and codebases.
Context
Purpose: Generate high-quality embeddings for semantic search and vector similarity matching
Scope: Foundation for both knowledge management (#107) and codebase search (future)
Architecture: Candle + ONNX (aligned with existing BERT intent classification stack)
Technical Decisions
-
Model:
BAAI/bge-small-en-v1.5(384 dimensions)- Superior retrieval quality vs all-MiniLM-L6-v2
- Better code understanding (trained on technical content)
- Actively maintained (2023+)
- MTEB benchmark: 62.0 avg (top-tier for small models)
-
Runtime: Candle + candle-onnx
- Reuses existing Candle stack from BERT classification
- Metal GPU acceleration (macOS)
- ONNX format for optimal embedding performance
- Follows bert-implementation-guide.md patterns
-
Use Cases:
- NodeSpace knowledge (notes, tasks, entities)
- Codebase semantic search (async background indexing)
Implementation Tasks
Core Service
- Create embedding service following Candle patterns (mirror BERT implementation)
- Implement model downloading from HuggingFace Hub
- Add Metal GPU acceleration support
- Create embedding generation API (single + batch)
- Implement F32_BLOB conversion for Turso storage
- Add caching layer (DashMap, similar to BERT)
Integration
- Follow
bert-implementation-guide.mdarchitecture patterns - Integrate with existing Candle infrastructure
- Add feature flag:
embedding-service - Support both sync and async embedding generation
Testing
- Unit tests for embedding generation
- Batch operation performance tests
- Model loading and caching tests
- F32_BLOB format compatibility tests
Acceptance Criteria
- Embedding service compiles with
embedding-servicefeature flag - bge-small-en-v1.5 downloads and loads via HuggingFace Hub
- Embedding generation produces consistent 384-dim vectors
- Model caching works offline-first (downloaded once)
- Batch operations handle 100+ texts efficiently
- Metal GPU acceleration works on macOS
- F32_BLOB format compatible with Turso vec_distance_cosine()
- API provides async embedding generation
- Cache provides <5ms latency for repeated embeddings
- Memory usage reasonable (<500MB for model + cache)
Technical Specifications
Dependencies:
[dependencies]
# Reuse existing Candle stack
candle-core = { git = "https://github.com/huggingface/candle.git", features = ["metal"] }
candle-nn = { git = "https://github.com/huggingface/candle.git" }
candle-onnx = { git = "https://github.com/huggingface/candle.git" }
tokenizers = { version = "0.15", default-features = false, features = ["onig"] }
hf-hub = "0.4.2"
dashmap = "5.0"
[features]
default = ["embedding-service"]
embedding-service = ["candle-core", "candle-onnx", "tokenizers", "hf-hub"]Service Implementation (follows BERT patterns from bert-implementation-guide.md):
use candle_core::{Device, Tensor};
use candle_onnx;
use dashmap::DashMap;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct EmbeddingConfig {
pub model_name: String, // "BAAI/bge-small-en-v1.5"
pub max_sequence_length: usize, // 512 tokens
pub use_instruction_prefix: bool, // Enable query prefixes
}
impl Default for EmbeddingConfig {
fn default() -> Self {
Self {
model_name: "BAAI/bge-small-en-v1.5".to_string(),
max_sequence_length: 512,
use_instruction_prefix: false,
}
}
}
pub struct EmbeddingService {
config: EmbeddingConfig,
#[cfg(feature = "embedding-service")]
model: Option<candle_onnx::ONNXModel>,
#[cfg(feature = "embedding-service")]
tokenizer: Option<Tokenizer>,
device: Device,
cache: Arc<DashMap<String, Vec<f32>>>,
initialized: bool,
}
impl EmbeddingService {
pub fn new(config: EmbeddingConfig) -> Result<Self> {
let device = Device::new_metal(0).unwrap_or(Device::Cpu);
Ok(Self {
config,
#[cfg(feature = "embedding-service")]
model: None,
#[cfg(feature = "embedding-service")]
tokenizer: None,
device,
cache: Arc::new(DashMap::new()),
initialized: false,
})
}
pub async fn initialize(&mut self) -> Result<()> {
if self.initialized {
return Ok(());
}
#[cfg(feature = "embedding-service")]
{
use hf_hub::api::tokio::Api;
tracing::info!("Loading embedding model: {}", self.config.model_name);
let api = Api::new()?;
let repo = api.model(self.config.model_name.clone());
// Download ONNX model and tokenizer
let model_file = repo.get("onnx/model.onnx").await?;
let tokenizer_file = repo.get("tokenizer.json").await?;
let model = candle_onnx::read_file(model_file, &self.device)?;
let tokenizer = Tokenizer::from_file(tokenizer_file)?;
self.model = Some(model);
self.tokenizer = Some(tokenizer);
tracing::info!("Embedding model initialized successfully");
}
self.initialized = true;
Ok(())
}
pub async fn generate_embedding(&self, text: &str) -> Result<Vec<f32>> {
// Check cache first
if let Some(cached) = self.cache.get(text) {
return Ok(cached.clone());
}
if !self.initialized {
return Err("Model not initialized".into());
}
#[cfg(feature = "embedding-service")]
{
let embedding = self.generate_embedding_internal(text).await?;
self.cache.insert(text.to_string(), embedding.clone());
Ok(embedding)
}
#[cfg(not(feature = "embedding-service"))]
{
// Stub: return zero vector
Ok(vec![0.0; 384])
}
}
pub async fn generate_batch(&self, texts: Vec<&str>) -> Result<Vec<Vec<f32>>> {
let mut results = Vec::with_capacity(texts.len());
for text in texts {
results.push(self.generate_embedding(text).await?);
}
Ok(results)
}
// Convert to F32_BLOB for Turso storage
pub fn to_blob(embedding: &[f32]) -> Vec<u8> {
embedding.iter()
.flat_map(|f| f.to_le_bytes())
.collect()
}
pub fn from_blob(blob: &[u8]) -> Vec<f32> {
blob.chunks_exact(4)
.map(|bytes| f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
.collect()
}
}Dependencies
- Prerequisite: BERT intent classification (Add intent classification for natural language commands #109) - shares Candle infrastructure
- Enables: Semantic search implementation (Semantic search: validation, benchmarks, and documentation #107)
Migration Path
Phase 1 (this issue): Single model for everything
- bge-small-en-v1.5 → knowledge + code
Phase 2 (future): Specialized models if needed
- bge-small-en-v1.5 → knowledge
- nomic-embed-text → code (768 dims, better code quality)
Performance Targets
- Model loading: <30 seconds (ONNX format)
- Single embedding: <10ms (Metal GPU)
- Batch 100 embeddings: <500ms
- Cache hit latency: <5ms
- Memory footprint: <500MB (model + cache)
References
- BERT Implementation Guide
- Technology Stack
- BAAI/bge-small-en-v1.5 model card
- MTEB Leaderboard
Activity
Initialize packages/nlp-engine with embedding service (closes #108)
malibio commentedon Oct 7, 2025
Additional Implementation: Centralized Data Directory & Model Bundling
As part of this PR, I've also implemented two important improvements:
1. Centralized
~/.nodespace/Data DirectoryDatabase Migration:
~/Library/Application Support/com.nodespace.app/nodespace.dbon macOS)~/.nodespace/database/nodespace.dbacross all platformsModel Storage:
~/.nodespace/models/BAAI-bge-small-en-v1.5/2. Model Bundling for End Users
The Problem: Users shouldn't need to install
huggingface-clior manually download models.The Solution:
During Build (CI/CD):
bun run tauri:builddownloads models automaticallyscripts/download-models.tsFirst Run:
~/.nodespace/models/ensure_models_installed()User Experience:
Implementation Details
Files Changed:
packages/desktop-app/src-tauri/src/commands/db.rs- Database migrationpackages/nlp-engine/src/config.rs- Model path resolutionscripts/download-models.ts- Build-time model downloadpackages/desktop-app/src-tauri/src/commands/models.rs- Runtime extractionpackages/desktop-app/src-tauri/tauri.conf.json- Resource bundling configDirectory Structure:
This provides a much better developer AND end-user experience! 🎉
Address all code review findings for PR #108
Initialize packages/nlp-engine with embedding service (#182)
chore(deps): prepare for baseline-browser-mapping env var fix
Initialize packages/nlp-engine with embedding service (#182)
chore(deps): prepare for baseline-browser-mapping env var fix
Initialize packages/nlp-engine with embedding service (#182)
chore(deps): prepare for baseline-browser-mapping env var fix
Initialize packages/nlp-engine with embedding service (#182)
chore(deps): prepare for baseline-browser-mapping env var fix