
    dh                    $   S SK Jr  S SKrS SKJrJrJrJrJrJ	r	J
r
Jr  S SKr S SKrS SKJr  S SKJr  S SKJr  SrS S	KJr  S S
KJr  S SKJr  S SKJr  S SKJr  \R@                  " \!5      r"\" SSSSS9 " S S\5      5       r#g! \ a    Sr NRf = f)    )annotationsN)AnyCallableDictIterableListOptionalTupleUnion)VectorStore)version_compare)SampleExtendErrorTF)
deprecated)Document)
Embeddings)maximal_marginal_relevancez0.3.3z1.0a  This class is deprecated and will be removed in a future version. You can swap to using the `DeeplakeVectorStore` implementation in `langchain-deeplake`. Please do not submit further PRs to this class.See <https://github.com/activeloopai/langchain-deeplake>z&langchain_deeplake.DeeplakeVectorStore)sinceremovalmessagealternative_importc                     \ rS rSr% SrSrS\S'   S/r\SSSSS	S
SSSS4                         SS jjr\	S S j5       r
  S!         S"S jjr S#       S$S jjr           S%                         S&S jjr S'       S(S jjr S'       S)S jjr S'       S*S jjr    S+             S,S jjr    S+             S-S jjr\SSS\4             S.S jj5       rS#S/S jjr\S0S j5       rS1S jrS2S jr\S3S j5       r\S4S j5       r\S5S j5       rSrg)6DeepLake   a|  `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   Tc                   X`l         Xpl        Xl        [        SL a  [	        S5      eU
