Skip to main content
Open In ColabOpen on GitHub

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",
)

插入文档来源

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 文档对象的列表。每个文档对象代表从索引文件中提取的一段文本。例如,它可能包含其中一个索引 PDF 文件中的一个段落。除了文本内容之外,该文档的元数据字段还包含了诸如文档 ID、此文档的来源(它来自哪个文件)和文档评分等信息。

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

细调

NeuralDBRetriever 可以根据用户行为和特定领域知识进行微调。它可以采用两种方式进行微调:

  1. 协会:检索器将源短语与目标短语关联起来。当检索器看到源短语时,它还会考虑与目标短语相关的结果。
  2. Upvoting: 当检索器为特定查询增加文档的得分时,这很有用。当您希望根据用户行为微调检索器时,可以使用此功能。例如,如果用户搜索“汽车是如何制造的”并喜欢返回的带有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),
]
)