
    Ng                         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
           G 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)sinceremovalalternative_importc                      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          Z ed          defd            Zde	dee         fdZdee         dee         fdZdee	         deee                  fdZde	dee         fdZde	dee         fdZdee	         deee                  f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	normalizeforbid )extraprotected_namespacesafter)modereturnc                 x   | j         | S 	 ddl}| j        |                    | j                  }n|                                }i }| j        r
| j        |d<   | j        r
| j        |d<    |j         d	i || _         n=# t          $ r t          d          t          $ r}t          d|           |d}~ww xY w| S )
zJValidate that AWS credentials to and python package exists in environment.Nr   )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$   sessionclient_paramses        b/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/embeddings/bedrock.pyvalidate_environmentz&BedrockEmbeddings.validate_environmentP   s    ;"K	LLL,8--T5R-SS  --//M @/3/?m,  B040An-('.LLmLLDKK 	 	 	>    	 	 	>:;> >  		 s   A1A= ="B7B22B7textc                    |                     t          j        d          }| j                            d          d         }| j        pi }i |}|dk    r"d|                                vrd|d<   |g|d<   n||d<   t          j        |          }	 | j	        
                    || j        d	d	
          }t          j        |                    d                                                    }|dk    r|                    d          d         S |                    d          S # t          $ r}t          d|           d}~ww xY w)z'Call out to Bedrock embedding endpoint. .r   cohere
input_typesearch_documenttexts	inputTextzapplication/json)bodymodelIdacceptcontentTyper8   
embeddings	embeddingz$Error raised by inference endpoint: N)replaceoslinesepr   splitr   keysjsondumpsr   invoke_modelloadsgetreadr'   r(   )	r)   r/   provider_model_kwargs
input_bodyr8   responseresponse_bodyr,   s	            r-   _embedding_funcz!BedrockEmbeddings._embedding_funcw   sm    ||BJ,, =&&s++A.)/R&&
x:??#4#444+<
<(#'&Jw '+J{#z*%%	I{//).	 0  H !Jx||F';';'@'@'B'BCCM8##$((66q99 %((555 	I 	I 	IGAGGHHH	Is   A<D" D" "
E,D>>Er<   c                     t          j        |          }|t           j                            |          z  }|                                S )z)Normalize the embedding to a unit vector.)nparraylinalgnormtolist)r)   r<   embnorm_embs       r-   _normalize_vectorz#BedrockEmbeddings._normalize_vector   s9    hz"",,,       r6   c                     g }|D ]H}|                      |          }| j        r|                     |          }|                    |           I|S )zCompute doc embeddings using a Bedrock model.

        Args:
            texts: The list of texts to embed

        Returns:
            List of embeddings, one for each text.
        )rN   r   rW   append)r)   r6   resultsr/   rL   s        r-   embed_documentsz!BedrockEmbeddings.embed_documents   sb      	% 	%D++D11H~ <11(;;NN8$$$$rX   c                 h    |                      |          }| j        r|                     |          S |S )zCompute query embeddings using a Bedrock model.

        Args:
            text: The text to embed.

        Returns:
            Embeddings for the text.
        )rN   r   rW   )r)   r/   r=   s      r-   embed_queryzBedrockEmbeddings.embed_query   s;     ((..	> 	5)))444rX   c                 >   K   t          d| j        |           d{V S )zAsynchronous compute query embeddings using a Bedrock model.

        Args:
            text: The text to embed.

        Returns:
            Embeddings for the text.
        N)r	   r^   )r)   r/   s     r-   aembed_queryzBedrockEmbeddings.aembed_query   s/       %T4+;TBBBBBBBBBrX   c                 f    K   t          j         fd|D               d{V }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                 :    g | ]}                     |          S r   )r`   ).0r/   r)   s     r-   
<listcomp>z6BedrockEmbeddings.aembed_documents.<locals>.<listcomp>   s'    'R'R'RD(9(9$(?(?'R'R'RrX   N)asynciogatherlist)r)   r6   results   `  r-   aembed_documentsz"BedrockEmbeddings.aembed_documents   sH       ~'R'R'R'RE'R'R'RSSSSSSSF||rX   )__name__
__module____qualname____doc__r   r   __annotations__r   r   strr   r   r   r   r   r   boolr   model_configr   r   r.   r   floatrN   rW   r\   r^   r`   ri   r   rX   r-   r   r      s         " FC!%K#%%% /3hsm222 1Hc000L $(L(4.'''1"&L(3-&&&CItE:H2FFFL_'"""$d $ $ $ #"$L#IC #IDK #I #I #I #IJ!DK !DK ! ! ! !T#Y 4U3D    ( U     
Cs 
CtE{ 
C 
C 
C 
CDI $tE{:K      rX   r   )re   rC   r?   typingr   r   r   r   numpyrP   langchain_core._api.deprecationr   langchain_core.embeddingsr   langchain_core.runnables.configr	   pydanticr
   r   r   typing_extensionsr   r   r   rX   r-   <module>rz      s     				 , , , , , , , , , , , ,     6 6 6 6 6 6 0 0 0 0 0 0 ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; " " " " " " 
8  
K K K K K	: K K 
K K KrX   