构建一个使用 LLM 根据内部文档回答问题的系统(RAG),每次都要把文档加载、分块、生成嵌入、检索以及交给 LLM 处理这些环节连接起来。LlamaIndex 以框架的形式提供了这套连接。我安装了它,并测试在切断网络且禁用 LLM 层的情况下,文档索引和检索是否仍能正常工作。
LlamaIndex 是一个 RAG 框架,覆盖了从文档加载、构建嵌入索引、检索到交给 LLM 处理的完整流程。LlamaIndex 采用 MIT 许可证(*1)。
1. 安装 LlamaIndex
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 设置为 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