
    Ng1                       d dl 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
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mZ d dl m!Z! d dl"m#Z#  G d de$          Z% G d de&e          Z' G d de          Z(dS )    )annotationsN)Enum)islice)
itemgetter)AnyCallableDict	GeneratorIterableListOptionalSequenceTupleTypeUnion)Document)
Embeddings)VectorStore)QdrantClientmodels)maximal_marginal_relevance)SparseEmbeddingsc                      e Zd ZdZdS )QdrantVectorStoreErrorz'`QdrantVectorStore` related exceptions.N)__name__
__module____qualname____doc__     S/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_qdrant/qdrant.pyr   r      s        1111r    r   c                      e Zd ZdZdZdZdS )RetrievalModedensesparsehybridN)r   r   r   DENSESPARSEHYBRIDr   r    r!   r#   r#   #   s        EFFFFr    r#   c                  f   e Zd ZU dZdZded<   dZded<   dZded<   d	Zded
<   de	j
        eeeej        j        deddf
ddZedd!            Zedd#            Zedd%            Zeddddddd&d'd(ddddddej        j        eeee	j
        dei i i d)d(ddfddI            Zede	j
        ddd&d'd(ddddddej        j        eeeedddfddJ            Z	 	 	 dddMZ	 	 	 	 	 	 	 ddd^Z	 	 	 	 	 	 	 ddd`Z	 	 	 	 	 	 dddbZ	 	 	 	 	 	 	 dddhZ	 	 	 	 	 	 	 dddiZ	 	 	 	 	 	 	 dddjZ	 dddlZddnZede	j
        di dej        j        eeeed(i i i ddfddp            Ze ddq            Z!ddsZ"eddv            Z#	 	 	 dddxZ$ddzZ%dd|Z&edd~            Z'edd            Z(edd            Z)edd            Z*dS )QdrantVectorStoreu  Qdrant vector store integration.

    Setup:
        Install ``langchain-qdrant`` package.

        .. code-block:: bash

            pip install -qU langchain-qdrant

    Key init args — indexing params:
        collection_name: str
            Name of the collection.
        embedding: Embeddings
            Embedding function to use.
        sparse_embedding: SparseEmbeddings
            Optional sparse embedding function to use.

    Key init args — client params:
        client: QdrantClient
            Qdrant client to use.
        retrieval_mode: RetrievalMode
            Retrieval mode to use.

    Instantiate:
        .. code-block:: python

            from langchain_qdrant import QdrantVectorStore
            from qdrant_client import QdrantClient
            from qdrant_client.http.models import Distance, VectorParams
            from langchain_openai import OpenAIEmbeddings

            client = QdrantClient(":memory:")

            client.create_collection(
                collection_name="demo_collection",
                vectors_config=VectorParams(size=1536, distance=Distance.COSINE),
            )

            vector_store = QdrantVectorStore(
                client=client,
                collection_name="demo_collection",
                embedding=OpenAIEmbeddings(),
            )

    Add Documents:
        .. code-block:: python

            from langchain_core.documents import Document
            from uuid import uuid4

            document_1 = Document(page_content="foo", metadata={"baz": "bar"})
            document_2 = Document(page_content="thud", metadata={"bar": "baz"})
            document_3 = Document(page_content="i will be deleted :(")

            documents = [document_1, document_2, document_3]
            ids = [str(uuid4()) for _ in range(len(documents))]
            vector_store.add_documents(documents=documents, ids=ids)

    Delete Documents:
        .. code-block:: python

            vector_store.delete(ids=[ids[-1]])

    Search:
        .. code-block:: python

            results = vector_store.similarity_search(query="thud",k=1)
            for doc in results:
                print(f"* {doc.page_content} [{doc.metadata}]")

        .. code-block:: python

            * thud [{'bar': 'baz', '_id': '0d706099-6dd9-412a-9df6-a71043e020de', '_collection_name': 'demo_collection'}]

    Search with filter:
        .. code-block:: python

            from qdrant_client.http import models

            results = vector_store.similarity_search(query="thud",k=1,filter=models.Filter(must=[models.FieldCondition(key="metadata.bar", match=models.MatchValue(value="baz"),)]))
            for doc in results:
                print(f"* {doc.page_content} [{doc.metadata}]")

        .. code-block:: python

            * thud [{'bar': 'baz', '_id': '0d706099-6dd9-412a-9df6-a71043e020de', '_collection_name': 'demo_collection'}]


    Search with score:
        .. code-block:: python

            results = vector_store.similarity_search_with_score(query="qux",k=1)
            for doc, score in results:
                print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")

        .. code-block:: python

            * [SIM=0.832268] foo [{'baz': 'bar', '_id': '44ec7094-b061-45ac-8fbf-014b0f18e8aa', '_collection_name': 'demo_collection'}]

    Async:
        .. code-block:: python

            # add documents
            # await vector_store.aadd_documents(documents=documents, ids=ids)

            # delete documents
            # await vector_store.adelete(ids=["3"])

            # search
            # results = vector_store.asimilarity_search(query="thud",k=1)

            # search with score
            results = await vector_store.asimilarity_search_with_score(query="qux",k=1)
            for doc,score in results:
                print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")

        .. code-block:: python

            * [SIM=0.832268] foo [{'baz': 'bar', '_id': '44ec7094-b061-45ac-8fbf-014b0f18e8aa', '_collection_name': 'demo_collection'}]

    Use as Retriever:
        .. code-block:: python

            retriever = vector_store.as_retriever(
                search_type="mmr",
                search_kwargs={"k": 1, "fetch_k": 2, "lambda_mult": 0.5},
            )
            retriever.invoke("thud")

        .. code-block:: python

            [Document(metadata={'bar': 'baz', '_id': '0d706099-6dd9-412a-9df6-a71043e020de', '_collection_name': 'demo_collection'}, page_content='thud')]

    page_contentstrCONTENT_KEYmetadataMETADATA_KEY VECTOR_NAMEzlangchain-sparseSPARSE_VECTOR_NAMENTclientr   collection_name	embeddingOptional[Embeddings]retrieval_moder#   vector_namecontent_payload_keymetadata_payload_keydistancemodels.Distancesparse_embeddingOptional[SparseEmbeddings]sparse_vector_namevalidate_embeddingsboolvalidate_collection_configc           	         |r|                      |||	           |r|                     |||||
||           || _        || _        || _        || _        || _        || _        || _        || _	        |	| _
        |
| _        dS )aa  Initialize a new instance of `QdrantVectorStore`.

        Example:
        .. code-block:: python
        qdrant = Qdrant(
            client=client,
            collection_name="my-collection",
            embedding=OpenAIEmbeddings(),
            retrieval_mode=RetrievalMode.HYBRID,
            sparse_embedding=FastEmbedSparse(),
        )
        N)_validate_embeddings_validate_collection_config_clientr5   _embeddingsr8   r9   r:   r;   r<   _sparse_embeddingsr@   )selfr4   r5   r6   r8   r9   r:   r;   r<   r>   r@   rA   rC   s                r!   __init__zQdrantVectorStore.__init__   s    6  	S%%niAQRRR% 		,,"   .$,&#6 $8! "2"4r    returnc                    | j         S )zGet the Qdrant client instance that is being used.

        Returns:
            QdrantClient: An instance of `QdrantClient`.
        )rG   rJ   s    r!   r4   zQdrantVectorStore.client   s     |r    r   c                <    | j         t          d          | j         S )zGet the dense embeddings instance that is being used.

        Raises:
            ValueError: If embeddings are `None`.

        Returns:
            Embeddings: An instance of `Embeddings`.
        NzBEmbeddings are `None`. Please set using the `embedding` parameter.)rH   
