
    Ngo                      d dl mZ d dlZd dlZd dlZd dlZd dlmZ d dlm	Z	 d dl
mZmZmZmZmZmZmZmZmZmZmZmZmZ d dlZd dlmZ d dlmZ d dlmZ d d	l m!Z! d d
l"m#Z# d dl$m%Z%m&Z& d dl'm(Z( d dl)m*Z* d dl+m,Z, er$ee-ee-e.e/e0e1f         f         Z2ee2e(j3        f         Z4 G d de5          Z6ddZ7 eddd           G d de#                      Z8dS )    )annotationsN)islice)
itemgetter)TYPE_CHECKINGAnyAsyncGeneratorCallableDict	GeneratorIterableListOptionalSequenceTupleTypeUnion)
deprecated)Document)
Embeddings)run_in_executor)VectorStore)AsyncQdrantClientQdrantClient)models)AsyncQdrantLocal)maximal_marginal_relevancec                      e Zd ZdZdS )QdrantExceptionz`Qdrant` related exceptions.N)__name__
__module____qualname____doc__     Y/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_qdrant/vectorstores.pyr   r   *   s        &&&&r$   r   methodr	   returnc                H     t          j                   d fd            }|S )z
    Decorator to call the synchronous method of the class if the async method is not
    implemented. This decorator might be only used for the methods that are defined
    as async in the class.
    selfr   argskwargsr'   c           
        K   	  | g|R i | d {V S # t           $ r5 t          d t          | j        dd                    g|R i | d {V cY S w xY w)N   )NotImplementedErrorr   getattrr   )r)   r*   r+   r&   s      r%   wrapperz#sync_call_fallback.<locals>.wrapper5   s      		6t666v666666666" 	 	 	
 )gdFOABB$788;?  CI          	s    <AA)r)   r   r*   r   r+   r   r'   r   )	functoolswraps)r&   r0   s   ` r%   sync_call_fallbackr3   .   s?     _V
 
 
 
 
 
 Nr$   z0.1.2QdrantVectorStorez0.5.0)sincealternativeremovalc                      e Zd ZU dZdZded<   dZded<   dZded	<   deed
eddfddZe	dd            Z
	 	 	 ddd&Ze	 	 	 ddd'            Z	 	 	 	 	 	 ddd6Ze	 	 ddd7            Z	 	 	 	 	 	 ddd9Ze	 	 	 	 	 	 ddd:            Z	 	 	 	 	 	 ddd=Ze	 	 	 	 	 	 ddd>            Z	 	 	 	 	 	 ddd?Ze	 	 	 	 	 	 ddd@            Z	 	 	 	 	 	 	 dddFZe	 	 	 	 	 	 	 dddG            Z	 	 	 	 	 	 	 dddHZe	 	 	 	 	 	 	 dddI            Z	 	 	 	 	 	 	 dddJZe	 	 	 	 	 	 	 dddK            ZdddNZe	 dddO            ZedddddPdQdRddddddddSeeeddddddddddddRfddu            ZedddddPdQdRdddddeed
efddv            Z eedddddPdQdRddddddddSeeeddddddddddddRfddw                        Z!edddPdQdRddddddddSeeedddddddddddRfddx            Z"edddPdQdRddddddddSeeedddddddddddRfddy            Z#e$dd{            Z%dd}Z&	 ddd~Z'e	 ddd            Z(edd            Z)edd            Z*ddZ+ddZ,ddZ-ddZ.ddZ/ddZ0	 	 	 dddZ1	 	 	 dddZ2e$	 	 	 	 	 	 	 	 	 	 	 ddd            Z3dS )QdrantaG  `Qdrant` vector store.

    Example:
        .. code-block:: python

            from qdrant_client import QdrantClient
            from langchain_qdrant import Qdrant

            client = QdrantClient()
            collection_name = "MyCollection"
            qdrant = Qdrant(client, collection_name, embedding_function)
    page_contentstrCONTENT_KEYmetadataMETADATA_KEYNOptional[str]VECTOR_NAMECOSINEclientr   collection_name
embeddingsOptional[Embeddings]content_payload_keymetadata_payload_keydistance_strategyvector_nameasync_clientOptional[Any]embedding_functionOptional[Callable]c
                   t          |t                    st          dt          |                     |4t          |t                    st          dt          |                     ||	t          d          ||	t          d          || _        |	| _        || _        || _        || _	        |p| j
        | _        |p| j        | _        |p| j        | _        |	t!          j        d           t          |t$                    s"t!          j        d           || _        d| _        |                                | _        dS )z%Initialize with necessary components.z@client should be an instance of qdrant_client.QdrantClient, got NzIasync_client should be an instance of qdrant_client.AsyncQdrantClientgot z=`embeddings` value can't be None. Pass `Embeddings` instance.zMBoth `embeddings` and `embedding_function` are passed. Use `embeddings` only.z]Using `embedding_function` is deprecated. Pass `Embeddings` instance to `embeddings` instead.zq`embeddings` should be an instance of `Embeddings`.Using `embeddings` as `embedding_function` which is deprecated)
isinstancer   
ValueErrortyper   _embeddings_embeddings_functionrB   rJ   rC   r<   rF   r>   rG   r@   rI   warningswarnr   upperrH   )
r)   rB   rC   rD   rF   rG   rH   rI   rJ   rL   s
             r%   __init__zQdrant.__init__X   s    &,// 	&F||& &  
 #J|EV,W,W#,L)), ,  
 "4"<O   !&8&D)  
 &$6!$*9E.#6#J$:J $8$MD<M!&:$*:)MF  
 *j11 	$MQ   )3D%#D!2!8!8!:!:r$   r'   c                    | j         S N)rR   r)   s    r%   rD   zQdrant.embeddings   s    r$   @   textsIterable[str]	metadatasOptional[List[dict]]idsOptional[Sequence[str]]
batch_sizeintr+   	List[str]c                    g }|                      ||||          D ]4\  }} | j        j        d| j        |d| |                    |           5|S ),  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.
            ids:
                Optional list of ids to associate with the texts. Ids have to be
                uuid-like strings.
            batch_size:
                How many vectors upload per-request.
                Default: 64

        Returns:
            List of ids from adding the texts into the vectorstore.
        rC   pointsr#   )_generate_rest_batchesrB   upsertrC   extend	r)   r\   r^   r`   rb   r+   	added_ids	batch_idsrh   s	            r%   	add_textszQdrant.add_texts   s    . 	!%!<!<9c:"
 "
 	( 	(Iv DK  $ 4V GM   Y''''r$   c                *  K   | j         t          | j         j        t                    rt	          d          g }|                     ||||          2 3 d{V \  }} | j         j        d| j        |d| d{V  |                    |           @6 |S )rf   N;QdrantLocal cannot interoperate with sync and async clientsrg   r#   )	rJ   rO   _clientr   r.   _agenerate_rest_batchesrj   rC   rk   rl   s	            r%   
aadd_textszQdrant.aadd_texts   s
     0 $
%'7)
 )
$ &M   	'+'C'C9c:(
 (
 	( 	( 	( 	( 	( 	( 	(#)V +$#*  $ 4V GM         Y''''(
 s   B   r   querykfilterOptional[MetadataFilter]search_paramsOptional[models.SearchParams]offsetscore_thresholdOptional[float]consistency Optional[models.ReadConsistency]List[Document]c           	          | j         ||f|||||d|}	t          t          t          d          |	                    S )a  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: Filter by metadata. Defaults to None.
            search_params: Additional search params
            offset:
                Offset of the first result to return.
                May be used to paginate results.
                Note: large offset values may cause performance issues.
            score_threshold:
                Define a minimal score threshold for the result.
                If defined, less similar results will not be returned.
                Score of the returned result might be higher or smaller than the
                threshold depending on the Distance function used.
                E.g. for cosine similarity only higher scores will be returned.
            consistency:
                Read consistency of the search. Defines how many replicas should be
                queried before returning the result.
                Values:
                - int - number of replicas to query, values should present in all
                        queried replicas
                - 'majority' - query all replicas, but return values present in the
                               majority of replicas
                - 'quorum' - query the majority of replicas, return values present in
                             all of them
                - 'all' - query all replicas, and return values present in all replicas
            **kwargs:
                Any other named arguments to pass through to QdrantClient.search()

        Returns:
            List of Documents most similar to the query.
        rx   rz   r|   r}   r   r   )similarity_search_with_scorelistmapr   )
