From 47c3221fda9c6ca16613f8e86f8ae64480d314e6 Mon Sep 17 00:00:00 2001 From: Tom Bocklisch Date: Sat, 18 Feb 2023 00:12:31 +0100 Subject: [PATCH] Max marginal relecance search fails if there are not enough docs (#1117) Implementation fails if there are not enough documents. Added the same check as used for similarity search. Current implementation raises ``` File ".venv/lib/python3.9/site-packages/langchain/vectorstores/faiss.py", line 160, in max_marginal_relevance_search _id = self.index_to_docstore_id[i] KeyError: -1 ``` --- langchain/vectorstores/faiss.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/langchain/vectorstores/faiss.py b/langchain/vectorstores/faiss.py index ed1eeccdd53..e4bbd8dba9a 100644 --- a/langchain/vectorstores/faiss.py +++ b/langchain/vectorstores/faiss.py @@ -189,6 +189,9 @@ class FAISS(VectorStore): docs = [] for i in selected_indices: _id = self.index_to_docstore_id[i] + if _id == -1: + # This happens when not enough docs are returned. + continue doc = self.docstore.search(_id) if not isinstance(doc, Document): raise ValueError(f"Could not find document for id {_id}, got {doc}")