IndexError: list index out of range in FAISS.from_documents

175 Views Asked by At

I'm encountering an error when using LangChain's FAISS module to build a vector index from a list of documents. Specifically, I'm getting an IndexError: list index out of range on the line where I call FAISS.from_documents(docs, embeddings).

My code:

import os
import streamlit as st
import pickle
import time
from langchain_openai import OpenAI
from langchain_openai import OpenAIEmbeddings
from langchain.chains import RetrievalQAWithSourcesChain
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import UnstructuredURLLoader
from langchain_community.embeddings import OpenAIEmbeddings
from langchain_community.vectorstores import FAISS
from dotenv import load_dotenv


from dotenv import load_dotenv
load_dotenv()  # take environment variables from .env (especially openai api key)

st.title("Link Reseaech Tool")
st.sidebar.title("News Article URLs")

urls = []
for i in range(1):
    url = st.sidebar.text_input(f"URL {i+1}")
    urls.append(url)

process_url_clicked = st.sidebar.button("Process URLs")
file_path = "faiss_store_openai.pkl"

llm = OpenAI(temperature=0.9, max_tokens=500)
if process_url_clicked:
    loader = UnstructuredURLLoader(urls=urls)
    st.text("data loading...")
    data = loader.load()
    text_splitter = RecursiveCharacterTextSplitter(
        separators=['\n\n', '\n', '.', ','],
        chunk_size=1000
    )
    st.text('text splitter started...')
    docs = text_splitter.split_documents(data)
    embeddings = OpenAIEmbeddings()
    db = FAISS.from_documents(docs, embeddings)
    st.text('Embedding Vector Started Building...')
    time.sleep(2)

query = st.text_input("Question: ")
if query:
    if os.path.exists(file_path):
        with open(file_path, "rb") as f:
            vectorstore = pickle.load(f)
            chain = RetrievalQAWithSourcesChain.from_llm(llm=llm, retriever=vectorstore.as_retriever())
            result = chain({"question": query}, return_only_outputs=True)
            # result will be a dictionary of this format --> {"answer": "", "sources": [] }
            st.header("Answer")
            st.write(result["answer"])

            # Display sources, if available
            sources = result.get("sources", "")
            if sources:
                st.subheader("Sources:")
                sources_list = sources.split("\n")  # Split the sources by newline
                for source in sources_list:
                    st.write(source)

The error i'm getting:

File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 535, in _run_script
    exec(code, module.__dict__)
File "/Users/rahulsharma/Desktop/2_news_research_tool_project/main.py", line 41, in <module>
    db = FAISS.from_documents(docs, embeddings)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain_core/vectorstores.py", line 528, in from_documents
    return cls.from_texts(texts, embedding, metadatas=metadatas, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain_community/vectorstores/faiss.py", line 966, in from_texts
    return cls.__from(
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain_community/vectorstores/faiss.py", line 923, in __from
    index = faiss.IndexFlatL2(len(embeddings[0]))

This error occurs on the line db = FAISS.from_documents(docs, embeddings).

Expected Outcome:

I expect the code to build a vector index using FAISS based on the provided documents and embeddings.

Environment details:

langchain: 0.1.3
python-dotenv: 1.0.0
streamlit: 1.31.1
unstructured: 0.12.5
tiktoken: 0.5.2
faiss-cpu: 1.7.4
libmagic: 1.0
python-magic: 0.4.27
python-magic-bin: None
OpenAI: 1.13.3
0

There are 0 best solutions below