agent-io 0.3.2

A Rust SDK for building AI agents with multi-provider LLM support
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
//! LanceDB-based memory store for persistent vector storage

use arrow::array::{Array, FixedSizeListArray, Float32Array, Int64Array, StringArray, UInt32Array};
use arrow::record_batch::RecordBatch;
use arrow_array::RecordBatchIterator;
use arrow_array::types::Float32Type;
use arrow_schema::{DataType, Field, Schema};
use async_trait::async_trait;
use futures::TryStreamExt;
use lancedb::query::{ExecutableQuery, QueryBase, Select};
use lancedb::{Table, connect};
use std::path::PathBuf;
use std::sync::Arc;

use crate::Result;
use crate::memory::entry::{MemoryEntry, MemoryType};
use crate::memory::store::MemoryStore;

const TABLE_NAME: &str = "memories";
const EMBEDDING_DIM: usize = 1536; // OpenAI embedding dimension

/// LanceDB memory store for persistent vector storage with FTS support
pub struct LanceDbStore {
    table: Arc<Table>,
}

impl LanceDbStore {
    /// Create a new LanceDB store with an in-memory database
    pub async fn new() -> Result<Self> {
        Self::open_uri("memory://agent_io_memories").await
    }

    /// Create a new LanceDB store with a file database
    pub async fn open<P: Into<PathBuf>>(path: P) -> Result<Self> {
        let path = path.into();

        // Ensure parent directory exists
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| crate::Error::Agent(format!("Failed to create directory: {}", e)))?;
        }

        let uri = path.to_string_lossy().to_string();
        Self::open_uri(&uri).await
    }

    async fn open_uri(uri: &str) -> Result<Self> {
        let db = connect(uri)
            .execute()
            .await
            .map_err(|e| crate::Error::Agent(format!("Failed to connect to LanceDB: {}", e)))?;

        let table_names = db
            .table_names()
            .execute()
            .await
            .map_err(|e| crate::Error::Agent(format!("Failed to list tables: {}", e)))?;

        let table = if table_names.contains(&TABLE_NAME.to_string()) {
            db.open_table(TABLE_NAME)
                .execute()
                .await
                .map_err(|e| crate::Error::Agent(format!("Failed to open table: {}", e)))?
        } else {
            // Create an empty table with schema
            let schema = Self::schema();
            db.create_empty_table(TABLE_NAME, schema)
                .execute()
                .await
                .map_err(|e| crate::Error::Agent(format!("Failed to create table: {}", e)))?
        };

        Ok(Self {
            table: Arc::new(table),
        })
    }

    /// Get the table schema
    fn schema() -> Arc<Schema> {
        Arc::new(Schema::new(vec![
            Field::new("id", DataType::Utf8, false),
            Field::new("content", DataType::Utf8, false),
            Field::new(
                "embedding",
                DataType::FixedSizeList(
                    Arc::new(Field::new("item", DataType::Float32, true)),
                    EMBEDDING_DIM as i32,
                ),
                true,
            ),
            Field::new("memory_type", DataType::Utf8, false),
            Field::new("metadata", DataType::Utf8, true),
            Field::new("created_at", DataType::Int64, false),
            Field::new("last_accessed", DataType::Int64, true),
            Field::new("importance", DataType::Float32, false),
            Field::new("access_count", DataType::UInt32, false),
        ]))
    }

    /// Convert memory type to string
    fn memory_type_to_string(t: &MemoryType) -> &'static str {
        match t {
            MemoryType::ShortTerm => "short_term",
            MemoryType::LongTerm => "long_term",
            MemoryType::Episodic => "episodic",
            MemoryType::Semantic => "semantic",
        }
    }

    /// Convert string to memory type
    fn string_to_memory_type(s: &str) -> MemoryType {
        match s {
            "long_term" => MemoryType::LongTerm,
            "episodic" => MemoryType::Episodic,
            "semantic" => MemoryType::Semantic,
            _ => MemoryType::ShortTerm,
        }
    }

    /// Convert MemoryEntry to RecordBatch
    fn entry_to_batch(entry: &MemoryEntry) -> Result<RecordBatch> {
        let schema = Self::schema();

        let id_array = StringArray::from(vec![entry.id.clone()]);
        let content_array = StringArray::from(vec![entry.content.clone()]);

        // Handle embedding as FixedSizeList
        let embedding_array = if let Some(ref embedding) = entry.embedding {
            FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>(
                vec![Some(embedding.iter().map(|&v| Some(v)).collect::<Vec<_>>())],
                EMBEDDING_DIM as i32,
            )
        } else {
            // Create a null array with the correct type
            FixedSizeListArray::from_iter_primitive::<Float32Type, Option<Option<f32>>, _>(
                vec![None],
                EMBEDDING_DIM as i32,
            )
        };

        let memory_type_array =
            StringArray::from(vec![Self::memory_type_to_string(&entry.memory_type)]);

        let metadata_array = if entry.metadata.is_empty() {
            StringArray::from(vec![None::<String>])
        } else {
            StringArray::from(vec![Some(
                serde_json::to_string(&entry.metadata).unwrap_or_default(),
            )])
        };

        let created_at_array = Int64Array::from(vec![entry.created_at.timestamp()]);
        let last_accessed_array =
            Int64Array::from(vec![entry.last_accessed.map(|la| la.timestamp())]);
        let importance_array = Float32Array::from(vec![entry.importance]);
        let access_count_array = UInt32Array::from(vec![entry.access_count]);

        RecordBatch::try_new(
            schema,
            vec![
                Arc::new(id_array),
                Arc::new(content_array),
                Arc::new(embedding_array),
                Arc::new(memory_type_array),
                Arc::new(metadata_array),
                Arc::new(created_at_array),
                Arc::new(last_accessed_array),
                Arc::new(importance_array),
                Arc::new(access_count_array),
            ],
        )
        .map_err(|e| crate::Error::Agent(format!("Failed to create record batch: {}", e)))
    }

    fn parse_batch_row(batch: &RecordBatch, i: usize) -> Result<MemoryEntry> {
        let id = batch
            .column(0)
            .as_any()
            .downcast_ref::<StringArray>()
            .map(|arr| arr.value(i).to_string())
            .unwrap_or_default();

        let content = batch
            .column(1)
            .as_any()
            .downcast_ref::<StringArray>()
            .map(|arr| arr.value(i).to_string())
            .unwrap_or_default();

        let embedding = batch
            .column(2)
            .as_any()
            .downcast_ref::<FixedSizeListArray>()
            .and_then(|arr| {
                if arr.is_null(i) {
                    return None;
                }
                let values = arr.value(i);
                values
                    .as_any()
                    .downcast_ref::<Float32Array>()
                    .map(|v| v.values().to_vec())
            });

        let memory_type = batch
            .column(3)
            .as_any()
            .downcast_ref::<StringArray>()
            .map(|arr| arr.value(i).to_string())
            .unwrap_or_default();

        let metadata = batch
            .column(4)
            .as_any()
            .downcast_ref::<StringArray>()
            .and_then(|arr| {
                if arr.is_null(i) {
                    None
                } else {
                    Some(arr.value(i).to_string())
                }
            });

        let created_at = batch
            .column(5)
            .as_any()
            .downcast_ref::<Int64Array>()
            .map(|arr| arr.value(i))
            .unwrap_or(0);

        let last_accessed = batch
            .column(6)
            .as_any()
            .downcast_ref::<Int64Array>()
            .and_then(|arr| {
                if arr.is_null(i) {
                    None
                } else {
                    Some(arr.value(i))
                }
            });

        let importance = batch
            .column(7)
            .as_any()
            .downcast_ref::<Float32Array>()
            .map(|arr| arr.value(i))
            .unwrap_or(0.5);

        let access_count = batch
            .column(8)
            .as_any()
            .downcast_ref::<UInt32Array>()
            .map(|arr| arr.value(i))
            .unwrap_or(0);

        let metadata_map: std::collections::HashMap<String, serde_json::Value> = metadata
            .as_ref()
            .and_then(|s| serde_json::from_str(s).ok())
            .unwrap_or_default();

        Ok(MemoryEntry {
            id,
            content,
            embedding,
            memory_type: Self::string_to_memory_type(&memory_type),
            metadata: metadata_map,
            created_at: chrono::DateTime::from_timestamp(created_at, 0)
                .map(|dt| dt.with_timezone(&chrono::Utc))
                .unwrap_or_else(chrono::Utc::now),
            last_accessed: last_accessed
                .and_then(|ts| chrono::DateTime::from_timestamp(ts, 0))
                .map(|dt| dt.with_timezone(&chrono::Utc)),
            importance,
            access_count,
        })
    }
}

