
    NgZ                        d dl mZ d dlZd dlZd dlmZmZ d dlmZm	Z	m
Z
mZmZmZmZ d dlmZ d dlmZ d dlmZ erd dlmZ d dlmZ  ej                    Ze G d	 d
                      Z G d de          ZdS )    )annotationsN)asdict	dataclass)TYPE_CHECKINGAnyDictIterableListOptionalTupleDocument)
Embeddings)VectorStore)DocumentCollectionc                  F    e Zd ZU dZded<   ded<   ded<   ded	<   d
ed<   dS )CollectionConfiga  Configuration for a `Zep Collection`.

    If the collection does not exist, it will be created.

    Attributes:
        name (str): The name of the collection.
        description (Optional[str]): An optional description of the collection.
        metadata (Optional[Dict[str, Any]]): Optional metadata for the collection.
        embedding_dimensions (int): The number of dimensions for the embeddings in
            the collection. This should match the Zep server configuration
            if auto-embed is true.
        is_auto_embedded (bool): A flag indicating whether the collection is
            automatically embedded by Zep.
    strnameOptional[str]descriptionOptional[Dict[str, Any]]metadataintembedding_dimensionsboolis_auto_embeddedN)__name__
__module____qualname____doc____annotations__     `/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/vectorstores/zep.pyr   r      sW           III&&&&r$   r   c                  v    e Zd ZdZdddddD fdZedEd            ZdFdZdFdZ	 	 dGdHdZ		 	 dGdId Z
	 	 dGdId!Z	 	 dJdKd*Z	 	 dJdKd+Z	 	 dLdMd-Z	 	 dLdNd/Z	 	 dLdNd0Z	 	 dLdNd1Z	 	 dLdMd2Z	 	 dLdOd4Z	 	 dLdOd5Z	 	 	 	 dPdQd;Z	 	 	 	 dPdQd<Z	 	 	 	 dPdRd=Z	 	 	 	 dPdRd>Ze	 	 	 	 	 	 dSdTdA            ZdUdVdCZ xZS )WZepVectorStorea  `Zep` vector store.

    It provides methods for adding texts or documents to the store,
    searching for similar documents, and deleting documents.

    Search scores are calculated using cosine similarity normalized to [0, 1].

    Args:
        api_url (str): The URL of the Zep API.
        collection_name (str): The name of the collection in the Zep store.
        api_key (Optional[str]): The API key for the Zep API.
        config (Optional[CollectionConfig]): The configuration for the collection.
            Required if the collection does not already exist.
        embedding (Optional[Embeddings]): Optional embedding function to use to
            embed the texts. Required if the collection is not auto-embedded.
    Napi_keyconfig	embeddingcollection_namer   api_urlr)   r   r*   Optional[CollectionConfig]r+   Optional[Embeddings]returnNonec               p   t                                                       |st          d          	 ddlm} n# t
          $ r t          d          w xY w |||          | _        || _        |r|j        | j        k    r| j        |_        || _	        | 
                                | _        || _        d S )Nz<collection_name must be specified when using ZepVectorStore.r   )	ZepClientz\Could not import zep-python python package. Please install it with `pip install zep-python`.)r)   )super__init__
ValueError
zep_pythonr3   ImportError_clientr,   r   _collection_config_load_collection_collection
_embedding)selfr,   r-   r)   r*   r+   r3   	__class__s          r%   r5   zZepVectorStore.__init__>   s     	 	N  	,,,,,,, 	 	 	C  	
 !y':::.  	/fkT%999.FK"(0022#s	   ; Ac                    | j         S )z/Access the query embedding object if available.)r=   )r>   s    r%   
embeddingszZepVectorStore.embeddingsa   s     r$   r   c                    ddl m} 	 | j        j                            | j                  }nB# |$ r: t                              d| j         d           |                                 }Y nw xY w|S )z;
        Load the collection from the Zep backend.
        r   )NotFoundErrorzCollection z$ not found. Creating new collection.)	r7   rC   r9   documentget_collectionr,   loggerinfo_create_collection)r>   rC   
collections      r%   r;   zZepVectorStore._load_collectionf   s     	-,,,,,	3.==d>RSSJJ 	3 	3 	3KKXd2XXX   0022JJJ		3 s   $- <A,+A,c                    | j         st          d           | j        j        j        di t          | j                   }|S )z=
        Create a new collection in the Zep backend.
        zCCollection config must be specified when creating a new collection.r#   )r:   r6   r9   rD   add_collectionr   )r>   rI   s     r%   rH   z!ZepVectorStore._create_collectionv   s_     & 	U   :T\*9 
 
T,--
 

 r$   textsIterable[str]	metadatasOptional[List[Dict[Any, Any]]]document_idsOptional[List[str]]List[ZepDocument]c           
     >   ddl m} d }| j        r*| j        j        r| j        t          j        dd           n| j        | j                            t          |                    }| j        rU| j        j	        t          |d                   k    r2t          d| j        j	         dt          |d                              n	 g }t          |          D ]E\  }}|                     |||r||         nd |r||         nd |r||         nd                      F|S )	Nr   r   z{The collection is set to auto-embed and an embedding 
                function is present. Ignoring the embedding function.   )
stacklevelzkThe embedding dimensions of the collection and the embedding function do not match. Collection dimensions: z, Embedding dimensions: )contentr   document_idr+   )zep_python.documentr   r<   r   r=   warningswarnembed_documentslistr   lenr6   	enumerateappend)	r>   rL   rN   rP   ZepDocumentrA   	documentsids	            r%   _generate_documents_to_addz)ZepVectorStore._generate_documents_to_add   s    	@?????
 	 0 A 	*I    
 _(88eEEJ D$4$IS1N N % % !-(=- - JqM**- -   ')	e$$ 	 	DAq-6@Yq\\D3? IQT/9Cjmmt	      r$   Optional[List[Dict[str, Any]]]kwargsr   	List[str]c                    | j         st          d          |                     |||          }| j                             |          }|S )a  Run more texts through the embeddings and add to the vectorstore.

        Args:
            texts: Iterable of strings to add to the vectorstore.
            metadatas: Optional list of metadatas associated with the texts.
            document_ids: Optional list of document ids associated with the texts.
            kwargs: vectorstore specific parameters

        Returns:
            List of ids from adding the texts into the vectorstore.
        <collection should be an instance of a Zep DocumentCollection)r<   r6   rd   add_documentsr>   rL   rN   rP   rf   ra   uuidss          r%   	add_textszZepVectorStore.add_texts   sX    $  	N   33E9lSS	 ..y99r$   c                   K   | j         st          d          |                     |||          }| j                             |           d{V }|S )zARun more texts through the embeddings and add to the vectorstore.ri   N)r<   r6   rd   aadd_documentsrk   s          r%   
aadd_textszZepVectorStore.aadd_texts   sn        	N   33E9lSS	&55i@@@@@@@@r$      querysearch_typer   r   kr   List[Document]c                    |dk    r | j         |f||d|S |dk    r | j        |f||d|S t          d| d          )>Return docs most similar to query using specified search type.
similarityrt   r   mmrsearch_type of ? not allowed. Expected search_type to be 'similarity' or 'mmr'.)similarity_searchmax_marginal_relevance_searchr6   r>   rr   rs   r   rt   rf   s         r%   searchzZepVectorStore.search   s     ,&&)4)%R1xRR6RRRE!!545X 17   ;+ ; ; ;  r$   c                   K   |dk    r | j         |f||d| d{V S |dk    r | j        |f||d| d{V S t          d| d          )rw   rx   ry   Nrz   r{   r|   )asimilarity_searchamax_marginal_relevance_searchr6   r   s         r%   asearchzZepVectorStore.asearch   s       ,&&00X 17         E!!<<X 17         ;+ ; ; ;  r$      c                <     | j         |f||d|}d |D             S )"Return docs most similar to query.ry   c                    g | ]\  }}|S r#   r#   .0doc_s      r%   
<listcomp>z4ZepVectorStore.similarity_search.<locals>.<listcomp>      ***Q***r$   (_similarity_search_with_relevance_scoresr>   rr   rt   r   rf   resultss         r%   r}   z ZepVectorStore.similarity_search  sI     @$?

 
-3
 
 +*'****r$   List[Tuple[Document, float]]c                $     | j         |f||d|S )z$Run similarity search with distance.ry   r   )r>   rr   rt   r   rf   s        r%   similarity_search_with_scorez+ZepVectorStore.similarity_search_with_score  s5     =t<

 
-3
 
 	
r$   c                    | j         st          d          | j         j        s8| j        r1| j                            |          } | j         j        d|||d|}n | j         j        |f||d|}d |D             S )a  
        Default similarity search with relevance scores. Modify if necessary
        in subclass.
        Return docs and relevance scores in the range [0, 1].

        0 is dissimilar, 1 is most similar.

        Args:
            query: input text
            k: Number of Documents to return. Defaults to 4.
            metadata: Optional, metadata filter
            **kwargs: kwargs to be passed to similarity search. Should include:
                score_threshold: Optional, a floating point value between 0 to 1 and
                    filter the resulting set of retrieved docs

        Returns:
            List of Tuples of (doc, similarity_score)
        ri   r+   limitr   r   r   c                V    g | ]&}t          |j        |j                   |j        pdf'S page_contentr   g        r   rV   r   scorer   r   s     r%   r   zKZepVectorStore._similarity_search_with_relevance_scores.<locals>.<listcomp>K  T     	
 	
 	
  !$ \   	 S	
 	
 	
r$   r#   )r<   r6   r   r=   embed_queryr   r>   rr   rt   r   rf   query_vectorr   s          r%   r   z7ZepVectorStore._similarity_search_with_relevance_scores"  s    4  	N   0 	T_ 	?66u==L-d&- &a( FL GG .d&- 5; G	
 	
 	
 	
 	
 		
r$   c                  K   | j         st          d          | j         j        s>| j        r7| j                            |          } | j         j        d|||d| d{V }n | j         j        |f||d| d{V }d |D             S )r   ri   r   Nr   c                V    g | ]&}t          |j        |j                   |j        pdf'S r   r   r   s     r%   r   zKZepVectorStore.asimilarity_search_with_relevance_scores.<locals>.<listcomp>n  r   r$   r#   )r<   r6   r   r=   r   r   r   s          r%   (asimilarity_search_with_relevance_scoresz7ZepVectorStore.asimilarity_search_with_relevance_scoresV  s       	N   0 	T_ 	?66u==L4D,4 &a( FL       GG 5D,4 5;       G	
 	
 	
 	
 	
 		
r$   c                L   K    | j         ||fd|i| d{V }d |D             S )r   r   Nc                    g | ]\  }}|S r#   r#   r   s      r%   r   z5ZepVectorStore.asimilarity_search.<locals>.<listcomp>  r   r$   )r   r   s         r%   r   z!ZepVectorStore.asimilarity_searchy  sk       FE1
 
'
+1
 
 
 
 
 
 
 
 +*'****r$   List[float]c                r    | j         st          d           | j         j        d|||d|}d |D             S )aF  Return docs most similar to embedding vector.

        Args:
            embedding: Embedding to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            metadata: Optional, metadata filter

        Returns:
            List of Documents most similar to the query vector.
        ri   r   c                D    g | ]}t          |j        |j                   S r   r   rV   r   r   s     r%   r   z>ZepVectorStore.similarity_search_by_vector.<locals>.<listcomp>  C     
 
 

 	  [  
 
 
r$   r#   r<   r6   r   r>   r+   rt   r   rf   r   s         r%   similarity_search_by_vectorz*ZepVectorStore.similarity_search_by_vector  sy    "  	N   *$") 
q8
 
?E
 

 

 
 
 
 	
r$   c                v   K   | j         st          d           | j         j        d|||d|}d |D             S )z-Return docs most similar to embedding vector.ri   r   c                D    g | ]}t          |j        |j                   S r   r   r   s     r%   r   z?ZepVectorStore.asimilarity_search_by_vector.<locals>.<listcomp>  r   r$   r#   r   r   s         r%   asimilarity_search_by_vectorz+ZepVectorStore.asimilarity_search_by_vector  s}        	N   *$") 
q8
 
?E
 

 

 
 
 
 	
r$            ?fetch_klambda_multfloatc           	        | j         st          d          | j         j        s:| j        r3| j                            |          } | j         j        d|||d|d|}n | j         j        |f||d|d|\  }}d |D             S )a  Return docs selected using the maximal marginal relevance.

        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
                     Zep determines this automatically and this parameter is
                        ignored.
            lambda_mult: Number between 0 and 1 that determines the degree
                        of diversity among the results with 0 corresponding
                        to maximum diversity and 1 to minimum diversity.
                        Defaults to 0.5.
            metadata: Optional, metadata to filter the resulting set of retrieved docs
        Returns:
            List of Documents selected by maximal marginal relevance.
        ri   rz   r+   r   r   rs   
mmr_lambdar   r   rs   r   c                D    g | ]}t          |j        |j                   S r   r   r   rc   s     r%   r   z@ZepVectorStore.max_marginal_relevance_search.<locals>.<listcomp>  )    WWW!ai!*EEEWWWr$   r#   )r<   r6   r   r=   r   r   search_return_query_vector	r>   rr   rt   r   r   r   rf   r   r   s	            r%   r~   z,ZepVectorStore.max_marginal_relevance_search  s    :  	N   0 	T_ 	?66u==L-d&- &!!&   GG %PD$4$O%!!&% % % %!G\ XWwWWWWr$   c           	     $  K   | j         st          d          | j         j        s@| j        r9| j                            |          } | j         j        d|||d|d| d{V }n! | j         j        |f||d|d| d{V \  }}d |D             S ):Return docs selected using the maximal marginal relevance.ri   rz   r   Nr   c                D    g | ]}t          |j        |j                   S r   r   r   s     r%   r   zAZepVectorStore.amax_marginal_relevance_search.<locals>.<listcomp>  r   r$   r#   )r<   r6   r   r=   r   r   asearch_return_query_vectorr   s	            r%   r   z-ZepVectorStore.amax_marginal_relevance_search  s'       	N   0 	T_ 	?66u==L4D,4 &!!&         GG +W$*:*V+!!&+ + + + % % % % % %!G\ XWwWWWWr$   c           	     v    | j         st          d           | j         j        d|||d|d|}d |D             S )a  Return docs selected using the maximal marginal relevance.

        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.

        Args:
            embedding: Embedding to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
                     Zep determines this automatically and this parameter is
                        ignored.
            lambda_mult: Number between 0 and 1 that determines the degree
                        of diversity among the results with 0 corresponding
                        to maximum diversity and 1 to minimum diversity.
                        Defaults to 0.5.
            metadata: Optional, metadata to filter the resulting set of retrieved docs
        Returns:
            List of Documents selected by maximal marginal relevance.
        ri   rz   r   c                D    g | ]}t          |j        |j                   S r   r   r   s     r%   r   zJZepVectorStore.max_marginal_relevance_search_by_vector.<locals>.<listcomp>K  r   r$   r#   r   r>   r+   rt   r   r   r   rf   r   s           r%   'max_marginal_relevance_search_by_vectorz6ZepVectorStore.max_marginal_relevance_search_by_vector!  sw    8  	N   *$") 
"
 
 
 
 XWwWWWWr$   c           	        K   | j         st          d           | j         j        d|||d|d| d{V }d |D             S )r   ri   rz   r   Nc                D    g | ]}t          |j        |j                   S r   r   r   s     r%   r   zKZepVectorStore.amax_marginal_relevance_search_by_vector.<locals>.<listcomp>e  r   r$   r#   )r<   r6   r   r   s           r%   (amax_marginal_relevance_search_by_vectorz7ZepVectorStore.amax_marginal_relevance_search_by_vectorM  s        	N   1(0 
"
 
 
 
 
 
 
 
 
 
 XWwWWWWr$    Optional[List[dict]]c                R     | |||||          }	|	                     ||           |	S )a  
        Class method that returns a ZepVectorStore instance initialized from texts.

        If the collection does not exist, it will be created.

        Args:
            texts (List[str]): The list of texts to add to the vectorstore.
            embedding (Optional[Embeddings]): Optional embedding function to use to
               embed the texts.
            metadatas (Optional[List[Dict[str, Any]]]): Optional list of metadata
               associated with the texts.
            collection_name (str): The name of the collection in the Zep store.
            api_url (str): The URL of the Zep API.
            api_key (Optional[str]): The API key for the Zep API.
            config (Optional[CollectionConfig]): The configuration for the collection.
            kwargs: Additional parameters specific to the vectorstore.

        Returns:
            ZepVectorStore: An instance of ZepVectorStore.
        r(   )rm   )
clsrL   r+   rN   r,   r-   r)   r*   rf   vecstores
             r%   
from_textszZepVectorStore.from_textsg  sG    @ 3
 
 
 	5),,,r$   idsc                    |t          |          dk    rt          d          | j        t          d          |D ]}| j                            |           dS )zDelete by Zep vector UUIDs.

        Parameters
        ----------
        ids : Optional[List[str]]
            The UUIDs of the vectors to delete.

        Raises
        ------
        ValueError
            If no UUIDs are provided.
        Nr   zNo uuids provided to delete.zNo collection name provided.)r]   r6   r<   delete_document)r>   r   rf   us       r%   deletezZepVectorStore.delete  sq     ;#c((a--;<<<#;<<< 	0 	0A,,Q////	0 	0r$   )r,   r   r-   r   r)   r   r*   r.   r+   r/   r0   r1   )r0   r/   )r0   r   )NN)rL   rM   rN   rO   rP   rQ   r0   rR   )
rL   rM   rN   re   rP   rQ   rf   r   r0   rg   )Nrq   )rr   r   rs   r   r   r   rt   r   rf   r   r0   ru   )r   N)
rr   r   rt   r   r   r   rf   r   r0   ru   )
rr   r   rt   r   r   r   rf   r   r0   r   )
r+   r   rt   r   r   r   rf   r   r0   ru   )r   r   r   N)rr   r   rt   r   r   r   r   r   r   r   rf   r   r0   ru   )r+   r   rt   r   r   r   r   r   r   r   rf   r   r0   ru   )NNr   r   NN)rL   rg   r+   r/   rN   r   r,   r   r-   r   r)   r   r*   r.   rf   r   r0   r'   )N)r   rQ   rf   r   r0   r1   )r   r   r    r!   r5   propertyrA   r;   rH   rd   rm   rp   r   r   r}   r   r   r   r   r   r   r~   r   r   r   classmethodr   r   __classcell__)r?   s   @r%   r'   r'   ,   s;        , "&-1*.$ $ $ $ $ $ $ $F    X         59,0	( ( ( ( (Z 59,0	    > 59,0	    , .2    2 .2    4 -1	+ + + + +" -1	
 
 
 
 
  -1	2
 2
 2
 2
 2
n -1	!
 !
 !
 !
 !
L -1	+ + + + +$ -1	 
  
  
  
  
J -1	
 
 
 
 
8  -16X 6X 6X 6X 6Xv  -1$X $X $X $X $XR  -1*X *X *X *X *X^  -1X X X X X4  +/*.!!%-1' ' ' ' ['R0 0 0 0 0 0 0 0 0r$   r'   )
__future__r   loggingrY   dataclassesr   r   typingr   r   r   r	   r
   r   r   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.vectorstoresr   rX   r`   r   	getLoggerrF   r   r'   r#   r$   r%   <module>r      s]   " " " " " "   ) ) ) ) ) ) ) ) L L L L L L L L L L L L L L L L L L - - - - - - 0 0 0 0 0 0 3 3 3 3 3 3 7;;;;;;666666 
			        .z	0 z	0 z	0 z	0 z	0[ z	0 z	0 z	0 z	0 z	0r$   