
    NgJ5                        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
mZ d dlmZ d dlmZ d dlmZ d dlmZ dZd	Z G d
 de          ZdS )    )annotationsN)AnyDictIterableListOptionalTupleTypeDocument)
Embeddings)get_from_dict_or_env)VectorStorei   langchain_pg_embeddingc                  p   e Zd ZdZeeddfdBdZdCdZedDd            Z	e
ddeedfdEd            ZdFd!Z	 	 dGdHd"Z	 	 dIdJd)Z	 	 dIdKd,Z	 	 dIdLd.Z	 	 dIdMd/Ze
deeddfdNd2            Ze
deeddfdOd5            Ze
eedfdPd6            Ze
dQd8            Ze
eeddfdRd;            Ze
dSdA            ZdS )THologresa  `Hologres API` vector store.

    - `connection_string` is a hologres connection string.
    - `embedding_function` any embedding function implementing
        `langchain.embeddings.base.Embeddings` interface.
    - `ndims` is the number of dimensions of the embedding output.
    - `table_name` is the name of the table to store embeddings and data.
        (default: langchain_pg_embedding)
        - NOTE: The table will be created when initializing the store (if not exists)
            So, make sure the user has the right permissions to create tables.
    - `pre_delete_table` if True, will delete the table if it exists.
        (default: False)
        - Useful for testing.
    FNconnection_stringstrembedding_functionr   ndimsint
table_namepre_delete_tableboolloggerOptional[logging.Logger]returnNonec                    || _         || _        || _        || _        || _        |pt          j        t                    | _        | 	                                 d S N)
r   r   r   r   r   logging	getLogger__name__r   __post_init__)selfr   r   r   r   r   r   s          e/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/vectorstores/hologres.py__init__zHologres.__init__    sY     "3
$"4 0; 1( ; ;    c                h    ddl m}  || j        | j        | j        ddi| j                  | _        dS )z'
        Initialize the store.
        r   )HologresVectordocumenttext)r   r   table_schemar   N)hologres_vectorr*   r   r   r   r   storage)r%   r*   s     r&   r$   zHologres.__post_init__1   sP     	322222%~"*$f-!2
 
 
r(   c                    | j         S r    )r   )r%   s    r&   
embeddingszHologres.embeddingsA   s    &&r(   texts	List[str]r1   List[List[float]]	metadatasOptional[List[dict]]idsOptional[List[str]]kwargsr   c	                    |d |D             }|sd |D             }|                      |	          }
 | |
||||          } |j        d||||d|	 |S )Nc                N    g | ]"}t          t          j                              #S  r   uuiduuid4.0_s     r&   
<listcomp>z#Hologres.__from.<locals>.<listcomp>S   &    4443tz||$$444r(   c                    g | ]}i S r<   r<   r@   s     r&   rC   z#Hologres.__from.<locals>.<listcomp>V       ++++++r(   )r   r   r   r   r   )r2   r1   r5   r7   r<   )get_connection_stringadd_embeddings)clsr2   r1   r   r5   r7   r   r   r   r9   r   stores               r&   __fromzHologres.__fromE   s     ;44e444C 	,++U+++I55f==/1!-
 
 
 	 	
J)	
 	
PV	
 	
 	
 r(   Iterable[str]
List[dict]c                    	 d |D             }| j                             ||||           dS # t          $ r%}| j                            |           Y d}~dS d}~ww xY w)a/  Add embeddings to the vectorstore.

        Args:
            texts: Iterable of strings to add to the vectorstore.
            embeddings: List of list of embedding vectors.
            metadatas: List of metadatas associated with the texts.
            kwargs: vectorstore specific parameters
        c                    g | ]}d |iS )r+   r<   rA   ts     r&   rC   z+Hologres.add_embeddings.<locals>.<listcomp>y   s    ;;;ZO;;;r(   N)r/   upsert_vectors	Exceptionr   	exception)r%   r2   r1   r5   r7   r9   schema_datases           r&   rH   zHologres.add_embeddingsh   s     	%;;U;;;LL''
