id
stringlengths
14
16
text
stringlengths
4
1.28k
source
stringlengths
54
121
79acd5ad3a21-4
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
79acd5ad3a21-5
try: from tqdm import tqdm self.pgbar = tqdm except ImportError: # Just in case if tqdm is not installed self.pgbar = lambda x: x super().__init__() if config is not None: self.config = config else: self.config = MyS...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
79acd5ad3a21-6
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}.{self.config.table}( {self.config.column_map[...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
79acd5ad3a21-7
) ENGINE = MergeTree ORDER BY {self.config.column_map['id']} """ self.dim = dim self.BS = "\\" self.must_escape = ("\\", "'") self.embedding_function = embedding.embed_query self.dist_order = "ASC" if self.config.metric in ["cosine", "l2"] else "DESC" # Create a c...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
79acd5ad3a21-8
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
79acd5ad3a21-9
texts: Iterable[str], metadatas: Optional[List[dict]] = None, batch_size: int = 32, ids: Optional[Iterable[str]] = None, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
79acd5ad3a21-10
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
79acd5ad3a21-11
if t: t.join() t = Thread(target=self._insert, args=[transac, keys]) t.start() transac = [] if len(transac) > 0: if t: t.join() self._insert(transac, keys) retu...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
79acd5ad3a21-12
text_ids: Optional[Iterable[str]] = None, 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...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
79acd5ad3a21-13
Returns: MyScale Index """ ctx = cls(embedding, config, **kwargs) ctx.add_texts(texts, ids=text_ids, batch_size=batch_size, metadatas=metadatas) return ctx def __repr__(self) -> str: """Text representation for myscale, prints backends, username and schemas. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
79acd5ad3a21-14
_repr += "-" * 51 + "\n" 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...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
79acd5ad3a21-15
q_str = f""" SELECT {self.config.column_map['text']}, {self.config.column_map['metadata']}, dist FROM {self.config.database}.{self.config.table} {where_str} ORDER BY distance({self.config.column_map['vector']}, [{q_emb_str}]) AS dist {sel...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
79acd5ad3a21-16
Defaults to None. 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`. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
79acd5ad3a21-17
query (str): query string k (int, optional): Top K neighbors to retrieve. Defaults to 4. where_str (Optional[str], optional): where condition string. Defaults to None. NOTE: Please do not let end-user to fill this and always be aware ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
79acd5ad3a21-18
] 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
79acd5ad3a21-19
use `{self.metadata_column}.attribute` instead of `attribute` alone. The default name for it is `metadata`. Returns: List[Document]: List of documents most similar to the query text and cosine distance in float for each. Lower score represents more similarit...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
79acd5ad3a21-20
] 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
58087099bdc0-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
58087099bdc0-1
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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-2
""" _LANGCHAIN_DEFAULT_DEEPLAKE_PATH = "./deeplake/" def __init__( self, dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH, token: Optional[str] = None, embedding_function: Optional[Embeddings] = None, read_only: bool = False, ingestion_batch_size: int = 1000, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-3
... 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", ... ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-4
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 s...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-5
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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-6
raise ValueError( "deeplake version should be >= 3.6.3, but you've installed" f" {deeplake.__version__}. Consider upgrading deeplake version \ pip install --upgrade deeplake." ) self.dataset_path = dataset_path self.vectorstore = DeepLakeVe...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-7
ids: Optional[List[str]] = None, **kwargs: Any, ) -> List[str]: """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_...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-8
kwargs = {} if ids: if self._id_tensor_name == "ids": # for backwards compatibility kwargs["ids"] = ids else: kwargs["id"] = ids if metadatas is None: metadatas = [{}] * len(list(texts)) return self.vectorstore.add( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-9
return_score: bool = False, ) -> Any[List[Document], List[Tuple[Document, float]]]: """Function for performing tql_search. Args: tql_query (str): TQL Query string for direct evaluation. Available only for `compute_engine` and `tensor_db`. exec_option (str, opt...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-10
Use runtime = {"db_engine": True} during dataset creation. return_score (bool): Return score with document. Default is False. Returns: List[Document] - A list of documents Raises: ValueError: If return_score is True but some condition is not met. """ r...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-11
def _search( self, query: Optional[str] = None, embedding: Optional[Union[List[float], np.ndarray]] = None, embedding_function: Optional[Callable] = None, k: int = 4, distance_metric: str = "L2", use_maximal_marginal_relevance: bool = False, fetch_k: Optio...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-12
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 (str): `L2` for Euclidean, `L1` for Nuclear, `max` ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-13
- ``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 way...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-14
**kwargs: Additional keyword arguments. Returns: List of Documents by the specified distance metric, if return_score True, return a tuple of (Document, score) Raises: ValueError: if both `embedding` and `embedding_function` are not specified. """ if kw...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-15
if embedding is None: if _embedding_function is None: raise ValueError( "Either `embedding` or `embedding_function` needs to be" " specified." ) embedding = _embedding_function(query) if query else None if isinstance...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-16
metadatas = result["metadata"] texts = result["text"] if use_maximal_marginal_relevance: lambda_mult = kwargs.get("lambda_mult", 0.5) indices = maximal_marginal_relevance( # type: ignore embedding, # type: ignore embeddings, k=min...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-17
] if return_score: return [(doc, score) for doc, score in zip(docs, scores)] return docs [docs] def similarity_search( self, query: str, k: int = 4, **kwargs: Any, ) -> List[Document]: """ Return docs most similar to query. Examp...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-18
... ) 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_metri...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-19
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. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-20
**kwargs, ) [docs] def similarity_search_by_vector( self, embedding: Union[List[float], np.ndarray], k: int = 4, **kwargs: Any, ) -> List[Document]: """ Return docs most similar to embedding vector. Examples: >>> # Search using an embedd...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-21
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}} ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-22
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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-23
return_score=False, **kwargs, ) [docs] def similarity_search_with_score( self, query: str, k: int = 4, **kwargs: Any, ) -> List[Tuple[Document, float]]: """ Run similarity search with Deep Lake with distance returned. Examples: >...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-24
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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-25
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. Resp...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-26
embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, exec_option: Optional[str] = None, **kwargs: Any, ) -> List[Document]: """ Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-27
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. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-28
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 databas...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-29
k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, exec_option: Optional[str] = None, **kwargs: Any, ) -> List[Document]: """Return docs selected using maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-30
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-pyt...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-31
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 ma...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-32
exec_option=exec_option, embedding_function=embedding_function, # type: ignore **kwargs, ) [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, ids: Optio...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-33
... 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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-34
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 inst...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-35
Raises: ValueError: If 'embedding' is provided in kwargs. This is deprecated, please use `embedding_function` instead. """ if kwargs.get("embedding"): raise ValueError( "using embedding as embedidng_functions is deprecated. " "Pleas...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-36
delete_all: Any[bool, None] = None, ) -> bool: """Delete the entities in the dataset. Args: ids (Optional[List[str]], optional): The document_ids to delete. Defaults to None. filter (Optional[Dict[str, str]], optional): The filter to delete by. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
58087099bdc0-37
Args: path (str): path of the dataset to delete. Raises: ValueError: if deeplake is not installed. """ try: import deeplake except ImportError: raise ValueError( "Could not import deeplake python package. " "...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
04321d39b384-0
Source code for langchain.vectorstores.annoy """Wrapper around Annoy vector database.""" from __future__ import annotations import os import pickle import uuid from configparser import ConfigParser from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple import numpy as np from l...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-1
try: import annoy except ImportError: raise ValueError( "Could not import annoy python package. " "Please install it with `pip install --user annoy` " ) return annoy [docs]class Annoy(VectorStore): """Wrapper around Annoy vector database. To use, you shoul...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-2
"""Initialize with necessary components.""" self.embedding_function = embedding_function self.index = index self.metric = metric self.docstore = docstore self.index_to_docstore_id = index_to_docstore_id [docs] def add_texts( self, texts: Iterable[str], ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-3
dists: List of distances of the documents in the index. Returns: List of Documents and scores. """ docs = [] for idx, dist in zip(idxs, dists): _id = self.index_to_docstore_id[idx] doc = self.docstore.search(_id) if not isinstance(doc, Docu...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-4
k: Number of Documents to return. Defaults to 4. search_k: inspect up to search_k nodes which defaults to n_trees * n if not provided Returns: List of Documents most similar to the query and score for each """ idxs, dists = self.index.get_nns_by_vector( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-5
search_k: inspect up to search_k nodes which defaults to n_trees * n if not provided Returns: List of Documents most similar to the query and score for each """ idxs, dists = self.index.get_nns_by_item( docstore_index, k, search_k=search_k, include_distanc...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-6
to n_trees * n if not provided Returns: List of Documents most similar to the query and score for each """ embedding = self.embedding_function(query) docs = self.similarity_search_with_score_by_vector(embedding, k, search_k) return docs [docs] def similarity_search...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-7
""" docs_and_scores = self.similarity_search_with_score_by_vector( embedding, k, search_k ) return [doc for doc, _ in docs_and_scores] [docs] def similarity_search_by_index( self, docstore_index: int, k: int = 4, search_k: int = -1, **kwargs: Any ) -> List[Document]: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-8
docstore_index, k, search_k ) return [doc for doc, _ in docs_and_scores] [docs] def similarity_search( self, query: str, k: int = 4, search_k: int = -1, **kwargs: Any ) -> List[Document]: """Return docs most similar to query. Args: query: Text to look up docume...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-9
[docs] def max_marginal_relevance_search_by_vector( self, 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. Maximal marg...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-10
Defaults to 0.5. Returns: List of Documents selected by maximal marginal relevance. """ idxs = self.index.get_nns_by_vector( embedding, fetch_k, search_k=-1, include_distances=False ) embeddings = [self.index.get_item_vector(i) for i in idxs] mmr_s...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-11
if not isinstance(doc, Document): raise ValueError(f"Could not find document for id {_id}, got {doc}") docs.append(doc) return docs [docs] def max_marginal_relevance_search( self, query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-12
lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. Returns: List of Documents selected by maximal ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-13
**kwargs: Any, ) -> Annoy: if metric not in INDEX_METRICS: raise ValueError( ( f"Unsupported distance metric: {metric}. " f"Expected one of {list(INDEX_METRICS)}" ) ) annoy = dependable_annoy_import() ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-14
index_to_id = {i: str(uuid.uuid4()) for i in range(len(documents))} docstore = InMemoryDocstore( {index_to_id[i]: doc for i, doc in enumerate(documents)} ) return cls(embedding.embed_query, index, metric, docstore, index_to_id) [docs] @classmethod def from_texts( cls, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-15
embedding: Embedding function to use. metadatas: List of metadata dictionaries to associate with documents. metric: Metric to use for indexing. Defaults to "angular". trees: Number of trees to use for indexing. Defaults to 100. n_jobs: Number of jobs to use for indexing. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-16
embeddings = embedding.embed_documents(texts) return cls.__from( texts, embeddings, embedding, metadatas, metric, trees, n_jobs, **kwargs ) [docs] @classmethod def from_embeddings( cls, text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-17
metric: Metric to use for indexing. Defaults to "angular". trees: Number of trees to use for indexing. Defaults to 100. n_jobs: Number of jobs to use for indexing. Defaults to -1 This is a user friendly interface that: 1. Creates an in memory docstore with provided embeddings...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-18
embeddings = [t[1] for t in text_embeddings] return cls.__from( texts, embeddings, embedding, metadatas, metric, trees, n_jobs, **kwargs ) [docs] def save_local(self, folder_path: str, prefault: bool = False) -> None: """Save Annoy index, docstore, and index_to_docstore_id to disk...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-19
"f": self.index.f, "metric": self.metric, } self.index.save(str(path / "index.annoy"), prefault=prefault) with open(path / "index.pkl", "wb") as file: pickle.dump((self.docstore, self.index_to_docstore_id, config_object), file) [docs] @classmethod def load_local( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
04321d39b384-20
path = Path(folder_path) # load index separately since it is not picklable annoy = dependable_annoy_import() # load docstore and index_to_docstore_id with open(path / "index.pkl", "rb") as file: docstore, index_to_docstore_id, config_object = pickle.load(file) f = int...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
f6eb15c794d4-0
Source code for langchain.vectorstores.typesense """Wrapper around Typesense vector search""" from __future__ import annotations import uuid from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings fro...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
f6eb15c794d4-1
import typesense node = { "host": "localhost", # For Typesense Cloud use xxx.a1.typesense.net "port": "8108", # For Typesense Cloud use 443 "protocol": "http" # For Typesense Cloud use https } typesense_client = typesense.Clie...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
f6eb15c794d4-2
def __init__( self, typesense_client: Client, embedding: Embeddings, *, typesense_collection_name: Optional[str] = None, text_key: str = "text", ): """Initialize with Typesense client.""" try: from typesense import Client except Imp...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
f6eb15c794d4-3
self._typesense_collection_name = ( typesense_collection_name or f"langchain-{str(uuid.uuid4())}" ) self._text_key = text_key @property def _collection(self) -> Collection: return self._typesense_client.collections[self._typesense_collection_name] def _prep_texts( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
f6eb15c794d4-4
return [ {"id": _id, "vec": vec, f"{self._text_key}": text, "metadata": metadata} for _id, vec, text, metadata in zip(_ids, embedded_texts, texts, _metadatas) ] def _create_collection(self, num_dim: int) -> None: fields = [ {"name": "vec", "type": "float[]", "num_...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
f6eb15c794d4-5
texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any, ) -> List[str]: """Run more texts through the embedding and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
f6eb15c794d4-6
self._create_collection(len(docs[0]["vec"])) self._collection.documents.import_(docs, {"action": "upsert"}) return [doc["id"] for doc in docs] [docs] def similarity_search_with_score( self, query: str, k: int = 10, filter: Optional[str] = "", ) -> List[Tuple[Do...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
f6eb15c794d4-7
""" embedded_query = [str(x) for x in self._embedding.embed_query(query)] query_obj = { "q": "*", "vector_query": f'vec:([{",".join(embedded_query)}], k:{k})', "filter_by": filter, "collection": self._typesense_collection_name, } docs = [] ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
f6eb15c794d4-8
self, query: str, k: int = 10, filter: Optional[str] = "", **kwargs: Any, ) -> List[Document]: """Return typesense documents most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
f6eb15c794d4-9
embedding: Embeddings, *, host: str = "localhost", port: Union[str, int] = "8108", protocol: str = "http", typesense_api_key: Optional[str] = None, connection_timeout_seconds: int = 2, **kwargs: Any, ) -> Typesense: """Initialize Typesense directly fro...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
f6eb15c794d4-10
) """ try: from typesense import Client except ImportError: raise ValueError( "Could not import typesense python package. " "Please install it with `pip install typesense`." ) node = { "host": host, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
f6eb15c794d4-11
texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, typesense_client: Optional[Client] = None, typesense_client_params: Optional[dict] = None, typesense_collection_name: Optional[str] = None, text_key: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
f6eb15c794d4-12
) vectorstore.add_texts(texts, metadatas=metadatas, ids=ids) return vectorstore
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
acf5728c5ee9-0
Source code for langchain.vectorstores.pinecone """Wrapper around Pinecone vector database.""" from __future__ import annotations import logging import uuid from typing import Any, Callable, Iterable, List, Optional, Tuple import numpy as np from langchain.docstore.document import Document from langchain.embeddings.bas...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
acf5728c5ee9-1
# in your Pinecone console pinecone.init(api_key="***", environment="...") index = pinecone.Index("langchain-demo") embeddings = OpenAIEmbeddings() vectorstore = Pinecone(index, embeddings.embed_query, "text") """ def __init__( self, index: Any, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
acf5728c5ee9-2
f"got {type(index)}" ) self._index = index self._embedding_function = embedding_function self._text_key = text_key self._namespace = namespace [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Opt...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
acf5728c5ee9-3
namespace: Optional pinecone namespace to add the texts to. Returns: List of ids from adding the texts into the vectorstore. """ if namespace is None: namespace = self._namespace # Embed and create the documents docs = [] ids = ids or [str(uuid.uui...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
acf5728c5ee9-4
k: int = 4, filter: Optional[dict] = None, namespace: Optional[str] = None, ) -> List[Tuple[Document, float]]: """Return pinecone documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to r...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
acf5728c5ee9-5
include_metadata=True, namespace=namespace, filter=filter, ) for res in results["matches"]: metadata = res["metadata"] if self._text_key in metadata: text = metadata.pop(self._text_key) score = res["score"] d...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
acf5728c5ee9-6
Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: Dictionary of argument(s) to filter on metadata namespace: Namespace to search in. Default will search in '' namespace. Returns: List of Documen...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
acf5728c5ee9-7
[docs] def max_marginal_relevance_search_by_vector( self, embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[dict] = None, namespace: Optional[str] = None, **kwargs: Any, ) -> List[Document]: ""...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
acf5728c5ee9-8
of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. Returns: List of Documents selected by maximal marginal relevance. """ if namespace is None: namespace = s...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
acf5728c5ee9-9
return [ Document(page_content=metadata.pop((self._text_key)), metadata=metadata) for metadata in selected ] [docs] def max_marginal_relevance_search( self, query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Opt...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
acf5728c5ee9-10
fetch_k: Number of Documents to fetch to pass to MMR algorithm. lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html