r)   rv   rw   rx   rz   r|   r}   r   r+   resultss
             r%   similarity_searchzQdrant.similarity_search   sd    Z 4$3	
 '+#	
 	
 	
 	
 C
1w//000r$   c                   K    | j         |||fi | d{V }t          t          t          d          |                    S )a3  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: Filter by metadata. Defaults to None.
        Returns:
            List of Documents most similar to the query.
        Nr   )asimilarity_search_with_scorer   r   r   )r)   rv   rw   rx   r+   r   s         r%   asimilarity_searchzQdrant.asimilarity_search  sV        ;:5!VVVvVVVVVVVVC
1w//000r$   List[Tuple[Document, float]]c           	     R     | j         |                     |          |f|||||d|S )a  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: Filter by metadata. Defaults to None.
            search_params: Additional search params
            offset:
                Offset of the first result to return.
                May be used to paginate results.
                Note: large offset values may cause performance issues.
            score_threshold:
                Define a minimal score threshold for the result.
                If defined, less similar results will not be returned.
                Score of the returned result might be higher or smaller than the
                threshold depending on the Distance function used.
                E.g. for cosine similarity only higher scores will be returned.
            consistency:
                Read consistency of the search. Defines how many replicas should be
                queried before returning the result.
                Values:
                - int - number of replicas to query, values should present in all
                        queried replicas
                - 'majority' - query all replicas, but return values present in the
                               majority of replicas
                - 'quorum' - query the majority of replicas, return values present in
                             all of them
                - 'all' - query all replicas, and return values present in all replicas
            **kwargs:
                Any other named arguments to pass through to QdrantClient.search()

        Returns:
            List of documents most similar to the query text and distance for each.
        r   )&similarity_search_with_score_by_vector_embed_query)	r)   rv   rw   rx   rz   r|   r}   r   r+   s	            r%   r   z#Qdrant.similarity_search_with_score1  sU    Z ;t:e$$	
 '+#	
 	
 	
 	
 		
r$   c           	     r   K   |                      |           d{V }	 | j        |	|f|||||d| d{V S )a  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: Filter by metadata. Defaults to None.
            search_params: Additional search params
            offset:
                Offset of the first result to return.
                May be used to paginate results.
                Note: large offset values may cause performance issues.
            score_threshold:
                Define a minimal score threshold for the result.
                If defined, less similar results will not be returned.
                Score of the returned result might be higher or smaller than the
                threshold depending on the Distance function used.
                E.g. for cosine similarity only higher scores will be returned.
            consistency:
                Read consistency of the search. Defines how many replicas should be
                queried before returning the result.
                Values:
                - int - number of replicas to query, values should present in all
                        queried replicas
                - 'majority' - query all replicas, but return values present in the
                               majority of replicas
                - 'quorum' - query the majority of replicas, return values present in
                             all of them
                - 'all' - query all replicas, and return values present in all replicas
            **kwargs:
                Any other named arguments to pass through to
                AsyncQdrantClient.Search().

        Returns:
            List of documents most similar to the query text and distance for each.
        Nr   )_aembed_query'asimilarity_search_with_score_by_vector)
r)   rv   rw   rx   rz   r|   r}   r   r+   query_embeddings
             r%   r   z$Qdrant.asimilarity_search_with_scorei  s      ^ !% 2 25 9 9999999ATA	
 '+#	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 		
r$   	embeddingList[float]c           	          | j         ||f|||||d|}	t          t          t          d          |	                    S )a  Return docs most similar to embedding vector.

        Args:
            embedding: Embedding vector to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            filter: Filter by metadata. Defaults to None.
            search_params: Additional search params
            offset:
                Offset of the first result to return.
                May be used to paginate results.
                Note: large offset values may cause performance issues.
            score_threshold:
                Define a minimal score threshold for the result.
                If defined, less similar results will not be returned.
                Score of the returned result might be higher or smaller than the
                threshold depending on the Distance function used.
                E.g. for cosine similarity only higher scores will be returned.
            consistency:
                Read consistency of the search. Defines how many replicas should be
                queried before returning the result.
                Values:
                - int - number of replicas to query, values should present in all
                        queried replicas
                - 'majority' - query all replicas, but return values present in the
                               majority of replicas
                - 'quorum' - query the majority of replicas, return values present in
                             all of them
                - 'all' - query all replicas, and return values present in all replicas
            **kwargs:
                Any other named arguments to pass through to QdrantClient.search()

        Returns:
            List of Documents most similar to the query.
        r   r   )r   r   r   r   
r)   r   rw   rx   rz   r|   r}   r   r+   r   s
             r%   similarity_search_by_vectorz"Qdrant.similarity_search_by_vector  sd    Z >$=	
 '+#	
 	
 	
 	
 C
1w//000r$   c           	        K    | j         ||f|||||d| d{V }	t          t          t          d          |	                    S )a  Return docs most similar to embedding vector.

        Args:
            embedding: Embedding vector to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            filter: Filter by metadata. Defaults to None.
            search_params: Additional search params
            offset:
                Offset of the first result to return.
                May be used to paginate results.
                Note: large offset values may cause performance issues.
            score_threshold:
                Define a minimal score threshold for the result.
                If defined, less similar results will not be returned.
                Score of the returned result might be higher or smaller than the
                threshold depending on the Distance function used.
                E.g. for cosine similarity only higher scores will be returned.
            consistency:
                Read consistency of the search. Defines how many replicas should be
                queried before returning the result.
                Values:
                - int - number of replicas to query, values should present in all
                        queried replicas
                - 'majority' - query all replicas, but return values present in the
                               majority of replicas
                - 'quorum' - query the majority of replicas, return values present in
                             all of them
                - 'all' - query all replicas, and return values present in all replicas
            **kwargs:
                Any other named arguments to pass through to
                AsyncQdrantClient.Search().

        Returns:
            List of Documents most similar to the query.
        r   Nr   )r   r   r   r   r   s
             r%   asimilarity_search_by_vectorz#Qdrant.asimilarity_search_by_vector  s      ^ ED	
 '+#	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 C
1w//000r$   c                    |Et          |t                    r0t          j        dt                                          |          }	n|}	|}
 j        	 j        |f}
  j        j        d j	        |
