
    Ng                       d dl mZ d dlZd dlmZmZmZmZmZm	Z	m
Z
mZ d dlZ	 d dlZd dlmZ d dlmZ d dlmZ dZn# e$ r dZY nw xY wd d	lmZ d d
lmZ d dlmZ d dlmZ  ej        e          Z  G d de          Z!dS )    )annotationsN)AnyCallableDictIterableListOptionalTupleUnion)VectorStore)version_compare)SampleExtendErrorTFDocument)
Embeddings)maximal_marginal_relevancec                  x   e Zd ZU dZdZded<   dgZedddddd	d
dddfdPd ZedQd!            Z		 	 dRdSd)Z
	 dTdUd,Z	 	 	 	 	 	 	 	 	 	 	 dVdWd<Z	 dXdYd=Z	 dXdZd?Z	 dXd[dAZ	 	 	 	 d\d]dEZ	 	 	 	 d\d^dFZedddefd_dG            ZdTd`dHZedadJ            ZdbdKZdcdLZedM             ZedN             ZedO             ZdS )dDeepLakea  `Activeloop Deep Lake` vector store.

    We integrated deeplake's similarity search and filtering for fast prototyping.
    Now, it supports Tensor Query Language (TQL) for production use cases
    over billion rows.

    Why Deep Lake?

    - Not only stores embeddings, but also the original data with version control.
    - Serverless, doesn't require another service and can be used with major
        cloud providers (S3, GCS, etc.)
    - More than just a multi-modal vector store. You can use the dataset
        to fine-tune your own LLM models.

    To use, you should have the ``deeplake`` python package installed.

    Example:
        .. code-block:: python

                from langchain_community.vectorstores import DeepLake
                from langchain_community.embeddings.openai import OpenAIEmbeddings

                embeddings = OpenAIEmbeddings()
                vectorstore = DeepLake("langchain_store", embeddings.embed_query)
    z./deeplake/str _LANGCHAIN_DEFAULT_DEEPLAKE_PATHlambda_multNFi   r   Tdataset_pathtokenOptional[str]	embeddingOptional[Embeddings]embedding_function	read_onlyboolingestion_batch_sizeintnum_workersverboseexec_optionruntimeOptional[Dict]index_params$Optional[Dict[str, Union[int, str]]]kwargsr   returnNonec                   || _         || _        || _        t          du rt	          d          |
ddik    r;t          t          j        d          dk    rt	          dt          j         d          || _        |rt          
                    d	           t          d| j        |p||||	||
|d
|| _        |p|| _        d| j                                        v rdnd| _        dS )a  Creates an empty DeepLakeVectorStore or loads an existing one.

        The DeepLakeVectorStore is located at the specified ``path``.

        Examples:
            >>> # Create a vector store with default tensors
            >>> deeplake_vectorstore = DeepLake(
            ...        path = <path_for_storing_Data>,
            ... )
            >>>
            >>> # Create a vector store in the Deep Lake Managed Tensor Database
            >>> data = DeepLake(
            ...        path = "hub://org_id/dataset_name",
            ...        runtime = {"tensor_db": True},
            ... )

        Args:
            dataset_path (str): The full path for storing to the Deep Lake
                Vector Store. It can be:
                - a Deep Lake cloud path of the form ``hub://org_id/dataset_name``.
                    Requires registration with Deep Lake.
                - an s3 path of the form ``s3://bucketname/path/to/dataset``.
                    Credentials are required in either the environment or passed to
                    the creds argument.
                - a local file system path of the form ``./path/to/dataset``
                    or ``~/path/to/dataset`` or ``path/to/dataset``.
                - a memory path of the form ``mem://path/to/dataset`` which doesn't
                    save the dataset but keeps it in memory instead.
                    Should be used only for testing as it does not persist.
                    Defaults to _LANGCHAIN_DEFAULT_DEEPLAKE_PATH.
            token (str, optional):  Activeloop token, for fetching credentials
                to the dataset at path if it is a Deep Lake dataset.
                Tokens are normally autogenerated. Optional.
            embedding (Embeddings, optional): Function to convert
                either documents or query. Optional.
            embedding_function (Embeddings, optional): Function to convert
                either documents or query. Optional. Deprecated: keeping this
                parameter for backwards compatibility.
            read_only (bool): Open dataset in read-only mode. Default is False.
            ingestion_batch_size (int): During data ingestion, data is divided
                into batches. Batch size is the size of each batch.
                Default is 1024.
            num_workers (int): Number of workers to use during data ingestion.
                Default is 0.
            verbose (bool): Print dataset summary after each operation.
                Default is True.
            exec_option (str, optional): Default method for search execution.
                It could be either ``"auto"``, ``"python"``, ``"compute_engine"``
                or ``"tensor_db"``. Defaults to ``"auto"``.
                If None, it's set to "auto".
                - ``auto``- Selects the best execution method based on the storage
                    location of the Vector Store. It is the default option.
                - ``python`` - Pure-python implementation that runs on the client and
                    can be used for data stored anywhere. WARNING: using this option
                    with big datasets is discouraged because it can lead to
                    memory issues.
                - ``compute_engine`` - Performant C++ implementation of the Deep Lake
                    Compute Engine that 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 and fully-hosted Managed Tensor Database
                    that is responsible for storage and query execution. Only available
                    for data stored in the Deep Lake Managed Database. Store datasets
                    in this database by specifying runtime = {"tensor_db": True}
                    during dataset creation.
            runtime (Dict, optional): Parameters for creating the Vector Store in
                Deep Lake's Managed Tensor Database. Not applicable when loading an
                existing Vector Store. To create a Vector Store in the Managed Tensor
                Database, set `runtime = {"tensor_db": True}`.
            index_params (Optional[Dict[str, Union[int, str]]], optional): Dictionary
                containing information about vector index that will be created. Defaults
                to None, which will utilize ``DEFAULT_VECTORSTORE_INDEX_PARAMS`` from
                ``deeplake.constants``. The specified key-values override the default
                ones.
                - threshold: The threshold for the dataset size above which an index
                    will be created for the embedding tensor. When the threshold value
                    is set to -1, index creation is turned off. Defaults to -1, which
                    turns off the index.
                - distance_metric: This key specifies the method of calculating the
                    distance between vectors when creating the vector database (VDB)
                    index. It can either be a string that corresponds to a member of
                    the DistanceType enumeration, or the string value itself.
                    - If no value is provided, it defaults to "L2".
                    - "L2" corresponds to DistanceType.L2_NORM.
                    - "COS" corresponds to DistanceType.COSINE_SIMILARITY.
                - additional_params: Additional parameters for fine-tuning the index.
            **kwargs: Other optional keyword arguments.

        Raises:
            ValueError: If some condition is not met.
        FzdCould not import deeplake python package. Please install it with `pip install deeplake[enterprise]`.	tensor_dbTz3.6.7zrTo use tensor_db option you need to update deeplake to `3.6.7` or higher. Currently installed deeplake version is z. zgUsing embedding function is deprecated and will be removed in the future. Please use embedding instead.)pathr   r   r   r$   r#   r%   r'   idsidN )r    r"   r#   _DEEPLAKE_INSTALLEDImportErrorr   deeplake__version__r   loggerwarningDeepLakeVectorStorevectorstore_embedding_functiontensors_id_tensor_name)selfr   r   r   r   r   r    r"   r#   r$   r%   r'   r)   s                e/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/vectorstores/deeplake.py__init__zDeepLake.__init__9   sI   V %9!&%''M   T*** 4g>>"DDT;C;OT T T   ) 	NN?  
 / 

"1>Y#%

 

 

 

 $6#B (-1A1I1I1K1K(K(KuuQU    c                    | j         S N)r;   r>   s    r?   
embeddingszDeepLake.embeddings   s    ''rA   textsIterable[str]	metadatasOptional[List[dict]]r0   Optional[List[str]]	List[str]c           
     *   |                      |d           i }|r| j        dk    r||d<   n||d<   | i gt          t          |                    z  }t	          |t                    st          |          }|t          d          t          |          dk    rt          d          	  | j        j        d|||d| j        j	        d	d
|S # t          $ r:}dt          |          v r"d}t          |j        d         dz   |z             |d}~ww xY w)aq  Run more texts through the embeddings and add to the vectorstore.

        Examples:
            >>> ids = deeplake_vectorstore.add_texts(
            ...     texts = <list_of_texts>,
            ...     metadatas = <list_of_metadata_jsons>,
            ...     ids = <list_of_ids>,
            ... )

        Args:
            texts (Iterable[str]): Texts to add to the vectorstore.
            metadatas (Optional[List[dict]], optional): Optional list of metadatas.
            ids (Optional[List[str]], optional): Optional list of IDs.
            embedding_function (Optional[Embeddings], optional): Embedding function
                to use to convert the text into embeddings.
            **kwargs (Any): Any additional keyword arguments passed is not supported
                by this method.

        Returns:
            List[str]: List of IDs of the added texts.
        	add_textsr0   r1   Nz$`texts` parameter shouldn't be None.r   z%`texts` parameter shouldn't be empty.r   T)textmetadataembedding_dataembedding_tensorr   
return_idsz2Failed to append a sample to the tensor 'metadata'zr**Hint: You might be using invalid type of argument in document loader (e.g. 'pathlib.PosixPath' instead of 'str')z

r2   )_validate_kwargsr=   lenlist
isinstance
ValueErrorr:   addr;   embed_documentsr   r   args)r>   rF   rH   r0   r)   emsgs          r?   rM   zDeepLake.add_texts   se   8 	fk222 	##u,, #u"ts4;;///I%&& 	 KKE=CDDDZZ1__DEEE	'4#' "$!,#'#;#K     ! 	 	 	Cs1vvMMR  !V!3c!9:::	s   +"C 
D5DDtqlList[Document]c                   | j                             ||          }|d         }|d         }d t          ||          D             }|r9t          t	          |                    }||         durt          d| d          |S )aJ  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.
        )queryr$   rO   rN   c                6    g | ]\  }}t          ||           S )page_contentrO   r   .0rN   rO   s      r?   
<listcomp>z(DeepLake._search_tql.<locals>.<listcomp>=  C     
 
 

 h	 !!  
 
 
rA   Fzspecifying z" is not supported with tql search.)r:   searchzipnextiterrW   )	r>   r]   r$   r)   resultrH   rF   docsunsupported_arguments	            r?   _search_tqlzDeepLake._search_tql  s    > !((# ) 
 
 :&	v
 

 #&eY"7"7
 
 
  	#'V#5#5 *+588 5"6 5 5 5  
 rA         r`   (Optional[Union[List[float], np.ndarray]]Optional[Callable]kdistance_metricuse_maximal_marginal_relevancefetch_kOptional[int]filterOptional[Union[Dict, Callable]]return_scoredeep_memory1Any[List[Document], List[Tuple[Document, float]]]c                   |                     d          r2t                              d           |                    d          |d<   |                     d          r#|                     |d         |
|	|||||          S |                     |d           |r t          |t                    r|j        }n|}n| j	        r| j	        j        }nd}| |t          d          |r ||          nd}t          |t                    r@t          j        |t          j                  }t          |j                  d	k    r|d
         }| j                            ||r|n||||
