Skip to content

Commit bb7c190

Browse files
authored
langchain: Fix error in LLMListwiseRerank when Document list is empty (#31300)
**Description:** This PR fixes an `IndexError` that occurs when `LLMListwiseRerank` is called with an empty list of documents. Earlier, the code assumed the presence of at least one document and attempted to construct the context string based on `len(documents) - 1`, which raises an error when documents is an empty list. The fix works with gpt-4o-mini if I make the list empty, but fails occasionally with gpt-3.5-turbo. In case of empty list, setting the string to "empty list" seems to have the expected response. **Issue:** #31192
1 parent 0b5c06e commit bb7c190

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

libs/langchain/langchain/retrievers/document_compressors/listwise_rerank.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,10 @@ def _get_prompt_input(input_: dict) -> dict[str, Any]:
2424
context = ""
2525
for index, doc in enumerate(documents):
2626
context += f"Document ID: {index}\n```{doc.page_content}```\n\n"
27-
context += f"Documents = [Document ID: 0, ..., Document ID: {len(documents) - 1}]"
27+
document_range = "empty list"
28+
if len(documents) > 0:
29+
document_range = f"Document ID: 0, ..., Document ID: {len(documents) - 1}"
30+
context += f"Documents = [{document_range}]"
2831
return {"query": input_["query"], "context": context}
2932

3033

0 commit comments

Comments
 (0)