
    +#h1                       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(y)    )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y)QdrantVectorStoreErrorz'`QdrantVectorStore` related exceptions.N)__name__
__module____qualname____doc__     T/var/www/html/sandstorm/venv/lib/python3.12/site-packages/langchain_qdrant/qdrant.pyr   r      s    1r    r   c                      e Zd ZdZdZdZy)RetrievalModedensesparsehybridN)r   r   r   DENSESPARSEHYBRIDr   r    r!   r#   r#   #   s    EFFr    r#   c                     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
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d+dZed,d       Zed-d       Zed.d       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	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d/d       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	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d0d       Z	 	 	 d1	 	 	 	 	 	 	 	 	 	 	 d2dZ	 	 	 	 	 	 	 d3	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d4dZ	 	 	 	 	 	 	 d3	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d5dZ	 	 	 	 	 	 d6	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d7dZ	 	 	 	 	 	 	 d8	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d9dZ	 	 	 	 	 	 	 d8	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d:dZ	 	 	 	 	 	 	 d8	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d;dZ	 d<	 	 	 	 	 d=dZd>dZede	j                  di dej                  j                  eeeedi i i ddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d?d        Ze d@d!       Z!dAd"Z"e	 	 	 	 	 	 	 	 	 	 dBd#       Z#	 	 	 d1	 	 	 	 	 	 	 	 	 dCd$Z$	 	 	 	 	 	 	 	 	 	 dDd%Z%	 	 	 	 dEd&Z&e	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dFd'       Z'e	 	 	 	 	 	 	 	 	 	 	 	 	 	 dGd(       Z(e	 	 	 	 	 	 	 	 	 	 dHd)       Z)e	 	 	 	 	 	 	 	 	 	 dId*       Z*y)J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_NAMENTc           	         |r| j                  |||	       |r| j                  |||||
||       || _        || _        || _        || _        || _        || _        || _        || _	        |	| _
        |
| _        y)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_clientcollection_name_embeddingsretrieval_modevector_namecontent_payload_keymetadata_payload_keydistance_sparse_embeddingssparse_vector_name)selfclientr8   	embeddingr:   r;   r<   r=   r>   sparse_embeddingr@   validate_embeddingsvalidate_collection_configs                r!   __init__zQdrantVectorStore.__init__   s    6 %%niAQR%,," .$,&#6 $8! "2"4r    c                    | j                   S )zGet the Qdrant client instance that is being used.

        Returns:
            QdrantClient: An instance of `QdrantClient`.
        )r7   rA   s    r!   rB   zQdrantVectorStore.client   s     ||r    c                H    | 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`.
        zBEmbeddings are `None`. Please set using the `embedding` parameter.)r9   
ValueErrorrI   s    r!   
embeddingszQdrantVectorStore.embeddings   s.     #T  r    c                H    | 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`.
        zPSparse embeddings are `None`. Please set using the `sparse_embedding` parameter.)r?   rK   rI   s    r!   sparse_embeddingsz#QdrantVectorStore.sparse_embeddings  s1     ""*E  &&&r    i  i  F@   c                    ||||	|
||||||d|} | j                  |||| ||||||||||||      }!|!j                  ||||       |!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")
        locationurlport	grpc_portprefer_grpchttpsapi_keyprefixtimeouthostpath)construct_instance	add_texts)"clstextsrC   	metadatasidsr8   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r>   r<   r=   r;   r:   rD   r@   collection_create_optionsvector_paramssparse_vector_params
batch_sizeforce_recreaterE   rF   kwargsclient_optionsqdrants"                                     r!   
from_textszQdrantVectorStore.from_texts  s    j !"&
 
 '' % &!