ddd| j        g|          }|d         |d         }|d         |d         |rn|                     dd          }t)          ||t+          |t                              |          }fd|D             fd|D             fd|D             d t-                    D             }|	r2t          t                    sgd t-          |          D             S |S )a
  
        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.
            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
                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.
        	tql_queryz4`tql_query` is deprecated. Please use `tql` instead.r]   )r]   r$   r{   r   r   ru   rv   ry   rh   NzAEither `embedding` or `embedding_function` needs to be specified.)dtype   r   r   rO   rN   )r   rt   ru   ry   r$   return_tensorsr|   scorer         ?)rt   r   c                     g | ]
}|         S r2   r2   )re   iscoress     r?   rf   z$DeepLake._search.<locals>.<listcomp>  s    111AfQi111rA   c                     g | ]
}|         S r2   r2   )re   r   rF   s     r?   rf   z$DeepLake._search.<locals>.<listcomp>  s    ///!U1X///rA   c                     g | ]
}|         S r2   r2   )re   r   rH   s     r?   rf   z$DeepLake._search.<locals>.<listcomp>  s    777!1777rA   c                6    g | ]\  }}t          ||           S rb   r   rd   s      r?   rf   z$DeepLake._search.<locals>.<listcomp>  rg   rA   c                    g | ]	\  }}||f
S r2   r2   )re   docr   s      r?   rf   z$DeepLake._search.<locals>.<listcomp>  s     EEEZS%S%LEEErA   )getr7   r8   popro   rS   rV   r   embed_queryr;   rW   rU   nparrayfloat32rT   shaper:   rh   r=   r   minri   )r>   r`   r   r   rt   ru   rv   rw   ry   r{   r$   r|   r)   r;   rl   rE   r   indicesrm   rH   r   rF   s                      @@@r?   _searchzDeepLake._searchO  s   | ::k"" 	4NNQRRR"JJ{33F5M::e 
	##5M')##5 //M $ 	 	 	 	fh/// 	',j99 9&8&D##&8##% 	'"&":"F"&"* "  
 7<E++E222Ii&& 	)"*===I9?##a''%aL	!((7>ggQ+#'VT=QR# ) 
 
 K(
:&	v) 	8 **]C88K0aU$$'	  G 2111111F////w///E7777w777I
 

 #&eY"7"7
 
 
  	Ffd++ " EE3tV3D3DEEEErA   c                &     | j         d||ddd|S )a1  
        Return docs most similar to query.

        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.
                    - '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.
        F)r`   rt   rv   r{   r2   r   r>   r`   rt   r)   s       r?   similarity_searchzDeepLake.similarity_search  s;    v t| 
+0	
 

 
 
 	
rA   Union[List[float], np.ndarray]c                &     | j         d||ddd|S )a  
        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:
                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
                    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.
        F)r   rt   rv   r{   r2   r   )r>   r   rt   r)   s       r?   similarity_search_by_vectorz$DeepLake.similarity_search_by_vector%  s;    | t| 
+0	
 

 
 
 	
rA   List[Tuple[Document, float]]c                $     | j         d||dd|S )a]  
        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.
                    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.T)r`   rt   r{   r2   r   r   s       r?   similarity_search_with_scorez%DeepLake.similarity_search_with_scorek  s8    n t| 

 
 	
 
 	
rA   r   List[float]floatc           
     *     | j         d|||d||d|S )a|
  
        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.
                - "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.
        T)r   rt   rw   rv   r   r$   r2   r   )r>   r   rt   rw   r   r$   r)   s          r?   'max_marginal_relevance_search_by_vectorz0DeepLake.max_marginal_relevance_search_by_vector  sA    p t| 
