
    hm#                        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j$                  e      Z G d d	e      Zy)
    )annotationsN)AnyIterableListOptionalTuple)Document)
Embeddings)VectorStore)DistanceStrategyc                  D   e Zd ZdZej
                  f	 	 	 	 	 ddZedd       ZddZ	ddZ
	 d	 	 	 	 	 	 	 ddZ	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZ	 d	 	 	 	 	 	 	 dd	Zd
g f	 	 	 	 	 	 	 	 	 ddZd
g d	 	 	 	 	 	 	 	 	 ddZd
g f	 	 	 	 	 	 	 	 	 ddZe	 d	 	 	 	 	 	 	 	 	 	 	 dd       Zy)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).
    c                h    	 dd l }|| _        || _        || _        y # t        $ r t        d      w xY w)Nr   z`Could not import kdbai_client python package. Please install it with `pip install kdbai_client`.)kdbai_clientImportError_table
_embeddingdistance_strategy)selftable	embeddingr   r   s        d/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langchain_community/vectorstores/kdbai.py__init__zKDBAI.__init__!   sF    	 #!2  	E 	s    1c                P    t        | j                  t              r| j                  S y N)
isinstancer   r
   )r   s    r   
embeddingszKDBAI.embeddings4   s    dooz2??"    c                    t        | j                  t              r$| j                  j                  t	        |            S |D cg c]  }| j                  |       c}S c c}w r   )r   r   r
   embed_documentslist)r   textsts      r   _embed_documentszKDBAI._embed_documents:   sF    dooz2??224;??,12q"222s   Ac                    t        | j                  t              r| j                  j                  |      S | j                  |      S r   )r   r   r
   embed_query)r   texts     r   _embed_queryzKDBAI._embed_query?   s4    dooz2??..t44t$$r   Nc                   	 dd l }	 dd l}| j                  j	                  |      }|j                         }||d<   |D cg c]  }|j                  d       c}|d<   |D 	cg c]  }	|j                  |	d       c}	|d	<   ||j                  ||gd
      }| j                  j                  |d       y # t        $ r t        d      w xY w# t        $ r t        d      w xY wc c}w c c}	w )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`.idzutf-8r'   float32)dtyper      )axisF)warn)numpyr   pandasr   r    	DataFrameencodearrayconcatr   insert)
r   r"   idsmetadatanppdembedsdfr#   es
             r   _insertzKDBAI._insertD   s    		 007\\^4167Aahhw'76
BHIQBHHQiH8I<B>2B2E*+  	> 	  	? 	 8Is!   B6 C C&!C+6CC#c                ,   	 ddl }t        |      }d}|*t        ||j                        r|}n|j	                  |      }g }t        |      dz
  |z  dz   }	t        |	      D ]  }
|
|z  }|
dz   |z  }||| }|r||| }n<t        t        |            D cg c]  }t        t        j                               ! }}| |j                  || j                  d      }nd}| j                  |||       ||z   } |S # t        $ r t        d      w xY wc c}w )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*   r.   T)drop)r2   r   r!   r   r3   lenrangestruuiduuid4ilocreset_indexr?   )r   r"   	metadatasr8   
batch_sizekwargsr;   metadfout_idsnbatchesiistartiendbatch	batch_ids_
batch_metas                    r   	add_textszKDBAI.add_textsc   s;   ,	 U# )R\\2"i0JNz1A5x 	*A^FEZ'D&&Et,	8=c%j8IJ1S.J	J!#[[5AAtAL
!
LL	:6	)G	* ;  	? 	, Ks   C9 $D9Dc                    	 ddl }|D cg c]  }|j                   }}|j                  |D cg c]  }|j                   c}      }| j                  |||      S # t        $ r t        d      w xY wc c}w c c}w )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*   )r9   rJ   )r2   r   page_contentr3   r9   rV   )r   	documentsrJ   rK   r;   xr"   r9   s           r   add_documentszKDBAI.add_documents   s    	 *33A33<<Y ? ?@~~eh:~NN  	? 	 4 ?s   A A4A9A1r.   c                L     | j                   | 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.
        kfilter)&similarity_search_by_vector_with_scorer(   )r   queryr^   r_   rK   s        r   similarity_search_with_scorez"KDBAI.similarity_search_with_score   s9    " ;t::e$
()&
<B
 	
r   r]   c                  d|v r|j                  d      } | j                  j                  d	|g||d|}g }t        |t              r|d   }n|S |j                  d      D ]j  }|j                  d      }|j                  d      }	|j                  t        ||j                         D 
ci c]  \  }}
|dk7  s||
 c}
}      |	f       l |S c c}
}w )
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)vectorsrd   r_   r   records)orientr'   __nn_distance)rX   r9    )	popr   searchr   r!   to_dictappendr	   items)r   r   r^   r_   rK   matchesdocsrowr'   scorevs              r   r`   z,KDBAI.similarity_search_by_vector_with_score   s    $ &=

3A$$++$$Wi[AfWPVWgt$ajGK??)?4 	C776?DGGO,EKK%)3699;!N41a!v+!Q$!N 	  "Os   ,C:Cc                d     | j                   |f||d|}|D cg c]  \  }}|	 c}}S c c}}w )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.
        r]   )rb   )r   ra   r^   r_   rK   docs_and_scoresdocrT   s           r   similarity_searchzKDBAI.similarity_search   sE    " <$;;
v
)/
 #22Q222s   ,c                    t        d       )zNot implemented.)	Exception)clsr"   r   rI   rK   s        r   
from_textszKDBAI.from_texts  s     *++r   )r   r   r   r
   r   zOptional[DistanceStrategy])returnzOptional[Embeddings])r"   Iterable[str]r|   zList[List[float]])r'   rD   r|   List[float]r   )r"   	List[str]r8   Optional[List[str]]r9   zOptional[Any]r|   None)NN    )r"   r}   rI   Optional[List[dict]]r8   r   rJ   intrK   r   r|   r   )r   )rY   List[Document]rJ   r   rK   r   r|   r   )
ra   rD   r^   r   r_   Optional[List]rK   r   r|   List[Tuple[Document, float]])
r   r~   r^   r   r_   r   rK   r   r|   r   )
ra   rD   r^   r   r_   r   rK   r   r|   r   )rz   r   r"   r   r   r
   rI   r   rK   r   r|   r   )__name__
__module____qualname____doc__r   EUCLIDEAN_DISTANCEr   propertyr   r$   r(   r?   rV   r[   rb   r`   rw   classmethodr{   ri   r   r   r   r      s   , //33 3
	3&  
3
% #'	++ !+  	+
 
+D +/#'55 (5 !	5
 5 5 
5p <>O'O58OILO	O8 !#	

 
 	

 
 
&
2 !#&& 	&
 & & 
&&V !#	33 3 	3
 3 
3, 
 +/	,,, , (	,
 , 
, ,r   r   )
__future__r   loggingrE   typingr   r   r   r   r   langchain_core.documentsr	   langchain_core.embeddingsr
   langchain_core.vectorstoresr   &langchain_community.vectorstores.utilsr   	getLoggerr   loggerr   ri   r   r   <module>r      s@    "   7 7 - 0 3 C			8	$,K ,r   