SS0:X  a;  [        [        R                  S5      S:X  a  [	        S[        R                   S35      eXl        U(       a  [        R                  S	5        [        SU R                  U=(       d    UUUU	UU
US
.UD6U l        U=(       d    UU l        SU R                  R                  5       ;   a  SU l        gSU l        g)am  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.
FzjCould not import deeplake python package. Please install it with `pip install deeplake[enterprise]<4.0.0`.	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.)pathembedding_function	read_onlytokenexec_optionverboseruntimeindex_paramsidsidN )ingestion_batch_sizenum_workersr%   _DEEPLAKE_INSTALLEDImportErrorr   deeplake__version__dataset_pathloggerwarningDeepLakeVectorStorevectorstore_embedding_functiontensors_id_tensor_name)selfr1   r#   	embeddingr!   r"   r+   r,   r%   r$   r&   r'   kwargss                a/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_community/vectorstores/deeplake.py__init__DeepLake.__init__F   s   V %9!&%'S  T** 4 4g>"D;;C;O;O:PPRT  )NN?
 / 

""1>Y#%

 

 $6#B (-1A1A1I1I1K(KuQU    c                    U R                   $ N)r6   r9   s    r<   
embeddingsDeepLake.embeddings   s    '''r?   c           
     &   U R                  US5        0 nU(       a  U R                  S:X  a  X4S'   OX4S'   Uc  0 /[        [        U5      5      -  n[	        U[        5      (       d  [        U5      nUc  [        S5      e[        U5      S:X  a  [        S5      e U R                  R                  " SUUUSU R                  R                  S	S
.UD6$ ! [         a6  nS[        U5      ;   a   Sn[        UR                  S   S-   U-   5      eUeSnAff = f)a  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_textsr(   r)   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

r*   )_validate_kwargsr8   lenlist
isinstance
ValueErrorr5   addr6   embed_documentsr   r   args)r9   texts	metadatasr(   r;   emsgs          r<   rF   DeepLake.add_texts   s)   8 	fk2##u, #u"ts4;//I%&&KE=CDDZ1_DEE	##'' "$!,#'#;#;#K#K   ! 	Cs1vMR  !V!3c!9::	s   6C 
D1DDc           	        U R                   R                  UUS9nUS   nUS   n[        Xe5       VVs/ sH  u  px[        UUS9PM     n	nnU(       a*  [	        [        U5      5      n
X:   SLa  [        SU
 S35      eU	$ s  snnf )a  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$   rH   rG   page_contentrH   Fzspecifying z" is not supported with tql search.)r5   searchzipr   nextiterrP   )r9   tqlr$   r;   resultrU   rT   rG   rH   docsunsupported_arguments              r<   _search_tqlDeepLake._search_tql$  s    > !!((# ) 
 :&	v #&e"7

 #8	 !! #8 	 
 #'V#5 +58 !"6!7 85 5 
 !
s   A>c                (   UR                  S5      (       a)  [        R                  S5        UR                  S5      US'   UR                  S5      (       a  U R	                  US   U
U	UUUUUS9$ U R                  US5        U(       a%  [        U[        5      (       a  UR                  nO-UnO*U R                  (       a  U R                  R                  nOSnUc  Uc  [        S5      eU(       a  U" U5      OSn[        U[        5      (       aA  [        R                  " U[        R                  S9n[        UR                   5      S	:  a  US
   nU R"                  R%                  UU(       a  UOUUUU
SSSU R&                  /US9nUS   nUS   nUS   nUS   nU(       am  UR                  SS5      n[)        UU[+        U[        U5      5      US9nU Vs/ sH  nUU   PM
     nnU Vs/ sH  nUU   PM
     nnU Vs/ sH  nUU   PM
     nn[-        UU5       VVs/ sH  u  nn[/        UUS9PM     nnnU	(       a;  [        U[        5      (       d  U/n[-        UU5       VVs/ sH
  u  nnUU4PM     snn$ U$ s  snf s  snf s  snf s  snnf s  snnf )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.ra   )ra   r$   return_scorer:   r!   distance_metricuse_maximal_marginal_relevancefilterr]   NzAEither `embedding` or `embedding_function` needs to be specified.)dtype   r   r:   rH   rG   )r:   krj   rl   r$   return_tensorsdeep_memoryscorer         ?)ro   r   r[   )getr2   r3   popre   rL   rO   r   embed_queryr6   rP   rN   nparrayfloat32rM   shaper5   r]   r8   r   minr^   r   )r9   rZ   r:   r!   ro   rj   rk   fetch_krl   ri   r$   rq   r;   r6   rb   scoresrC   rU   rT   r   indicesirG   rH   rc   docrr   s                              r<   _searchDeepLake._search\  s   | ::k""NNQR"JJ{3F5M::e##5M')##5 //M $ 	 	 	fh/,j99&8&D&D#&8#%%"&":":"F"F"&"* W  7<+E2Ii&&"**=I9??#a'%aL	!!((7gQ+#'VT=Q=QR# ) 
 K(
:&	v) **]C8K0aU$'	G *11AfQiF1'./w!U1XwE//67w!1wI7 #&eY"7

 #8h	 !! #8 	 
 fd++ 36tV3DE3DZS%S%L3DEE% 2/7
 Fs   I9)I>=JJ#Jc                0    U R                   " SUUSSS.UD6$ )a	  
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)rZ   ro   rk   ri   r*   r   r9   rZ   ro   r;   s       r<   similarity_searchDeepLake.similarity_search  s1    v || 
+0	

 
 	
r?   c                0    U R                   " SUUSSS.UD6$ )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:   ro   rk   ri   r*   r   )r9   r:   ro   r;   s       r<   similarity_search_by_vector$DeepLake.similarity_search_by_vector1  s1    | || 
+0	

 
 	
r?   c                .    U R                   " SUUSS.UD6$ )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)rZ   ro   ri   r*   r   r   s       r<   similarity_search_with_score%DeepLake.similarity_search_with_scorew  s.    n || 

 	
 	
r?   c           
     4    U R                   " SUUUSUUS.UD6$ )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:   ro   r|   rk   r   r$   r*   r   )r9   r:   ro   r|   r   r$   r;   s          r<   'max_marginal_relevance_search_by_vector0DeepLake.max_marginal_relevance_search_by_vector  s7    p || 
+/##
 
 	
r?   c                    UR                  S5      =(       d    U R                  nUc  [        S5      eU R                  " SUUUSUUUS.UD6$ )af	  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:   zXFor MMR search, you must specify an embedding function on `creation` or during add call.T)rZ   ro   r|   rk   r   r$   r!   r*   )rt   r6   rP   r   )r9   rZ   ro   r|   r   r$   r;   r!   s           r<   max_marginal_relevance_search&DeepLake.max_marginal_relevance_search  sn    x $ZZ4P8P8P%2  || 	
+/##1	
 	
 		
r?   c                <    U " SXRS.UD6nUR                  UUUS9  U$ )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.
)r1   r:   )rT   rU   r(   r*   )rF   )clsrT   r:   rU   r(   r1   r;   deeplake_datasets           r<   
from_textsDeepLake.from_textsD  s=    d XLXQWX"" 	# 	

  r?   c                |    UR                  S5      nUR                  S5      nU R                  R                  XUS9  g)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.
rl   
delete_all)r(   rl   r   T)rt   r5   delete)r9   r(   r;   rl   r   s        r<   r   DeepLake.delete~  s<     H%ZZ-
C:Nr?   c                d     SSK nUR                  " USSS9  g! [         a    [        S5      ef = f)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)r/   r.   r   )r   r    r/   s      r<   force_delete_by_pathDeepLake.force_delete_by_path  s@    	 	t48  	A 	s    /c                "    U R                  SS9  g)zDelete the collection.T)r   N)r   rB   s    r<   delete_datasetDeepLake.delete_dataset  s    t$r?   c                X    [         R                  S5        U R                  R                  $ )Nz^this method is deprecated and will be removed, better to use `db.vectorstore.dataset` instead.)r2   r3   r5   datasetrB   s    r<   dsDeepLake.ds  s'    >	
 '''r?   c                    U(       a<  U R                  U5      nU R                  X5      nU(       a  [        SU SU S35      eg g )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<   rL   DeepLake._validate_kwargs  sZ    --k:K # : :6 O )* +##.-w8  !	 r?   c                *    US:X  a  U R                   $ / $ )Nr]   )_valid_search_kwargs)r   r   s     r<   r   DeepLake._get_valid_args  s    ("+++Ir?   c                    U R                  5        VVs0 sH  u  p#X!;  d  M  X#_M     n nnS nU (       a(  SR                  [        U R                  5       5      5      nU$ s  snnf )Nz`, `)itemsjoinsetkeys)r;   r   ro   vr   s        r<   r   DeepLake._get_unsupported_items  sV    #)<<>J>41Q5I$!$>J  &C,> ?  	 Ks
   
AA)r6   r8   r1   r+   r,   r5   r%   )r1   r   r#   Optional[str]r:   Optional[Embeddings]r!   r   r"   boolr+   intr,   r   r%   r   r$   r   r&   zOptional[Dict]r'   z$Optional[Dict[str, Union[int, str]]]r;   r   returnNone)r   r   )NN)
rT   zIterable[str]rU   Optional[List[dict]]r(   Optional[List[str]]r;   r   r   	List[str]rA   )ra   r   r$   r   r;   r   r   List[Document])NNN   NF   NFNF)rZ   r   r:   z(Optional[Union[List[float], np.ndarray]]r!   zOptional[Callable]ro   r   rj   r   rk   r   r|   zOptional[int]rl   zOptional[Union[Dict, Callable]]ri   r   r$   r   rq   r   r;   r   r   z1Any[List[Document], List[Tuple[Document, float]]])r   )rZ   r   ro   r   r;   r   r   r   )r:   zUnion[List[float], np.ndarray]ro   r   r;   r   r   r   )rZ   r   ro   r   r;   r   r   zList[Tuple[Document, float]])r   r   rs   N)r:   zList[float]ro   r   r|   r   r   floatr$   r   r;   r   r   r   )rZ   r   ro   r   r|   r   r   r   r$   r   r;   r   r   r   )rT   r   r:   r   rU   r   r(   r   r1   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   	list[str])r;   r   r   r   r   r   )__name__
__module____qualname____firstlineno____doc__r   __annotations__r   r=   propertyrC   rF   re   r   r   r   r   r   r   classmethodr   r   r   r   r   rL   r   staticmethodr   __static_attributes__r*   r?   r<   r   r      sD   4 -:$c9)? =#*.37$(%)"&=ATVTV TV (	TV
 1TV TV "TV TV TV #TV  TV ;TV TV 
TVl ( ( +/#'	BB (B !	B
 B 
BN &*66 #6 	6
 
6t  $>B15)-/4!#26"%)!PP <P /	P
 P 'P )-P P 0P P #P P P 
;Pj A
A
 A
 	A

 
A
L D
1D
 D
 	D

 
D
R <
<
 <
 	<

 
&<
B  %)@
@
 @
 	@

 @
 #@
 @
 
@
J  %)K
K
 K
 	K

 K
 #K
 K
 
K
Z  +/*.#'<7 7  (7  (	7 
 !7  7  7  
7  7 r( 9 9&%( 	 	   ! !r?   r   )$
__future__r   loggingtypingr   r   r   r   r   r	   r
   r   numpyrw   r/   r   r4   deeplake.core.fast_forwardingr   deeplake.util.exceptionsr   r-   r.   langchain_core._apir   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.vectorstores&langchain_community.vectorstores.utilsr   	getLoggerr   r2   r   r*   r?   r<   <module>r      s    "  N N N  ;=: + - 0 3 M			8	$ 
	C @b!{ b!b!3    s   B BB