
    7|h                         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y)    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                   v   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y)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                    | j                   | S 	 ddl}| j                  |j                  | j                        }n|j                         }i }| j                  r| j                  |d<   | j
                  r| j
                  |d<    |j                   di || _         | S # t        $ r t        d      t        $ r}t        d|       |d}~ww xY w)	zJValidate that AWS credentials to and python package exists in environment.Nr   )profile_namer   r   zRCould 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: )zbedrock-runtime)	r   boto3r   Sessionr   r   ImportError	Exception
ValueError)selfr#   sessionclient_paramses        e/var/www/html/test/engine/venv/lib/python3.12/site-packages/langchain_community/embeddings/bedrock.pyvalidate_environmentz&BedrockEmbeddings.validate_environmentP   s     ;;"K	,,8--T5R5R-S  --/M/3/?/?m,  040A0An-('..LmLDK   	>   	::;> 		s   BB C:C		Ctextc                 j   |j                  t        j                  d      }| j                  j	                  d      d   }| j
                  xs i }i |}|dk(  rd|j                         vrd|d<   |g|d<   n||d<   t        j                  |      }	 | j                  j                  || j                  d	d	
      }t        j                  |j                  d      j                               }|dk(  r|j                  d      d   S |j                  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contentTyper7   
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_bodyr7   responseresponse_bodyr+   s	            r,   _embedding_funcz!BedrockEmbeddings._embedding_funcw   s;    ||BJJ, ==&&s+A.))/R&&
x:??#44+<
<(#'&Jw '+J{#zz*%	I{{//).	 0 H !JJx||F';'@'@'BCM8#$((6q99 %((55 	ICA3GHH	Is   A3D D 	D2D--D2r;   c                     t        j                  |      }|t         j                  j                  |      z  }|j	                         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   s4    hhz",,      r5   c                     g }|D ]A  }| j                  |      }| j                  r| j                  |      }|j                  |       C |S )zCompute doc embeddings using a Bedrock model.

        Args:
            texts: The list of texts to embed

        Returns:
            List of embeddings, one for each text.
        )rM   r   rV   append)r(   r5   resultsr.   rK   s        r,   embed_documentsz!BedrockEmbeddings.embed_documents   sR      	%D++D1H~~11(;NN8$	% rW   c                 b    | j                  |      }| j                  r| j                  |      S |S )zCompute query embeddings using a Bedrock model.

        Args:
            text: The text to embed.

        Returns:
            Embeddings for the text.
        )rM   r   rV   )r(   r.   r<   s      r,   embed_queryzBedrockEmbeddings.embed_query   s2     ((.	>>)))44rW   c                 L   K   t        d| j                  |       d{   S 7 w)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Bs   $"$c                    K   t        j                  |D cg c]  }| j                  |       c}  d{   }t        |      S c c}w 7 w)zAsynchronous compute doc embeddings using a Bedrock model.

        Args:
            texts: The list of texts to embed

        Returns:
            List of embeddings, one for each text.
        N)asynciogatherr_   list)r(   r5   r.   results       r,   aembed_documentsz"BedrockEmbeddings.aembed_documents   sB      ~~E'RD(9(9$(?'RSSF| (SSs   AAAA
A)__name__
__module____qualname____doc__r   r   __annotations__r   r   strr   r   r   r   r   r   boolr   model_configr   r   r-   r   floatrM   rV   r[   r]   r_   re   r   rW   r,   r   r      sY   " FC!%K#% /3hsm2 1Hc0L $(L(4.'1"&L(3-&CItEH2FL'"$d $ #$L#IC #IDK #IJ!DK !DK !T#Y 4U3D ( U  
Cs 
CtE{ 
CDI $tE{:K rW   r   )ra   rB   r>   typingr   r   r   r   numpyrO   langchain_core._api.deprecationr   langchain_core.embeddingsr   langchain_core.runnables.configr	   pydanticr
   r   r   typing_extensionsr   r   r   rW   r,   <module>rv      sW      	 , ,  6 0 ; ; ; " 
8
K	: K
KrW   