ValueErrorrN   s    r!   
embeddingszQdrantVectorStore.embeddings   s-     #T   r    r   c                <    | j         t          d          | j         S )zGet the sparse embeddings instance that is being used.

        Raises:
            ValueError: If sparse embeddings are `None`.

        Returns:
            SparseEmbeddings: An instance of `SparseEmbeddings`.
        NzPSparse embeddings are `None`. Please set using the `sparse_embedding` parameter.)rI   rP   rN   s    r!   sparse_embeddingsz#QdrantVectorStore.sparse_embeddings  s0     "*E   &&r    i  i  F@   clsType[QdrantVectorStore]texts	List[str]	metadatasOptional[List[dict]]idsOptional[Sequence[str | int]]Optional[str]locationurlportOptional[int]	grpc_portintprefer_grpchttpsOptional[bool]api_keyprefixtimeouthostpathcollection_create_optionsDict[str, Any]vector_paramssparse_vector_params
batch_sizeforce_recreatekwargsr   c                    ||||	|
||||||d|} |                      |||| ||||||||||||          }!|!                    ||||           |!S )a  Construct an instance of `QdrantVectorStore` from a list of texts.

        This is a user-friendly interface that:
        1. Creates embeddings, one for each text
        2. Creates a Qdrant collection if it doesn't exist.
        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, url="http://localhost:6333")
        r^   r_   r`   rb   rd   re   rg   rh   ri   rj   rk   )construct_instance	add_texts)"rU   rW   r6   rY   r[   r5   r^   r_   r`   rb   rd   re   rg   rh   ri   rj   rk   r<   r:   r;   r9   r8   r>   r@   rl   rn   ro   rp   rq   rA   rC   rr   client_optionsqdrants"                                     r!   
