[docs]defembed_documents(self,texts:List[str])->List[List[float]]:"""Embed search docs. Args: texts: The list of texts to embed Returns: List[List[float]]: List of embeddings, one for each text. """ifnotself.access_token:self._refresh_access_token_with_lock()text_in_chunks=[texts[i:i+self.chunk_size]foriinrange(0,len(texts),self.chunk_size)]lst=[]forchunkintext_in_chunks:resp=self._embedding({"input":[textfortextinchunk]})ifresp.get("error_code"):ifresp.get("error_code")==111:self._refresh_access_token_with_lock()resp=self._embedding({"input":[textfortextinchunk]})else:raiseValueError(f"Error from Ernie: {resp}")lst.extend([i["embedding"]foriinresp["data"]])returnlst
[docs]defembed_query(self,text:str)->List[float]:"""Embed query text. Args: text: The text to embed. Returns: List[float]: Embeddings for the text. """ifnotself.access_token:self._refresh_access_token_with_lock()resp=self._embedding({"input":[text]})ifresp.get("error_code"):ifresp.get("error_code")==111:self._refresh_access_token_with_lock()resp=self._embedding({"input":[text]})else:raiseValueError(f"Error from Ernie: {resp}")returnresp["data"][0]["embedding"]
[docs]asyncdefaembed_query(self,text:str)->List[float]:"""Asynchronous Embed query text. Args: text: The text to embed. Returns: List[float]: Embeddings for the text. """returnawaitrun_in_executor(None,self.embed_query,text)
[docs]asyncdefaembed_documents(self,texts:List[str])->List[List[float]]:"""Asynchronous Embed search docs. Args: texts: The list of texts to embed Returns: List[List[float]]: List of embeddings, one for each text. """result=awaitasyncio.gather(*[self.aembed_query(text)fortextintexts])returnlist(result)