U
    h                     @  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 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ddZd
dddddZ d
ddddZ!dS )z*Wrapper around YandexGPT embedding models.    )annotationsN)AnyCallableDictListSequence)
Embeddings)	BaseModelField	SecretStr)convert_to_secret_strget_from_dict_or_envpre_init)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< G d d! d!Zed"d"d#d$d%Zd&d'd(d)d*Zdd+d,d-d.Zd/S )0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_metadatac                   @  s   e Zd ZdZdS )zYandexGPTEmbeddings.ConfigTN)__name__
__module____qualname__Zallow_population_by_field_name r-   r-   I/tmp/pip-unpacked-wheel-9gdii04g/langchain_community/embeddings/yandex.pyConfigJ   s   r/   r   )valuesreturnc                 C  st  t t|ddd}||d< t t|ddd}||d< t|ddd}||d< | dkrj| dkrjtd|d rd	d
|d   fg|d< |d r|d d|d f nd	d|d   fg|d< |ds|d dkrtdd|d  d|d  d|d  |d< |dsX|d dkr2tdd|d  d|d  d|d  |d< |d rp|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)clsr0   r   r   r   r-   r-   r.   validate_environmentM   sD      
z(YandexGPTEmbeddings.validate_environment	List[str]zList[List[float]])textsr1   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.
        )r;   _embed_with_retryselfr;   r-   r-   r.   embed_documents}   s    
z#YandexGPTEmbeddings.embed_documentszList[float])textr1   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)r;   embed_queryr   r<   )r?   rA   r-   r-   r.   rB      s    	zYandexGPTEmbeddings.embed_queryN)r*   r+   r,   __doc__r   __annotations__r   r
   r   r   r   r   r   r    r!   r$   r&   r(   r/   r   r9   r@   rB   r-   r-   r-   r.   r      s&   
/r   zCallable[[Any], Any])llmr1   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)Z
multiplierminmax)reraisestopwaitr   Zbefore_sleep)grpcrF   r   r   r$   r   r   r   loggerloggingWARNING)rE   rF   Zmin_secondsZmax_secondsr-   r-   r.   _create_retry_decorator   s    
rR   r   )rE   kwargsr1   c                   s*   t  }|ddd fdd}|f |S )z)Use tenacity to retry the embedding call.r   )_kwargsr1   c                    s   t  f| S )N)_make_request)rT   rE   r-   r.   _completion_with_retry   s    z1_embed_with_retry.<locals>._completion_with_retry)rR   )rE   rS   Zretry_decoratorrW   r-   rV   r.   r=      s    r=   r:   r>   c              
   K  s  zVdd l }zddlm} ddlm} W n, tk
rR   ddlm} ddlm} Y nX W n, tk
r } ztd|W 5 d }~X Y nX g }|	 }|
| j|}	|dr| j}
n| j}
|D ]D}||
|d}||	}|j|| jd}|t|j t| j q|S )Nr   )TextEmbeddingRequest)EmbeddingsServiceStubzkPlease install YandexCloud SDK  with `pip install yandexcloud`             or upgrade it to recent version.rB   )r   rA   )metadata)rN   ZDyandex.cloud.ai.foundation_models.v1.embedding.embedding_service_pb2rX   ZIyandex.cloud.ai.foundation_models.v1.embedding.embedding_service_pb2_grpcrY   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!   r7   r   r   ZTextEmbeddingr)   r6   listZ	embeddingtimesleepr&   )r?   r;   rS   rN   rX   rY   eresultZchannel_credentialsZchannelr   rA   requestZstubresr-   r-   r.   rU      s6    
rU   )"rC   
__future__r   rP   r^   typingr   r   r   r   r   Zlangchain_core.embeddingsr   Zlangchain_core.pydantic_v1r	   r
   r   Zlangchain_core.utilsr   r   r   Ztenacityr   r   r   r   r   	getLoggerr*   rO   r   rR   r=   rU   r-   r-   r-   r.   <module>   s   
~