U
    h                     @   s   d dl Z d dlZd dlZd dl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 d dlmZ eddd	d
G dd deeZdS )    N)AnyDictListOptional)
deprecated)
Embeddings)	BaseModelroot_validator)run_in_executorz0.2.11z1.0zlangchain_aws.BedrockEmbeddings)ZsinceZremovalZalternative_importc                   @   s(  e Zd ZU dZeed< dZee ed< dZ	ee ed< dZ
eed< dZee ed< dZee ed	< d
Zeed< G dd dZed
ddeedddZeee dddZee ee dddZee eee  dddZeee dddZeee dddZee eee  dd d!ZdS )"BedrockEmbeddingsa  Bedrock embedding models.

    To authenticate, the AWS client uses the following methods to
    automatically load credentials:
    https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html

    If a specific credential profile should be used, you must pass
    the name of the profile from the ~/.aws/credentials file that is to be used.

    Make sure the credentials / roles used have the required policies to
    access the Bedrock service.
    clientNregion_namecredentials_profile_namezamazon.titan-embed-text-v1model_idmodel_kwargsendpoint_urlF	normalizec                   @   s   e Zd ZdZdS )zBedrockEmbeddings.ConfigZforbidN)__name__
__module____qualname__extra r   r   J/tmp/pip-unpacked-wheel-9gdii04g/langchain_community/embeddings/bedrock.pyConfigM   s   r   T)preZskip_on_failure)valuesreturnc              
   C   s   |d dk	r|S znddl }|d dk	r8|j|d d}n| }i }|d rX|d |d< |d rl|d |d< |jd||d< W nL tk
r   td	Y n2 tk
r } ztd
| |W 5 d}~X Y nX |S )zJValidate that AWS credentials to and python package exists in environment.r   Nr   r   )Zprofile_namer   r   bedrock-runtimezRCould not import boto3 python package. Please install it with `pip install boto3`.zCould not load credentials to authenticate with AWS client. Please check that credentials in the specified profile name are valid. Bedrock error: )r   )boto3Sessionr   ImportError	Exception
ValueError)clsr   r   sessionZclient_paramser   r   r   validate_environmentP   s0    z&BedrockEmbeddings.validate_environment)textr   c           	   
   C   s   | tjd}| jdd }| jp&i }|}|dkrVd| krJd|d< |g|d< n||d< t|}zR| j	j
|| jd	d	d
}t|d }|dkr|dd W S |dW S W n0 tk
r } ztd| W 5 d}~X Y nX dS )z'Call out to Bedrock embedding endpoint. .r   ZcohereZ
input_typeZsearch_documenttextsZ	inputTextzapplication/json)bodyZmodelIdacceptcontentTyper+   
embeddings	embeddingz$Error raised by inference endpoint: N)replaceoslinesepr   splitr   keysjsondumpsr   Zinvoke_modelloadsgetreadr!   r"   )	selfr'   ZproviderZ_model_kwargsZ
input_bodyr+   responseZresponse_bodyr%   r   r   r   _embedding_funcw   s.    

z!BedrockEmbeddings._embedding_func)r.   r   c                 C   s"   t |}|t j| }| S )z)Normalize the embedding to a unit vector.)nparrayZlinalgZnormtolist)r:   r.   ZembZnorm_embr   r   r   _normalize_vector   s    
z#BedrockEmbeddings._normalize_vector)r*   r   c                 C   s6   g }|D ](}|  |}| jr&| |}|| q|S )zCompute doc embeddings using a Bedrock model.

        Args:
            texts: The list of texts to embed

        Returns:
            List of embeddings, one for each text.
        )r<   r   r@   append)r:   r*   resultsr'   r;   r   r   r   embed_documents   s    	

z!BedrockEmbeddings.embed_documentsc                 C   s   |  |}| jr| |S |S )zCompute query embeddings using a Bedrock model.

        Args:
            text: The text to embed.

        Returns:
            Embeddings for the text.
        )r<   r   r@   )r:   r'   r/   r   r   r   embed_query   s    	

zBedrockEmbeddings.embed_queryc                    s   t d| j|I dH S )zAsynchronous compute query embeddings using a Bedrock model.

        Args:
            text: The text to embed.

        Returns:
            Embeddings for the text.
        N)r
   rD   )r:   r'   r   r   r   aembed_query   s    
zBedrockEmbeddings.aembed_queryc                    s&   t j fdd|D  I dH }t|S )zAsynchronous compute doc embeddings using a Bedrock model.

        Args:
            texts: The list of texts to embed

        Returns:
            List of embeddings, one for each text.
        c                    s   g | ]}  |qS r   )rE   ).0r'   r:   r   r   
<listcomp>   s     z6BedrockEmbeddings.aembed_documents.<locals>.<listcomp>N)asyncioZgatherlist)r:   r*   resultr   rG   r   aembed_documents   s    
z"BedrockEmbeddings.aembed_documents)r   r   r   __doc__r   __annotations__r   r   strr   r   r   r   r   r   boolr   r	   r&   r   floatr<   r@   rC   rD   rE   rL   r   r   r   r   r      s"   

&%r   )rI   r5   r1   typingr   r   r   r   Znumpyr=   Zlangchain_core._api.deprecationr   Zlangchain_core.embeddingsr   Zlangchain_core.pydantic_v1r   r	   Zlangchain_core.runnables.configr
   r   r   r   r   r   <module>   s   