o
    ZhJ5                     @  s   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 deZdS )    )annotationsN)AnyDictIterableListOptionalTupleTypeDocument)
Embeddings)get_from_dict_or_env)VectorStorei   Zlangchain_pg_embeddingc                   @  s.  e Zd ZdZeeddfdRddZdSddZedTddZ	e
ddeedfdUd!d"ZdVd%d&Z		dWdXd'd(Z	)	dYdZd/d0Z	)	dYd[d3d4Z	)	dYd\d6d7Z	)	dYd]d8d9Ze
deeddfd^d<d=Ze
deeddfd_d@dAZe
eedfd`dBdCZe
dadEdFZe
eeddfdbdIdJZe
dcdPdQZdS )d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                 C  s:   || _ || _|| _|| _|| _|ptt| _| 	  d S N)
r   r   r   r   r   logging	getLogger__name__r   __post_init__)selfr   r   r   r   r   r    r"   `/var/www/html/lang_env/lib/python3.10/site-packages/langchain_community/vectorstores/hologres.py__init__    s   	zHologres.__init__c                 C  s0   ddl m} || j| j| jddi| jd| _dS )z'
        Initialize the store.
        r   )HologresVectordocumenttext)r   r   Ztable_schemar   N)Zhologres_vectorr%   r   r   r   r   storage)r!   r%   r"   r"   r#   r    1   s   zHologres.__post_init__c                 C  s   | j S r   )r   )r!   r"   r"   r#   
embeddingsA   s   zHologres.embeddingstexts	List[str]r)   List[List[float]]	metadatasOptional[List[dict]]idsOptional[List[str]]kwargsr   c	                 K  sb   |d u rdd |D }|sdd |D }|  |	}
| |
||||d}|jd||||d|	 |S )Nc                 S     g | ]}t t qS r"   r   uuiduuid4.0_r"   r"   r#   
<listcomp>S       z#Hologres.__from.<locals>.<listcomp>c                 S     g | ]}i qS r"   r"   r6   r"   r"   r#   r9   V       )r   r   r   r   r   )r*   r)   r-   r/   r"   )get_connection_stringadd_embeddings)clsr*   r)   r   r-   r/   r   r   r   r1   r   storer"   r"   r#   Z__fromE   s$   
zHologres.__fromIterable[str]
List[dict]c              
   K  sZ   zdd |D }| j |||| W dS  ty, } z| j| W Y d}~dS d}~w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                 S  s   g | ]}d |iqS )r&   r"   r7   tr"   r"   r#   r9   y       z+Hologres.add_embeddings.<locals>.<listcomp>N)r(   Zupsert_vectors	Exceptionr   	exception)r!   r*   r)   r-   r/   r1   Zschema_dataser"   r"   r#   r>   h   s   zHologres.add_embeddingsc                 K  sT   |du rdd |D }| j t|}|sd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                 S  r2   r"   r3   r6   r"   r"   r#   r9      r:   z&Hologres.add_texts.<locals>.<listcomp>c                 S  r;   r"   r"   r6   r"   r"   r#   r9      r<   )r   embed_documentslistr>   )r!   r*   r-   r/   r1   r)   r"   r"   r#   	add_texts~   s   zHologres.add_texts   querykfilterOptional[dict]List[Document]c                 K  s   | j j|d}| j|||d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'   	embeddingrN   rO   )r   embed_querysimilarity_search_by_vector)r!   rM   rN   rO   r1   rS   r"   r"   r#   similarity_search   s   zHologres.similarity_searchrS   List[float]c                 K  s   | j |||d}d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.
        rR   c                 S  s   g | ]\}}|qS r"   r"   )r7   docr8   r"   r"   r#   r9      rE   z8Hologres.similarity_search_by_vector.<locals>.<listcomp>)&similarity_search_with_score_by_vector)r!   rS   rN   rO   r1   Zdocs_and_scoresr"   r"   r#   rU      s   z$Hologres.similarity_search_by_vectorList[Tuple[Document, float]]c                 C  s    | j |}| j|||d}|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
        rR   )r   rT   rY   )r!   rM   rN   rO   rS   docsr"   r"   r#   similarity_search_with_score   s
   z%Hologres.similarity_search_with_scorec                 C  s(   | j j||dg|d}dd |D }|S )Nr&   )rN   Zselect_columnsZmetadata_filtersc                 S  s(   g | ]}t |d  |d d|d fqS )r&   metadata)page_contentr]   Zdistancer
   )r7   resultr"   r"   r#   r9      s    zCHologres.similarity_search_with_score_by_vector.<locals>.<listcomp>)r(   search)r!   rS   rN   rO   resultsr[   r"   r"   r#   rY      s   

