o
    ZhZ                     @  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rHd 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!   [/var/www/html/lang_env/lib/python3.10/site-packages/langchain_community/vectorstores/zep.pyr      s   
 r   c                      s  e Zd ZdZdddddZ fddZed[ddZd\ddZd\ddZ		d]d^dd Z			d]d_d%d&Z
		d]d_d'd(Z		)d`dad1d2Z		)d`dad3d4Z	5	dbdcd6d7Z	5	dbddd9d:Z	5	dbddd;d<Z	5	dbddd=d>Z	5	dbdcd?d@Z	5	dbdedBdCZ	5	dbdedDdEZ	5	F	G	dfdgdKdLZ	5	F	G	dfdgdMdNZ	5	F	G	dfdhdOdPZ	5	F	G	dfdhdQdRZe			S	S		didjdUdVZdkdldXdYZ  ZS )m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                  s   t    |stdzddlm} W n ty   tdw |||d| _|| _|r5|j| jkr5| 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"   r0   >   s&   
	

zZepVectorStore.__init__c                 C  s   | j S )z/Access the query embedding object if available.)r8   )r9   r!   r!   r"   
embeddingsa   s   zZepVectorStore.embeddingsr   c                 C  sT   ddl m} z| jj| j}W |S  |y)   td| j d |  }Y |S w )z;
        Load the collection from the Zep backend.
        r   )NotFoundErrorzCollection z$ not found. Creating new collection.)	r2   r=   r4   documentZget_collectionr(   loggerinfo_create_collection)r9   r=   
collectionr!   r!   r"   r6   f   s   
zZepVectorStore._load_collectionc                 C  s,   | 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.Nr!   )r5   r1   r4   r>   Zadd_collectionr   )r9   rB   r!   r!   r"   rA   v   s   z!ZepVectorStore._create_collectiontextsIterable[str]	metadatasOptional[List[Dict[Any, Any]]]document_idsOptional[List[str]]List[ZepDocument]c           	   	   C  s   ddl m} d }| jr| jjr| jd urtjddd n,| jd urG| jt|}| jrF| jj	t
|d krFtd| jj	 dt
|d  n	 g }t|D ]!\}}||||r\|| nd |rc|| nd |rj|| nd d qN|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   r7   r   r8   warningswarnZembed_documentslistr   lenr1   	enumerateappend)	r9   rC   rE   rG   ZepDocumentr<   	documentsidr!   r!   r"   _generate_documents_to_add   sD   


z)ZepVectorStore._generate_documents_to_addOptional[List[Dict[str, Any]]]kwargsr   	List[str]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)r7   r1   rX   Zadd_documentsr9   rC   rE   rG   rZ   rU   Zuuidsr!   r!   r"   	add_texts   s   zZepVectorStore.add_textsc                   s4   | j std| |||}| j |I dH }|S )zARun more texts through the embeddings and add to the vectorstore.r\   N)r7   r1   rX   Zaadd_documentsr]   r!   r!   r"   
aadd_texts   s   zZepVectorStore.aadd_texts   querysearch_typer   r   kr   List[Document]c                 K  sP   |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rc   r   mmrsearch_type of ? not allowed. Expected search_type to be 'similarity' or 'mmr'.)similarity_searchmax_marginal_relevance_searchr1   r9   ra   rb   r   rc   rZ   r!   r!   r"   search   s   	
zZepVectorStore.searchc                   s^   |dkr| j |f||d|I dH S |dkr'| j|f||d|I dH S td| d)re   rf   rg   Nrh   ri   rj   )asimilarity_searchamax_marginal_relevance_searchr1   rm   r!   r!   r"   asearch   s(   	
zZepVectorStore.asearch   c                 K  s&   | j |f||d|}dd |D S )"Return docs most similar to query.rg   c                 S     g | ]\}}|qS r!   r!   .0doc_r!   r!   r"   
<listcomp>      z4ZepVectorStore.similarity_search.<locals>.<listcomp>(_similarity_search_with_relevance_scoresr9   ra   rc   r   rZ   resultsr!   r!   r"   rk     s   	z ZepVectorStore.similarity_searchList[Tuple[Document, float]]c                 K  s   | j |f||d|S )z$Run similarity search with distance.rg   r{   )r9   ra   rc   r   rZ   r!   r!   r"   similarity_search_with_score  s   	z+ZepVectorStore.similarity_search_with_scorec                 K  sl   | j std| j js"| jr"| j|}| j jd|||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)
        r\   r'   limitr   r   r   c                 S  &   g | ]}t |j|jd |jpdfqS Zpage_contentr   g        r   rL   r   Zscorerv   rw   r!   r!   r"   ry   K      zKZepVectorStore._similarity_search_with_relevance_scores.<locals>.<listcomp>Nr!   )r7   r1   r   r8   embed_queryrn   r9   ra   rc   r   rZ   query_vectorr~   r!   r!   r"   r|   "  s*   z7ZepVectorStore._similarity_search_with_relevance_scoresc                   sz   | j std| j js&| jr&| j|}| j jd|||d|I dH }n| j j|f||d|I dH }dd |D S )rs   r\   r   Nr   c                 S  r   r   r   r   r!   r!   r"   ry   n  r   zKZepVectorStore.asimilarity_search_with_relevance_scores.<locals>.<listcomp>r!   )r7   r1   r   r8   r   rq   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 )rs   r   Nc                 S  rt   r!   r!   ru   r!   r!   r"   ry     rz   z5ZepVectorStore.asimilarity_search.<locals>.<listcomp>)r   r}   r!   r!   r"   ro   y  s   	z!ZepVectorStore.asimilarity_searchList[float]c                 K  s6   | j std| j jd|||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.
        r\   r   c                 S     g | ]
}t |j|jd qS r   r   rL   r   r   r!   r!   r"   ry         z>ZepVectorStore.similarity_search_by_vector.<locals>.<listcomp>Nr!   r7   r1   rn   r9   r'   rc   r   rZ   r~   r!   r!   r"   similarity_search_by_vector  s   z*ZepVectorStore.similarity_search_by_vectorc                   s8   | j std| j jd|||d|}dd |D S )z-Return docs most similar to embedding vector.r\   r   c                 S  r   r   r   r   r!   r!   r"   ry     r   z?ZepVectorStore.asimilarity_search_by_vector.<locals>.<listcomp>Nr!   r   r   r!   r!   r"   asimilarity_search_by_vector  s   z+ZepVectorStore.asimilarity_search_by_vector         ?fetch_klambda_multfloatc           	      K  sx   | j std| j js$| jr$| j|}| j jd|||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.
        r\   rh   r'   r   r   rb   
