
    hZ                        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j0                         Ze G d	 d
             Z G d de      Zy)    )annotationsN)asdict	dataclass)TYPE_CHECKINGAnyDictIterableListOptionalTupleDocument)
Embeddings)VectorStore)DocumentCollectionc                  D    e Zd ZU dZded<   ded<   ded<   ded	<   d
ed<   y)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__     b/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langchain_community/vectorstores/zep.pyr   r      s&     I&&r$   r   c                      e Zd ZdZdddd	 	 	 	 	 	 	 	 	 	 	 d fdZedd       ZddZddZ	 	 d	 	 	 	 	 	 	 ddZ		 	 d	 	 	 	 	 	 	 	 	 dd	Z
	 	 d	 	 	 	 	 	 	 	 	 dd
Z	 	 d 	 	 	 	 	 	 	 	 	 	 	 d!dZ	 	 d 	 	 	 	 	 	 	 	 	 	 	 d!dZ	 	 d"	 	 	 	 	 	 	 	 	 d#dZ	 	 d"	 	 	 	 	 	 	 	 	 d$dZ	 	 d"	 	 	 	 	 	 	 	 	 d$dZ	 	 d"	 	 	 	 	 	 	 	 	 d$dZ	 	 d"	 	 	 	 	 	 	 	 	 d#dZ	 	 d"	 	 	 	 	 	 	 	 	 d%dZ	 	 d"	 	 	 	 	 	 	 	 	 d%dZ	 	 	 	 d&	 	 	 	 	 	 	 	 	 	 	 	 	 d'dZ	 	 	 	 d&	 	 	 	 	 	 	 	 	 	 	 	 	 d'dZ	 	 	 	 d&	 	 	 	 	 	 	 	 	 	 	 	 	 d(dZ	 	 	 	 d&	 	 	 	 	 	 	 	 	 	 	 	 	 d(dZe	 	 	 	 	 	 d)	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d*d       Zd+d,dZ xZS )-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	embeddingc               D   t         |           |st        d      	 ddlm}  |||      | _        || _        |r*|j                  | j                  k7  r| j                  |_        || _	        | j                         | _        || _        y # t
        $ r t        d      w xY w)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_pythonr-   ImportError_clientcollection_namer   _collection_config_load_collection_collection
_embedding)selfr4   api_urlr)   r*   r+   r-   	__class__s          r%   r/   zZepVectorStore.__init__>   s     	N 	, !':. fkkT%9%99..FK"(002#  	C 	s   B
 
Bc                    | j                   S )z/Access the query embedding object if available.)r8   )r9   s    r%   
embeddingszZepVectorStore.embeddingsa   s     r$   c                    ddl m} 	 | j                  j                  j	                  | j
                        }|S # |$ r7 t        j                  d| j
                   d       | j                         }Y |S w xY w)z;
        Load the collection from the Zep backend.
        r   )NotFoundErrorzCollection z$ not found. Creating new collection.)	r1   r?   r3   documentget_collectionr4   loggerinfo_create_collection)r9   r?   
collections      r%   r6   zZepVectorStore._load_collectionf   s{     	-	3..==d>R>RSJ   	3KKd2233WX 002J	3s   /9 8A54A5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#   )r5   r0   r3   r@   add_collectionr   )r9   rE   s     r%   rD   z!ZepVectorStore._create_collectionv   sV     &&U  :T\\**99 
T,,-

 r$   c           
     R   ddl m} d }| j                  r:| j                  j                  r$| j                  t        j                  dd       n| j                  | j                  j                  t        |            }| j                  rW| j                  j                  t        |d         k7  r2t        d| j                  j                   dt        |d                	 g }t        |      D ]5  \  }}|j                   |||r||   nd |r||   nd |r||   nd              7 |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   r7   r   r8   warningswarnembed_documentslistr   lenr0   	enumerateappend)	r9   texts	metadatasdocument_idsZepDocumentr=   	documentsids	            r%   _generate_documents_to_addz)ZepVectorStore._generate_documents_to_add   s5    	@
 0 0 A A*I 
 __(88eEJD$4$4$I$IS1N % !((==> ?JqM*+-  ')	e$ 	DAq-6Yq\D3?QT/9jmt		 r$   c                    | j                   st        d      | j                  |||      }| j                   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)r7   r0   r\   add_documentsr9   rU   rV   rW   kwargsrY   uuidss          r%   	add_textszZepVectorStore.add_texts   sN    $ N  33E9lS	  ..y9r$   c                   K   | j                   st        d      | j                  |||      }| j                   j                  |       d{   }|S 7 w)zARun more texts through the embeddings and add to the vectorstore.r^   N)r7   r0   r\   aadd_documentsr`   s          r%   
aadd_textszZepVectorStore.aadd_texts   s[      N  33E9lS	&&55i@@ As   A	AAA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kr   mmrsearch_type of ? not allowed. Expected search_type to be 'similarity' or 'mmr'.)similarity_searchmax_marginal_relevance_searchr0   r9   querysearch_typer   rk   ra   s         r%   searchzZepVectorStore.search   s}     ,&)4))%R1xR6RRE!5455X17  !+ /; ; r$   c                   K   |dk(  r | j                   |f||d| d{   S |dk(  r | j                  |f||d| d{   S t        d| d      7 67 w)rh   ri   rj   Nrl   rm   rn   )asimilarity_searchamax_marginal_relevance_searchr0   rq   s         r%   asearchzZepVectorStore.asearch   s      ,&000X17   E!<<<X17   !+ /; ; s!   AA"AAAAc                d     | j                   |f||d|}|D cg c]  \  }}|	 c}}S c c}}w )"Return docs most similar to query.rj   (_similarity_search_with_relevance_scoresr9   rr   rk   r   ra   resultsdoc_s           r%   ro   z ZepVectorStore.similarity_search  sF     @$??

-3
 #**Q***s   ,c                .     | j                   |f||d|S )z$Run similarity search with distance.rj   r{   )r9   rr   rk   r   ra   s        r%   similarity_search_with_scorez+ZepVectorStore.similarity_search_with_score  s.     =t<<

-3
 	
r$   c                   | j                   st        d      | j                   j                  sH| j                  r<| j                  j	                  |      } | j                   j
                  d|||d|}n  | j                   j
                  |f||d|}|D cg c]3  }t        |j                  |j                        |j                  xs df5 c}S c c}w )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)
        r^   r+   limitr   r   r   page_contentr           r#   )
