社内ドキュメントやサポート履歴を検索するとき、キーワード検索では単語が一致しないと見つからない。書き方が違うだけで、聞きたいことと同じ内容が書かれた文章を取りこぼす。人間なら「言い方は違うが同じことを言っている」と気づけるが、単純な文字列一致では気づけない。txtaiは、文章を意味のベクトルに変換して検索する埋め込みデータベースである。実際にインストールし、単語が1つも重ならない検索が当たるかを確かめた。
txtaiは埋め込みベースの検索・LLMワークフロー構築のためのオールインワンフレームワークである。ソースはApache 2.0 Licenseで公開されている(*1)。
1. インストールする
埋め込みモデル(sentence-transformers/all-MiniLM-L6-v2)はビルド時(ネットワークあり)に取得しておく。
FROM docker.io/library/python:3.12.13-slim
RUN pip install --no-cache-dir --quiet 'txtai==9.11.0'
COPY install_model.py /tmp/install_model.py
RUN python /tmp/install_model.py
WORKDIR /work
# install_model.py
import txtai
embeddings = txtai.Embeddings(path="sentence-transformers/all-MiniLM-L6-v2")
embeddings.index([(0, "warm up the model cache", None)])
print("warmup ok")
podman build -t txtai-sandbox .
2. 単語が重ならない検索を試す
5つの短い文章をインデックスし、そのどれとも単語が重ならないクエリで検索した。ネットワークを遮断した状態で実行する。
import txtai
embeddings = txtai.Embeddings(path="sentence-transformers/all-MiniLM-L6-v2")
documents = [
(0, "The cat sat quietly on the windowsill in the sun.", None),
(1, "Stock markets fell sharply after the interest rate announcement.", None),
(2, "A kitten curled up and slept on the warm windowsill.", None),
(3, "The central bank raised rates to fight inflation.", None),
(4, "She baked a loaf of sourdough bread this morning.", None),
]
embeddings.index(documents)
query = "a small cat napping by a window"
results = embeddings.search(query, 3)
for uid, score in results:
print(f"score={score:.3f} {documents[uid][1]}")
podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 \
-v "$(pwd)":/work -w /work txtai-sandbox \
python search_demo.py
-vは指定したディレクトリをコンテナから読み書き可能にする。実験専用の空ディレクトリで実行し、秘密鍵や認証情報を置かないこと。
結果は次の通りだった。
QUERY: a small cat napping by a window
score=0.638 A kitten curled up and slept on the warm windowsill.
score=0.612 The cat sat quietly on the windowsill in the sun.
score=0.243 She baked a loaf of sourdough bread this morning.
クエリのnappingはどちらの文にも登場しない。smallもkittenという単語には出てこない。それでも猫がまどろんでいる2文が上位に来て、無関係なパンの文章は明確に低いスコアになった。金融関連の2文(利上げ・株価)は上位3件にすら入らなかった。文字列としての一致を1つも使わずに、意味の近さだけで並び替えている。
キーワードの言い回しを、気にしなくていい検索
検索する側が、登録されている文章と同じ単語を選べるとは限らない。埋め込みによる検索は、その前提そのものを外す。聞きたいことを自分の言葉で書けば、表現の違いを埋めた上で近い内容を返してくれる。検索窓の前で「なんて単語で調べればヒットするか」を考える時間が、そのぶん減っていく。
出典
*1 txtai (GitHub), https://github.com/neuml/txtai, Apache 2.0 License