Skip to main content

larastvel_core/ai/
vector_store.rs

1//! Vector stores — the Rust equivalent of Laravel 13's `VectorStore` from
2//! `laravel/ai`.
3//!
4//! A vector store ingests documents, embeds them, and answers similarity
5//! queries. Two implementations ship with the framework:
6//!
7//! - [`FileVectorStore`] — a local JSON-file store, no database needed.
8//! - [`PostgresVectorStore`] — PostgreSQL + `pgvector` (the Laravel default
9//!   backing store); use `VectorSimilarityQuery` for ad-hoc semantic search
10//!   on your own tables.
11
12use sea_orm::ConnectionTrait;
13use serde::{Deserialize, Serialize};
14use serde_json::Value;
15use std::path::Path;
16use std::sync::Arc;
17use tokio::sync::Mutex;
18
19use super::messages::EmbeddingOptions;
20use super::provider::ProviderError;
21use super::Ai;
22
23/// The default directory / file used by [`Ai::vector_store`].
24pub const DEFAULT_VECTOR_STORE_PATH: &str = "storage/ai/vector-store.json";
25
26/// An error raised by a vector store.
27#[derive(Debug, thiserror::Error)]
28pub enum VectorStoreError {
29    #[error("vector store I/O error: {0}")]
30    Io(#[from] std::io::Error),
31    #[error("vector store embedding error: {0}")]
32    Embedding(#[from] ProviderError),
33    #[error("vector store database error: {0}")]
34    Database(#[from] sea_orm::DbErr),
35    #[error("vector store JSON error: {0}")]
36    Json(#[from] serde_json::Error),
37}
38
39/// One retrieved document, mirroring the Laravel AI SDK's vector query
40/// items (`id`, `content`, `additionalArguments`).
41#[derive(Debug, Clone, PartialEq)]
42pub struct VectorQueryItem {
43    /// The document's path / id.
44    pub id: String,
45    /// The document's content.
46    pub content: String,
47    /// Provider-specific extra metadata.
48    pub additional_arguments: Value,
49}
50
51/// The result of a vector query, mirroring Laravel's `VectorQueryResult`.
52#[derive(Debug, Clone, Default)]
53pub struct VectorQueryResult {
54    /// Matching documents, best first.
55    pub items: Vec<VectorQueryItem>,
56}
57
58impl VectorQueryResult {
59    /// The best matching item, if any.
60    pub fn first(&self) -> Option<&VectorQueryItem> {
61        self.items.first()
62    }
63}
64
65/// A document store that answers similarity queries via embeddings —
66/// Laravel 13's `VectorStore` contract (`addFileContent`, `addFile`,
67/// `query`, `delete`).
68#[async_trait::async_trait]
69pub trait VectorStore: Send + Sync + std::fmt::Debug {
70    /// Embed and store a document at `path`.
71    async fn add_file_content(&self, path: &str, content: &str) -> Result<(), VectorStoreError>;
72
73    /// Embed and store a document at `path`.
74    async fn add_file(&self, path: &str, content: &str) -> Result<(), VectorStoreError> {
75        self.add_file_content(path, content).await
76    }
77
78    /// Find the `top_k` documents closest to the query.
79    async fn query(&self, query: &str, top_k: usize)
80        -> Result<VectorQueryResult, VectorStoreError>;
81
82    /// Remove all documents stored under `path`.
83    async fn delete(&self, path: &str) -> Result<(), VectorStoreError>;
84}
85
86#[derive(Debug, Clone, Serialize, Deserialize)]
87struct FileRecord {
88    path: String,
89    content: String,
90    embedding: Vec<f32>,
91    additional_arguments: Value,
92}
93
94/// A vector store persisted to a local JSON file. Embeddings go through the
95/// given [`Ai`] (including its embedding cache), so repeated content never
96/// re-embeds. Querying embeds the query and scans the file's records with
97/// cosine similarity.
98#[derive(Debug)]
99pub struct FileVectorStore {
100    ai: Arc<Ai>,
101    path: Arc<str>,
102    records: Mutex<Vec<FileRecord>>,
103    embedding_model: Option<String>,
104}
105
106impl FileVectorStore {
107    /// Create a store backed by the JSON file at `path` (created on first
108    /// write; its parent directories are created too).
109    pub async fn new(ai: Arc<Ai>, path: impl Into<String>) -> Result<Self, VectorStoreError> {
110        let path: Arc<str> = path.into().into();
111        let records = Self::load(&path).await.unwrap_or_default();
112        Ok(Self {
113            ai,
114            path,
115            records: Mutex::new(records),
116            embedding_model: None,
117        })
118    }
119
120    /// Use a specific embedding model for this store's requests.
121    pub fn with_embedding_model(mut self, model: impl Into<String>) -> Self {
122        self.embedding_model = Some(model.into());
123        self
124    }
125
126    /// The JSON file backing this store.
127    pub fn path(&self) -> &str {
128        &self.path
129    }
130
131    async fn load(path: &str) -> Result<Vec<FileRecord>, VectorStoreError> {
132        let content = tokio::fs::read_to_string(path).await?;
133        Ok(serde_json::from_str(&content).unwrap_or_default())
134    }
135
136    async fn save(&self, records: &[FileRecord]) -> Result<(), VectorStoreError> {
137        if let Some(parent) = Path::new(&*self.path).parent() {
138            tokio::fs::create_dir_all(parent).await?;
139        }
140        let tmp = format!("{}.tmp", self.path);
141        tokio::fs::write(&tmp, serde_json::to_string(records)?).await?;
142        tokio::fs::rename(&tmp, &*self.path).await?;
143        Ok(())
144    }
145
146    async fn embed(&self, input: &str) -> Result<Vec<f32>, VectorStoreError> {
147        let options = EmbeddingOptions {
148            model: self.embedding_model.clone(),
149        };
150        Ok(self.ai.provider().embed(input, &options).await?)
151    }
152
153    fn cosine(a: &[f32], b: &[f32]) -> f64 {
154        let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
155        let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
156        let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
157        if norm_a == 0.0 || norm_b == 0.0 {
158            return 0.0;
159        }
160        (dot / (norm_a * norm_b)) as f64
161    }
162}
163
164#[async_trait::async_trait]
165impl VectorStore for FileVectorStore {
166    async fn add_file_content(&self, path: &str, content: &str) -> Result<(), VectorStoreError> {
167        let embedding = self.embed(content).await?;
168        let mut records = self.records.lock().await;
169        records.retain(|record| record.path != path);
170        records.push(FileRecord {
171            path: path.to_string(),
172            content: content.to_string(),
173            embedding,
174            additional_arguments: Value::Object(Default::default()),
175        });
176        let snapshot = records.clone();
177        drop(records);
178        self.save(&snapshot).await
179    }
180
181    async fn query(
182        &self,
183        query: &str,
184        top_k: usize,
185    ) -> Result<VectorQueryResult, VectorStoreError> {
186        let embedding = self.embed(query).await?;
187        let records = self.records.lock().await;
188        let mut scored: Vec<(f64, &FileRecord)> = records
189            .iter()
190            .map(|record| (Self::cosine(&embedding, &record.embedding), record))
191            .collect();
192        scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
193        Ok(VectorQueryResult {
194            items: scored
195                .into_iter()
196                .take(top_k)
197                .map(|(_, record)| VectorQueryItem {
198                    id: record.path.clone(),
199                    content: record.content.clone(),
200                    additional_arguments: record.additional_arguments.clone(),
201                })
202                .collect(),
203        })
204    }
205
206    async fn delete(&self, path: &str) -> Result<(), VectorStoreError> {
207        let mut records = self.records.lock().await;
208        let before = records.len();
209        records.retain(|record| record.path != path);
210        let removed = before != records.len();
211        let snapshot = records.clone();
212        drop(records);
213        if removed {
214            self.save(&snapshot).await?;
215        }
216        Ok(())
217    }
218}
219
220/// Options for the PostgreSQL + `pgvector` store.
221#[derive(Debug, Clone)]
222pub struct PostgresVectorStoreOptions {
223    /// The table storing the vectors. Defaults to `vector_store_items`.
224    pub table: String,
225    /// The embedding dimension. Defaults to 1536 (OpenAI
226    /// `text-embedding-3-small`).
227    pub embedding_dim: usize,
228}
229
230impl Default for PostgresVectorStoreOptions {
231    fn default() -> Self {
232        Self {
233            table: "vector_store_items".into(),
234            embedding_dim: 1536,
235        }
236    }
237}
238
239/// A vector store backed by PostgreSQL + `pgvector`, mirroring Laravel 13's
240/// `PostgresVectorStore`.
241///
242/// The store manages a table (`vector_store_items` by default) with
243/// `file_path`, `content`, `embedding vector(1536)`, and
244/// `additional_arguments jsonb` columns; rows are matched with cosine
245/// distance (`<=>`), the Laravel default.
246#[derive(Debug)]
247pub struct PostgresVectorStore {
248    conn: sea_orm::DatabaseConnection,
249    options: PostgresVectorStoreOptions,
250    ai: Arc<Ai>,
251}
252
253impl PostgresVectorStore {
254    /// Create a store for the given database connection. The backing table
255    /// is created on demand when the store is first used.
256    pub fn new(
257        conn: sea_orm::DatabaseConnection,
258        ai: Arc<Ai>,
259        options: PostgresVectorStoreOptions,
260    ) -> Self {
261        Self { conn, options, ai }
262    }
263
264    /// Ensure the backing table exists (`CREATE TABLE IF NOT EXISTS` plus
265    /// the pgvector extension when needed).
266    pub async fn ensure_table(&self) -> Result<(), VectorStoreError> {
267        let sql = format!(
268            "CREATE TABLE IF NOT EXISTS \"{}\" (
269                id BIGSERIAL PRIMARY KEY,
270                file_path TEXT NOT NULL,
271                content TEXT NOT NULL,
272                embedding vector({}) NOT NULL,
273                additional_arguments JSONB DEFAULT '{{}}'::jsonb
274            )",
275            self.options.table, self.options.embedding_dim
276        );
277        self.conn.execute_unprepared(&sql).await?;
278        Ok(())
279    }
280
281    async fn embed(&self, input: &str) -> Result<Vec<f32>, VectorStoreError> {
282        Ok(self
283            .ai
284            .provider()
285            .embed(input, &EmbeddingOptions::default())
286            .await?)
287    }
288
289    fn vector_literal(embedding: &[f32]) -> String {
290        let inner = embedding
291            .iter()
292            .map(f32::to_string)
293            .collect::<Vec<_>>()
294            .join(",");
295        format!("'[{inner}]'::vector")
296    }
297
298    fn query_sql(options: &PostgresVectorStoreOptions, top_k: usize) -> String {
299        format!(
300            "SELECT file_path, content, additional_arguments FROM \"{}\" \
301             ORDER BY embedding <=> $1::vector ASC LIMIT {top_k}",
302            options.table
303        )
304    }
305
306    fn delete_sql(options: &PostgresVectorStoreOptions) -> String {
307        format!("DELETE FROM \"{}\" WHERE file_path = $1", options.table)
308    }
309}
310
311#[async_trait::async_trait]
312impl VectorStore for PostgresVectorStore {
313    async fn add_file_content(&self, path: &str, content: &str) -> Result<(), VectorStoreError> {
314        let embedding = self.embed(content).await?;
315        self.ensure_table().await?;
316        let sql = format!(
317            "INSERT INTO \"{}\" (file_path, content, embedding, additional_arguments) \
318             VALUES ($1, $2, {}, '{{}}'::jsonb)",
319            self.options.table,
320            Self::vector_literal(&embedding)
321        );
322        let statement = sea_orm::Statement::from_sql_and_values(
323            sea_orm::DatabaseBackend::Postgres,
324            &sql,
325            vec![path.into(), content.into()],
326        );
327        self.conn.execute(statement).await?;
328        Ok(())
329    }
330
331    async fn query(
332        &self,
333        query: &str,
334        top_k: usize,
335    ) -> Result<VectorQueryResult, VectorStoreError> {
336        let embedding = self.embed(query).await?;
337        let sql = Self::query_sql(&self.options, top_k);
338        let statement = sea_orm::Statement::from_sql_and_values(
339            sea_orm::DatabaseBackend::Postgres,
340            &sql,
341            vec![Self::vector_literal(&embedding).into()],
342        );
343        let rows = self.conn.query_all(statement).await?;
344        let mut items = Vec::with_capacity(rows.len());
345        for row in rows {
346            let id: String = row.try_get("", "file_path")?;
347            let content: String = row.try_get("", "content")?;
348            let additional_arguments: String = row.try_get("", "additional_arguments")?;
349            items.push(VectorQueryItem {
350                id,
351                content,
352                additional_arguments: serde_json::from_str(&additional_arguments)
353                    .unwrap_or(Value::Null),
354            });
355        }
356        Ok(VectorQueryResult { items })
357    }
358
359    async fn delete(&self, path: &str) -> Result<(), VectorStoreError> {
360        let sql = Self::delete_sql(&self.options);
361        let statement = sea_orm::Statement::from_sql_and_values(
362            sea_orm::DatabaseBackend::Postgres,
363            &sql,
364            vec![path.into()],
365        );
366        self.conn.execute(statement).await?;
367        Ok(())
368    }
369}
370
371// ============================================================================
372// TESTS
373// ============================================================================
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378    use crate::ai::FakeAi;
379
380    fn fake_ai() -> Arc<Ai> {
381        Arc::new(Ai::new(Arc::new(FakeAi::new())))
382    }
383
384    #[tokio::test]
385    async fn test_file_store_add_query_delete() {
386        let store = FileVectorStore::new(fake_ai(), "/tmp/larastvel-test-vector-store.json")
387            .await
388            .unwrap();
389        store
390            .add_file_content("docs/intro.md", "Larastvel is a Rust framework")
391            .await
392            .unwrap();
393        store
394            .add_file_content("docs/api.md", "Axum powers the routing")
395            .await
396            .unwrap();
397
398        let result = store.query("routing framework", 2).await.unwrap();
399        assert_eq!(result.items.len(), 2);
400        assert_eq!(result.first().unwrap().id, "docs/api.md");
401
402        let top_1 = store.query("Larastvel framework", 1).await.unwrap();
403        assert_eq!(top_1.items.len(), 1);
404
405        store.delete("docs/api.md").await.unwrap();
406        let result = store.query("routing framework", 2).await.unwrap();
407        assert_eq!(result.items.len(), 1);
408        assert_eq!(result.first().unwrap().id, "docs/intro.md");
409
410        let _ = tokio::fs::remove_file("/tmp/larastvel-test-vector-store.json").await;
411    }
412
413    #[tokio::test]
414    async fn test_file_store_replaces_existing_path() {
415        let store = FileVectorStore::new(fake_ai(), "/tmp/larastvel-test-vector-store-2.json")
416            .await
417            .unwrap();
418        store
419            .add_file_content("docs/a.md", "first version")
420            .await
421            .unwrap();
422        store
423            .add_file_content("docs/a.md", "second version")
424            .await
425            .unwrap();
426
427        let result = store.query("second", 1).await.unwrap();
428        assert_eq!(result.items.len(), 1);
429        assert_eq!(result.first().unwrap().content, "second version");
430
431        let _ = tokio::fs::remove_file("/tmp/larastvel-test-vector-store-2.json").await;
432    }
433
434    #[test]
435    fn test_vector_literal_format() {
436        assert_eq!(
437            PostgresVectorStore::vector_literal(&[0.1, 0.5, 1.0]),
438            "'[0.1,0.5,1]'::vector"
439        );
440    }
441
442    #[test]
443    fn test_postgres_store_sql() {
444        let sql = PostgresVectorStore::query_sql(&PostgresVectorStoreOptions::default(), 5);
445        assert!(sql.contains("FROM \"vector_store_items\""));
446        assert!(sql.contains("ORDER BY embedding <=> $1::vector ASC"));
447        assert!(sql.contains("LIMIT 5"));
448
449        let sql = PostgresVectorStore::delete_sql(&PostgresVectorStoreOptions::default());
450        assert!(sql.contains("DELETE FROM \"vector_store_items\""));
451        assert!(sql.contains("WHERE file_path = $1"));
452    }
453
454    #[test]
455    fn test_cosine_similarity() {
456        assert!((FileVectorStore::cosine(&[1.0, 0.0], &[1.0, 0.0]) - 1.0).abs() < 1e-6);
457        assert!((FileVectorStore::cosine(&[1.0, 0.0], &[0.0, 1.0])).abs() < 1e-6);
458        assert_eq!(FileVectorStore::cosine(&[], &[]), 0.0);
459    }
460}