r7   r0   r   r8   embed_queryrt   r   rK   r   scorer9   rr   rk   r   ra   query_vectorr~   r   s           r%   r|   z7ZepVectorStore._similarity_search_with_relevance_scores"  s    4 N  00T__??66u=L-d&&-- &a(FLG .d&&--5;G 	
  !$ \\ 		 S	
 		
 	
s   8Cc                  K   | j                   st        d      | j                   j                  sP| j                  rD| j                  j	                  |      } | j                   j
                  d|||d| d{   }n( | j                   j
                  |f||d| d{   }|D cg c]3  }t        |j                  |j                        |j                  xs df5 c}S 7 l7 Ec c}w w)rz   r^   r   Nr   r   r   r#   )
r7   r0   r   r8   r   rx   r   rK   r   r   r   s           r%   (asimilarity_search_with_relevance_scoresz7ZepVectorStore.asimilarity_search_with_relevance_scoresV  s     N  00T__??66u=L4D,,44 &a(FL G 5D,,445; G 	
  !$ \\ 		 S	
 		
	
s6   A8C0:C';(C0#C)$C0,8C+$C0)C0+C0c                   K    | j                   ||fd|i| d{   }|D cg c]  \  }}|	 c}}S 7 c c}}w w)rz   r   N)r   r}   s           r%   rv   z!ZepVectorStore.asimilarity_searchy  sV      FEE1
'
+1
 
 #**Q**	
 +s   >6	>8>>c                    | j                   st        d       | j                   j                  d|||d|}|D cg c]#  }t        |j                  |j
                        % c}S c c}w )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.
        r^   r   r   r#   r7   r0   rt   r   rK   r   r9   r+   rk   r   ra   r~   r   s          r%   similarity_search_by_vectorz*ZepVectorStore.similarity_search_by_vector  s    " N  *$"")) 
q8
?E
 

 	  [[
 	
 
s   (A'c                   K   | j                   st        d       | j                   j                  d|||d|}|D cg c]#  }t        |j                  |j
                        % c}S c c}w w)z-Return docs most similar to embedding vector.r^   r   r   r#   r   r   s          r%   asimilarity_search_by_vectorz+ZepVectorStore.asimilarity_search_by_vector  s      N  *$"")) 
q8
?E
 

 	  [[
 	
 
s   <A.(A)&A.c           	        | j                   st        d      | j                   j                  sJ| j                  r>| j                  j	                  |      } | j                   j
                  d|||d|d|}n% | j                   j                  |f||d|d|\  }}|D 	cg c]#  }	t        |	j                  |	j                        % c}	S c c}	w )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.
        r^   rl   r+   r   r   rs   
mmr_lambdar   r   rs   r   r   r#   )
r7   r0   r   r8   r   rt   search_return_query_vectorr   rK   r   
r9   rr   rk   fetch_klambda_multr   ra   r   r~   r[   s
             r%   rp   z,ZepVectorStore.max_marginal_relevance_search  s    : N  00T__??66u=L-d&&-- &!!& G %PD$4$4$O$O%!!&% %!G\ PWW!aii!**EWWWs   !(Cc           	       K   | j                   st        d      | j                   j                  sR| j                  rF| j                  j	                  |      } | j                   j
                  d|||d|d| d{   }n- | j                   j                  |f||d|d| d{   \  }}|D 	cg c]#  }	t        |	j                  |	j                        % c}	S 7 a7 8c c}	w w):Return docs selected using the maximal marginal relevance.r^   rl   r   Nr   r   r#   )
