
    Ng7                        d Z ddlmZ ddlZddl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 ddlmZ erddlmZ  ej                    Z G d	 d
e          ZdS )z'Wrapper around Epsilla vector database.    )annotationsN)TYPE_CHECKINGAnyIterableListOptionalTypeDocument)
Embeddings)VectorStore)vectordbc                      e Zd ZU dZdZded<   dZded<   dZded<   eefd8dZe	d9d            Z
d:dZd;d:dZ	 d<d=dZ	 d>d?d"Z	 	 	 d@dAd+Z	 dBdCd1Zeddeeed#fdDd5            Zedeeed#fdEd7            ZdS )FEpsillaar  
    Wrapper around Epsilla vector database.

    As a prerequisite, you need to install ``pyepsilla`` package
    and have a running Epsilla vector database (for example, through our docker image)
    See the following documentation for how to run an Epsilla vector database:
    https://epsilla-inc.gitbook.io/epsilladb/quick-start

    Args:
        client (Any): Epsilla client to connect to.
        embeddings (Embeddings): Function used to embed the texts.
        db_path (Optional[str]): The path where the database will be persisted.
                                 Defaults to "/tmp/langchain-epsilla".
        db_name (Optional[str]): Give a name to the loaded database.
                                 Defaults to "langchain_store".
    Example:
        .. code-block:: python

            from langchain_community.vectorstores import Epsilla
            from pyepsilla import vectordb

            client = vectordb.Client()
            embeddings = OpenAIEmbeddings()
            db_path = "/tmp/vectorstore"
            db_name = "langchain_store"
            epsilla = Epsilla(client, embeddings, db_path, db_name)
    langchain_storestr_LANGCHAIN_DEFAULT_DB_NAMEz/tmp/langchain-epsilla_LANGCHAIN_DEFAULT_DB_PATHlangchain_collection_LANGCHAIN_DEFAULT_TABLE_NAMEclientr   
embeddingsr   db_pathOptional[str]db_namec                   	 ddl }n"# t          $ r}t          d          |d}~ww xY wt          ||j        j        |j        j        j        f          st          dt          |                     || _
        || _        || _        t          j        | _        | j
                            ||           | j
                            |           dS )z%Initialize with necessary components.r   NziCould not import pyepsilla python package. Please install pyepsilla package with `pip install pyepsilla`.zbclient should be an instance of pyepsilla.vectordb.Client or pyepsilla.cloud.client.Vectordb, got )r   r   r   )	pyepsillaImportError
isinstancer   Clientcloudr   Vectordb	TypeErrortype_client_db_name_embeddingsr   r   _collection_nameload_dbuse_db)selfr   r   r   r   r   es          d/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/vectorstores/epsilla.py__init__zEpsilla.__init__4   s
   	 	 	 	Q  	 Y'.	0F0OP
 
 	 G8<VG G  
 )/% ' EWg>>>G,,,,,s    
&!&returnOptional[Embeddings]c                    | j         S N)r(   )r,   s    r.   r   zEpsilla.embeddingsS   s        collection_nameNonec                    || _         dS )z~
        Set default collection to use.

        Args:
            collection_name (str): The name of the collection.
        N)r)   r,   r5   s     r.   use_collectionzEpsilla.use_collectionW   s     !0r4    c                L    |s| j         }| j                            |           dS )z
        Clear data in a collection.

        Args:
            collection_name (Optional[str]): The name of the collection.
                If not provided, the default collection will be used.
        N)r)   r&   