+/##
 
 
 
 	
rA   c                    |                     d          p| j        }|t          d           | j        d|||d|||d|S )a
  Return docs selected using maximal marginal relevance.

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

        Examples:
        >>> # Search using an embedding
        >>> data = vector_store.max_marginal_relevance_search(
        ...        query = <query_to_search>,
        ...        embedding_function = <embedding_function_for_query>,
        ...        k = <number_of_items_to_return>,
        ...        exec_option = <preferred_exec_option>,
        ... )

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents for MMR algorithm.
            lambda_mult: Value between 0 and 1. 0 corresponds
                        to maximum diversity and 1 to minimum.
                        Defaults to 0.5.
            exec_option (str): Supports 3 ways to perform searching.
                - "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.
            kwargs: Additional keyword arguments

        Returns:
            List of Documents selected by maximal marginal relevance.

        Raises:
            ValueError: when MRR search is on but embedding function is
                not specified.
        r   NzXFor MMR search, you must specify an embedding function on `creation` or during add call.T)r`   rt   rw   rv   r   r$   r   r2   )r   r;   rW   r   )r>   r`   rt   rw   r   r$   r)   r   s           r?   max_marginal_relevance_searchz&DeepLake.max_marginal_relevance_search  s}    x $ZZ44P8P%2   t| 	
