From 73ad987535adba8cd3d3afcb24fdc2aa7c3b935e Mon Sep 17 00:00:00 2001 From: Martin Chen Date: Sat, 11 Jan 2025 11:30:19 +0800 Subject: [PATCH] Bug fix: "IndexError: list index out of range" caused by base.py line 556 # The old code is not handling the error properly. # It is giving an error: IndexError: list index out of range when the key is expired or wrong. # Other api errors might also not be handled properly. # Please test with the following code # Old code gives error: IndexError: list index out of range # New code gives error on expired key: ValueError: Not enough available money, Please go to recharge # and error on wrong key: ValueError: Please check sk-************6GzDaH key from the platform.. from langchain_community.vectorstores import FAISS from langchain_openai.embeddings import OpenAIEmbeddings import os os.environ['OPENAI_API_BASE'] = "https://api.agicto.cn/v1" # os.environ['OPENAI_API_KEY'] = "sk-8Dxxl7SxhIHU8J3M6GzDaHfzgUjC3Cm21BSR8Dxx4EuctMJ2" # Expired key, out of money os.environ['OPENAI_API_KEY'] = "sk-8Dxxl7SxhIHU8J3M6GzDaH" # Wrong key vectorstore = FAISS.from_texts( [ "some text", "some more text" ], embedding=OpenAIEmbeddings(), ) --- libs/partners/openai/langchain_openai/embeddings/base.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/libs/partners/openai/langchain_openai/embeddings/base.py b/libs/partners/openai/langchain_openai/embeddings/base.py index 252996dc8b32f..8a54cf576d41a 100644 --- a/libs/partners/openai/langchain_openai/embeddings/base.py +++ b/libs/partners/openai/langchain_openai/embeddings/base.py @@ -552,7 +552,10 @@ async def empty_embedding() -> List[float]: ) if not isinstance(average_embedded, dict): average_embedded = average_embedded.model_dump() - _cached_empty_embedding = average_embedded["data"][0]["embedding"] + if (len(average_embedded["data"]) > 0): + _cached_empty_embedding = average_embedded["data"][0]["embedding"] + else: + raise ValueError(average_embedded["message"]) return _cached_empty_embedding return [e if e is not None else await empty_embedding() for e in embeddings]