|
| 1 | +# SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai> |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +from haystack import component, default_from_dict, default_to_dict |
| 7 | +from haystack.dataclasses import Document |
| 8 | +from haystack.document_stores.types import FilterPolicy |
| 9 | +from haystack.document_stores.types.filter_policy import apply_filter_policy |
| 10 | + |
| 11 | +from haystack_integrations.document_stores.faiss import FAISSDocumentStore |
| 12 | + |
| 13 | + |
| 14 | +@component |
| 15 | +class FAISSEmbeddingRetriever: |
| 16 | + """ |
| 17 | + Retrieves documents from the `FAISSDocumentStore`, based on their dense embeddings. |
| 18 | +
|
| 19 | + Example usage: |
| 20 | + ```python |
| 21 | + from haystack import Document, Pipeline |
| 22 | + from haystack.components.embedders import SentenceTransformersTextEmbedder, SentenceTransformersDocumentEmbedder |
| 23 | + from haystack.document_stores.types import DuplicatePolicy |
| 24 | +
|
| 25 | + from haystack_integrations.document_stores.faiss import FAISSDocumentStore |
| 26 | + from haystack_integrations.components.retrievers.faiss import FAISSEmbeddingRetriever |
| 27 | +
|
| 28 | + document_store = FAISSDocumentStore(embedding_dim=768) |
| 29 | +
|
| 30 | + documents = [ |
| 31 | + Document(content="There are over 7,000 languages spoken around the world today."), |
| 32 | + Document(content="Elephants have been observed to behave in a way that indicates a high level of intelligence."), |
| 33 | + Document(content="In certain places, you can witness the phenomenon of bioluminescent waves."), |
| 34 | + ] |
| 35 | +
|
| 36 | + document_embedder = SentenceTransformersDocumentEmbedder() |
| 37 | + document_embedder.warm_up() |
| 38 | + documents_with_embeddings = document_embedder.run(documents)["documents"] |
| 39 | +
|
| 40 | + document_store.write_documents(documents_with_embeddings, policy=DuplicatePolicy.OVERWRITE) |
| 41 | +
|
| 42 | + query_pipeline = Pipeline() |
| 43 | + query_pipeline.add_component("text_embedder", SentenceTransformersTextEmbedder()) |
| 44 | + query_pipeline.add_component("retriever", FAISSEmbeddingRetriever(document_store=document_store)) |
| 45 | + query_pipeline.connect("text_embedder.embedding", "retriever.query_embedding") |
| 46 | +
|
| 47 | + query = "How many languages are there?" |
| 48 | + res = query_pipeline.run({"text_embedder": {"text": query}}) |
| 49 | +
|
| 50 | + assert res["retriever"]["documents"][0].content == "There are over 7,000 languages spoken around the world today." |
| 51 | + ``` |
| 52 | + """ |
| 53 | + |
| 54 | + def __init__( |
| 55 | + self, |
| 56 | + *, |
| 57 | + document_store: FAISSDocumentStore, |
| 58 | + filters: dict[str, Any] | None = None, |
| 59 | + top_k: int = 10, |
| 60 | + filter_policy: str | FilterPolicy = FilterPolicy.REPLACE, |
| 61 | + ): |
| 62 | + """ |
| 63 | + :param document_store: An instance of `FAISSDocumentStore`. |
| 64 | + :param filters: Filters applied to the retrieved Documents at initialisation time. At runtime, these are merged |
| 65 | + with any runtime filters according to the `filter_policy`. |
| 66 | + :param top_k: Maximum number of Documents to return. |
| 67 | + :param filter_policy: Policy to determine how init-time and runtime filters are combined. |
| 68 | + See `FilterPolicy` for details. Defaults to `FilterPolicy.REPLACE`. |
| 69 | + :raises ValueError: If `document_store` is not an instance of `FAISSDocumentStore`. |
| 70 | + """ |
| 71 | + if not isinstance(document_store, FAISSDocumentStore): |
| 72 | + msg = "document_store must be an instance of FAISSDocumentStore" |
| 73 | + raise ValueError(msg) |
| 74 | + |
| 75 | + self.document_store = document_store |
| 76 | + self.filters = filters or {} |
| 77 | + self.top_k = top_k |
| 78 | + self.filter_policy = ( |
| 79 | + filter_policy if isinstance(filter_policy, FilterPolicy) else FilterPolicy.from_str(filter_policy) |
| 80 | + ) |
| 81 | + |
| 82 | + def to_dict(self) -> dict[str, Any]: |
| 83 | + """ |
| 84 | + Serializes the component to a dictionary. |
| 85 | +
|
| 86 | + :returns: Dictionary with serialized data. |
| 87 | + """ |
| 88 | + return default_to_dict( |
| 89 | + self, |
| 90 | + filters=self.filters, |
| 91 | + top_k=self.top_k, |
| 92 | + filter_policy=self.filter_policy.value, |
| 93 | + document_store=self.document_store.to_dict(), |
| 94 | + ) |
| 95 | + |
| 96 | + @classmethod |
| 97 | + def from_dict(cls, data: dict[str, Any]) -> "FAISSEmbeddingRetriever": |
| 98 | + """ |
| 99 | + Deserializes the component from a dictionary. |
| 100 | +
|
| 101 | + :param data: Dictionary to deserialize from. |
| 102 | + :returns: Deserialized component. |
| 103 | + """ |
| 104 | + doc_store_params = data["init_parameters"]["document_store"] |
| 105 | + data["init_parameters"]["document_store"] = FAISSDocumentStore.from_dict(doc_store_params) |
| 106 | + # Pipelines serialized with old versions of the component might not |
| 107 | + # have the filter_policy field. |
| 108 | + if filter_policy := data["init_parameters"].get("filter_policy"): |
| 109 | + data["init_parameters"]["filter_policy"] = FilterPolicy.from_str(filter_policy) |
| 110 | + return default_from_dict(cls, data) |
| 111 | + |
| 112 | + @component.output_types(documents=list[Document]) |
| 113 | + def run( |
| 114 | + self, |
| 115 | + query_embedding: list[float], |
| 116 | + filters: dict[str, Any] | None = None, |
| 117 | + top_k: int | None = None, |
| 118 | + ) -> dict[str, list[Document]]: |
| 119 | + """ |
| 120 | + Retrieve documents from the `FAISSDocumentStore`, based on their embeddings. |
| 121 | +
|
| 122 | + :param query_embedding: Embedding of the query. |
| 123 | + :param filters: Filters applied to the retrieved Documents. The way runtime filters are applied depends on |
| 124 | + the `filter_policy` chosen at retriever initialization. See init method docstring for more |
| 125 | + details. |
| 126 | + :param top_k: Maximum number of Documents to return. Overrides the value set at initialization. |
| 127 | + :returns: A dictionary with the following keys: |
| 128 | + - `documents`: List of `Document`s that are similar to `query_embedding`. |
| 129 | + """ |
| 130 | + filters = apply_filter_policy(self.filter_policy, self.filters, filters) |
| 131 | + top_k = top_k or self.top_k |
| 132 | + docs = self.document_store.search(query_embedding=query_embedding, top_k=top_k, filters=filters) |
| 133 | + return {"documents": docs} |
| 134 | + |
| 135 | + @component.output_types(documents=list[Document]) |
| 136 | + async def run_async( |
| 137 | + self, |
| 138 | + query_embedding: list[float], |
| 139 | + filters: dict[str, Any] | None = None, |
| 140 | + top_k: int | None = None, |
| 141 | + ) -> dict[str, list[Document]]: |
| 142 | + """ |
| 143 | + Asynchronously retrieve documents from the `FAISSDocumentStore`, based on their embeddings. |
| 144 | +
|
| 145 | + Since FAISS search is CPU-bound and fully in-memory, this delegates directly to the synchronous |
| 146 | + `run()` method. No I/O or network calls are involved. |
| 147 | +
|
| 148 | + :param query_embedding: Embedding of the query. |
| 149 | + :param filters: Filters applied to the retrieved Documents. The way runtime filters are applied depends on |
| 150 | + the `filter_policy` chosen at retriever initialization. See init method docstring for more |
| 151 | + details. |
| 152 | + :param top_k: Maximum number of Documents to return. Overrides the value set at initialization. |
| 153 | + :returns: A dictionary with the following keys: |
| 154 | + - `documents`: List of `Document`s that are similar to `query_embedding`. |
| 155 | + """ |
| 156 | + return self.run(query_embedding=query_embedding, filters=filters, top_k=top_k) |
0 commit comments