💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Add SQLite ANN, closes #780
davidmezzettid535fc51015c
diff --git a/docs/embeddings/configuration/ann.md b/docs/embeddings/configuration/ann.mdindex 883aeb02..6ce134b1 100644--- a/docs/embeddings/configuration/ann.md+++ b/docs/embeddings/configuration/ann.md@@ -4,7 +4,7 @@ Approximate Nearest Neighbor (ANN) index configuration for storing vector embedd## backend```yaml-backend: faiss|hnsw|annoy|numpy|torch|pgvector|custom+backend: faiss|hnsw|annoy|numpy|torch|pgvector|sqlite|custom```Sets the ANN backend. Defaults to `faiss`. Additional backends are available via the [ann](../../../install/#ann) extras package. Set custom backends via setting this parameter to the fully resolvable class string.@@ -61,10 +61,6 @@ annoy:See [Annoy documentation](https://github.com/spotify/annoy#full-python-api) for more information on these parameters. Note that annoy indexes can not be modified after creation, upserts/deletes and other modifications are not supported.### numpy-```yaml-numpy:- quantize: number of quantized bits when working with quantized vectors (int)-```The NumPy backend is a k-nearest neighbors backend. It's designed for simplicity and works well with smaller datasets.@@ -81,3 +77,14 @@ pgvector:```The pgvector backend stores embeddings in a Postgres database. See the [pgvector documentation](https://github.com/pgvector/pgvector-python?tab=readme-ov-file#sqlalchemy) for more information on these parameters. See the [SQLAlchemy](https://docs.sqlalchemy.org/en/20/core/engines.html#database-urls) documentation for more information on how to construct url connection strings.++### sqlite+```yaml+sqlite:+ quantize: store vectors with x-bit precision vs 32-bit (boolean|int)+ true sets 8-bit precision, false disables, int sets specified+ precision+ table: database table to store vectors - defaults to `vectors`+```++The SQLite backend stores embeddings in a SQLite database using [sqlite-vec](https://github.com/asg017/sqlite-vec). This backend supports 1-bit and 8-bit quantization at the storage level.diff --git a/docs/embeddings/configuration/vectors.md b/docs/embeddings/configuration/vectors.mdindex 45f2a17d..5a858951 100644--- a/docs/embeddings/configuration/vectors.md+++ b/docs/embeddings/configuration/vectors.md@@ -110,11 +110,12 @@ Enables truncation of vectors to this dimensionality. This is only useful for moquantize: int|boolean```-Enables scalar quantization at the specified precision. Supports 1-bit through 8-bit quantization. Scalar quantization transforms continuous floating point values-to discrete unsigned integers. Quantized data storage is only supported by the `faiss`, `numpy` and `torch` ANN backends.+Enables scalar vector quantization at the specified precision. Supports 1-bit through 8-bit quantization. Scalar quantization transforms continuous floating point values to discrete unsigned integers. Only the `faiss`, `numpy` and `torch` ANN backends support storing these vectors.This parameter supports booleans for backwards compatability. When set to true/false, this flag sets [faiss.quantize](../ann/#faiss).+In addition to vector-level quantization, some ANN backends have the ability to quantize vectors at the storage layer. See the [ANN](../ann) configuration options for more.+## instructions```yamlinstructions:diff --git a/setup.py b/setup.pyindex 85c29eb4..5fa9ef1c 100644--- a/setup.py+++ b/setup.py@@ -32,6 +32,7 @@ extras["ann"] = ["hnswlib>=0.5.0","pgvector>=0.2.5","sqlalchemy>=2.0.20",+ "sqlite-vec>=0.1.1",]extras["api"] = [diff --git a/src/python/txtai/ann/factory.py b/src/python/txtai/ann/factory.pyindex d934cb76..cb0a4892 100644--- a/src/python/txtai/ann/factory.py+++ b/src/python/txtai/ann/factory.py@@ -9,6 +9,7 @@ from .faiss import Faissfrom .hnsw import HNSWfrom .numpy import NumPyfrom .pgvector import PGVector+from .sqlite import SQLitefrom .torch import Torch@@ -44,6 +45,8 @@ class ANNFactory:ann = NumPy(config)elif backend == "pgvector":ann = PGVector(config)+ elif backend == "sqlite":+ ann = SQLite(config)elif backend == "torch":ann = Torch(config)else:diff --git a/src/python/txtai/ann/numpy.py b/src/python/txtai/ann/numpy.pyindex 2025f23e..eeb2f8d7 100644--- a/src/python/txtai/ann/numpy.py+++ b/src/python/txtai/ann/numpy.py@@ -42,13 +42,11 @@ class NumPy(ANN):self.metadata(self.settings())def append(self, embeddings):- new = embeddings.shape[0]-# Append new data to arrayself.backend = self.cat((self.backend, self.tensor(embeddings)), axis=0)# Update id offset and index metadata- self.config["offset"] += new+ self.config["offset"] += embeddings.shape[0]self.metadata()def delete(self, ids):diff --git a/src/python/txtai/ann/pgvector.py b/src/python/txtai/ann/pgvector.pyindex d80a1754..181e517d 100644--- a/src/python/txtai/ann/pgvector.py+++ b/src/python/txtai/ann/pgvector.py@@ -55,11 +55,14 @@ class PGVector(ANN):# Add id offset and index build metadataself.config["offset"] = embeddings.shape[0]+ self.metadata(self.settings())def append(self, embeddings):self.database.execute(self.table.insert(), [{"indexid": x + self.config["offset"], "embedding": row} for x, row in enumerate(embeddings)])+ # Update id offset and index metadataself.config["offset"] += embeddings.shape[0]+ self.metadata()def delete(self, ids):self.database.execute(delete(self.table).where(self.table.c["indexid"].in_(ids)))@@ -116,7 +119,7 @@ class PGVector(ANN):f"{table}-index",self.table.c["embedding"],postgresql_using="hnsw",- postgresql_with={"m": self.setting("m", 16), "ef_construction": self.setting("efconstruction", 200)},+ postgresql_with=self.settings(),postgresql_ops={"embedding": "vector_ip_ops"},)@@ -128,3 +131,13 @@ class PGVector(ANN):# Create table and indexself.table.create(self.engine, checkfirst=True)index.create(self.engine, checkfirst=True)++ def settings(self):+ """+ Returns settings for this index.++ Returns:+ dict+ """++ return {"m": self.setting("m", 16), "ef_construction": self.setting("efconstruction", 200)}diff --git a/src/python/txtai/ann/sqlite.py b/src/python/txtai/ann/sqlite.pynew file mode 100644index 00000000..b8ea8847--- /dev/null+++ b/src/python/txtai/ann/sqlite.py@@ -0,0 +1,296 @@+"""+SQLite module+"""++import os+import sqlite3++# Conditional import+try:+ import sqlite_vec++ SQLITEVEC = True+except ImportError:+ SQLITEVEC = False++from .base import ANN+++class SQLite(ANN):+ """+ Builds an ANN index backed by a SQLite database.+ """++ def __init__(self, config):+ super().__init__(config)++ if not SQLITEVEC:+ raise ImportError('sqlite-vec is not available - install "ann" extra to enable')++ # Database parameters+ self.connection, self.cursor, self.path = None, None, ""++ # Quantization setting+ self.quantize = self.setting("quantize")+ self.quantize = 8 if isinstance(self.quantize, bool) else int(self.quantize) if self.quantize else None++ def load(self, path):+ self.path = path++ def index(self, embeddings):+ # Initialize tables+ self.initialize(recreate=True)++ # Add vectors+ self.database().executemany(self.insertsql(), enumerate(embeddings))++ # Add id offset and index build metadata+ self.config["offset"] = embeddings.shape[0]+ self.metadata(self.settings())++ def append(self, embeddings):+ self.database().executemany(self.insertsql(), [(x + self.config["offset"], row) for x, row in enumerate(embeddings)])++ self.config["offset"] += embeddings.shape[0]+ self.metadata()++ def delete(self, ids):+ self.database().executemany(self.deletesql(), [(x,) for x in ids])++ def search(self, queries, limit):+ results = []+ for query in queries:+ # Execute query+ self.database().execute(self.searchsql(), [query, limit])++ # Add query results+ results.append(list(self.database()))++ return results++ def count(self):+ self.database().execute(self.countsql())+ return self.cursor.fetchone()[0]++ def save(self, path):+ # Temporary database+ if not self.path:+ # Save temporary database+ self.connection.commit()++ # Copy data from current to new+ connection = self.copy(path)++ # Close temporary database+ self.connection.close()++ # Point connection to new connection+ self.connection = connection+ self.cursor = self.connection.cursor()+ self.path = path++ # Paths are equal, commit changes+ elif self.path == path:+ self.connection.commit()++ # New path is different from current path, copy data and continue using current connection+ else:+ self.copy(path).close()++ def initialize(self, recreate=False):+ """+ Initializes a new database session.++ Args:+ recreate: Recreates the database tables if True+ """++ # Create table+ self.database().execute(self.tablesql())++ # Clear data+ if recreate:+ self.database().execute(self.tosql("DELETE FROM {table}"))++ def settings(self):+ """+ Returns settings for this index.++ Returns:+ dict+ """++ sqlite, sqlitevec = self.database().execute("SELECT sqlite_version(), vec_version()").fetchone()++ return {"sqlite": sqlite, "sqlite-vec": sqlitevec}++ def database(self):+ """+ Gets the current database cursor. Creates a new connection+ if there isn't one.++ Returns:+ cursor+ """++ if not self.connection:+ self.connection = self.connect(self.path)+ self.cursor = self.connection.cursor()++ return self.cursor++ def connect(self, path):+ """+ Creates a new database connection.++ Args:+ path: path to database file++ Returns:+ database connection+ """++ # Create connection+ connection = sqlite3.connect(path, check_same_thread=False)++ # Load sqlite-vec extension+ connection.enable_load_extension(True)+ sqlite_vec.load(connection)+ connection.enable_load_extension(False)++ # Return connection and cursor+ return connection++ def copy(self, path):+ """+ Copies content from the current database into target.++ Args:+ path: target database path++ Returns:+ new database connection+ """++ # Delete existing file, if necessary+ if os.path.exists(path):+ os.remove(path)++ # Create new connection+ connection = self.connect(path)++ if self.connection.in_transaction:+ # Initialize connection+ connection.execute(self.tablesql())++ # The backup call will hang if there are uncommitted changes, need to copy over+ # with iterdump (which is much slower)+ for sql in self.connection.iterdump():+ if self.tosql('insert into "{table}"') in sql.lower():+ connection.execute(sql)+ else:+ # Database is up to date, can do a more efficient copy with SQLite C API+ self.connection.backup(connection)++ return connection++ def tablesql(self):+ """+ Builds a CREATE table statement for table.++ Returns:+ CREATE TABLE+ """++ # Binary quantization+ if self.quantize == 1:+ embedding = f"embedding BIT[{self.config['dimensions']}]"++ # INT8 quantization+ elif self.quantize == 8:+ embedding = f"embedding INT8[{self.config['dimensions']}] distance=cosine"++ # Standard FLOAT32+ else:+ embedding = f"embedding FLOAT[{self.config['dimensions']}] distance=cosine"++ # Return CREATE TABLE sql+ return self.tosql(("CREATE VIRTUAL TABLE IF NOT EXISTS {table} USING vec0" "(indexid INTEGER PRIMARY KEY, " f"{embedding})"))++ def insertsql(self):+ """+ Creates an INSERT SQL statement.++ Returns:+ INSERT+ """++ return self.tosql(f"INSERT INTO {{table}}(indexid, embedding) VALUES (?, {self.embeddingsql()})")++ def deletesql(self):+ """+ Creates a DELETE SQL statement.++ Returns:+ DELETE+ """++ return self.tosql("DELETE FROM {table} WHERE indexid = ?")++ def searchsql(self):+ """+ Creates a SELECT SQL statement for search.++ Returns:+ SELECT+ """++ return self.tosql(+ ("SELECT indexid, 1 - distance " "FROM {table} " f"WHERE embedding MATCH {self.embeddingsql()} " "ORDER BY distance " "LIMIT ?")+ )++ def countsql(self):+ """+ Creates a SELECT COUNT statement.++ Returns:+ SELECT COUNT+ """++ return self.tosql("SELECT count(indexid) FROM {table}")++ def embeddingsql(self):+ """+ Creates an embeddings column SQL snippet.++ Returns:+ embeddings column SQL+ """++ # Binary quantization+ if self.quantize == 1:+ embedding = "vec_quantize_binary(?)"++ # INT8 quantization+ elif self.quantize == 8:+ embedding = "vec_quantize_int8(?, 'unit')"++ # Standard FLOAT32+ else:+ embedding = "?"++ return embedding++ def tosql(self, sql):+ """+ Creates a SQL statement substituting in the configured table name.++ Args:+ sql: SQL statement with a {table} parameter++ Returns:+ fully resolved SQL statement+ """++ table = self.setting("table", "vectors")+ return sql.format(table=table)diff --git a/test/python/testann.py b/test/python/testann.pyindex 7e085b9d..f2e6bd8c 100644--- a/test/python/testann.py+++ b/test/python/testann.py@@ -126,7 +126,7 @@ class TestANN(unittest.TestCase):os.makedirs(output, exist_ok=True)# Generate data and save as pickle- data = np.random.rand(100, 300).astype(np.float32)+ data = np.random.rand(100, 240).astype(np.float32)serializer.save(data, path)ann = ANNFactory.create({"backend": "numpy"})@@ -142,14 +142,14 @@ class TestANN(unittest.TestCase):"""# Generate test record- data = np.random.rand(1, 300).astype(np.float32)+ data = np.random.rand(1, 240).astype(np.float32)# Mock database queryquery.return_value = [(x, -1.0) for x in range(data.shape[0])]# Create ANNpath = os.path.join(tempfile.gettempdir(), "pgvector.sqlite")- ann = ANNFactory.create({"backend": "pgvector", "pgvector": {"url": f"sqlite:///{path}"}, "dimensions": 300})+ ann = ANNFactory.create({"backend": "pgvector", "pgvector": {"url": f"sqlite:///{path}"}, "dimensions": 240})# Test indexingann.index(data)@@ -172,6 +172,45 @@ class TestANN(unittest.TestCase):# Close ANNann.close()+ def testSQLite(self):+ """+ Test SQLite backend+ """++ self.runTests("sqlite")++ def testSQLiteCustom(self):+ """+ Test SQLite backend with custom settings+ """++ # Test with custom settings+ self.runTests("sqlite", {"sqlite": {"quantize": 1}})+ self.runTests("sqlite", {"sqlite": {"quantize": 8}})++ # Test saving to a new path+ model = self.backend("sqlite")+ expected = model.count() - 1++ # Test save variations+ index = os.path.join(tempfile.gettempdir(), "ann.sqlite")+ new = os.path.join(tempfile.gettempdir(), "ann.sqlite.new")++ # Save new+ model.save(index)++ # Save to same path+ model.save(index)++ # Delete id+ model.delete([0])++ # Save to another path+ model.load(index)+ model.save(new)++ self.assertEqual(model.count(), expected)+def testTorch(self):"""Test Torch backend@@ -213,7 +252,7 @@ class TestANN(unittest.TestCase):"""# Generate test data- data = np.random.rand(length, 300).astype(np.float32)+ data = np.random.rand(length, 240).astype(np.float32)self.normalize(data)config = {"backend": name, "dimensions": data.shape[1]}@@ -242,7 +281,7 @@ class TestANN(unittest.TestCase):model = self.backend(name, params)# Generate test data- data = np.random.rand(length, 300).astype(np.float32)+ data = np.random.rand(length, 240).astype(np.float32)self.normalize(data)model.append(data)@@ -306,7 +345,7 @@ class TestANN(unittest.TestCase):model = self.backend(name, params)# Generate query vector- query = np.random.rand(300).astype(np.float32)+ query = np.random.rand(240).astype(np.float32)self.normalize(query)# Ensure top result has similarity > 0diff --git a/test/python/testoptional.py b/test/python/testoptional.pyindex 90d96b5e..f1df867e 100644--- a/test/python/testoptional.py+++ b/test/python/testoptional.py@@ -47,6 +47,7 @@ class TestOptional(unittest.TestCase):"sentence_transformers","soundfile","sqlalchemy",+ "sqlite_vec","tika","ttstokenizer","xmltodict",@@ -97,6 +98,9 @@ class TestOptional(unittest.TestCase):with self.assertRaises(ImportError):ANNFactory.create({"backend": "pgvector"})+ with self.assertRaises(ImportError):+ ANNFactory.create({"backend": "sqlite"})+def testApi(self):"""Test missing api dependencies