|	|||dd||d
|} fd|D             S )a  Return docs most similar to embedding vector.

        Args:
            embedding: Embedding vector to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            filter: Filter by metadata. Defaults to None.
            search_params: Additional search params
            offset:
                Offset of the first result to return.
                May be used to paginate results.
                Note: large offset values may cause performance issues.
            score_threshold:
                Define a minimal score threshold for the result.
                If defined, less similar results will not be returned.
                Score of the returned result might be higher or smaller than the
                threshold depending on the Distance function used.
                E.g. for cosine similarity only higher scores will be returned.
            consistency:
                Read consistency of the search. Defines how many replicas should be
                queried before returning the result.
                Values:
                - int - number of replicas to query, values should present in all
                        queried replicas
                - 'majority' - query all replicas, but return values present in the
                               majority of replicas
                - 'quorum' - query the majority of replicas, return values present in
                             all of them
                - 'all' - query all replicas, and return values present in all replicas
            **kwargs:
                Any other named arguments to pass through to QdrantClient.search()

        Returns:
            List of documents most similar to the query text and distance for each.
        NUsing dict as a `filter` is deprecated. Please use qdrant-client filters directly: https://qdrant.tech/documentation/concepts/filtering/TF
rC   query_vectorquery_filterrz   limitr|   with_payloadwith_vectorsr}   r   c                l    g | ]0}                     |j        j        j                  |j        f1S r#   _document_from_scored_pointrC   rF   rG   score.0resultr)   s     r%   
<listcomp>zAQdrant.similarity_search_with_score_by_vector.<locals>.<listcomp>a  \     
 
 
  00(,-	  
 
 
r$   r#   )
rO   dictrT   rU   DeprecationWarning_qdrant_filter_from_dictrI   rB   searchrC   r)   r   rw   rx   rz   r|   r}   r   r+   qdrant_filterr   r   s   `           r%   r   z-Qdrant.similarity_search_with_score_by_vector  s    Z *VT":":MH #	   !99&AAMM"M ' ,i8L$$+$ 
 0%&'+#
 
 
 

 
 
 
 "
 
 
 	
r$   c                   K    j         t           j         j        t                    rt	          d          |Et          |t
                    r0t          j        dt                      	                    |          }	n|}	|}
 j
        	 j
        |f}
  j         j        d j        |
|	|||dd||d
| d{V } fd|D             S )	a  Return docs most similar to embedding vector.

        Args:
            embedding: Embedding vector to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            filter: Filter by metadata. Defaults to None.
            search_params: Additional search params
            offset:
                Offset of the first result to return.
                May be used to paginate results.
                Note: large offset values may cause performance issues.
            score_threshold:
                Define a minimal score threshold for the result.
                If defined, less similar results will not be returned.
                Score of the returned result might be higher or smaller than the
                threshold depending on the Distance function used.
                E.g. for cosine similarity only higher scores will be returned.
            consistency:
                Read consistency of the search. Defines how many replicas should be
                queried before returning the result.
                Values:
                - int - number of replicas to query, values should present in all
                        queried replicas
                - 'majority' - query all replicas, but return values present in the
                               majority of replicas
                - 'quorum' - query the majority of replicas, return values present in
                             all of them
                - 'all' - query all replicas, and return values present in all replicas
            **kwargs:
                Any other named arguments to pass through to
                AsyncQdrantClient.Search().

        Returns:
            List of documents most similar to the query text and distance for each.
        Nrq   r   TFr   c                l    g | ]0}                     |j        j        j                  |j        f1S r#   r   r   s     r%   r   zBQdrant.asimilarity_search_with_score_by_vector.<locals>.<listcomp>  r   r$   r#   )rJ   rO   rr   r   r.   r   rT   rU   r   r   rI   r   rC   r   s   `           r%   r   z.Qdrant.asimilarity_search_with_score_by_vectorn  sI     ` $
%'7)
 )
$ &M   *VT":":MH #	   !99&AAMM"M ' ,i8L0)0 
 0%&'+#
 
 
 
 
 
 
 
 
 

 
 
 
 "
 
 
 	
r$            ?fetch_klambda_multfloatc	                X    |                      |          }
 | j        |
f|||||||d|	S )a  Return docs selected using the maximal marginal relevance.

        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
                     Defaults to 20.
            lambda_mult: Number between 0 and 1 that determines the degree
                        of diversity among the results with 0 corresponding
                        to maximum diversity and 1 to minimum diversity.
                        Defaults to 0.5.
            filter: Filter by metadata. Defaults to None.
            search_params: Additional search params
            score_threshold:
                Define a minimal score threshold for the result.
                If defined, less similar results will not be returned.
                Score of the returned result might be higher or smaller than the
                threshold depending on the Distance function used.
                E.g. for cosine similarity only higher scores will be returned.
            consistency:
                Read consistency of the search. Defines how many replicas should be
                queried before returning the result.
                Values:
                - int - number of replicas to query, values should present in all
                        queried replicas
                - 'majority' - query all replicas, but return values present in the
                               majority of replicas
                - 'quorum' - query the majority of replicas, return values present in
                             all of them
                - 'all' - query all replicas, and return values present in all replicas
            **kwargs:
                Any other named arguments to pass through to QdrantClient.search()
        Returns:
            List of Documents selected by maximal marginal relevance.
        rw   r   r   rx   rz   r}   r   )r   'max_marginal_relevance_search_by_vectorr)   rv   rw   r   r   rx   rz   r}   r   r+   r   s              r%   max_marginal_relevance_searchz$Qdrant.max_marginal_relevance_search  s[    d ++E22;t;

#'+#

 

 

 

 
	
r$   c	                t   K   |                      |           d{V }
 | j        |
f|||||||d|	 d{V S )a  Return docs selected using the maximal marginal relevance.

        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
                     Defaults to 20.
            lambda_mult: Number between 0 and 1 that determines the degree
                        of diversity among the results with 0 corresponding
                        to maximum diversity and 1 to minimum diversity.
                        Defaults to 0.5.
            filter: Filter by metadata. Defaults to None.
            search_params: Additional search params
            score_threshold:
                Define a minimal score threshold for the result.
                If defined, less similar results will not be returned.
                Score of the returned result might be higher or smaller than the
                threshold depending on the Distance function used.
                E.g. for cosine similarity only higher scores will be returned.
            consistency:
                Read consistency of the search. Defines how many replicas should be
                queried before returning the result.
                Values:
                - int - number of replicas to query, values should present in all
                        queried replicas
                - 'majority' - query all replicas, but return values present in the
                               majority of replicas
                - 'quorum' - query the majority of replicas, return values present in
                             all of them
                - 'all' - query all replicas, and return values present in all replicas
            **kwargs:
                Any other named arguments to pass through to
                AsyncQdrantClient.Search().
        Returns:
            List of Documents selected by maximal marginal relevance.
        Nr   )r   (amax_marginal_relevance_search_by_vectorr   s              r%   amax_marginal_relevance_searchz%Qdrant.amax_marginal_relevance_search  s      h !% 2 25 9 9999999BTB

#'+#

 

 

 

 

 

 

 

 

 

 
	
r$   c	                     | j         |f|||||||d|	}
t          t          t          d          |
                    S )a  Return docs selected using the maximal marginal relevance.

        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.

        Args:
            embedding: Embedding to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
            lambda_mult: Number between 0 and 1 that determines the degree
                        of diversity among the results with 0 corresponding
                        to maximum diversity and 1 to minimum diversity.
                        Defaults to 0.5.
            filter: Filter by metadata. Defaults to None.
            search_params: Additional search params
            score_threshold:
                Define a minimal score threshold for the result.
                If defined, less similar results will not be returned.
                Score of the returned result might be higher or smaller than the
                threshold depending on the Distance function used.
                E.g. for cosine similarity only higher scores will be returned.
            consistency:
                Read consistency of the search. Defines how many replicas should be
                queried before returning the result.
                Values:
                - int - number of replicas to query, values should present in all
                        queried replicas
                - 'majority' - query all replicas, but return values present in the
                               majority of replicas
                - 'quorum' - query the majority of replicas, return values present in
                             all of them
                - 'all' - query all replicas, and return values present in all replicas
            **kwargs:
                Any other named arguments to pass through to QdrantClient.search()
        Returns:
            List of Documents selected by maximal marginal relevance.
        r   r   )2max_marginal_relevance_search_with_score_by_vectorr   r   r   r)   r   rw   r   r   rx   rz   r}   r   r+   r   s              r%   r   z.Qdrant.max_marginal_relevance_search_by_vectorM  sf    b J$I

#'+#

 

 

 

 C
1w//000r$   c	                   K    | j         |f|||||||d|	 d{V }
t          t          t          d          |
                    S )a9  Return docs selected using the maximal marginal relevance.
        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.
        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
                     Defaults to 20.
            lambda_mult: Number between 0 and 1 that determines the degree
                        of diversity among the results with 0 corresponding
                        to maximum diversity and 1 to minimum diversity.
                        Defaults to 0.5.
            filter: Filter by metadata. Defaults to None.
            search_params: Additional search params
            score_threshold:
                Define a minimal score threshold for the result.
                If defined, less similar results will not be returned.
                Score of the returned result might be higher or smaller than the
                threshold depending on the Distance function used.
                E.g. for cosine similarity only higher scores will be returned.
            consistency:
                Read consistency of the search. Defines how many replicas should be
                queried before returning the result.
                Values:
                - int - number of replicas to query, values should present in all
                        queried replicas
                - 'majority' - query all replicas, but return values present in the
                               majority of replicas
                - 'quorum' - query the majority of replicas, return values present in
                             all of them
                - 'all' - query all replicas, and return values present in all replicas
            **kwargs:
                Any other named arguments to pass through to
                AsyncQdrantClient.Search().
        Returns:
            List of Documents selected by maximal marginal relevance and distance for
            each.
        r   Nr   )3amax_marginal_relevance_search_with_score_by_vectorr   r   r   r   s              r%   r   z/Qdrant.amax_marginal_relevance_search_by_vector  s      f QP

#'+#

 

 

 

 

 

 

 

 

 

 C
1w//000r$   c	                     |}
 j         	 j         |
f}
  j        j        d j        |
|||dd||d	|	 fdD             }t	          t          j        |          |||          } fd|D             S )a#  Return docs selected using the maximal marginal relevance.
        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.
        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
                     Defaults to 20.
            lambda_mult: Number between 0 and 1 that determines the degree
                        of diversity among the results with 0 corresponding
                        to maximum diversity and 1 to minimum diversity.
                        Defaults to 0.5.
            filter: Filter by metadata. Defaults to None.
            search_params: Additional search params
            score_threshold:
                Define a minimal score threshold for the result.
                If defined, less similar results will not be returned.
                Score of the returned result might be higher or smaller than the
                threshold depending on the Distance function used.
                E.g. for cosine similarity only higher scores will be returned.
            consistency:
                Read consistency of the search. Defines how many replicas should be
                queried before returning the result.
                Values:
                - int - number of replicas to query, values should present in all
                        queried replicas
                - 'majority' - query all replicas, but return values present in the
                               majority of replicas
                - 'quorum' - query the majority of replicas, return values present in
                             all of them
                - 'all' - query all replicas, and return values present in all replicas
            **kwargs:
                Any other named arguments to pass through to QdrantClient.search()
        Returns:
            List of Documents selected by maximal marginal relevance and distance for
            each.
        NT	rC   r   r   rz   r   r   r   r}   r   c                j    g | ]/}j         |j                            j                   n|j        0S rY   rI   vectorgetr   s     r%   r   zMQdrant.max_marginal_relevance_search_with_score_by_vector.<locals>.<listcomp>  Q     
 
 
  + Md.///
 
 
r$   rw   r   c                    g | ]<}                     |         j        j        j                  |         j        f=S r#   r   r   ir   r)   s     r%   r   zMQdrant.max_marginal_relevance_search_with_score_by_vector.<locals>.<listcomp>  e     
 
 
  00AJ(,-	  
 
 
 
r$   r#   )rI   rB   r   rC   r   nparrayr)   r   rw   r   r   rx   rz   r}   r   r+   r   rD   mmr_selectedr   s   `            @r%   r   z9Qdrant.max_marginal_relevance_search_with_score_by_vector  s    b !' ,l;L$$+$ 
 0%'+#
 
 
 

 
 
 
 "	
 
 

 2HYqk
 
 

 
 
 
 
 "
 
 
 	
