diff --git a/README.md b/README.md index 7df1263..ba6032c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # VectorDB -[![](https://dcbadge.vercel.app/api/server/aDNg6E9szy?compact=true&style=flat)](https://discord.gg/aDNg6E9szy) [![Twitter](https://img.shields.io/twitter/follow/KagiHQ?style=social)](https://twitter.com/KagiHQ) [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/license/mit/) +[![](https://dcbadge.vercel.app/api/server/aDNg6E9szy?compact=true&style=flat)](https://discord.gg/aDNg6E9szy) [![Twitter](https://img.shields.io/twitter/follow/KagiHQ?style=social)](https://twitter.com/KagiHQ) [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/license/mit/) VectorDB is a simple, lightweight, fully local, end-to-end solution for using embeddings-based text retrieval. @@ -8,7 +8,6 @@ Thanks to its low latency and small memory footprint, VectorDB is used to power Check an [example Colab notebook](https://colab.research.google.com/drive/1pecKGCCru_Jvx7v0WRNrW441EBlcS5qS#scrollTo=Eh6o8m7d8eOk) where this is used to filter the content of [Kagi Small Web](https://kagi.com/smallweb) RSS feed based on stated user interests. - ## Installation To install VectorDB, use pip: @@ -19,7 +18,7 @@ pip install vectordb2 ## Usage -Quick example that loads data into memory, and runs retrieval. All data will be handled locally, including embeddings and vector search, completely trasparent for the user with maximum possible performance. +Quick example that loads data into memory, and runs retrieval. All data will be handled locally, including embeddings and vector search, completely trasparent for the user with maximum possible performance. ```python from vectordb import Memory @@ -53,55 +52,52 @@ This returns the chunks with the added metadata and the vector distance (where 0 ## Options - **Memory(memory_file=None, chunking_strategy={"mode":"sliding_window"}, embeddings="normal")** +- `memory_file`: _Optional._ Path to the memory file. If provided, memory will persist to disk and loaded/saved to this file. +- `chunking_strategy`: _Optional._ Dictionary containing the chunking mode. -- `memory_file`: *Optional.* Path to the memory file. If provided, memory will persist to disk and loaded/saved to this file. -- `chunking_strategy`: *Optional.* Dictionary containing the chunking mode. - - Options:\ - `{'mode':'sliding_window', 'window_size': 240, 'overlap': 8}` (default)\ + Options:\ + `{'mode':'sliding_window', 'window_size': 240, 'overlap': 8}` (default)\ `{'mode':'paragraph'}` -- `embeddings`: *Optional.* - - Options:\ + +- `embeddings`: _Optional._ + + Options:\ `fast` - Uses Universal Sentence Encoder 4\ `normal` - Uses "BAAI/bge-small-en-v1.5" (default)\ `best` - Uses "BAAI/bge-base-en-v1.5"\ `multilingual` - Uses Universal Sentence Encoder Multilingual Large 3 - - You can also specify a custom HuggingFace model by name eg. `TaylorAI/bge-micro-v2`. See also [Pretrained models](https://www.sbert.net/docs/pretrained_models.html) and [MTEB](https://huggingface.co/spaces/mteb/leaderboard). + You can also specify a custom HuggingFace model by name eg. `TaylorAI/bge-micro-v2`. See also [Pretrained models](https://www.sbert.net/docs/pretrained_models.html) and [MTEB](https://huggingface.co/spaces/mteb/leaderboard). **Memory.save(texts, metadata, memory_file=None)** Save content to memory. Metadata will be automatically optimized to use less resources. -- `texts`: *Required.* Text or list of texts to be saved. -- `metdata`: *Optional.* Metadata or list of metadata associated with the texts. -- `memory_file`: *Optional.* Path to persist the memory file. By default +- `texts`: _Required._ Text or list of texts to be saved. +- `metdata`: _Optional._ Metadata or list of metadata associated with the texts. +- `memory_file`: _Optional._ Path to persist the memory file. By default **Memory.search(query, top_n=5, unique=False, batch_results="flatten")** Search inside memory. -- `query`: *Required.* Query text or list of queries (see `batch_results` option below for handling results for a list). -- `top_n`: *Optional.* Number of most similar chunks to return (default: 5). -- `unique`: *Optional.* Return only items chunks from unique original texts (additional chunks coming from the same text will be ignored). Note this may return less chhunks than requested (default: False). -- `batch_results`: *Optional.* When input is a list of queries, output algorithm can be "flatten" or "diverse". Flatten returns true nearest neighbours across all input queries, meaning all results could come from just one query. "diverse" attempts to spread out the results, so that each query's nearest neighbours are equally added (neareast first across all queries, than 2nd nearest and so on). (default: "flatten") +- `query`: _Required._ Query text or list of queries (see `batch_results` option below for handling results for a list). +- `top_n`: _Optional._ Number of most similar chunks to return (default: 5). +- `unique`: _Optional._ Return only items chunks from unique original texts (additional chunks coming from the same text will be ignored). Note this may return less chunks than requested (default: False). +- `batch_results`: _Optional._ When input is a list of queries, output algorithm can be "flatten" or "diverse". Flatten returns true nearest neighbours across all input queries, meaning all results could come from just one query. "diverse" attempts to spread out the results, so that each query's nearest neighbours are equally added (neareast first across all queries, than 2nd nearest and so on). (default: "flatten") +- `context` Optional. When `context = n` (default 0), n chunks before and after the result in the original text are returned along with the result. This is useful when using sliding window with smaller chunks, or paragraph chunking when you have relatively short paragraphs. **Memory.clear()** Clears the memory. - **Memory.dump()** Prints the contents of the memory. - ## Example ```python @@ -184,6 +180,7 @@ print(results) ``` Output: + ```json [ { @@ -208,40 +205,34 @@ Output: ## Embeddings performance analysis - -We constantly evaluate embedding models using standardized benchmarks (higher is better). Average latency is measured locally on CPU (lower is better). Benchmark data pulled from [MTEB](https://huggingface.co/spaces/mteb/leaderboard). - - - -| Model | Latency | Benchmark 1 | Benchmark 2 | Benchmark 3 | Benchmark 4 | -|-----------------------------------------------|----------|-------------|-------------|-------------|-------------| -| all-mpnet-base-v2 | 6.12 s | 80.28 | 65.07 | 43.69 | 83.04 | -| all-MiniLM-L6-v2 | 1.14 s | 78.9 | 63.05 | 42.35 | 82.37 | -| BAAI/bge-large-en-v1.5 | 20.8 s | 83.11 | 75.97 | 46.08 | 87.12 | -| BAAI/bge-base-en-v1.5 | 6.48 s | 82.4 | 75.53 | 45.77 | 86.55 | -| BAAI/bge-small-en-v1.5 | 1.85 s | 81.59 | 74.14 | 43.82 | 84.92 | -| TaylorAI/bge-micro-v2 | 0.671 s | 78.65 | 68.04 | 39.18 | 82.81 | -| TaylorAI/gte-tiny | 1.25 s | 80.46 | 70.35 | 42.09 | 82.83 | -| thenlper/gte-base | 6.28 s | 82.3 | 73.01 | 46.2 | 84.57 | -| thenlper/gte-small | 2.14 s | 82.07 | 72.31 | 44.89 | 83.54 | -| universal-sentence-encoder-large/5 | 0.769 s | 74.05 | 67.9 | 37.82 | 79.53 | -| universal-sentence-encoder-multilingual-large/3| 1.02 s | 75.35 | 65.78 | 35.06 | 79.62 | -| universal-sentence-encoder-multilingual/3 | 0.162 s | 75.39 | 63.42 | 34.82 | 75.43 | -| universal-sentence-encoder/4 | 0.019 s | 72.04 | 64.45 | 35.71 | 76.23 | - -*Relative embeddings latency on CPU* +We constantly evaluate embedding models using standardized benchmarks (higher is better). Average latency is measured locally on CPU (lower is better). Benchmark data pulled from [MTEB](https://huggingface.co/spaces/mteb/leaderboard). + +| Model | Latency | Benchmark 1 | Benchmark 2 | Benchmark 3 | Benchmark 4 | +| ----------------------------------------------- | ------- | ----------- | ----------- | ----------- | ----------- | +| all-mpnet-base-v2 | 6.12 s | 80.28 | 65.07 | 43.69 | 83.04 | +| all-MiniLM-L6-v2 | 1.14 s | 78.9 | 63.05 | 42.35 | 82.37 | +| BAAI/bge-large-en-v1.5 | 20.8 s | 83.11 | 75.97 | 46.08 | 87.12 | +| BAAI/bge-base-en-v1.5 | 6.48 s | 82.4 | 75.53 | 45.77 | 86.55 | +| BAAI/bge-small-en-v1.5 | 1.85 s | 81.59 | 74.14 | 43.82 | 84.92 | +| TaylorAI/bge-micro-v2 | 0.671 s | 78.65 | 68.04 | 39.18 | 82.81 | +| TaylorAI/gte-tiny | 1.25 s | 80.46 | 70.35 | 42.09 | 82.83 | +| thenlper/gte-base | 6.28 s | 82.3 | 73.01 | 46.2 | 84.57 | +| thenlper/gte-small | 2.14 s | 82.07 | 72.31 | 44.89 | 83.54 | +| universal-sentence-encoder-large/5 | 0.769 s | 74.05 | 67.9 | 37.82 | 79.53 | +| universal-sentence-encoder-multilingual-large/3 | 1.02 s | 75.35 | 65.78 | 35.06 | 79.62 | +| universal-sentence-encoder-multilingual/3 | 0.162 s | 75.39 | 63.42 | 34.82 | 75.43 | +| universal-sentence-encoder/4 | 0.019 s | 72.04 | 64.45 | 35.71 | 76.23 | + +_Relative embeddings latency on CPU_ ![Embeddings Latency on CPU](images/speed_cpu.png) -*Relative embeddings latency on GPU* +_Relative embeddings latency on GPU_ ![Embeddings Latency on GPU](images/speed_gpu.png) - ![Embeddings Quality](images/quality.png) ![Scatter of Embeddings](images/scatter.png) - - ## Vector search performance analysis VectorDB is also optimized for speed of retrieval. We automatically uses [Faiss](https://github.com/facebookresearch/faiss) for low number of chunks (<4000) and [mrpt](https://github.com/vioshyvo/mrpt) for high number of chunks to ensure maximum performance across the spectrum of use cases. diff --git a/vectordb/memory.py b/vectordb/memory.py index b2a4dcb..ddb5013 100644 --- a/vectordb/memory.py +++ b/vectordb/memory.py @@ -133,7 +133,7 @@ def save( Storage(self.memory_file).save_to_disk([{"memory": self.memory, "metadata" :self.metadata_memory}]) def search( - self, query: str, top_n: int = 5, unique: bool = False, batch_results: str = "flatten" + self, query: str, top_n: int = 5, unique: bool = False, batch_results: str = "flatten", context: int = 0 ) -> List[Dict[str, Any]]: """ Searches for the most similar chunks to the given query in memory. @@ -170,14 +170,19 @@ def search( ) # Use seen_text_indices instead of seen_meta_indices indices = unique_indices - results = [ - { - "chunk": self.memory[i[0]]["chunk"], - "metadata": self.metadata_memory[self.memory[i[0]]["metadata_index"]], - "distance": i[1], - } - for i in indices - ] + results = [] + for i in indices: + chunk_with_context = "" + for j in range(-context, context+1): + chunk_with_context += self.memory[i[0]+j]["chunk"] if i[0]+j >= 0 and i[0]+j < len(self.memory) else "" + results += [ + { + "chunk": chunk_with_context, + "metadata": self.metadata_memory[self.memory[i[0]]["metadata_index"]], + "distance": i[1], + } + ] + return results