z/Hologres.similarity_search_with_score_by_vectorr?   Type[Hologres]c           
      K  s0   | 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
        r-   r/   r   r   r   )rI   rJ   _Hologres__from)
r?   r*   rS   r-   r   r   r/   r   r1   r)   r"   r"   r#   
from_texts   s   	zHologres.from_textstext_embeddingsList[Tuple[str, List[float]]]c                 K  s>   dd |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                 S     g | ]}|d  qS )r   r"   rC   r"   r"   r#   r9   7  rE   z,Hologres.from_embeddings.<locals>.<listcomp>c                 S  rh   )   r"   rC   r"   r"   r#   r9   8  rE   rc   )rd   )r?   rf   rS   r-   r   r   r/   r   r1   r*   r)   r"   r"   r#   from_embeddings  s    	zHologres.from_embeddingsc                 K  s    |  |}| |||||d}|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   )r=   )r?   rS   r   r   r   r1   r   r@   r"   r"   r#   from_existing_indexF  s   
zHologres.from_existing_indexDict[str, Any]c                 C  s   t |ddd}|std|S )Nr   ZHOLOGRES_CONNECTION_STRING)datakeyZ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)r?   r1   r   r"   r"   r#   r=   a  s   zHologres.get_connection_string	documentspre_delete_collectionc              
   K  sN   dd |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                 S     g | ]}|j qS r"   )r^   r7   dr"   r"   r#   r9         z+Hologres.from_documents.<locals>.<listcomp>c                 S  rr   r"   )r]   rs   r"   r"   r#   r9     ru   r   )r*   rq   rS   r-   r/   r   r   Nr"   )r=   re   )r?   rp   rS   r   r   r/   rq   r1   r*   r-   r   r"   r"   r#   from_documentst  s   
zHologres.from_documentshostportdatabaseuserpasswordc              
   C  s"   d| d| d| d| d| 
S )z2Return connection string from database parameters.zdbname=z user=z
 password=z host=z port=r"   )r?   rw   rx   ry   rz   r{   r"   r"   r#    connection_string_from_db_params  s    z)Hologres.connection_string_from_db_params)r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   r   )r   r   )r*   r+   r)   r,   r   r   r-   r.   r/   r0   r   r   r   r   r   r   r1   r   r   r   )r*   rA   r)   r,   r-   rB   r/   r+   r1   r   r   r   )NN)
r*   rA   r-   r.   r/   r0   r1   r   r   r+   )rL   N)
rM   r   rN   r   rO   rP   r1   r   r   rQ   )
rS   rW   rN   r   rO   rP   r1   r   r   rQ   )rM   r   rN   r   rO   rP   r   rZ   )rS   rW   rN   r   rO   rP   r   rZ   )r?   rb   r*   r+   rS   r   r-   r.   r   r   r   r   r/   r0   r   r   r1   r   r   r   )rf   rg   rS   r   r-   r.   r   r   r   r   r/   r0   r   r   r1   r   r   r   )r?   rb   rS   r   r   r   r   r   r   r   r1   r   r   r   )r1   rl   r   r   )r?   rb   rp   rQ   rS   r   r   r   r   r   r/   r0   rq   r   r1   r   r   r   )rw   r   rx   r   ry   r   rz   r   r{   r   r   r   )r   
__module____qualname____doc__ADA_TOKEN_COUNT_LANGCHAIN_DEFAULT_TABLE_NAMEr$   r    propertyr)   classmethodrd   r>   rK   rV   rU   r\   rY   re   rj   rk   r=   rv   r|   r"   r"   r"   r#   r      s|    

" !.$r   )
__future__r   r   r4   typingr   r   r   r   r   r   r	   Zlangchain_core.documentsr   Zlangchain_core.embeddingsr   Zlangchain_core.utilsr   Zlangchain_core.vectorstoresr   r   r   r   r"   r"   r"   r#   <module>   s    $