CLQQQQQ 	% 	% 	%K!!!$$$$$$$$$	%s   )- 
AAAc                    |d |D             }| j                             t          |                    }|sd |D             } | j        ||||fi | |S )ar  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.
            kwargs: vectorstore specific parameters

        Returns:
            List of ids from adding the texts into the vectorstore.
        Nc                N    g | ]"}t          t          j                              #S r<   r=   r@   s     r&   rC   z&Hologres.add_texts.<locals>.<listcomp>   rD   r(   c                    g | ]}i S r<   r<   r@   s     r&   rC   z&Hologres.add_texts.<locals>.<listcomp>   rF   r(   )r   embed_documentslistrH   )r%   r2   r5   r7   r9   r1   s         r&   	add_textszHologres.add_texts~   sy    " ;44e444C,<<T%[[II
 	,++U+++IE:y#HHHHH
r(      querykfilterOptional[dict]List[Document]c                h    | j                             |          }|                     |||          S )a^  Run similarity search with Hologres with distance.

        Args:
            query (str): Query text to search for.
            k (int): Number of results to return. Defaults to 4.
            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.

        Returns:
            List of Documents most similar to the query.
        )r,   	embeddingr_   r`   )r   embed_querysimilarity_search_by_vector)r%   r^   r_   r`   r9   re   s         r&   similarity_searchzHologres.similarity_search   sC    " +77U7CC	// 0 
 
 	
r(   re   List[float]c                J    |                      |||          }d |D             S )ak  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.
            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.

        Returns:
            List of Documents most similar to the query vector.
        rd   c                    g | ]\  }}|S r<   r<   )rA   docrB   s      r&   rC   z8Hologres.similarity_search_by_vector.<locals>.<listcomp>   s    222Q222r(   )&similarity_search_with_score_by_vector)r%   re   r_   r`   r9   docs_and_scoress         r&   rg   z$Hologres.similarity_search_by_vector   s<    " EE1V F 
 
 32/2222r(   List[Tuple[Document, float]]c                j    | j                             |          }|                     |||          }|S )ab  Return docs most similar to query.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.

        Returns:
            List of Documents most similar to the query and score for each
        rd   )r   rf   rm   )r%   r^   r_   r`   re   docss         r&   similarity_search_with_scorez%Hologres.similarity_search_with_score   sB      +77>>	::1V ; 
 
 r(   c                \    | j                             ||dg|          }d |D             }|S )Nr+   )r_   select_columnsmetadata_filtersc                X    g | ]'}t          |d          |d                   |d         f(S )r+   metadata)page_contentrw   distancer   )rA   results     r&   rC   zCHologres.similarity_search_with_score_by_vector.<locals>.<listcomp>   sX     	
 	
 	
  !'
