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
#[macro_use]
extern crate anyhow;

use anyhow::Result;
use async_trait::async_trait;
use naive::NaiveVectorStore;
use serde::{Deserialize, Serialize};

pub(crate) use document::Document;

pub mod document;
pub mod metrics;
pub mod naive;

pub type Embeddings = Vec<f64>;

#[async_trait]
pub trait Embedder: Send + Sync {
    async fn embed(&self, text: &str) -> Result<Embeddings>;
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Configuration {
    pub source_path: String,
    pub data_path: String,
    pub chunk_size: Option<usize>,
}

#[async_trait]
pub trait VectorStore: Send {
    #[allow(clippy::borrowed_box)]
    async fn new(embedder: Box<dyn Embedder>, config: Configuration) -> Result<Self>
    where
        Self: Sized;

    async fn add(&mut self, document: Document) -> Result<bool>;
    async fn retrieve(&self, query: &str, top_k: usize) -> Result<Vec<(Document, f64)>>;
}

pub async fn factory(
    flavor: &str,
    embedder: Box<dyn Embedder>,
    config: Configuration,
) -> Result<Box<dyn VectorStore>> {
    match flavor {
        "naive" => Ok(Box::new(NaiveVectorStore::new(embedder, config).await?)),
        _ => Err(anyhow!("flavor '{flavor} not supported yet")),
    }
}