Retriever that can enrich documents with similarity scores and embeddings. Extends LangChain's ``VectorStoreRetriever`` with a ``"similarity_with_embeddings"`` search type. When used, each returned document's ``metadata`` dict gains ``__similarity`` (float) and ``__embeddings`` (li
| 17 | |
| 18 | |
| 19 | class AdvancedVectorStoreRetriever(VectorStoreRetriever): |
| 20 | """Retriever that can enrich documents with similarity scores and embeddings. |
| 21 | |
| 22 | Extends LangChain's ``VectorStoreRetriever`` with a |
| 23 | ``"similarity_with_embeddings"`` search type. When used, each |
| 24 | returned document's ``metadata`` dict gains ``__similarity`` (float) |
| 25 | and ``__embeddings`` (list[float]) keys. |
| 26 | """ |
| 27 | |
| 28 | allowed_search_types: ClassVar[Collection[str]] = ( |
| 29 | "similarity", |
| 30 | "similarity_score_threshold", |
| 31 | "mmr", |
| 32 | "similarity_with_embeddings", |
| 33 | ) |
| 34 | |
| 35 | def _get_relevant_documents(self, query: str, *, run_manager: CallbackManagerForRetrieverRun) -> List[Document]: |
| 36 | """Fetch relevant documents for the configured search type. |
| 37 | |
| 38 | Supports all standard search types plus |
| 39 | ``"similarity_with_embeddings"`` which attaches score and |
| 40 | embedding vector metadata to each document. |
| 41 | |
| 42 | Args: |
| 43 | query: The search query string. |
| 44 | run_manager: LangChain callback manager. |
| 45 | |
| 46 | Returns: |
| 47 | list[Document]: Retrieved documents, optionally enriched |
| 48 | with similarity scores and embeddings. |
| 49 | """ |
| 50 | |
| 51 | if self.search_type == "similarity_with_embeddings": |
| 52 | docs_scores_and_embeddings = self.vectorstore.advanced_similarity_search(query, **self.search_kwargs) |
| 53 | |
| 54 | for doc, score, embeddings in docs_scores_and_embeddings: |
| 55 | if "__embeddings" not in doc.metadata.keys(): |
| 56 | doc.metadata["__embeddings"] = embeddings |
| 57 | if "__similarity" not in doc.metadata.keys(): |
| 58 | doc.metadata["__similarity"] = score |
| 59 | |
| 60 | docs = [doc for doc, _, _ in docs_scores_and_embeddings] |
| 61 | elif self.search_type == "similarity_score_threshold": |
| 62 | docs_and_similarities = self.vectorstore.similarity_search_with_relevance_scores(query, **self.search_kwargs) |
| 63 | for doc, similarity in docs_and_similarities: |
| 64 | if "__similarity" not in doc.metadata.keys(): |
| 65 | doc.metadata["__similarity"] = similarity |
| 66 | |
| 67 | docs = [doc for doc, _ in docs_and_similarities] |
| 68 | else: |
| 69 | docs = super()._get_relevant_documents(query, run_manager=run_manager) |
| 70 | |
| 71 | return docs |
| 72 | |
| 73 | |
| 74 | class AdvancedVectorStore(VectorStore): |