from_textszQdrantVectorStore.from_texts  s    j !"&
 
 
 '' % &!
 
$ 		3
;;;r    c                `    t          d||||||	|
||||d|} | ||||||||||||          S )zConstruct an instance of `QdrantVectorStore` from an existing collection
        without adding any data.

        Returns:
            QdrantVectorStore: A new instance of `QdrantVectorStore`.
        rt   r4   r5   r6   r8   r:   r;   r<   r9   r>   r@   rA   rC   r   )r   )rU   r5   r6   r8   r^   r_   r`   rb   rd   re   rg   rh   ri   rj   rk   r<   r:   r;   r9   r@   r>   rA   rC   rr   r4   s                            r!   from_existing_collectionz*QdrantVectorStore.from_existing_collectionl  s    B  
#
 
 
 
 s+) 3!5#-1 3'A
 
 
 	
r    Iterable[str]List[str | int]c                    g }|                      ||||          D ]4\  }} | j        j        d| j        |d| |                    |           5|S )zAdd texts with embeddings to the vectorstore.

        Returns:
            List of ids from adding the texts into the vectorstore.
        )r5   pointsr   )_generate_batchesr4   upsertr5   extend)	rJ   rW   rY   r[   rp   rr   	added_ids	batch_idsr   s	            r!   rv   zQdrantVectorStore.add_texts  s     	!%!7!79c:"
 "
 	( 	(Iv DK  $ 4V GM   Y''''r       r   querykfilterOptional[models.Filter]search_paramsOptional[models.SearchParams]offsetscore_thresholdOptional[float]consistency Optional[models.ReadConsistency]hybrid_fusionOptional[models.FusionQuery]List[Document]c	           
          | j         ||f||||||d|	}
t          t          t          d          |
                    S )zvReturn docs most similar to query.

        Returns:
            List of Documents most similar to the query.
        )r   r   r   r   r   r   r   )similarity_search_with_scorelistmapr   )rJ   r   r   r   r   r   r   r   r   rr   resultss              r!   similarity_searchz#QdrantVectorStore.similarity_search  sf    " 4$3

 '+#'

 

 

 

 C
1w//000r    List[Tuple[Document, float]]c	                     j         ||||dd||d	|	}
 j        t          j        k    r; j                            |          }  j        j        d| j        d|
j	        }ne j        t          j
        k    rX j                            |          }  j        j        dt          j        |j        |j                   j        d|
j	        }n j        t          j        k    rˉ j                            |          } j                            |          }  j        j        dt          j         j        ||||          t          j         j        t          j        |j        |j                  |||          g|p#t          j        t          j        j                  d|
j	        }nt-          d	 j         d
           fd|D             S )zReturn docs most similar to query.

        Returns:
            List of documents most similar to the query text and distance for each.
        TF)	r5   query_filterr   limitr   with_payloadwith_vectorsr   r   )r   using)indicesvalues)r   r   r   r   params)fusion)prefetchr   zInvalid retrieval mode. .c                l    g | ]0}                     |j        j        j                  |j        f1S r   _document_from_pointr5   r:   r;   score.0resultrJ   s     r!   
<listcomp>zBQdrantVectorStore.similarity_search_with_score.<locals>.<listcomp>.  s\     
 
 
  ))(,-	  
 
 
r    r   )r5   r8   r#   r'   rQ   embed_queryr4   query_pointsr9   r   r(   rS   r   SparseVectorr   r   r@   r)   PrefetchFusionQueryFusionRRFrP   )rJ   r   r   r   r   r   r   r   r   rr   query_optionsquery_dense_embeddingr   query_sparse_embeddings   `             r!   r   z.QdrantVectorStore.similarity_search_with_score  sv   $  $3"* !.&
 
 
 -"555$(O$?$?$F$F!.dk. +&     	 G  M$888%)%;%G%G%N%N".dk. )2:18   -      G  M$888$(O$?$?$F$F!%)%;%G%G%N%N".dk. O".3%,   O"5$1$:$B#9#@    &,	 	 	& $Sv'9AR'S'S'S) *  + , - G2 N8KNNNOOO
 
 
 
 "
 
 
 	
r    List[float]c                     |}	                       j         j         j         j        |             j        j        d j        | j        |	|||dd||d|j        }
 fd|
D             S )zReturn docs most similar to embedding vector.

        Returns:
            List of Documents most similar to the query.
        )r4   r5   r9   r<   dense_embeddingsTF)r5   r   r   r   r   r   r   r   r   r   r   c                ^    g | ])}                     |j        j        j                  *S r   r   r5   r:   r;   r   s     r!   r   zAQdrantVectorStore.similarity_search_by_vector.<locals>.<listcomp>c  P     
 
 
  %%$()	 
 
 
r    r   )_validate_collection_for_denser4   r5   r9   r<   r   r   )rJ   r6   r   r   r   r   r   r   rr   qdrant_filterr   s   `          r!   similarity_search_by_vectorz-QdrantVectorStore.similarity_search_by_vector;  s      ++; 0(]& 	, 	
 	
 	
 +$+* 
 0"&'+#
 
 
 
  	
 
 
 
 "
 
 
 	
r             ?fetch_klambda_multfloatc	                    |                      | j        | j        | j        | j        | j                   | j                            |          }
 | j        |
f|||||||d|	S )a%  Return docs selected using the maximal marginal relevance with dense vectors.

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


        Returns:
            List of Documents selected by maximal marginal relevance.
        r   r   r   r   r   r   r   )r   r4   r5   r9   r<   rQ   r   'max_marginal_relevance_search_by_vector)rJ   r   r   r   r   r   r   r   r   rr   query_embeddings              r!   max_marginal_relevance_searchz/QdrantVectorStore.max_marginal_relevance_searchm  s    * 	++K MO	
 	
 	
 /55e<<;t;

#'+#

 

 

 

 
	
r    c	                     | j         |f|||||||d|	}
t          t          t          d          |
                    S )a$  Return docs selected using the maximal marginal relevance with dense vectors.

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

        Returns:
            List of Documents selected by maximal marginal relevance.
        r   r   )2max_marginal_relevance_search_with_score_by_vectorr   r   r   )rJ   r6   r   r   r   r   r   r   r   rr   r   s              r!   r   z9QdrantVectorStore.max_marginal_relevance_search_by_vector  se    ( J$I

#'+#

 

 

 

 C
1w//000r    c	                       j         j        d j        ||||dd|| j        d
|	j         fdD             }
t          t          j        |          |
||          } fd|D             S )a2  Return docs selected using the maximal marginal relevance.
        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.

        Returns:
            List of Documents selected by maximal marginal relevance and distance for
            each.
        T)
r5   r   r   r   r   r   r   r   r   r   c                    g | ]B}t          |j        t                    r|j        n|j                            j                  CS r   )
isinstancevectorr   getr9   r   s     r!   r   zXQdrantVectorStore.max_marginal_relevance_search_with_score_by_vector.<locals>.<listcomp>  sX     
 
 
  &-..5FMM""4#344
 
 
r    )r   r   c                    g | ]<}                     |         j        j        j                  |         j        f=S r   r   )r   ir   rJ   s     r!   r   zXQdrantVectorStore.max_marginal_relevance_search_with_score_by_vector.<locals>.<listcomp>  se     
 
 
  ))AJ(,-	  
 
 
 
r    r   )r4   r   r5   r9   r   r   nparray)rJ   r6   r   r   r   r   r   r   r   rr   rQ   mmr_selectedr   s   `           @r!   r   zDQdrantVectorStore.max_marginal_relevance_search_with_score_by_vector  s    ( +$+* 
 0'+#"
 
 
 
  	
 
 
 
 "	
 
 

 2HYqk
 
 

 
 
 
 
 "
 
 
 	
r    Optional[List[str | int]]c                x    | j                             | j        |          }|j        t          j        j        k    S )zDelete documents by their ids.

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

        Returns:
            True if deletion is successful, False otherwise.
        )r5   points_selector)r4   deleter5   statusr   UpdateStatus	COMPLETED)rJ   r[   rr   r   s       r!   r   zQdrantVectorStore.delete  s>     ## 0 $ 
 
 } 3 ===r    Sequence[str | int]c               d      j                              j        |d          } fd|D             S )NT)r   c                ^    g | ])}                     |j        j        j                  *S r   r   r   s     r!   r   z0QdrantVectorStore.get_by_ids.<locals>.<listcomp>  r   r    )r4   retriever5   )rJ   r[   r   s   `  r!   
get_by_idszQdrantVectorStore.get_by_ids  sO    +&&t';St&TT
 
 
 
 "
 
 
 	
r    rw   c                \   |r|                      |||           |pt          j                    j        }t	          d
i |}|                    |          }|r|r|                    |           d}|r|r|                     ||||	|
||           ni i }}|t          j	        k    rG|
                    dg          }t          |d                   |d<   ||d<   |	t          j        d
i |i}n|t          j        k    r|
t          j        d
i |i}ni|t          j        k    rY|
                    dg          }t          |d                   |d<   ||d<   |	t          j        d
i |i}|
t          j        d
i |i}||d<   ||d<   ||d<    |j        d
i |  | ||||||||	||
dd	          }|S )NF
dummy_textr   sizer<   r5   vectors_configsparse_vectors_configr{   r   )rE   uuiduuid4hexr   collection_existsdelete_collectionrF   r#   r'   embed_documentslenr   VectorParamsr(   SparseVectorParamsr)   create_collection)rU   r6   r8   r>   rw   r5   r<   r:   r;   r9   r@   rq   rl   rn   ro   rA   rC   r4   r   r   r   partial_embeddingsrx   s                          r!   ru   z$QdrantVectorStore.construct_instance  s   (  	R$$^Y@PQQQ)=TZ\\-=////"44_EE 	& 	&$$_555 % 6	B) 	//#"&   571N!444%.%>%>~%N%N"(+,>q,A(B(Bf%,4j)  !4 " "'" ""  =#777&(A ) ).) ))%%  =#777%.%>%>~%N%N"(+,>q,A(B(Bf%,4j)  !4 " "'" "" '(A ) ).) ))% <K%&78:H%&67AV%&=>$F$AA'@AAA+) 3!5#-1 %',
 
 
 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,QdrantVectorStore._cosine_relevance_score_fnw  s     3#%%r    Callable[[float], float]c                    | j         t          j        j        k    r| j        S | j         t          j        j        k    r| j        S | j         t          j        j        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.
        z:Unknown distance strategy, must be COSINE, DOT, or EUCLID.)
r<   r   DistanceCOSINEr   DOT%_max_inner_product_relevance_score_fnEUCLID_euclidean_relevance_score_fnrP   rN   s    r!   _select_relevance_score_fnz,QdrantVectorStore._select_relevance_score_fn|  sj     =FO22222]fo111==]fo44455L  r    scored_pointr   c                    |j                             |          pi }|j        |d<   ||d<   t          |j                             |d          |          S )N_id_collection_namer1   )r,   r/   )payloadr   idr   )rU   r   r5   r:   r;   r/   s         r!   r   z&QdrantVectorStore._document_from_point  sg      '++,@AAGR&/'6#$%-112ErJJ
 
 
 	
r    FGenerator[tuple[list[str | int], list[models.PointStruct]], Any, None]c              #  :  K   t          |          }t          |pg           }t          |pd t          |          D                       }t          t          ||                    x}rt          t          ||                    pd }	t          t          ||                    }
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   z7QdrantVectorStore._generate_batches.<locals>.<listcomp>  s!    #J#J#JDJLL$4#J#J#Jr    c                D    g | ]\  }}}t          j        |||           S ))r  r   r  )r   PointStruct)r   point_idr   r  s       r!   r   z7QdrantVectorStore._generate_batches.<locals>.<listcomp>  sK        .Hfg "!#    r    )iterr   r   zip_build_vectors_build_payloadsr:   r;   )rJ   rW   rY   r[   rp   texts_iteratormetadatas_iteratorids_iteratorbatch_textsbatch_metadatasr   r   s               r!   r   z#QdrantVectorStore._generate_batches  sJ      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  25''44((#'01	 	2 	2  F$ V####+ "&"D"DEEEk 	$ 	$ 	$ 	$ 	$r    
List[dict]c                    g }t          |          D ];\  }}|t          d          |||         nd }|                    ||||i           <|S )Nz]At least one of the texts is None. Please remove it before calling .from_texts or .add_texts.)	enumeraterP   append)	rJ   rW   rY   r:   r;   payloadsr   textr/   s	            r!   r  z!QdrantVectorStore._build_payloads  s      '' 	 	GAt| 9   (1'<y||$HOO'((    r    List[models.VectorStruct]c                     j         t          j        k    r5 j                            t          |                    } fd|D             S  j         t          j        k    r5 j                            t          |                    } fd|D             S  j         t          j        k    r j                            t          |                    } j                            t          |                    }t          |          t          |          k    s
J d             fdt          ||          D             S t          d j          d          )Nc                "    g | ]}j         |iS r   )r9   r   r   rJ   s     r!   r   z4QdrantVectorStore._build_vectors.<locals>.<listcomp>  s5         $f  r    c                ^    g | ])}j         t          j        |j        |j                   i*S )r   r   )r@   r   r   r   r   r  s     r!   r   z4QdrantVectorStore._build_vectors.<locals>.<listcomp>  sP        	 +V-@%}fn. . .  r    z6Mismatched length between dense and sparse embeddings.c           	     r    g | ]3\  }}j         |j        t          j        |j        |j                   i4S r!  )r9   r@   r   r   r   r   )r   dense_vectorsparse_vectorrJ   s      r!   r   z4QdrantVectorStore._build_vectors.<locals>.<listcomp>  s^     
 
 
 0L- $l+V-@,3]=R. . .
 
 
r    zUnknown retrieval mode. z to build vectors.)r8   r#   r'   rQ   r   r   r(   rS   r)   r   r  rP   )rJ   rW   batch_embeddingsbatch_sparse_embeddingsr   rS   s   `     r!   r  z QdrantVectorStore._build_vectors  s    -"555#>>tE{{KK    /	     M$888&*&<&L&LU' '#    6     M$888#>>tE{{KK $ 6 F FtE{{ S S'((C!- -   G  
 
 
 
 47$&74 4
 
 
 
 R4+>RRR  r    Nonec                2   |t           j        k    r|                     |||||           d S |t           j        k    r|                     |||           d S |t           j        k    r2|                     |||||           |                     |||           d S d S N)r#   r'   r   r(   _validate_collection_for_sparser)   )rU   r4   r5   r8   r9   r@   r<   r6   s           r!   rF   z-QdrantVectorStore._validate_collection_config  s     ]000..h	     }333//);     }333..h	   //);    	 43r    r   $Union[Embeddings, List[float], None]c                $   |                     |          }|j        j        j        }t	          |t
                    rK||vr>t          d| d| dd                    |                                           d          ||         }n|dk    rt          d| d          |
J d	            t	          |t                    r*t          |                    d
g          d                   }n4t	          |t                    rt          |          }nt          d          |j        |k    rt          d|j         d| d          |j        |k    r?t          d|j        j         d|                                 d|j        j         d          d S )Nr5   Existing Qdrant collection z% does not contain dense vector named z,. Did you mean one of the existing vectors: z, zS? If you want to recreate the collection, set `force_recreate` parameter to `True`.r1   z is built with unnamed dense vector. If you want to reuse it, set `vector_name` to ''(empty string).If you want to recreate the collection, set `force_recreate` to `True`.zVectorParams is Noner   r   zInvalid `embeddings` type.z@Existing Qdrant collection is configured for dense vectors with z% dimensions. Selected embeddings are z_-dimensional. If you want to recreate the collection, set `force_recreate` parameter to `True`.z-Existing Qdrant collection is configured for z similarity, but requested z&. Please set `distance` parameter to `zl` if you want to reuse it. If you want to recreate the collection, set `force_recreate` parameter to `True`.)get_collectionconfigr   vectorsr   r	   r   joinkeysr   r   r   r   rP   r   r<   nameupper)	rU   r4   r5   r9   r<   r   collection_infovector_configvector_sizes	            r!   r   z0QdrantVectorStore._validate_collection_for_dense+  s    !///PP'.5=mT** 	-//,,/ , ,2=, , *.=3E3E3G3G)H)H, , ,   *+6MM
 b  ,6/ 6 6 6   ((*@(((&
33 	;.>>~NNqQRRKK($// 	;.//KK9:::,,(( %( (+6( ( (   !X--(( ).( (>>##( ( "*/( ( (   .-r    c                    |                     |          }|j        j        j        }|||vrt	          d| d| d          d S )Nr-  r.  z' does not contain sparse vectors named zS. If you want to recreate the collection, set `force_recreate` parameter to `True`.)r/  r0  r   sparse_vectorsr   )rU   r4   r5   r@   r6  sparse_vector_configs         r!   r*  z1QdrantVectorStore._validate_collection_for_sparsen  sz     !///PP.5<K !(!)===((o ( (0D( ( (   >=r    c                    |t           j        k    r|t          d          |t           j        k    r|t          d          |t           j        k    r$t          |d u |d u g          rt          d          d S d S )Nz9'embedding' cannot be None when retrieval mode is 'dense'zA'sparse_embedding' cannot be None when retrieval mode is 'sparse'zVBoth 'embedding' and 'sparse_embedding' cannot be None when retrieval mode is 'hybrid')r#   r'   rP   r(   r)   any)rU   r8   r6   r>   s       r!   rE   z&QdrantVectorStore._validate_embeddings  s     ]000Y5FK   }3338H8PS   }333$ 0D 899
 9
3 2   4333r    )r4   r   r5   r-   r6   r7   r8   r#   r9   r-   r:   r-   r;   r-   r<   r=   r>   r?   r@   r-   rA   rB   rC   rB   )rL   r   )rL   r   )rL   r   )BrU   rV   rW   rX   r6   r7   rY   rZ   r[   r\   r5   r]   r^   r]   r_   r]   r`   ra   rb   rc   rd   rB   re   rf   rg   r]   rh   r]   ri   ra   rj   r]   rk   r]   r<   r=   r:   r-   r;   r-   r9   r-   r8   r#   r>   r?   r@   r-   rl   rm   rn   rm   ro   rm   rp   rc   rq   rB   rA   rB   rC   rB   rr   r   rL   r+   )2rU   rV   r5   r-   r6   r7   r8   r#   r^   r]   r_   r]   r`   ra   rb   rc   rd   rB   re   rf   rg   r]   rh   r]   ri   ra   rj   r]   rk   r]   r<   r=   r:   r-   r;   r-   r9   r-   r@   r-   r>   r?   rA   rB   rC   rB   rr   r   rL   r+   )NNrT   )rW   r}   rY   rZ   r[   r\   rp   rc   rr   r   rL   r~   )r   NNr   NNN)r   r-   r   rc   r   r   r   r   r   rc   r   r   r   r   r   r   rr   r   rL   r   )r   r-   r   rc   r   r   r   r   r   rc   r   r   r   r   r   r   rr   r   rL   r   )r   NNr   NN)r6   r   r   rc   r   r   r   r   r   rc   r   r   r   r   rr   r   rL   r   )r   r   r   NNNN)r   r-   r   rc   r   rc   r   r   r   r   r   r   r   r   r   r   rr   r   rL   r   )r6   r   r   rc   r   rc   r   r   r   r   r   r   r   r   r   r   rr   r   rL   r   )r6   r   r   rc   r   rc   r   r   r   r   r   r   r   r   r   r   rr   r   rL   r   r)  )r[   r   rr   r   rL   rf   )r[   r   rL   r   )$rU   rV   r6   r7   r8   r#   r>   r?   rw   rm   r5   r]   r<   r=   r:   r-   r;   r-   r9   r-   r@   r-   rq   rB   rl   rm   rn   rm   ro   rm   rA   rB   rC   rB   rL   r+   )r<   r   rL   r   )rL   r   )
r   r   r5   r-   r:   r-   r;   r-   rL   r   )
rW   r}   rY   rZ   r[   r\   rp   rc   rL   r  )
rW   r}   rY   rZ   r:   r-   r;   r-   rL   r  )rW   r}   rL   r  )rU   rV   r4   r   r5   r-   r8   r#   r9   r-   r@   r-   r<   r=   r6   r7   rL   r'  )rU   rV   r4   r   r5   r-   r9   r-   r<   r=   r   r+  rL   r'  )
rU   rV   r4   r   r5   r-   r@   r-   rL   r'  )
rU   rV   r8   r#   r6   r7   r>   r?   rL   r'  )+r   r   r   r   r.   __annotations__r0   r2   r3   r#   r'   r   r   r   rK   propertyr4   rQ   rS   classmethodry   r|   rv   r   r   r   r   r   r   r   r   ru   staticmethodr   r   r   r   r  r  rF   r   r*  rE   r   r    r!   r+   r+   )   s        E EN &K%%%%"L""""K00000 +/(5(;&#.$0$*O$:7;"4$(+/25 25 25 25 25h    X       X  ' ' ' X'   +/*.-1)-"&!"! $!% $!%""$*O$:#.$0&(5(;7;"446(*/1$$(+/?U U U U [Un  +/(5(;"&!"! $!% $!%""$*O$:#.$0&"47;$(+//<
 <
 <
 <
 [<
B +/-1    6 *.7;+/8<6:1 1 1 1 1B *.7;+/8<6:X
 X
 X
 X
 X
z *.7;+/8<0
 0
 0
 0
 0
j  *.7;+/8<(
 (
 (
 (
 (
Z  *.7;+/8<1 1 1 1 1H  *.7;+/8<6
 6
 6
 6
 6
t *.> > > > >(
 
 
 
  +/(5(;7;)+)-$*O$:#.$0&"4$46(*/1$(+/#c c c c [cJ & & & \&   * 
 
 
 [
$ +/-1 $  $  $  $  $D   01 1 1 1f    [8 @ @ @ [@D    [(    [  r    r+   ))
__future__r   r   enumr   	itertoolsr   operatorr   typingr   r   r	   r
   r   r   r   r   r   r   r   numpyr   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.vectorstoresr   qdrant_clientr   r   langchain_qdrant._utilsr   "langchain_qdrant.sparse_embeddingsr   	Exceptionr   r-   r#   r+   r   r    r!   <module>rO     s   " " " " " "                                                 - - - - - - 0 0 0 0 0 0 3 3 3 3 3 3 . . . . . . . . > > > > > > ? ? ? ? ? ?2 2 2 2 2Y 2 2 2    C   q q q q q q q q q qr    