跳到主要內容

NeuralDB

NeuralDB 是由 ThirdAI 開發,對 CPU 友善且可微調的檢索引擎。

初始化

有兩種初始化方法

  • 從頭開始:基本模型
  • 從檢查點:載入先前儲存的模型

對於以下所有初始化方法,如果已設定 THIRDAI_KEY 環境變數,則可以省略 thirdai_key 參數。

ThirdAI API 金鑰可於 https://www.thirdai.com/try-bolt/ 取得

from langchain_community.retrievers import NeuralDBRetriever

# From scratch
retriever = NeuralDBRetriever.from_scratch(thirdai_key="your-thirdai-key")

# From checkpoint
retriever = NeuralDBRetriever.from_checkpoint(
# Path to a NeuralDB checkpoint. For example, if you call
# retriever.save("/path/to/checkpoint.ndb") in one script, then you can
# call NeuralDBRetriever.from_checkpoint("/path/to/checkpoint.ndb") in
# another script to load the saved model.
checkpoint="/path/to/checkpoint.ndb",
thirdai_key="your-thirdai-key",
)
API 參考:NeuralDBRetriever

插入文件來源

retriever.insert(
# If you have PDF, DOCX, or CSV files, you can directly pass the paths to the documents
sources=["/path/to/doc.pdf", "/path/to/doc.docx", "/path/to/doc.csv"],
# When True this means that the underlying model in the NeuralDB will
# undergo unsupervised pretraining on the inserted files. Defaults to True.
train=True,
# Much faster insertion with a slight drop in performance. Defaults to True.
fast_mode=True,
)

from thirdai import neural_db as ndb

retriever.insert(
# If you have files in other formats, or prefer to configure how
# your files are parsed, then you can pass in NeuralDB document objects
# like this.
sources=[
ndb.PDF(
"/path/to/doc.pdf",
version="v2",
chunk_size=100,
metadata={"published": 2022},
),
ndb.Unstructured("/path/to/deck.pptx"),
]
)

檢索文件

要查詢檢索器,您可以使用標準的 LangChain 檢索器方法 get_relevant_documents,它會返回 LangChain Document 物件的列表。每個文件物件代表索引文件中一段文字。例如,它可能包含一個索引 PDF 文件中的一段段落。除了文字之外,文件的 metadata 欄位還包含文件 ID、文件來源(來自哪個檔案)以及文件分數等資訊。

# This returns a list of LangChain Document objects
documents = retriever.invoke("query", top_k=10)

微調

NeuralDBRetriever 可以根據使用者行為和特定領域知識進行微調。可以透過兩種方式進行微調

  1. 關聯:檢索器將來源短語與目標短語相關聯。當檢索器看到來源短語時,它也會考慮與目標短語相關的結果。
  2. 投票贊成:檢索器會提高特定查詢的文件分數。當您想要根據使用者行為微調檢索器時,這非常有用。例如,如果使用者搜尋「汽車是如何製造的」並喜歡返回的 ID 為 52 的文件,那麼我們可以對查詢「汽車是如何製造的」投票贊成 ID 為 52 的文件。
retriever.associate(source="source phrase", target="target phrase")
retriever.associate_batch(
[
("source phrase 1", "target phrase 1"),
("source phrase 2", "target phrase 2"),
]
)

retriever.upvote(query="how is a car manufactured", document_id=52)
retriever.upvote_batch(
[
("query 1", 52),
("query 2", 20),
]
)

這個頁面有幫助嗎?