Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Add autoid, closes #502. Add kwargs, closes #503

davidmezzetti319a11cacfe8
diff --git a/README.md b/README.md
index 476bfcf6..c79e3f81 100644
--- a/README.md
+++ b/README.md
@@ -83,10 +83,10 @@ New vector databases, LLM frameworks and everything in between are sprouting up
# Get started in a couple lines
from txtai.embeddings import Embeddings
-embeddings = Embeddings({"path": "sentence-transformers/all-MiniLM-L6-v2"})
-embeddings.index([(0, "Correct", None), (1, "Not what we hoped", None)])
+embeddings = Embeddings()
+embeddings.index(["Correct", "Not what we hoped"])
embeddings.search("positive", 1)
-#[(0, 0.2986203730106354)]
+#[(0, 0.29862046241760254)]
```
- Built-in API makes it easy to develop applications using your programming language of choice
```yaml
diff --git a/docs/embeddings/configuration/index.md b/docs/embeddings/configuration/index.md
index dbc617d3..54875113 100644
--- a/docs/embeddings/configuration/index.md
+++ b/docs/embeddings/configuration/index.md
@@ -1,6 +1,6 @@
# Configuration
-This following describes available embeddings configuration. These parameters are set via the [Embeddings constructor](../methods#txtai.embeddings.base.Embeddings.__init__).
+This following describes available embeddings configuration. These parameters are set in the [Embeddings constructor](../methods#txtai.embeddings.base.Embeddings.__init__) via either the `config` parameter or as keyword arguments.
## format
```yaml
@@ -170,7 +170,7 @@ See [Annoy documentation](https://github.com/spotify/annoy#full-python-api) for
content: boolean|sqlite|duckdb|custom
```
-Enables content storage. When true, the default storage engine, `sqlite` will be used. Also supports `duckdb`. Add custom storage engines via setting this parameter to the fully resolvable class string.
+Enables content storage. When true, the default storage engine, `sqlite` will be used to save metadata alongside embeddings vectors. Also supports `duckdb`. Add custom storage engines via setting this parameter to the fully resolvable class string.
Content storage specific settings are set with a corresponding configuration object having the same name as the content storage engine (i.e. duckdb or sqlite). None of these are required and are set to defaults if omitted.
@@ -181,6 +181,13 @@ sqlite:
defaults to false
```
+## objects
+```yaml
+objects: boolean
+```
+
+Enables object storage. When content storage is enabled and this is true, support for storing binary content alongside embeddings vectors and metadata is enabled.
+
## functions
```yaml
functions: list
diff --git a/docs/embeddings/index.md b/docs/embeddings/index.md
index e2a2df27..f68917e1 100644
--- a/docs/embeddings/index.md
+++ b/docs/embeddings/index.md
@@ -11,7 +11,7 @@ The following code snippet shows how to build and search an embeddings index.
from txtai.embeddings import Embeddings
# Create embeddings model, backed by sentence-transformers & transformers
-embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2"})
+embeddings = Embeddings(path="sentence-transformers/nli-mpnet-base-v2")
data = [
"US tops 5 million confirmed virus cases",
@@ -24,10 +24,10 @@ data = [
"Make huge profits without work, earn up to $100,000 a day"
]
-# Create an index for the list of text
-embeddings.index([(uid, text, None) for uid, text in enumerate(data)])
+# Index the list of text
+embeddings.index(data)
-print("%-20s %s" % ("Query", "Best Match"))
+print(f"{'Query':20} Best Match")
print("-" * 50)
# Run an embeddings search for each query
@@ -38,30 +38,32 @@ for query in ("feel good story", "climate change", "public health story", "war",
uid = embeddings.search(query, 1)[0][0]
# Print text
- print("%-20s %s" % (query, data[uid]))
+ print(f"{query:20} {data[uid]}")
```
## Build
-An embeddings instance can be created as follows:
+An embeddings instance is [configuration-driven](configuration) based on what is passed in the constructor. Vectors are stored with the option to also [store content](configuration#content). Content storage enables additional filtering and data retrieval options.
+
+The example above sets a specific embeddings vector model via the [path](configuration#path) parameter. An embeddings instance with no configuration can also be created.
```python
-embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2"})
+embeddings = Embeddings()
```
-The example above builds a transformers-based embeddings instance. In this case, when loading and searching for data, a transformers model is used to vectorize data.
-
-The embeddings instance is [configuration-driven](configuration) based on what is passed in the constructor. Embeddings indexes store vectors and can optionally [store content](configuration#content). Content storage enables additional filtering and data retrieval options.
+In this case, when loading and searching for data, the [default transformers vector model](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) is used to vectorize data. See the [model guide](../models) for current model recommentations.
## Index
After creating a new embeddings instance, the next step is adding data to it.
```python
-embeddings.index([(uid, text, None) for uid, text in enumerate(data)])
+embeddings.index(rows)
```
-The index method takes an iterable collection of tuples with three values.
+The index method takes an iterable and supports the following formats for each element.
+
+- `(id, data, tags)` - default processing format
| Element | Description |
| ----------- | ------------------------------------------------------------- |
@@ -69,7 +71,15 @@ The index method takes an iterable collection of tuples with three values.
| data | input data to index, can be text, a dictionary or object |
| tags | optional tags string, used to mark/label data as it's indexed |
-When the data element is a dictionary and it has a field named `text`, that will be used for indexing.
+- `(id, data)`
+
+ Same as above but without tags.
+
+- `data`
+
+Single element to index. In this case, unique id's will automatically be generated. Note that for generated id's, [upsert](methods/#txtai.embeddings.base.Embeddings.upsert) and [delete](methods/#txtai.embeddings.base.Embeddings.delete) calls require a separate search to get the target ids.
+
+When the data field is a dictionary, text is passed via the `text` key, binary objects via the `object` key. Note that [content](configuration#content) must be enabled to store metadata and [objects](configuration#objects) to store binary object data. The `id` and `tags` keys will be extracted, if provided.
The input iterable can be a list or generator. [Generators](https://wiki.python.org/moin/Generators) help with indexing very large datasets as only portions of the data is in memory at any given time.
diff --git a/docs/embeddings/indexing.md b/docs/embeddings/indexing.md
index 323c1d31..db7f1b82 100644
--- a/docs/embeddings/indexing.md
+++ b/docs/embeddings/indexing.md
@@ -73,7 +73,7 @@ embeddings.delete(ids)
When [content storage](../configuration#content) is enabled, [reindex](../methods#txtai.embeddings.base.Embeddings.reindex) can be called to rebuild the index with new settings. For example, the backend can be switched from faiss to hnsw or the vector model can be updated. This prevents having to go back to the original raw data.
```python
-embeddings.reindex({"path": "sentence-transformers/all-MiniLM-L6-v2", "backend": "hnsw"})
+embeddings.reindex(path="sentence-transformers/all-MiniLM-L6-v2", backend="hnsw")
```
## Graph
@@ -109,8 +109,8 @@ Graphs are persisted alongside an embeddings index. Each save and load will also
When using [word vector backed models](../configuration#words) with scoring set, a separate call is required before calling `index` as follows:
```python
-embeddings.score([(uid, text, None) for uid, text in enumerate(data)])
-embeddings.index([(uid, text, None) for uid, text in enumerate(data)])
+embeddings.score(rows)
+embeddings.index(rows)
```
Two calls are required to support generator-backed iteration of data. The scoring index requires a separate full-pass of the data.
diff --git a/docs/embeddings/query.md b/docs/embeddings/query.md
index 0dac0ff6..796262fe 100644
--- a/docs/embeddings/query.md
+++ b/docs/embeddings/query.md
@@ -60,8 +60,8 @@ Content can be indexed in multiple ways when content storage is enabled. [Rememb
For example:
```python
-embeddings.index([(0, {"text": "text to index", "flag": True,
- "entry": "2022-01-01"}, None)])
+embeddings.index([{"text": "text to index", "flag": True,
+ "entry": "2022-01-01"}])
```
With the above input data, queries can now have more complex filters.
@@ -76,12 +76,12 @@ txtai's query layer automatically detects columns and translates queries into a
Nested dictionaries/JSON is supported and can be escaped with bracket statements.
```python
-embeddings.index([(0, {"text": "text to index",
- "parent": {"child element": "abc"}}, None)])
+embeddings.index([{"text": "text to index",
+ "parent": {"child element": "abc"}}])
```
```sql
-SELECT text FROM txtai WHERE [parent.child element] ='abc'
+SELECT text FROM txtai WHERE [parent.child element] = 'abc'
```
Note the bracket statement escaping the nested column with spaces in the name.
@@ -104,12 +104,15 @@ SELECT count(*), flag FROM txtai GROUP BY flag ORDER BY count(*) DESC
txtai has support for storing and retrieving binary objects. Binary objects can be retrieved as shown in the example below.
```python
+# Create embeddings index with content and object storage enabled
+embeddings = Embeddings(content=True, objects=True)
+
# Get an image
-request = open("demo.gif")
+request = open("demo.gif", "rb")
# Insert record
embeddings.index([("txtai", {"text": "txtai executes machine-learning workflows.",
- "object": request.read()}, None)])
+ "object": request.read()})])
# Query txtai and get associated object
query = "select object from txtai where similar('machine learning') limit 1"
@@ -125,9 +128,9 @@ Custom, user-defined SQL functions extend selection, filtering and ordering clau
translate = Translation()
# Create embeddings index
-embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2",
- "content": True,
- "functions": [translate]})
+embeddings = Embeddings(path="sentence-transformers/nli-mpnet-base-v2",
+ content=True,
+ functions=[translate]})
# Run a search using a custom SQL function
embeddings.search("""
diff --git a/docs/why.md b/docs/why.md
index 1d991eca..a69bfdc6 100644
--- a/docs/why.md
+++ b/docs/why.md
@@ -10,10 +10,10 @@ New vector databases, LLM frameworks and everything in between are sprouting up
# Get started in a couple lines
from txtai.embeddings import Embeddings
-embeddings = Embeddings({"path": "sentence-transformers/all-MiniLM-L6-v2"})
-embeddings.index([(0, "Correct", None), (1, "Not what we hoped", None)])
+embeddings = Embeddings()
+embeddings.index(["Correct", "Not what we hoped"])
embeddings.search("positive", 1)
-#[(0, 0.2986203730106354)]
+#[(0, 0.29862046241760254)]
```
- Built-in API makes it easy to develop applications using your programming language of choice
```yaml
diff --git a/src/python/txtai/app/base.py b/src/python/txtai/app/base.py
index dfe4be63..6c2c6757 100644
--- a/src/python/txtai/app/base.py
+++ b/src/python/txtai/app/base.py
@@ -207,7 +207,7 @@ class Application:
# Load existing index if available
self.embeddings = Embeddings()
self.embeddings.load(self.config.get("path"), self.config.get("cloud"))
- elif config:
+ elif "embeddings" in self.config:
# Initialize empty embeddings
self.embeddings = Embeddings(config)
@@ -359,25 +359,8 @@ class Application:
if not self.documents:
self.documents = Documents()
- batch = []
- index = self.embeddings.config.get("offset", 0) + len(self.documents)
- for document in documents:
- if isinstance(document, dict):
- # Create (id, data, tags) tuple from dictionary
- document = (document["id"], document, document.get("tags"))
- elif isinstance(document, tuple):
- # Create (id, data, tags) tuple
- document = (document[0], document[1], None) if len(document) < 3 else document[:3]
- else:
- # Create (id, data, tags) tuple using id autosequence
- document = (index, document, None)
- index += 1
-
- # Add document tuple (id, data, tags)
- batch.append(document)
-
- # Add batch
- self.documents.add(batch)
+ # Add documents
+ self.documents.add(documents)
# Return unmodified input documents
return documents
diff --git a/src/python/txtai/embeddings/__init__.py b/src/python/txtai/embeddings/__init__.py
index 2df4abbb..379af0f0 100644
--- a/src/python/txtai/embeddings/__init__.py
+++ b/src/python/txtai/embeddings/__init__.py
@@ -2,6 +2,7 @@
Embeddings imports
"""
+from .action import Action
from .base import Embeddings
from .documents import Documents
from .explain import Explain
diff --git a/src/python/txtai/embeddings/action.py b/src/python/txtai/embeddings/action.py
new file mode 100644
index 00000000..75ffff1b
--- /dev/null
+++ b/src/python/txtai/embeddings/action.py
@@ -0,0 +1,15 @@
+"""
+Action module
+"""
+
+from enum import Enum
+
+
+class Action(Enum):
+ """
+ Index action types
+ """
+
+ INDEX = 1
+ UPSERT = 2
+ REINDEX = 3
diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.py
index 191aeee4..707600f9 100644
--- a/src/python/txtai/embeddings/base.py
+++ b/src/python/txtai/embeddings/base.py
@@ -20,13 +20,15 @@ from ..graph import GraphFactory
from ..scoring import ScoringFactory
from ..vectors import VectorsFactory
+from .action import Action
from .explain import Explain
from .functions import Functions
from .reducer import Reducer
from .query import Query
from .search import Search
+from .stream import Stream
from .terms import Terms
-from .transform import Action, Transform
+from .transform import Transform
# pylint: disable=R0904
@@ -38,13 +40,14 @@ class Embeddings:
"""
# pylint: disable = W0231
- def __init__(self, config=None):
+ def __init__(self, config=None, **kwargs):
"""
Creates a new embeddings index. Embeddings indexes are thread-safe for read operations but writes must be
synchronized.
Args:
config: embeddings configuration
+ kwargs: additional configuration as keyword args
"""
# Index configuration
@@ -74,6 +77,9 @@ class Embeddings:
# Index archive
self.archive = None
+ # Merge configuration into single dictionary
+ config = {**config, **kwargs} if config and kwargs else kwargs if kwargs else config
+
# Set initial configuration
self.configure(config)
@@ -82,19 +88,19 @@ class Embeddings:
Builds a scoring index. Only used by word vectors models.
Args:
- documents: list of (id, data, tags)
+ documents: iterable of (id, data, tags), (id, data) or data
"""
- # Build scoring index over documents
+ # Build scoring index for word vectors term weighting
if self.scoring:
- self.scoring.index(documents)
+ self.scoring.index(Stream(self)(documents))
def index(self, documents, reindex=False):
"""
Builds an embeddings index. This method overwrites an existing index.
Args:
- documents: list of (id, data, tags)
+ documents: iterable of (id, data, tags), (id, data) or data
reindex: if this is a reindex operation in which case database creation is skipped, defaults to False
"""
@@ -111,12 +117,13 @@ class Embeddings:
# Create graph, if necessary
self.graph = self.creategraph()
- # Create transform action
+ # Create transform and stream
transform = Transform(self, Action.REINDEX if reindex else Action.INDEX)
+ stream = Stream(self, Action.REINDEX if reindex else Action.INDEX)
with tempfile.NamedTemporaryFile(mode="wb", suffix=".npy") as buffer:
# Load documents into database and transform to vectors
- ids, dimensions, embeddings = transform(documents, buffer)
+ ids, dimensions, embeddings = transform(stream(documents), buffer)
if ids:
# Build LSA model (if enabled). Remove principal components from embeddings.
if self.config.get("pca"):
@@ -135,7 +142,7 @@ class Embeddings:
# Add embeddings to the index
self.ann.index(embeddings)
- # Save indexids-ids mapping for indexes with no database, except when this is a reindex action
+ # Save indexids-ids mapping for indexes with no database, except when this is a reindex
if not reindex and not self.database:
self.config["ids"] = ids
@@ -150,7 +157,7 @@ class Embeddings:
this method runs a standard index operation.
Args:
- documents: list of (id, data, tags)
+ documents: iterable of (id, data, tags), (id, data) or data
"""
# Run standard insert if index doesn't exist or it has no records
@@ -158,12 +165,13 @@ class Embeddings:
self.index(documents)
return
- # Create transform action
+ # Create transform and stream
transform = Transform(self, Action.UPSERT)
+ stream = Stream(self, Action.UPSERT)
with tempfile.NamedTemporaryFile(mode="wb", suffix=".npy") as buffer:
# Load documents into database and transform to vectors
- ids, _, embeddings = transform(documents, buffer)
+ ids, _, embeddings = transform(stream(documents), buffer)
if ids:
# Remove principal components from embeddings, if necessary
if self.reducer:
@@ -269,7 +277,7 @@ class Embeddings:
Transforms document into an embeddings vector.
Args:
- document: (id, data, tags)
+ documents: iterable of (id, data, tags), (id, data) or data
Returns:
embeddings vector
@@ -282,15 +290,18 @@ class Embeddings:
Transforms documents into embeddings vectors.
Args:
- documents: list of (id, data, tags)
+ documents: iterable of (id, data, tags), (id, data) or data
category: category for instruction-based embeddings
Returns:
embeddings vectors
"""
+ # Initialize default parameters, if necessary
+ self.defaults()
+
# Convert documents into sentence embeddings
- embeddings = self.model.batchtransform(documents, category)
+ embeddings = self.model.batchtransform(Stream(self)(documents), category)
# Reduce the dimensionality of the embeddings. Scale the embeddings using this
# model to reduce the noise of common but less relevant terms.
diff --git a/src/python/txtai/embeddings/stream.py b/src/python/txtai/embeddings/stream.py
new file mode 100644
index 00000000..6460bb10
--- /dev/null
+++ b/src/python/txtai/embeddings/stream.py
@@ -0,0 +1,62 @@
+"""
+Stream module
+"""
+
+from .transform import Action
+
+
+class Stream:
+ """
+ Yields input document as standard (id, data, tags) tuples.
+ """
+
+ def __init__(self, embeddings, action=None):
+ """
+ Create a new stream.
+
+ Args:
+ embeddings: embeddings instance
+ action: optional index action
+ """
+
+ self.embeddings = embeddings
+ self.action = action
+
+ # Alias embeddings attributes
+ self.config = self.embeddings.config
+
+ # Get config parameters
+ self.offset = self.config.get("offset", 0) if self.action == Action.UPSERT else 0
+ self.autoid = self.config.get("autoid", self.offset) if self.action == Action.UPSERT else 0
+
+ def __call__(self, documents):
+ """
+ Yield (id, data, tags) tuples from a stream of documents.
+
+ Args:
+ documents: input documents
+ """
+
+ # Iterate over documents and yield standard (id, data, tag) tuples
+ for document in documents:
+ if isinstance(document, dict):
+ # Create (id, data, tags) tuple from dictionary
+ document = document.get("id"), document, document.get("tags")
+ elif isinstance(document, tuple):
+ # Create (id, data, tags) tuple
+ document = document if len(document) >= 3 else (document[0], document[1], None)
+ else:
+ # Create (id, data, tags) tuple with empty fields
+ document = None, document, None
+
+ # Set autoid if the action is set
+ if self.action and document[0] is None:
+ document = (self.autoid, document[1], document[2])
+ self.autoid += 1
+
+ # Yield (id, data, tags) tuple
+ yield document
+
+ # Save autoid sequence if used
+ if self.action and self.autoid:
+ self.config["autoid"] = self.autoid
diff --git a/src/python/txtai/embeddings/transform.py b/src/python/txtai/embeddings/transform.py
index d9ddcfbe..3702ddd2 100644
--- a/src/python/txtai/embeddings/transform.py
+++ b/src/python/txtai/embeddings/transform.py
@@ -5,23 +5,23 @@ Transform module
import os
import pickle
-from enum import Enum
-
import numpy as np
+from .action import Action
+
class Transform:
"""
- Executes a transform action. Processes a stream of documents, loads batches into a database and vectorizes documents.
+ Executes a transform. Processes a stream of documents, loads batches into a database and vectorizes documents.
"""
def __init__(self, embeddings, action):
"""
- Creates a new transform action.
+ Creates a new transform.
Args:
embeddings: embeddings instance
- action: transform action
+ action: index action
"""
self.embeddings = embeddings
@@ -47,7 +47,7 @@ class Transform:
This method loads a stream of documents into a database (if applicable) and vectorizes documents into an embeddings array.
Args:
- documents: iterable collection of (id, data, tags)
+ documents: iterable of (id, data, tags)
buffer: file path used for memmap buffer
Returns:
@@ -147,13 +147,3 @@ class Transform:
# Increment offset
self.offset += offset
-
-
-class Action(Enum):
- """
- Transform action types
- """
-
- INDEX = 1
- UPSERT = 2
- REINDEX = 3
diff --git a/src/python/txtai/vectors/words.py b/src/python/txtai/vectors/words.py
index bb13d492..6147db8c 100644
--- a/src/python/txtai/vectors/words.py
+++ b/src/python/txtai/vectors/words.py
@@ -89,7 +89,7 @@ class WordVectors(Vectors):
# pylint: disable=E1133
if weights and [x for x in weights if x > 0]:
- # Build weighted average embeddings vector. Create weights array os float32 to match embeddings precision.
+ # Build weighted average embeddings vector. Create weights array as float32 to match embeddings precision.
embedding = np.average(self.lookup(tokens), weights=np.array(weights, dtype=np.float32), axis=0)
else:
# If no weights, use mean