$ 		3
;r    c                X    t        d||||||	|
||||d|} | ||||||||||||      S )zConstruct an instance of `QdrantVectorStore` from an existing collection
        without adding any data.

        Returns:
            QdrantVectorStore: A new instance of `QdrantVectorStore`.
        rQ   rB   r8   rC   r:   r<   r=   r>   r;   rD   r@   rE   rF   r   )r   )r_   r8   rC   r:   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r>   r<   r=   r;   r@   rD   rE   rF   rh   rB   s                            r!   from_existing_collectionz*QdrantVectorStore.from_existing_collectionl  sr    B  
#
 
 +) 3!5#-1 3'A
 	
r    c                    g }| j                  ||||      D ]?  \  }} | j                  j                  d| j                  |d| |j	                  |       A |S )zAdd texts with embeddings to the vectorstore.

        Returns:
            List of ids from adding the texts into the vectorstore.
        )r8   pointsr   )_generate_batchesrB   upsertr8   extend)	rA   r`   ra   rb   rf   rh   	added_ids	batch_idsrp   s	            r!   r^   zQdrantVectorStore.add_texts  sw     	!%!7!79c:"
 	(Iv DKK  $ 4 4VGM Y'	( r    c	           
     t     | j                   ||f||||||d|	}
t        t        t        d      |
            S )zvReturn docs most similar to query.

        Returns:
            List of Documents most similar to the query.
        )filtersearch_paramsoffsetscore_thresholdconsistencyhybrid_fusionr   )similarity_search_with_scorelistmapr   )rA   querykrw   rx   ry   rz   r{   r|   rh   resultss              r!   similarity_searchz#QdrantVectorStore.similarity_search  sW    " 4$33

 '+#'

 

 C
1w/00r    c	                D   | j                   ||||dd||d	|	}
| j                  t        j                  k(  rP| j                  j                  |      } | j                  j                  d|| j                  d|
j                  }n| j                  t        j                  k(  ry| j                  j                  |      } | j                  j                  dt        j                  |j                  |j                        | j                   d|
j                  }n5| j                  t        j"                  k(  r| j                  j                  |      }| j                  j                  |      } | j                  j                  dt        j$                  | j                  ||||      t        j$                  | j                   t        j                  |j                  |j                        |||      g|xs. t        j&                  t        j(                  j*                        d|
j                  }nt-        d	| j                   d
      |D cg c]@  }| j/                  || j                   | j0                  | j2                        |j4                  fB c}S c c}w )zReturn docs most similar to query.

        Returns:
            List of documents most similar to the query text and distance for each.
        TF)	r8   query_filterrx   limitry   with_payloadwith_vectorsrz   r{   )r   using)indicesvalues)r   r   rw   r   params)fusion)prefetchr   zInvalid retrieval mode. .r   )r8   r:   r#   r'   rL   embed_queryrB   query_pointsr;   rp   r(   rN   r   SparseVectorr   r   r@   r)   PrefetchFusionQueryFusionRRFrK   _document_from_pointr<   r=   score)rA   r   r   rw   rx   ry   rz   r{   r|   rh   query_optionsquery_dense_embeddingr   query_sparse_embeddingresults                  r!   r}   z.QdrantVectorStore.similarity_search_with_score  s   $  $33"* !.&
 
 -"5"55$(OO$?$?$F!.dkk.. +&&   f	    M$8$88%)%;%;%G%G%N".dkk.. ))2::188 --   f    M$8$88$(OO$?$?$F!%)%;%;%G%G%N".dkk.. OO"..3%, OO"55$11$:$B$B#9#@#@  &,	& $Sv'9'9ARAR'S)*  +, f- 2 78K8K7LANOO "
  ))((,,--	 
 	
 
s   AJc                   |}	| j                  | j                  | j                  | j                  | j                  |        | j                  j
                  d| j                  || j                  |	|||dd||d|j                  }
|
D cg c]4  }| j                  || j                  | j                  | j                        6 c}S c c}w )zReturn docs most similar to embedding vector.

        Returns:
            List of Documents most similar to the query.
        )rB   r8   r;   r>   dense_embeddingsTF)r8   r   r   r   rx   r   ry   r   r   rz   r{   r   )
_validate_collection_for_denserB   r8   r;   r>   r   rp   r   r<   r=   )rA   rC   r   rw   rx   ry   rz   r{   rh   qdrant_filterr   r   s               r!   similarity_search_by_vectorz-QdrantVectorStore.similarity_search_by_vector;  s      ++;; 00((]]& 	, 	
 +$++** 
 00""&'+#
 
 & 	, "
  %%$$(())	
 	
 
s   9Cc	                    | j                  | j                  | 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   fetch_klambda_multrw   rx   rz   r{   )r   rB   r8   r;   r>   rL   r   'max_marginal_relevance_search_by_vector)rA   r   r   r   r   rw   rx   rz   r{   rh   query_embeddings              r!   max_marginal_relevance_searchz/QdrantVectorStore.max_marginal_relevance_searchm  s    * 	++KK  MMOO	
 //55e<;t;;

#'+#

 

 
	
r    c	                t     | 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   )rA   rC   r   r   r   rw   rx   rz   r{   rh   r   s              r!   r   z9QdrantVectorStore.max_marginal_relevance_search_by_vector  sV    ( J$II

#'+#

 

 C
1w/00r    c	                8    | j                   j                  d| j                  ||||dd||| j                  d
|	j                  }
|
D cg c]M  }t        |j                  t              r|j                  n$|j                  j                  | j                        O }}t        t        j                  |      |||      }|D cg c]F  }| j                  |
|   | j                  | j                  | j                        |
|   j                  fH c}S c c}w c c}w )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)
r8   r   r   rx   r   r   r   rz   r{   r   )r   r   r   )rB   r   r8   r;   rp   
isinstancevectorr~   getr   nparrayr   r<   r=   r   )rA   rC   r   r   r   rw   rx   rz   r{   rh   r   r   rL   mmr_selectedis                  r!   r   zDQdrantVectorStore.max_marginal_relevance_search_with_score_by_vector  s7   ( +$++** 
 00'+#""
 
 & 	$ "	
  &--. MM""4#3#345

 
 2HHYqk
 "
  ))AJ((,,--	 
  
 	


s   
ADADc                    | j                   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.
        )r8   points_selector)rB   deleter8   statusr   UpdateStatus	COMPLETED)rA   rb   rh   r   s       r!   r   zQdrantVectorStore.delete  sF     ## 00 $ 
 }} 3 3 = ===r    c          	         | j                   j                  | j                  |d      }|D cg c]4  }| j                  || j                  | j                  | j
                        6 c}S c c}w )NT)r   )rB   retriever8   r   r<   r=   )rA   rb   r   r   s       r!   
get_by_idszQdrantVectorStore.get_by_ids  sp    ++&&t';';St&T "
  %%$$(())	
 	
 
s   9A)c                V   |r| j                  |||       |xs t        j                         j                  }t	        d
i |}|j                  |      }|r|r|j                  |       d}|r|r%| j                  ||||	|
||       ni i }}|t        j                  k(  r@|j                  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(  rV|j                  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>   r8   vectors_configsparse_vectors_configrm   r   )r5   uuiduuid4hexr   collection_existsdelete_collectionr6   r#   r'   embed_documentslenr   VectorParamsr(   SparseVectorParamsr)   create_collection)r_   rC   r:   rD   ri   r8   r>   r<   r=   r;   r@   rg   rc   rd   re   rE   rF   rB   r   r   r   partial_embeddingsrj   s                          r!   r]   z$QdrantVectorStore.construct_instance  s"   ( $$^Y@PQ)=TZZ\-=-=//"44_E$$_5 %)//#"& 571N!4!44%.%>%>~%N"(+,>q,A(Bf%,4j)  !4!4 "'""  =#7#77&(A(A ).))%  =#7#77%.%>%>~%N"(+,>q,A(Bf%,4j)  !4!4 "'"" '(A(A ).))% <K%&78:H%&67AV%&=>$F$$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    c                J   | 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_fnrK   rI   s    r!   _select_relevance_score_fnz,QdrantVectorStore._select_relevance_score_fn|  sz     ==FOO222222]]foo111===]]foo444555L r    c                    |j                   j                  |      xs i }|j                  |d<   ||d<   t        |j                   j                  |d      |      S )N_id_collection_namer1   )r,   r/   )payloadr   idr   )r_   scored_pointr8   r<   r=   r/   s         r!   r   z&QdrantVectorStore._document_from_point  s_      ''++,@AGR&//'6#$%--112ErJ
 	
r    c           
   #  ~  K   t        |      }t        |xs g       }t        |xs5 t        |      D cg c]   }t        j                         j                  " c}      }t	        t        ||            x}	rt	        t        ||            xs d }
t	        t        ||            }t        || j                  |	      | j                  |	|
| j                  | j                              D cg c]  \  }}}t        j                  |||        }}}}||f t	        t        ||            x}	ry y c c}w c c}}}w w)N)r   r   r   )iterr   r   r   r~   r   zip_build_vectors_build_payloadsr<   r=   r   PointStruct)rA   r`   ra   rb   rf   texts_iteratormetadatas_iterator_ids_iteratorbatch_textsbatch_metadatasru   point_idr   r   rp   s                   r!   rq   z#QdrantVectorStore._generate_batches  s6     e!)/r2CJd5k#JDJJL$4$4#JK!&"DEEkE"6*<j#IJRdOVL*=>I 25''4((#'0011		2  .Hfg ""!#F $ V##+ "&"DEEkE $K
s#   1D=%D1BD=*#D6!D=/D=c                    g }t        |      D ]0  \  }}|t        d      |||   nd }|j                  ||||i       2 |S )Nz]At least one of the texts is None. Please remove it before calling .from_texts or .add_texts.)	enumeraterK   append)	rA   r`   ra   r<   r=   payloadsr   textr/   s	            r!   r   z!QdrantVectorStore._build_payloads  sl      ' 	GAt| 9  (1'<y|$HOO'((	 r    c                   | j                   t        j                  k(  r@| j                  j	                  t        |            }|D cg c]  }| j                  |i c}S | j                   t        j                  k(  ri| j                  j	                  t        |            }|D cg c]9  }| j                  t        j                  |j                  |j                        i; c}S | j                   t        j                  k(  r| j                  j	                  t        |            }| j                  j	                  t        |            }t        |      t        |      k(  sJ d       t!        ||      D cg c]H  \  }}| j                  || j                  t        j                  |j                  |j                        iJ c}}S t#        d| j                    d      c c}w c c}w c c}}w )N)r   r   z6Mismatched length between dense and sparse embeddings.zUnknown retrieval mode. z to build vectors.)r:   r#   r'   rL   r   r~   r;   r(   rN   r@   r   r   r   r   r)   r   r   rK   )	rA   r`   batch_embeddingsr   batch_sparse_embeddingsr   rN   dense_vectorsparse_vectors	            r!   r   z QdrantVectorStore._build_vectors  s    -"5"55#>>tE{K
 /	  $$f    M$8$88&*&<&<&L&LU'# 6 	 ++V-@-@%}}fnn.    M$8$88#>>tE{K $ 6 6 F FtE{ S'(C!-  HGH  47$&74
 0L- $$l++V-@-@,33]=R=R.
 
 *4+>+>*??QR S"
