viruPVS/langchain-docs huggingface dataset:
text=texts,
            metadata=metadatas,
            embedding_data=texts,
            embedding_tensor="embedding",
            embedding_function=self._embedding_function.embed_documents,  # type: ignore
            return_ids=True,
            **kwargs,
        )
    def _search_tql(
        self,
        tql: Optional[str],
        exec_option: Optional[str] = None,
        **kwargs: Any,
    ) -> List[Document]:
        """Function for performing tql_search.
        Args:
            tql (str): TQL Query string for direct evaluation.
                Available only for `compute_engine` and `tensor_db`.
            exec_option (str, optional): Supports 3 ways to search.
                Could be "python", "compute_engine" or "tensor_db". Default is "python".
                - ``python`` - Pure-python implementation for the client.
                    WARNING: not recommended for big datasets due to potential memory
                    issues.
                - ``compute_engine`` - C++ implementation of Deep Lake Compute
                    Engine for the client. Not for in-memory or local datasets.
                - ``tensor_db`` - Hosted Managed Tensor Database for storage
                    and query execution. Only for data in Deep Lake Managed Database.
                        Use runtime = {"db_engine": True} during dataset creation.
            return_score (bool): Return score with document. Default is False.
        Returns:
            Tuple[List[Document], List[Tuple[Document, float]]] - A tuple of two lists.
                The first list contains Documents, and the second list contains
                tuples of Document and float score.
        Raises:
            ValueError: If return_score is True but some condition is not met.
        """
        result = self.vectorstore.search(
            query=tql,
"""
        result = self.vectorstore.search(
            query=tql,
            exec_option=exec_option,
        )
        metadatas = result["metadata"]
        texts = result["text"]
        docs = [
            Document(
                page_content=text,
                metadata=metadata,
            )
            for text, metadata in zip(texts, metadatas)
        ]
        if kwargs:
            unsupported_argument = next(iter(kwargs))
            if kwargs[unsupported_argument] is not False:
                raise ValueError(
                    f"specifying {unsupported_argument} is "
                    "not supported with tql search."
                )
        return docs
    def _search(
        self,
        query: Optional[str] = None,
        embedding: Optional[Union[List[float], np.ndarray]] = None,
        embedding_function: Optional[Callable] = None,
        k: int = 4,
        distance_metric: Optional[str] = None,
        use_maximal_marginal_relevance: bool = False,
        fetch_k: Optional[int] = 20,
        filter: Optional[Union[Dict, Callable]] = None,
        return_score: bool = False,
        exec_option: Optional[str] = None,
        deep_memory: bool = False,
        **kwargs: Any,
    ) -> Any[List[Document], List[Tuple[Document, float]]]:
        """
        Return docs similar to query.
        Args:
            query (str, optional): Text to look up similar docs.
            embedding (Union[List[float], np.ndarray], optional): Query's embedding.
            embedding_function (Callable, optional): Function to convert `query`
                into embedding.
            k (int): Number of Documents to return.
into embedding.
            k (int): Number of Documents to return.
            distance_metric (Optional[str], optional): `L2` for Euclidean, `L1` for
                Nuclear, `max` for L-infinity distance, `cos` for cosine similarity,
                'dot' for dot product.
            filter (Union[Dict, Callable], optional): Additional filter prior
                to the embedding search.
                - ``Dict`` - Key-value search on tensors of htype json, on an
                    AND basis (a sample must satisfy all key-value filters to be True)
                    Dict = {"tensor_name_1": {"key": value},
                            "tensor_name_2": {"key": value}}
                - ``Function`` - Any function compatible with `deeplake.filter`.
            use_maximal_marginal_relevance (bool): Use maximal marginal relevance.
            fetch_k (int): Number of Documents for MMR algorithm.
            return_score (bool): Return the score.
            exec_option (str, optional): Supports 3 ways to perform searching.
                Could be "python", "compute_engine" or "tensor_db".
                - ``python`` - Pure-python implementation for the client.
                    WARNING: not recommended for big datasets.
                - ``compute_engine`` - C++ implementation of Deep Lake Compute
                    Engine for the client. Not for in-memory or local datasets.
                - ``tensor_db`` - Hosted Managed Tensor Database for storage
                    and query execution. Only for data in Deep Lake Managed Database.
                    Use runtime = {"db_engine": True} during dataset creation.
            deep_memory (bool): Whether to use the Deep Memory model for improving
                search results. Defaults to False if deep_memory is not specified in
                the Vector Store initialization. If True, the distance metric is set
the Vector Store initialization. If True, the distance metric is set
                to "deepmemory_distance", which represents the metric with which the
                model was trained. The search is performed using the Deep Memory model.
                If False, the distance metric is set to "COS" or whatever distance
                metric user specifies.
            **kwargs: Additional keyword arguments.
        Returns:
            List of Documents by the specified distance metric,
            if return_score True, return a tuple of (Document, score)
        Raises:
            ValueError: if both `embedding` and `embedding_function` are not specified.
        """
        if kwargs.get("tql"):
            return self._search_tql(
                tql=kwargs["tql"],
                exec_option=exec_option,
                return_score=return_score,
                embedding=embedding,
                embedding_function=embedding_function,
                distance_metric=distance_metric,
                use_maximal_marginal_relevance=use_maximal_marginal_relevance,
                filter=filter,
            )
        if embedding_function:
            if isinstance(embedding_function, Embeddings):
                _embedding_function = embedding_function.embed_query
            else:
                _embedding_function = embedding_function
        elif self._embedding_function:
            _embedding_function = self._embedding_function.embed_query
        else:
            _embedding_function = None
        if embedding is None:
            if _embedding_function is None:
                raise ValueError(
                    "Either `embedding` or `embedding_function` needs to be"
                    " specified."
                )
            embedding = _embedding_function(query) if query else None
        if isinstance(embedding, list):
            embedding = np.array(embedding, dtype=np.float32)
            if len(embedding.shape) > 1:
if len(embedding.shape) > 1:
                embedding = embedding[0]
        result = self.vectorstore.search(
            embedding=embedding,
            k=fetch_k if use_maximal_marginal_relevance else k,
            distance_metric=distance_metric,
            filter=filter,
            exec_option=exec_option,
            return_tensors=["embedding", "metadata", "text", self._id_tensor_name],
            deep_memory=deep_memory,
        )
        scores = result["score"]
        embeddings = result["embedding"]
        metadatas = result["metadata"]
        texts = result["text"]
        if use_maximal_marginal_relevance:
            lambda_mult = kwargs.get("lambda_mult", 0.5)
            indices = maximal_marginal_relevance(  # type: ignore
                embedding,  # type: ignore
                embeddings,
                k=min(k, len(texts)),
                lambda_mult=lambda_mult,
            )
            scores = [scores[i] for i in indices]
            texts = [texts[i] for i in indices]
            metadatas = [metadatas[i] for i in indices]
        docs = [
            Document(
                page_content=text,
                metadata=metadata,
            )
            for text, metadata in zip(texts, metadatas)
        ]
        if return_score:
            return [(doc, score) for doc, score in zip(docs, scores)]
        return docs
[docs]    def similarity_search(
        self,
        query: str,
        k: int = 4,
        **kwargs: Any,
    ) -> List[Document]:
        """
        Return docs most similar to query.
        Examples:
            >>> # Search using an embedding
Examples:
            >>> # Search using an embedding
            >>> data = vector_store.similarity_search(
            ...     query=<your_query>,
            ...     k=<num_items>,
            ...     exec_option=<preferred_exec_option>,
            ... )
            >>> # Run tql search:
            >>> data = vector_store.similarity_search(
            ...     query=None,
            ...     tql="SELECT * WHERE id == <id>",
            ...     exec_option="compute_engine",
            ... )
        Args:
            k (int): Number of Documents to return. Defaults to 4.
            query (str): Text to look up similar documents.
            **kwargs: Additional keyword arguments include:
                embedding (Callable): Embedding function to use. Defaults to None.
                distance_metric (str): 'L2' for Euclidean, 'L1' for Nuclear, 'max'
                    for L-infinity, 'cos' for cosine, 'dot' for dot product.
                    Defaults to 'L2'.
                filter (Union[Dict, Callable], optional): Additional filter
                    before embedding search.
                    - Dict: Key-value search on tensors of htype json,
                        (sample must satisfy all key-value filters)
                        Dict = {"tensor_1": {"key": value}, "tensor_2": {"key": value}}
                    - Function: Compatible with `deeplake.filter`.
                    Defaults to None.
                exec_option (str): Supports 3 ways to perform searching.
                    'python', 'compute_engine', or 'tensor_db'. Defaults to 'python'.
                    - 'python': Pure-python implementation for the client.
                        WARNING: not recommended for big datasets.
                    - 'compute_engine': C++ implementation of the Compute Engine for
                        the client. Not for in-memory or local datasets.
the client. Not for in-memory or local datasets.
                    - 'tensor_db': Managed Tensor Database for storage and query.
                        Only for data in Deep Lake Managed Database.
                        Use `runtime = {"db_engine": True}` during dataset creation.
                deep_memory (bool): Whether to use the Deep Memory model for improving
                    search results. Defaults to False if deep_memory is not specified
                    in the Vector Store initialization. If True, the distance metric
                    is set to "deepmemory_distance", which represents the metric with
                    which the model was trained. The search is performed using the Deep
                    Memory model. If False, the distance metric is set to "COS" or
                    whatever distance metric user specifies.
        Returns:
            List[Document]: List of Documents most similar to the query vector.
        """
        return self._search(
            query=query,
            k=k,
            use_maximal_marginal_relevance=False,
            return_score=False,
            **kwargs,
        )
[docs]    def similarity_search_by_vector(
        self,
        embedding: Union[List[float], np.ndarray],
        k: int = 4,
        **kwargs: Any,
    ) -> List[Document]:
        """
        Return docs most similar to embedding vector.
        Examples:
            >>> # Search using an embedding
            >>> data = vector_store.similarity_search_by_vector(
            ...    embedding=<your_embedding>,
            ...    k=<num_items_to_return>,
            ...    exec_option=<preferred_exec_option>,
            ... )
        Args:
            embedding (Union[List[float], np.ndarray]):
                Embedding to find similar docs.
            k (int): Number of Documents to return. Defaults to 4.
            **kwargs: Additional keyword arguments including:
**kwargs: Additional keyword arguments including:
                filter (Union[Dict, Callable], optional):
                    Additional filter before embedding search.
                    - ``Dict`` - Key-value search on tensors of htype json. True
                        if all key-value filters are satisfied.
                        Dict = {"tensor_name_1": {"key": value},
                                "tensor_name_2": {"key": value}}
                    - ``Function`` - Any function compatible with
                        `deeplake.filter`.
                    Defaults to None.
                exec_option (str): Options for search execution include
                    "python", "compute_engine", or "tensor_db". Defaults to
                    "python".
                    - "python" - Pure-python implementation running on the client.
                        Can be used for data stored anywhere. WARNING: using this
                        option with big datasets is discouraged due to potential
                        memory issues.
                    - "compute_engine" - Performant C++ implementation of the Deep
                        Lake Compute Engine. Runs on the client and can be used for
                        any data stored in or connected to Deep Lake. It cannot be
                        used with in-memory or local datasets.
                    - "tensor_db" - Performant, fully-hosted Managed Tensor Database.
                        Responsible for storage and query execution. Only available
                        for data stored in the Deep Lake Managed Database.
                        To store datasets in this database, specify
                        `runtime = {"db_engine": True}` during dataset creation.
                distance_metric (str): `L2` for Euclidean, `L1` for Nuclear,
                    `max` for L-infinity distance, `cos` for cosine similarity,
                    'dot' for dot product. Defaults to `L2`.
                deep_memory (bool): Whether to use the Deep Memory model for improving
                    search results. Defaults to False if deep_memory is not specified
search results. Defaults to False if deep_memory is not specified
                    in the Vector Store initialization. If True, the distance metric
                    is set to "deepmemory_distance", which represents the metric with
                    which the model was trained. The search is performed using the Deep
                    Memory model. If False, the distance metric is set to "COS" or
                    whatever distance metric user specifies.
        Returns:
            List[Document]: List of Documents most similar to the query vector.
        """
        return self._search(
            embedding=embedding,
            k=k,
            use_maximal_marginal_relevance=False,
            return_score=False,
            **kwargs,
        )
[docs]    def similarity_search_with_score(
        self,
        query: str,
        k: int = 4,
        **kwargs: Any,
    ) -> List[Tuple[Document, float]]:
        """
        Run similarity search with Deep Lake with distance returned.
        Examples:
        >>> data = vector_store.similarity_search_with_score(
        ...     query=<your_query>,
        ...     embedding=<your_embedding_function>
        ...     k=<number_of_items_to_return>,
        ...     exec_option=<preferred_exec_option>,
        ... )
        Args:
            query (str): Query text to search for.
            k (int): Number of results to return. Defaults to 4.
            **kwargs: Additional keyword arguments. Some of these arguments are:
                distance_metric: `L2` for Euclidean, `L1` for Nuclear, `max` L-infinity
                    distance, `cos` for cosine similarity, 'dot' for dot product.
                    Defaults to `L2`.
                filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
                    embedding_function (Callable): Embedding function to use. Defaults
                    to None.
                exec_option (str): DeepLakeVectorStore supports 3 ways to perform
                    searching. It could be either "python", "compute_engine" or
                    "tensor_db". Defaults to "python".
                    - "python" - Pure-python implementation running on the client.
                        Can be used for data stored anywhere. WARNING: using this
                        option with big datasets is discouraged due to potential
                        memory issues.
                    - "compute_engine" - Performant C++ implementation of the Deep
                        Lake Compute Engine. Runs on the client and can be used for
                        any data stored in or connected to Deep Lake. It cannot be used
                        with in-memory or local datasets.
                    - "tensor_db" - Performant, fully-hosted Managed Tensor Database.
                        Responsible for storage and query execution. Only available for
                        data stored in the Deep Lake Managed Database. To store datasets
                        in this database, specify `runtime = {"db_engine": True}`
                        during dataset creation.
                deep_memory (bool): Whether to use the Deep Memory model for improving
                    search results. Defaults to False if deep_memory is not specified
                    in the Vector Store initialization. If True, the distance metric
                    is set to "deepmemory_distance", which represents the metric with
                    which the model was trained. The search is performed using the Deep
                    Memory model. If False, the distance metric is set to "COS" or
                    whatever distance metric user specifies.
        Returns:
            List[Tuple[Document, float]]: List of documents most similar to the query
                text with distance in float."""
        return self._search(
            query=query,
            k=k,
return self._search(
            query=query,
            k=k,
            return_score=True,
            **kwargs,
        )
[docs]    def max_marginal_relevance_search_by_vector(
        self,
        embedding: List[float],
        k: int = 4,
        fetch_k: int = 20,
        lambda_mult: float = 0.5,
        exec_option: Optional[str] = None,
        **kwargs: Any,
    ) -> List[Document]:
        """
        Return docs selected using the maximal marginal relevance. Maximal marginal
        relevance optimizes for similarity to query AND diversity among selected docs.
        Examples:
        >>> data = vector_store.max_marginal_relevance_search_by_vector(
        ...        embedding=<your_embedding>,
        ...        fetch_k=<elements_to_fetch_before_mmr_search>,
        ...        k=<number_of_items_to_return>,
        ...        exec_option=<preferred_exec_option>,
        ... )
        Args:
            embedding: Embedding to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch for MMR algorithm.
            lambda_mult: Number between 0 and 1 determining the degree of diversity.
                0 corresponds to max diversity and 1 to min diversity. Defaults to 0.5.
            exec_option (str): DeepLakeVectorStore supports 3 ways for searching.
                Could be "python", "compute_engine" or "tensor_db". Defaults to
                "python".
                - "python" - Pure-python implementation running on the client.
                    Can be used for data stored anywhere. WARNING: using this
                    option with big datasets is discouraged due to potential
                    memory issues.
option with big datasets is discouraged due to potential
                    memory issues.
                - "compute_engine" - Performant C++ implementation of the Deep
                    Lake Compute Engine. Runs on the client and can be used for
                    any data stored in or connected to Deep Lake. It cannot be used
                    with in-memory or local datasets.
                - "tensor_db" - Performant, fully-hosted Managed Tensor Database.
                    Responsible for storage and query execution. Only available for
                    data stored in the Deep Lake Managed Database. To store datasets
                    in this database, specify `runtime = {"db_engine": True}`
                    during dataset creation.
            deep_memory (bool): Whether to use the Deep Memory model for improving
                search results. Defaults to False if deep_memory is not specified
                in the Vector Store initialization. If True, the distance metric
                is set to "deepmemory_distance", which represents the metric with
                which the model was trained. The search is performed using the Deep
                Memory model. If False, the distance metric is set to "COS" or
                whatever distance metric user specifies.
            **kwargs: Additional keyword arguments.
        Returns:
            List[Documents] - A list of documents.
        """
        return self._search(
            embedding=embedding,
            k=k,
            fetch_k=fetch_k,
            use_maximal_marginal_relevance=True,
            lambda_mult=lambda_mult,
            exec_option=exec_option,
            **kwargs,
        )
[docs]    def max_marginal_relevance_search(
        self,
        query: str,
        k: int = 4,
        fetch_k: int = 20,
        lambda_mult: float = 0.5,
        exec_option: Optional[str] = None,