id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
54
121
73bbcb23f714-12
metadata_field = _get_kwargs_value(kwargs, "metadata_field", "metadata") # Get embedding of the user query embedding = self.embedding_function.embed_query(query) # Do ANN/KNN search to get top fetch_k results where fetch_k >= k results = self._raw_similarity_search_with_score(query, fetc...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
73bbcb23f714-13
and lucene engines recommended for large datasets. Also supports brute force search through Script Scoring and Painless Scripting. Optional Args: vector_field: Document field embeddings are stored in. Defaults to "vector_field". text_field: Document field the text of ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
73bbcb23f714-14
"ef_search", "ef_construction", "m", ] embeddings = embedding.embed_documents(texts) _validate_embeddings_and_bulk_size(len(embeddings), bulk_size) dim = len(embeddings[0]) # Get the index name from either from kwargs or ENV Variable # before falli...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
73bbcb23f714-15
metadatas=metadatas, vector_field=vector_field, text_field=text_field, mapping=mapping, ) return cls(opensearch_url, index_name, embedding, **kwargs)
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
89d4fa1cf376-0
Source code for langchain.vectorstores.faiss """Wrapper around FAISS vector database.""" from __future__ import annotations import math import os import pickle import uuid from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple import numpy as np from langchain.docstore.base imp...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
89d4fa1cf376-1
return faiss def _default_relevance_score_fn(score: float) -> float: """Return a similarity score on a scale [0, 1].""" # The 'correct' relevance function # may differ depending on a few things, including: # - the distance / similarity metric used by the VectorStore # - the scale of your embeddings ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
89d4fa1cf376-2
self._normalize_L2 = normalize_L2 def __add( self, texts: Iterable[str], embeddings: Iterable[List[float]], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any, ) -> List[str]: if not isinstance(self.docstore, AddableMixi...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
89d4fa1cf376-3
return [_id for _, _id, _ in full_info] [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
89d4fa1cf376-4
ids: Optional list of unique IDs. Returns: List of ids from adding the texts into the vectorstore. """ if not isinstance(self.docstore, AddableMixin): raise ValueError( "If trying to add texts, the underlying docstore should support " f"add...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
89d4fa1cf376-5
vector = np.array([embedding], dtype=np.float32) if self._normalize_L2: faiss.normalize_L2(vector) scores, indices = self.index.search(vector, k if filter is None else fetch_k) docs = [] for j, i in enumerate(indices[0]): if i == -1: # This happens...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
89d4fa1cf376-6
Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. fetch_k: (Optional[int]) Number of Documents to fetch before filtering. Defau...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
89d4fa1cf376-7
) return [doc for doc, _ in docs_and_scores] [docs] def similarity_search( self, query: str, k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any, ) -> List[Document]: """Return docs most similar to query. Ar...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
89d4fa1cf376-8
fetch_k: Number of Documents to fetch before filtering 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 diver...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
89d4fa1cf376-9
# This happens when not enough docs are returned. continue _id = self.index_to_docstore_id[i] doc = self.docstore.search(_id) if not isinstance(doc, Document): raise ValueError(f"Could not find document for id {_id}, got {doc}") docs.append...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
89d4fa1cf376-10
[docs] def merge_from(self, target: FAISS) -> None: """Merge another FAISS object with the current one. Add the target FAISS to the current one. Args: target: FAISS object you wish to merge into the current one Returns: None. """ if not isinstan...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
89d4fa1cf376-11
) -> FAISS: faiss = dependable_faiss_import() index = faiss.IndexFlatL2(len(embeddings[0])) vector = np.array(embeddings, dtype=np.float32) if normalize_L2: faiss.normalize_L2(vector) index.add(vector) documents = [] if ids is None: ids = [...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
89d4fa1cf376-12
faiss = FAISS.from_texts(texts, embeddings) """ embeddings = embedding.embed_documents(texts) return cls.__from( texts, embeddings, embedding, metadatas=metadatas, ids=ids, **kwargs, ) [docs] @classmethod def ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
89d4fa1cf376-13
"""Save FAISS index, docstore, and index_to_docstore_id to disk. Args: folder_path: folder path to save index, docstore, and index_to_docstore_id to. index_name: for saving with a specific index file name """ path = Path(folder_path) path.mkdir(exi...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
89d4fa1cf376-14
) # load docstore and index_to_docstore_id with open(path / "{index_name}.pkl".format(index_name=index_name), "rb") as f: docstore, index_to_docstore_id = pickle.load(f) return cls(embeddings.embed_query, index, docstore, index_to_docstore_id) def _similarity_search_with_relevanc...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
8a894195acf4-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
8a894195acf4-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
8a894195acf4-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
8a894195acf4-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
8a894195acf4-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
8a894195acf4-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
8a894195acf4-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
8a894195acf4-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
8a894195acf4-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
e87e3913e0d0-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
e87e3913e0d0-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
e87e3913e0d0-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
e87e3913e0d0-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
e87e3913e0d0-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
e87e3913e0d0-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
540259259ab4-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
540259259ab4-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
540259259ab4-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
540259259ab4-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
540259259ab4-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
540259259ab4-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
540259259ab4-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
540259259ab4-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
3836f701208f-0
Source code for langchain.vectorstores.singlestoredb """Wrapper around SingleStore DB.""" from __future__ import annotations import enum import json from typing import ( Any, ClassVar, Collection, Iterable, List, Optional, Tuple, Type, ) from sqlalchemy.pool import QueuePool from langcha...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
3836f701208f-1
def __init__( self, embedding: Embeddings, *, distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, table_name: str = "embeddings", content_field: str = "content", metadata_field: str = "metadata", vector_field: str = "vector", pool_size...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
3836f701208f-2
max_overflow (int, optional): Determines the maximum number of connections allowed beyond the pool_size. Defaults to 10. timeout (float, optional): Specifies the maximum wait time in seconds for establishing a connection. Defaults to 30. Following arguments pertai...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
3836f701208f-3
conv (dict[int, Callable], optional): A dictionary of data conversion functions. credential_type (str, optional): Specifies the type of authentication to use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO. autocommit (bool, optional): Enables autocommits. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
3836f701208f-4
vectorstore = SingleStoreDB(OpenAIEmbeddings()) """ self.embedding = embedding self.distance_strategy = distance_strategy self.table_name = table_name self.content_field = content_field self.metadata_field = metadata_field self.vector_field = vector_field ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
3836f701208f-5
finally: cur.close() finally: conn.close() [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, embeddings: Optional[List[List[float]]] = None, **kwargs: Any, ) -> List[str]: """Add more texts...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
3836f701208f-6
) -> List[Document]: """Returns the most similar indexed documents to the query text. Uses cosine similarity. Args: query (str): The query text for which to find similar documents. k (int): The number of documents to return. Default is 4. filter (dict): A dict...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
3836f701208f-7
# Creates embedding vector from user query embedding = self.embedding.embed_query(query) conn = self.connection_pool.connect() result = [] where_clause: str = "" where_clause_values: List[Any] = [] if filter: where_clause = "WHERE " arguments = [] ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
3836f701208f-8
+ (k,), ) for row in cur.fetchall(): doc = Document(page_content=row[0], metadata=row[1]) result.append((doc, float(row[2]))) finally: cur.close() finally: conn.close() return result [docs] ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
3836f701208f-9
embedding, distance_strategy=distance_strategy, table_name=table_name, content_field=content_field, metadata_field=metadata_field, vector_field=vector_field, pool_size=pool_size, max_overflow=max_overflow, timeout=timeout, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
b8d4bdf4b23b-0
Source code for langchain.vectorstores.weaviate """Wrapper around weaviate vector database.""" from __future__ import annotations import datetime from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type from uuid import uuid4 import numpy as np from langchain.docstore.document import Document from ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
b8d4bdf4b23b-1
if weaviate_api_key is not None else None ) client = weaviate.Client(weaviate_url, auth_client_secret=auth) return client def _default_score_normalizer(val: float) -> float: return 1 - 1 / (1 + np.exp(val)) def _json_serializable(value: Any) -> Any: if isinstance(value, datetime.datetime): ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
b8d4bdf4b23b-2
) if not isinstance(client, weaviate.Client): raise ValueError( f"client should be an instance of weaviate.Client, got {type(client)}" ) self._client = client self._index_name = index_name self._embedding = embedding self._text_key = text_k...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
b8d4bdf4b23b-3
if self._embedding is not None: vector = self._embedding.embed_documents([text])[0] else: vector = None batch.add_data_object( data_object=data_properties, class_name=self._index_name, uui...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
b8d4bdf4b23b-4
if kwargs.get("search_distance"): content["certainty"] = kwargs.get("search_distance") query_obj = self._client.query.get(self._index_name, self._query_attrs) if kwargs.get("where_filter"): query_obj = query_obj.with_where(kwargs.get("where_filter")) if kwargs.get("additi...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
b8d4bdf4b23b-5
docs.append(Document(page_content=text, metadata=res)) return docs [docs] def max_marginal_relevance_search( self, query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
b8d4bdf4b23b-6
**kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: embedding: Embedding to look up documents similar to. k...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
b8d4bdf4b23b-7
return docs [docs] def similarity_search_with_score( self, query: str, k: int = 4, **kwargs: Any ) -> List[Tuple[Document, float]]: """ Return list of documents most similar to the query text and cosine distance in float for each. Lower score represents more similarity. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
b8d4bdf4b23b-8
return docs_and_scores def _similarity_search_with_relevance_scores( self, query: str, k: int = 4, **kwargs: Any, ) -> List[Tuple[Document, float]]: """Return docs and relevance scores, normalized on a scale from 0 to 1. 0 is dissimilar, 1 is most similar. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
b8d4bdf4b23b-9
weaviate = Weaviate.from_texts( texts, embeddings, weaviate_url="http://localhost:8080" ) """ client = _create_weaviate_client(**kwargs) from weaviate.util import get_valid_uuid index_name = kwargs.get("index_nam...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
b8d4bdf4b23b-10
"class_name": index_name, } if embeddings is not None: params["vector"] = embeddings[i] batch.add_data_object(**params) batch.flush() relevance_score_fn = kwargs.get("relevance_score_fn") by_text: bool = kwargs.get("by_text"...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
5652a56a6ff1-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
5652a56a6ff1-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
5652a56a6ff1-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
5652a56a6ff1-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
5652a56a6ff1-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
5652a56a6ff1-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
5652a56a6ff1-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
5652a56a6ff1-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
5652a56a6ff1-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
5652a56a6ff1-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
5652a56a6ff1-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
e4ee70c4b3b9-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
9f819fb5da00-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
9f819fb5da00-1
): """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
9f819fb5da00-2
Args: query: Text to look up documents similar to. 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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
9f819fb5da00-3
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 """ embedding = self.embedding_function(query) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
9f819fb5da00-4
Returns: List of Documents most similar to the embedding. """ docs_and_scores = self.similarity_search_with_score_by_index( docstore_index, k, search_k ) return [doc for doc, _ in docs_and_scores] [docs] def similarity_search( self, query: str, k: int =...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
9f819fb5da00-5
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. """ idxs = self.index.get_nns_by_vector( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
9f819fb5da00-6
k: Number of Documents to return. Defaults to 4. 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...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html