+/##1	
 	
 	
 	
 		
rA   c                L     | d||d|}|                     |||           |S )a>  Create a Deep Lake dataset from a raw documents.

        If a dataset_path is specified, the dataset will be persisted in that location,
        otherwise by default at `./deeplake`

        Examples:
        >>> # Search using an embedding
        >>> vector_store = DeepLake.from_texts(
        ...        texts = <the_texts_that_you_want_to_embed>,
        ...        embedding_function = <embedding_function_for_query>,
        ...        k = <number_of_items_to_return>,
        ...        exec_option = <preferred_exec_option>,
        ... )

        Args:
            dataset_path (str): - The full path to the dataset. Can be:
                - Deep Lake cloud path of the form ``hub://username/dataset_name``.
                    To write to Deep Lake cloud datasets,
                    ensure that you are logged in to Deep Lake
                    (use 'activeloop login' from command line)
                - AWS S3 path of the form ``s3://bucketname/path/to/dataset``.
                    Credentials are required in either the environment
                - Google Cloud Storage path of the form
                    ``gcs://bucketname/path/to/dataset`` Credentials are required
                    in either the environment
                - Local file system path of the form ``./path/to/dataset`` or
                    ``~/path/to/dataset`` or ``path/to/dataset``.
                - In-memory path of the form ``mem://path/to/dataset`` which doesn't
                    save the dataset, but keeps it in memory instead.
                    Should be used only for testing as it does not persist.
            texts (List[Document]): List of documents to add.
            embedding (Optional[Embeddings]): Embedding function. Defaults to None.
                Note, in other places, it is called embedding_function.
            metadatas (Optional[List[dict]]): List of metadatas. Defaults to None.
            ids (Optional[List[str]]): List of document IDs. Defaults to None.
            kwargs: Additional keyword arguments.

        Returns:
            DeepLake: Deep Lake dataset.
        )r   r   )rF   rH   r0   r2   )rM   )clsrF   r   rH   r0   r   r)   deeplake_datasets           r?   
from_textszDeepLake.from_texts8  sQ    d 3XLIXXQWXX"" 	# 	
 	
 	

  rA   c                    |                     d          }|                     d          }| j                            |||           dS )a  Delete the entities in the dataset.

        Args:
            ids (Optional[List[str]], optional): The document_ids to delete.
                Defaults to None.
            **kwargs: Other keyword arguments that subclasses might use.
                - filter (Optional[Dict[str, str]], optional): The filter to delete by.
                - delete_all (Optional[bool], optional): Whether to drop the dataset.

        Returns:
            bool: Whether the delete operation was successful.
        ry   
delete_all)r0   ry   r   T)r   r:   delete)r>   r0   r)   ry   r   s        r?   r   zDeepLake.deleter  sI     H%%ZZ--
C:NNNtrA   r/   c                r    	 ddl }n# t          $ r t          d          w xY w |j        |dd           dS )zForce delete dataset by path.

        Args:
            path (str): path of the dataset to delete.

        Raises:
            ValueError: if deeplake is not installed.
        r   NzXCould not import deeplake python package. Please install it with `pip install deeplake`.T)large_okforce)r5   r4   r   )r   r/   r5   s      r?   force_delete_by_pathzDeepLake.force_delete_by_path  sf    	OOOO 	 	 	A  	
 	t4888888s    !c                2    |                      d           dS )zDelete the collection.T)r   N)r   rD   s    r?   delete_datasetzDeepLake.delete_dataset  s    t$$$$$rA   c                N    t                               d           | j        j        S )Nz^this method is deprecated and will be removed, better to use `db.vectorstore.dataset` instead.)r7   r8   r:   datasetrD   s    r?   dszDeepLake.ds  s+    >	
 	
 	
 ''rA   c                    |rC|                      |          }|                     ||          }|rt          d| d| d          d S d S )N`z` are not a valid argument to z method)_get_valid_args_get_unsupported_items	TypeError)r   r)   method_namevalid_itemsunsupported_itemss        r?   rS   zDeepLake._validate_kwargs  s     	--k::K # : :6; O O  8) 8 8#.8 8 8  	 	 rA   c                     |dk    r| j         S g S )Nrh   )_valid_search_kwargs)r   r   s     r?   r   zDeepLake._get_valid_args  s    (""++IrA   c                    fd|                                  D             } d }| r4d                    t          |                                                     }|S )Nc                $    i | ]\  }}|v	||S r2   r2   )re   rt   vr   s      r?   
