Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Update documentation with 4.0 changes, closes #196

davidmezzetti66280ae339b3
diff --git a/docs/embeddings.md b/docs/embeddings/configuration.md
similarity index 66%
rename from docs/embeddings.md
rename to docs/embeddings/configuration.md
index fd6b775b..623e6b33 100644
--- a/docs/embeddings.md
+++ b/docs/embeddings/configuration.md
@@ -1,71 +1,57 @@
-# Embeddings
-Embeddings is the engine that delivers semantic search. Data is transformed into embeddings vectors where similar concepts will produce similar vectors. Indexes both large and small are built with these vectors. The indexes are used find results that have the same meaning, not necessarily the same keywords.
-
-Embeddings parameters are set through the constructor. Examples below.
-
-```python
-# Transformers embeddings model
-Embeddings({"method": "transformers",
- "path": "sentence-transformers/nli-mpnet-base-v2"})
-
-# Word embeddings model
-Embeddings({"method": "words",
- "path": vectors,
- "storevectors": True,
- "scoring": "bm25",
- "pca": 3,
- "quantize": True})
-```
-
-## Configuration
+# Configuration
-### method
+## method
```yaml
-method: transformers|sentence-transformers|words
+method: transformers|sentence-transformers|words|external
```
Sentence embeddings method to use. Options listed below.
-#### transformers
+### transformers
Builds sentence embeddings using a transformers model. While this can be any transformers model, it works best with
[models trained](https://huggingface.co/models?pipeline_tag=sentence-similarity) to build sentence embeddings.
-#### sentence-transformers
+### sentence-transformers
Same as transformers but loads models with the sentence-transformers library.
-#### words
+### words
Builds sentence embeddings using a word embeddings model.
-sentence-transformers and words require the [similarity](https://neuml.github.io/txtai/install/#similarity) extras package to be installed.
+### external
-The method is inferred using the _path_ if not provided.
+Sentence embeddings are loaded via an external model or API. Requires setting the `transform` parameter to a function that translates data into vectors.
-### path
+The method is inferred using the _path_, if not provided. sentence-transformers and words require the [similarity](../../install/#similarity) extras package to be installed.
+
+## path
```yaml
path: string
```
-Required field that sets the path for a vectors model. When using a transformers/sentence-transformers model, this can be any model on the
+Sets the path for a vectors model. When using a transformers/sentence-transformers model, this can be any model on the
[Hugging Face Model Hub](https://huggingface.co/models) or a local file path. Otherwise, it must be a local file path to a word embeddings model.
-### backend
+## backend
```yaml
backend: faiss|hnsw|annoy
```
Approximate Nearest Neighbor (ANN) index backend for storing generated sentence embeddings. Defaults to Faiss. Additional backends require the
-[similarity](https://neuml.github.io/txtai/install/#similarity) extras package to be installed.
+[similarity](../../install/#similarity) extras package to be installed.
Backend-specific settings are set with a corresponding configuration object having the same name as the backend (i.e. annoy, faiss, or hnsw). None of these are required and are set to defaults if omitted.
### faiss
```yaml
faiss:
- components: Comma separated list of components - defaults to "Flat" for small indices and "IVFx,Flat" for larger indexes where x = 4 * sqrt(embeddings count)
- nprobe: search probe setting (int) - defaults to x/16 (as defined above) for larger indexes
+ components: Comma separated list of components - defaults to "Flat" for small
+ indices and "IVFx,Flat" for larger indexes where
+ x = 4 * sqrt(embeddings count)
+ nprobe: search probe setting (int) - defaults to x/16 (as defined above)
+ for larger indexes
```
See the following Faiss documentation links for more information.
@@ -95,7 +81,14 @@ 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.
-### quantize
+## content
+```yaml
+content: string|boolean
+```
+
+Enables content storage. When true, the default content storage engine will be used. Otherwise, the string must specify the supported content storage engine to use.
+
+## quantize
```yaml
quantize: boolean
```
@@ -117,7 +110,7 @@ English language sentence embeddings in some situations.
Word embeddings provide a good tradeoff of performance to functionality for a similarity search system. With that being said, Transformers models are making great progress in scaling performance down to smaller models and are the preferred vector backend in txtai for most cases.
-Word embeddings models require the [similarity](https://neuml.github.io/txtai/install/#similarity) extras package to be installed.
+Word embeddings models require the [similarity](../../install/#similarity) extras package to be installed.
### storevectors
```yaml
@@ -139,15 +132,3 @@ pca: int
```
Removes _n_ principal components from generated sentence embeddings. When enabled, a TruncatedSVD model is built to help with dimensionality reduction. After pooling of vectors creates a single sentence embedding, this method is applied.
-
-::: txtai.embeddings.Embeddings.__init__
-::: txtai.embeddings.Embeddings.batchsearch
-::: txtai.embeddings.Embeddings.batchsimilarity
-::: txtai.embeddings.Embeddings.batchtransform
-::: txtai.embeddings.Embeddings.index
-::: txtai.embeddings.Embeddings.load
-::: txtai.embeddings.Embeddings.save
-::: txtai.embeddings.Embeddings.score
-::: txtai.embeddings.Embeddings.search
-::: txtai.embeddings.Embeddings.similarity
-::: txtai.embeddings.Embeddings.transform
diff --git a/docs/embeddings/methods.md b/docs/embeddings/methods.md
new file mode 100644
index 00000000..73a535ef
--- /dev/null
+++ b/docs/embeddings/methods.md
@@ -0,0 +1,3 @@
+# Methods
+
+::: txtai.embeddings.Embeddings
diff --git a/docs/embeddings/overview.md b/docs/embeddings/overview.md
new file mode 100644
index 00000000..0115c5a6
--- /dev/null
+++ b/docs/embeddings/overview.md
@@ -0,0 +1,88 @@
+# Embeddings
+
+Embeddings is the engine that delivers semantic search. Data is transformed into embeddings vectors where similar concepts will produce similar vectors. Indexes both large and small are built with these vectors. The indexes are used find results that have the same meaning, not necessarily the same keywords.
+
+The following code snippet shows how to build and search an embeddings index.
+
+```python
+from txtai.embeddings import Embeddings
+
+# Create embeddings model, backed by sentence-transformers & transformers
+embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2"})
+
+data = [
+ "US tops 5 million confirmed virus cases",
+ "Canada's last fully intact ice shelf has suddenly collapsed, " +
+ "forming a Manhattan-sized iceberg",
+ "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
+ "The National Park Service warns against sacrificing slower friends " +
+ "in a bear attack",
+ "Maine man wins $1M from $25 lottery ticket",
+ "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)])
+
+print("%-20s %s" % ("Query", "Best Match"))
+print("-" * 50)
+
+# Run an embeddings search for each query
+for query in ("feel good story", "climate change", "public health story", "war",
+ "wildlife", "asia", "lucky", "dishonest junk"):
+ # Extract uid of first result
+ # search result format: (uid, score)
+ uid = embeddings.search(query, 1)[0][0]
+
+ # Print text
+ print("%-20s %s" % (query, data[uid]))
+```
+
+## Build
+
+An embeddings instance can be created as follows:
+
+```python
+embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2"})
+```
+
+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. A number of different options are supported to cover a wide variety of use cases.
+
+## 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)])
+```
+
+The index method takes an iterable collection of tuples with three values.
+
+| Element | Description |
+| ----------- | ------------------------------------------------------------- |
+| id | unique record id |
+| 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 |
+
+The input iterable can be a list and/or a 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.
+
+txtai buffers data to temporary storage along the way during indexing as embeddings vectors can be quite large (for example 768 dimensions of float32 is 768 * 4 = 3072 bytes per vector).
+
+## Search
+
+Once data is indexed, it is ready for search.
+
+```python
+embeddings.search(query, limit)
+```
+
+The search method takes two parameters, the query and query limit. The results format is different based on whether [content](../configuration/#content) is stored or not.
+
+- List of `(id, score)` when content is disabled
+- List of `{**query columns}` when content is enabled
+
+## Links
+
+- [Configuration](../configuration)
+- [Methods](../methods)
+- [Query Guide](../query)
diff --git a/docs/embeddings/query.md b/docs/embeddings/query.md
new file mode 100644
index 00000000..0e898cce
--- /dev/null
+++ b/docs/embeddings/query.md
@@ -0,0 +1,119 @@
+# Query guide
+
+This section covers how to query data with txtai. The simplest way to search for data is building a natural language string with the desired content to find. txtai also supports querying with SQL. We'll cover both methods here.
+
+## Natural language queries
+
+In the simplest case, the query is text and the results are index text that is most similar to the query text.
+
+```python
+embeddings.search("feel good story")
+embeddings.search("wildlife")
+```
+
+The queries above search the index for similarity matches on `feel good story` and `wildlife`. If content storage is enabled, a list of `{**query columns}` is returned. Otherwise, a list of `(id, score)` tuples are returned.
+
+## SQL
+
+txtai supports more complex queries with [SQL](https://en.wikipedia.org/wiki/SQL). This is only supported if [content storage](../configuration/#content) is enabled. txtai has a translation layer that analyzes input SQL statements and combines similarity results with content stored in a relational database.
+
+SQL queries are run through `embeddings.search` like natural language queries but the examples below only show the SQL query for conciseness.
+
+```python
+embeddings.search("SQL query")
+```
+
+### Similar clause
+
+The similar clause is a txtai function that enables similarity searches with SQL.
+
+```sql
+SELECT id, text, score FROM txtai WHERE similar('feel good story')
+SELECT id, text, score FROM txtai WHERE similar('feel good story')
+```
+
+The similar clause takes two arguments:
+
+```sql
+similar("query", "number of candidates")
+```
+
+| Argument | Description |
+| --------------------- | ---------------------------------------|
+| query | natural language query to run |
+| number of candidates | number of candidate results to return |
+
+The txtai query layer has to join results from two separate components, a relational store and a similarity index. With a similar clause, a similarity search is run and those ids are fed to the underlying database query.
+
+The number of candidates should be larger than the desired number of results as additional filtering could occur. If this is not specified, it defaults to 10 times the number of desired results.
+
+### Dynamic columns
+
+Content can be indexed in multiple ways when content storage is enabled. [Remember that input documents](../overview#index) take the form of `(id, data, tags)` tuples. If data is a string, then content is primarily filtered with similar clauses. If data is a dictionary, then all fields in the dictionary are indexed and searchable.
+
+For example:
+
+```python
+embeddings.index([(0, {"text": "text to index", "flag": True,
+ "entry": "2022-01-01"}, None)])
+```
+
+With the above input data, queries can now have more complex filters.
+
+```sql
+SELECT text, flag, entry FROM txtai WHERE similar('query') AND flag = 1
+AND entry >= '2022-01-01'
+```
+
+txtai's query layer automatically detects columns and translates queries into a format that can be understood by the underlying database.
+
+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)])
+```
+
+```sql
+SELECT text FROM txtai WHERE [parent.child element] ='abc'
+```
+
+Note the bracket statement escaping the nested column with spaces in the name.
+
+### Aggregation queries
+
+The goal of txtai's query language is to closely support all functions in the underlying database engine. The main challenge is ensuring dynamic columns are properly escaped into the engines native query function.
+
+Aggregation query examples.
+
+```sql
+SELECT count(*) FROM txtai WHERE similar('feel good story') AND score >= 0.15
+SELECT max(length(text)) FROM txtai WHERE similar('feel good story')
+AND score >= 0.15
+SELECT count(*), flag FROM txtai GROUP BY flag ORDER BY count(*) DESC
+```
+
+## Binary objects
+
+txtai has support for storing and retrieving binary objects. Binary objects can be retrieved as shown in the example below.
+
+```python
+# Get an image
+request = open("demo.gif")
+
+# Insert record
+embeddings.index([("txtai", {"text": "txtai executes machine-learning workflows.",
+ "object": request.read()}, None)])
+
+# Query txtai and get associated object
+query = "select object from txtai where similar('machine learning') limit 1"
+result = embeddings.search(query)[0]["object"]
+```
+
+## Combined index architecture
+
+When content storage is enabled, txtai becomes a dual storage engine. Content is stored in an underlying database (currently supports [SQLite](https://en.wikipedia.org/wiki/SQLite)) along with an Approximate Nearest Neighbor (ANN) index. These components combine to deliver similarity search alongside traditional structured search.
+
+The ANN index stores ids and vectors for each input element. When a natural language query is run, the query is translated into a vector and a similarity query finds the best matching ids. When a database is added into the mix, an additional step is applied. This step takes those ids and effectively inserts them as part of the underlying database query.
+
+Dynamic columns are supported via the underlying engine. For SQLite, data is stored as JSON and dynamic columns are converted into `json_extract` clauses. This same concept can be expanded to other storage engines like PostgreSQL and could even work with NoSQL stores.
diff --git a/mkdocs.yml b/mkdocs.yml
index 6bea181b..284d8e7e 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -33,7 +33,11 @@ nav:
- Why txtai?: why.md
- Installation: install.md
- Examples: examples.md
- - Embeddings: embeddings.md
+ - Embeddings:
+ - Overview: embeddings/overview.md
+ - Configuration: embeddings/configuration.md
+ - Methods: embeddings/methods.md
+ - Query Guide: embeddings/query.md
- Pipeline:
- Overview: pipeline/overview.md
- Audio: