id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
53
121
926f7a3a3a06-4
def _build_insert_sql(self, transac: Iterable, column_names: Iterable[str]) -> str: ks = ",".join(column_names) embed_tuple_index = tuple(column_names).index( self.config.column_map["embedding"] ) _data = [] for n in transac: n = ",".join( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
926f7a3a3a06-5
metadata: Optional column data to be inserted Returns: List of ids from adding the texts into the VectorStore. """ # Embed and create the documents ids = ids or [sha1(t.encode("utf-8")).hexdigest() for t in texts] colmap_ = self.config.column_map transac = [] ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
926f7a3a3a06-6
return [] [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]] = None, config: Optional[StarRocksSettings] = None, text_ids: Optional[Iterable[str]] = None, batch_size: int = 32, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
926f7a3a3a06-7
_repr += f"\033[1musername: {self.config.username}\033[0m\n\nTable Schema:\n" width = 25 fields = 3 _repr += "-" * (width * fields + 1) + "\n" columns = ["name", "type", "key"] _repr += f"|\033[94m{columns[0]:24s}\033[0m|\033[96m{columns[1]:24s}" _repr += f"\033[0m|\033[9...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
926f7a3a3a06-8
q_str = f""" SELECT {self.config.column_map['document']}, {self.config.column_map['metadata']}, cosine_similarity_norm(array<float>[{q_emb_str}], {self.config.column_map['embedding']}) as dist FROM {self.config.database}.{self.config.table} ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
926f7a3a3a06-9
"""Perform a similarity search with StarRocks by vectors Args: 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 No...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
926f7a3a3a06-10
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 of SQL injection. When dealing with metadatas, remember to use `{self.metadata...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
bf9be4fbeeec-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
bf9be4fbeeec-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
bf9be4fbeeec-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
bf9be4fbeeec-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
bf9be4fbeeec-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
bf9be4fbeeec-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
bf9be4fbeeec-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
bf9be4fbeeec-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
862f01a7db39-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
862f01a7db39-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
862f01a7db39-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
862f01a7db39-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
862f01a7db39-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
862f01a7db39-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
862f01a7db39-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
862f01a7db39-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
862f01a7db39-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
862f01a7db39-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
862f01a7db39-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
7abb230f4ea9-0
Source code for langchain.vectorstores.rocksetdb """Wrapper around Rockset vector database.""" from __future__ import annotations import logging from enum import Enum from typing import Any, Iterable, List, Optional, Tuple from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
7abb230f4ea9-1
client: Any, embeddings: Embeddings, collection_name: str, text_key: str, embedding_key: str, ): """Initialize with Rockset client. Args: client: Rockset client object collection: Rockset collection to insert docs / query embeddings...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
7abb230f4ea9-2
"""Run more texts through the embeddings and add to the vectorstore Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ids: Optional list of ids to associate with the texts. batch_si...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
7abb230f4ea9-3
) -> Rockset: """Create Rockset wrapper with existing texts. This is intended as a quicker way to get started. """ # Sanitize imputs assert client is not None, "Rockset Client cannot be None" assert collection_name, "Collection name cannot be empty" assert text_ke...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
7abb230f4ea9-4
k (int, optional): Top K neighbors to retrieve. Defaults to 4. where_str (Optional[str], optional): Metadata filters supplied as a SQL `where` condition string. Defaults to None. eg. "price<=70.0 AND brand='Nintendo'" NOTE: Please do not let end-user to fill this ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
7abb230f4ea9-5
"""Accepts a query_embedding (vector), and returns documents with similar embeddings.""" docs_and_scores = self.similarity_search_by_vector_with_relevance_scores( embedding, k, distance_func, where_str, **kwargs ) return [doc for doc, _ in docs_and_scores] [docs] def simil...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
7abb230f4ea9-6
self._text_key, type(v) ) page_content = v elif k == "dist": assert isinstance( v, float ), "Computed distance between vectors must of type `float`. \ But found {}".format( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
7abb230f4ea9-7
collection=self._collection_name, data=batch ) return [doc_status._id for doc_status in add_doc_res.data] [docs] def delete_texts(self, ids: List[str]) -> None: """Delete a list of docs from the Rockset collection""" try: from rockset.models import DeleteDocumentsRequestDa...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
d4f44340bf93-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
d4f44340bf93-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
d4f44340bf93-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
d4f44340bf93-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
d4f44340bf93-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
d4f44340bf93-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
d4f44340bf93-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
d4f44340bf93-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
d4f44340bf93-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
d4f44340bf93-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
d4f44340bf93-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
35778753d1dd-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
35778753d1dd-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
35778753d1dd-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
35778753d1dd-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
35778753d1dd-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
35778753d1dd-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
35778753d1dd-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
35778753d1dd-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
84c33472e2d3-0
Source code for langchain.vectorstores.clickhouse """Wrapper around open source ClickHouse VectorSearch capability.""" 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, Union from pydantic im...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
84c33472e2d3-1
Defaults to 'vector_table'. metric (str) : Metric to compute distance, supported are ('angular', 'euclidean', 'manhattan', 'hamming', 'dot'). Defaults to 'angular'. https://github.com/spotify/annoy/blob/main/src/annoymodule.cc#L149-L169 ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
84c33472e2d3-2
return getattr(self, item) class Config: env_file = ".env" env_prefix = "clickhouse_" env_file_encoding = "utf-8" [docs]class Clickhouse(VectorStore): """Wrapper around ClickHouse vector database You need a `clickhouse-connect` python package, and a valid account to connect to Cl...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
84c33472e2d3-3
assert self.config assert self.config.host and self.config.port assert ( self.config.column_map and self.config.database and self.config.table and self.config.metric ) for k in ["id", "embedding", "document", "metadata", "uuid"]: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
84c33472e2d3-4
""" self.dim = dim self.BS = "\\" self.must_escape = ("\\", "'") self.embedding_function = embedding self.dist_order = "ASC" # Only support ConsingDistance and L2Distance # Create a connection to clickhouse self.client = get_client( host=self.config.h...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
84c33472e2d3-5
[docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, batch_size: int = 32, ids: Optional[Iterable[str]] = None, **kwargs: Any, ) -> List[str]: """Insert more texts through the embeddings and add to the VectorStore. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
84c33472e2d3-6
transac.append(v) if len(transac) == batch_size: if t: t.join() t = Thread(target=self._insert, args=[transac, keys]) t.start() transac = [] if len(transac) > 0: if t: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
84c33472e2d3-7
Returns: ClickHouse 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 ClickHouse Vector Store, prints backends, username ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
84c33472e2d3-8
else: where_str = "" settings_strs = [] if self.config.index_query_params: for k in self.config.index_query_params: settings_strs.append(f"SETTING {k}={self.config.index_query_params[k]}") q_str = f""" SELECT {self.config.column_map['document']...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
84c33472e2d3-9
self, embedding: List[float], k: int = 4, where_str: Optional[str] = None, **kwargs: Any, ) -> List[Document]: """Perform a similarity search with ClickHouse by vectors Args: query (str): query string k (int, optional): Top K neighbors to retri...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
84c33472e2d3-10
Args: 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...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
6148901c39e6-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
6148901c39e6-1
- Useful for testing. """ 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, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
6148901c39e6-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
6148901c39e6-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
6148901c39e6-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
6148901c39e6-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
6148901c39e6-6
) for result in results ] return documents_with_scores [docs] def similarity_search_by_vector( self, embedding: List[float], k: int = 4, filter: Optional[dict] = None, **kwargs: Any, ) -> List[Document]: """Return docs most similar to em...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
6148901c39e6-7
connection_string=connection_string, collection_name=collection_name, embedding_function=embedding, embedding_dimension=embedding_dimension, pre_delete_collection=pre_delete_collection, ) store.add_texts(texts=texts, metadatas=metadatas, ids=ids, **kwargs)...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
6148901c39e6-8
return cls.from_texts( texts=texts, pre_delete_collection=pre_delete_collection, embedding=embedding, embedding_dimension=embedding_dimension, metadatas=metadatas, ids=ids, collection_name=collection_name, **kwargs, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
371726e38a5b-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
371726e38a5b-1
f"client should be an instance of pinecone.index.Index, " 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: Itera...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
371726e38a5b-2
self, query: str, 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. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
371726e38a5b-3
"""Return pinecone documents most similar to query. 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 i...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
371726e38a5b-4
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/pinecone.html
371726e38a5b-5
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/pinecone.html
371726e38a5b-6
embeddings = OpenAIEmbeddings() pinecone = Pinecone.from_texts( texts, embeddings, index_name="langchain-demo" ) """ try: import pinecone except ImportError: raise ValueError( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
371726e38a5b-7
else: metadata = [{} for _ in range(i, i_end)] for j, line in enumerate(lines_batch): metadata[j][text_key] = line to_upsert = zip(ids_batch, embeds, metadata) # upsert to Pinecone index.upsert(vectors=list(to_upsert), namespace=namespace) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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
90d57b75adf4-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