drop_tabler8   s     r.   
clear_datazEpsilla.clear_data`   s0      	4"3O00000r4   Nresponse_fieldsOptional[List[str]]
List[dict]c                   |s| j         }| j                            ||          \  }}|dk    rKt                              d|d                     t          d                    |d                             |d         S )a  Get the collection.

        Args:
            collection_name (Optional[str]): The name of the collection
                to retrieve data from.
                If not provided, the default collection will be used.
            response_fields (Optional[List[str]]): List of field names in the result.
                If not specified, all available fields will be responded.

        Returns:
            A list of the retrieved data.
        )
table_namer>      zFailed to get records: message
Error: {}.result)r)   r&   getloggererror	Exceptionformat)r,   r5   r>   status_coderesponses        r.   rG   zEpsilla.getl   s      	4"3O $ 0 0& !1 !
 !
X #LLH8I3FHHIIIL//0CDDEEE!!r4   rB   list	metadatasOptional[list[dict]]c                F   |st          d          t          |d                   }dddddddd	|d
g}|d |D             }|D ]}|                                D ]\  }}	||v r
t          |	t                    rd}
n[t          |	t
                    rd}
nCt          |	t                    rd}
n+t          |	t                    rd}
nt          d| d          |                    ||
d           |                    |           | j	        
                    ||          \  }}|dk    rt|dk    r t                              d| d           d S t                              d| d|d                     t          d                    |d                             d S )NzEmbeddings list is empty.r   idINT)namedataTypetextSTRINGr   VECTOR_FLOAT)rT   rU   
dimensionsc                    g | ]
}|d          S )rT    ).0fields     r.   
<listcomp>z.Epsilla._create_collection.<locals>.<listcomp>   s    ===U5====r4   FLOATBOOLzUnsupported data type for .)table_fieldsrC   i  z#Continuing with the existing table zFailed to create collection : rD   rE   )
ValueErrorlenitemsr    r   intfloatboolappendr&   create_tablerH   inforI   rJ   rK   )r,   rB   r   rO   dimfieldsfield_namesmetadatakeyvalued_typerL   rM   s                r.   _create_collectionzEpsilla._create_collection   s      	:8999*Q-  u--22!~SQQ

  ==f===K% , ,"*.."2"2 , ,JCk)) !%-- 	N!)#E3// N!&#E511 N!(#E400 N!'()Lc)L)L)LMMMMM3F"C"CDDD&&s++++," !% 9 9V !: !
 !
X #c!!O*OOOPPPPPV:VV)ATVV     3 3HY4G H HIII r4   FtextsIterable[str]Optional[List[dict]]drop_oldOptional[bool]kwargs	List[str]c                d    |s j         }n| _         |r j                            |           t          |          }	  j                            |          }n# t          $ r  fd|D             }Y nw xY wt          |          dk    rt          	                    d           g S  
                    |||           d |D             }g }t          |          D ]U\  }	}
|
||	         ||	         d}|'||	                                         }|D ]
\  }}|||<   |                    |           V j                            ||	          \  }}|d
k    rNt                              d| d|d                     t!          d                    |d                             d |D             S )a  
        Embed texts and add them to the database.

        Args:
            texts (Iterable[str]): The texts to embed.
            metadatas (Optional[List[dict]]): Metadata dicts
                        attached to each of the texts. Defaults to None.
            collection_name (Optional[str]): Which collection to use.
                        Defaults to "langchain_collection".
                        If provided, default collection name will be set as well.
            drop_old (Optional[bool]): Whether to drop the previous collection
                        and create a new one. Defaults to False.

        Returns:
            List of ids of the added texts.
        r   c                D    g | ]}j                             |          S r[   )r(   embed_query)r\   xr,   s     r.   r^   z%Epsilla.add_texts.<locals>.<listcomp>   s*    IIIa$*66q99IIIr4   r   zNothing to insert, skipping.)rB   r   rO   c                N    g | ]"}t          t          j                              #S r[   )hashuuiduuid4)r\   _s     r.   r^   z%Epsilla.add_texts.<locals>.<listcomp>   s&    111atDJLL!!111r4   rR   rV   r   N)rB   recordsrC   zFailed to add records to rc   rD   rE   c                ,    g | ]}t          |          S r[   )r   )r\   rR   s     r.   r^   z%Epsilla.add_texts.<locals>.<listcomp>   s    &&&BB&&&r4   )r)   r&   drop_dbrN   r(   embed_documentsNotImplementedErrorre   rH   debugrt   	enumeraterf   rj   insertrI   rJ   rK   )r,   ru   rO   r5   rx   rz   r   idsr   indexrR   recordrp   rq   rr   rL   rM   s   `                r.   	add_textszEpsilla.add_texts   s.   0  	4"3OO$3D! 	:L   999U	J)99%@@JJ" 	J 	J 	JIIII5IIIJJJ	J z??aLL7888I&: 	  	
 	
 	
 215111"3 
	# 
	#IE2e(/ F
 $$U+1133"* ( (JC"'F3KKNN6"""" $ 3 3& !4 !
 !
