Gemini
Qdrant 与 Gemini Embedding Model API 及其官方 Python SDK 兼容,可以像安装其他任何包一样安装它。
Gemini 是 Google PaLM 模型的一个新系列,于 2023 年 12 月发布。新的 embedding 模型是之前 Gecko Embedding Model 的后继者。
在最新的模型中,可以向 API 调用传递一个额外的参数 task_type
。此参数用于指定所使用的 embeddings 的预期用途。
Embedding Model API 支持各种任务类型,概述如下:
retrieval_query
: 在搜索/检索设置中的查询retrieval_document
: 来自被搜索语料库的文档semantic_similarity
: 文本语义相似度classification
: 用于文本分类的 embeddingsclustering
: 生成的 embeddings 将用于聚类task_type_unspecified
: 未设置值,将默认为其他值之一。
如果您正在构建语义搜索应用程序,例如 RAG,则应将 task_type="retrieval_document"
用于索引文档,将 task_type="retrieval_query"
用于搜索查询。
以下示例展示了如何使用 Qdrant 进行此操作
设置
pip install google-generativeai
让我们看看如何使用 Embedding Model API 为检索嵌入文档。
以下示例展示了如何使用 models/embedding-001
模型和 retrieval_document
任务类型嵌入文档
嵌入文档
import google.generativeai as gemini_client
from qdrant_client import QdrantClient
from qdrant_client.models import Distance, PointStruct, VectorParams
collection_name = "example_collection"
GEMINI_API_KEY = "YOUR GEMINI API KEY" # add your key here
client = QdrantClient(url="http://localhost:6333")
gemini_client.configure(api_key=GEMINI_API_KEY)
texts = [
"Qdrant is a vector database that is compatible with Gemini.",
"Gemini is a new family of Google PaLM models, released in December 2023.",
]
results = [
gemini_client.embed_content(
model="models/embedding-001",
content=sentence,
task_type="retrieval_document",
title="Qdrant x Gemini",
)
for sentence in texts
]
使用 Qdrant 创建 Qdrant Points 并索引文档
创建 Qdrant Points
points = [
PointStruct(
id=idx,
vector=response['embedding'],
payload={"text": text},
)
for idx, (response, text) in enumerate(zip(results, texts))
]
创建 Collection
client.create_collection(collection_name, vectors_config=
VectorParams(
size=768,
distance=Distance.COSINE,
)
)
将这些添加到 Collection 中
client.upsert(collection_name, points)
使用 Qdrant 搜索文档
文档索引完成后,您可以使用相同的模型和 retrieval_query
任务类型搜索最相关的文档
client.search(
collection_name=collection_name,
query_vector=gemini_client.embed_content(
model="models/embedding-001",
content="Is Qdrant compatible with Gemini?",
task_type="retrieval_query",
)["embedding"],
)
将 Gemini Embedding Models 与 二进制量化 结合使用
您可以将 Gemini Embedding Models 与 二进制量化 结合使用——这是一种可以将 embeddings 大小减少 32 倍而不会过多损失搜索结果质量的技术。
在此表格中,您可以看到使用 models/embedding-001
模型进行二进制量化与原始模型进行搜索的结果对比
在过采样为 3 且限制为 100 时,启用重排序的情况下,相对于精确最近邻,我们的召回率为 95%。
过采样 | 1 | 1 | 2 | 2 | 3 | 3 | |
---|---|---|---|---|---|---|---|
重排序 | False | True | False | True | False | True | |
限制 | |||||||
10 | 0.523333 | 0.831111 | 0.523333 | 0.915556 | 0.523333 | 0.950000 | |
20 | 0.510000 | 0.836667 | 0.510000 | 0.912222 | 0.510000 | 0.937778 | |
50 | 0.489111 | 0.841556 | 0.489111 | 0.913333 | 0.488444 | 0.947111 | |
100 | 0.485778 | 0.846556 | 0.485556 | 0.929000 | 0.486000 | 0.956333 |
就是这样!您现在可以将 Gemini Embedding Models 与 Qdrant 结合使用了!