建立使用 LLM 根據內部文件回答問題的系統(RAG)時,每次都需要串接文件載入、分塊、嵌入、檢索,以及交給 LLM 處理等步驟。LlamaIndex 以框架形式提供這些串接功能。我安裝了它,並測試在網路中斷且停用 LLM 層的情況下,文件索引和檢索是否能運作。
LlamaIndex 是一個 RAG 框架,涵蓋從文件載入、建立嵌入索引、檢索到交給 LLM 處理的流程。LlamaIndex 的原始碼採用 MIT 授權 (*1)。
1. 安裝
FROM docker.io/library/python:3.12.13-slim
RUN pip install --no-cache-dir --quiet 'llama-index-core==0.14.23' 'llama-index-embeddings-huggingface==0.7.0'
COPY warmup_model.py /tmp/warmup_model.py
RUN python /tmp/warmup_model.py
WORKDIR /work
podman build -t llama-index-sandbox .
2. 不使用 LLM 測試索引和檢索
將 Settings.llm = None 設定後便會停用 LLM 部分,因此我只用嵌入模型測試索引和檢索。我登錄了四份簡短文件,並用一個與各文件用詞重疊很少的查詢進行搜尋。測試時停用了網路存取。
from llama_index.core import Document, VectorStoreIndex, Settings
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
Settings.embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2")
Settings.llm = None
documents = [
Document(text="Restarting the router fixes the wifi connection issue in most cases."),
Document(text="The invoice was rejected because the tax identifier field was empty."),
Document(text="Water the tomato plants every morning before the sun gets strong."),
Document(text="A missing tax ID caused the payment validation to fail."),
]
index = VectorStoreIndex.from_documents(documents)
retriever = index.as_retriever(similarity_top_k=2)
query = "billing rejected, tax number missing"
nodes = retriever.retrieve(query)
for node in nodes:
print(f"score={node.score:.4f} {node.text}")
podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 \
-e HF_HUB_OFFLINE=1 -e TRANSFORMERS_OFFLINE=1 \
-v "$(pwd)":/work -w /work llama-index-sandbox \
python index_demo.py
-v 讓容器可以讀寫指定的目錄。請在專供實驗的空目錄中執行此命令。即使模型已快取,我仍需要使用 HF_HUB_OFFLINE 和 TRANSFORMERS_OFFLINE,防止嵌入模型所依賴的函式庫檢查網路連線。自從撰寫 headroom 文章以來,我已多次遇到這個已知現象。
輸出如下:
QUERY: billing rejected, tax number missing
score=0.6907 A missing tax ID caused the payment validation to fail.
score=0.6777 The invoice was rejected because the tax identifier field was empty.
兩份關於稅務與帳務的文件和查詢幾乎沒有共同用詞,卻佔據了前兩個位置。搜尋結果排除了 Wi-Fi 和番茄澆水的文件。即使沒有 LLM,文件載入、索引和檢索流程仍能獨立運作。
先透過檢索驗證串接
建立 RAG 系統時,如果一次測試從頭到呼叫 LLM 的整個流程,就較難釐清失敗是由索引、檢索還是生成造成的。LlamaIndex 讓您可以移除 LLM 層,單獨測試檢索,從而在測試生成之前確認基本串接。
來源
*1 LlamaIndex (GitHub), https://github.com/run-llama/llama_index, MIT License