r7   r0   r   r8   r   rx   asearch_return_query_vectorr   rK   r   r   s
             r%   rw   z-ZepVectorStore.amax_marginal_relevance_search  s      N  00T__??66u=L4D,,44 &!!&  G +W$*:*:*V*V+!!&+ + %!G\ PWW!aii!**EWW%% Xs6   A:C'<C=*C''C (C'3(C"C' C'"C'c           	         | j                   st        d       | j                   j                  d|||d|d|}|D cg c]#  }t        |j                  |j
                        % c}S c c}w )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.
        r^   rl   r   r   r#   r   	r9   r+   rk   r   r   r   ra   r~   r[   s	            r%   'max_marginal_relevance_search_by_vectorz6ZepVectorStore.max_marginal_relevance_search_by_vector!  s|    8 N  *$"")) 
"
 
 PWW!aii!**EWWWs   (A)c           	        K   | j                   st        d       | j                   j                  d|||d|d| d{   }|D cg c]#  }t        |j                  |j
                        % c}S 7 3c c}w w)r   r^   rl   r   Nr   r#   )r7   r0   rx   r   rK   r   r   s	            r%   (amax_marginal_relevance_search_by_vectorz7ZepVectorStore.amax_marginal_relevance_search_by_vectorM  s      N  1((00 
"
 
 
 PWW!aii!**EWW
 Xs"   =A:A3 A:(A50A:5A:c                D     | |||||      }	|	j                  ||       |	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(   )rc   )
clsrU   r+   rV   r4   r:   r)   r*   ra   vecstores
             r%   
from_textszZepVectorStore.from_textsg  s5    @ 
 	5),r$   c                    |t        |      dk(  rt        d      | j                  t        d      |D ]  }| j                  j                  |        y)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.)rR   r0   r7   delete_document)r9   idsra   us       r%   deletezZepVectorStore.delete  sZ     ;#c(a-;<<#;<< 	0A,,Q/	0r$   )r4   r   r:   r   r)   r   r*   Optional[CollectionConfig]r+   Optional[Embeddings]returnNone)r   r   )r   r   )NN)rU   Iterable[str]rV   zOptional[List[Dict[Any, Any]]]rW   Optional[List[str]]r   zList[ZepDocument])
rU   r   rV   zOptional[List[Dict[str, Any]]]rW   r   ra   r   r   	List[str])N   )rr   r   rs   r   r   r   rk   r   ra   r   r   List[Document])   N)
rr   r   rk   r   r   r   ra   r   r   r   )
rr   r   rk   r   r   r   ra   r   r   zList[Tuple[Document, float]])
r+   List[float]rk   r   r   r   ra   r   r   r   )r      g      ?N)rr   r   rk   r   r   r   r   floatr   r   ra   r   r   r   )r+   r   rk   r   r   r   r   r   r   r   ra   r   r   r   )NN r   NN)rU   r   r+   r   rV   zOptional[List[dict]]r4   r   r:   r   r)   r   r*   r   ra   r   r   r'   )N)r   r   ra   r   r   r   )r   r   r    r!   r/   propertyr=   r6   rD   r\   rc   rf   rt   rx   ro   r   r|   r   rv   r   r   rp   rw   r   r   classmethodr   r   __classcell__)r;   s   @r%   r'   r'   ,   se   , "&-1*.$$ $
 $ +$ ($ 
$F     59,0	(( 2( *	(
 
(Z 59,0	 2 *	
  
> 59,0	 2 *	
  
, .2  +	
   
2 .2  +	
   
4 -1	++ + +	+
 + 
+" -1	

 
 +	

 
 
&
  -1	2
2
 2
 +	2

 2
 
&2
n -1	!
!
 !
 +	!

 !
 
&!
L -1	++ + +	+
 + 
+$ -1	 
 
  
 +	 

  
 
 
J -1	

 
 +	

 
 

8  -16X6X 6X 	6X
 6X +6X 6X 
6Xv  -1$X$X $X 	$X
 $X +$X $X 
$XR  -1*X*X *X 	*X
 *X +*X *X 
*X^  -1XX X 	X
 X +X X 
X4  +/*.!!%-1'' (' (	'
 ' ' ' +' ' 
' 'R0 0r$   r'   )
__future__r   loggingrN   dataclassesr   r   typingr   r   r   r	   r
   r   r   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.vectorstoresr   rM   rX   r   	getLoggerrB   r   r'   r#   r$   r%   <module>r      se    "   ) L L L - 0 3;6 
			   .z	0[ z	0r$   