Voyage AI
Voyage AI 提供尖端的嵌入/向量化模型。
让我们加载 Voyage AI Embedding 类。(使用 pip install langchain-voyageai 安装 LangChain 合作伙伴包)
from langchain_voyageai import VoyageAIEmbeddings
Voyage AI 使用 API 密钥来监控使用情况并管理权限。要获取您的密钥,请在我们的主页上创建一个账户。然后,使用您的 API 密钥创建一个 VoyageEmbeddings 模型。您可以使用以下任一模型:(来源):
voyage-3-largevoyage-3voyage-3-litevoyage-large-2voyage-code-2voyage-2voyage-law-2voyage-large-2-instructvoyage-finance-2voyage-multilingual-2
embeddings = VoyageAIEmbeddings(
voyage_api_key="[ Your Voyage API key ]", model="voyage-law-2"
)
准备文档,并使用 embed_documents 获取它们的嵌入。
documents = [
"Caching embeddings enables the storage or temporary caching of embeddings, eliminating the necessity to recompute them each time.",
"An LLMChain is a chain that composes basic LLM functionality. It consists of a PromptTemplate and a language model (either an LLM or chat model). It formats the prompt template using the input key values provided (and also memory key values, if available), passes the formatted string to LLM and returns the LLM output.",
"A Runnable represents a generic unit of work that can be invoked, batched, streamed, and/or transformed.",
]
documents_embds = embeddings.embed_documents(documents)
documents_embds[0][:5]
[0.0562174916267395,
0.018221192061901093,
0.0025736060924828053,
-0.009720131754875183,
0.04108370840549469]
同理,使用 embed_query 来嵌入查询。
query = "What's an LLMChain?"
query_embd = embeddings.embed_query(query)
query_embd[:5]
[-0.0052348352037370205,
-0.040072452276945114,
0.0033957737032324076,
0.01763271726667881,
-0.019235141575336456]
一个极简的检索系统
嵌入的主要特点是,两个嵌入之间的余弦相似度能够捕捉到对应原始文本段的语义相关性。这使得我们可以利用嵌入来进行语义检索/搜索。
我们可以根据余弦相似度在文档嵌入中找到几个最接近的嵌入,并使用 LangChain 的 KNNRetriever 类检索相应的文档。
from langchain_community.retrievers import KNNRetriever
retriever = KNNRetriever.from_texts(documents, embeddings)
# retrieve the most relevant documents
result = retriever.invoke(query)
top1_retrieved_doc = result[0].page_content # return the top1 retrieved result
print(top1_retrieved_doc)
API Reference:KNNRetriever
An LLMChain is a chain that composes basic LLM functionality. It consists of a PromptTemplate and a language model (either an LLM or chat model). It formats the prompt template using the input key values provided (and also memory key values, if available), passes the formatted string to LLM and returns the LLM output.
Related
- Embedding model conceptual guide
- Embedding model how-to guides