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
use serde::Deserialize;

use crate::embeddings::{DocumentEmbeddings, Embedding, EmbeddingError};

pub mod in_memory_store;

#[derive(Debug, thiserror::Error)]
pub enum VectorStoreError {
    #[error("Embedding error: {0}")]
    EmbeddingError(#[from] EmbeddingError),

    /// Json error (e.g.: serialization, deserialization, etc.)
    #[error("Json error: {0}")]
    JsonError(#[from] serde_json::Error),

    #[error("Datastore error: {0}")]
    DatastoreError(#[from] Box<dyn std::error::Error + Send + Sync>),
}

pub trait VectorStore: Send + Sync {
    type Q;

    fn add_documents(
        &mut self,
        documents: Vec<DocumentEmbeddings>,
    ) -> impl std::future::Future<Output = Result<(), VectorStoreError>> + Send;

    fn get_document_embeddings(
        &self,
        id: &str,
    ) -> impl std::future::Future<Output = Result<Option<DocumentEmbeddings>, VectorStoreError>> + Send;

    fn get_document<T: for<'a> Deserialize<'a>>(
        &self,
        id: &str,
    ) -> impl std::future::Future<Output = Result<Option<T>, VectorStoreError>> + Send;

    fn get_document_by_query(
        &self,
        query: Self::Q,
    ) -> impl std::future::Future<Output = Result<Option<DocumentEmbeddings>, VectorStoreError>> + Send;
}

pub trait VectorStoreIndex: Send + Sync {
    fn embed_document(
        &self,
        document: &str,
    ) -> impl std::future::Future<Output = Result<Embedding, VectorStoreError>> + Send;

    /// Get the top n documents based on the distance to the given embedding.
    /// The distance is calculated as the cosine distance between the prompt and
    /// the document embedding.
    /// The result is a list of tuples with the distance and the document.
    fn top_n_from_query(
        &self,
        query: &str,
        n: usize,
    ) -> impl std::future::Future<Output = Result<Vec<(f64, DocumentEmbeddings)>, VectorStoreError>> + Send;

    /// Same as `top_n_from_query` but returns the documents without its embeddings.
    /// The documents are deserialized into the given type.
    fn top_n_documents_from_query<T: for<'a> Deserialize<'a>>(
        &self,
        query: &str,
        n: usize,
    ) -> impl std::future::Future<Output = Result<Vec<(f64, T)>, VectorStoreError>> + Send {
        async move {
            let documents = self.top_n_from_query(query, n).await?;
            Ok(documents
                .into_iter()
                .map(|(distance, doc)| (distance, serde_json::from_value(doc.document).unwrap()))
                .collect())
        }
    }

    /// Same as `top_n_from_query` but returns the document ids only.
    fn top_n_ids_from_query(
        &self,
        query: &str,
        n: usize,
    ) -> impl std::future::Future<Output = Result<Vec<(f64, String)>, VectorStoreError>> + Send
    {
        async move {
            let documents = self.top_n_from_query(query, n).await?;
            Ok(documents
                .into_iter()
                .map(|(distance, doc)| (distance, doc.id))
                .collect())
        }
    }

    /// Get the top n documents based on the distance to the given embedding.
    /// The distance is calculated as the cosine distance between the prompt and
    /// the document embedding.
    /// The result is a list of tuples with the distance and the document.
    fn top_n_from_embedding(
        &self,
        prompt_embedding: &Embedding,
        n: usize,
    ) -> impl std::future::Future<Output = Result<Vec<(f64, DocumentEmbeddings)>, VectorStoreError>> + Send;

    /// Same as `top_n_from_embedding` but returns the documents without its embeddings.
    /// The documents are deserialized into the given type.
    fn top_n_documents_from_embedding<T: for<'a> Deserialize<'a>>(
        &self,
        prompt_embedding: &Embedding,
        n: usize,
    ) -> impl std::future::Future<Output = Result<Vec<(f64, T)>, VectorStoreError>> + Send {
        async move {
            let documents = self.top_n_from_embedding(prompt_embedding, n).await?;
            Ok(documents
                .into_iter()
                .map(|(distance, doc)| (distance, serde_json::from_value(doc.document).unwrap()))
                .collect())
        }
    }

    /// Same as `top_n_from_embedding` but returns the document ids only.
    fn top_n_ids_from_embedding(
        &self,
        prompt_embedding: &Embedding,
        n: usize,
    ) -> impl std::future::Future<Output = Result<Vec<(f64, String)>, VectorStoreError>> + Send
    {
        async move {
            let documents = self.top_n_from_embedding(prompt_embedding, n).await?;
            Ok(documents
                .into_iter()
                .map(|(distance, doc)| (distance, doc.id))
                .collect())
        }
    }
}

pub struct NoIndex;

impl VectorStoreIndex for NoIndex {
    async fn embed_document(&self, _document: &str) -> Result<Embedding, VectorStoreError> {
        Ok(Embedding::default())
    }

    async fn top_n_from_query(
        &self,
        _query: &str,
        _n: usize,
    ) -> Result<Vec<(f64, DocumentEmbeddings)>, VectorStoreError> {
        Ok(vec![])
    }

    async fn top_n_from_embedding(
        &self,
        _prompt_embedding: &Embedding,
        _n: usize,
    ) -> Result<Vec<(f64, DocumentEmbeddings)>, VectorStoreError> {
        Ok(vec![])
    }
}