id
stringlengths
14
16
text
stringlengths
4
1.28k
source
stringlengths
54
121
acf5728c5ee9-11
batch_size: int = 32, text_key: str = "text", index_name: Optional[str] = None, namespace: Optional[str] = None, **kwargs: Any, ) -> Pinecone: """Construct Pinecone wrapper from raw documents. This is a user friendly interface that: 1. Embeds documents. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
acf5728c5ee9-12
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
acf5728c5ee9-13
else: raise ValueError( f"Index '{index_name}' not found in your Pinecone project. " f"Did you mean one of the following indexes: {', '.join(indexes)}" ) for i in range(0, len(texts), batch_size): # set end position of batch i_end =...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
acf5728c5ee9-14
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
acf5728c5ee9-15
"Please install it with `pip install pinecone-client`." ) return cls( pinecone.Index(index_name), embedding.embed_query, text_key, namespace ) [docs] def delete(self, ids: List[str]) -> None: """Delete by vector IDs. Args: ids: List of ids to delete...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
3366fa642411-0
Source code for langchain.vectorstores.tigris from __future__ import annotations import itertools from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple from langchain.embeddings.base import Embeddings from langchain.schema import Document from langchain.vectorstores import VectorStore if TYPE_CHECKING:...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html
3366fa642411-1
except ImportError: raise ValueError( "Could not import tigrisdb python package. " "Please install it with `pip install tigrisdb`" ) self._embed_fn = embeddings self._vector_store = TigrisVectorStore(client.get_search(), index_name) @property ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html
3366fa642411-2
metadatas: Optional list of metadatas associated with the texts. ids: Optional list of ids for documents. Ids will be autogenerated if not provided. kwargs: vectorstore specific parameters Returns: List of ids from adding the texts into the vectorstore. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html
3366fa642411-3
return [doc for doc, _ in docs_with_scores] [docs] def similarity_search_with_score( self, query: str, k: int = 4, filter: Optional[TigrisFilter] = None, ) -> List[Tuple[Document, float]]: """Run similarity search with Chroma with distance. Args: query ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html
3366fa642411-4
vector=vector, k=k, filter_by=filter ) docs: List[Tuple[Document, float]] = [] for r in result: docs.append( ( Document( page_content=r.doc["text"], metadata=r.doc.get("metadata") ), r...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html
3366fa642411-5
if not index_name: raise ValueError("`index_name` is required") if not client: client = TigrisClient() store = cls(client, embedding, index_name) store.add_texts(texts=texts, metadatas=metadatas, ids=ids) return store def _prep_docs( self, text...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html
3366fa642411-6
doc: TigrisDocument = { "text": t, "embeddings": e or [], "metadata": m or {}, } if _id: doc["id"] = _id docs.append(doc) return docs
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html
e9e16c948090-0
Source code for langchain.vectorstores.starrocks """Wrapper around open source StarRocks 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 from pydantic import Base...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-1
""" for a in args: if a not in s: return False return True def debug_output(s: Any) -> None: """ Print a debug message if DEBUG is True. Args: s: The message to print """ if DEBUG: print(s) def get_named_result(connection: Any, query: str) -> List[dict[str...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-2
r = {} for idx, datum in enumerate(value): k = columns[idx][0] r[k] = datum result.append(r) debug_output(result) cursor.close() return result class StarRocksSettings(BaseSettings): """StarRocks Client Configuration Attribute: StarRocks_host (str) : An...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-3
Defaults to 'vector_table'. 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/starrocks.html
e9e16c948090-4
} database: str = "default" table: str = "langchain" def __getitem__(self, item: str) -> Any: return getattr(self, item) class Config: env_file = ".env" env_prefix = "starrocks_" env_file_encoding = "utf-8" [docs]class StarRocks(VectorStore): """Wrapper around StarRoc...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-5
[StarRocks github](https://github.com/StarRocks/starrocks) """ def __init__( self, embedding: Embeddings, config: Optional[StarRocksSettings] = None, **kwargs: Any, ) -> None: """StarRocks Wrapper to LangChain embedding_function (Embeddings): config (S...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-6
self.pgbar = lambda x, **kwargs: x super().__init__() if config is not None: self.config = config else: self.config = StarRocksSettings() assert self.config assert self.config.host and self.config.port assert self.config.column_map and self.config....
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-7
) ENGINE = OLAP PRIMARY KEY(id) DISTRIBUTED BY HASH(id) \ PROPERTIES ("replication_num" = "1")\ """ self.dim = dim self.BS = "\\" self.must_escape = ("\\", "'") self.embedding_function = embedding self.dist_order = "DESC" debug_output(self.config) # Create a con...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-8
return "".join(f"{self.BS}{c}" if c in self.must_escape else c for c in value) 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"] ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-9
VALUES {','.join(_data)} """ return i_str def _insert(self, transac: Iterable, column_names: Iterable[str]) -> None: _insert_query = self._build_insert_sql(transac, column_names) debug_output(_insert_query) get_named_result(self.connection, _insert_que...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-10
batch_size: Batch size of insertion 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...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-11
try: t = None for v in self.pgbar( zip(*values), desc="Inserting data...", total=len(metadatas) ): assert ( len(v[keys.index(self.config.column_map["embedding"])]) == self.dim ) transac.append(v) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-12
except Exception as e: logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") return [] [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]] = None, config: Opt...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-13
config (StarRocksSettings, Optional): StarRocks configuration text_ids (Optional[Iterable], optional): IDs for the texts. Defaults to None. batch_size (int, optional): Batchsize when transmitting data to StarRocks. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-14
""" _repr = f"\033[92m\033[1m{self.config.database}.{self.config.table} @ " _repr += f"{self.config.host}:{self.config.port}\033[0m\n\n" _repr += f"\033[1musername: {self.config.username}\033[0m\n\nTable Schema:\n" width = 25 fields = 3 _repr += "-" * (width * fields + 1)...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-15
_repr += "-" * (width * fields + 1) + "\n" q_str = f"DESC {self.config.database}.{self.config.table}" debug_output(q_str) rs = get_named_result(self.connection, q_str) for r in rs: _repr += f"|\033[94m{r['Field']:24s}\033[0m|\033[96m{r['Type']:24s}" _repr += f"\03...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-16
) -> str: q_emb_str = ",".join(map(str, q_emb)) if where_str: where_str = f"WHERE {where_str}" else: where_str = "" q_str = f""" SELECT {self.config.column_map['document']}, {self.config.column_map['metadata']}, cosine...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-17
) -> List[Document]: """Perform a similarity search with StarRocks Args: query (str): query string k (int, optional): Top K neighbors to retrieve. Defaults to 4. where_str (Optional[str], optional): where condition string. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-18
embedding: List[float], k: int = 4, where_str: Optional[str] = None, **kwargs: Any, ) -> List[Document]: """Perform a similarity search with StarRocks by vectors Args: query (str): query string k (int, optional): Top K neighbors to retrieve. Defaults t...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-19
""" q_str = self._build_query_sql(embedding, k, where_str) try: return [ Document( page_content=r[self.config.column_map["document"]], metadata=json.loads(r[self.config.column_map["metadata"]]), ) for r i...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
e9e16c948090-20
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/starrocks.html
e9e16c948090-21
), r["dist"], ) for r in get_named_result(self.connection, q_str) ] 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: """ ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
8b68bb3e4b98-0
Source code for langchain.vectorstores.vectara """Wrapper around Vectara vector database.""" from __future__ import annotations import json import logging import os from hashlib import md5 from typing import Any, Iterable, List, Optional, Tuple, Type import requests from pydantic import Field from langchain.embeddings....
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
8b68bb3e4b98-1
) """ def __init__( self, vectara_customer_id: Optional[str] = None, vectara_corpus_id: Optional[str] = None, vectara_api_key: Optional[str] = None, ): """Initialize with Vectara API.""" self._vectara_customer_id = vectara_customer_id or os.environ.get( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
8b68bb3e4b98-2
): logging.warning( "Cant find Vectara credentials, customer_id or corpus_id in " "environment." ) else: logging.debug(f"Using corpus id {self._vectara_corpus_id}") self._session = requests.Session() # to reuse connections adap...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
8b68bb3e4b98-3
Args: url (str): URL of the page to delete. doc_id (str): ID of the document to delete. Returns: bool: True if deletion was successful, False otherwise. """ body = { "customer_id": self._vectara_customer_id, "corpus_id": self._vectara_c...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
8b68bb3e4b98-4
f"{response.text}" ) return False return True def _index_doc(self, doc: dict) -> bool: request: dict[str, Any] = {} request["customer_id"] = self._vectara_customer_id request["corpus_id"] = self._vectara_corpus_id request["document"] = doc resp...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
8b68bb3e4b98-5
return False else: return True [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: texts:...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
8b68bb3e4b98-6
doc = { "document_id": doc_id, "metadataJson": json.dumps({"source": "langchain"}), "parts": [ {"text": text, "metadataJson": json.dumps(md)} for text, md in zip(texts, metadatas) ], } succeeded = self._index_doc(doc) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
8b68bb3e4b98-7
"""Return Vectara documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 5. lambda_val: lexical match parameter for hybrid search. filter: Dictionary of argument(s) to fi...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
8b68bb3e4b98-8
"start": 0, "num_results": k, "context_config": { "sentences_before": n_sentence_context, "sentences_after": n_sentence_context, }, "corpus_key": [ ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
8b68bb3e4b98-9
"Query failed %s", f"(code {response.status_code}, reason {response.reason}, details " f"{response.text})", ) return [] result = response.json() responses = result["responseSet"][0]["response"] vectara_default_metadata = ["lang", "len", "of...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
8b68bb3e4b98-10
filter: Optional[str] = None, n_sentence_context: int = 0, **kwargs: Any, ) -> List[Document]: """Return Vectara documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults t...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
8b68bb3e4b98-11
query, k=k, lambda_val=lambda_val, filter=filter, n_sentence_context=n_sentence_context, **kwargs, ) return [doc for doc, _ in docs_and_scores] [docs] @classmethod def from_texts( cls: Type[Vectara], texts: List[str], ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
8b68bb3e4b98-12
vectara_customer_id=customer_id, vectara_corpus_id=corpus_id, vectara_api_key=api_key, ) """ # Note: Vectara generates its own embeddings, so we ignore the provided # embeddings (required by interface) vectara = cls(**kwargs) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
8b68bb3e4b98-13
"n_sentence_context": "0", } ) """Search params. k: Number of Documents to return. Defaults to 5. lambda_val: lexical match parameter for hybrid search. filter: Dictionary of argument(s) to filter on metadata. For example a filter can be "doc.rating > 3.0 and part.lan...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
8b68bb3e4b98-14
texts (List[str]): The text metadatas (List[dict]): Metadata dicts, must line up with existing store """ self.vectorstore.add_texts(texts, metadatas)
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
31f9b9315f8c-0
Source code for langchain.vectorstores.hologres """VectorStore wrapper around a Hologres database.""" from __future__ import annotations import json import logging import uuid from typing import Any, Dict, Iterable, List, Optional, Tuple, Type from langchain.docstore.document import Document from langchain.embeddings.b...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-1
self.ndims = ndims def create_vector_extension(self) -> None: self.cursor.execute("create extension if not exists proxima") self.conn.commit() def create_table(self, drop_if_exist: bool = True) -> None: if drop_if_exist: self.cursor.execute(f"drop table if exists {self.table_...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-2
'{"embedding":{"algorithm":"Graph", "distance_method":"SquaredEuclidean", "build_params":{"min_flush_proxima_row_count" : 1, "min_compaction_proxima_row_count" : 1, "max_total_size_to_merge_mb" : 2000}}}');""" ) self.conn.commit() def get_by_id(self, id: str) -> List[Tuple]: statement = ( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-3
id: Optional[str] = None, ) -> None: self.cursor.execute( f'insert into "{self.table_name}" ' f"values (%s, array{json.dumps(embedding)}::float4[], %s, %s)", (id if id is not None else "null", json.dumps(metadata), document), ) self.conn.commit() def q...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-4
params.append(val) filter_clause = "where " + " and ".join(conjuncts) sql = ( f"select document, metadata::text, " f"pm_approx_squared_euclidean_distance(array{json.dumps(embedding)}" f"::float4[], embedding) as distance from" f" {self.table_name} {fil...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-5
- `table_name` is the name of the table to store embeddings and data. (default: langchain_pg_embedding) - NOTE: The table will be created when initializing the store (if not exists) So, make sure the user has the right permissions to create tables. - `pre_delete_table` if True, will dele...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-6
self.ndims = ndims self.table_name = table_name self.embedding_function = embedding_function self.pre_delete_table = pre_delete_table self.logger = logger or logging.getLogger(__name__) self.__post_init__() def __post_init__( self, ) -> None: """ I...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-7
@classmethod def __from( cls, texts: List[str], embeddings: List[List[float]], embedding_function: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, ndims: int = ADA_TOKEN_COUNT, table_name: str = _LANGCHAIN_DEFAULT_T...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-8
ndims=ndims, table_name=table_name, pre_delete_table=pre_delete_table, ) store.add_embeddings( texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs ) return store [docs] def add_embeddings( self, texts: Iterable...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-9
""" try: for text, metadata, embedding, id in zip(texts, metadatas, embeddings, ids): self.storage.insert(embedding, metadata, text, id) except Exception as e: self.logger.exception(e) self.storage.conn.commit() [docs] def add_texts( self, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-10
Returns: List of ids from adding the texts into the vectorstore. """ if ids is None: ids = [str(uuid.uuid1()) for _ in texts] embeddings = self.embedding_function.embed_documents(list(texts)) if not metadatas: metadatas = [{} for _ in texts] se...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-11
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.similarity_search_by_vector( embedding=embedding, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-12
Returns: List of Documents most similar to the query vector. """ docs_and_scores = self.similarity_search_with_score_by_vector( embedding=embedding, k=k, filter=filter ) return [doc for doc, _ in docs_and_scores] [docs] def similarity_search_with_score( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-13
""" embedding = self.embedding_function.embed_query(query) docs = self.similarity_search_with_score_by_vector( embedding=embedding, k=k, filter=filter ) return docs [docs] def similarity_search_with_score_by_vector( self, embedding: List[float], k: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-14
[docs] @classmethod def from_texts( cls: Type[Hologres], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ndims: int = ADA_TOKEN_COUNT, table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME, ids: Optional[List[str]] = None, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-15
metadatas=metadatas, ids=ids, ndims=ndims, table_name=table_name, pre_delete_table=pre_delete_table, **kwargs, ) [docs] @classmethod def from_embeddings( cls, text_embeddings: List[Tuple[str, List[float]]], embedding: Emb...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-16
Postgres connection string is required "Either pass it as a parameter or set the HOLOGRES_CONNECTION_STRING environment variable. Example: .. code-block:: python from langchain import Hologres from langchain.embeddings import OpenAIEmbeddings ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-17
table_name=table_name, pre_delete_table=pre_delete_table, **kwargs, ) [docs] @classmethod def from_existing_index( cls: Type[Hologres], embedding: Embeddings, ndims: int = ADA_TOKEN_COUNT, table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME, pre...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-18
pre_delete_table=pre_delete_table, ) return store [docs] @classmethod def get_connection_string(cls, kwargs: Dict[str, Any]) -> str: connection_string: str = get_from_dict_or_env( data=kwargs, key="connection_string", env_key="HOLOGRES_CONNECTION_STRING...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-19
ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any, ) -> Hologres: """ Return VectorStore initialized from documents and embeddings. Postgres connection string is required "Either pass it as a parameter or set the HOLOGRES_CONN...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
31f9b9315f8c-20
**kwargs, ) [docs] @classmethod def connection_string_from_db_params( cls, host: str, port: int, database: str, user: str, password: str, ) -> str: """Return connection string from database parameters.""" return ( f"dbname={d...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
f218ee937c07-0
Source code for langchain.vectorstores.redis """Wrapper around Redis vector database.""" from __future__ import annotations import json import logging import uuid from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Literal, Mapping, Optional, Tuple, Type,...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-1
# required modules REDIS_REQUIRED_MODULES = [ {"name": "search", "ver": 20400}, {"name": "searchlight", "ver": 20400}, ] # distance mmetrics REDIS_DISTANCE_METRICS = Literal["COSINE", "IP", "L2"] def _check_redis_module_exist(client: RedisType, required_modules: List[dict]) -> None: """Check if the correct ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-2
error_message = ( "Redis cannot be used as a vector database without RediSearch >=2.4" "Please head to https://redis.io/docs/stack/search/quick_start/" "to know more about installing the RediSearch module within Redis Stack." ) logging.error(error_message) raise ValueError(error_mess...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-3
def _redis_prefix(index_name: str) -> str: """Redis key prefix for a given index.""" return f"doc:{index_name}" def _default_relevance_score(val: float) -> float: return 1 - val [docs]class Redis(VectorStore): """Wrapper around Redis vector database. To use, you should have the ``redis`` python pack...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-4
redis_url: str, index_name: str, embedding_function: Callable, content_key: str = "content", metadata_key: str = "metadata", vector_key: str = "content_vector", relevance_score_fn: Optional[ Callable[[float], float] ] = _default_relevance_score, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-5
_check_redis_module_exist(redis_client, REDIS_REQUIRED_MODULES) except ValueError as e: raise ValueError(f"Redis failed to connect: {e}") self.client = redis_client self.content_key = content_key self.metadata_key = metadata_key self.vector_key = vector_key se...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-6
) # Check if index exists if not _check_index_exists(self.client, self.index_name): # Define schema schema = ( TextField(name=self.content_key), TextField(name=self.metadata_key), VectorField( self.vector_key, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-7
embeddings: Optional[List[List[float]]] = None, batch_size: int = 1000, **kwargs: Any, ) -> List[str]: """Add more texts to the vectorstore. Args: texts (Iterable[str]): Iterable of strings/text to add to the vectorstore. metadatas (Optional[List[dict]], optio...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-8
""" ids = [] prefix = _redis_prefix(self.index_name) # Get keys or ids from kwargs # Other vectorstores use ids keys_or_ids = kwargs.get("keys", kwargs.get("ids")) # Write data to redis pipeline = self.client.pipeline(transaction=False) for i, text in enum...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-9
}, ) ids.append(key) # Write batch if i % batch_size == 0: pipeline.execute() # Cleanup final batch pipeline.execute() return ids [docs] def similarity_search( self, query: str, k: int = 4, **kwargs: Any ) -> List[Doc...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-10
[docs] def similarity_search_limit_score( self, query: str, k: int = 4, score_threshold: float = 0.2, **kwargs: Any ) -> List[Document]: """ Returns the most similar indexed documents to the query text within the score_threshold range. Args: query (str): The qu...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-11
including the match score for each document. Note: If there are no documents that satisfy the score_threshold value, an empty list is returned. """ docs_and_scores = self.similarity_search_with_score(query, k=k) return [doc for doc, score in docs_and_scores if sco...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-12
) return_fields = [self.metadata_key, self.content_key, "vector_score"] return ( Query(base_query) .return_fields(*return_fields) .sort_by("vector_score") .paging(0, k) .dialect(2) ) [docs] def similarity_search_with_score( s...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-13
# Creates Redis query redis_query = self._prepare_query(k) params_dict: Mapping[str, str] = { "vector": np.array(embedding) # type: ignore .astype(dtype=np.float32) .tobytes() } # Perform vector search results = self.client.ft(self.index_name)...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-14
"""Return docs and relevance scores, normalized on a scale from 0 to 1. 0 is dissimilar, 1 is most similar. """ if self.relevance_score_fn is None: raise ValueError( "relevance_score_fn must be provided to" " Redis constructor to normalize scores" ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-15
metadata_key: str = "metadata", vector_key: str = "content_vector", distance_metric: REDIS_DISTANCE_METRICS = "COSINE", **kwargs: Any, ) -> Tuple[Redis, List[str]]: """Create a Redis vectorstore from raw documents. This is a user-friendly interface that: 1. Embeds...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-16
embeddings = OpenAIEmbeddings() redisearch, keys = RediSearch.from_texts_return_keys( texts, embeddings, redis_url="redis://username:password@localhost:6379" ) """ redis_url = get_from_dict_or_env(kwargs, "redis_...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-17
embeddings = embedding.embed_documents(texts) # Create the search index instance._create_index(dim=len(embeddings[0]), distance_metric=distance_metric) # Add data to Redis keys = instance.add_texts(texts, metadatas, embeddings) return instance, keys [docs] @classmethod def...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-18
1. Embeds documents. 2. Creates a new index for the embeddings in Redis. 3. Adds the documents to the newly created Redis index. This is intended to be a quick way to get started. Example: .. code-block:: python from langchain.vectorstores import Redis...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-19
vector_key=vector_key, **kwargs, ) return instance [docs] @staticmethod def delete( ids: List[str], **kwargs: Any, ) -> bool: """ Delete a Redis entry. Args: ids: List of ids (keys) to delete. Returns: bool: W...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-20
) try: # We need to first remove redis_url from kwargs, # otherwise passing it to Redis will result in an error. if "redis_url" in kwargs: kwargs.pop("redis_url") client = redis.from_url(url=redis_url, **kwargs) except ValueError as e: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-21
Args: index_name (str): Name of the index to drop. delete_documents (bool): Whether to drop the associated documents. Returns: bool: Whether or not the drop was successful. """ redis_url = get_from_dict_or_env(kwargs, "redis_url", "REDIS_URL") try: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-22
except ValueError as e: raise ValueError(f"Your redis connected error: {e}") # Check if index exists try: client.ft(index_name).dropindex(delete_documents) logger.info("Drop index") return True except: # noqa: E722 # Index not exist ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-23
except ImportError: raise ValueError( "Could not import redis python package. " "Please install it with `pip install redis`." ) try: # We need to first remove redis_url from kwargs, # otherwise passing it to Redis will result in an ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-24
redis_url, index_name, embedding.embed_query, content_key=content_key, metadata_key=metadata_key, vector_key=vector_key, **kwargs, ) [docs] def as_retriever(self, **kwargs: Any) -> RedisVectorStoreRetriever: return RedisVectorSto...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-25
"""Validate search type.""" if "search_type" in values: search_type = values["search_type"] if search_type not in ("similarity", "similarity_limit"): raise ValueError(f"search_type of {search_type} not allowed.") return values def get_relevant_documents(self, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
f218ee937c07-26
raise NotImplementedError("RedisVectorStoreRetriever does not support async") def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]: """Add documents to vectorstore.""" return self.vectorstore.add_documents(documents, **kwargs) async def aadd_documents( self, doc...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
7403d9ea8923-0
Source code for langchain.vectorstores.zilliz from __future__ import annotations import logging from typing import Any, List, Optional from langchain.embeddings.base import Embeddings from langchain.vectorstores.milvus import Milvus logger = logging.getLogger(__name__) [docs]class Zilliz(Milvus): def _create_index(...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html
7403d9ea8923-1
} try: self.col.create_index( self._vector_field, index_params=self.index_params, using=self.alias, ) # If default did not work, most likely Milvus self-hosted ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html
7403d9ea8923-2
logger.error( "Failed to create an index on collection: %s", self.collection_name ) raise e [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collect...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html