o
    Zh                     @   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 d dlmZ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)run_in_executor)	BaseModel
ConfigDictmodel_validator)Selfz0.2.11z1.0zlangchain_aws.BedrockEmbeddings)ZsinceZremovalZalternative_importc                   @   sB  e Zd ZU dZ	 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< 	 edddZedddefddZde	dee fddZdee dee fddZdee	 deee  fddZde	dee fddZde	dee fdd Zdee	 deee  f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.
    Nclientregion_namecredentials_profile_namezamazon.titan-embed-text-v1model_idmodel_kwargsendpoint_urlF	normalizeZforbid )extraZprotected_namespacesafter)modereturnc              
   C   s   | j dur| S z3ddl}| jdur|j| jd}n| }i }| jr'| j|d< | jr/| j|d< |j d	i || _ W | S  tyE   td tyX } ztd| |d}~ww )
zJValidate that AWS credentials to and python package exists in environment.Nr   )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   )	r   boto3r   Sessionr   r   ImportError	Exception
ValueError)selfr   sessionZclient_paramser   r   ]/var/www/html/lang_env/lib/python3.10/site-packages/langchain_community/embeddings/bedrock.pyvalidate_environmentP   s8   



z&BedrockEmbeddings.validate_environmenttextc           	   
   C   s   | tjd}| jdd }| jpi }i |}|dkr,d| vr&d|d< |g|d< n||d< t|}z'| j	j
|| jd	d	d
}t|d }|dkrW|dd W S |dW S  tyo } ztd| d}~ww )z'Call out to Bedrock embedding endpoint. .r   ZcohereZ
input_typeZsearch_documenttextsZ	inputTextzapplication/json)bodyZmodelIdacceptZcontentTyper)   
embeddings	embeddingz$Error raised by inference endpoint: N)replaceoslinesepr   splitr   keysjsondumpsr   Zinvoke_modelloadsgetreadr   r   )	r    r%   providerZ_model_kwargsZ
input_bodyr)   responseZresponse_bodyr"   r   r   r#   _embedding_funcw   s2   

z!BedrockEmbeddings._embedding_funcr+   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_vectorr(   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.
        )r9   r   r=   append)r    r(   resultsr%   r8   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.
        )r9   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   rA   )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   )rB   ).0r%   r    r   r#   
<listcomp>   s    z6BedrockEmbeddings.aembed_documents.<locals>.<listcomp>N)asynciogatherlist)r    r(   resultr   rD   r#   aembed_documents   s   
z"BedrockEmbeddings.aembed_documents)__name__
__module____qualname____doc__r   r   __annotations__r   r   strr   r   r   r   r   r   boolr
   Zmodel_configr   r   r$   r   floatr9   r=   r@   rA   rB   rJ   r   r   r   r#   r      s4   
 &%"r   )rF   r2   r.   typingr   r   r   r   numpyr:   Zlangchain_core._api.deprecationr   Zlangchain_core.embeddingsr   Zlangchain_core.runnables.configr   Zpydanticr	   r
   r   Ztyping_extensionsr   r   r   r   r   r#   <module>   s     