r$   c	                j   K    j         t           j         j        t                    rt	          d          |}
 j        	 j        |
f}
  j         j        d j        |
|||dd||d	|	 d{V  fdD             }t          t          j
        |          |||          } fd|D             S )	a/  Return docs selected using the maximal marginal relevance.
        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.
        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
                     Defaults to 20.
            lambda_mult: Number between 0 and 1 that determines the degree
                        of diversity among the results with 0 corresponding
                        to maximum diversity and 1 to minimum diversity.
                        Defaults to 0.5.
        Returns:
            List of Documents selected by maximal marginal relevance and distance for
            each.
        Nrq   Tr   c                j    g | ]/}j         |j                            j                   n|j        0S rY   r   r   s     r%   r   zNQdrant.amax_marginal_relevance_search_with_score_by_vector.<locals>.<listcomp>U  r   r$   r   c                    g | ]<}                     |         j        j        j                  |         j        f=S r#   r   r   s     r%   r   zNQdrant.amax_marginal_relevance_search_with_score_by_vector.<locals>.<listcomp>^  r   r$   r#   )rJ   rO   rr   r   r.   rI   r   rC   r   r   r   r   s   `            @r%   r   z:Qdrant.amax_marginal_relevance_search_with_score_by_vector"  sN     : $
%'7)
 )
$ &M   !' ,l;L0)0 
 0%'+#
 
 
 
 
 
 
 
 
 

 
 
 
 "	
 
 

 2HYqk
 
 

 
 
 
 
 "
 
 
 	
