Source code for agentscope.embedding._dashscope_embedding
# -*- coding: utf-8 -*-"""The dashscope embedding module in agentscope."""fromdatetimeimportdatetimefromtypingimportAny,Listfrom._cache_baseimportEmbeddingCacheBasefrom._embedding_responseimportEmbeddingResponsefrom._embedding_usageimportEmbeddingUsagefrom._embedding_baseimportEmbeddingModelBase
[docs]classDashScopeTextEmbedding(EmbeddingModelBase):"""DashScope text embedding model class"""
[docs]def__init__(self,api_key:str,model_name:str,embedding_cache:EmbeddingCacheBase|None=None,)->None:"""Initialize the DashScope text embedding model class. Args: api_key (`str`): The dashscope API key. model_name (`str`): The name of the embedding model. embedding_cache (`EmbeddingCacheBase`): The embedding cache class instance, used to cache the embedding results to avoid repeated API calls. """super().__init__(model_name)self.api_key=api_keyself.embedding_cache=embedding_cache
[docs]asyncdef__call__(self,text:List[str],**kwargs:Any,)->EmbeddingResponse:"""Call the DashScope embedding API. Args: text (`List[str]`): The input text to be embedded. It can be a list of strings. """kwargs={"input":text,"model":self.model_name,**kwargs,}ifself.embedding_cache:cached_embeddings=awaitself.embedding_cache.retrieve(identifier=kwargs,)ifcached_embeddings:returnEmbeddingResponse(embeddings=cached_embeddings,usage=EmbeddingUsage(tokens=0,time=0,),source="cache",)importdashscopestart_time=datetime.now()response=dashscope.embeddings.TextEmbedding.call(api_key=self.api_key,**kwargs,)time=(datetime.now()-start_time).total_seconds()ifresponse.status_code!=200:raiseRuntimeError(f"Failed to get embedding from DashScope API: {response}",)ifself.embedding_cache:awaitself.embedding_cache.store(identifier=kwargs,embeddings=[_["embedding"]for_inresponse.output["embeddings"]],)embedding_response=EmbeddingResponse(embeddings=[_["embedding"]for_inresponse.output["embeddings"]],usage=EmbeddingUsage(tokens=response.usage["total_tokens"],time=time,),)returnembedding_response