id
stringlengths
14
15
text
stringlengths
35
2.51k
source
stringlengths
61
154
173f0a856c90-6
lambda_mult=lambda_mult, ) candidates = _results_to_docs(results) selected_results = [r for i, r in enumerate(candidates) if i in mmr_selected] return selected_results [docs] def max_marginal_relevance_search( self, query: str, k: int = DEFAULT_K, fetch...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
173f0a856c90-7
) return docs [docs] def delete_collection(self) -> None: """Delete the collection.""" self._client.delete_collection(self._collection.name) [docs] def get( self, ids: Optional[OneOrMany[ID]] = None, where: Optional[Where] = None, limit: Optional[int] = None...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
173f0a856c90-8
kwargs["include"] = include return self._collection.get(**kwargs) [docs] def persist(self) -> None: """Persist the collection. This can be used to explicitly persist the data to disk. It will also be called automatically when the object is destroyed. """ if self._persi...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
173f0a856c90-9
client: Optional[chromadb.Client] = None, **kwargs: Any, ) -> Chroma: """Create a Chroma vectorstore from a raw documents. If a persist_directory is specified, the collection will be persisted there. Otherwise, the data will be ephemeral in-memory. Args: texts (Li...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
173f0a856c90-10
client: Optional[chromadb.Client] = None, # Add this line **kwargs: Any, ) -> Chroma: """Create a Chroma vectorstore from a list of documents. If a persist_directory is specified, the collection will be persisted there. Otherwise, the data will be ephemeral in-memory. Args: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
4a21a2dd68dc-0
Source code for langchain.vectorstores.matching_engine """Vertex Matching Engine implementation of the vector store.""" from __future__ import annotations import json import logging import time import uuid from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Type from langchain.docstore.document import Docu...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html
4a21a2dd68dc-1
using this module. See usage in docs/modules/indexes/vectorstores/examples/matchingengine.ipynb. Note that this implementation is mostly meant for reading if you are planning to do a real time implementation. While reading is a real time operation, updating the index takes close ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html
4a21a2dd68dc-2
"to use the MatchingEngine Vectorstore." ) [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. Args: te...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html
4a21a2dd68dc-3
) logger.debug("Updated index with new configuration.") return ids def _upload_to_gcs(self, data: str, gcs_location: str) -> None: """Uploads data to gcs_location. Args: data: The data that will be stored. gcs_location: The location where the data will be stor...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html
4a21a2dd68dc-4
page_content = self._download_from_gcs(f"documents/{doc.id}") results.append(Document(page_content=page_content)) logger.debug("Downloaded documents for query.") return results def _get_index_id(self) -> str: """Gets the correct index id for the endpoint. Returns: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html
4a21a2dd68dc-5
) [docs] @classmethod def from_components( cls: Type["MatchingEngine"], project_id: str, region: str, gcs_bucket_name: str, index_id: str, endpoint_id: str, credentials_path: Optional[str] = None, embedding: Optional[Embeddings] = None, ) -> "Ma...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html
4a21a2dd68dc-6
return cls( project_id=project_id, index=index, endpoint=endpoint, embedding=embedding or cls._get_default_embeddings(), gcs_client=gcs_client, credentials=credentials, gcs_bucket_name=gcs_bucket_name, ) @classmethod def...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html
4a21a2dd68dc-7
) -> MatchingEngineIndex: """Creates a MatchingEngineIndex object by id. Args: index_id: The created index id. project_id: The project to retrieve index from. region: Location to retrieve index from. credentials: GCS credentials. Returns: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html
4a21a2dd68dc-8
A configured GCS client. """ from google.cloud import storage return storage.Client(credentials=credentials, project=project_id) @classmethod def _init_aiplatform( cls, project_id: str, region: str, gcs_bucket_name: str, credentials: "Credentials",...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html
6b03f8d18f8b-0
Source code for langchain.vectorstores.atlas """Wrapper around Atlas by Nomic.""" from __future__ import annotations import logging import uuid from typing import Any, Iterable, List, Optional, Type import numpy as np from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
6b03f8d18f8b-1
is_public (bool): Whether your project is publicly accessible. True by default. reset_project_if_exists (bool): Whether to reset this project if it already exists. Default False. Generally userful during development and testing. """ try: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
6b03f8d18f8b-2
metadatas (Optional[List[dict]], optional): Optional list of metadatas. ids (Optional[List[str]]): An optional list of ids. refresh(bool): Whether or not to refresh indices with the updated data. Default True. Returns: List[str]: List of IDs of the added texts...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
6b03f8d18f8b-3
else: if metadatas is None: data = [ {"text": text, AtlasDB._ATLAS_DEFAULT_ID_FIELD: ids[i]} for i, text in enumerate(texts) ] else: for i, text in enumerate(texts): metadatas[i]["text"] =...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
6b03f8d18f8b-4
""" if self._embedding_function is None: raise NotImplementedError( "AtlasDB requires an embedding_function for text similarity search!" ) _embedding = self._embedding_function.embed_documents([query])[0] embedding = np.array(_embedding).reshape(1, -1) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
6b03f8d18f8b-5
ids (Optional[List[str]]): Optional list of document IDs. If None, ids will be auto created description (str): A description for your project. is_public (bool): Whether your project is publicly accessible. True by default. reset_project_if_exists (bool...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
6b03f8d18f8b-6
ids: Optional[List[str]] = None, name: Optional[str] = None, api_key: Optional[str] = None, persist_directory: Optional[str] = None, description: str = "A description for your project", is_public: bool = True, reset_project_if_exists: bool = False, index_kwargs: O...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
6b03f8d18f8b-7
return cls.from_texts( name=name, api_key=api_key, texts=texts, embedding=embedding, metadatas=metadatas, ids=ids, description=description, is_public=is_public, reset_project_if_exists=reset_project_if_exists, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
b8c55f08f1e5-0
Source code for langchain.vectorstores.supabase from __future__ import annotations import uuid from itertools import repeat from typing import ( TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type, Union, ) import numpy as np from langchain.docstore.document import Document from la...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
b8c55f08f1e5-1
embedding: Embeddings, table_name: str, query_name: Union[str, None] = None, ) -> None: """Initialize with supabase client.""" try: import supabase # noqa: F401 except ImportError: raise ValueError( "Could not import supabase python pa...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
b8c55f08f1e5-2
"""Return VectorStore initialized from texts and embeddings.""" if not client: raise ValueError("Supabase client is required.") if not table_name: raise ValueError("Supabase document table_name is required.") embeddings = embedding.embed_documents(texts) ids = [st...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
b8c55f08f1e5-3
) -> List[Tuple[Document, float]]: vectors = self._embedding.embed_documents([query]) return self.similarity_search_by_vector_with_relevance_scores(vectors[0], k) [docs] def similarity_search_by_vector_with_relevance_scores( self, query: List[float], k: int ) -> List[Tuple[Document, float...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
b8c55f08f1e5-4
), ) for search in res.data if search.get("content") ] return match_result @staticmethod def _texts_to_documents( texts: Iterable[str], metadatas: Optional[Iterable[dict[Any, Any]]] = None, ) -> List[Document]: """Return list of Doc...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
b8c55f08f1e5-5
if len(result.data) == 0: raise Exception("Error inserting: No rows added") # VectorStore.add_vectors returns ids as strings ids = [str(i.get("id")) for i in result.data if i.get("id")] id_list.extend(ids) return id_list [docs] def max_marginal_relevance_se...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
b8c55f08f1e5-6
matched_embeddings, k=k, lambda_mult=lambda_mult, ) filtered_documents = [matched_documents[i] for i in mmr_selected] return filtered_documents [docs] def max_marginal_relevance_search( self, query: str, k: int = 4, fetch_k: int = 20, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
b8c55f08f1e5-7
SELECT id, content, metadata, embedding, 1 -(docstore.embedding <=> query_embedding) AS similarity FROM docstore ORDER BY docstore.embedding <=> query_embedding LIMIT match...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
6937ad042eb1-0
Source code for langchain.vectorstores.awadb """Wrapper around AwaDB for embedding vectors""" from __future__ import annotations import logging import uuid from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type from langchain.docstore.document import Document from langchain.embeddings.base import ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
6937ad042eb1-1
self.table2embeddings: dict[str, Embeddings] = {} if embedding is not None: self.table2embeddings[table_name] = embedding self.using_table_name = table_name [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, is_duplica...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
6937ad042eb1-2
[docs] def similarity_search( self, query: str, k: int = DEFAULT_TOPN, **kwargs: Any, ) -> List[Document]: """Return docs most similar to query.""" if self.awadb_client is None: raise ValueError("AwaDB client is None!!!") embedding = None ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
6937ad042eb1-3
retrieval_docs = self.similarity_search_by_vector(embedding, k, scores) L2_Norm = 0.0 for score in scores: L2_Norm = L2_Norm + score * score L2_Norm = pow(L2_Norm, 0.5) doc_no = 0 for doc in retrieval_docs: doc_tuple = (doc, 1 - (scores[doc_no] / L2_Norm))...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
6937ad042eb1-4
L2_Norm = L2_Norm + score * score L2_Norm = pow(L2_Norm, 0.5) doc_no = 0 for doc in retrieval_docs: doc_tuple = (doc, 1 - scores[doc_no] / L2_Norm) results.append(doc_tuple) doc_no = doc_no + 1 return results [docs] def similarity_search_by_vector( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
6937ad042eb1-5
content = item_detail[item_key] elif ( item_key == "Field@1" or item_key == "text_embedding" ): # embedding field for the document continue elif item_key == "score": # L2 distance if scores is not None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
6937ad042eb1-6
) -> str: """Get the current table.""" return self.using_table_name [docs] @classmethod def from_texts( cls: Type[AwaDB], texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, table_name: str = _DEFAULT_TABLE_NAME...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
6937ad042eb1-7
table_name: str = _DEFAULT_TABLE_NAME, log_and_data_dir: Optional[str] = None, client: Optional[awadb.Client] = None, **kwargs: Any, ) -> AwaDB: """Create an AwaDB vectorstore from a list of documents. If a log_and_data_dir specified, the table will be persisted there. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
945561975e29-0
Source code for langchain.vectorstores.elastic_vector_search """Wrapper around Elasticsearch vector database.""" from __future__ import annotations import uuid from abc import ABC from typing import ( TYPE_CHECKING, Any, Dict, Iterable, List, Mapping, Optional, Tuple, Union, ) from l...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
945561975e29-1
# defined as an abstract base class itself, allowing the creation of subclasses with # their own specific implementations. If you plan to subclass ElasticVectorSearch, # you can inherit from it and define your own implementation of the necessary methods # and attributes. [docs]class ElasticVectorSearch(VectorStore, ABC...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
945561975e29-2
4. Click "Reset password" 5. Follow the prompts to reset the password The format for Elastic Cloud URLs is https://username:password@cluster_id.region_id.gcp.cloud.es.io:9243. Example: .. code-block:: python from langchain import ElasticVectorSearch from langchain.embeddi...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
945561975e29-3
self.index_name = index_name _ssl_verify = ssl_verify or {} try: self.client = elasticsearch.Elasticsearch(elasticsearch_url, **_ssl_verify) except ValueError as e: raise ValueError( f"Your elasticsearch client string is mis-formatted. Got error: {e} " ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
945561975e29-4
# just to save expensive steps for last self.create_index(self.client, self.index_name, mapping) for i, text in enumerate(texts): metadata = metadatas[i] if metadatas else {} request = { "_op_type": "index", "_index": self.index_name, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
945561975e29-5
Returns: List of Documents most similar to the query. """ embedding = self.embedding.embed_query(query) script_query = _default_script_query(embedding, filter) response = self.client_search( self.client, self.index_name, script_query, size=k ) hits...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
945561975e29-6
elasticsearch_url="http://localhost:9200" ) """ elasticsearch_url = elasticsearch_url or get_from_env( "elasticsearch_url", "ELASTICSEARCH_URL" ) index_name = index_name or uuid.uuid4().hex vectorsearch = cls(elasticsearch_url, index_name, embedding, *...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
945561975e29-7
# TODO: Check if this can be done in bulk for id in ids: self.client.delete(index=self.index_name, id=id) [docs]class ElasticKnnSearch(ElasticVectorSearch): """ A class for performing k-Nearest Neighbors (k-NN) search on an Elasticsearch index. The class is designed for a text search sce...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
945561975e29-8
) self.embedding = embedding self.index_name = index_name self.query_field = query_field self.vector_query_field = vector_query_field # If a pre-existing Elasticsearch connection is provided, use it. if es_connection is not None: self.client = es_connection ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
945561975e29-9
"k": k, "num_candidates": num_candidates, } # Case 1: `query_vector` is provided, but not `model_id` -> use query_vector if query_vector and not model_id: knn["query_vector"] = query_vector # Case 2: `query` and `model_id` are provided, -> use query_vector_builder...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
945561975e29-10
search on the Elasticsearch index and returns the results. Args: query: The query or queries to be used for the search. Required if `query_vector` is not provided. k: The number of nearest neighbors to return. Defaults to 10. query_vector: The query vector to ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
945561975e29-11
model_id: Optional[str] = None, size: Optional[int] = 10, source: Optional[bool] = True, knn_boost: Optional[float] = 0.9, query_boost: Optional[float] = 0.1, fields: Optional[ Union[List[Mapping[str, Any]], Tuple[Mapping[str, Any], ...], None] ] = None, )...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
945561975e29-12
included. Defaults to None. vector_query_field: Field name to use in knn search if not default 'vector' query_field: Field name to use in search if not default 'text' Returns: The search results. Raises: ValueError: If neither `query_vector` nor `model_id`...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
fa0bf0c43f71-0
Source code for langchain.vectorstores.mongodb_atlas from __future__ import annotations import logging from typing import ( TYPE_CHECKING, Any, Dict, Generator, Iterable, List, Optional, Tuple, TypeVar, Union, ) from langchain.docstore.document import Document from langchain.embe...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html
fa0bf0c43f71-1
""" Args: collection: MongoDB collection to add the texts to. embedding: Text embedding model to use. text_key: MongoDB field that will contain the text for each document. embedding_key: MongoDB field that will contain the embedding for ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html
fa0bf0c43f71-2
""" batch_size = kwargs.get("batch_size", DEFAULT_INSERT_BATCH_SIZE) _metadatas: Union[List, Generator] = metadatas or ({} for _ in texts) texts_batch = [] metadatas_batch = [] result_ids = [] for i, (text, metadata) in enumerate(zip(texts, _metadatas)): texts...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html
fa0bf0c43f71-3
"""Return MongoDB documents most similar to query, along with scores. Use the knnBeta Operator available in MongoDB Atlas Search This feature is in early access and available only for evaluation purposes, to validate functionality, and to gather feedback from a small closed group of earl...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html
fa0bf0c43f71-4
docs.append((Document(page_content=text, metadata=res), score)) return docs [docs] def similarity_search( self, query: str, k: int = 4, pre_filter: Optional[dict] = None, post_filter_pipeline: Optional[List[Dict]] = None, **kwargs: Any, ) -> List[Document]:...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html
fa0bf0c43f71-5
collection: Optional[Collection[MongoDBDocumentType]] = None, **kwargs: Any, ) -> MongoDBAtlasVectorSearch: """Construct MongoDBAtlasVectorSearch wrapper from raw documents. This is a user-friendly interface that: 1. Embeds documents. 2. Adds the documents to a provid...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html
f76a16c2f8cf-0
Source code for langchain.vectorstores.tair """Wrapper around Tair Vector.""" from __future__ import annotations import json import logging import uuid from typing import Any, Iterable, List, Optional, Type from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from langchain....
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
f76a16c2f8cf-1
index_type: str, data_type: str, **kwargs: Any, ) -> bool: index = self.client.tvs_get_index(self.index_name) if index is not None: logger.info("Index already exists") return False self.client.tvs_create_index( self.index_name, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
f76a16c2f8cf-2
""" Returns the most similar indexed documents to the query text. Args: query (str): The query text for which to find similar documents. k (int): The number of documents to return. Default is 4. Returns: List[Document]: A list of documents that are most simila...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
f76a16c2f8cf-3
if "tair_url" in kwargs: kwargs.pop("tair_url") distance_type = tairvector.DistanceMetric.InnerProduct if "distance_type" in kwargs: distance_type = kwargs.pop("distance_typ") index_type = tairvector.IndexType.HNSW if "index_type" in kwargs: index_type...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
f76a16c2f8cf-4
cls, documents: List[Document], embedding: Embeddings, metadatas: Optional[List[dict]] = None, index_name: str = "langchain", content_key: str = "content", metadata_key: str = "metadata", **kwargs: Any, ) -> Tair: texts = [d.page_content for d in docum...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
f76a16c2f8cf-5
# index not exist logger.info("Index does not exist") return False return True [docs] @classmethod def from_existing_index( cls, embedding: Embeddings, index_name: str = "langchain", content_key: str = "content", metadata_key: str = "metadat...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
88c876174b1f-0
Source code for langchain.vectorstores.deeplake """Wrapper around Activeloop Deep Lake.""" from __future__ import annotations import logging from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union import numpy as np try: import deeplake from deeplake.core.fast_forwarding import version_co...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-1
vectorstore = DeepLake("langchain_store", embeddings.embed_query) """ _LANGCHAIN_DEFAULT_DEEPLAKE_PATH = "./deeplake/" def __init__( self, dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH, token: Optional[str] = None, embedding_function: Optional[Embeddings] = None, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-2
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 inge...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-3
"Please install it with `pip install deeplake`." ) if version_compare(deeplake.__version__, "3.6.2") == -1: raise ValueError( "deeplake version should be >= 3.6.3, but you've installed" f" {deeplake.__version__}. Consider upgrading deeplake version \ ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-4
ids (Optional[List[str]], optional): Optional list of IDs. **kwargs: other optional keyword arguments. Returns: List[str]: List of IDs of the added texts. """ kwargs = {} if ids: if self._id_tensor_name == "ids": # for backwards compatibility ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-5
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. re...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-6
""" 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. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-7
and query execution. Only for data in Deep Lake Managed Database. Use runtime = {"db_engine": True} during dataset creation. **kwargs: Additional keyword arguments. Returns: List of Documents by the specified distance metric, if return_score True, return a...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-8
) scores = result["score"] embeddings = result["embedding"] metadatas = result["metadata"] texts = result["text"] if use_maximal_marginal_relevance: lambda_mult = kwargs.get("lambda_mult", 0.5) indices = maximal_marginal_relevance( # type: ignore ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-9
... 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...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-10
k=k, use_maximal_marginal_relevance=False, return_score=False, **kwargs, ) [docs] def similarity_search_by_vector( self, embedding: Union[List[float], np.ndarray], k: int = 4, **kwargs: Any, ) -> List[Document]: """ Retur...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-11
- "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. - "tens...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-12
... ) 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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-13
text with distance in float.""" return self._search( query=query, k=k, return_score=True, **kwargs, ) [docs] def max_marginal_relevance_search_by_vector( self, embedding: List[float], k: int = 4, fetch_k: int = 20, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-14
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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-15
... 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. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-16
"For MMR search, you must specify an embedding function on" " `creation` or during add call." ) return self._search( query=query, k=k, fetch_k=fetch_k, use_maximal_marginal_relevance=True, lambda_mult=lambda_mult, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-17
(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 ar...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
88c876174b1f-18
metadatas=metadatas, ids=ids, embedding_function=embedding.embed_documents, # type: ignore ) return deeplake_dataset [docs] def delete( self, ids: Any[List[str], None] = None, filter: Any[Dict[str, str], None] = None, delete_all: Any[bool, None...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
1958d10fb430-0
Source code for langchain.vectorstores.myscale """Wrapper around MyScale vector database.""" from __future__ import annotations import json import logging from hashlib import sha1 from threading import Thread from typing import Any, Dict, Iterable, List, Optional, Tuple from pydantic import BaseSettings from langchain....
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
1958d10fb430-1
column_map (Dict) : Column type map to project column name onto langchain semantics. Must have keys: `text`, `id`, `vector`, must be same size to number of columns. For example: .. code-block:: python { ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
1958d10fb430-2
constraints and even sub-queries. For more information, please visit [myscale official site](https://docs.myscale.com/en/overview/) """ def __init__( self, embedding: Embeddings, config: Optional[MyScaleSettings] = None, **kwargs: Any, ) -> None: """MyScal...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
1958d10fb430-3
dim = len(embedding.embed_query("try this out")) index_params = ( ", " + ",".join([f"'{k}={v}'" for k, v in self.config.index_param.items()]) if self.config.index_param else "" ) schema_ = f""" CREATE TABLE IF NOT EXISTS {self.config.database}.{sel...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
1958d10fb430-4
def _build_istr(self, transac: Iterable, column_names: Iterable[str]) -> str: ks = ",".join(column_names) _data = [] for n in transac: n = ",".join([f"'{self.escape_str(str(_n))}'" for _n in n]) _data.append(f"({n})") i_str = f""" INSERT INTO TABLE...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
1958d10fb430-5
column_names = { colmap_["id"]: ids, colmap_["text"]: texts, colmap_["vector"]: map(self.embedding_function, texts), } metadatas = metadatas or [{} for _ in texts] column_names[colmap_["metadata"]] = map(json.dumps, metadatas) assert len(set(colmap_) -...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
1958d10fb430-6
batch_size: int = 32, **kwargs: Any, ) -> MyScale: """Create Myscale wrapper with existing texts Args: embedding_function (Embeddings): Function to extract text embedding texts (Iterable[str]): List or tuple of strings to be added config (MyScaleSettings, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
1958d10fb430-7
for r in self.client.query( f"DESC {self.config.database}.{self.config.table}" ).named_results(): _repr += ( f"|\033[94m{r['name']:24s}\033[0m|\033[96m{r['type']:24s}\033[0m|\n" ) _repr += "-" * 51 + "\n" return _repr def _build_qstr( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
1958d10fb430-8
NOTE: Please do not let end-user to fill this and always be aware of SQL injection. When dealing with metadatas, remember to use `{self.metadata_column}.attribute` instead of `attribute` alone. The default name for it is `metadata`. Returns: List...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
1958d10fb430-9
] except Exception as e: logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") return [] [docs] def similarity_search_with_relevance_scores( self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any ) -> List[Tuple[Document, float]]: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
1958d10fb430-10
] except Exception as e: logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") return [] [docs] def drop(self) -> None: """ Helper function: Drop data """ self.client.command( f"DROP TABLE IF EXISTS {self.config.database}....
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
27c778c1385a-0
Source code for langchain.vectorstores.analyticdb """VectorStore wrapper around a Postgres/PGVector database.""" from __future__ import annotations import logging import uuid from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Type from sqlalchemy import REAL, Column, String, Table, create_engine, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
27c778c1385a-1
""" def __init__( self, connection_string: str, embedding_function: Embeddings, embedding_dimension: int = _LANGCHAIN_DEFAULT_EMBEDDING_DIM, collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, pre_delete_collection: bool = False, logger: Optional[loggin...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
27c778c1385a-2
""" ) result = conn.execute(index_query).scalar() # Create the index if it doesn't exist if not result: index_statement = text( f""" CREATE INDEX {index_name} ON {s...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
27c778c1385a-3
if not metadatas: metadatas = [{} for _ in texts] # Define the table schema chunks_table = Table( self.collection_name, Base.metadata, Column("id", TEXT, primary_key=True), Column("embedding", ARRAY(REAL)), Column("document", String...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
27c778c1385a-4
k (int): Number of results to return. Defaults to 4. filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. Returns: List of Documents most similar to the query. """ embedding = self.embedding_function.embed_query(text=query) return self.similari...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
27c778c1385a-5
**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) """ return self.si...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
27c778c1385a-6
( Document( page_content=result.document, metadata=result.metadata, ), result.distance if self.embedding_function is not None else None, ) for result in results ] return documents_with_scores ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html