Skip to main content
Open In ColabOpen on GitHub

FAISS

Facebook AI相似搜索(FAISS) 是一个用于高效相似度搜索和稠密向量聚类的库。它包含可以在任意大小集合中进行搜索的算法,这些集合可能大到无法装入RAM中。它还包含评估和支持参数调整所需的代码。

See 《FAISS库》 研究论文。

您可以在此页面找到FAISS文档:此链接

这个笔记本展示了如何使用与FAISS向量数据库相关的功能。它将展示特定于此集成的功能性。浏览完毕后,可以探索相关用例页面来了解如何在更大的链中使用这种向量存储。

设置

The integration lives in the langchain-community package. We also need to install the faiss package itself. We can install these with:

注意,你也可以安装faiss-gpu以使用GPU加速版本

pip install -qU langchain-community faiss-cpu

如果您想要获得最佳的模型调用自动化跟踪,您也可以通过取消注释下方代码来设置您的LangSmith API密钥。

# os.environ["LANGSMITH_TRACING"] = "true"
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass()

初始化

pip install -qU langchain-openai
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
import faiss
from langchain_community.docstore.in_memory import InMemoryDocstore
from langchain_community.vectorstores import FAISS

index = faiss.IndexFlatL2(len(embeddings.embed_query("hello world")))

vector_store = FAISS(
embedding_function=embeddings,
index=index,
docstore=InMemoryDocstore(),
index_to_docstore_id={},
)

管理向量存储

添加项到向量存储

from uuid import uuid4

from langchain_core.documents import Document

document_1 = Document(
page_content="I had chocolate chip pancakes and scrambled eggs for breakfast this morning.",
metadata={"source": "tweet"},
)

document_2 = Document(
page_content="The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees.",
metadata={"source": "news"},
)

document_3 = Document(
page_content="Building an exciting new project with LangChain - come check it out!",
metadata={"source": "tweet"},
)

document_4 = Document(
page_content="Robbers broke into the city bank and stole $1 million in cash.",
metadata={"source": "news"},
)

document_5 = Document(
page_content="Wow! That was an amazing movie. I can't wait to see it again.",
metadata={"source": "tweet"},
)

document_6 = Document(
page_content="Is the new iPhone worth the price? Read this review to find out.",
metadata={"source": "website"},
)

document_7 = Document(
page_content="The top 10 soccer players in the world right now.",
metadata={"source": "website"},
)

document_8 = Document(
page_content="LangGraph is the best framework for building stateful, agentic applications!",
metadata={"source": "tweet"},
)

document_9 = Document(
page_content="The stock market is down 500 points today due to fears of a recession.",
metadata={"source": "news"},
)

document_10 = Document(
page_content="I have a bad feeling I am going to get deleted :(",
metadata={"source": "tweet"},
)

documents = [
document_1,
document_2,
document_3,
document_4,
document_5,
document_6,
document_7,
document_8,
document_9,
document_10,
]
uuids = [str(uuid4()) for _ in range(len(documents))]

vector_store.add_documents(documents=documents, ids=uuids)
API 参考:文档
['22f5ce99-cd6f-4e0c-8dab-664128307c72',
'dc3f061b-5f88-4fa1-a966-413550c51891',
'd33d890b-baad-47f7-b7c1-175f5f7b4e59',
'6e6c01d2-6020-4a7b-95da-ef43d43f01b5',
'e677223d-ad75-4c1a-bef6-b5912bd1de03',
'47e2a168-6462-4ed2-b1d9-d9edfd7391d6',
'1e4d66d6-e155-4891-9212-f7be97f36c6a',
'c0663096-e1a5-4665-b245-1c2e6c4fb653',
'8297474a-7f7c-4006-9865-398c1781b1bc',
'44e4be03-0a8d-4316-b3c4-f35f4bb2b532']

删除向量存储中的项

vector_store.delete(ids=[uuids[-1]])
True

