← 研究筆記
沒有相同關鍵字也能找到正確文字:實測 txtai

沒有相同關鍵字也能找到正確文字:實測 txtai

記錄在網路中斷的情況下執行 txtai。這是一個以語意相似度搜尋文字的 embedding 資料庫,僅憑語意相似度就找到了與查詢沒有共同詞語的段落。

本文介紹的儲存庫

neuml/txtai

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

12.7k Python Apache License 2.0

搜尋內部文件或支援紀錄時,如果用詞不同,關鍵字搜尋就可能漏掉結果。即使某個段落回答的是同一個問題,也可能因為表述不同而被錯過。人能辨認出兩個段落用不同的詞表達相同的意思,但單純的字串比對無法辨認這種差異。txtai 是一個將文字轉換成語意向量並加以搜尋的 embedding 資料庫。我安裝了它,測試當查詢和結果沒有共同詞語時,是否仍能找到相符內容。

txtai 是一個整合式 framework,用來建立以 embedding 為基礎的搜尋和 LLM 工作流程。此專案以 Apache 2.0 授權發布原始碼 (*1)。

1. 安裝

在建置期間啟用網路存取,下載 embedding 模型(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. 測試沒有共同詞語的搜尋

我為五個短句建立索引,然後用一個與這些句子都沒有共同詞語的查詢進行搜尋。執行時網路處於中斷狀態。

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 相符。兩個關於貓的句子排在前面,無關的麵包句子則得到低得多的分數。兩個關於升息和股價的金融句子沒有進入前 3 名。txtai 僅使用語意相似度,在沒有任何字串相符的情況下重新排序結果。

不必使用相同關鍵字的搜尋

不必使用與已建立索引的文字相同的詞語。Embedding 搜尋讓您可以使用自己的說法。系統會考量表達方式的差異,傳回意思相近的內容。您花在搜尋框前猜測哪些詞語能找到相符結果的時間也會減少。

來源

*1 txtai (GitHub), https://github.com/neuml/txtai, Apache 2.0 License