cortex-rs
Pure compiled native Rust memory engine with vector search and SQLite WAL
Brought by drakestapleton
cortex-rs / src / embeddings.rs
| 1 | use reqwest::Client; |
| 2 | use serde_json::json; |
| 3 | use std::time::Duration; |
| 4 | |
| 5 | pub const EMBEDDING_DIMENSIONS: usize = 768; |
| 6 | |
| 7 | pub fn embedding_to_bytes(v: &[f32]) -> Vec<u8> { |
| 8 | let mut bytes = Vec::with_capacity(v.len() * 4); |
| 9 | for &f in v { |
| 10 | bytes.extend_from_slice(&f.to_le_bytes()); |
| 11 | } |
| 12 | bytes |
| 13 | } |
| 14 | |
| 15 | pub fn bytes_to_embedding(b: &[u8]) -> Vec<f32> { |
| 16 | let mut v = Vec::with_capacity(b.len() / 4); |
| 17 | for chunk in b.chunks_exact(4) { |
| 18 | let arr: [u8; 4] = [chunk[0], chunk[1], chunk[2], chunk[3]]; |
| 19 | v.push(f32::from_le_bytes(arr)); |
| 20 | } |
| 21 | v |
| 22 | } |
| 23 | |
| 24 | pub fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 { |
| 25 | if a.len() != b.len() || a.is_empty() { |
| 26 | return 0.0; |
| 27 | } |
| 28 | let mut dot = 0.0f32; |
| 29 | let mut norm_a = 0.0f32; |
| 30 | let mut norm_b = 0.0f32; |
| 31 | for i in 0..a.len() { |
| 32 | dot += a[i] * b[i]; |
| 33 | norm_a += a[i] * a[i]; |
| 34 | norm_b += b[i] * b[i]; |
| 35 | } |
| 36 | let denom = norm_a.sqrt() * norm_b.sqrt(); |
| 37 | if denom > 0.0 { |
| 38 | dot / denom |
| 39 | } else { |
| 40 | 0.0 |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | pub fn cosine_distance(a: &[f32], b: &[f32]) -> f32 { |
| 45 | 1.0 - cosine_similarity(a, b) |
| 46 | } |
| 47 | |
| 48 | pub async fn fetch_embedding(client: &Client, text: &str, encoder_url: &str) -> Result<Vec<f32>, String> { |
| 49 | let payload = json!({ |
| 50 | "text": text, |
| 51 | "modelId": "BAAI/bge-base-en-v1.5", |
| 52 | "modelRevision": "cortex-bge-base-en-v1.5-768-v1", |
| 53 | "priority": "recall" |
| 54 | }); |
| 55 | |
| 56 | let resp = client |
| 57 | .post(format!("{}/embed", encoder_url.trim_end_matches("/"))) |
| 58 | .timeout(Duration::from_millis(1500)) |
| 59 | .json(&payload) |
| 60 | .send() |
| 61 | .await |
| 62 | .map_err(|e| format!("Failed to connect to embedding encoder on {}: {}", encoder_url, e))?; |
| 63 | |
| 64 | if !resp.status().is_success() { |
| 65 | let status = resp.status(); |
| 66 | let body = resp.text().await.unwrap_or_default(); |
| 67 | return Err(format!("Encoder returned error HTTP {}: {}", status, body)); |
| 68 | } |
| 69 | |
| 70 | let val: serde_json::Value = resp.json().await |
| 71 | .map_err(|e| format!("Failed to parse embedding response JSON: {}", e))?; |
| 72 | |
| 73 | if let Some(arr) = val.get("embedding").and_then(|v| v.as_array()) { |
| 74 | let mut emb = Vec::with_capacity(arr.len()); |
| 75 | for num in arr { |
| 76 | if let Some(f) = num.as_f64() { |
| 77 | emb.push(f as f32); |
| 78 | } |
| 79 | } |
| 80 | if emb.len() == EMBEDDING_DIMENSIONS { |
| 81 | return Ok(emb); |
| 82 | } else { |
| 83 | return Err(format!("Expected {} dimensions, got {}", EMBEDDING_DIMENSIONS, emb.len())); |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | Err("Invalid embedding payload structure from encoder service".to_string()) |
| 88 | } |
| 89 | |
| 90 | #[cfg(test)] |
| 91 | mod tests { |
| 92 | use super::*; |
| 93 | |
| 94 | #[test] |
| 95 | fn test_embedding_bytes_roundtrip() { |
| 96 | let orig = vec![0.123f32, -0.456, 0.789, 1.0]; |
| 97 | let bytes = embedding_to_bytes(&orig); |
| 98 | assert_eq!(bytes.len(), 16); |
| 99 | let recovered = bytes_to_embedding(&bytes); |
| 100 | assert_eq!(orig, recovered); |
| 101 | } |
| 102 | |
| 103 | #[test] |
| 104 | fn test_cosine_similarity() { |
| 105 | let a = vec![1.0f32, 0.0, 0.0]; |
| 106 | let b = vec![1.0f32, 0.0, 0.0]; |
| 107 | assert!((cosine_similarity(&a, &b) - 1.0).abs() < 1e-5); |
| 108 | |
| 109 | let c = vec![0.0f32, 1.0, 0.0]; |
| 110 | assert!((cosine_similarity(&a, &c) - 0.0).abs() < 1e-5); |
| 111 | } |
| 112 | |
| 113 | #[test] |
| 114 | fn test_cosine_distance_and_empty_handling() { |
| 115 | let a = vec![1.0f32, 0.0, 0.0]; |
| 116 | let b = vec![1.0f32, 0.0, 0.0]; |
| 117 | assert!((cosine_distance(&a, &b) - 0.0).abs() < 1e-5); |
| 118 | |
| 119 | let orthogonal = vec![0.0f32, 1.0, 0.0]; |
| 120 | assert!((cosine_distance(&a, &orthogonal) - 1.0).abs() < 1e-5); |
| 121 | |
| 122 | let opposite = vec![-1.0f32, 0.0, 0.0]; |
| 123 | assert!((cosine_distance(&a, &opposite) - 2.0).abs() < 1e-5); |
| 124 | |
| 125 | let empty: Vec<f32> = vec![]; |
| 126 | assert_eq!(cosine_similarity(&empty, &empty), 0.0); |
| 127 | assert_eq!(cosine_distance(&empty, &empty), 1.0); |
| 128 | |
| 129 | let mismatched = vec![1.0f32, 0.0]; |
| 130 | assert_eq!(cosine_similarity(&a, &mismatched), 0.0); |
| 131 | assert_eq!(cosine_distance(&a, &mismatched), 1.0); |
| 132 | |
| 133 | let zeros = vec![0.0f32, 0.0, 0.0]; |
| 134 | assert_eq!(cosine_similarity(&zeros, &zeros), 0.0); |
| 135 | assert_eq!(cosine_distance(&zeros, &zeros), 1.0); |
| 136 | } |
| 137 | } |