通过阿里云百炼API调用将多种模态转换为向量

更新时间:
复制为 MD 格式

本文介绍如何通过大模型服务平台百炼进行多模态向量生成,并入库至向量检索服务DashVector中进行向量检索。

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

前提条件

通用多模态向量

模型根据用户的输入生成连续向量,这些输入可以是文本、图片或视频,文件格式详情请参照限流。适用于视频分类、图像分类、图文检索等任务场景。

使用限制与核心功能请参见文本与多模态向量化

使用示例

说明

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

  1. DashVector api-key替换示例中的{your-dashvector-api-key}

  2. DashVector Cluster Endpoint替换示例中的{your-dashvector-cluster-endpoint}

  3. DashScope api-key替换示例中的{your-dashscope-api-key}

import dashscope
from dashvector import Client


dashscope.api_key = '{your-dashscope-api-key}'


# 调用DashScope multimodal-embedding-v1模型,将各种模态素材embedding为向量
def generate_embeddings(text: str = None, image: str = None, video: str = None):
    input = []
    if text:
        input.append({'text': text})
    if image:
        input.append({'image': image})
    if video:
        input.append({'video': video})
    result = dashscope.MultiModalEmbedding.call(
        model="multimodal-embedding-v1",
        input=input
    )
    if result.status_code != 200:
        raise Exception(f"multimodal-embedding-v1 failed to generate embedding of {input}, result: {result}")
    return result.output["embeddings"][0]["embedding"]

# 创建DashVector Client
client = Client(
    api_key='{your-dashvector-api-key}',
    endpoint='{your-dashvector-cluster-endpoint}'
)

#  创建DashVector Collection
rsp = client.create('multimodal-embedding', 1024)
assert rsp
collection = client.get('multimodal-embedding')
assert collection

#  向量入库DashVector
collection.insert(
    [
        ('ID1', generate_embeddings(text='阿里云向量检索服务DashVector是性能、性价比具佳的向量数据库之一')),
        ('ID2', generate_embeddings(image='https://dashscope.oss-cn-beijing.aliyuncs.com/images/256_1.png')),
        ('ID3', generate_embeddings(video='https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250107/lbcemt/new+video.mp4')),
        ('ID4', generate_embeddings(
            text='阿里云向量检索服务DashVector是性能、性价比具佳的向量数据库之一',
            image='https://dashscope.oss-cn-beijing.aliyuncs.com/images/256_1.png',
            video='https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250107/lbcemt/new+video.mp4'
        ))
    ]
)
# 向量检索
docs = collection.query(
    generate_embeddings(text='The best vector database')
)
print(docs)