airust 0.4.17

A modular Rust knowledge engine: lexical search, text matching, optional semantic retrieval and reranking
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
#![doc = include_str!("../docs/SEMANTIC.md")]

use crate::{
    index::validate_entry,
    ranking::{Ranked, TopK},
    Context, Engine, IndexError, KnowledgeEntry,
};
use std::{
    collections::{BTreeMap, BTreeSet},
    sync::Arc,
};
use thiserror::Error;

#[cfg(feature = "local-embeddings")]
pub mod local;

#[derive(Debug, Error)]
#[non_exhaustive]
pub enum EmbeddingError {
    #[cfg(feature = "execution")]
    #[error(transparent)]
    Execution(#[from] crate::execution::ExecutionError),
    #[error("embedding space requires a nonempty model recipe ID and positive dimension")]
    InvalidSpace,
    #[error("expected {expected} vector components, received {actual}")]
    Dimension { expected: usize, actual: usize },
    #[error("vector component {0} is not finite")]
    NonFinite(usize),
    #[error("embedding vector must have a nonzero norm")]
    ZeroVector,
    #[error("embedding spaces do not match: expected {expected:?}, received {actual:?}")]
    SpaceMismatch { expected: String, actual: String },
    #[error("embedding input must not be empty or whitespace-only")]
    EmptyInput,
    #[error("embedding batch size must be positive")]
    BatchSize,
    #[error("provider returned {actual} vectors for {expected} inputs")]
    BatchCount { expected: usize, actual: usize },
    #[error("minimum cosine score must be finite and between -1 and 1")]
    InvalidThreshold,
    #[error("embedding provider failed: {0}")]
    Provider(String),
    #[error(transparent)]
    Index(#[from] IndexError),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmbeddingSpace {
    model: String,
    dimensions: usize,
}

impl EmbeddingSpace {
    pub fn new(model: impl Into<String>, dimensions: usize) -> Result<Self, EmbeddingError> {
        let model = model.into();
        if model.trim().is_empty() || dimensions == 0 {
            return Err(EmbeddingError::InvalidSpace);
        }
        Ok(Self { model, dimensions })
    }

    pub fn model(&self) -> &str {
        &self.model
    }

    pub fn dimensions(&self) -> usize {
        self.dimensions
    }

    pub(crate) fn require(&self, other: &Self) -> Result<(), EmbeddingError> {
        if self == other {
            Ok(())
        } else {
            Err(EmbeddingError::SpaceMismatch {
                expected: format!("{}:{}", self.model, self.dimensions),
                actual: format!("{}:{}", other.model, other.dimensions),
            })
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Embedding {
    space: EmbeddingSpace,
    values: Vec<f32>,
}

impl Embedding {
    pub fn new(space: EmbeddingSpace, mut values: Vec<f32>) -> Result<Self, EmbeddingError> {
        let norm = vector_norm(&values, space.dimensions)?;
        for value in &mut values {
            *value = (f64::from(*value) / norm) as f32;
        }
        Ok(Self { space, values })
    }

    pub fn space(&self) -> &EmbeddingSpace {
        &self.space
    }

    pub fn values(&self) -> &[f32] {
        &self.values
    }

    pub fn cosine(&self, other: &Self) -> Result<f64, EmbeddingError> {
        self.space.require(&other.space)?;
        cosine_similarity(&self.values, &other.values)
    }
}

pub(crate) fn vector_norm(values: &[f32], dimensions: usize) -> Result<f64, EmbeddingError> {
    if values.len() != dimensions || dimensions == 0 {
        return Err(EmbeddingError::Dimension {
            expected: dimensions,
            actual: values.len(),
        });
    }
    let mut squared = 0.0;
    for (index, &value) in values.iter().enumerate() {
        if !value.is_finite() {
            return Err(EmbeddingError::NonFinite(index));
        }
        squared += f64::from(value) * f64::from(value);
    }
    if squared == 0.0 {
        return Err(EmbeddingError::ZeroVector);
    }
    Ok(squared.sqrt())
}

pub fn cosine_similarity(left: &[f32], right: &[f32]) -> Result<f64, EmbeddingError> {
    let left_norm = vector_norm(left, left.len())?;
    let right_norm = vector_norm(right, left.len())?;
    let dot: f64 = left
        .iter()
        .zip(right)
        .map(|(&a, &b)| f64::from(a) * f64::from(b))
        .sum();
    Ok((dot / left_norm / right_norm).clamp(-1.0, 1.0))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EmbeddingPurpose {
    Query,
    Document,
}

pub trait EmbeddingProvider {
    fn space(&self) -> &EmbeddingSpace;

    fn embed(
        &mut self,
        texts: &[&str],
        purpose: EmbeddingPurpose,
    ) -> Result<Vec<Vec<f32>>, EmbeddingError>;
}

pub fn embed_batch(
    provider: &mut (impl EmbeddingProvider + ?Sized),
    texts: &[&str],
    purpose: EmbeddingPurpose,
) -> Result<Vec<Embedding>, EmbeddingError> {
    if texts.iter().any(|text| text.trim().is_empty()) {
        return Err(EmbeddingError::EmptyInput);
    }
    if texts.is_empty() {
        return Ok(Vec::new());
    }
    let space = provider.space().clone();
    let vectors = provider.embed(texts, purpose)?;
    space.require(provider.space())?;
    if vectors.len() != texts.len() {
        return Err(EmbeddingError::BatchCount {
            expected: texts.len(),
            actual: vectors.len(),
        });
    }
    vectors
        .into_iter()
        .map(|vector| Embedding::new(space.clone(), vector))
        .collect()
}

#[derive(Debug, Clone)]
pub struct SemanticSearchOptions {
    #[cfg(feature = "execution")]
    control: Option<crate::execution::WorkControl>,
    limit: usize,
    min_score: f64,
    context: Option<Context>,
}

impl SemanticSearchOptions {
    #[cfg(feature = "execution")]
    fn progress(&self, phase: crate::execution::WorkPhase, completed: usize, total: Option<usize>) {
        if let Some(control) = self.control() {
            control.progress(phase, completed, total);
        }
    }

    #[cfg(feature = "execution")]
    pub fn with_control(mut self, control: crate::execution::WorkControl) -> Self {
        self.control = Some(control);
        self
    }
    #[cfg(feature = "execution")]
    pub fn control(&self) -> Option<&crate::execution::WorkControl> {
        self.control.as_ref()
    }
    fn checkpoint(&self) -> Result<(), EmbeddingError> {
        #[cfg(feature = "execution")]
        if let Some(control) = &self.control {
            control
                .checkpoint()
                .map_err(crate::semantic::EmbeddingError::from)?;
        }
        Ok(())
    }

    pub fn new(limit: usize) -> Self {
        Self {
            limit,
            ..Self::default()
        }
    }

    pub fn with_min_score(mut self, min_score: f64) -> Result<Self, EmbeddingError> {
        if !min_score.is_finite() || !(-1.0..=1.0).contains(&min_score) {
            return Err(EmbeddingError::InvalidThreshold);
        }
        self.min_score = min_score;
        Ok(self)
    }

    pub fn with_context(mut self, context: Context) -> Self {
        self.context = Some(context);
        self
    }

    pub fn limit(&self) -> usize {
        self.limit
    }

    pub fn min_score(&self) -> f64 {
        self.min_score
    }

    pub fn context(&self) -> Option<&Context> {
        self.context.as_ref()
    }
}

impl Default for SemanticSearchOptions {
    fn default() -> Self {
        Self {
            #[cfg(feature = "execution")]
            control: None,
            limit: 10,
            min_score: -1.0,
            context: None,
        }
    }
}

#[derive(Debug, Clone, serde::Serialize)]
#[non_exhaustive]
pub struct SemanticResult<'a> {
    pub entry: &'a KnowledgeEntry,
    pub score: f64,
}

impl Ranked for SemanticResult<'_> {
    fn score(&self) -> f64 {
        self.score
    }
    fn id(&self) -> &str {
        &self.entry.id
    }
}

#[derive(Debug, Clone)]
pub struct SemanticIndex {
    lexical: Engine,
    space: EmbeddingSpace,
    vectors: BTreeMap<String, Arc<Vec<f32>>>,
}

impl SemanticIndex {
    #[cfg(feature = "cache")]
    pub(crate) fn from_cached_parts(
        lexical: Engine,
        space: EmbeddingSpace,
        vectors: BTreeMap<String, Vec<f32>>,
    ) -> Self {
        Self {
            lexical,
            space,
            vectors: vectors
                .into_iter()
                .map(|(id, vector)| (id, Arc::new(vector)))
                .collect(),
        }
    }
    pub fn new(space: EmbeddingSpace) -> Self {
        Self {
            lexical: Engine::new(),
            space,
            vectors: BTreeMap::new(),
        }
    }

    pub fn from_index(
        lexical: Engine,
        provider: &mut (impl EmbeddingProvider + ?Sized),
        batch_size: usize,
    ) -> Result<Self, EmbeddingError> {
        if batch_size == 0 {
            return Err(EmbeddingError::BatchSize);
        }
        let space = provider.space().clone();
        let mut vectors = BTreeMap::new();
        let mut entries = lexical.entries();
        loop {
            let batch: Vec<_> = entries.by_ref().take(batch_size).collect();
            if batch.is_empty() {
                break;
            }
            space.require(provider.space())?;
            let texts: Vec<_> = batch.iter().map(|entry| entry.text.as_str()).collect();
            let embedded = embed_batch(provider, &texts, EmbeddingPurpose::Document)?;
            space.require(provider.space())?;
            for (entry, embedding) in batch.into_iter().zip(embedded) {
                vectors.insert(entry.id.clone(), Arc::new(embedding.values));
            }
        }
        drop(entries);
        Ok(Self {
            lexical,
            space,
            vectors,
        })
    }

    #[cfg(feature = "hnsw")]
    pub(crate) fn shared_embeddings(&self) -> impl Iterator<Item = (&str, Arc<Vec<f32>>)> {
        self.vectors
            .iter()
            .map(|(id, vector)| (id.as_str(), Arc::clone(vector)))
    }

    pub fn space(&self) -> &EmbeddingSpace {
        &self.space
    }
    pub fn lexical(&self) -> &Engine {
        &self.lexical
    }

    pub fn into_lexical(self) -> Engine {
        self.lexical
    }
    pub fn len(&self) -> usize {
        self.lexical.len()
    }
    pub fn is_empty(&self) -> bool {
        self.lexical.is_empty()
    }
    pub fn embedding(&self, id: &str) -> Option<&[f32]> {
        self.vectors.get(id).map(|vector| vector.as_slice())
    }
    #[cfg(feature = "snapshots")]
    pub(crate) fn replace_unchanged_text(
        &mut self,
        entry: KnowledgeEntry,
    ) -> Result<Option<KnowledgeEntry>, EmbeddingError> {
        if self
            .lexical
            .get(&entry.id)
            .is_none_or(|old| old.text != entry.text)
        {
            return Ok(None);
        }
        Ok(self.lexical.upsert(entry)?)
    }

    pub fn upsert_embedded(
        &mut self,
        entry: KnowledgeEntry,
        embedding: Embedding,
    ) -> Result<Option<KnowledgeEntry>, EmbeddingError> {
        self.space.require(embedding.space())?;
        let normalized = validate_entry(&entry)?;
        self.vectors
            .insert(entry.id.clone(), Arc::new(embedding.values));
        Ok(self.lexical.insert_validated(entry, normalized))
    }

    pub fn upsert(
        &mut self,
        entry: KnowledgeEntry,
        provider: &mut (impl EmbeddingProvider + ?Sized),
    ) -> Result<Option<KnowledgeEntry>, EmbeddingError> {
        let normalized = validate_entry(&entry)?;
        self.space.require(provider.space())?;
        let mut embedded = embed_batch(provider, &[&entry.text], EmbeddingPurpose::Document)?;
        self.space.require(provider.space())?;
        let embedding = embedded.pop().expect("validated single embedding");
        self.vectors
            .insert(entry.id.clone(), Arc::new(embedding.values));
        Ok(self.lexical.insert_validated(entry, normalized))
    }

    pub fn upsert_batch(
        &mut self,
        entries: Vec<KnowledgeEntry>,
        provider: &mut (impl EmbeddingProvider + ?Sized),
        batch_size: usize,
    ) -> Result<usize, EmbeddingError> {
        if batch_size == 0 {
            return Err(EmbeddingError::BatchSize);
        }
        self.space.require(provider.space())?;
        let mut ids = BTreeSet::new();
        let mut prepared = Vec::with_capacity(entries.len());
        for entry in entries {
            if !ids.insert(entry.id.clone()) {
                return Err(IndexError::DuplicateId(entry.id).into());
            }
            let normalized = validate_entry(&entry)?;
            prepared.push((entry, normalized));
        }
        let mut embeddings = Vec::with_capacity(prepared.len());
        for batch in prepared.chunks(batch_size) {
            self.space.require(provider.space())?;
            let texts: Vec<_> = batch.iter().map(|(entry, _)| entry.text.as_str()).collect();
            embeddings.extend(embed_batch(provider, &texts, EmbeddingPurpose::Document)?);
            self.space.require(provider.space())?;
        }
        let count = prepared.len();
        for ((entry, normalized), embedding) in prepared.into_iter().zip(embeddings) {
            self.vectors
                .insert(entry.id.clone(), Arc::new(embedding.values));
            self.lexical.insert_validated(entry, normalized);
        }
        Ok(count)
    }

    pub fn remove(&mut self, id: &str) -> Option<KnowledgeEntry> {
        self.vectors.remove(id);
        self.lexical.remove(id)
    }

    pub fn clear(&mut self) {
        self.vectors.clear();
        self.lexical.clear();
    }

    pub fn search(
        &self,
        query: &str,
        provider: &mut (impl EmbeddingProvider + ?Sized),
        options: &SemanticSearchOptions,
    ) -> Result<Vec<SemanticResult<'_>>, EmbeddingError> {
        options.checkpoint()?;
        if query.trim().is_empty() {
            return Err(EmbeddingError::EmptyInput);
        }
        self.space.require(provider.space())?;
        if options.limit == 0 || self.is_empty() {
            return Ok(Vec::new());
        }
        #[cfg(feature = "execution")]
        options.progress(crate::execution::WorkPhase::Embedding, 0, Some(1));
        options.checkpoint()?;
        let embeddings = embed_batch(provider, &[query], EmbeddingPurpose::Query);
        options.checkpoint()?;
        let mut embeddings = embeddings?;
        #[cfg(feature = "execution")]
        options.progress(crate::execution::WorkPhase::Embedding, 1, Some(1));
        self.space.require(provider.space())?;
        self.search_embedding(
            &embeddings.pop().expect("validated single embedding"),
            options,
        )
    }

    pub fn search_embedding(
        &self,
        query: &Embedding,
        options: &SemanticSearchOptions,
    ) -> Result<Vec<SemanticResult<'_>>, EmbeddingError> {
        options.checkpoint()?;
        self.space.require(query.space())?;
        let mut results = TopK::new(options.limit);
        if options.limit == 0 {
            return Ok(Vec::new());
        }
        #[cfg(feature = "execution")]
        options.progress(
            crate::execution::WorkPhase::Ranking,
            0,
            Some(self.vectors.len()),
        );
        for (position, (id, vector)) in self.vectors.iter().enumerate() {
            #[cfg(not(feature = "execution"))]
            let _ = position;
            #[cfg(feature = "execution")]
            if position.is_multiple_of(512) {
                options.progress(
                    crate::execution::WorkPhase::Ranking,
                    position,
                    Some(self.vectors.len()),
                );
            }
            options.checkpoint()?;
            let entry = self
                .lexical
                .get(id)
                .expect("semantic and lexical IDs agree");
            if options
                .context
                .as_ref()
                .is_some_and(|context| !context.includes(entry))
            {
                continue;
            }
            let score = cosine_similarity(query.values(), vector)?;
            if score >= options.min_score {
                results.push(SemanticResult { entry, score });
            }
        }
        options.checkpoint()?;
        let results = results.finish();
        #[cfg(feature = "execution")]
        options.progress(
            crate::execution::WorkPhase::Ranking,
            self.vectors.len(),
            Some(self.vectors.len()),
        );
        options.checkpoint()?;
        Ok(results)
    }
}

#[cfg(feature = "execution")]
pub(crate) struct ControlledProvider<'a> {
    pub(crate) provider: &'a mut dyn EmbeddingProvider,
    pub(crate) control: &'a crate::execution::WorkControl,
}
#[cfg(feature = "execution")]
impl EmbeddingProvider for ControlledProvider<'_> {
    fn space(&self) -> &EmbeddingSpace {
        self.provider.space()
    }
    fn embed(
        &mut self,
        texts: &[&str],
        purpose: EmbeddingPurpose,
    ) -> Result<Vec<Vec<f32>>, EmbeddingError> {
        self.control
            .progress(crate::execution::WorkPhase::Embedding, 0, Some(texts.len()));
        self.control.checkpoint()?;
        let result = self.provider.embed(texts, purpose);
        self.control.checkpoint()?;
        if result.is_ok() {
            self.control.progress(
                crate::execution::WorkPhase::Embedding,
                texts.len(),
                Some(texts.len()),
            );
        }
        result
    }
}