a
    bgZ                     @  s   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rd dlmZ d dlmZ e ZeG d	d
 d
ZG dd deZdS )    )annotationsN)asdict	dataclass)TYPE_CHECKINGAnyDictIterableListOptionalTupleDocument)
Embeddings)VectorStore)DocumentCollectionc                   @  s:   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__ r!   r!   r/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/vectorstores/zep.pyr      s   
r   c                      s2  e Zd ZdZddddddddddd	 fd
dZeddddZddddZddddZdTdddddddZ	dUdddddddd Z
dVddddddd!d"ZdWddd$d%dd&d'd(d)ZdXddd$d%dd&d'd*d+ZdYdd%d$dd&d-d.d/ZdZdd%d$dd0d-d1d2Zd[dd%d$dd0d-d3d4Zd\dd%d$dd0d-d5d6Zd]dd%d$dd&d-d7d8Zd^d9d%d$dd&d:d;d<Zd_d9d%d$dd&d:d=d>Zd`dd%d%dAd$dd&dBdCdDZdadd%d%dAd$dd&dBdEdFZdbd9d%d%dAd$dd&dGdHdIZdcd9d%d%dAd$dd&dGdJdKZedddddMdddddd dN	dOdPZdeddddQdRdSZ  ZS )f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	embeddingr   r   zOptional[CollectionConfig]zOptional[Embeddings]None)collection_nameapi_urlr%   r&   r'   returnc                  s   t    |stdzddlm} W n ty@   tdY n0 |||d| _|| _|rn|j| jkrn| 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_pythonr,   ImportError_clientr)   r   _collection_config_load_collection_collection
_embedding)selfr)   r*   r%   r&   r'   r,   	__class__r!   r"   r.   >   s$    	


zZepVectorStore.__init__)r+   c                 C  s   | j S )z/Access the query embedding object if available.)r6   )r7   r!   r!   r"   
embeddingsa   s    zZepVectorStore.embeddingsr   c                 C  sT   ddl m} z| jj| j}W n. |yN   td| j d |  }Y n0 |S )z;
        Load the collection from the Zep backend.
        r   )NotFoundErrorzCollection z$ not found. Creating new collection.)	r0   r;   r2   documentZget_collectionr)   loggerinfo_create_collection)r7   r;   
collectionr!   r!   r"   r4   f   s    zZepVectorStore._load_collectionc                 C  s,   | j std| jjjf i t| j }|S )z=
        Create a new collection in the Zep backend.
        zCCollection config must be specified when creating a new collection.)r3   r/   r2   r<   Zadd_collectionr   )r7   r@   r!   r!   r"   r?   v   s    z!ZepVectorStore._create_collectionzIterable[str]zOptional[List[Dict[Any, Any]]]zOptional[List[str]]zList[ZepDocument])texts	metadatasdocument_idsr+   c           	   	   C  s   ddl m} d }| jr8| jjr8| jd urtjddd nV| jd ur| jt|}| jr| jj	t
|d krtd| jj	 dt
|d  n g }t|D ]B\}}||||r|| nd |r|| nd |r|| nd d q|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   Zdocument_idr'   )zep_python.documentr   r5   r   r6   warningswarnZembed_documentslistr   lenr/   	enumerateappend)	r7   rA   rB   rC   ZepDocumentr:   	documentsidr!   r!   r"   _generate_documents_to_add   s>    


	z)ZepVectorStore._generate_documents_to_addzOptional[List[Dict[str, Any]]]r   z	List[str])rA   rB   rC   kwargsr+   c                 K  s,   | 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)r5   r/   rR   Zadd_documentsr7   rA   rB   rC   rS   rO   Zuuidsr!   r!   r"   	add_texts   s    zZepVectorStore.add_textsc                   s2   | j std| |||}| j |I dH }|S )zARun more texts through the embeddings and add to the vectorstore.rT   N)r5   r/   rR   Zaadd_documentsrU   r!   r!   r"   
