Typesense
Typesense is an open-source, in-memory search engine, that you can either self-host or run on Typesense Cloud.
Typesense focuses on performance by storing the entire index in RAM (with a backup on disk) and also focuses on providing an out-of-the-box developer experience by simplifying available options and setting good defaults.
It also lets you combine attribute-based filtering together with vector queries, to fetch the most relevant documents.
本笔记本向您展示如何将 Typesense 用作您的向量存储。
首先让我们安装依赖项:
%pip install --upgrade --quiet typesense openapi-schema-pydantic langchain-openai langchain-community tiktoken
我们要使用 OpenAIEmbeddings,因此我们需要获取OpenAI API密钥。
import getpass
import os
if "OPENAI_API_KEY" not in os.environ:
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
from langchain_community.document_loaders import TextLoader
from langchain_community.vectorstores import Typesense
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import CharacterTextSplitter
让我们导入测试数据集:
loader = TextLoader("../../how_to/state_of_the_union.txt")
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
docs = text_splitter.split_documents(documents)
embeddings = OpenAIEmbeddings()
docsearch = Typesense.from_documents(
docs,
embeddings,
typesense_client_params={
"host": "localhost", # Use xxx.a1.typesense.net for Typesense Cloud
"port": "8108", # Use 443 for Typesense Cloud
"protocol": "http", # Use https for Typesense Cloud
"typesense_api_key": "xyz",
"typesense_collection_name": "lang-chain",
},
)
相似性搜索
query = "What did the president say about Ketanji Brown Jackson"
found_docs = docsearch.similarity_search(query)
print(found_docs[0].page_content)
使用Typesense作为检索器
Typesense 与其他所有向量数据库一样,通过使用余弦相似度,成为 LangChain 检索器。
retriever = docsearch.as_retriever()
retriever
query = "What did the president say about Ketanji Brown Jackson"
retriever.invoke(query)[0]