libs/partners/qdrant/langchain_qdrant/vectorstores.py PYTHON 2,333 lines View on github.com → Search inside
File is large — showing lines 1–2,000 of 2,333.
1from __future__ import annotations23import functools4import os5import uuid6import warnings7from collections.abc import Callable8from itertools import islice9from operator import itemgetter10from typing import TYPE_CHECKING, Any1112import numpy as np13from langchain_core._api.deprecation import deprecated14from langchain_core.documents import Document15from langchain_core.embeddings import Embeddings16from langchain_core.runnables.config import run_in_executor17from langchain_core.vectorstores import VectorStore18from qdrant_client import AsyncQdrantClient, QdrantClient19from qdrant_client.http import models20from qdrant_client.local.async_qdrant_local import AsyncQdrantLocal2122from langchain_qdrant._utils import maximal_marginal_relevance2324if TYPE_CHECKING:25    from collections.abc import AsyncGenerator, Generator, Iterable, Sequence2627    DictFilter = dict[str, str | int | bool | dict | list]28    MetadataFilter = DictFilter | models.Filter293031class QdrantException(Exception):  # noqa: N81832    """`Qdrant` related exceptions."""333435def sync_call_fallback(method: Callable) -> Callable:36    """Call the synchronous method if the async method is not implemented.3738    This decorator should only be used for methods that are defined as async in the39    class.4041    """4243    @functools.wraps(method)44    async def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:45        try:46            return await method(self, *args, **kwargs)47        except NotImplementedError:48            # If the async method is not implemented, call the synchronous method49            # by removing the first letter from the method name. For example,50            # if the async method is called `aadd_texts`, the synchronous method51            # will be called `aad_texts`.52            return await run_in_executor(53                None, getattr(self, method.__name__[1:]), *args, **kwargs54            )5556    return wrapper575859@deprecated(since="0.1.2", alternative="QdrantVectorStore", removal="0.5.0")60class Qdrant(VectorStore):61    """`Qdrant` vector store.6263    ```python64    from qdrant_client import QdrantClient65    from langchain_qdrant import Qdrant6667    client = QdrantClient()68    collection_name = "MyCollection"69    qdrant = Qdrant(client, collection_name, embedding_function)70    ```71    """7273    CONTENT_KEY: str = "page_content"74    METADATA_KEY: str = "metadata"75    VECTOR_NAME: str | None = None7677    def __init__(78        self,79        client: Any,80        collection_name: str,81        embeddings: Embeddings | None = None,82        content_payload_key: str = CONTENT_KEY,83        metadata_payload_key: str = METADATA_KEY,84        distance_strategy: str = "COSINE",85        vector_name: str | None = VECTOR_NAME,86        async_client: Any | None = None,87        embedding_function: Callable | None = None,  # deprecated88    ) -> None:89        """Initialize with necessary components."""90        if not isinstance(client, QdrantClient):91            msg = (92                f"client should be an instance of qdrant_client.QdrantClient, "93                f"got {type(client)}"94            )95            raise TypeError(msg)9697        if async_client is not None and not isinstance(async_client, AsyncQdrantClient):98            msg = (99                f"async_client should be an instance of qdrant_client.AsyncQdrantClient"100                f"got {type(async_client)}"101            )102            raise ValueError(msg)103104        if embeddings is None and embedding_function is None:105            msg = "`embeddings` value can't be None. Pass `embeddings` instance."106            raise ValueError(msg)107108        if embeddings is not None and embedding_function is not None:109            msg = (110                "Both `embeddings` and `embedding_function` are passed. "111                "Use `embeddings` only."112            )113            raise ValueError(msg)114115        self._embeddings = embeddings116        self._embeddings_function = embedding_function117        self.client: QdrantClient = client118        self.async_client: AsyncQdrantClient | None = async_client119        self.collection_name = collection_name120        self.content_payload_key = content_payload_key or self.CONTENT_KEY121        self.metadata_payload_key = metadata_payload_key or self.METADATA_KEY122        self.vector_name = vector_name or self.VECTOR_NAME123124        if embedding_function is not None:125            warnings.warn(126                "Using `embedding_function` is deprecated. "127                "Pass `Embeddings` instance to `embeddings` instead.",128                stacklevel=2,129            )130131        if not isinstance(embeddings, Embeddings):132            warnings.warn(133                "`embeddings` should be an instance of `Embeddings`."134                "Using `embeddings` as `embedding_function` which is deprecated",135                stacklevel=2,136            )137            self._embeddings_function = embeddings138            self._embeddings = None139140        self.distance_strategy = distance_strategy.upper()141142    @property143    def embeddings(self) -> Embeddings | None:144        return self._embeddings145146    def add_texts(147        self,148        texts: Iterable[str],149        metadatas: list[dict] | None = None,150        ids: Sequence[str] | None = None,151        batch_size: int = 64,152        **kwargs: Any,153    ) -> list[str]:154        """Run more texts through the embeddings and add to the `VectorStore`.155156        Args:157            texts: Iterable of strings to add to the `VectorStore`.158            metadatas: Optional list of metadatas associated with the texts.159            ids:160                Optional list of ids to associate with the texts. Ids have to be161                uuid-like strings.162            batch_size:163                How many vectors upload per-request.164                Default: `64`165            **kwargs: Additional keyword arguments.166167        Returns:168            List of ids from adding the texts into the `VectorStore`.169170        """171        added_ids = []172        for batch_ids, points in self._generate_rest_batches(173            texts, metadatas, ids, batch_size174        ):175            self.client.upsert(176                collection_name=self.collection_name, points=points, **kwargs177            )178            added_ids.extend(batch_ids)179180        return added_ids181182    @sync_call_fallback183    async def aadd_texts(184        self,185        texts: Iterable[str],186        metadatas: list[dict] | None = None,187        ids: Sequence[str] | None = None,188        batch_size: int = 64,189        **kwargs: Any,190    ) -> list[str]:191        """Run more texts through the embeddings and add to the `VectorStore`.192193        Args:194            texts: Iterable of strings to add to the `VectorStore`.195            metadatas: Optional list of metadatas associated with the texts.196            ids:197                Optional list of ids to associate with the texts. Ids have to be198                uuid-like strings.199            batch_size:200                How many vectors upload per-request.201                Default: `64`202            **kwargs: Additional keyword arguments.203204        Returns:205            List of ids from adding the texts into the `VectorStore`.206207        """208        if self.async_client is None or isinstance(209            self.async_client._client, AsyncQdrantLocal210        ):211            msg = "QdrantLocal cannot interoperate with sync and async clients"212            raise NotImplementedError(msg)213214        added_ids = []215        async for batch_ids, points in self._agenerate_rest_batches(216            texts, metadatas, ids, batch_size217        ):218            await self.async_client.upsert(219                collection_name=self.collection_name, points=points, **kwargs220            )221            added_ids.extend(batch_ids)222223        return added_ids224225    def similarity_search(226        self,227        query: str,228        k: int = 4,229        filter: MetadataFilter | None = None,  # noqa: A002230        search_params: models.SearchParams | None = None,231        offset: int = 0,232        score_threshold: float | None = None,233        consistency: models.ReadConsistency | None = None,234        **kwargs: Any,235    ) -> list[Document]:236        """Return docs most similar to query.237238        Args:239            query: Text to look up documents similar to.240            k: Number of Documents to return.241            filter: Filter by metadata.242            search_params: Additional search params243            offset:244                Offset of the first result to return.245                May be used to paginate results.246                Note: large offset values may cause performance issues.247            score_threshold:248                Define a minimal score threshold for the result.249                If defined, less similar results will not be returned.250                Score of the returned result might be higher or smaller than the251                threshold depending on the Distance function used.252                E.g. for cosine similarity only higher scores will be returned.253            consistency:254                Read consistency of the search. Defines how many replicas should be255                queried before returning the result.256                Values:257                - int - number of replicas to query, values should present in all258                        queried replicas259                - 'majority' - query all replicas, but return values present in the260                               majority of replicas261                - 'quorum' - query the majority of replicas, return values present in262                             all of them263                - 'all' - query all replicas, and return values present in all replicas264            **kwargs:265                Any other named arguments to pass through to QdrantClient.search()266267        Returns:268            List of `Document` objects most similar to the query.269270        """271        results = self.similarity_search_with_score(272            query,273            k,274            filter=filter,275            search_params=search_params,276            offset=offset,277            score_threshold=score_threshold,278            consistency=consistency,279            **kwargs,280        )281        return list(map(itemgetter(0), results))282283    @sync_call_fallback284    async def asimilarity_search(285        self,286        query: str,287        k: int = 4,288        filter: MetadataFilter | None = None,  # noqa: A002289        **kwargs: Any,290    ) -> list[Document]:291        """Return docs most similar to query.292293        Args:294            query: Text to look up documents similar to.295            k: Number of Documents to return.296            filter: Filter by metadata.297            **kwargs: Additional keyword arguments.298299        Returns:300            List of `Document` objects most similar to the query.301302        """303        results = await self.asimilarity_search_with_score(query, k, filter, **kwargs)304        return list(map(itemgetter(0), results))305306    def similarity_search_with_score(307        self,308        query: str,309        k: int = 4,310        filter: MetadataFilter | None = None,  # noqa: A002311        search_params: models.SearchParams | None = None,312        offset: int = 0,313        score_threshold: float | None = None,314        consistency: models.ReadConsistency | None = None,315        **kwargs: Any,316    ) -> list[tuple[Document, float]]:317        """Return docs most similar to query.318319        Args:320            query: Text to look up documents similar to.321            k: Number of Documents to return.322            filter: Filter by metadata.323            search_params: Additional search params324            offset:325                Offset of the first result to return.326                May be used to paginate results.327                Note: large offset values may cause performance issues.328            score_threshold:329                Define a minimal score threshold for the result.330                If defined, less similar results will not be returned.331                Score of the returned result might be higher or smaller than the332                threshold depending on the Distance function used.333                E.g. for cosine similarity only higher scores will be returned.334            consistency:335                Read consistency of the search. Defines how many replicas should be336                queried before returning the result.337                Values:338                - int - number of replicas to query, values should present in all339                        queried replicas340                - 'majority' - query all replicas, but return values present in the341                               majority of replicas342                - 'quorum' - query the majority of replicas, return values present in343                             all of them344                - 'all' - query all replicas, and return values present in all replicas345            **kwargs:346                Any other named arguments to pass through to QdrantClient.search()347348        Returns:349            List of documents most similar to the query text and distance for each.350351        """352        return self.similarity_search_with_score_by_vector(353            self._embed_query(query),354            k,355            filter=filter,356            search_params=search_params,357            offset=offset,358            score_threshold=score_threshold,359            consistency=consistency,360            **kwargs,361        )362363    @sync_call_fallback364    async def asimilarity_search_with_score(365        self,366        query: str,367        k: int = 4,368        filter: MetadataFilter | None = None,  # noqa: A002369        search_params: models.SearchParams | None = None,370        offset: int = 0,371        score_threshold: float | None = None,372        consistency: models.ReadConsistency | None = None,373        **kwargs: Any,374    ) -> list[tuple[Document, float]]:375        """Return docs most similar to query.376377        Args:378            query: Text to look up documents similar to.379            k: Number of Documents to return.380            filter: Filter by metadata.381            search_params: Additional search params382            offset:383                Offset of the first result to return.384                May be used to paginate results.385                Note: large offset values may cause performance issues.386            score_threshold:387                Define a minimal score threshold for the result.388                If defined, less similar results will not be returned.389                Score of the returned result might be higher or smaller than the390                threshold depending on the Distance function used.391                E.g. for cosine similarity only higher scores will be returned.392            consistency:393                Read consistency of the search. Defines how many replicas should be394                queried before returning the result.395                Values:396                - int - number of replicas to query, values should present in all397                        queried replicas398                - 'majority' - query all replicas, but return values present in the399                    majority of replicas400                - 'quorum' - query the majority of replicas, return values present in401                    all of them402                - 'all' - query all replicas, and return values present in all replicas403            **kwargs:404                Any other named arguments to pass through to405                AsyncQdrantClient.Search().406407        Returns:408            List of documents most similar to the query text and distance for each.409410        """411        query_embedding = await self._aembed_query(query)412        return await self.asimilarity_search_with_score_by_vector(413            query_embedding,414            k,415            filter=filter,416            search_params=search_params,417            offset=offset,418            score_threshold=score_threshold,419            consistency=consistency,420            **kwargs,421        )422423    def similarity_search_by_vector(424        self,425        embedding: list[float],426        k: int = 4,427        filter: MetadataFilter | None = None,  # noqa: A002428        search_params: models.SearchParams | None = None,429        offset: int = 0,430        score_threshold: float | None = None,431        consistency: models.ReadConsistency | None = None,432        **kwargs: Any,433    ) -> list[Document]:434        """Return docs most similar to embedding vector.435436        Args:437            embedding: Embedding vector to look up documents similar to.438            k: Number of Documents to return.439            filter: Filter by metadata.440            search_params: Additional search params441            offset:442                Offset of the first result to return.443                May be used to paginate results.444                Note: large offset values may cause performance issues.445            score_threshold:446                Define a minimal score threshold for the result.447                If defined, less similar results will not be returned.448                Score of the returned result might be higher or smaller than the449                threshold depending on the Distance function used.450                E.g. for cosine similarity only higher scores will be returned.451            consistency:452                Read consistency of the search. Defines how many replicas should be453                queried before returning the result.454                Values:455                - int - number of replicas to query, values should present in all456                        queried replicas457                - 'majority' - query all replicas, but return values present in the458                    majority of replicas459                - 'quorum' - query the majority of replicas, return values present in460                    all of them461                - 'all' - query all replicas, and return values present in all replicas462            **kwargs:463                Any other named arguments to pass through to QdrantClient.search()464465        Returns:466            List of `Document` objects most similar to the query.467468        """469        results = self.similarity_search_with_score_by_vector(470            embedding,471            k,472            filter=filter,473            search_params=search_params,474            offset=offset,475            score_threshold=score_threshold,476            consistency=consistency,477            **kwargs,478        )479        return list(map(itemgetter(0), results))480481    @sync_call_fallback482    async def asimilarity_search_by_vector(483        self,484        embedding: list[float],485        k: int = 4,486        filter: MetadataFilter | None = None,  # noqa: A002487        search_params: models.SearchParams | None = None,488        offset: int = 0,489        score_threshold: float | None = None,490        consistency: models.ReadConsistency | None = None,491        **kwargs: Any,492    ) -> list[Document]:493        """Return docs most similar to embedding vector.494495        Args:496            embedding: Embedding vector to look up documents similar to.497            k: Number of Documents to return.498            filter: Filter by metadata.499            search_params: Additional search params500            offset:501                Offset of the first result to return.502                May be used to paginate results.503                Note: large offset values may cause performance issues.504            score_threshold:505                Define a minimal score threshold for the result.506                If defined, less similar results will not be returned.507                Score of the returned result might be higher or smaller than the508                threshold depending on the Distance function used.509                E.g. for cosine similarity only higher scores will be returned.510            consistency:511                Read consistency of the search. Defines how many replicas should be512                queried before returning the result.513                Values:514                - int - number of replicas to query, values should present in all515                        queried replicas516                - 'majority' - query all replicas, but return values present in the517                    majority of replicas518                - 'quorum' - query the majority of replicas, return values present in519                    all of them520                - 'all' - query all replicas, and return values present in all replicas521            **kwargs:522                Any other named arguments to pass through to523                AsyncQdrantClient.Search().524525        Returns:526            List of `Document` objects most similar to the query.527528        """529        results = await self.asimilarity_search_with_score_by_vector(530            embedding,531            k,532            filter=filter,533            search_params=search_params,534            offset=offset,535            score_threshold=score_threshold,536            consistency=consistency,537            **kwargs,538        )539        return list(map(itemgetter(0), results))540541    def similarity_search_with_score_by_vector(542        self,543        embedding: list[float],544        k: int = 4,545        filter: MetadataFilter | None = None,  # noqa: A002546        search_params: models.SearchParams | None = None,547        offset: int = 0,548        score_threshold: float | None = None,549        consistency: models.ReadConsistency | None = None,550        **kwargs: Any,551    ) -> list[tuple[Document, float]]:552        """Return docs most similar to embedding vector.553554        Args:555            embedding: Embedding vector to look up documents similar to.556            k: Number of Documents to return.557            filter: Filter by metadata.558            search_params: Additional search params559            offset:560                Offset of the first result to return.561                May be used to paginate results.562                Note: large offset values may cause performance issues.563            score_threshold:564                Define a minimal score threshold for the result.565                If defined, less similar results will not be returned.566                Score of the returned result might be higher or smaller than the567                threshold depending on the Distance function used.568                E.g. for cosine similarity only higher scores will be returned.569            consistency:570                Read consistency of the search. Defines how many replicas should be571                queried before returning the result.572                Values:573                - int - number of replicas to query, values should present in all574                        queried replicas575                - 'majority' - query all replicas, but return values present in the576                    majority of replicas577                - 'quorum' - query the majority of replicas, return values present in578                    all of them579                - 'all' - query all replicas, and return values present in all replicas580            **kwargs:581                Any other named arguments to pass through to QdrantClient.search()582583        Returns:584            List of documents most similar to the query text and distance for each.585586        """587        if filter is not None and isinstance(filter, dict):588            warnings.warn(589                "Using dict as a `filter` is deprecated. Please use qdrant-client "590                "filters directly: "591                "https://qdrant.tech/documentation/concepts/filtering/",592                DeprecationWarning,593                stacklevel=2,594            )595            qdrant_filter = self._qdrant_filter_from_dict(filter)596        else:597            qdrant_filter = filter598599        query_vector = embedding600        if self.vector_name is not None:601            query_vector = (self.vector_name, embedding)  # type: ignore[assignment]602603        results = self.client.search(604            collection_name=self.collection_name,605            query_vector=query_vector,606            query_filter=qdrant_filter,607            search_params=search_params,608            limit=k,609            offset=offset,610            with_payload=True,611            with_vectors=False,  # LangChain does not expect vectors to be returned612            score_threshold=score_threshold,613            consistency=consistency,614            **kwargs,615        )616        return [617            (618                self._document_from_scored_point(619                    result,620                    self.collection_name,621                    self.content_payload_key,622                    self.metadata_payload_key,623                ),624                result.score,625            )626            for result in results627        ]628629    @sync_call_fallback630    async def asimilarity_search_with_score_by_vector(631        self,632        embedding: list[float],633        k: int = 4,634        filter: MetadataFilter | None = None,  # noqa: A002635        search_params: models.SearchParams | None = None,636        offset: int = 0,637        score_threshold: float | None = None,638        consistency: models.ReadConsistency | None = None,639        **kwargs: Any,640    ) -> list[tuple[Document, float]]:641        """Return docs most similar to embedding vector.642643        Args:644            embedding: Embedding vector to look up documents similar to.645            k: Number of Documents to return.646            filter: Filter by metadata.647            search_params: Additional search params648            offset:649                Offset of the first result to return.650                May be used to paginate results.651                Note: large offset values may cause performance issues.652            score_threshold:653                Define a minimal score threshold for the result.654                If defined, less similar results will not be returned.655                Score of the returned result might be higher or smaller than the656                threshold depending on the Distance function used.657                E.g. for cosine similarity only higher scores will be returned.658            consistency:659                Read consistency of the search. Defines how many replicas should be660                queried before returning the result.661                Values:662                - int - number of replicas to query, values should present in all663                        queried replicas664                - 'majority' - query all replicas, but return values present in the665                    majority of replicas666                - 'quorum' - query the majority of replicas, return values present in667                    all of them668                - 'all' - query all replicas, and return values present in all replicas669            **kwargs:670                Any other named arguments to pass through to671                AsyncQdrantClient.Search().672673        Returns:674            List of documents most similar to the query text and distance for each.675676        """677        if self.async_client is None or isinstance(678            self.async_client._client, AsyncQdrantLocal679        ):680            msg = "QdrantLocal cannot interoperate with sync and async clients"681            raise NotImplementedError(msg)682        if filter is not None and isinstance(filter, dict):683            warnings.warn(684                "Using dict as a `filter` is deprecated. Please use qdrant-client "685                "filters directly: "686                "https://qdrant.tech/documentation/concepts/filtering/",687                DeprecationWarning,688                stacklevel=2,689            )690            qdrant_filter = self._qdrant_filter_from_dict(filter)691        else:692            qdrant_filter = filter693694        query_vector = embedding695        if self.vector_name is not None:696            query_vector = (self.vector_name, embedding)  # type: ignore[assignment]697698        results = await self.async_client.search(699            collection_name=self.collection_name,700            query_vector=query_vector,701            query_filter=qdrant_filter,702            search_params=search_params,703            limit=k,704            offset=offset,705            with_payload=True,706            with_vectors=False,  # LangChain does not expect vectors to be returned707            score_threshold=score_threshold,708            consistency=consistency,709            **kwargs,710        )711        return [712            (713                self._document_from_scored_point(714                    result,715                    self.collection_name,716                    self.content_payload_key,717                    self.metadata_payload_key,718                ),719                result.score,720            )721            for result in results722        ]723724    def max_marginal_relevance_search(725        self,726        query: str,727        k: int = 4,728        fetch_k: int = 20,729        lambda_mult: float = 0.5,730        filter: MetadataFilter | None = None,  # noqa: A002731        search_params: models.SearchParams | None = None,732        score_threshold: float | None = None,733        consistency: models.ReadConsistency | None = None,734        **kwargs: Any,735    ) -> list[Document]:736        """Return docs selected using the maximal marginal relevance.737738        Maximal marginal relevance optimizes for similarity to query AND diversity739        among selected documents.740741        Args:742            query: Text to look up documents similar to.743            k: Number of Documents to return.744            fetch_k: Number of Documents to fetch to pass to MMR algorithm.745            lambda_mult: Number between `0` and `1` that determines the degree746                of diversity among the results with `0` corresponding to maximum747                diversity and `1` to minimum diversity.748            filter: Filter by metadata.749            search_params: Additional search params750            score_threshold:751                Define a minimal score threshold for the result.752                If defined, less similar results will not be returned.753                Score of the returned result might be higher or smaller than the754                threshold depending on the Distance function used.755                E.g. for cosine similarity only higher scores will be returned.756            consistency:757                Read consistency of the search. Defines how many replicas should be758                queried before returning the result.759                Values:760                - int - number of replicas to query, values should present in all761                        queried replicas762                - 'majority' - query all replicas, but return values present in the763                    majority of replicas764                - 'quorum' - query the majority of replicas, return values present in765                    all of them766                - 'all' - query all replicas, and return values present in all replicas767            **kwargs:768                Any other named arguments to pass through to QdrantClient.search()769770        Returns:771            List of `Document` objects selected by maximal marginal relevance.772773        """774        query_embedding = self._embed_query(query)775        return self.max_marginal_relevance_search_by_vector(776            query_embedding,777            k=k,778            fetch_k=fetch_k,779            lambda_mult=lambda_mult,780            filter=filter,781            search_params=search_params,782            score_threshold=score_threshold,783            consistency=consistency,784            **kwargs,785        )786787    @sync_call_fallback788    async def amax_marginal_relevance_search(789        self,790        query: str,791        k: int = 4,792        fetch_k: int = 20,793        lambda_mult: float = 0.5,794        filter: MetadataFilter | None = None,  # noqa: A002795        search_params: models.SearchParams | None = None,796        score_threshold: float | None = None,797        consistency: models.ReadConsistency | None = None,798        **kwargs: Any,799    ) -> list[Document]:800        """Return docs selected using the maximal marginal relevance.801802        Maximal marginal relevance optimizes for similarity to query AND diversity803        among selected documents.804805        Args:806            query: Text to look up documents similar to.807            k: Number of Documents to return.808            fetch_k: Number of Documents to fetch to pass to MMR algorithm.809            lambda_mult: Number between `0` and `1` that determines the degree810                        of diversity among the results with `0` corresponding811                        to maximum diversity and `1` to minimum diversity.812            filter: Filter by metadata.813            search_params: Additional search params814            score_threshold:815                Define a minimal score threshold for the result.816                If defined, less similar results will not be returned.817                Score of the returned result might be higher or smaller than the818                threshold depending on the Distance function used.819                E.g. for cosine similarity only higher scores will be returned.820            consistency:821                Read consistency of the search. Defines how many replicas should be822                queried before returning the result.823                Values:824                - `int` - number of replicas to query, values should present in all825                        queried replicas826                - `'majority'` - query all replicas, but return values present in the827                    majority of replicas828                - `'quorum'` - query the majority of replicas, return values present in829                    all of them830                - `'all'` - query all replicas, and return values present in all831                    replicas832            **kwargs:833                Any other named arguments to pass through to834                `AsyncQdrantClient.Search()`.835836        Returns:837            List of `Document` objects selected by maximal marginal relevance.838839        """840        query_embedding = await self._aembed_query(query)841        return await self.amax_marginal_relevance_search_by_vector(842            query_embedding,843            k=k,844            fetch_k=fetch_k,845            lambda_mult=lambda_mult,846            filter=filter,847            search_params=search_params,848            score_threshold=score_threshold,849            consistency=consistency,850            **kwargs,851        )852853    def max_marginal_relevance_search_by_vector(854        self,855        embedding: list[float],856        k: int = 4,857        fetch_k: int = 20,858        lambda_mult: float = 0.5,859        filter: MetadataFilter | None = None,  # noqa: A002860        search_params: models.SearchParams | None = None,861        score_threshold: float | None = None,862        consistency: models.ReadConsistency | None = None,863        **kwargs: Any,864    ) -> list[Document]:865        """Return docs selected using the maximal marginal relevance.866867        Maximal marginal relevance optimizes for similarity to query AND diversity868        among selected documents.869870        Args:871            embedding: Embedding to look up documents similar to.872            k: Number of Documents to return.873            fetch_k: Number of Documents to fetch to pass to MMR algorithm.874            lambda_mult: Number between `0` and `1` that determines the degree875                        of diversity among the results with `0` corresponding876                        to maximum diversity and `1` to minimum diversity.877            filter: Filter by metadata.878            search_params: Additional search params879            score_threshold:880                Define a minimal score threshold for the result.881                If defined, less similar results will not be returned.882                Score of the returned result might be higher or smaller than the883                threshold depending on the Distance function used.884                e.g. for cosine similarity only higher scores will be returned.885            consistency:886                Read consistency of the search. Defines how many replicas should be887                queried before returning the result.888                Values:889                - `int` - number of replicas to query, values should present in all890                        queried replicas891                - `'majority'` - query all replicas, but return values present in the892                    majority of replicas893                - `'quorum'` - query the majority of replicas, return values present in894                    all of them895                - `'all'` - query all replicas, and return values present in all896                    replicas897            **kwargs:898                Any other named arguments to pass through to `QdrantClient.search()`899900        Returns:901            List of `Document` objects selected by maximal marginal relevance.902903        """904        results = self.max_marginal_relevance_search_with_score_by_vector(905            embedding,906            k=k,907            fetch_k=fetch_k,908            lambda_mult=lambda_mult,909            filter=filter,910            search_params=search_params,911            score_threshold=score_threshold,912            consistency=consistency,913            **kwargs,914        )915        return list(map(itemgetter(0), results))916917    @sync_call_fallback918    async def amax_marginal_relevance_search_by_vector(919        self,920        embedding: list[float],921        k: int = 4,922        fetch_k: int = 20,923        lambda_mult: float = 0.5,924        filter: MetadataFilter | None = None,  # noqa: A002925        search_params: models.SearchParams | None = None,926        score_threshold: float | None = None,927        consistency: models.ReadConsistency | None = None,928        **kwargs: Any,929    ) -> list[Document]:930        """Return docs selected using the maximal marginal relevance.931932        Maximal marginal relevance optimizes for similarity to query AND diversity933        among selected documents.934935        Args:936            embedding: Embedding vector to look up documents similar to.937            k: Number of `Document` objects to return.938            fetch_k: Number of `Document` to fetch to pass to MMR algorithm.939            lambda_mult: Number between `0` and `1` that determines the degree940                        of diversity among the results with `0` corresponding941                        to maximum diversity and `1` to minimum diversity.942            filter: Filter by metadata.943            search_params: Additional search params944            score_threshold:945                Define a minimal score threshold for the result.946                If defined, less similar results will not be returned.947                Score of the returned result might be higher or smaller than the948                threshold depending on the Distance function used.949                E.g. for cosine similarity only higher scores will be returned.950            consistency:951                Read consistency of the search. Defines how many replicas should be952                queried before returning the result.953                Values:954                - `int` - number of replicas to query, values should present in all955                        queried replicas956                - `'majority'` - query all replicas, but return values present in the957                    majority of replicas958                - `'quorum'` - query the majority of replicas, return values present in959                    all of them960                - `'all'` - query all replicas, and return values present in all961                    replicas962            **kwargs:963                Any other named arguments to pass through to964                `AsyncQdrantClient.Search()`.965966        Returns:967            List of `Document` objects selected by maximal marginal relevance and968            distance for each.969970        """971        results = await self.amax_marginal_relevance_search_with_score_by_vector(972            embedding,973            k=k,974            fetch_k=fetch_k,975            lambda_mult=lambda_mult,976            filter=filter,977            search_params=search_params,978            score_threshold=score_threshold,979            consistency=consistency,980            **kwargs,981        )982        return list(map(itemgetter(0), results))983984    def max_marginal_relevance_search_with_score_by_vector(985        self,986        embedding: list[float],987        k: int = 4,988        fetch_k: int = 20,989        lambda_mult: float = 0.5,990        filter: MetadataFilter | None = None,  # noqa: A002991        search_params: models.SearchParams | None = None,992        score_threshold: float | None = None,993        consistency: models.ReadConsistency | None = None,994        **kwargs: Any,995    ) -> list[tuple[Document, float]]:996        """Return docs selected using the maximal marginal relevance.997998        Maximal marginal relevance optimizes for similarity to query AND diversity999        among selected documents.10001001        Args:1002            embedding: Embedding vector to look up documents similar to.1003            k: Number of Documents to return.1004            fetch_k: Number of Documents to fetch to pass to MMR algorithm.1005            lambda_mult: Number between `0` and `1` that determines the degree of1006                diversity among the results with `0` corresponding to maximum diversity1007                and `1` to minimum diversity.1008            filter: Filter by metadata.1009            search_params: Additional search params1010            score_threshold:1011                Define a minimal score threshold for the result.1012                If defined, less similar results will not be returned.1013                Score of the returned result might be higher or smaller than the1014                threshold depending on the Distance function used.1015                E.g. for cosine similarity only higher scores will be returned.1016            consistency:1017                Read consistency of the search. Defines how many replicas should be1018                queried before returning the result.1019                Values:1020                - int - number of replicas to query, values should present in all1021                        queried replicas1022                - 'majority' - query all replicas, but return values present in the1023                    majority of replicas1024                - 'quorum' - query the majority of replicas, return values present in1025                    all of them1026                - 'all' - query all replicas, and return values present in all replicas1027            **kwargs:1028                Any other named arguments to pass through to QdrantClient.search()10291030        Returns:1031            List of `Document` objects selected by maximal marginal relevance and1032                distance for each.1033        """1034        query_vector = embedding1035        if self.vector_name is not None:1036            query_vector = (self.vector_name, query_vector)  # type: ignore[assignment]10371038        results = self.client.search(1039            collection_name=self.collection_name,1040            query_vector=query_vector,1041            query_filter=filter,1042            search_params=search_params,1043            limit=fetch_k,1044            with_payload=True,1045            with_vectors=True,1046            score_threshold=score_threshold,1047            consistency=consistency,1048            **kwargs,1049        )1050        embeddings = [1051            result.vector.get(self.vector_name)  # type: ignore[index, union-attr]1052            if self.vector_name is not None1053            else result.vector1054            for result in results1055        ]1056        mmr_selected = maximal_marginal_relevance(1057            np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult1058        )1059        return [1060            (1061                self._document_from_scored_point(1062                    results[i],1063                    self.collection_name,1064                    self.content_payload_key,1065                    self.metadata_payload_key,1066                ),1067                results[i].score,1068            )1069            for i in mmr_selected1070        ]10711072    @sync_call_fallback1073    async def amax_marginal_relevance_search_with_score_by_vector(1074        self,1075        embedding: list[float],1076        k: int = 4,1077        fetch_k: int = 20,1078        lambda_mult: float = 0.5,1079        filter: MetadataFilter | None = None,  # noqa: A0021080        search_params: models.SearchParams | None = None,1081        score_threshold: float | None = None,1082        consistency: models.ReadConsistency | None = None,1083        **kwargs: Any,1084    ) -> list[tuple[Document, float]]:1085        """Return docs selected using the maximal marginal relevance.10861087        Maximal marginal relevance optimizes for similarity to query AND diversity1088        among selected documents.10891090        Args:1091            embedding: Embedding vector to look up documents similar to.1092            k: Number of Documents to return.1093            fetch_k: Number of Documents to fetch to pass to MMR algorithm.1094            lambda_mult: Number between `0` and `1` that determines the degree of1095                diversity among the results with `0` corresponding to maximum diversity1096                and `1` to minimum diversity.1097            filter: Filter by metadata.1098            search_params: Additional search params.1099            score_threshold: Define a minimal score threshold for the result.1100            consistency: Read consistency of the search.1101            **kwargs: Additional keyword arguments.11021103        Returns:1104            List of `Document` objects selected by maximal marginal relevance and1105                distance for each.1106        """1107        if self.async_client is None or isinstance(1108            self.async_client._client, AsyncQdrantLocal1109        ):1110            msg = "QdrantLocal cannot interoperate with sync and async clients"1111            raise NotImplementedError(msg)1112        query_vector = embedding1113        if self.vector_name is not None:1114            query_vector = (self.vector_name, query_vector)  # type: ignore[assignment]11151116        results = await self.async_client.search(1117            collection_name=self.collection_name,1118            query_vector=query_vector,1119            query_filter=filter,1120            search_params=search_params,1121            limit=fetch_k,1122            with_payload=True,1123            with_vectors=True,1124            score_threshold=score_threshold,1125            consistency=consistency,1126            **kwargs,1127        )1128        embeddings = [1129            result.vector.get(self.vector_name)  # type: ignore[index, union-attr]1130            if self.vector_name is not None1131            else result.vector1132            for result in results1133        ]1134        mmr_selected = maximal_marginal_relevance(1135            np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult1136        )1137        return [1138            (1139                self._document_from_scored_point(1140                    results[i],1141                    self.collection_name,1142                    self.content_payload_key,1143                    self.metadata_payload_key,1144                ),1145                results[i].score,1146            )1147            for i in mmr_selected1148        ]11491150    def delete(self, ids: list[str] | None = None, **kwargs: Any) -> bool | None:1151        """Delete by vector ID or other criteria.11521153        Args:1154            ids: List of ids to delete.1155            **kwargs: Other keyword arguments that subclasses might use.11561157        Returns:1158            True if deletion is successful, `False` otherwise.11591160        """1161        result = self.client.delete(1162            collection_name=self.collection_name,1163            points_selector=ids,1164        )1165        return result.status == models.UpdateStatus.COMPLETED11661167    @sync_call_fallback1168    async def adelete(self, ids: list[str] | None = None, **kwargs: Any) -> bool | None:1169        """Delete by vector ID or other criteria.11701171        Args:1172            ids: List of ids to delete.1173            **kwargs: Other keyword arguments that subclasses might use.11741175        Returns:1176            True if deletion is successful, `False` otherwise.11771178        """1179        if self.async_client is None or isinstance(1180            self.async_client._client, AsyncQdrantLocal1181        ):1182            msg = "QdrantLocal cannot interoperate with sync and async clients"1183            raise NotImplementedError(msg)11841185        result = await self.async_client.delete(1186            collection_name=self.collection_name,1187            points_selector=ids,1188        )11891190        return result.status == models.UpdateStatus.COMPLETED11911192    @classmethod1193    def from_texts(1194        cls: type[Qdrant],1195        texts: list[str],1196        embedding: Embeddings,1197        metadatas: list[dict] | None = None,1198        ids: Sequence[str] | None = None,1199        location: str | None = None,1200        url: str | None = None,1201        port: int | None = 6333,1202        grpc_port: int = 6334,1203        prefer_grpc: bool = False,  # noqa: FBT001, FBT0021204        https: bool | None = None,  # noqa: FBT0011205        api_key: str | None = None,1206        prefix: str | None = None,1207        timeout: int | None = None,1208        host: str | None = None,1209        path: str | None = None,1210        collection_name: str | None = None,1211        distance_func: str = "Cosine",1212        content_payload_key: str = CONTENT_KEY,1213        metadata_payload_key: str = METADATA_KEY,1214        vector_name: str | None = VECTOR_NAME,1215        batch_size: int = 64,1216        shard_number: int | None = None,1217        replication_factor: int | None = None,1218        write_consistency_factor: int | None = None,1219        on_disk_payload: bool | None = None,  # noqa: FBT0011220        hnsw_config: models.HnswConfigDiff | None = None,1221        optimizers_config: models.OptimizersConfigDiff | None = None,1222        wal_config: models.WalConfigDiff | None = None,1223        quantization_config: models.QuantizationConfig | None = None,1224        init_from: models.InitFrom | None = None,1225        on_disk: bool | None = None,  # noqa: FBT0011226        force_recreate: bool = False,  # noqa: FBT001, FBT0021227        **kwargs: Any,1228    ) -> Qdrant:1229        """Construct Qdrant wrapper from a list of texts.12301231        Args:1232            texts: A list of texts to be indexed in Qdrant.1233            embedding: A subclass of `Embeddings`, responsible for text vectorization.1234            metadatas:1235                An optional list of metadata. If provided it has to be of the same1236                length as a list of texts.1237            ids:1238                Optional list of ids to associate with the texts. Ids have to be1239                uuid-like strings.1240            location:1241                If ':memory:' - use in-memory Qdrant instance.1242                If `str` - use it as a `url` parameter.1243                If `None` - fallback to relying on `host` and `port` parameters.1244            url: either host or str of "scheme | None, host, port | None,1245                prefix | None".1246            port: Port of the REST API interface. Default: 63331247            grpc_port: Port of the gRPC interface. Default: 63341248            prefer_grpc:1249                If true - use gPRC interface whenever possible in custom methods.1250                Default: False1251            https: If true - use HTTPS(SSL) protocol. Default: None1252            api_key:1253                    API key for authentication in Qdrant Cloud. Default: None1254                    Can also be set via environment variable `QDRANT_API_KEY`.1255            prefix:1256                If not None - add prefix to the REST URL path.1257                Example: service/v1 will result in1258                    http://localhost:6333/service/v1/{qdrant-endpoint} for REST API.1259                Default: None1260            timeout:1261                Timeout for REST and gRPC API requests.1262                Default: 5.0 seconds for REST and unlimited for gRPC1263            host:1264                Host name of Qdrant service. If url and host are None, set to1265                'localhost'. Default: None1266            path:1267                Path in which the vectors will be stored while using local mode.1268                Default: None1269            collection_name:1270                Name of the Qdrant collection to be used. If not provided,1271                it will be created randomly. Default: None1272            distance_func:1273                Distance function. One of: "Cosine" / "Euclid" / "Dot".1274                Default: "Cosine"1275            content_payload_key:1276                A payload key used to store the content of the document.1277                Default: "page_content"1278            metadata_payload_key:1279                A payload key used to store the metadata of the document.1280                Default: "metadata"1281            vector_name:1282                Name of the vector to be used internally in Qdrant.1283                Default: None1284            batch_size:1285                How many vectors upload per-request.1286                Default: 641287            shard_number: Number of shards in collection. Default is 1, minimum is 1.1288            replication_factor:1289                Replication factor for collection. Default is 1, minimum is 1.1290                Defines how many copies of each shard will be created.1291                Have effect only in distributed mode.1292            write_consistency_factor:1293                Write consistency factor for collection. Default is 1, minimum is 1.1294                Defines how many replicas should apply the operation for us to consider1295                it successful. Increasing this number will make the collection more1296                resilient to inconsistencies, but will also make it fail if not enough1297                replicas are available.1298                Does not have any performance impact.1299                Have effect only in distributed mode.1300            on_disk_payload:1301                If true - point`s payload will not be stored in memory.1302                It will be read from the disk every time it is requested.1303                This setting saves RAM by (slightly) increasing the response time.1304                Note: those payload values that are involved in filtering and are1305                indexed - remain in RAM.1306            hnsw_config: Params for HNSW index1307            optimizers_config: Params for optimizer1308            wal_config: Params for Write-Ahead-Log1309            quantization_config:1310                Params for quantization, if None - quantization will be disabled1311            init_from:1312                Use data stored in another collection to initialize this collection1313            on_disk:1314                If true - vectors will be stored on disk, reducing memory usage.1315            force_recreate:1316                Force recreating the collection1317            **kwargs:1318                Additional arguments passed directly into REST client initialization13191320        This is a user-friendly interface that:13211322        1. Creates embeddings, one for each text1323        2. Initializes the Qdrant database as an in-memory docstore by default1324            (and overridable to a remote docstore)1325        3. Adds the text embeddings to the Qdrant database13261327        This is intended to be a quick way to get started.13281329        ```python1330        from langchain_qdrant import Qdrant1331        from langchain_openai import OpenAIEmbeddings13321333        embeddings = OpenAIEmbeddings()1334        qdrant = Qdrant.from_texts(texts, embeddings, "localhost")1335        ```1336        """1337        qdrant = cls.construct_instance(1338            texts,1339            embedding,1340            location,1341            url,1342            port,1343            grpc_port,1344            prefer_grpc,1345            https,1346            api_key,1347            prefix,1348            timeout,1349            host,1350            path,1351            collection_name,1352            distance_func,1353            content_payload_key,1354            metadata_payload_key,1355            vector_name,1356            shard_number,1357            replication_factor,1358            write_consistency_factor,1359            on_disk_payload,1360            hnsw_config,1361            optimizers_config,1362            wal_config,1363            quantization_config,1364            init_from,1365            on_disk,1366            force_recreate,1367            **kwargs,1368        )1369        qdrant.add_texts(texts, metadatas, ids, batch_size)1370        return qdrant13711372    @classmethod1373    def from_existing_collection(1374        cls: type[Qdrant],1375        embedding: Embeddings,1376        path: str | None = None,1377        collection_name: str | None = None,1378        location: str | None = None,1379        url: str | None = None,1380        port: int | None = 6333,1381        grpc_port: int = 6334,1382        prefer_grpc: bool = False,  # noqa: FBT001, FBT0021383        https: bool | None = None,  # noqa: FBT0011384        api_key: str | None = None,1385        prefix: str | None = None,1386        timeout: int | None = None,1387        host: str | None = None,1388        content_payload_key: str = CONTENT_KEY,1389        metadata_payload_key: str = METADATA_KEY,1390        distance_strategy: str = "COSINE",1391        vector_name: str | None = VECTOR_NAME,1392        **kwargs: Any,1393    ) -> Qdrant:1394        """Get instance of an existing Qdrant collection.13951396        This method will return the instance of the store without inserting any new1397        embeddings.1398        """1399        if collection_name is None:1400            msg = "Must specify collection_name. Received None."1401            raise ValueError(msg)14021403        client, async_client = cls._generate_clients(1404            location=location,1405            url=url,1406            port=port,1407            grpc_port=grpc_port,1408            prefer_grpc=prefer_grpc,1409            https=https,1410            api_key=api_key,1411            prefix=prefix,1412            timeout=timeout,1413            host=host,1414            path=path,1415            **kwargs,1416        )1417        return cls(1418            client=client,1419            async_client=async_client,1420            collection_name=collection_name,1421            embeddings=embedding,1422            content_payload_key=content_payload_key,1423            metadata_payload_key=metadata_payload_key,1424            distance_strategy=distance_strategy,1425            vector_name=vector_name,1426        )14271428    @classmethod1429    @sync_call_fallback1430    async def afrom_texts(1431        cls: type[Qdrant],1432        texts: list[str],1433        embedding: Embeddings,1434        metadatas: list[dict] | None = None,1435        ids: Sequence[str] | None = None,1436        location: str | None = None,1437        url: str | None = None,1438        port: int | None = 6333,1439        grpc_port: int = 6334,1440        prefer_grpc: bool = False,  # noqa: FBT001, FBT0021441        https: bool | None = None,  # noqa: FBT0011442        api_key: str | None = None,1443        prefix: str | None = None,1444        timeout: int | None = None,  # noqa: ASYNC1091445        host: str | None = None,1446        path: str | None = None,1447        collection_name: str | None = None,1448        distance_func: str = "Cosine",1449        content_payload_key: str = CONTENT_KEY,1450        metadata_payload_key: str = METADATA_KEY,1451        vector_name: str | None = VECTOR_NAME,1452        batch_size: int = 64,1453        shard_number: int | None = None,1454        replication_factor: int | None = None,1455        write_consistency_factor: int | None = None,1456        on_disk_payload: bool | None = None,  # noqa: FBT0011457        hnsw_config: models.HnswConfigDiff | None = None,1458        optimizers_config: models.OptimizersConfigDiff | None = None,1459        wal_config: models.WalConfigDiff | None = None,1460        quantization_config: models.QuantizationConfig | None = None,1461        init_from: models.InitFrom | None = None,1462        on_disk: bool | None = None,  # noqa: FBT0011463        force_recreate: bool = False,  # noqa: FBT001, FBT0021464        **kwargs: Any,1465    ) -> Qdrant:1466        """Construct Qdrant wrapper from a list of texts.14671468        Args:1469            texts: A list of texts to be indexed in Qdrant.1470            embedding: A subclass of `Embeddings`, responsible for text vectorization.1471            metadatas:1472                An optional list of metadata. If provided it has to be of the same1473                length as a list of texts.1474            ids:1475                Optional list of ids to associate with the texts. Ids have to be1476                uuid-like strings.1477            location:1478                If ':memory:' - use in-memory Qdrant instance.1479                If `str` - use it as a `url` parameter.1480                If `None` - fallback to relying on `host` and `port` parameters.1481            url: either host or str of "scheme | None, host, port | None,1482                prefix | None".1483            port: Port of the REST API interface. Default: 63331484            grpc_port: Port of the gRPC interface. Default: 63341485            prefer_grpc:1486                If true - use gPRC interface whenever possible in custom methods.1487                Default: False1488            https: If true - use HTTPS(SSL) protocol. Default: None1489            api_key:1490                    API key for authentication in Qdrant Cloud. Default: None1491                    Can also be set via environment variable `QDRANT_API_KEY`.1492            prefix:1493                If not None - add prefix to the REST URL path.1494                Example: service/v1 will result in1495                    http://localhost:6333/service/v1/{qdrant-endpoint} for REST API.1496                Default: None1497            timeout:1498                Timeout for REST and gRPC API requests.1499                Default: 5.0 seconds for REST and unlimited for gRPC1500            host:1501                Host name of Qdrant service. If url and host are None, set to1502                'localhost'. Default: None1503            path:1504                Path in which the vectors will be stored while using local mode.1505                Default: None1506            collection_name:1507                Name of the Qdrant collection to be used. If not provided,1508                it will be created randomly. Default: None1509            distance_func:1510                Distance function. One of: "Cosine" / "Euclid" / "Dot".1511                Default: "Cosine"1512            content_payload_key:1513                A payload key used to store the content of the document.1514                Default: "page_content"1515            metadata_payload_key:1516                A payload key used to store the metadata of the document.1517                Default: "metadata"1518            vector_name:1519                Name of the vector to be used internally in Qdrant.1520                Default: None1521            batch_size:1522                How many vectors upload per-request.1523                Default: 641524            shard_number: Number of shards in collection. Default is 1, minimum is 1.1525            replication_factor:1526                Replication factor for collection. Default is 1, minimum is 1.1527                Defines how many copies of each shard will be created.1528                Have effect only in distributed mode.1529            write_consistency_factor:1530                Write consistency factor for collection. Default is 1, minimum is 1.1531                Defines how many replicas should apply the operation for us to consider1532                it successful. Increasing this number will make the collection more1533                resilient to inconsistencies, but will also make it fail if not enough1534                replicas are available.1535                Does not have any performance impact.1536                Have effect only in distributed mode.1537            on_disk_payload:1538                If true - point`s payload will not be stored in memory.1539                It will be read from the disk every time it is requested.1540                This setting saves RAM by (slightly) increasing the response time.1541                Note: those payload values that are involved in filtering and are1542                indexed - remain in RAM.1543            hnsw_config: Params for HNSW index1544            optimizers_config: Params for optimizer1545            wal_config: Params for Write-Ahead-Log1546            quantization_config:1547                Params for quantization, if None - quantization will be disabled1548            init_from:1549                Use data stored in another collection to initialize this collection1550            on_disk:1551                If true - point`s payload will not be stored in memory.1552                It will be read from the disk every time it is requested.1553                This setting saves RAM by (slightly) increasing the response time.1554                Note: those payload values that are involved in filtering and are1555                indexed - remain in RAM.1556            force_recreate:1557                Force recreating the collection1558            **kwargs:1559                Additional arguments passed directly into REST client initialization15601561        This is a user-friendly interface that:15621563        1. Creates embeddings, one for each text1564        2. Initializes the Qdrant database as an in-memory docstore by default1565            (and overridable to a remote docstore)1566        3. Adds the text embeddings to the Qdrant database15671568        This is intended to be a quick way to get started.15691570        ```python1571        from langchain_qdrant import Qdrant1572        from langchain_openai import OpenAIEmbeddings15731574        embeddings = OpenAIEmbeddings()1575        qdrant = await Qdrant.afrom_texts(texts, embeddings, "localhost")1576        ```1577        """1578        qdrant = await cls.aconstruct_instance(1579            texts,1580            embedding,1581            location,1582            url,1583            port,1584            grpc_port,1585            prefer_grpc,1586            https,1587            api_key,1588            prefix,1589            timeout,1590            host,1591            path,1592            collection_name,1593            distance_func,1594            content_payload_key,1595            metadata_payload_key,1596            vector_name,1597            shard_number,1598            replication_factor,1599            write_consistency_factor,1600            on_disk_payload,1601            hnsw_config,1602            optimizers_config,1603            wal_config,1604            quantization_config,1605            init_from,1606            on_disk,1607            force_recreate,1608            **kwargs,1609        )1610        await qdrant.aadd_texts(texts, metadatas, ids, batch_size)1611        return qdrant16121613    @classmethod1614    def construct_instance(1615        cls: type[Qdrant],1616        texts: list[str],1617        embedding: Embeddings,1618        location: str | None = None,1619        url: str | None = None,1620        port: int | None = 6333,1621        grpc_port: int = 6334,1622        prefer_grpc: bool = False,  # noqa: FBT001, FBT0021623        https: bool | None = None,  # noqa: FBT0011624        api_key: str | None = None,1625        prefix: str | None = None,1626        timeout: int | None = None,1627        host: str | None = None,1628        path: str | None = None,1629        collection_name: str | None = None,1630        distance_func: str = "Cosine",1631        content_payload_key: str = CONTENT_KEY,1632        metadata_payload_key: str = METADATA_KEY,1633        vector_name: str | None = VECTOR_NAME,1634        shard_number: int | None = None,1635        replication_factor: int | None = None,1636        write_consistency_factor: int | None = None,1637        on_disk_payload: bool | None = None,  # noqa: FBT0011638        hnsw_config: models.HnswConfigDiff | None = None,1639        optimizers_config: models.OptimizersConfigDiff | None = None,1640        wal_config: models.WalConfigDiff | None = None,1641        quantization_config: models.QuantizationConfig | None = None,1642        init_from: models.InitFrom | None = None,1643        on_disk: bool | None = None,  # noqa: FBT0011644        force_recreate: bool = False,  # noqa: FBT001, FBT0021645        **kwargs: Any,1646    ) -> Qdrant:1647        # Just do a single quick embedding to get vector size1648        partial_embeddings = embedding.embed_documents(texts[:1])1649        vector_size = len(partial_embeddings[0])1650        collection_name = collection_name or uuid.uuid4().hex1651        distance_func = distance_func.upper()1652        client, async_client = cls._generate_clients(1653            location=location,1654            url=url,1655            port=port,1656            grpc_port=grpc_port,1657            prefer_grpc=prefer_grpc,1658            https=https,1659            api_key=api_key,1660            prefix=prefix,1661            timeout=timeout,1662            host=host,1663            path=path,1664            **kwargs,1665        )1666        collection_exists = client.collection_exists(collection_name)16671668        if collection_exists and force_recreate:1669            client.delete_collection(collection_name)1670            collection_exists = False16711672        if collection_exists:1673            # Get the vector configuration of the existing collection and vector, if it1674            # was specified. If the old configuration does not match the current one,1675            # an exception is raised.1676            collection_info = client.get_collection(collection_name=collection_name)1677            current_vector_config = collection_info.config.params.vectors1678            if isinstance(current_vector_config, dict) and vector_name is not None:1679                if vector_name not in current_vector_config:1680                    msg = (1681                        f"Existing Qdrant collection {collection_name} does not "1682                        f"contain vector named {vector_name}. Did you mean one of the "1683                        f"existing vectors: {', '.join(current_vector_config.keys())}? "1684                        f"If you want to recreate the collection, set `force_recreate` "1685                        f"parameter to `True`."1686                    )1687                    raise QdrantException(msg)1688                current_vector_config = current_vector_config.get(vector_name)  # type: ignore[assignment]1689            elif isinstance(current_vector_config, dict) and vector_name is None:1690                msg = (1691                    f"Existing Qdrant collection {collection_name} uses named vectors. "1692                    f"If you want to reuse it, please set `vector_name` to any of the "1693                    f"existing named vectors: "1694                    f"{', '.join(current_vector_config.keys())}."1695                    f"If you want to recreate the collection, set `force_recreate` "1696                    f"parameter to `True`."1697                )1698                raise QdrantException(msg)1699            elif (1700                not isinstance(current_vector_config, dict) and vector_name is not None1701            ):1702                msg = (1703                    f"Existing Qdrant collection {collection_name} doesn't use named "1704                    f"vectors. If you want to reuse it, please set `vector_name` to "1705                    f"`None`. If you want to recreate the collection, set "1706                    f"`force_recreate` parameter to `True`."1707                )1708                raise QdrantException(msg)1709            if not isinstance(current_vector_config, models.VectorParams):1710                msg = (1711                    "Expected current_vector_config to be an instance of "1712                    f"models.VectorParams, but got {type(current_vector_config)}"1713                )1714                raise ValueError(msg)1715            # Check if the vector configuration has the same dimensionality.1716            if current_vector_config.size != vector_size:1717                msg = (1718                    f"Existing Qdrant collection is configured for vectors with "1719                    f"{current_vector_config.size} "1720                    f"dimensions. Selected embeddings are {vector_size}-dimensional. "1721                    f"If you want to recreate the collection, set `force_recreate` "1722                    f"parameter to `True`."1723                )1724                raise QdrantException(msg)17251726            current_distance_func = (1727                current_vector_config.distance.name.upper()  # type: ignore[union-attr]1728            )1729            if current_distance_func != distance_func:1730                msg = (1731                    f"Existing Qdrant collection is configured for "1732                    f"{current_distance_func} similarity, but requested "1733                    f"{distance_func}. Please set `distance_func` parameter to "1734                    f"`{current_distance_func}` if you want to reuse it. "1735                    f"If you want to recreate the collection, set `force_recreate` "1736                    f"parameter to `True`."1737                )1738                raise QdrantException(msg)1739        else:1740            vectors_config = models.VectorParams(1741                size=vector_size,1742                distance=models.Distance[distance_func],1743                on_disk=on_disk,1744            )17451746            # If vector name was provided, we're going to use the named vectors feature1747            # with just a single vector.1748            if vector_name is not None:1749                vectors_config = {  # type: ignore[assignment]1750                    vector_name: vectors_config,1751                }17521753            client.create_collection(1754                collection_name=collection_name,1755                vectors_config=vectors_config,1756                shard_number=shard_number,1757                replication_factor=replication_factor,1758                write_consistency_factor=write_consistency_factor,1759                on_disk_payload=on_disk_payload,1760                hnsw_config=hnsw_config,1761                optimizers_config=optimizers_config,1762                wal_config=wal_config,1763                quantization_config=quantization_config,1764                init_from=init_from,1765                timeout=timeout,  # type: ignore[arg-type]1766            )1767        return cls(1768            client=client,1769            collection_name=collection_name,1770            embeddings=embedding,1771            content_payload_key=content_payload_key,1772            metadata_payload_key=metadata_payload_key,1773            distance_strategy=distance_func,1774            vector_name=vector_name,1775            async_client=async_client,1776        )17771778    @classmethod1779    async def aconstruct_instance(1780        cls: type[Qdrant],1781        texts: list[str],1782        embedding: Embeddings,1783        location: str | None = None,1784        url: str | None = None,1785        port: int | None = 6333,1786        grpc_port: int = 6334,1787        prefer_grpc: bool = False,  # noqa: FBT001, FBT0021788        https: bool | None = None,  # noqa: FBT0011789        api_key: str | None = None,1790        prefix: str | None = None,1791        timeout: int | None = None,  # noqa: ASYNC1091792        host: str | None = None,1793        path: str | None = None,1794        collection_name: str | None = None,1795        distance_func: str = "Cosine",1796        content_payload_key: str = CONTENT_KEY,1797        metadata_payload_key: str = METADATA_KEY,1798        vector_name: str | None = VECTOR_NAME,1799        shard_number: int | None = None,1800        replication_factor: int | None = None,1801        write_consistency_factor: int | None = None,1802        on_disk_payload: bool | None = None,  # noqa: FBT0011803        hnsw_config: models.HnswConfigDiff | None = None,1804        optimizers_config: models.OptimizersConfigDiff | None = None,1805        wal_config: models.WalConfigDiff | None = None,1806        quantization_config: models.QuantizationConfig | None = None,1807        init_from: models.InitFrom | None = None,1808        on_disk: bool | None = None,  # noqa: FBT0011809        force_recreate: bool = False,  # noqa: FBT001, FBT0021810        **kwargs: Any,1811    ) -> Qdrant:1812        # Just do a single quick embedding to get vector size1813        partial_embeddings = await embedding.aembed_documents(texts[:1])1814        vector_size = len(partial_embeddings[0])1815        collection_name = collection_name or uuid.uuid4().hex1816        distance_func = distance_func.upper()1817        client, async_client = cls._generate_clients(1818            location=location,1819            url=url,1820            port=port,1821            grpc_port=grpc_port,1822            prefer_grpc=prefer_grpc,1823            https=https,1824            api_key=api_key,1825            prefix=prefix,1826            timeout=timeout,1827            host=host,1828            path=path,1829            **kwargs,1830        )18311832        collection_exists = client.collection_exists(collection_name)18331834        if collection_exists and force_recreate:1835            client.delete_collection(collection_name)1836            collection_exists = False18371838        if collection_exists:1839            # Get the vector configuration of the existing collection and vector, if it1840            # was specified. If the old configuration does not match the current one,1841            # an exception is raised.1842            collection_info = client.get_collection(collection_name=collection_name)1843            current_vector_config = collection_info.config.params.vectors1844            if isinstance(current_vector_config, dict) and vector_name is not None:1845                if vector_name not in current_vector_config:1846                    msg = (1847                        f"Existing Qdrant collection {collection_name} does not "1848                        f"contain vector named {vector_name}. Did you mean one of the "1849                        f"existing vectors: {', '.join(current_vector_config.keys())}? "1850                        f"If you want to recreate the collection, set `force_recreate` "1851                        f"parameter to `True`."1852                    )1853                    raise QdrantException(msg)1854                current_vector_config = current_vector_config.get(vector_name)  # type: ignore[assignment]1855            elif isinstance(current_vector_config, dict) and vector_name is None:1856                msg = (1857                    f"Existing Qdrant collection {collection_name} uses named vectors. "1858                    f"If you want to reuse it, please set `vector_name` to any of the "1859                    f"existing named vectors: "1860                    f"{', '.join(current_vector_config.keys())}."1861                    f"If you want to recreate the collection, set `force_recreate` "1862                    f"parameter to `True`."1863                )1864                raise QdrantException(msg)1865            elif (1866                not isinstance(current_vector_config, dict) and vector_name is not None1867            ):1868                msg = (1869                    f"Existing Qdrant collection {collection_name} doesn't use named "1870                    f"vectors. If you want to reuse it, please set `vector_name` to "1871                    f"`None`. If you want to recreate the collection, set "1872                    f"`force_recreate` parameter to `True`."1873                )1874                raise QdrantException(msg)1875            if not isinstance(current_vector_config, models.VectorParams):1876                msg = (1877                    "Expected current_vector_config to be an instance of "1878                    f"models.VectorParams, but got {type(current_vector_config)}"1879                )1880                raise ValueError(msg)18811882            # Check if the vector configuration has the same dimensionality.1883            if current_vector_config.size != vector_size:1884                msg = (1885                    f"Existing Qdrant collection is configured for vectors with "1886                    f"{current_vector_config.size} "1887                    f"dimensions. Selected embeddings are {vector_size}-dimensional. "1888                    f"If you want to recreate the collection, set `force_recreate` "1889                    f"parameter to `True`."1890                )1891                raise QdrantException(msg)18921893            current_distance_func = (1894                current_vector_config.distance.name.upper()  # type: ignore[union-attr]1895            )1896            if current_distance_func != distance_func:1897                msg = (1898                    f"Existing Qdrant collection is configured for "1899                    f"{current_vector_config.distance} "  # type: ignore[union-attr]1900                    f"similarity. Please set `distance_func` parameter to "1901                    f"`{distance_func}` if you want to reuse it. If you want to "1902                    f"recreate the collection, set `force_recreate` parameter to "1903                    f"`True`."1904                )1905                raise QdrantException(msg)1906        else:1907            vectors_config = models.VectorParams(1908                size=vector_size,1909                distance=models.Distance[distance_func],1910                on_disk=on_disk,1911            )19121913            # If vector name was provided, we're going to use the named vectors feature1914            # with just a single vector.1915            if vector_name is not None:1916                vectors_config = {  # type: ignore[assignment]1917                    vector_name: vectors_config,1918                }19191920            client.create_collection(1921                collection_name=collection_name,1922                vectors_config=vectors_config,1923                shard_number=shard_number,1924                replication_factor=replication_factor,1925                write_consistency_factor=write_consistency_factor,1926                on_disk_payload=on_disk_payload,1927                hnsw_config=hnsw_config,1928                optimizers_config=optimizers_config,1929                wal_config=wal_config,1930                quantization_config=quantization_config,1931                init_from=init_from,1932                timeout=timeout,  # type: ignore[arg-type]1933            )1934        return cls(1935            client=client,1936            collection_name=collection_name,1937            embeddings=embedding,1938            content_payload_key=content_payload_key,1939            metadata_payload_key=metadata_payload_key,1940            distance_strategy=distance_func,1941            vector_name=vector_name,1942            async_client=async_client,1943        )19441945    @staticmethod1946    def _cosine_relevance_score_fn(distance: float) -> float:1947        """Normalize the distance to a score on a scale [0, 1]."""1948        return (distance + 1.0) / 2.019491950    def _select_relevance_score_fn(self) -> Callable[[float], float]:1951        """Your 'correct' relevance function may differ depending on a few things.19521953        For example:1954        - The distance / similarity metric used by the VectorStore1955        - The scale of your embeddings (OpenAI's are unit normed. Many others are not!)1956        - Embedding dimensionality1957        - etc.1958        """1959        if self.distance_strategy == "COSINE":1960            return self._cosine_relevance_score_fn1961        if self.distance_strategy == "DOT":1962            return self._max_inner_product_relevance_score_fn1963        if self.distance_strategy == "EUCLID":1964            return self._euclidean_relevance_score_fn1965        msg = (1966            "Unknown distance strategy, must be cosine, max_inner_product, or euclidean"1967        )1968        raise ValueError(msg)19691970    def _similarity_search_with_relevance_scores(1971        self,1972        query: str,1973        k: int = 4,1974        **kwargs: Any,1975    ) -> list[tuple[Document, float]]:1976        """Return docs and relevance scores in the range `[0, 1]`.19771978        `0` is dissimilar, `1` is most similar.19791980        Args:1981            query: input text1982            k: Number of Documents to return.1983            **kwargs: Kwargs to be passed to similarity search.19841985                Should include `score_threshold`, an optional floating point value1986                between `0` to `1` to filter the resulting set of retrieved docs.19871988        Returns:1989            List of tuples of `(doc, similarity_score)`19901991        """1992        return self.similarity_search_with_score(query, k, **kwargs)19931994    @sync_call_fallback1995    async def _asimilarity_search_with_relevance_scores(1996        self,1997        query: str,1998        k: int = 4,1999        **kwargs: Any,2000    ) -> list[tuple[Document, float]]:

Code quality findings 2

Ensure functions have docstrings for documentation
info maintainability missing-docstring
async def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def embeddings(self) -> Embeddings | None:

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.

Generated by searchcode.com · powered by code_get_file + code_get_findings