#[async_trait]
impl MemoryStore for LanceDbStore {
    async fn add(&self, entry: MemoryEntry) -> Result<String> {
        let id = entry.id.clone();
        let batch = Self::entry_to_batch(&entry)?;

        self.table
            .add(RecordBatchIterator::new(
                vec![Ok(batch.clone())],
                batch.schema(),
            ))
            .execute()
            .await
            .map_err(|e| crate::Error::Agent(format!("Failed to add memory: {}", e)))?;

        Ok(id)
    }

    async fn get(&self, id: &str) -> Result<Option<MemoryEntry>> {
        let batches = self
            .table
            .query()
            .only_if(format!("id = '{}'", id.replace('\'', "''")))
            .execute()
            .await
            .map_err(|e| crate::Error::Agent(format!("Failed to query: {}", e)))?
            .try_collect::<Vec<_>>()
            .await
            .map_err(|e| crate::Error::Agent(format!("Failed to collect batches: {}", e)))?;

        if let Some(batch) = batches.first()
            && batch.num_rows() > 0
        {
            return Ok(Some(Self::parse_batch_row(batch, 0)?));
        }

        Ok(None)
    }

    async fn delete(&self, id: &str) -> Result<()> {
        self.table
            .delete(&format!("id = '{}'", id.replace('\'', "''")))
            .await
            .map_err(|e| crate::Error::Agent(format!("Failed to delete memory: {}", e)))?;

        Ok(())
    }

