o
    Zh                     @  s   d Z ddlmZ ddlZddlZddlmZmZmZm	Z	m
Z
 ddlmZ ddlmZmZmZ ddlmZmZmZmZ ddlmZmZmZmZmZ eeZG d	d
 d
eeZdddZ dddZ!dddZ"dS )z*Wrapper around YandexGPT embedding models.    )annotationsN)AnyCallableDictListSequence)
Embeddings)convert_to_secret_strget_from_dict_or_envpre_init)	BaseModel
ConfigDictField	SecretStr)before_sleep_logretryretry_if_exception_typestop_after_attemptwait_exponentialc                   @  s   e Zd ZU dZdZded< 	 dZded< 	 edddZded	< 	 dZ	ded
< 	 dZ
ded< 	 dZded< 	 edddZded< 	 dZded< 	 dZded< 	 dZded< 	 dZded< 	 dZded< 	 ded< ed d!d"Zed2d&d'Zd3d+d,Zd4d/d0Zd1S )5YandexGPTEmbeddingsa4  YandexGPT Embeddings models.

    To use, you should have the ``yandexcloud`` python package installed.

    There are two authentication options for the service account
    with the ``ai.languageModels.user`` role:
        - You can specify the token in a constructor parameter `iam_token`
        or in an environment variable `YC_IAM_TOKEN`.
        - You can specify the key in a constructor parameter `api_key`
        or in an environment variable `YC_API_KEY`.

    To use the default model specify the folder ID in a parameter `folder_id`
    or in an environment variable `YC_FOLDER_ID`.

    Example:
        .. code-block:: python

            from langchain_community.embeddings.yandex import YandexGPTEmbeddings
            embeddings = YandexGPTEmbeddings(iam_token="t1.9eu...", folder_id=<folder-id>)
     r   	iam_tokenapi_keyZquery_model_uri)defaultaliasstr	model_uridoc_model_uri	folder_idztext-search-docdoc_model_nameztext-search-queryZquery_model_name
model_nameZlatestmodel_versionzllm.api.cloud.yandex.net:443url   intmax_retriesg        floatsleep_intervalFbooldisable_request_loggingr   grpc_metadataT )Zpopulate_by_nameZprotected_namespacesvaluesr   returnc                 C  sl  t t|ddd}||d< t t|ddd}||d< t|ddd}||d< | dkr5| dkr5td|d rWd	d
|d   fg|d< |d rV|d d|d f nd	d|d   fg|d< |ds|d dkrttdd|d  d|d  d|d  |d< |ds|d dkrtdd|d  d|d  d|d  |d< |d r|d d |S )z.Validate that iam token exists in environment.r   ZYC_IAM_TOKENr   r   Z
YC_API_KEYr   ZYC_FOLDER_IDz7Either 'YC_API_KEY' or 'YC_IAM_TOKEN' must be provided.authorizationzBearer r*   zx-folder-idzApi-Key r   z0'doc_model_uri' or 'folder_id' must be provided.zemb:///r   r!   r   z,'model_uri' or 'folder_id' must be provided.r    r)   )zx-data-logging-enabledfalse)r	   r
   Zget_secret_value
ValueErrorappendget)clsr,   r   r   r   r+   r+   \/var/www/html/lang_env/lib/python3.10/site-packages/langchain_community/embeddings/yandex.pyvalidate_environmentL   sF   
 
 z(YandexGPTEmbeddings.validate_environmenttexts	List[str]List[List[float]]c                 C  s   t | |dS )zEmbed documents using a YandexGPT embeddings models.

        Args:
            texts: The list of texts to embed.

        Returns:
            List of embeddings, one for each text.
        )r7   _embed_with_retry)selfr7   r+   r+   r5   embed_documents|   s   
z#YandexGPTEmbeddings.embed_documentstextList[float]c                 C  s   t | |gddd S )zEmbed a query using a YandexGPT embeddings models.

        Args:
            text: The text to embed.

        Returns:
            Embeddings for the text.
        T)r7   embed_queryr   r:   )r<   r>   r+   r+   r5   r@      s   	zYandexGPTEmbeddings.embed_queryN)r,   r   r-   r   )r7   r8   r-   r9   )r>   r   r-   r?   )__name__
__module____qualname____doc__r   __annotations__r   r   r   r   r   r   r    r!   r"   r%   r'   r)   r   Zmodel_configr   r6   r=   r@   r+   r+   r+   r5   r      s@   
 
/r   llmr-   Callable[[Any], Any]c                 C  sB   ddl m} d}d}tdt| jtd||dt|ttt	j
dS )Nr   )RpcError   <   T)
multiplierminmax)reraisestopwaitr   before_sleep)grpcrH   r   r   r%   r   r   r   loggerloggingWARNING)rF   rH   Zmin_secondsZmax_secondsr+   r+   r5   _create_retry_decorator   s   
rV   kwargsr   c                   s(   t  }|d fdd}|di |S )	z)Use tenacity to retry the embedding call._kwargsr   r-   c                    s   t  fi | S )N)_make_request)rX   rF   r+   r5   _completion_with_retry   s   z1_embed_with_retry.<locals>._completion_with_retryN)rX   r   r-   r   r+   )rV   )rF   rW   Zretry_decoratorr[   r+   rZ   r5   r;      s   r;   r<   r7   r8   c              
   K  s   z*dd l }zddlm} ddlm} W n ty(   ddlm} ddlm} Y nw W n ty; } ztd|d }~ww g }|	 }|
| j|}	|drR| j}
n| j}
|D ]"}||
|d}||	}|j|| jd}|t|j t| j qW|S )Nr   )TextEmbeddingRequest)EmbeddingsServiceStubzkPlease install YandexCloud SDK  with `pip install yandexcloud`             or upgrade it to recent version.r@   )r   r>   )metadata)rR   ZDyandex.cloud.ai.foundation_models.v1.embedding.embedding_service_pb2r\   ZIyandex.cloud.ai.foundation_models.v1.embedding.embedding_service_pb2_grpcr]   ModuleNotFoundErrorZByandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2ZGyandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2_grpcImportErrorZssl_channel_credentialsZsecure_channelr"   r3   r   r   ZTextEmbeddingr*   r2   listZ	embeddingtimesleepr'   )r<   r7   rW   rR   r\   r]   eresultZchannel_credentialsZchannelr   r>   requestZstubresr+   r+   r5   rY      s>   
rY   )rF   r   r-   rG   )rF   r   rW   r   r-   r   )r<   r   r7   r8   )#rD   
__future__r   rT   rb   typingr   r   r   r   r   Zlangchain_core.embeddingsr   Zlangchain_core.utilsr	   r
   r   Zpydanticr   r   r   r   tenacityr   r   r   r   r   	getLoggerrA   rS   r   rV   r;   rY   r+   r+   r+   r5   <module>   s    

}
