diff options
Diffstat (limited to 'personal_agent/memory/store.py')
| -rw-r--r-- | personal_agent/memory/store.py | 40 |
1 files changed, 34 insertions, 6 deletions
diff --git a/personal_agent/memory/store.py b/personal_agent/memory/store.py index e5fca96..164d11f 100644 --- a/personal_agent/memory/store.py +++ b/personal_agent/memory/store.py @@ -21,6 +21,16 @@ class LongTermMemoryStore: (str(memory.id), memory.content, memory.category.value, created_at), ) + connection.execute( + """ + INSERT INTO memories_fts(rowid, content) + SELECT rowid, content + FROM memories + WHERE id = ? + """, + (str(memory.id),), + ) + def get(self, memory_id: UUID) -> LongTermMemory | None: with self.database.connect() as connection: row = connection.execute( @@ -52,6 +62,18 @@ class LongTermMemoryStore: def delete(self, memory_id: UUID) -> None: with self.database.connect() as connection: connection.execute( + """ + DELETE FROM memories_fts + WHERE rowid = ( + SELECT rowid + FROM memories + WHERE id = ? + ) + """, + (str(memory_id),), + ) + + connection.execute( "DELETE FROM memories WHERE id = ?", (str(memory_id),), ) @@ -68,18 +90,24 @@ class LongTermMemoryStore: if not query.strip(): raise ValueError("Search query must not be empty") + terms = query.split() + fts_query = " OR ".join( + f'"{term.replace(chr(34), chr(34) * 2)}"' for term in terms + ) + sql = """ - SELECT id, content, category, created_at - FROM memories - WHERE content LIKE ? + SELECT m.id, m.content, m.category, m.created_at + FROM memories_fts as f + JOIN memories AS m ON m.rowid = f.rowid + WHERE memories_fts MATCH ? """ - parameters: list[str | int] = [f"%{query}%"] + parameters: list[str | int] = [fts_query] if category is not None: - sql += " AND category = ?" + sql += " AND m.category = ?" parameters.append(category.value) - sql += " ORDER BY id LIMIT ?" + sql += " ORDER BY bm25(memories_fts) LIMIT ?" parameters.append(limit) with self.database.connect() as connection: |
