本文介绍如何通过模型服务灵积DashScope将 文本转换为向量 ,并入库至向量检索服务DashVector中进行向量检索。
模型服务灵积DashScope,通过灵活、易用的模型API服务,让各种模态模型的能力,都能方便的为AI开发者所用。通过灵积API,开发者不仅可以直接集成大模型的强大能力,也可以对模型进行训练微调,实现模型定制化。
前提条件
-
DashVector:
- 已创建Cluster
- 已获得API-KEY
- 已安装最新版SDK
-
DashScope:
- 已开通服务并获得API-KEY
- 已安装最新版SDK
通用文本向量
简介
通用文本向量,是通义实验室基于LLM底座的多语言文本统一向量模型,面向全球多个主流语种,提供高水准的向量服务,帮助开发者将文本数据快速转换为高质量的向量数据。
使用示例
需要进行如下替换代码才能正常运行:
-
DashVector api-key替换示例中的{your-dashvector-api-key}
-
DashVector Cluster Endpoint替换示例中的{your-dashvector-cluster-endpoint}
-
DashScope api-key替换示例中的{your-dashscope-api-key}
Python示例:
import dashscope
from dashscope import TextEmbedding
from dashvector import Client
from typing import List, Union
dashscope.api_key = '{your-dashscope-api-key}'
# 调用DashScope通用文本向量模型,将文本embedding为向量
def generate_embeddings(texts: Union[List[str], str], text_type: str = 'document'):
rsp = TextEmbedding.call(
model=TextEmbedding.Models.text_embedding_v2,
input=texts,
text_type=text_type
)
embeddings = [record['embedding'] for record in rsp.output['embeddings']]
return embeddings if isinstance(embeddings, list) else embeddings[0]
# 创建DashVector Client
client = Client(
api_key='{your-dashvector-api-key}',
endpoint='{your-dashvector-cluster-endpoint}'
)
# 创建DashVector Collection
rsp = client.create('dashscope-text-embedding', 1536)
assert rsp
collection = client.get('dashscope-text-embedding')
assert collection
# 向量入库DashVector
collection.insert(
('ID1', generate_embeddings('阿里云向量检索服务DashVector是性能、性价比具佳的向量数据库之一'))
)
# 向量检索
docs = collection.query(
generate_embeddings('The best vector database', 'query')
)
print(docs)