!3#J/   z"	
 	
 	
r(   )r/   search)r%   re   r_   r`   resultsrq   s         r&   rm   z/Hologres.similarity_search_with_score_by_vector   sR     )-(;(;J<& )< )
 )
	
 	
 "	
 	
 	
 r(   rI   Type[Hologres]c           	     r    |                     t          |                    }	 | j        ||	|f|||||d|S )aM  
        Return VectorStore initialized from texts and embeddings.
        Hologres connection string is required
        "Either pass it as a parameter
        or set the HOLOGRES_CONNECTION_STRING environment variable.
        Create the connection string by calling
        HologresVector.connection_string_from_db_params
        r5   r7   r   r   r   )rZ   r[   _Hologres__from)
rI   r2   re   r5   r   r   r7   r   r9   r1   s
             r&   
from_textszHologres.from_texts   sa    ( ..tE{{;;
sz

  !-

 

 

 

 
	
r(   text_embeddingsList[Tuple[str, List[float]]]c           	     ^    d |D             }	d |D             }
 | j         |	|
|f|||||d|S )a~  Construct Hologres wrapper from raw documents and pre-
        generated embeddings.

        Return VectorStore initialized from documents and embeddings.
        Hologres connection string is required
        "Either pass it as a parameter
        or set the HOLOGRES_CONNECTION_STRING environment variable.
        Create the connection string by calling
        HologresVector.connection_string_from_db_params

        Example:
            .. code-block:: python

                from langchain_community.vectorstores import Hologres
                from langchain_community.embeddings import OpenAIEmbeddings
                embeddings = OpenAIEmbeddings()
                text_embeddings = embeddings.embed_documents(texts)
                text_embedding_pairs = list(zip(texts, text_embeddings))
                faiss = Hologres.from_embeddings(text_embedding_pairs, embeddings)
        c                    g | ]
}|d          S )r   r<   rP   s     r&   rC   z,Hologres.from_embeddings.<locals>.<listcomp>7  s    ///!1///r(   c                    g | ]
}|d          S )   r<   rP   s     r&   rC   z,Hologres.from_embeddings.<locals>.<listcomp>8  s    444qad444r(   r   )r   )rI   r   re   r5   r   r   r7   r   r9   r2   r1   s              r&   from_embeddingszHologres.from_embeddings  so    @ 0////44O444
sz

  !-

 

 

 

 
	
r(   c                P    |                      |          } | |||||          }|S )z
        Get instance of an existing Hologres store.This method will
        return the instance of the store without inserting any new
        embeddings
        )r   r   r   r   r   )rG   )rI   re   r   r   r   r9   r   rJ   s           r&   from_existing_indexzHologres.from_existing_indexF  sD      55f==/!(-
 
 
 r(   Dict[str, Any]c                L    t          |dd          }|st          d          |S )Nr   HOLOGRES_CONNECTION_STRING)datakeyenv_keyzHologres connection string is requiredEither pass it as a parameteror set the HOLOGRES_CONNECTION_STRING environment variable.Create the connection string by callingHologresVector.connection_string_from_db_params)r   
ValueError)rI   r9   r   s      r&   rG   zHologres.get_connection_stringa  sJ    !5#0"
 "
 "
 ! 	B   ! r(   	documentspre_delete_collectionc                    d |D             }d |D             }	|                      |          }
|
|d<    | j        d||||	|||d|S )aQ  
        Return VectorStore initialized from documents and embeddings.
        Hologres connection string is required
        "Either pass it as a parameter
        or set the HOLOGRES_CONNECTION_STRING environment variable.
        Create the connection string by calling
        HologresVector.connection_string_from_db_params
        c                    g | ]	}|j         
S r<   )rx   rA   ds     r&   rC   z+Hologres.from_documents.<locals>.<listcomp>  s    333A333r(   c                    g | ]	}|j         
S r<   )rw   r   s     r&   rC   z+Hologres.from_documents.<locals>.<listcomp>  s    333AQZ333r(   r   )r2   r   re   r5   r7   r   r   r<   )rG   r   )rI   r   re   r   r   r7   r   r9   r2   r5   r   s              r&   from_documentszHologres.from_documentst  s    ( 4333333333	55f==&7"#s~ 	
"7!	
 	
 	
 	
 		
r(   hostportdatabaseuserpasswordc           
     $    d| d| d| d| d| 
S )z2Return connection string from database parameters.zdbname=z user=z
 password=z host=z port=r<   )rI   r   r   r   r   r   s         r&    connection_string_from_db_paramsz)Hologres.connection_string_from_db_params  s6     YhXXdXXhXXdXXRVXX	
r(   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   r   )r   r   )r2   r3   r1   r4   r   r   r5   r6   r7   r8   r   r   r   r   r   r   r9   r   r   r   )r2   rL   r1   r4   r5   rM   r7   r3   r9   r   r   r   )NN)
r2   rL   r5   r6   r7   r8   r9   r   r   r3   )r]   N)
r^   r   r_   r   r`   ra   r9   r   r   rb   )
re   ri   r_   r   r`   ra   r9   r   r   rb   )r^   r   r_   r   r`   ra   r   ro   )re   ri   r_   r   r`   ra   r   ro   )rI   r}   r2   r3   re   r   r5   r6   r   r   r   r   r7   r8   r   r   r9   r   r   r   )r   r   re   r   r5   r6   r   r   r   r   r7   r8   r   r   r9   r   r   r   )rI   r}   re   r   r   r   r   r   r   r   r9   r   r   r   )r9   r   r   r   )rI   r}   r   rb   re   r   r   r   r   r   r7   r8   r   r   r9   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   )r#   
__module____qualname____doc__ADA_TOKEN_COUNT_LANGCHAIN_DEFAULT_TABLE_NAMEr'   r$   propertyr1   classmethodr   rH   r\   rh   rg   rr   rm   r   r   r   rG   r   r   r<   r(   r&   r   r      s|        & %7!&+/    "
 
 
 
  ' ' ' X'  +/#'$7!&        [ D% % % %2 +/#'	    @ !%	
 
 
 
 
6 !%	3 3 3 3 32 !%	    2 !%	    , 
 +/$7#'!&
 
 
 
 [
B 
 +/$7#'!&,
 ,
 ,
 ,
 [,
\  %7!&    [4 ! ! ! [!$ 
 %7#'&+"
 "
 "
 "
 ["
H 
 
 
 [
 
 
r(   r   )
__future__r   r!   r>   typingr   r   r   r   r   r	   r
   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.utilsr   langchain_core.vectorstoresr   r   r   r   r<   r(   r&   <module>r      s    " " " " " "   C C C C C C C C C C C C C C C C C C - - - - - - 0 0 0 0 0 0 5 5 5 5 5 5 3 3 3 3 3 3 8 U
 U
 U
 U
 U
{ U
 U
 U
 U
 U
r(   