Skip to content

Initialize packages/nlp-engine with embedding service #108

Closed

Description

@malibio

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:

    1. NodeSpace knowledge (notes, tasks, entities)
    2. 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.md architecture 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-service feature 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

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

Activity

  1. self-assigned this
    on Oct 7, 2025
  2. added a commit that references this issue on Oct 7, 2025
    8cc560d
  3. malibio commented on Oct 7, 2025

    @malibio
    CollaboratorAuthor

    Additional Implementation: Centralized Data Directory & Model Bundling

    As part of this PR, I've also implemented two important improvements:

    1. Centralized ~/.nodespace/ Data Directory

    Database Migration:

    • Old: Platform-specific paths (e.g., ~/Library/Application Support/com.nodespace.app/nodespace.db on macOS)
    • New: Unified ~/.nodespace/database/nodespace.db across all platforms
    • Migration: Automatic on first run - copies existing database seamlessly
    • Benefits:
      • ✅ Consistent location across macOS, Windows, Linux
      • ✅ User-friendly: All data in one visible place
      • ✅ Backup-friendly: Single directory to backup
      • ✅ Easy to find and manage

    Model Storage:

    • Location: ~/.nodespace/models/BAAI-bge-small-en-v1.5/
    • Consistency: Same pattern as database
    • Version updates: Can update models without reinstalling app

    2. Model Bundling for End Users

    The Problem: Users shouldn't need to install huggingface-cli or manually download models.

    The Solution:

    1. During Build (CI/CD):

      • bun run tauri:build downloads models automatically
      • Models bundled with app (~130MB added to bundle)
      • Script: scripts/download-models.ts
    2. First Run:

      • App extracts bundled models to ~/.nodespace/models/
      • Command: ensure_models_installed()
      • Happens transparently
    3. User Experience:

      • ✅ Install app → Works immediately
      • ✅ No manual setup required
      • ✅ Fully offline from first launch
      • ✅ No technical knowledge needed

    Implementation Details

    Files Changed:

    • packages/desktop-app/src-tauri/src/commands/db.rs - Database migration
    • packages/nlp-engine/src/config.rs - Model path resolution
    • scripts/download-models.ts - Build-time model download
    • packages/desktop-app/src-tauri/src/commands/models.rs - Runtime extraction
    • packages/desktop-app/src-tauri/tauri.conf.json - Resource bundling config

    Directory Structure:

    ~/.nodespace/
    ├── database/
    │   └── nodespace.db
    └── models/
        └── BAAI-bge-small-en-v1.5/
            ├── model.onnx
            └── tokenizer.json
    

    This provides a much better developer AND end-user experience! 🎉

  4. added a commit that references this issue on Oct 8, 2025
    d5c45cf
  5. added 4 commits that reference this issue on Feb 4, 2026
    53de5e5
    9cbda30
    52fe0de
    5573d04
  6. added 2 commits that reference this issue on Feb 26, 2026
    cae573e
    447aa50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions