
    Ng'                        d Z ddlmZ ddlZddlZddlZddlmZ ddlm	Z	m
Z
mZmZmZmZ ddlmZ ddlmZmZ ddlmZ dd	lmZ  ej        d
          ZddZd dZd!dZd"dZd#dZ G d de          ZdS )$a!  Module contains code for a cache backed embedder.

The cache backed embedder is a wrapper around an embedder that caches
embeddings in a key-value store. The cache is used to avoid recomputing
embeddings for the same text.

The text is hashed and the hash is used as the key in the cache.
    )annotationsN)partial)CallableListOptionalSequenceUnioncast)
Embeddings)	BaseStore	ByteStore)batch_iterate)EncoderBackedStorei  )intinput_stringstrreturn	uuid.UUIDc                    t          j        |                     d                                                    }t	          j        t          |          S )z1Hash a string and returns the corresponding UUID.zutf-8)hashlibsha1encode	hexdigestuuiduuid5NAMESPACE_UUID)r   
hash_values     V/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain/embeddings/cache.py_hash_string_to_uuidr      s=    l11'::;;EEGGJ:nj111    key	namespacec                @    |t          t          |                     z   S )zEncode a key.)r   r   )r!   r"   s     r   _key_encoderr$   !   s    s/445555r    Callable[[str], str]c                .    t          t          |           S )zCreate an encoder for a key.r"   )r   r$   r'   s    r   _create_key_encoderr(   &   s    <95555r    valueSequence[float]bytesc                N    t          j        |                                           S )zSerialize a value.)jsondumpsr   )r)   s    r   _value_serializerr/   +   s    :e##%%%r    serialized_valueList[float]c                    t          t          t                   t          j        |                                                     S )zDeserialize a value.)r
   r   floatr-   loadsdecode)r0   s    r   _value_deserializerr6   0   s-    UTZ(8(?(?(A(ABBCCCr    c                  n     e Zd ZdZdddd" fdZd#dZd#dZd$dZd$dZe	ddddd%d!            Z
 xZS )&CacheBackedEmbeddingsa  Interface for caching results from embedding models.

    The interface allows works with any store that implements
    the abstract store interface accepting keys of type str and values of list of
    floats.

    If need be, the interface can be extended to accept other implementations
    of the value serializer and deserializer, as well as the key encoder.

    Note that by default only document embeddings are cached. To cache query
    embeddings too, pass in a query_embedding_store to constructor.

    Examples:

        .. code-block: python

            from langchain.embeddings import CacheBackedEmbeddings
            from langchain.storage import LocalFileStore
            from langchain_community.embeddings import OpenAIEmbeddings

            store = LocalFileStore('./my_cache')

            underlying_embedder = OpenAIEmbeddings()
            embedder = CacheBackedEmbeddings.from_bytes_store(
                underlying_embedder, store, namespace=underlying_embedder.model
            )

            # Embedding is computed and cached
            embeddings = embedder.embed_documents(["hello", "goodbye"])

            # Embeddings are retrieved from the cache, no computation is done
            embeddings = embedder.embed_documents(["hello", "goodbye"])
    N
batch_sizequery_embedding_storeunderlying_embeddingsr   document_embedding_storeBaseStore[str, List[float]]r:   Optional[int]r;   %Optional[BaseStore[str, List[float]]]r   Nonec                   t                                                       || _        || _        || _        || _        dS )a  Initialize the embedder.

        Args:
            underlying_embeddings: the embedder to use for computing embeddings.
            document_embedding_store: The store to use for caching document embeddings.
            batch_size: The number of documents to embed between store updates.
            query_embedding_store: The store to use for caching query embeddings.
                If None, query embeddings are not cached.
        N)super__init__r=   r;   r<   r:   )selfr<   r=   r:   r;   	__class__s        r   rD   zCacheBackedEmbeddings.__init__X   s>    " 	(@%%:"%:"$r    texts	List[str]List[List[float]]c           	        | j                                       }d t          |          D             }t          | j        |          D ]z}fd|D             }| j                            |          }| j                             t          t          ||                               t          ||          D ]
\  }}|||<   {t          t          t          t                            |          S )w  Embed a list of texts.

        The method first checks the cache for the embeddings.
        If the embeddings are not found, the method uses the underlying embedder
        to embed the documents and stores the results in the cache.

        Args:
            texts: A list of texts to embed.

        Returns:
            A list of embeddings for the given texts.
        c                    g | ]	\  }}||
S N .0ivectors      r   
<listcomp>z9CacheBackedEmbeddings.embed_documents.<locals>.<listcomp>   $     *
 *
 *
!VV^A^^^r    c                     g | ]
}|         S rN   rN   rP   rQ   rG   s     r   rS   z9CacheBackedEmbeddings.embed_documents.<locals>.<listcomp>       ???!U1X???r    )r=   mget	enumerater   r:   r<   embed_documentsmsetlistzipr
   r   r3   	rE   rG   vectorsall_missing_indicesmissing_indicesmissing_textsmissing_vectorsindexupdated_vectors	    `       r   rZ   z%CacheBackedEmbeddings.embed_documentso   s    372O2T2T3
 3
*
 *
(11*
 *
 *
  -T_>QRR 	0 	0O???????M"8HHWWO)..S8899   *-_o)N)N 0 0%~!/0 ew
 
 	
r    c           	       K   | j                                        d{V }d t          |          D             }t          | j        |          D ]}fd|D             }| j                            |           d{V }| j                             t          t          ||                               d{V  t          ||          D ]
\  }}|||<   t          t          t          t                            |          S )rK   Nc                    g | ]	\  }}||
S rM   rN   rO   s      r   rS   z:CacheBackedEmbeddings.aembed_documents.<locals>.<listcomp>   rT   r    c                     g | ]
}|         S rN   rN   rV   s     r   rS   z:CacheBackedEmbeddings.aembed_documents.<locals>.<listcomp>   rW   r    )r=   amgetrY   r   r:   r<   aembed_documentsamsetr\   r]   r
   r   r3   r^   s	    `       r   rj   z&CacheBackedEmbeddings.aembed_documents   sm      /55e<<<<<<<< 	*
 *
(11*
 *
 *
  -T_>QRR 		0 		0O???????M$($>$O$O% %      O /55S8899         *-_o)N)N 0 0%~!/0 ew
 
 	
r    textr   r1   c                    | j         s| j                            |          S | j                             |g          \  }||S | j                            |          }| j                             ||fg           |S ),  Embed query text.

        By default, this method does not cache queries. To enable caching, set the
        `cache_query` parameter to `True` when initializing the embedder.

        Args:
            text: The text to embed.

        Returns:
            The embedding for the given text.
        )r;   r<   embed_queryrX   r[   rE   rl   cachedrR   s       r   ro   z!CacheBackedEmbeddings.embed_query   s     ) 	@-99$???.33TF;;	M+77=="''$(8999r    c                ,  K   | j         s | j                            |           d{V S | j                             |g           d{V \  }||S | j                            |           d{V }| j                             ||fg           d{V  |S )rn   N)r;   r<   aembed_queryri   rk   rp   s       r   rs   z"CacheBackedEmbeddings.aembed_query   s       ) 	G3@@FFFFFFFFF4::D6BBBBBBBB	M1>>tDDDDDDDD(..v/?@@@@@@@@@r     F)r"   r:   query_embedding_cachedocument_embedding_cacher   r"   ru   Union[bool, ByteStore]c               B   |}t          |          }t          t          t          t                   f         ||t
          t                    }|du r|}n@|du rd}n9t          t          t          t                   f         ||t
          t                    } | ||||          S )a  On-ramp that adds the necessary serialization and encoding to the store.

        Args:
            underlying_embeddings: The embedder to use for embedding.
            document_embedding_cache: The cache to use for storing document embeddings.
            *,
            namespace: The namespace to use for document cache.
                       This namespace is used to avoid collisions with other caches.
                       For example, set it to the name of the embedding model used.
            batch_size: The number of documents to embed between store updates.
            query_embedding_cache: The cache to use for storing query embeddings.
                True to use the same cache as document embeddings.
                False to not cache query embeddings.
        TFNr9   )r(   r   r   r   r3   r/   r6   )	clsr<   rv   r"   r:   ru   key_encoderr=   r;   s	            r   from_bytes_storez&CacheBackedEmbeddings.from_bytes_store   s    0 	))44#5c4;6F#G$	$
 $
  !D(($<!!"e++$(!!$6sDK7G$H%!#	% %! s!$!"7	
 
 
 	
r    )
r<   r   r=   r>   r:   r?   r;   r@   r   rA   )rG   rH   r   rI   )rl   r   r   r1   )r<   r   rv   r   r"   r   r:   r?   ru   rw   r   r8   )__name__
__module____qualname____doc__rD   rZ   rj   ro   rs   classmethodr{   __classcell__)rF   s   @r   r8   r8   5   s           N %)GK% % % % % % % %.
 
 
 
B#
 #
 #
 #
J   .   .  $(8=0
 0
 0
 0
 0
 [0
 0
 0
 0
 0
r    r8   )r   r   r   r   )r!   r   r"   r   r   r   )r"   r   r   r%   )r)   r*   r   r+   )r0   r+   r   r1   ) r   
__future__r   r   r-   r   	functoolsr   typingr   r   r   r   r	   r
   langchain_core.embeddingsr   langchain_core.storesr   r   langchain_core.utils.iterr    langchain.storage.encoder_backedr   UUIDr   r   r$   r(   r/   r6   r8   rN   r    r   <module>r      s    # " " " " "          B B B B B B B B B B B B B B B B 0 0 0 0 0 0 6 6 6 6 6 6 6 6 3 3 3 3 3 3 ? ? ? ? ? ?t$$$2 2 2 26 6 6 6
6 6 6 6
& & & &
D D D D
_
 _
 _
 _
 _
J _
 _
 _
 _
 _
r    