a
    bgm#                     @  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	 d dl
mZ d dlmZ d dlmZ d dlmZ eeZG dd	 d	eZdS )
    )annotationsN)AnyIterableListOptionalTuple)Document)
Embeddings)VectorStore)DistanceStrategyc                	   @  s  e Zd ZdZejfddddddZedd	d
dZdddddZ	dddddZ
d7dddddddZd8dddd ddd!d"d#Zd9d$d ddd%d&d'Zd(g fdd d)dd*d+d,d-Zd(g d.dd d)dd*d/d0d1Zd(g fdd d)dd$d+d2d3Zed:ddddddd4d5d6ZdS );KDBAIaT  `KDB.AI` vector store.

    See https://kdb.ai.

    To use, you should have the `kdbai_client` python package installed.

    Args:
        table: kdbai_client.Table object to use as storage,
        embedding: Any embedding function implementing
            `langchain.embeddings.base.Embeddings` interface,
        distance_strategy: One option from DistanceStrategy.EUCLIDEAN_DISTANCE,
            DistanceStrategy.DOT_PRODUCT or DistanceStrategy.COSINE.

    See the example [notebook](https://github.com/KxSystems/langchain/blob/KDB.AI/docs/docs/integrations/vectorstores/kdbai.ipynb).
    r   r	   zOptional[DistanceStrategy])table	embeddingdistance_strategyc                 C  s>   zdd l }W n ty&   tdY n0 || _|| _|| _d S )Nr   z`Could not import kdbai_client python package. Please install it with `pip install kdbai_client`.)kdbai_clientImportError_table
_embeddingr   )selfr   r   r   r    r   t/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/vectorstores/kdbai.py__init__!   s    
zKDBAI.__init__zOptional[Embeddings])returnc                 C  s   t | jtr| jS d S N)
isinstancer   r	   r   r   r   r   
embeddings4   s    zKDBAI.embeddingszIterable[str]zList[List[float]])textsr   c                   s.   t  jtr jt|S  fdd|D S )Nc                   s   g | ]}  |qS r   )r   .0tr   r   r   
<listcomp>=       z*KDBAI._embed_documents.<locals>.<listcomp>)r   r   r	   embed_documentslist)r   r   r   r   r   _embed_documents:   s    zKDBAI._embed_documentsstrzList[float])textr   c                 C  s"   t | jtr| j|S | |S r   )r   r   r	   Zembed_query)r   r'   r   r   r   _embed_query?   s    zKDBAI._embed_queryNz	List[str]zOptional[List[str]]zOptional[Any]None)r   idsmetadatar   c                   s   zdd l  W n ty&   tdY n0 zdd l}W n tyN   tdY n0 | j|}| }||d< dd |D |d<  fdd|D |d	< |d ur|j||gd
d}| jj|dd d S )Nr   zRCould not import numpy python package. Please install it with `pip install numpy`.TCould not import pandas python package. Please install it with `pip install pandas`.idc                 S  s   g | ]}| d qS )zutf-8)encoder   r   r   r   r!   ]   r"   z!KDBAI._insert.<locals>.<listcomp>r'   c                   s   g | ]} j |d dqS )Zfloat32)Zdtype)array)r   enpr   r   r!   ^   r"   r      )ZaxisF)warn)	numpyr   pandasr   r#   	DataFrameconcatr   insert)r   r   r*   r+   pdZembedsZdfr   r1   r   _insertD   s(    

zKDBAI._insert    zOptional[List[dict]]int)r   	metadatasr*   
batch_sizekwargsr   c                 K  s  zddl }W n ty&   tdY n0 t|}d}|durXt||jrN|}n
||}g }t|d | d }	t|	D ]}
|
| }|
d | }||| }|r||| }ndd tt|D }|dur|j|| jdd}nd}| 	||| || }qx|S )	a  Run more texts through the embeddings and add to the vectorstore.

        Args:
            texts (Iterable[str]): Texts to add to the vectorstore.
            metadatas (Optional[List[dict]]): List of metadata corresponding to each
                chunk of text.
            ids (Optional[List[str]]): List of IDs corresponding to each chunk of text.
            batch_size (Optional[int]): Size of batch of chunks of text to insert at
                once.

        Returns:
            List[str]: List of IDs of the added texts.
        r   Nr,   r3   c                 S  s   g | ]}t t qS r   )r&   uuiduuid4)r   _r   r   r   r!      r"   z#KDBAI.add_texts.<locals>.<listcomp>T)Zdrop)
r6   r   r$   r   r7   lenrangeZilocZreset_indexr;   )r   r   r>   r*   r?   r@   r:   ZmetadfZout_idsZnbatchesiistartZiendbatchZ	batch_idsZ
batch_metar   r   r   	add_textsc   s6    


zKDBAI.add_textszList[Document])	documentsr?   r@   r   c                 K  sZ   zddl }W n ty&   tdY n0 dd |D }|dd |D }| j|||dS )aH  Run more documents through the embeddings and add to the vectorstore.

        Args:
            documents (List[Document]: Documents to add to the vectorstore.
            batch_size (Optional[int]): Size of batch of documents to insert at once.

        Returns:
            List[str]: List of IDs of the added texts.
        r   Nr,   c                 S  s   g | ]
}|j qS r   )page_contentr   xr   r   r   r!      r"   z'KDBAI.add_documents.<locals>.<listcomp>c                 S  s   g | ]
}|j qS r   )r+   rL   r   r   r   r!      r"   )r+   r?   )r6   r   r7   rI   )r   rJ   r?   r@   r:   r   r+   r   r   r   add_documents   s    
zKDBAI.add_documentsr3   zOptional[List]zList[Tuple[Document, float]])querykfilterr@   r   c                 K  s   | j | |f||d|S )an  Run similarity search with distance from a query string.

        Args:
            query (str): Query string.
            k (Optional[int]): number of neighbors to retrieve.
            filter (Optional[List]): KDB.AI metadata filter clause: https://code.kx.com/kdbai/use/filter.html

        Returns:
            List[Document]: List of similar documents.
        rP   rQ   )&similarity_search_by_vector_with_scorer(   )r   rO   rP   rQ   r@   r   r   r   similarity_search_with_score   s    z"KDBAI.similarity_search_with_scorerR   )r   rP   rQ   r@   r   c          
      K  s   d|v r| d}| jjf |g||d|}g }t|trF|d }n|S |jddD ]<}| d}| d}	|t|dd	 | D d
|	f qV|S )a  Return documents most similar to embedding, along with scores.

        Args:
            embedding (List[float]): query vector.
            k (Optional[int]): number of neighbors to retrieve.
            filter (Optional[List]): KDB.AI metadata filter clause: https://code.kx.com/kdbai/use/filter.html

        Returns:
            List[Document]: List of similar documents.
        n)ZvectorsrU   rQ   r   records)Zorientr'   Z__nn_distancec                 S  s   i | ]\}}|d kr||qS )r'   r   )r   rP   vr   r   r   
<dictcomp>   r"   z@KDBAI.similarity_search_by_vector_with_score.<locals>.<dictcomp>)rK   r+   )	popr   searchr   r$   to_dictappendr   items)
r   r   rP   rQ   r@   matchesdocsrowr'   Zscorer   r   r   rS      s&    




	z,KDBAI.similarity_search_by_vector_with_scorec                 K  s&   | j |f||d|}dd |D S )a`  Run similarity search from a query string.

        Args:
            query (str): Query string.
            k (Optional[int]): number of neighbors to retrieve.
            filter (Optional[List]): KDB.AI metadata filter clause: https://code.kx.com/kdbai/use/filter.html

        Returns:
            List[Document]: List of similar documents.
        rR   c                 S  s   g | ]\}}|qS r   r   )r   docrC   r   r   r   r!     r"   z+KDBAI.similarity_search.<locals>.<listcomp>)rT   )r   rO   rP   rQ   r@   Zdocs_and_scoresr   r   r   similarity_search   s    zKDBAI.similarity_search)clsr   r   r>   r@   r   c                 K  s   t d dS )zNot implemented.N)	Exception)rc   r   r   r>   r@   r   r   r   
from_texts  s    	zKDBAI.from_texts)N)NNr<   )r<   )N)__name__
__module____qualname____doc__r   ZEUCLIDEAN_DISTANCEr   propertyr   r%   r(   r;   rI   rN   rT   rS   rb   classmethodre   r   r   r   r   r      s6   	 "   8 + r   )
__future__r   loggingrA   typingr   r   r   r   r   Zlangchain_core.documentsr   Zlangchain_core.embeddingsr	   Zlangchain_core.vectorstoresr
   Z&langchain_community.vectorstores.utilsr   	getLoggerrf   loggerr   r   r   r   r   <module>   s   