X #LLTOTTx	?RTT   L//0CDDEEE&&#&&&&s    A A65A6   querykrg   List[Document]c                   |s| j         }| j                            |          }| j                            |d||          \  }}|dk    rLt
                              d|d          d           t          d                    |d                             g dt          t          fd	|d
                             S )a  
        Return the documents that are semantically most relevant to the query.

        Args:
            query (str): String to query the vectorstore with.
            k (Optional[int]): Number of documents to return. Defaults to 4.
            collection_name (Optional[str]): Collection to use.
                Defaults to "langchain_store" or the one provided before.
        Returns:
            List of documents that are semantically most relevant to the query
        r   )rB   query_fieldquery_vectorlimitrC   zSearch failed: rD   ra   rE   r   c                N     t           d          fd D                       S )NrV   c                *    i | ]}|v||         S r[   r[   )r\   rq   exclude_keysitems     r.   
<dictcomp>z?Epsilla.similarity_search.<locals>.<lambda>.<locals>.<dictcomp>  s0       +.#\:Q:QT#Y:Q:Q:Qr4   )page_contentrp   r
   )r   r   s   `r.   <lambda>z+Epsilla.similarity_search.<locals>.<lambda>  sI    X!%f    26     r4   rF   )r)   r(   r~   r&   r   rH   rI   rJ   rK   rN   map)	r,   r   r   r5   rz   r   rL   rM   r   s	           @r.   similarity_searchzEpsilla.similarity_search   s      	4"3O'33E:: $ 2 2&$%	 !3 !
 !
X #LLA8I+>AAABBBL//0CDDEEE333    " 

 

 
	
r4   clsType[Epsilla]	embeddingc	                P    t          ||||          }
 |
j        |f|||d|	 |
S )a  Create an Epsilla vectorstore from raw documents.

        Args:
            texts (List[str]): List of text data to be inserted.
            embeddings (Embeddings): Embedding function.
            client (pyepsilla.vectordb.Client): Epsilla client to connect to.
            metadatas (Optional[List[dict]]): Metadata for each text.
                    Defaults to None.
            db_path (Optional[str]): The path where the database will be persisted.
                    Defaults to "/tmp/langchain-epsilla".
            db_name (Optional[str]): Give a name to the loaded database.
                    Defaults to "langchain_store".
            collection_name (Optional[str]): Which collection to use.
                    Defaults to "langchain_collection".
                    If provided, default collection name will be set as well.
            drop_old (Optional[bool]): Whether to drop the previous collection
                    and create a new one. Defaults to False.

        Returns:
            Epsilla: Epsilla vector store.
        )r   r   )rO   r5   rx   )r   r   )r   ru   r   rO   r   r   r   r5   rx   rz   instances              r.   
from_textszEpsilla.from_texts  sY    D 69gwOOO	
+		
 	

 	
 	
 	
 r4   	documentsc           
     ^    d |D             }	d |D             }
 | j         |	|f|
|||||d|S )a"  Create an Epsilla vectorstore from a list of documents.

        Args:
            texts (List[str]): List of text data to be inserted.
            embeddings (Embeddings): Embedding function.
            client (pyepsilla.vectordb.Client): Epsilla client to connect to.
            metadatas (Optional[List[dict]]): Metadata for each text.
                    Defaults to None.
            db_path (Optional[str]): The path where the database will be persisted.
                    Defaults to "/tmp/langchain-epsilla".
            db_name (Optional[str]): Give a name to the loaded database.
                    Defaults to "langchain_store".
            collection_name (Optional[str]): Which collection to use.
                    Defaults to "langchain_collection".
                    If provided, default collection name will be set as well.
            drop_old (Optional[bool]): Whether to drop the previous collection
                    and create a new one. Defaults to False.

        Returns:
            Epsilla: Epsilla vector store.
        c                    g | ]	}|j         
S r[   )r   r\   docs     r.   r^   z*Epsilla.from_documents.<locals>.<listcomp>m  s    777c!777r4   c                    g | ]	}|j         
S r[   )rp   r   s     r.   r^   z*Epsilla.from_documents.<locals>.<listcomp>n  s    777cS\777r4   )rO   r   r   r   r5   rx   )r   )r   r   r   r   r   r   r5   rx   rz   ru   rO   s              r.   from_documentszEpsilla.from_documentsL  so    B 87Y77777Y777	s~

  +

 

 

 

 
	
r4   )r   r   r   r   r   r   r   r   )r0   r1   )r5   r   r0   r6   )r:   )r:   N)r5   r   r>   r?   r0   r@   r3   )rB   r   r   rN   rO   rP   r0   r6   )Nr:   F)ru   rv   rO   rw   r5   r   rx   ry   rz   r   r0   r{   )r   r:   )
r   r   r   rg   r5   r   rz   r   r0   r   )r   r   ru   r{   r   r   rO   rw   r   r   r   r   r   r   r5   r   rx   ry   rz   r   r0   r   )r   r   r   r   r   r   r   r   r   r   r   r   r5   r   rx   ry   rz   r   r0   r   )__name__
__module____qualname____doc__r   __annotations__r   r   r/   propertyr   r9   r=   rG   rt   r   r   classmethodr   r   r[   r4   r.   r   r      s         8 '87777&>>>>>)?!???? "<!;- - - - ->       X 0 0 0 0
1 
1 
1 
1 
1 QU" " " " "4 TX*J *J *J *J *J^ +/)+#(D' D' D' D' D'N >@&
 &
 &
 &
 &
P 
 +/!;!;)F#(* * * * [*X 
 !;!;)F#(-
 -
 -
 -
 [-
 -
 -
r4   r   )r   
__future__r   loggingr   typingr   r   r   r   r   r	   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.vectorstoresr   r   r   	getLoggerrH   r   r[   r4   r.   <module>r      s    - - " " " " " "   E E E E E E E E E E E E E E E E - - - - - - 0 0 0 0 0 0 3 3 3 3 3 3 #""""""				g
 g
 g
 g
 g
k g
 g
 g
 g
 g
r4   