langchain.vectorstores.deeplake.DeepLake

class langchain.vectorstores.deeplake.DeepLake(dataset_path: str = './deeplake/', token: Optional[str] = None, embedding: Optional[Embeddings] = None, embedding_function: Optional[Embeddings] = None, read_only: bool = False, ingestion_batch_size: int = 1000, num_workers: int = 0, verbose: bool = True, exec_option: Optional[str] = None, **kwargs: Any)[source]

Bases: VectorStore

Wrapper around Deep Lake, a data lake for deep learning applications.

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

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

embeddings = OpenAIEmbeddings()
vectorstore = DeepLake("langchain_store", embeddings.embed_query)

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",
...        exec_option = "tensor_db",
... )
Parameters
  • dataset_path (str) – Path to existing dataset or where to create a new one. 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 1000.

  • 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) –

    DeepLakeVectorStore supports 3 ways to perform searching - “python”, “compute_engine”, “tensor_db” and auto. Default is None. - 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.

      WARNING: using this with big datasets can lead to memory issues. Data can be stored anywhere.

    • compute_engine - C++ implementation of the Deep Lake Compute

      Engine that runs on the client. Can be used for any data stored in or connected to Deep Lake. Not for in-memory or local datasets.

    • tensor_db - Hosted Managed Tensor Database that is

      responsible for storage and query execution. Only for data stored in the Deep Lake Managed Database. Use runtime = {“db_engine”: True} during dataset creation.

  • **kwargs – Other optional keyword arguments.

Raises

ValueError – If some condition is not met.

Methods

__init__([dataset_path, token, embedding, ...])

Creates an empty DeepLakeVectorStore or loads an existing one.

aadd_documents(documents, **kwargs)

Run more documents through the embeddings and add to the vectorstore.

aadd_texts(texts[, metadatas])

Run more texts through the embeddings and add to the vectorstore.

add_documents(documents, **kwargs)

Run more documents through the embeddings and add to the vectorstore.

add_texts(texts[, metadatas, ids])

Run more texts through the embeddings and add to the vectorstore.

afrom_documents(documents, embedding, **kwargs)

Return VectorStore initialized from documents and embeddings.

afrom_texts(texts, embedding[, metadatas])

Return VectorStore initialized from texts and embeddings.

amax_marginal_relevance_search(query[, k, ...])

Return docs selected using the maximal marginal relevance.

amax_marginal_relevance_search_by_vector(...)

Return docs selected using the maximal marginal relevance.

as_retriever(**kwargs)

asearch(query, search_type, **kwargs)

Return docs most similar to query using specified search type.

asimilarity_search(query[, k])

Return docs most similar to query.

asimilarity_search_by_vector(embedding[, k])

Return docs most similar to embedding vector.

asimilarity_search_with_relevance_scores(query)

Return docs most similar to query.

delete([ids])

Delete the entities in the dataset.

delete_dataset()

Delete the collection.

ds()

force_delete_by_path(path)

Force delete dataset by path.

from_documents(documents, embedding, **kwargs)

Return VectorStore initialized from documents and embeddings.

from_texts(texts[, embedding, metadatas, ...])

Create a Deep Lake dataset from a raw documents.

max_marginal_relevance_search(query[, k, ...])

Return docs selected using maximal marginal relevance.

max_marginal_relevance_search_by_vector(...)

Return docs selected using the maximal marginal relevance.

search(query, search_type, **kwargs)

Return docs most similar to query using specified search type.

similarity_search(query[, k])

Return docs most similar to query.

similarity_search_by_vector(embedding[, k])

Return docs most similar to embedding vector.

similarity_search_with_relevance_scores(query)

Return docs and relevance scores in the range [0, 1].

similarity_search_with_score(query[, k])

Run similarity search with Deep Lake with distance returned.

Attributes

embeddings

Access the query embedding object if available.

async aadd_documents(documents: List[Document], **kwargs: Any) List[str]

Run more documents through the embeddings and add to the vectorstore.

Parameters

(List[Document] (documents) – Documents to add to the vectorstore.

Returns

List of IDs of the added texts.

Return type

List[str]

async aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) List[str]

Run more texts through the embeddings and add to the vectorstore.

add_documents(documents: List[Document], **kwargs: Any) List[str]

Run more documents through the embeddings and add to the vectorstore.

Parameters

(List[Document] (documents) – Documents to add to the vectorstore.

Returns

List of IDs of the added texts.

Return type

List[str]

add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) List[str][source]

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>,
... )
Parameters
  • 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 of IDs of the added texts.

Return type

List[str]

async classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) VST

Return VectorStore initialized from documents and embeddings.

async classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) VST

Return VectorStore initialized from texts and embeddings.

Return docs selected using the maximal marginal relevance.

async amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) List[Document]

Return docs selected using the maximal marginal relevance.

as_retriever(**kwargs: Any) VectorStoreRetriever
async asearch(query: str, search_type: str, **kwargs: Any) List[Document]

Return docs most similar to query using specified search type.

Return docs most similar to query.

async asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) List[Document]

Return docs most similar to embedding vector.

async asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) List[Tuple[Document, float]]

Return docs most similar to query.

delete(ids: Optional[List[str]] = None, **kwargs: Any) bool[source]

Delete the entities in the dataset.

Parameters
  • 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

Whether the delete operation was successful.

Return type

bool

delete_dataset() None[source]

Delete the collection.

ds() Any[source]
classmethod force_delete_by_path(path: str) None[source]

Force delete dataset by path.

Parameters

path (str) – path of the dataset to delete.

Raises

ValueError – if deeplake is not installed.

classmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) VST

Return VectorStore initialized from documents and embeddings.

classmethod from_texts(texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, dataset_path: str = './deeplake/', **kwargs: Any) DeepLake[source]

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>, … )

Parameters
  • 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

Deep Lake dataset.

Return type

DeepLake

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>, … )

Parameters
  • 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.

  • **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.

max_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, exec_option: Optional[str] = None, **kwargs: Any) List[Document][source]

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>, … )

Parameters
  • 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.

  • **kwargs – Additional keyword arguments.

Returns

List[Documents] - A list of documents.

search(query: str, search_type: str, **kwargs: Any) List[Document]

Return docs most similar to query using specified search type.

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",
... )
Parameters
  • 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.

Returns

List of Documents most similar to the query vector.

Return type

List[Document]

similarity_search_by_vector(embedding: Union[List[float], ndarray], k: int = 4, **kwargs: Any) List[Document][source]

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>,
... )
Parameters
  • 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.

Returns

List of Documents most similar to the query vector.

Return type

List[Document]

similarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) List[Tuple[Document, float]]

Return docs and relevance scores in the range [0, 1].

0 is dissimilar, 1 is most similar.

Parameters
  • query – input text

  • k – Number of Documents to return. Defaults to 4.

  • **kwargs

    kwargs to be passed to similarity search. Should include: score_threshold: Optional, a floating point value between 0 to 1 to

    filter the resulting set of retrieved docs

Returns

List of Tuples of (doc, similarity_score)

similarity_search_with_score(query: str, k: int = 4, **kwargs: Any) List[Tuple[Document, float]][source]

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>, … )

Parameters
  • 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.

Returns

List of documents most similar to the query

text with distance in float.

Return type

List[Tuple[Document, float]]

property embeddings: Optional[langchain.embeddings.base.Embeddings]

Access the query embedding object if available.

Examples using DeepLake