r$   Optional[List[str]]Optional[bool]c                x    | j                             | j        |          }|j        t          j        j        k    S )Delete by vector ID or other criteria.

        Args:
            ids: List of ids to delete.
            **kwargs: Other keyword arguments that subclasses might use.

        Returns:
            True if deletion is successful, False otherwise.
        rC   points_selector)rB   deleterC   statusr   UpdateStatus	COMPLETEDr)   r`   r+   r   s       r%   r   zQdrant.deletek  s>     ## 0 $ 
 
 } 3 ===r$   c                   K   | j         t          | j         j        t                    rt	          d          | j                             | j        |           d{V }|j        t          j	        j
        k    S )r   Nrq   r   )rJ   rO   rr   r   r.   r   rC   r   r   r   r   r   s       r%   adeletezQdrant.adelete|  s       $
%'7)
 )
$ &M   (// 0 0 
 
 
 
 
 
 
 

 } 3 ===r$       FCosineclsType[Qdrant]r   locationurlportOptional[int]	grpc_portprefer_grpcboolhttpsapi_keyprefixtimeouthostpathdistance_funcshard_numberreplication_factorwrite_consistency_factoron_disk_payloadhnsw_configOptional[models.HnswConfigDiff]optimizers_config%Optional[models.OptimizersConfigDiff]
wal_configOptional[models.WalConfigDiff]quantization_config#Optional[models.QuantizationConfig]	init_fromOptional[models.InitFrom]on_diskforce_recreatec!                     | j         |||||||	|
||||||||||||||||||||| fi |!}"|"                    ||||           |"S )a  Construct Qdrant wrapper from a list of texts.

        Args:
            texts: A list of texts to be indexed in Qdrant.
            embedding: A subclass of `Embeddings`, responsible for text vectorization.
            metadatas:
                An optional list of metadata. If provided it has to be of the same
                length as a list of texts.
            ids:
                Optional list of ids to associate with the texts. Ids have to be
                uuid-like strings.
            location:
                If ':memory:' - use in-memory Qdrant instance.
                If `str` - use it as a `url` parameter.
                If `None` - fallback to relying on `host` and `port` parameters.
            url: either host or str of "Optional[scheme], host, Optional[port],
                Optional[prefix]". Default: `None`
            port: Port of the REST API interface. Default: 6333
            grpc_port: Port of the gRPC interface. Default: 6334
            prefer_grpc:
                If true - use gPRC interface whenever possible in custom methods.
                Default: False
            https: If true - use HTTPS(SSL) protocol. Default: None
            api_key:
                    API key for authentication in Qdrant Cloud. Default: None
                    Can also be set via environment variable `QDRANT_API_KEY`.
            prefix:
                If not None - add prefix to the REST URL path.
                Example: service/v1 will result in
                    http://localhost:6333/service/v1/{qdrant-endpoint} for REST API.
                Default: None
            timeout:
                Timeout for REST and gRPC API requests.
                Default: 5.0 seconds for REST and unlimited for gRPC
            host:
                Host name of Qdrant service. If url and host are None, set to
                'localhost'. Default: None
            path:
                Path in which the vectors will be stored while using local mode.
                Default: None
            collection_name:
                Name of the Qdrant collection to be used. If not provided,
                it will be created randomly. Default: None
            distance_func:
                Distance function. One of: "Cosine" / "Euclid" / "Dot".
                Default: "Cosine"
            content_payload_key:
                A payload key used to store the content of the document.
                Default: "page_content"
            metadata_payload_key:
                A payload key used to store the metadata of the document.
                Default: "metadata"
            vector_name:
                Name of the vector to be used internally in Qdrant.
                Default: None
            batch_size:
                How many vectors upload per-request.
                Default: 64
            shard_number: Number of shards in collection. Default is 1, minimum is 1.
            replication_factor:
                Replication factor for collection. Default is 1, minimum is 1.
                Defines how many copies of each shard will be created.
                Have effect only in distributed mode.
            write_consistency_factor:
                Write consistency factor for collection. Default is 1, minimum is 1.
                Defines how many replicas should apply the operation for us to consider
                it successful. Increasing this number will make the collection more
                resilient to inconsistencies, but will also make it fail if not enough
                replicas are available.
                Does not have any performance impact.
                Have effect only in distributed mode.
            on_disk_payload:
                If true - point`s payload will not be stored in memory.
                It will be read from the disk every time it is requested.
                This setting saves RAM by (slightly) increasing the response time.
                Note: those payload values that are involved in filtering and are
                indexed - remain in RAM.
            hnsw_config: Params for HNSW index
            optimizers_config: Params for optimizer
            wal_config: Params for Write-Ahead-Log
            quantization_config:
                Params for quantization, if None - quantization will be disabled
            init_from:
                Use data stored in another collection to initialize this collection
            force_recreate:
                Force recreating the collection
            **kwargs:
                Additional arguments passed directly into REST client initialization

        This is a user-friendly interface that:
        1. Creates embeddings, one for each text
        2. Initializes the Qdrant database as an in-memory docstore by default
           (and overridable to a remote docstore)
        3. Adds the text embeddings to the Qdrant database

        This is intended to be a quick way to get started.

        Example:
            .. code-block:: python

                from langchain_qdrant import Qdrant
                from langchain_openai import OpenAIEmbeddings
                embeddings = OpenAIEmbeddings()
                qdrant = Qdrant.from_texts(texts, embeddings, "localhost")
        )construct_instancero   #r   r\   r   r^   r`   r   r   r   r   r   r   r   r   r   r   r   rC   r   rF   rG   rI   rb   r   r   r   r   r   r   r  r  r  r  r  r+   qdrants#                                      r%   
from_textszQdrant.from_texts  s    \ (' $;
 
< =
 
@ 		3
;;;r$   c                    |t          d           | j        d||||||	|
||||d|\  }} | ||||||||          S )z
        Get instance of an existing Qdrant collection.
        This method will return the instance of the store without inserting any new
        embeddings
        Nz,Must specify collection_name. Received None.r   r   r   r   r   r   r   r   r   r   r   )rB   rJ   rC   rD   rF   rG   rH   rI   r#   )rP   _generate_clients)r   r   r   rC   r   r   r   r   r   r   r   r   r   r   rF   rG   rH   rI   r+   rB   rJ   s                        r%   from_existing_collectionzQdrant.from_existing_collectionH  s    8 "KLLL4s4  
# 
  
  
  
 s%+  3!5/#	
 	
 	
 		