查询向量存储

一旦您的向量存储已经创建并添加了相关文档,您很可能在运行链或代理的过程中希望对其进行查询。

查询直接

进行简单的相似度搜索并结合元数据过滤可以按照以下方式进行:

results = vector_store.similarity_search(
"LangChain provides abstractions to make working with LLMs easy",
k=2,
filter={"source": "tweet"},
)
for res in results:
print(f"* {res.page_content} [{res.metadata}]")
* Building an exciting new project with LangChain - come check it out! [{'source': 'tweet'}]
* LangGraph is the best framework for building stateful, agentic applications! [{'source': 'tweet'}]

一些高级元数据过滤支持使用MongoDB查询和投影操作符。当前支持的操作符列表如下:

  • $eq (等于)
  • $neq (不等于)
  • $gt (大于)
  • $lt (小于)
  • $gte (大于或等于)
  • $lte (小于或等于)
  • $in (会员列表)
  • $nin (不在列表中)
  • $and (所有条件必须匹配)
  • $or (任何条件必须匹配)
  • $not (否定条件)

使用高级元数据过滤进行相同的上述相似性搜索可以按照以下方式进行:

results = vector_store.similarity_search(
"LangChain provides abstractions to make working with LLMs easy",
k=2,
filter={"source": {"$eq": "tweet"}},
)
for res in results:
print(f"* {res.page_content} [{res.metadata}]")
* Building an exciting new project with LangChain - come check it out! [{'source': 'tweet'}]
* LangGraph is the best framework for building stateful, agentic applications! [{'source': 'tweet'}]

相似性搜索(带分数)

也可以按分数搜索:

results = vector_store.similarity_search_with_score(
"Will it be hot tomorrow?", k=1, filter={"source": "news"}
)
for res, score in results:
print(f"* [SIM={score:3f}] {res.page_content} [{res.metadata}]")
* [SIM=0.893688] The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees. [{'source': 'news'}]

其他搜索方法

有多种其他方式来搜索FAISS向量存储。要查看这些方法的完整列表,请参阅API参考

查询通过转换为检索器

您也可以将向量存储转换为检索器,以便在链条中更方便地使用。

retriever = vector_store.as_retriever(search_type="mmr", search_kwargs={"k": 1})
retriever.invoke("Stealing from the bank is a crime", filter={"source": "news"})
[Document(metadata={'source': 'news'}, page_content='Robbers broke into the city bank and stole $1 million in cash.')]

使用检索增强生成

对于如何使用此向量存储进行检索增强生成(RAG)的指南,请参见以下部分:

保存和加载

您可以保存和加载一个FAISS索引,这样每次使用时就不必每次都重新创建它。

vector_store.save_local("faiss_index")

new_vector_store = FAISS.load_local(
"faiss_index", embeddings, allow_dangerous_deserialization=True
)

docs = new_vector_store.similarity_search("qux")
docs[0]
Document(metadata={'source': 'tweet'}, page_content='Building an exciting new project with LangChain - come check it out!')

合并

您也可以合并两个FAISS向量存储库

db1 = FAISS.from_texts(["foo"], embeddings)
db2 = FAISS.from_texts(["bar"], embeddings)

db1.docstore._dict
{'b752e805-350e-4cf5-ba54-0883d46a3a44': Document(page_content='foo')}
db2.docstore._dict
{'08192d92-746d-4cd1-b681-bdfba411f459': Document(page_content='bar')}
db1.merge_from(db2)
db1.docstore._dict
{'b752e805-350e-4cf5-ba54-0883d46a3a44': Document(page_content='foo'),
'08192d92-746d-4cd1-b681-bdfba411f459': Document(page_content='bar')}

API 参考

详细文档请参阅所有FAISS向量存储功能和配置的API参考:https://python.langchain.com/api_reference/community/vectorstores/langchain_community.vectorstores.faiss.FAISS.html