U
    h                     @  s   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	m
Z
mZmZ d dlZd dlmZ d dlmZ d dlmZmZmZ d dlmZmZ d dlmZmZmZmZ eeZ d	d
dddZ!dddddZ"d	dddddZ#eddddG dd	 d	eeZ$dS )    )annotationsN)AnyCallableDictListOptionalTupleUnioncast)
deprecated)
Embeddings)	BaseModel	SecretStrroot_validator)convert_to_secret_strget_from_dict_or_env)before_sleep_logretrystop_after_attemptwait_exponentialVoyageEmbeddingszCallable[[Any], Any])
embeddingsreturnc                 C  s0   d}d}t dt| jtd||dtttjdS )N   
   T   )Z
multiplierminmax)reraisestopwaitZbefore_sleep)r   r   max_retriesr   r   loggerloggingWARNING)r   Zmin_secondsZmax_seconds r%   K/tmp/pip-unpacked-wheel-9gdii04g/langchain_community/embeddings/voyageai.py_create_retry_decorator   s    
r'   dict)responser   c                 C  s    d| krt dt|  | S )NdatazVoyage API Error. Message: )RuntimeErrorjsondumps)r)   r%   r%   r&   _check_response,   s    r.   r   )r   kwargsr   c                 K  s&   t | }|ddddd}|f |S )z)Use tenacity to retry the embedding call.r   )r/   r   c                  [  s   t jf | }t| S )N)requestspostr.   r,   )r/   r)   r%   r%   r&   _embed_with_retry6   s    z+embed_with_retry.<locals>._embed_with_retry)r'   )r   r/   Zretry_decoratorr2   r%   r%   r&   embed_with_retry2   s    r3   z0.0.29z1.0z%langchain_voyageai.VoyageAIEmbeddings)ZsinceZremovalZalternative_importc                   @  s   e Zd ZU dZded< dZded< dZded< d	ed
< dZd	ed< dZded< dZ	ded< dZ
ded< G dd dZedddddddZd0ddddddZd1dd dd!d"d#d$Zdd!d%d&d'Zdd(d)d*d+Zdd,ddd!d-d.d/ZdS )2r   a  Voyage embedding models.

    To use, you should have the environment variable ``VOYAGE_API_KEY`` set with
    your API key or pass it as a named parameter to the constructor.

    Example:
        .. code-block:: python

            from langchain_community.embeddings import VoyageEmbeddings

            voyage = VoyageEmbeddings(voyage_api_key="your-api-key", model="voyage-2")
            text = "This is a test query."
            query_result = voyage.embed_query(text)
    strmodelz&https://api.voyageai.com/v1/embeddingsvoyage_api_baseNzOptional[SecretStr]voyage_api_keyint
batch_size   r!   z+Optional[Union[float, Tuple[float, float]]]request_timeoutFboolshow_progress_barT
truncationc                   @  s   e Zd ZdZdS )zVoyageEmbeddings.ConfigZforbidN)__name__
__module____qualname__extrar%   r%   r%   r&   Configf   s   rC   )prer   )valuesr   c                 C  sZ   t t|dd|d< d|kr.d|d< td d|krVd|krN|d dkrNdnd	|d< |S )
z?Validate that api key and python package exists in environment.r7   ZVOYAGE_API_KEYr5   z	voyage-01zmodel will become a required arg for VoyageAIEmbeddings, we recommend to specify it when using this class. Currently the default is set to voyage-01.r9   )zvoyage-2z	voyage-02H      )r   r   r"   warning)clsrE   r%   r%   r&   validate_environmenti   s     

z%VoyageEmbeddings.validate_environmentz	List[str]zOptional[str])input
input_typer   c                 C  s>   t t| j }| jdd| i| j||| jd| jd}|S )NAuthorizationzBearer )r5   rK   rL   r>   )urlheadersr,   timeout)r
   r   r7   Zget_secret_valuer6   r5   r>   r;   )selfrK   rL   Zapi_keyparamsr%   r%   r&   _invocation_params   s    z#VoyageEmbeddings._invocation_paramszOptional[int]zList[List[float]])textsr9   rL   r   c           
   
   C  s   g }|d kr| j }| jrlzddlm} W n, tk
rT } ztd|W 5 d }~X Y nX |tdt||}ntdt||}|r|dkrtd| d|D ]>}t| f| j	||||  |d}	|
dd	 |	d
 D  q|S )Nr   )tqdmzgMust have tqdm installed if `show_progress_bar` is set to True. Please install with `pip install tqdm`.)querydocumentzinput_type z0 is invalid. Options: None, 'query', 'document'.)rK   rL   c                 s  s   | ]}|d  V  qdS )Z	embeddingNr%   ).0rr%   r%   r&   	<genexpr>   s     z3VoyageEmbeddings._get_embeddings.<locals>.<genexpr>r*   )r9   r=   Z	tqdm.autorU   ImportErrorrangelen
ValueErrorr3   rS   extend)
rQ   rT   r9   rL   r   rU   eZ_iterir)   r%   r%   r&   _get_embeddings   s:    
 z VoyageEmbeddings._get_embeddings)rT   r   c                 C  s   | j || jddS )zCall out to Voyage Embedding endpoint for embedding search docs.

        Args:
            texts: The list of texts to embed.

        Returns:
            List of embeddings, one for each text.
        rW   r9   rL   rb   r9   )rQ   rT   r%   r%   r&   embed_documents   s
    	  z VoyageEmbeddings.embed_documentszList[float])textr   c                 C  s   | j |g| jddd S )zCall out to Voyage Embedding endpoint for embedding query text.

        Args:
            text: The text to embed.

        Returns:
            Embedding for the text.
        rV   rc   r   rd   )rQ   rf   r%   r%   r&   embed_query   s    	  zVoyageEmbeddings.embed_query)rL   )rT   rL   r   c                C  s   | j || j|dS )aP  Call out to Voyage Embedding endpoint for embedding general text.

        Args:
            texts: The list of texts to embed.
            input_type: Type of the input text. Default to None, meaning the type is
                unspecified. Other options: query, document.

        Returns:
            Embedding for the text.
        rc   rd   )rQ   rT   rL   r%   r%   r&   embed_general_texts   s
      z$VoyageEmbeddings.embed_general_texts)N)NN)r?   r@   rA   __doc____annotations__r6   r7   r!   r;   r=   r>   rC   r   rJ   rS   rb   re   rg   rh   r%   r%   r%   r&   r   >   s*   
   ))%
__future__r   r,   r#   typingr   r   r   r   r   r   r	   r
   r0   Zlangchain_core._api.deprecationr   Zlangchain_core.embeddingsr   Zlangchain_core.pydantic_v1r   r   r   Zlangchain_core.utilsr   r   Ztenacityr   r   r   r   	getLoggerr?   r"   r'   r.   r3   r   r%   r%   r%   r&   <module>   s&   (
