Запрос на помощь по конвейеру RAGPython

Программы на Python
Anonymous
Запрос на помощь по конвейеру RAG

Сообщение Anonymous »

Я немного новичок во всем, что касается конвейера RAG, и немного теряюсь в бесконечных возможностях его создания. Моя цель — создать скрипт, который сможет преобразовать около 60 анатомических PDF-файлов в базу данных векторного хранилища и использовать ее для ответа на вопросы о частях тела и возврата ссылок на страницы PDF-файлов, откуда была взята эта информация.Мой сценарий пока выглядит так, потому что это единственный способ заставить его работать:

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

import os

import faiss
import nest_asyncio
from dotenv import load_dotenv
from llama_index.core import (
Settings,
SimpleDirectoryReader,
StorageContext,
VectorStoreIndex,
load_index_from_storage,
)
from llama_index.core.callbacks import CallbackManager, LlamaDebugHandler
from llama_index.vector_stores.faiss import FaissVectorStore

nest_asyncio.apply()
load_dotenv()

llama_debug = LlamaDebugHandler(print_trace_on_end=True)
callback_manager = CallbackManager([llama_debug])
Settings.callback_manager = callback_manager

save_dir = "./documents/vector_store"

d = 1536
faiss_index = faiss.IndexFlatL2(d)
vector_store = FaissVectorStore(faiss_index=faiss_index)
storage_context = StorageContext.from_defaults(vector_store=vector_store)

if not os.path.exists(save_dir):
print("Saving vector store to disk ...")
documents = SimpleDirectoryReader("./documents/test/").load_data()
vector_store = VectorStoreIndex.from_documents(
documents,
storage_context=storage_context,
)
vector_store.storage_context.persist(persist_dir=save_dir)
vector_query_engine = vector_store.as_query_engine(similarity_top_k=3)
else:
print("Loading vector store from disk...")
vector_store = FaissVectorStore.from_persist_dir(save_dir)
storage_context = StorageContext.from_defaults(
vector_store=vector_store, persist_dir=save_dir
)
index = load_index_from_storage(storage_context=storage_context)
vector_query_engine = index.as_query_engine(similarity_top_k=3)

response = vector_query_engine.query(
"What is the diaphragm and what position does it occupy in the body?"
)

print(response)
for i, node in enumerate(response.source_nodes):
metadata = node.node.metadata
text_chunk = node.node.text
page_label = metadata.get("page_label", "N/A")
file_name = metadata.get("file_name", "N/A")
print(f"Reference nr: {i+1}, Page: {page_label}, Document: {file_name}")
print(f"Text Chunk: {text_chunk}\n")

А это (начало) вывода:

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

Trace: query
|_CBEventType.QUERY -> 2.734167 seconds
|_CBEventType.RETRIEVE -> 0.417225 seconds
|_CBEventType.EMBEDDING -> 0.417225 seconds
|_CBEventType.SYNTHESIZE -> 2.316942 seconds
|_CBEventType.TEMPLATING -> 0.0 seconds
|_CBEventType.LLM -> 2.30051 seconds
**********
A diaphragm is a dome-shaped muscle that separates the thoracic cavity from the abdominal cavity. It is positioned below the lungs and heart, and above the liver, stomach, and other abdominal organs. The diaphragm is connected to the thoracic aorta, which supplies blood to the chest wall and thoracic organs, and the inferior vena cava, which returns blood from the lower body to the heart.

Reference nr: 1, Page: 317, Document: random_pdf.pdf
Text Chunk: even during sleep, and must have a constant flow of
blood to supply oxygen and remove waste products.For this reason there are four vessels that bring bloodto the circle of Willis. From this anastomosis, severalpaired arteries (the cerebral arteries) extend into thebrain itself.
The thoracic aorta and its branches supply the
chest wall and the organs within the thoracic cavity.These vessels are listed in T able 13–1.
The abdominal aorta gives rise to arteries that sup-ply the abdominal wall and organs and to the common
iliac arteries, which continue into the legs. Notice inFig. 13–3 that the common iliac artery becomes theexternal iliac artery, which becomes the femoral artery,which becomes the popliteal artery; the same vesselhas different names based on location. These vesselsare also listed in T able 13–1 (see Box 13–3: PulseSites).
The systemic veins drain blood from organs or
parts of the body and often parallel their correspond-The Vascular System 299
Figure 13–5. Arteries and veins of the head and neck shown in right lateral view. Veins
are labeled on the left.  Arteries are labeled on the right.

У меня два вопроса:
  • на более теоретическом уровне: я думал, что конвейер RAG необходим (в очень упрощенный способ) 1) встраивание фрагментов 2) поиск по сходству 3) перефразирование ответа LLM; однако этот сценарий работает довольно хорошо, очевидно, пропуская и 1, и 3, так что я упускаю суть? или llama-index абстрагируется от большей части реализации?
  • на практическом уровне: как мне это улучшить? Скрипт работает так, как обычно выдает разумные ответы, но текст в "source_nodes" иногда очень неудовлетворителен с точки зрения релевантности.
Любая помощь/руководство или ресурсы будут очень признательны!

Подробнее здесь: https://stackoverflow.com/questions/786 ... lp-request

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