File size: 7,415 Bytes
cbc00ce | 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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | # -*- coding: utf-8 -*-
# Copyright (c) Alibaba, Inc. and its affiliates.
from dataclasses import dataclass
from typing import List
from dashscope.api_entities.dashscope_response import (
DashScopeAPIResponse,
DictMixin,
)
from dashscope.client.base_api import BaseApi, BaseAioApi
from dashscope.common.error import InputRequired, ModelRequired
from dashscope.common.utils import _get_task_group_and_task
from dashscope.utils.oss_utils import preprocess_message_element
@dataclass(init=False)
class MultiModalEmbeddingItemBase(DictMixin):
factor: float
def __init__(self, factor: float, **kwargs):
super().__init__(factor=factor, **kwargs)
@dataclass(init=False)
class MultiModalEmbeddingItemText(MultiModalEmbeddingItemBase):
text: str
def __init__(self, text: str, factor: float, **kwargs):
super().__init__(factor, **kwargs)
self.text = text
@dataclass(init=False)
class MultiModalEmbeddingItemImage(MultiModalEmbeddingItemBase):
image: str
def __init__(self, image: str, factor: float, **kwargs):
super().__init__(factor, **kwargs)
self.image = image
@dataclass(init=False)
class MultiModalEmbeddingItemAudio(MultiModalEmbeddingItemBase):
audio: str
def __init__(self, audio: str, factor: float, **kwargs):
super().__init__(factor, **kwargs)
self.audio = audio
class MultiModalEmbedding(BaseApi):
task = "multimodal-embedding"
class Models:
multimodal_embedding_one_peace_v1 = "multimodal-embedding-one-peace-v1"
@classmethod
def call( # type: ignore[override]
cls,
model: str,
# pylint: disable=redefined-builtin
input: List[MultiModalEmbeddingItemBase],
api_key: str = None,
workspace: str = None,
**kwargs,
) -> DashScopeAPIResponse:
"""Get embedding multimodal contents..
Args:
model (str): The embedding model name.
input (List[MultiModalEmbeddingElement]): The embedding
elements, every element include data, modal, factor field.
workspace (str): The dashscope workspace id.
**kwargs:
auto_truncation(bool, `optional`): Automatically truncate
audio longer than 15 seconds or text longer than 70 words.
Default to false(Too long input will result in failure).
Returns:
DashScopeAPIResponse: The embedding result.
"""
if input is None or not input:
raise InputRequired("prompt is required!")
if model is None or not model:
raise ModelRequired("Model is required!")
embedding_input = {}
has_upload = cls._preprocess_message_inputs(
model,
input, # type: ignore[arg-type]
api_key,
) # noqa: E501
if has_upload:
headers = kwargs.pop("headers", {})
headers["X-DashScope-OssResourceResolve"] = "enable"
kwargs["headers"] = headers
embedding_input["contents"] = input
kwargs.pop("stream", False) # not support streaming output.
task_group, function = _get_task_group_and_task(__name__)
return super().call(
model=model,
input=embedding_input,
task_group=task_group,
task=MultiModalEmbedding.task,
function=function,
api_key=api_key,
workspace=workspace,
**kwargs,
)
@classmethod
def _preprocess_message_inputs(
cls,
model: str,
input_data: List[dict],
api_key: str,
):
"""preprocess following inputs
input = [{'factor': 1, 'text': 'hello'},
{'factor': 2, 'audio': ''},
{'factor': 3, 'image': ''}]
"""
has_upload = False
upload_certificate = None
for elem in input_data:
if not isinstance(elem, (int, float, bool, str, bytes, bytearray)):
is_upload, upload_certificate = preprocess_message_element(
model,
elem,
api_key,
upload_certificate, # type: ignore[arg-type]
)
if is_upload and not has_upload:
has_upload = True
return has_upload
class AioMultiModalEmbedding(BaseAioApi):
task = "multimodal-embedding"
class Models:
multimodal_embedding_one_peace_v1 = "multimodal-embedding-one-peace-v1"
@classmethod
async def call( # type: ignore[override]
cls,
model: str,
# pylint: disable=redefined-builtin
input: List[MultiModalEmbeddingItemBase],
api_key: str = None,
workspace: str = None,
**kwargs,
) -> DashScopeAPIResponse:
"""Get embedding multimodal contents..
Args:
model (str): The embedding model name.
input (List[MultiModalEmbeddingElement]): The embedding
elements, every element include data, modal, factor field.
workspace (str): The dashscope workspace id.
**kwargs:
auto_truncation(bool, `optional`): Automatically truncate
audio longer than 15 seconds or text longer than 70 words.
Default to false(Too long input will result in failure).
Returns:
DashScopeAPIResponse: The embedding result.
"""
if input is None or not input:
raise InputRequired("prompt is required!")
if model is None or not model:
raise ModelRequired("Model is required!")
embedding_input = {}
has_upload = cls._preprocess_message_inputs(
model,
input, # type: ignore[arg-type]
api_key,
) # noqa: E501
if has_upload:
headers = kwargs.pop("headers", {})
headers["X-DashScope-OssResourceResolve"] = "enable"
kwargs["headers"] = headers
embedding_input["contents"] = input
kwargs.pop("stream", False) # not support streaming output.
task_group, function = _get_task_group_and_task(__name__)
response = await super().call(
model=model,
input=embedding_input,
task_group=task_group,
task=MultiModalEmbedding.task,
function=function,
api_key=api_key,
workspace=workspace,
**kwargs,
)
return response
@classmethod
def _preprocess_message_inputs(
cls,
model: str,
input_data: List[dict],
api_key: str,
):
"""preprocess following inputs
input = [{'factor': 1, 'text': 'hello'},
{'factor': 2, 'audio': ''},
{'factor': 3, 'image': ''}]
"""
has_upload = False
upload_certificate = None
for elem in input_data:
if not isinstance(elem, (int, float, bool, str, bytes, bytearray)):
is_upload, upload_certificate = preprocess_message_element(
model,
elem,
api_key,
upload_certificate, # type: ignore[arg-type]
)
if is_upload and not has_upload:
has_upload = True
return has_upload
|