    async fn search(&self, query: &str, limit: usize) -> Result<Vec<MemoryEntry>> {
        let batches = self
            .table
            .query()
            .only_if(format!("content LIKE '%{}%'", query.replace('\'', "''")))
            .limit(limit)
            .execute()
            .await
            .map_err(|e| crate::Error::Agent(format!("Failed to search: {}", e)))?
            .try_collect::<Vec<_>>()
            .await
            .map_err(|e| crate::Error::Agent(format!("Failed to collect batches: {}", e)))?;

        let mut entries = Vec::new();
        for batch in batches {
            for i in 0..batch.num_rows() {
                entries.push(Self::parse_batch_row(&batch, i)?);
            }
        }

        Ok(entries)
    }

    async fn search_by_embedding(
        &self,
        embedding: &[f32],
        limit: usize,
        threshold: f32,
    ) -> Result<Vec<MemoryEntry>> {
        let batches = self
            .table
            .query()
            .limit(limit * 2) // Fetch more to filter by threshold
            .nearest_to(embedding)
            .map_err(|e| crate::Error::Agent(format!("Failed to create vector search: {}", e)))?
            .execute()
            .await
            .map_err(|e| crate::Error::Agent(format!("Failed to search by embedding: {}", e)))?
            .try_collect::<Vec<_>>()
            .await
            .map_err(|e| crate::Error::Agent(format!("Failed to collect batches: {}", e)))?;

        let mut entries_with_score = Vec::new();
        for batch in batches {
            for i in 0..batch.num_rows() {
                let entry = Self::parse_batch_row(&batch, i)?;

                // Get similarity from _distance column if present
                let similarity = if let Some(distance_col) = batch.column_by_name("_distance") {
                    let dist = distance_col
                        .as_any()
                        .downcast_ref::<Float32Array>()
                        .map(|arr| arr.value(i))
                        .unwrap_or(1.0);
                    1.0 - dist // Convert distance to similarity
                } else if let Some(ref entry_embedding) = entry.embedding {
                    cosine_similarity(embedding, entry_embedding)
                } else {
                    0.0
                };

                if similarity >= threshold {
                    entries_with_score.push((entry, similarity));
                }
            }
        }

        // Sort by similarity descending
        entries_with_score
            .sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        entries_with_score.truncate(limit);

        Ok(entries_with_score.into_iter().map(|(e, _)| e).collect())
    }

