a
    bgJ5                     @  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ddddddd	d
ddZd	dddZeddddZ	e
ddeedfdddddddddd d
ddZdddddd	dddZdHddddddd d!ZdIddd#dd$d%d&d'ZdJd(dd#dd$d)d*d+ZdKddd#d,d-d.d/ZdLd(dd#d,d0d1d2Ze
deeddfd3ddddddddd d4
d5d6Ze
deeddfd7dddddddd d8	d9d:Ze
eedfd3dddddd d;d<d=Ze
d>dd?d@dAZe
eeddfd3d$ddddddd dB	dCdDZe
dddddddEdFdGZdS )M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strr   intboolzOptional[logging.Logger]None)connection_stringembedding_functionndims
table_namepre_delete_tableloggerreturnc                 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!   w/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/vectorstores/hologres.py__init__    s    	zHologres.__init__)r   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.embeddingsz	List[str]zList[List[float]]zOptional[List[dict]]zOptional[List[str]]r   )
textsr(   r   	metadatasidsr   r   r   kwargsr   c	                 K  sb   |d u rdd |D }|s(dd |D }|  |	}
| |
||||d}|jf ||||d|	 |S )Nc                 S  s   g | ]}t t qS r!   r   uuiduuid4.0_r!   r!   r"   
<listcomp>S       z#Hologres.__from.<locals>.<listcomp>c                 S  s   g | ]}i qS r!   r!   r0   r!   r!   r"   r3   V   r4   )r   r   r   r   r   )r)   r(   r*   r+   )get_connection_stringadd_embeddings)clsr)   r(   r   r*   r+   r   r   r   r,   r   storer!   r!   r"   Z__fromE   s$    
zHologres.__fromzIterable[str]z
List[dict])r)   r(   r*   r+   r,   r   c              
   K  sZ   z$dd |D }| j |||| W n0 tyT } z| j| W Y d}~n
d}~0 0 dS )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!   r1   tr!   r!   r"   r3   y   r4   z+Hologres.add_embeddings.<locals>.<listcomp>N)r'   Zupsert_vectors	Exceptionr   	exception)r    r)   r(   r*   r+   r,   Zschema_dataser!   r!   r"   r6   h   s
    zHologres.add_embeddings)r)   r*   r+   r,   r   c                 K  sT   |du rdd |D }| j t|}|s8d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  s   g | ]}t t qS r!   r-   r0   r!   r!   r"   r3      r4   z&Hologres.add_texts.<locals>.<listcomp>c                 S  s   g | ]}i qS r!   r!   r0   r!   r!   r"   r3      r4   )r   embed_documentslistr6   )r    r)   r*   r+   r,   r(   r!   r!   r"   	add_texts~   s    zHologres.add_texts   zOptional[dict]zList[Document])querykfilterr,   r   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&   	embeddingrC   rD   )r   embed_querysimilarity_search_by_vector)r    rB   rC   rD   r,   rF   r!   r!   r"   similarity_search   s    zHologres.similarity_searchzList[float])rF   rC   rD   r,   r   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.
        rE   c                 S  s   g | ]\}}|qS r!   r!   )r1   docr2   r!   r!   r"   r3      r4   z8Hologres.similarity_search_by_vector.<locals>.<listcomp>)&similarity_search_with_score_by_vector)r    rF   rC   rD   r,   Zdocs_and_scoresr!   r!   r"   rH      s    z$Hologres.similarity_search_by_vectorzList[Tuple[Document, float]])rB   rC   rD   r   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
        rE   )r   rG   rK   )r    rB   rC   rD   rF   docsr!   r!   r"   similarity_search_with_score   s
    z%Hologres.similarity_search_with_score)rF   rC   rD   r   c                 C  s(   | j j||dg|d}dd |D }|S )Nr%   )rC   Zselect_columnsZmetadata_filtersc                 S  s(   g | ] }t |d  |d d|d fqS )r%   metadata)page_contentrN   Zdistancer
   )r1   resultr!   r!   r"   r3      s   zCHologres.similarity_search_with_score_by_vector.<locals>.<listcomp>)r'   search)r    rF   rC   rD   resultsrL   r!   r!   r"   rK      s    

z/Hologres.similarity_search_with_score_by_vectorzType[Hologres])
r7   r)   rF   r*   r   r   r+   r   r,   r   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   )r>   r?   _Hologres__from)
r7   r)   rF   r*   r   r   r+   r   r,   r(   r!   r!   r"   
from_texts   s    	zHologres.from_textszList[Tuple[str, List[float]]])	text_embeddingsrF   r*   r   r   r+   r   r,   r   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  s   g | ]}|d  qS )r   r!   r9   r!   r!   r"   r3   7  r4   z,Hologres.from_embeddings.<locals>.<listcomp>c                 S  s   g | ]}|d  qS )   r!   r9   r!   r!   r"   r3   8  r4   rS   )rT   )r7   rV   rF   r*   r   r   r+   r   r,   r)   r(   r!   r!   r"   from_embeddings  s     	zHologres.from_embeddings)r7   rF   r   r   r   r,   r   c                 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   )r5   )r7   rF   r   r   r   r,   r   r8   r!   r!   r"   from_existing_indexF  s    
zHologres.from_existing_indexzDict[str, Any])r,   r   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)r7   r,   r   r!   r!   r"   r5   a  s    zHologres.get_connection_string)	r7   	documentsrF   r   r   r+   pre_delete_collectionr,   r   c              
   K  sN   dd |D }dd |D }	|  |}
|
|d< | jf ||||	|||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  s   g | ]
}|j qS r!   )rO   r1   dr!   r!   r"   r3     r4   z+Hologres.from_documents.<locals>.<listcomp>c                 S  s   g | ]
}|j qS r!   )rN   r_   r!   r!   r"   r3     r4   r   )r)   r^   rF   r*   r+   r   r   )r5   rU   )r7   r]   rF   r   r   r+   r^   r,   r)   r*   r   r!   r!   r"   from_documentst  s    
zHologres.from_documents)hostportdatabaseuserpasswordr   c              
   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!   )r7   rb   rc   rd   re   rf   r!   r!   r"    connection_string_from_db_params  s     z)Hologres.connection_string_from_db_params)NN)rA   N)rA   N)rA   N)rA   N)r   
__module____qualname____doc__ADA_TOKEN_COUNT_LANGCHAIN_DEFAULT_TABLE_NAMEr#   r   propertyr(   classmethodrT   r6   r@   rI   rH   rM   rK   rU   rX   rY   r5   ra   rg   r!   r!   r!   r"   r      sz   $"           $!"."$r   )
__future__r   r   r.   typingr   r   r   r   r   r   r	   Zlangchain_core.documentsr   Zlangchain_core.embeddingsr   Zlangchain_core.utilsr   Zlangchain_core.vectorstoresr   rk   rl   r   r!   r!   r!   r"   <module>   s   $