aadd_texts   s    zZepVectorStore.aadd_texts   r   r   zList[Document])querysearch_typer   krS   r+   c                 K  sT   |dkr | j |f||d|S |dkr@| j|f||d|S td| ddS )>Return docs most similar to query using specified search type.
similarityr[   r   mmrsearch_type of ? not allowed. Expected search_type to be 'similarity' or 'mmr'.N)similarity_searchmax_marginal_relevance_searchr/   r7   rY   rZ   r   r[   rS   r!   r!   r"   search   s    	
zZepVectorStore.searchc                   s`   |dkr&| j |f||d|I dH S |dkrL| j|f||d|I dH S td| ddS )r\   r]   r^   Nr_   r`   ra   )asimilarity_searchamax_marginal_relevance_searchr/   rd   r!   r!   r"   asearch   s&    	
zZepVectorStore.asearch   )rY   r[   r   rS   r+   c                 K  s&   | j |f||d|}dd |D S )"Return docs most similar to query.r^   c                 S  s   g | ]\}}|qS r!   r!   .0doc_r!   r!   r"   
<listcomp>      z4ZepVectorStore.similarity_search.<locals>.<listcomp>(_similarity_search_with_relevance_scoresr7   rY   r[   r   rS   resultsr!   r!   r"   rb     s    	z ZepVectorStore.similarity_searchzList[Tuple[Document, float]]c                 K  s   | j |f||d|S )z$Run similarity search with distance.r^   rq   )r7   rY   r[   r   rS   r!   r!   r"   similarity_search_with_score  s    	z+ZepVectorStore.similarity_search_with_scorec                 K  sl   | j std| j jsD| jrD| j|}| j jf |||d|}n| j j|f||d|}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)
        rT   r'   limitr   rw   r   c                 S  s&   g | ]}t |j|jd |jpdfqS Zpage_contentr   g        r   rF   r   Zscorerl   rm   r!   r!   r"   ro   K  s   zKZepVectorStore._similarity_search_with_relevance_scores.<locals>.<listcomp>)r5   r/   r   r6   embed_queryre   r7   rY   r[   r   rS   query_vectorrt   r!   r!   r"   rr   "  s*    z7ZepVectorStore._similarity_search_with_relevance_scoresc                   sx   | j std| j jsJ| jrJ| j|}| j jf |||d|I dH }n | j j|f||d|I dH }dd |D S )rj   rT   rv   Nrx   c                 S  s&   g | ]}t |j|jd |jpdfqS ry   r{   r|   r!   r!   r"   ro   n  s   zKZepVectorStore.asimilarity_search_with_relevance_scores.<locals>.<listcomp>)r5   r/   r   r6   r}   rh   r~   r!   r!   r"   (asimilarity_search_with_relevance_scoresV  s*    	z7ZepVectorStore.asimilarity_search_with_relevance_scoresc                   s,   | j ||fd|i|I dH }dd |D S )rj   r   Nc                 S  s   g | ]\}}|qS r!   r!   rk   r!   r!   r"   ro     rp   z5ZepVectorStore.asimilarity_search.<locals>.<listcomp>)r   rs   r!   r!   r"   rf   y  s    	z!ZepVectorStore.asimilarity_searchzList[float])r'   r[   r   rS   r+   c                 K  s6   | j std| j jf |||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.
        rT   rv   c                 S  s   g | ]}t |j|jd qS rz   r   rF   r   r|   r!   r!   r"   ro     s
   z>ZepVectorStore.similarity_search_by_vector.<locals>.<listcomp>r5   r/   re   r7   r'   r[   r   rS   rt   r!   r!   r"   similarity_search_by_vector  s    z*ZepVectorStore.similarity_search_by_vectorc                   s6   | j std| j jf |||d|}dd |D S )z-Return docs most similar to embedding vector.rT   rv   c                 S  s   g | ]}t |j|jd qS r   r   r|   r!   r!   r"   ro     s
   z?ZepVectorStore.asimilarity_search_by_vector.<locals>.<listcomp>r   r   r!   r!   r"   asimilarity_search_by_vector  s    z+ZepVectorStore.asimilarity_search_by_vector         ?float)rY   r[   fetch_klambda_multr   rS   r+   c           	      K  sx   | j std| j jsH| jrH| j|}| j jf |||d|d|}n"| j j|f||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:
            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.
        rT   r_   r'   rw   r   rZ   