    async fn ids(&self) -> Result<Vec<String>> {
        let batches = self
            .table
            .query()
            .select(Select::columns(&["id"]))
            .execute()
            .await
            .map_err(|e| crate::Error::Agent(format!("Failed to query ids: {}", e)))?
            .try_collect::<Vec<_>>()
            .await
            .map_err(|e| crate::Error::Agent(format!("Failed to collect batches: {}", e)))?;

        let mut ids = Vec::new();
        for batch in batches {
            if let Some(id_array) = batch
                .column_by_name("id")
                .and_then(|col| col.as_any().downcast_ref::<StringArray>())
            {
                for i in 0..id_array.len() {
                    ids.push(id_array.value(i).to_string());
                }
            }
        }

        Ok(ids)
    }

    async fn count(&self) -> Result<usize> {
        let batches = self
            .table
            .query()
            .select(Select::columns(&["id"]))
            .execute()
            .await
            .map_err(|e| crate::Error::Agent(format!("Failed to count: {}", e)))?
            .try_collect::<Vec<_>>()
            .await
            .map_err(|e| crate::Error::Agent(format!("Failed to collect batches: {}", e)))?;

        let mut count = 0;
        for batch in batches {
            count += batch.num_rows();
        }

        Ok(count)
    }

    async fn update(&self, entry: MemoryEntry) -> Result<()> {
        // LanceDB doesn't have a native update, so we delete and re-add
        self.delete(&entry.id).await?;
        self.add(entry).await?;
        Ok(())
    }

    async fn clear(&self) -> Result<()> {
        self.table
            .delete("true")
            .await
            .map_err(|e| crate::Error::Agent(format!("Failed to clear memories: {}", e)))?;

        Ok(())
    }
}

/// Compute cosine similarity between two vectors
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
    if a.len() != b.len() || a.is_empty() {
        return 0.0;
    }

    let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
    let mag_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
    let mag_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();

    if mag_a == 0.0 || mag_b == 0.0 {
        return 0.0;
    }

    dot / (mag_a * mag_b)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_lancedb_store_basic() {
        let store = LanceDbStore::new().await.expect("Failed to create store");

        let entry = MemoryEntry::new("This is a test memory");
        let id = store.add(entry.clone()).await.expect("Failed to add");

        let retrieved = store.get(&id).await.expect("Failed to get");
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().content, "This is a test memory");
    }

    #[tokio::test]
    async fn test_lancedb_store_delete() {
        let store = LanceDbStore::new().await.expect("Failed to create store");

        let entry = MemoryEntry::new("Memory to delete");
        let id = store.add(entry).await.expect("Failed to add");

        store.delete(&id).await.expect("Failed to delete");

        let retrieved = store.get(&id).await.expect("Failed to get");
        assert!(retrieved.is_none());
    }

    #[tokio::test]
    async fn test_lancedb_store_search() {
        let store = LanceDbStore::new().await.expect("Failed to create store");

        store
            .add(MemoryEntry::new("Rust programming language"))
            .await
            .ok();
        store
            .add(MemoryEntry::new("Python machine learning"))
            .await
            .ok();
        store
            .add(MemoryEntry::new("Rust async programming"))
            .await
            .ok();

        let results = store.search("Rust", 10).await.expect("Failed to search");
        assert!(!results.is_empty());
    }

    #[tokio::test]
    async fn test_lancedb_store_count() {
        let store = LanceDbStore::new().await.expect("Failed to create store");

        store.clear().await.ok();

        store.add(MemoryEntry::new("Test 1")).await.ok();
        store.add(MemoryEntry::new("Test 2")).await.ok();

        let count = store.count().await.expect("Failed to count");
        assert_eq!(count, 2);
    }
}