r$   c!                   K    | j         |||||||	|
||||||||||||||||||||| fi |! d{V }"|"                    ||||           d{V  |"S )a  Construct Qdrant wrapper from a list of texts.

        Args:
            texts: A list of texts to be indexed in Qdrant.
            embedding: A subclass of `Embeddings`, responsible for text vectorization.
            metadatas:
                An optional list of metadata. If provided it has to be of the same
                length as a list of texts.
            ids:
                Optional list of ids to associate with the texts. Ids have to be
                uuid-like strings.
            location:
                If ':memory:' - use in-memory Qdrant instance.
                If `str` - use it as a `url` parameter.
                If `None` - fallback to relying on `host` and `port` parameters.
            url: either host or str of "Optional[scheme], host, Optional[port],
                Optional[prefix]". Default: `None`
            port: Port of the REST API interface. Default: 6333
            grpc_port: Port of the gRPC interface. Default: 6334
            prefer_grpc:
                If true - use gPRC interface whenever possible in custom methods.
                Default: False
            https: If true - use HTTPS(SSL) protocol. Default: None
            api_key:
                    API key for authentication in Qdrant Cloud. Default: None
                    Can also be set via environment variable `QDRANT_API_KEY`.
            prefix:
                If not None - add prefix to the REST URL path.
                Example: service/v1 will result in
                    http://localhost:6333/service/v1/{qdrant-endpoint} for REST API.
                Default: None
            timeout:
                Timeout for REST and gRPC API requests.
                Default: 5.0 seconds for REST and unlimited for gRPC
            host:
                Host name of Qdrant service. If url and host are None, set to
                'localhost'. Default: None
            path:
                Path in which the vectors will be stored while using local mode.
                Default: None
            collection_name:
                Name of the Qdrant collection to be used. If not provided,
                it will be created randomly. Default: None
            distance_func:
                Distance function. One of: "Cosine" / "Euclid" / "Dot".
                Default: "Cosine"
            content_payload_key:
                A payload key used to store the content of the document.
                Default: "page_content"
            metadata_payload_key:
                A payload key used to store the metadata of the document.
                Default: "metadata"
            vector_name:
                Name of the vector to be used internally in Qdrant.
                Default: None
            batch_size:
                How many vectors upload per-request.
                Default: 64
            shard_number: Number of shards in collection. Default is 1, minimum is 1.
            replication_factor:
                Replication factor for collection. Default is 1, minimum is 1.
                Defines how many copies of each shard will be created.
                Have effect only in distributed mode.
            write_consistency_factor:
                Write consistency factor for collection. Default is 1, minimum is 1.
                Defines how many replicas should apply the operation for us to consider
                it successful. Increasing this number will make the collection more
                resilient to inconsistencies, but will also make it fail if not enough
                replicas are available.
                Does not have any performance impact.
                Have effect only in distributed mode.
            on_disk_payload:
                If true - point`s payload will not be stored in memory.
                It will be read from the disk every time it is requested.
                This setting saves RAM by (slightly) increasing the response time.
                Note: those payload values that are involved in filtering and are
                indexed - remain in RAM.
            hnsw_config: Params for HNSW index
            optimizers_config: Params for optimizer
            wal_config: Params for Write-Ahead-Log
            quantization_config:
                Params for quantization, if None - quantization will be disabled
            init_from:
                Use data stored in another collection to initialize this collection
            force_recreate:
                Force recreating the collection
            **kwargs:
                Additional arguments passed directly into REST client initialization

        This is a user-friendly interface that:
        1. Creates embeddings, one for each text
        2. Initializes the Qdrant database as an in-memory docstore by default
           (and overridable to a remote docstore)
        3. Adds the text embeddings to the Qdrant database

        This is intended to be a quick way to get started.

        Example:
            .. code-block:: python

                from langchain_qdrant import Qdrant
                from langchain_openai import OpenAIEmbeddings
                embeddings = OpenAIEmbeddings()
                qdrant = await Qdrant.afrom_texts(texts, embeddings, "localhost")
        N)aconstruct_instancert   r  s#                                      r%   afrom_textszQdrant.afrom_texts  s      ^ /s. $;
 
< =
 
 
 
 
 
 
 
@ y#zBBBBBBBBBr$   c                z   |                     |d d                   }t          |d                   } |pt          j                    j        }|                                } | j        d|||||||	|
|||d|\  }!}"|!                    |          }#|#r|r|!                    |           d}#|#r|!	                    |          }$|$j
        j        j        }%t          |%t                    rZ|X||%vr>t          d| d| dd	                    |%                                           d
          |%                    |          }%n|t          |%t                    r=|;t          d| dd	                    |%                                           d          t          |%t                    s|t          d| d          t          |%t&          j                  sJ dt+          |%                       |%j        | k    rt          d|%j         d|  d          |%j        j                                        }&|&|k    rt          d|& d| d|& d          nNt'          j        | t&          j        |         |          }'|||'i}'|!                    ||'||||||||||            | |!|||||||"          }(|(S )Nr-   r   r  FrC   Existing Qdrant collection  does not contain vector named ,. Did you mean one of the existing vectors: , S? If you want to recreate the collection, set `force_recreate` parameter to `True`.m uses named vectors. If you want to reuse it, please set `vector_name` to any of the existing named vectors: R.If you want to recreate the collection, set `force_recreate` parameter to `True`. doesn't use named vectors. If you want to reuse it, please set `vector_name` to `None`. If you want to recreate the collection, set `force_recreate` parameter to `True`.QExpected current_vector_config to be an instance of models.VectorParams, but got :Existing Qdrant collection is configured for vectors with % dimensions. Selected embeddings are _-dimensional. If you want to recreate the collection, set `force_recreate` parameter to `True`.-Existing Qdrant collection is configured for z similarity, but requested z+. Please set `distance_func` parameter to `l` if you want to reuse it. If you want to recreate the collection, set `force_recreate` parameter to `True`.sizedistancer  rC   vectors_configr   r   r   r   r   r   r  r  r  r   rB   rC   rD   rF   rG   rH   rI   rJ   r#   )embed_documentslenuuiduuid4hexrV   r  collection_existsdelete_collectionget_collectionconfigparamsvectorsrO   r   r   joinkeysr   r   VectorParamsrQ   r&  r'  nameDistancecreate_collection)r   r\   r   r   r   r   r   r   r   r   r   r   r   r   rC   r   rF   rG   rI   r   r   r   r   r   r   r  r  r  r  r  r+   partial_embeddingsvector_sizerB   rJ   r0  collection_infocurrent_vector_configcurrent_distance_funcr)  r  s)                                            r%   r
  zQdrant.construct_instance2  s   F '66uRaRyAA,Q/00)=TZ\\-=%++--4s4  
# 
  
  
  
 #44_EE 	& 	&$$_555 % W	 %33O3TTO$3$:$A$I!/66 ;;R&;;;)0o 0 00;0 0-1YY7L7Q7Q7S7S-T-T0 0 0   )>(A(A+(N(N%%1488 [=P%,/ , , yy!6!;!;!=!=>>, , ,   4d;;@K@W%=/ = = =   3V5HII  N045J0K0KN N  
 %)[88%,,1, ,;F, , ,   &.399;; " %55%,,, ,$, , ., , ,   6 $0 7  N &" $$ /-)#5)A /'"3%$7# %    +  3!5+#%	
 	
 	
 r$   c                  K   |                     |d d                    d {V }t          |d                   } |pt          j                    j        }|                                } | j        d|||||||	|
|||d|\  }!}"|!                    |          }#|#r|r|!                    |           d}#|#r|!	                    |          }$|$j
        j        j        }%t          |%t                    rZ|X||%vr>t          d| d| dd	                    |%                                           d
          |%                    |          }%n|t          |%t                    r=|;t          d| dd	                    |%                                           d          t          |%t                    s|t          d| d          t          |%t&          j                  sJ dt+          |%                       |%j        | k    rt          d|%j         d|  d          |%j        j                                        }&|&|k    rt          d|%j         d| d          nNt'          j        | t&          j        |         |          }'|||'i}'|!                    ||'||||||||||            | |!|||||||"          }(|(S )Nr-   r   r  Fr  r  r  r  r  r  r  r  r  r  r   r!  r"  r#  z6 similarity. Please set `distance_func` parameter to `r$  r%  r(  r*  r#   )aembed_documentsr,  r-  r.  r/  rV   r  r0  r1  r2  r3  r4  r5  rO   r   r   r6  r7  r   r   r8  rQ   r&  r'  r9  r:  r;  r<  s)                                            r%   r  zQdrant.aconstruct_instance  s!     F $-#=#=eBQBi#H#HHHHHHH,Q/00)=TZ\\-=%++--4s4  
# 
  
  
  
 #44_EE 	& 	&$$_555 % Y	 %33O3TTO$3$:$A$I!/66 ;;R&;;;)0o 0 00;0 0-1YY7L7Q7Q7S7S-T-T0 0 0   )>(A(A+(N(N%%1488 [=P%,/ , , yy!6!;!;!=!=>>, , ,   4d;;@K@W%=/ = = =   3V5HII  N045J0K0KN N   %)[88%,,1, ,;F, , ,   &.399;; " %55%,5  &     6 $0 7  N &" $$ /-)#5)A /'"3%$7# %    +  3!5+#%	
 	
 	
 r$   r'  c                    | dz   dz  S )z4Normalize the distance to a score on a scale [0, 1].g      ?g       @r#   )r'  s    r%   _cosine_relevance_score_fnz!Qdrant._cosine_relevance_score_fns  s     3#%%r$   Callable[[float], float]c                    | j         dk    r| j        S | j         dk    r| j        S | j         dk    r| j        S t	          d          )a8  
        The 'correct' relevance function
        may differ depending on a few things, including:
        - the distance / similarity metric used by the VectorStore
        - the scale of your embeddings (OpenAI's are unit normed. Many others are not!)
        - embedding dimensionality
        - etc.
        rA   DOTEUCLIDzJUnknown distance strategy, must be cosine, max_inner_product, or euclidean)rH   rE  %_max_inner_product_relevance_score_fn_euclidean_relevance_score_fnrP   rZ   s    r%   _select_relevance_score_fnz!Qdrant._select_relevance_score_fnx  s`     !X--22#u,,==#x//552  r$   c                      | j         ||fi |S )   Return docs and relevance scores in the range [0, 1].

        0 is dissimilar, 1 is most similar.

        Args:
            query: input text
            k: Number of Documents to return. Defaults to 4.
            **kwargs: kwargs to be passed to similarity search. Should include:
                score_threshold: Optional, a floating point value between 0 to 1 to
                    filter the resulting set of retrieved docs

        Returns:
            List of Tuples of (doc, similarity_score)
        )r   r)   rv   rw   r+   s       r%   (_similarity_search_with_relevance_scoresz/Qdrant._similarity_search_with_relevance_scores  s!    ( 1t0DDVDDDr$   c                0   K    | j         ||fi | d{V S )rN  N)r   rO  s       r%   )_asimilarity_search_with_relevance_scoresz0Qdrant._asimilarity_search_with_relevance_scores  s7      * 8T7qKKFKKKKKKKKKr$   
List[dict]c                    g }t          |          D ];\  }}|t          d          |||         nd }|                    ||||i           <|S )NzpAt least one of the texts is None. Please remove it before calling .from_texts or .add_texts on Qdrant instance.)	enumeraterP   append)	r   r\   r^   rF   rG   payloadsr   textr=   s	            r%   _build_payloadszQdrant._build_payloads  s      '' 	 	GAt| L   (1'<y||$HOO'((    r$   scored_pointr   c                    |j                             |          pi }|j        |d<   ||d<   t          |j                             |d          |          S )N_id_collection_name )r:   r=   )payloadr   idr   )r   rZ  rC   rF   rG   r=   s         r%   r   z"Qdrant._document_from_scored_point  sg      '++,@AAGR&/'6#$%-112ErJJ
 
 
 	
r$   keyvalueList[models.FieldCondition]c                `   g }t          |t                    rI|                                D ]3\  }}|                    |                     | d| |                     4nt          |t
                    rr|D ]n}t          |t                    r-|                    |                     | d|                     D|                    |                     | |                     onF|                    t          j        | j	         d| t          j
        |                               |S )N.z[])rb  )ra  match)rO   r   itemsrk   _build_conditionr   rV  r   FieldConditionrG   
