← 研究ノート
LLMなしでも、検索基盤の骨組みは試せる。LlamaIndexを動かす

LLMなしでも、検索基盤の骨組みは試せる。LlamaIndexを動かす

RAG構築フレームワークLlamaIndexを、LLMなし・ネットワーク遮断のまま動かした記録。埋め込みモデルだけの構成で、言い回しの違うクエリでも正しい文書を引き当てた。

この記事で取り扱うリポジトリ

run-llama/llama_index

LlamaIndex is the leading document agent and OCR platform

50.9k Python MIT License

社内文書に基づいてLLMに回答させる仕組み(RAG)を作るとき、文書の読み込み・分割・埋め込み・検索・LLMへの受け渡しといった配線を毎回自分で組むのは手間がかかる。LlamaIndexは、この一連の配線をフレームワークとして提供するライブラリである。実際にインストールし、LLM部分を使わずにネットワークを遮断した状態で、文書の索引化と検索が動くかを確かめた。

LlamaIndexは文書の読み込みから埋め込み索引の構築、検索、LLMへの受け渡しまでを一貫して扱うRAG構築フレームワークである。ソースはMIT Licenseで公開されている(*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部分を使わない構成にし、埋め込みモデルによる索引化と検索だけを試した。4件の短い文書を登録し、そのどれとも単語がほぼ重ならないクエリで検索した。ネットワークを遮断した状態で実行する。

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.

クエリと単語がほとんど重ならない2件の税務・請求関連の文書が正しく上位に来て、Wi-Fiやトマトの水やりに関する文書は除外された。LLMを一切使わない構成でも、文書の読み込み・索引化・検索という配線部分は単独で機能する。

配線を、まず検索だけで検証する

RAGを構築する際、LLM呼び出しまで含めた全体を一度に検証しようとすると、うまくいかない原因が索引・検索・生成のどこにあるか切り分けにくくなる。LlamaIndexのようにLLM部分を明示的に外して検索だけを検証できれば、配線の土台部分が正しく機能しているかを先に確認できる。

出典

*1 LlamaIndex (GitHub), https://github.com/run-llama/llama_index, MIT License