Ошибка в PDF-вопросе-ответе: объект «dict» не имеет атрибута «поиск».Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Ошибка в PDF-вопросе-ответе: объект «dict» не имеет атрибута «поиск».

Сообщение Anonymous »

Я работаю над системой вопросов и ответов в формате PDF, используя LangChain и FAISS для векторного хранения. Однако во время процесса получения возникает ошибка:

Код: Выделить всё

Error during question answering: 'dict' object has no attribute 'search'
Полная обратная трассировка:

Код: Выделить всё

AttributeError                            Traceback (most recent call last)
 in ()
157 query = "What is the main topic of the document?"
158
--> 159 main(pdf_path, query)
160
161 # try:

13 frames
/usr/local/lib/python3.10/dist-packages/langchain_community/vectorstores/faiss.py in similarity_search_with_score_by_vector(self, embedding, k, filter, fetch_k, **kwargs)
424                 continue
425             _id = self.index_to_docstore_id[i]
--> 426             doc = self.docstore.search(_id)
427             if not isinstance(doc, Document):
428                 raise ValueError(f"Could not find document for id {_id}, got {doc}")

AttributeError: 'dict' object has no attribute 'search'
Вот фрагмент соответствующего кода, в котором, похоже, возникает проблема:

Код: Выделить всё

def create_retrieval_qa(document_text):
"""Create a RetrievalQA instance using the FAISS index(document text) and LLM."""
document = Document(page_content=document_text)

# Get embeddings for the document using embed_documents
embedding = embeddings.embed_documents([document.page_content])  # Use the LangChain embeddings
embedding = np.array(embedding)  # Convert to a NumPy array

# Check if embedding is correctly shaped
if embedding.ndim != 2 or embedding.shape[0] != 1:
raise ValueError("Embedding should be a 2D array with shape (1, embedding_dim).")

# Create FAISS index and add the document embedding
index = faiss.IndexFlatL2(embedding.shape[1])
index.add(embedding)  # Add the document embedding to the index

# Create docstore and index to docstore id mapping
docstore = {0: document}  # Mapping index to the Document
index_to_docstore_id = {0: 0}  # Document index mapping

# Create the FAISS vector store with the required embedding function
vector_store = FAISS(
index=index,
docstore=docstore,
index_to_docstore_id=index_to_docstore_id,
embedding_function=embeddings.embed_query  # Use embed_query for retrieval
)

# print("Vector Store:", vector_store)
retriever = vector_store.as_retriever(search_type="similarity")
# Check the retriever type
print("Retriever Type:", type(retriever))

'''
error you're encountering suggests that the retriever is not being set up correctly or that it's being used improperly in this context.
'''
retrieval_qa = RetrievalQA.from_chain_type(
llm=llm,
chain_type="stuff", # or "map_reduce"  or other types depending on your needs
retriever=retriever
)

return retrieval_qa, retriever

def answer_question(query, retrieval_qa):
"""Answer the question using the RetrievalQA instance."""
response = retrieval_qa({"query": query})
return response.get('output') or response.get('result')

def main(pdf_path, query):
"""Main function to ingest a PDF, create a QA instance, and answer a question."""
# Ingest the PDF and create an index
text = ingest_single_pdf(pdf_path)

# Create the retrieval chain
retrieval_qa, retriever = create_retrieval_qa(text)

# Test the vector store with the query
# test_vector_store(retrieval_qa.retriever.vectorstore, query)

try:
print(dir(retriever))
docs = retriever.get_relevant_documents(query)
print("Relevant Documents:", docs)  # Debugging
except Exception as e:
print("Error during document retrieval:", e)

# Answer the query
answer = answer_question(query, retrieval_qa)

print(f"Query: '{query}'")
print(f"Answer: {answer}")

# Example usage
pdf_path = "/content/my_pdf.pdf"
Ошибка возникает, когда я пытаюсь использовать средство извлечения для получения соответствующих документов для запроса.
Вопросы:< /p>
  • Правильно ли я настраиваю векторное хранилище и ретривер FAISS?
  • Есть ли что-то особенное в том, как я настраиваю пытаетесь получить документы, которые могут вызвать эту проблему?
  • Есть ли обновления или изменения в библиотеке LangChain, о которых мне следует знать, которые могут повлиять на то, как я это настроил?
Дополнительная информация:
  • Я подтвердил, что индекс FAISS заполнено правильно.
  • Модель внедрения работает должным образом.


Подробнее здесь: https://stackoverflow.com/questions/790 ... ute-search
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»