本文介绍如何通过模型服务灵积DashScope将文本转换为向量,并入库至向量检索服务DashVector中进行向量检索。

模型服务灵积DashScope,通过灵活、易用的模型API服务,让各种模态模型的能力,都能方便的为AI开发者所用。通过灵积API,开发者不仅可以直接集成大模型的强大能力,也可以对模型进行训练微调,实现模型定制化。


前提条件

  • DashVector:
  • DashScope:


通用文本向量

简介

 通用文本向量,是通义实验室基于LLM底座的多语言文本统一向量模型,面向全球多个主流语种,提供高水准的向量服务,帮助开发者将文本数据快速转换为高质量的向量数据。

模型名称

向量维度

度量方式

向量数据类型

备注

text-embedding-v1

1536

Cosine

Float32

  • 单行最大输入字符长度:2048
  • 单次请求文本最大行数:25
  • 支持语种:中文、英语、西班牙语、法语、葡萄牙语、印尼语

text-embedding-v2

1536

Cosine

Float32

  • 单行最大输入字符长度:2048
  • 单次请求文本最大行数:25
  • 支持语种:中文、英语、西班牙语、法语、葡萄牙语、印尼语、日语、韩语、德语、俄罗斯语

说明

关于灵积通用文本向量更多信息请参考: 通用文本向量

使用示例

说明

需要进行如下替换代码才能正常运行:

  1. DashVector api-key替换示例中的{your-dashvector-api-key}
  2. DashVector Cluster Endpoint替换示例中的{your-dashvector-cluster-endpoint}
  3. 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(texts, 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)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.



相关最佳实践


ONE-PEACE多模态向量表征

 ONE-PEAC是一个图文音三模态通用表征模型,同样可通过ONE-PEAC将文本转换为向量。

详情参考: 从多种模态混合生成向量 —— ONE-PEACE多模态向量表征