ThirdAI NeuralDB
初始化
有兩種初始化方法
- 從頭開始:基本模型
- 從檢查點:載入先前儲存的模型
對於以下所有初始化方法,如果已設定 THIRDAI_KEY
環境變數,則可以省略 thirdai_key
參數。
ThirdAI API 金鑰可以從 https://www.thirdai.com/try-bolt/ 取得
您需要使用 pip install -qU langchain-community
安裝 langchain-community
才能使用此整合
from langchain_community.vectorstores import NeuralDBVectorStore
# From scratch
vectorstore = NeuralDBVectorStore.from_scratch(thirdai_key="your-thirdai-key")
# From checkpoint
vectorstore = NeuralDBVectorStore.from_checkpoint(
# Path to a NeuralDB checkpoint. For example, if you call
# vectorstore.save("/path/to/checkpoint.ndb") in one script, then you can
# call NeuralDBVectorStore.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 參考文檔:NeuralDBVectorStore
插入文檔來源
vectorstore.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
vectorstore.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 向量儲存庫方法 similarity_search
,它會傳回 LangChain Document 物件的列表。每個文檔物件代表來自索引檔案的文字塊。例如,它可能包含來自其中一個索引 PDF 檔案的段落。除了文字外,文檔的 metadata 欄位還包含文檔的 ID、此文檔的來源(來自哪個檔案)以及文檔的分數等資訊。
# This returns a list of LangChain Document objects
documents = vectorstore.similarity_search("query", k=10)
微調
NeuralDBVectorStore 可以根據使用者行為和特定領域知識進行微調。它可以通過兩種方式進行微調
- 關聯:向量儲存庫將來源短語與目標短語關聯起來。當向量儲存庫看到來源短語時,它也會考慮與目標短語相關的結果。
- 加權:向量儲存庫會針對特定查詢提高文檔的分數權重。當您想要根據使用者行為微調向量儲存庫時,這非常有用。例如,如果使用者搜尋「汽車是如何製造的」並喜歡傳回的 ID 為 52 的文檔,那麼我們可以針對查詢「汽車是如何製造的」來加權 ID 為 52 的文檔。
vectorstore.associate(source="source phrase", target="target phrase")
vectorstore.associate_batch(
[
("source phrase 1", "target phrase 1"),
("source phrase 2", "target phrase 2"),
]
)
vectorstore.upvote(query="how is a car manufactured", document_id=52)
vectorstore.upvote_batch(
[
("query 1", 52),
("query 2", 20),
]
)