<dictcomp>z3DeepLake._get_unsupported_items.<locals>.<dictcomp>  s)    JJJ41aQk5I5I!Q5I5I5IrA   z`, `)itemsjoinsetkeys)r)   r   r   s    ` r?   r   zDeepLake._get_unsupported_items  s[    JJJJ6<<>>JJJ  	@ &C,>,> ? ?  rA   )r   r   r   r   r   r   r   r   r   r   r    r!   r"   r!   r#   r   r$   r   r%   r&   r'   r(   r)   r   r*   r+   )r*   r   )NN)
rF   rG   rH   rI   r0   rJ   r)   r   r*   rK   rC   )r]   r   r$   r   r)   r   r*   r^   )NNNrp   NFrq   NFNF)r`   r   r   rr   r   rs   rt   r!   ru   r   rv   r   rw   rx   ry   rz   r{   r   r$   r   r|   r   r)   r   r*   r}   )rp   )r`   r   rt   r!   r)   r   r*   r^   )r   r   rt   r!   r)   r   r*   r^   )r`   r   rt   r!   r)   r   r*   r   )rp   rq   r   N)r   r   rt   r!   rw   r!   r   r   r$   r   r)   r   r*   r^   )r`   r   rt   r!   rw   r!   r   r   r$   r   r)   r   r*   r^   )rF   rK   r   r   rH   rI   r0   rJ   r   r   r)   r   r*   r   )r0   rJ   r)   r   r*   r   )r/   r   r*   r+   )r*   r+   )r*   r   )__name__
__module____qualname____doc__r   __annotations__r   r@   propertyrE   rM   ro   r   r   r   r   r   r   classmethodr   r   r   r   r   rS   r   staticmethodr   r2   rA   r?   r   r      s         4 -:$9999)? =#*.37$(%)"&=ATV TV TV TV TVl ( ( ( X( +/#'	B B B B BN &*6 6 6 6 6t  $>B15)-/4!#26"%)!Q Q Q Q Ql A
 A
 A
 A
 A
L D
 D
 D
 D
 D
R <
 <
 <
 <
 <
B  %)@
 @
 @
 @
 @
J  %)K
 K
 K
 K
 K
Z  +/*.#'<7  7  7  7  [7 r    ( 9 9 9 [9&% % % %( ( ( ( 	 	 [	   [ ! ! \! ! !rA   r   )"
__future__r   loggingtypingr   r   r   r   r   r	   r
   r   numpyr   r5   r   r9   deeplake.core.fast_forwardingr   deeplake.util.exceptionsr   r3   r4   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.vectorstores&langchain_community.vectorstores.utilsr   	getLoggerr   r7   r   r2   rA   r?   <module>r      sv   " " " " " "  N N N N N N N N N N N N N N N N N N N N     OOO;;;;;;======::::::        . - - - - - 0 0 0 0 0 0 3 3 3 3 3 3 M M M M M M		8	$	$c! c! c! c! c!{ c! c! c! c! c!s   = AA