s   G #>G%6AG*c                   |t         j                  k(  r| j                  |||||       y |t         j                  k(  r| j	                  |||       y |t         j
                  k(  r)| j                  |||||       | j	                  |||       y y N)r#   r'   r   r(   _validate_collection_for_sparser)   )r_   rB   r8   r:   r;   r@   r>   rC   s           r!   r6   z-QdrantVectorStore._validate_collection_config  s     ]000..h	 }333//); }333..h	 //);	 4r    c                   |j                  |      }|j                  j                  j                  }t	        |t
              r<||vr2t        d| d| ddj                  |j                                d      ||   }n|dk7  rt        d| d      |J d	       t	        |t              rt        |j                  d
g      d         }n't	        |t              rt        |      }nt        d      |j                  |k7  rt        d|j                   d| d      |j                  |k7  rKt        d|j                  j                    d|j#                          d|j                  j                    d      y )Nr8   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~   rK   r   r>   nameupper)	r_   rB   r8   r;   r>   r   collection_infovector_configvector_sizes	            r!   r   z0QdrantVectorStore._validate_collection_for_dense+  s    !///P'..55==mT*-/,1/1B C22= ?))-=3E3E3G)H(I J+,  *+6M
 b ,1/1B C6 6  (@*@@(&
3.>>~NqQRK($/./K9::,(R %%& '++6- 8'(  !!X-(? ))..//J>>#$ %!**//0 1'(  .r    c                    |j                  |      }|j                  j                  j                  }|||vrt	        d| d| d      y )Nr   r   z' does not contain sparse vectors named zS. If you want to recreate the collection, set `force_recreate` parameter to `True`.)r   r   r   sparse_vectorsr   )r_   rB   r8   r@   r   sparse_vector_configs         r!   r   z1QdrantVectorStore._validate_collection_for_sparsen  sp     !///P.55<<KK !(!)==(-o-> ?00D/E F'(  >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      y y )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'   rK   r(   r)   any)r_   r:   rC   rD   s       r!   r5   z&QdrantVectorStore._validate_embeddings  s     ]000Y5FK  }3338H8PS  }333$ 0D 899
 2 9
3r    )rB   r   r8   r-   rC   Optional[Embeddings]r:   r#   r;   r-   r<   r-   r=   r-   r>   models.DistancerD   Optional[SparseEmbeddings]r@   r-   rE   boolrF   r  )returnr   )r  r   )r  r   )Br_   Type[QdrantVectorStore]r`   z	List[str]rC   r  ra   Optional[List[dict]]rb   Optional[Sequence[str | int]]r8   Optional[str]rR   r  rS   r  rT   Optional[int]rU   intrV   r  rW   Optional[bool]rX   r  rY   r  rZ   r  r[   r  r\   r  r>   r	  r<   r-   r=   r-   r;   r-   r:   r#   rD   r
  r@   r-   rc   Dict[str, Any]rd   r  re   r  rf   r  rg   r  rE   r  rF   r  rh   r   r  r+   )2r_   r  r8   r-   rC   r  r:   r#   rR   r  rS   r  rT   r  rU   r  rV   r  rW   r  rX   r  rY   r  rZ   r  r[   r  r\   r  r>   r	  r<   r-   r=   r-   r;   r-   r@   r-   rD   r
  rE   r  rF   r  rh   r   r  r+   )NNrO   )r`   Iterable[str]ra   r  rb   r  rf   r  rh   r   r  zList[str | int])   NNr   NNN)r   r-   r   r  rw   Optional[models.Filter]rx   Optional[models.SearchParams]ry   r  rz   Optional[float]r{    Optional[models.ReadConsistency]r|   Optional[models.FusionQuery]rh   r   r  List[Document])r   r-   r   r  rw   r  rx   r  ry   r  rz   r  r{   r  r|   r  rh   r   r  List[Tuple[Document, float]])r  NNr   NN)rC   List[float]r   r  rw   r  rx   r  ry   r  rz   r  r{   r  rh   r   r  r  )r     g      ?NNNN)r   r-   r   r  r   r  r   floatrw   r  rx   r  rz   r  r{   r  rh   r   r  r  )rC   r  r   r  r   r  r   r   rw   r  rx   r  rz   r  r{   r  rh   r   r  r  )rC   r  r   r  r   r  r   r   rw   r  rx   r  rz   r  r{   r  rh   r   r  r  r   )rb   zOptional[List[str | int]]rh   r   r  r  )rb   zSequence[str | int]r  r  )$r_   r  rC   r  r:   r#   rD   r
  ri   r  r8   r  r>   r	  r<   r-   r=   r-   r;   r-   r@   r-   rg   r  rc   r  rd   r  re   r  rE   r  rF   r  r  r+   )r>   r   r  r   )r  zCallable[[float], float])
r   r   r8   r-   r<   r-   r=   r-   r  r   )
r`   r  ra   r  rb   r  rf   r  r  zFGenerator[tuple[list[str | int], list[models.PointStruct]], Any, None])
r`   r  ra   r  r<   r-   r=   r-   r  z
List[dict])r`   r  r  zList[models.VectorStruct])r_   r  rB   r   r8   r-   r:   r#   r;   r-   r@   r-   r>   r	  rC   r  r  None)r_   r  rB   r   r8   r-   r;   r-   r>   r	  r   z$Union[Embeddings, List[float], None]r  r!  )
r_   r  rB   r   r8   r-   r@   r-   r  r!  )
r_   r  r:   r#   rC   r  rD   r
  r  r!  )+r   r   r   r   r.   __annotations__r0   r2   r3   r#   r'   r   r   r   rG   propertyrB   rL   rN   classmethodrk   rn   r^   r   r}   r   r   r   r   r   r   r]   staticmethodr   r   r   rq   r   r   r6   r   r   r5   r   r    r!   r+   r+   )   s%   EN &K%"L#"K00 +/(5(;(;&#.$0$*OO$:$:7;"4$(+/2525 25 (	25
 &25 25 !25 "25 "25 525  25 "25 %)25h       ' '   +/*.-1)-"&!"! $!% $!%""$*OO$:$:#.$0&(5(;(;7;"446(*/1$$(+/?U$UU (U (	U
 +U 'U  U U U U U U U U U  !U" #U$ "%U& !'U( ")U* +U, &-U. 5/U0  1U2 $23U4 &5U6 -7U8 9U: ;U< "=U> %)?U@ AUB 
CU Un  +/(5(;(;"&!"! $!% $!%""$*OO$:$:#.$0&"47;$(+//<
$<
<
 (<
 &	<

  <
 <
 <
 <
 <
 <
 <
 <
 <
 <
 <
  "!<
" !#<
$ "%<
& '<
(  )<
* 5+<
, "-<
. %)/<
0 1<
2 
3<
 <
B +/-1 ( +	
   
6 *.7;+/8<6:11 1 (	1
 51 1 )1 61 41 1 
1B *.7;+/8<6:X
X
 X
 (	X

 5X
 X
 )X
 6X
 4X
 X
 
&X
z *.7;+/8<0
0
 0
 (	0

 50
 0
 )0
 60
 0
 
0
j  *.7;+/8<(
(
 (
 	(

 (
 ((
 5(
 )(
 6(
 (
 
(
Z  *.7;+/8<11 1 	1
 1 (1 51 )1 61 1 
1H  *.7;+/8<6
6
 6
 	6

 6
 (6
 56
 )6
 66
 6
 
&6
t *.>&> > 
	>(
  +/(5(;(;7;)+)-$*OO$:$:#.$0&"4$46(*/1$(+/#c$c'c &c 5	c
 'c 'c "c !c "c c  c c $2c &c -c  "!c" %)#c$ 
%c cJ & &* 

 
 !	

 "
 

 
$ +/-1 $ $ ( $ +	 $
  $ 
P $D ( !	
 " 
011 
#1f $  &	
    " ( 
 8 @$@@ @ 	@
 "@ ?@ 
@ @D $   	
 
 ( $% ( 5	
 
 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>r3     sg    "         - 0 3 . > ?2Y 2C q qr    