MatchValue)r)   ra  rb  out_key_values         r%   rh  zQdrant._build_condition  sR   eT"" 	${{}} J Je

400C$%HHIIIIJt$$ 	 H Hfd++ HJJt44ZZZHHIIIIJJt44XvFFGGGG	H JJ%4<<s<< +%888     
r$   Optional[DictFilter]Optional[models.Filter]c                r     |sd S t          j         fd|                                D                       S )Nc                L    g | ] \  }}                     ||          D ]}|!S r#   )rh  )r   ra  rb  	conditionr)   s       r%   r   z3Qdrant._qdrant_filter_from_dict.<locals>.<listcomp>  sT       C!%!6!6sE!B!B      r$   )must)r   Filterrg  )r)   rx   s   ` r%   r   zQdrant._qdrant_filter_from_dict  sY      	4}   "(,,..  
 
 
 	
r$   c                    | j         | j                             |          }n,| j        |                     |          }nt          d          t	          |d          r|                                n|S )zEmbed query text.

        Used to provide backward compatibility with `embedding_function` argument.

        Args:
            query: Query text.

        Returns:
            List of floats representing the query embedding.
        N2Neither of embeddings or embedding_function is settolist)rD   embed_queryrS   rP   hasattrrw  r)   rv   r   s      r%   r   zQdrant._embed_query  sv     ?&33E::II(4 55e<<		 !UVVV%,Y%A%APy!!!yPr$   c                   K   | j         !| j                             |           d{V }n,| j        |                     |          }nt          d          t	          |d          r|                                n|S )zEmbed query text asynchronously.

        Used to provide backward compatibility with `embedding_function` argument.

        Args:
            query: Query text.

        Returns:
            List of floats representing the query embedding.
        Nrv  rw  )rD   aembed_queryrS   rP   ry  rw  rz  s      r%   r   zQdrant._aembed_query  s       ?&"o::5AAAAAAAAII(4 55e<<		 !UVVV%,Y%A%APy!!!yPr$   List[List[float]]c                   | j         L| j                             t          |                    }t          |d          r|                                }nl| j        Vg }|D ]P}|                     |          }t          |d          r|                                }|                    |           Qnt          d          |S zEmbed search texts.

        Used to provide backward compatibility with `embedding_function` argument.

        Args:
            texts: Iterable of texts to embed.

        Returns:
            List of floats representing the texts embedding.
        Nrw  rv  )rD   r+  r   ry  rw  rS   rV  rP   r)   r\   rD   rX  r   s        r%   _embed_textszQdrant._embed_texts0  s     ?&88eEEJz8,, 1'..00
&2J - - 55d;;	:x00 3 ) 0 0 2 2I!!),,,,	- QRRRr$   c                  K   | j         R| j                             t          |                     d{V }t          |d          r|                                }nl| j        Vg }|D ]P}|                     |          }t          |d          r|                                }|                    |           Qnt          d          |S r  )rD   rC  r   ry  rw  rS   rV  rP   r  s        r%   _aembed_textszQdrant._aembed_textsK  s       ?&#??ULLLLLLLLJz8,, 1'..00
&2J - - 55d;;	:x00 3 ) 0 0 2 2I!!),,,,	- QRRRr$   AGenerator[Tuple[List[str], List[models.PointStruct]], None, None]c              #  D   K   t          |          }t          |pg           }t          |pd t          |          D                       }t          t          ||                    x}rt          t          ||                    pd }	t          t          ||                    }
                     |          } fdt	          |
|                     ||	 j         j                            D             }|
|fV  t          t          ||                    x}d S d S )Nc                >    g | ]}t          j                    j        S r#   r-  r.  r/  r   _s     r%   r   z1Qdrant._generate_rest_batches.<locals>.<listcomp>o  !    #J#J#JDJLL$4#J#J#Jr$   c                f    g | ]-\  }}}t          j        |j        |nj        |i|          .S N)r`  r   r_  r   PointStructrI   r   point_idr   r_  r)   s       r%   r   z1Qdrant._generate_rest_batches.<locals>.<listcomp>x  d        .Hfg "'/ "6*F3#    r$   )iterr   r   r  ziprY  rF   rG   r)   r\   r^   r`   rb   texts_iteratormetadatas_iteratorids_iteratorbatch_textsbatch_metadatasrn   batch_embeddingsrh   s   `            r%   ri   zQdrant._generate_rest_batchesf  s]      e!)/r22CJ#J#Jd5kk#J#J#JKK!&"D"DEEEk 	$"6*<j#I#IJJRdOVL*==>>I  $00==    25$((#'01	 	2 	2  F( V####9 "&"D"DEEEk 	$ 	$ 	$ 	$ 	$r$   @AsyncGenerator[Tuple[List[str], List[models.PointStruct]], None]c               R   K   t          |          }t          |pg           }t          |pd t          |          D                       }t          t          ||                    x}rt          t          ||                    pd }	t          t          ||                    }
                     |           d {V } fdt	          |