mmr_lambdar   r   rb   r   c                 S  r   r   r   rv   rW   r!   r!   r"   ry         z@ZepVectorStore.max_marginal_relevance_search.<locals>.<listcomp>Nr!   )r7   r1   r   r8   r   rn   Zsearch_return_query_vector	r9   ra   rc   r   r   r   rZ   r   r~   r!   r!   r"   rl     s4   	
	z,ZepVectorStore.max_marginal_relevance_searchc           	        s   | j std| j js(| jr(| j|}| j jd|||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.r\   rh   r   Nr   c                 S  r   r   r   r   r!   r!   r"   ry     r   zAZepVectorStore.amax_marginal_relevance_search.<locals>.<listcomp>r!   )r7   r1   r   r8   r   rq   Zasearch_return_query_vectorr   r!   r!   r"   rp     s6   		z-ZepVectorStore.amax_marginal_relevance_searchc                 K  s:   | j std| j jd|||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.
        r\   rh   r   c                 S  r   r   r   r   r!   r!   r"   ry   K  r   zJZepVectorStore.max_marginal_relevance_search_by_vector.<locals>.<listcomp>Nr!   r   r9   r'   rc   r   r   r   rZ   r~   r!   r!   r"   'max_marginal_relevance_search_by_vector!  s   	z6ZepVectorStore.max_marginal_relevance_search_by_vectorc                   sB   | j std| j jd|||d|d|I dH }dd |D S )r   r\   rh   r   Nc                 S  r   r   r   r   r!   r!   r"   ry   e  r   zKZepVectorStore.amax_marginal_relevance_search_by_vector.<locals>.<listcomp>r!   )r7   r1   rq   r   r!   r!   r"   (amax_marginal_relevance_search_by_vectorM  s   
	z7ZepVectorStore.amax_marginal_relevance_search_by_vector Optional[List[dict]]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$   )r^   )
clsrC   r'   rE   r(   r)   r%   r&   rZ   Zvecstorer!   r!   r"   
from_textsg  s    zZepVectorStore.from_textsidsc                 K  sH   |du s
t |dkrtd| jdu rtd|D ]}| j| q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.)rQ   r1   r7   Zdelete_document)r9   r   rZ   ur!   r!   r"   delete  s   
zZepVectorStore.delete)r(   r   r)   r   r%   r   r&   r*   r'   r+   r,   r-   )r,   r+   )r,   r   )NN)rC   rD   rE   rF   rG   rH   r,   rI   )
rC   rD   rE   rY   rG   rH   rZ   r   r,   r[   )Nr`   )ra   r   rb   r   r   r   rc   r   rZ   r   r,   rd   )rr   N)
ra   r   rc   r   r   r   rZ   r   r,   rd   )
ra   r   rc   r   r   r   rZ   r   r,   r   )
r'   r   rc   r   r   r   rZ   r   r,   rd   )rr   r   r   N)ra   r   rc   r   r   r   r   r   r   r   rZ   r   r,   rd   )r'   r   rc   r   r   r   r   r   r   r   rZ   r   r,   rd   )NNr   r   NN)rC   r[   r'   r+   rE   r   r(   r   r)   r   r%   r   r&   r*   rZ   r   r,   r#   )N)r   rH   rZ   r   r,   r-   )r   r   r   r   r0   propertyr<   r6   rA   rX   r^   r_   rn   rq   rk   r   r|   r   ro   r   r   rl   rp   r   r   classmethodr   r   __classcell__r!   r!   r:   r"   r#   ,   s    #

-7&%;)/)r#   )
__future__r   loggingrN   dataclassesr   r   typingr   r   r   r   r	   r
   r   Zlangchain_core.documentsr   Zlangchain_core.embeddingsr   Zlangchain_core.vectorstoresr   rM   rT   r   	getLoggerr?   r   r#   r!   r!   r!   r"   <module>   s    $