mmr_lambdarw   r   rZ   r   c                 S  s   g | ]}t |j|jd qS r   r   rl   rQ   r!   r!   r"   ro     rp   z@ZepVectorStore.max_marginal_relevance_search.<locals>.<listcomp>)r5   r/   r   r6   r}   re   Zsearch_return_query_vector	r7   rY   r[   r   r   r   rS   r   rt   r!   r!   r"   rc     s4    	
	z,ZepVectorStore.max_marginal_relevance_searchc           	        s   | j std| j jsN| jrN| j|}| j jf |||d|d|I dH }n(| j j|f||d|d|I dH \}}dd |D S ):Return docs selected using the maximal marginal relevance.rT   r_   r   Nr   c                 S  s   g | ]}t |j|jd qS r   r   r   r!   r!   r"   ro     rp   zAZepVectorStore.amax_marginal_relevance_search.<locals>.<listcomp>)r5   r/   r   r6   r}   rh   Zasearch_return_query_vectorr   r!   r!   r"   rg     s4    		z-ZepVectorStore.amax_marginal_relevance_search)r'   r[   r   r   r   rS   r+   c                 K  s:   | j std| j jf |||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.
        rT   r_   r   c                 S  s   g | ]}t |j|jd qS r   r   r   r!   r!   r"   ro   K  rp   zJZepVectorStore.max_marginal_relevance_search_by_vector.<locals>.<listcomp>r   r7   r'   r[   r   r   r   rS   rt   r!   r!   r"   'max_marginal_relevance_search_by_vector!  s    	z6ZepVectorStore.max_marginal_relevance_search_by_vectorc                   s@   | j std| j jf |||d|d|I dH }dd |D S )r   rT   r_   r   Nc                 S  s   g | ]}t |j|jd qS r   r   r   r!   r!   r"   ro   e  rp   zKZepVectorStore.amax_marginal_relevance_search_by_vector.<locals>.<listcomp>)r5   r/   rh   r   r!   r!   r"   (amax_marginal_relevance_search_by_vectorM  s    
	z7ZepVectorStore.amax_marginal_relevance_search_by_vector zOptional[List[dict]])	rA   r'   rB   r)   r*   r%   r&   rS   r+   c           
      K  s"   | |||||d}	|	 || |	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$   )rV   )
clsrA   r'   rB   r)   r*   r%   r&   rS   Zvecstorer!   r!   r"   
from_textsg  s     zZepVectorStore.from_texts)idsrS   r+   c                 K  sH   |du st |dkrtd| jdu r.td|D ]}| j| q2d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.)rK   r/   r5   Zdelete_document)r7   r   rS   ur!   r!   r"   delete  s    
zZepVectorStore.delete)NN)NN)NN)NrX   )NrX   )ri   N)ri   N)ri   N)ri   N)ri   N)ri   N)ri   N)ri   r   r   N)ri   r   r   N)ri   r   r   N)ri   r   r   N)NNr   r   NN)N)r   r   r   r   r.   propertyr:   r4   r?   rR   rV   rW   re   rh   rb   ru   rr   r   rf   r   r   rc   rg   r   r   classmethodr   r   __classcell__r!   r!   r8   r"   r#   ,   s    #  -              7  &    %      ;    )    /          ")r#   )
__future__r   loggingrH   dataclassesr   r   typingr   r   r   r   r	   r
   r   Zlangchain_core.documentsr   Zlangchain_core.embeddingsr   Zlangchain_core.vectorstoresr   rG   rN   r   	getLoggerr=   r   r#   r!   r!   r!   r"   <module>   s   $