|                     ||	 j         j                            D             }|
|fW V  t          t          ||                    x}d S d S )Nc                >    g | ]}t          j                    j        S r#   r  r  s     r%   r   z2Qdrant._agenerate_rest_batches.<locals>.<listcomp>  r  r$   c                f    g | ]-\  }}}t          j        |j        |nj        |i|          .S r  r  r  s       r%   r   z2Qdrant._agenerate_rest_batches.<locals>.<listcomp>  r  r$   )r  r   r   r  r  rY  rF   rG   r  s   `            r%   rs   zQdrant._agenerate_rest_batches  sr      e!)/r22CJ#J#Jd5kk#J#J#JKK!&"D"DEEEk 	$"6*<j#I#IJJRdOVL*==>>I &*%7%7%D%DDDDDDD    25$((#'01	 	2 	2  F( V#####9 "&"D"DEEEk 	$ 	$ 	$ 	$ 	$r$   0Tuple[QdrantClient, Optional[AsyncQdrantClient]]c                    |t          j        d          }t          d| |||||||||	|
d|}| dk    s|
d }nt          d| |||||||||	|
d|}||fS )NQDRANT_API_KEYr  z:memory:r#   )osgetenvr   r   )r   r   r   r   r   r   r   r   r   r   r   r+   sync_clientrJ   s                 r%   r  zQdrant._generate_clients  s     ?i 011G" 
#
 
 
 
 z!!T%5  LL, !#'   L L((r$   )rB   r   rC   r;   rD   rE   rF   r;   rG   r;   rH   r;   rI   r?   rJ   rK   rL   rM   )r'   rE   )NNr[   )r\   r]   r^   r_   r`   ra   rb   rc   r+   r   r'   rd   )ru   NNr   NN)rv   r;   rw   rc   rx   ry   rz   r{   r|   rc   r}   r~   r   r   r+   r   r'   r   )ru   N)
rv   r;   rw   rc   rx   ry   r+   r   r'   r   )rv   r;   rw   rc   rx   ry   rz   r{   r|   rc   r}   r~   r   r   r+   r   r'   r   )r   r   rw   rc   rx   ry   rz   r{   r|   rc   r}   r~   r   r   r+   r   r'   r   )r   r   rw   rc   rx   ry   rz   r{   r|   rc   r}   r~   r   r   r+   r   r'   r   )ru   r   r   NNNN)rv   r;   rw   rc   r   rc   r   r   rx   ry   rz   r{   r}   r~   r   r   r+   r   r'   r   )r   r   rw   rc   r   rc   r   r   rx   ry   rz   r{   r}   r~   r   r   r+   r   r'   r   )r   r   rw   rc   r   rc   r   r   rx   ry   rz   r{   r}   r~   r   r   r+   r   r'   r   rY   )r`   r   r+   r   r'   r   )Fr   r   r\   rd   r   r   r^   r_   r`   ra   r   r?   r   r?   r   r   r   rc   r   r   r   r   r   r?   r   r?   r   r   r   r?   r   r?   rC   r?   r   r;   rF   r;   rG   r;   rI   r?   rb   rc   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'   r9   )(r   r   r   r   r   r?   rC   r?   r   r?   r   r?   r   r   r   rc   r   r   r   r   r   r?   r   r?   r   r   r   r?   rF   r;   rG   r;   rH   r;   rI   r?   r+   r   r'   r9   )@r   r   r\   rd   r   r   r   r?   r   r?   r   r   r   rc   r   r   r   r   r   r?   r   r?   r   r   r   r?   r   r?   rC   r?   r   r;   rF   r;   rG   r;   rI   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'   r9   )r'  r   r'   r   )r'   rF  )ru   )rv   r;   rw   rc   r+   r   r'   r   )
r\   r]   r^   r_   rF   r;   rG   r;   r'   rS  )
rZ  r   rC   r;   rF   r;   rG   r;   r'   r   )ra  r;   rb  r   r'   rc  )rx   rn  r'   ro  )rv   r;   r'   r   )r\   r]   r'   r}  )
r\   r]   r^   r_   r`   ra   rb   rc   r'   r  )
r\   r]   r^   r_   r`   ra   rb   rc   r'   r  )NNr   r   FNNNNNN)r   r?   r   r?   r   r   r   rc   r   r   r   r   r   r?   r   r?   r   r   r   r?   r   r?   r+   r   r'   r  )4r   r    r!   r"   r<   __annotations__r>   r@   rW   propertyrD   ro   r3   rt   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   classmethodr  r  r  r
  r  staticmethodrE  rL  rP  rR  rY  r   rh  r   r   r   r  r  ri   rs   r  r#   r$   r%   r9   r9   E   s}          &K%%%%"L""""!%K%%%% ,0#.$0!)%0&*15;; ;; ;; ;; ;;z       X  +/'+         D  +/'+' ' ' ' 'X +/7;+/8<71 71 71 71 71r  +/	1 1 1 1 1* +/7;+/8<6
 6
 6
 6
 6
p  +/7;+/8<8
 8
 8
 8
 8
z +/7;+/8<71 71 71 71 71r  +/7;+/8<81 81 81 81 81z +/7;+/8<T
 T
 T
 T
 T
l  +/7;+/8<\
 \
 \
 \
 \
B  +/7;+/8<=
 =
 =
 =
 =
~   +/7;+/8<>
 >
 >
 >
 >
F  +/7;+/8<<1 <1 <1 <1 <1|   +/7;+/8<=1 =1 =1 =1 =1D  +/7;+/8<U
 U
 U
 U
 U
n   +/7;+/8<F
 F
 F
 F
 F
P> > > > >" )-> > > > >4 
 +/'+"&!"! $!% $!%"")-%#.$0%0&*,026*.7;CG59CG/3"&$Cn n n n [n`  #)-"&!"! $!% $!%"#.$0!)%0%5
 5
 5
 5
 [5
n 
 +/'+"&!"! $!% $!%"")-%#.$0%0&*,026*.7;CG59CG/3"&$Cn n n n  [n` 
 #'!"! $!% $!%"")-%#.$0%0&*,026*.7;CG59CG/3"&$=\ \ \ \ [\| 
 #'!"! $!% $!%"")-%#.$0%0&*,026*.7;CG59CG/3"&$=_ _ _ _ [_B & & & \&   2 E E E E E,  L L L L L,    [0 
 
 
 [
   ,
 
 
 
Q Q Q Q(Q Q Q Q(   6   < +/'+&$ &$ &$ &$ &$V +/'+&$ &$ &$ &$ &$P "&!"! $!% $!%""4) 4) 4) 4) \4) 4) 4)r$   r9   )r&   r	   r'   r	   )9
__future__r   r1   r  r-  rT   	itertoolsr   operatorr   typingr   r   r   r	   r
   r   r   r   r   r   r   r   r   numpyr   langchain_core._api.deprecationr   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.runnables.configr   langchain_core.vectorstoresr   qdrant_clientr   r   qdrant_client.httpr   &qdrant_client.local.async_qdrant_localr   langchain_qdrant._utilsr   r;   rc   r   r   r   
DictFilterrt  MetadataFilter	Exceptionr   r3   r9   r#   r$   r%   <module>r     s   " " " " " "     				                                                 6 6 6 6 6 6 - - - - - - 0 0 0 0 0 0 ; ; ; ; ; ; 3 3 3 3 3 3 9 9 9 9 9 9 9 9 % % % % % % C C C C C C > > > > > > 6c5c4t!;<<=J:v}45N' ' ' ' 'i ' ' '   . '':GLLLe") e") e") e") e")[ e") e") MLe") e") e")r$   