id
stringlengths
14
15
text
stringlengths
44
2.47k
source
stringlengths
61
181
581ba3862030-0
Source code for langchain.vectorstores.hologres 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.schema.embeddings import Embeddings from langchain.schema.vectorst...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
581ba3862030-1
array_length(embedding, 1) = {self.ndims}), metadata json, document text);""" ) self.cursor.execute( f"call set_table_property('{self.table_name}'" + """, 'proxima_vectors', '{"embedding":{"algorithm":"Graph", "distance_method":"SquaredEuclidean", "build_params":{"min_flush_prox...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
581ba3862030-2
params = [] filter_clause = "" if filter is not None: conjuncts = [] for key, val in filter.items(): conjuncts.append("metadata->>%s=%s") params.append(key) params.append(val) filter_clause = "where " + " and ".join(conj...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
581ba3862030-3
embedding_function: Embeddings, ndims: int = ADA_TOKEN_COUNT, table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME, pre_delete_table: bool = False, logger: Optional[logging.Logger] = None, ) -> None: self.connection_string = connection_string self.ndims = ndims sel...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
581ba3862030-4
) -> Hologres: if ids is None: ids = [str(uuid.uuid1()) for _ in texts] if not metadatas: metadatas = [{} for _ in texts] connection_string = cls.get_connection_string(kwargs) store = cls( connection_string=connection_string, embedding_func...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
581ba3862030-5
**kwargs: Any, ) -> List[str]: """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. kwargs: vectorstore specific parameters...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
581ba3862030-6
k: int = 4, filter: Optional[dict] = None, **kwargs: Any, ) -> List[Document]: """Return docs most similar to embedding vector. Args: embedding: Embedding to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter (Opt...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
581ba3862030-7
) -> List[Tuple[Document, float]]: results: List[Tuple[str, str, float]] = self.storage.query_nearest_neighbours( embedding, k, filter ) docs = [ ( Document( page_content=result[0], metadata=json.loads(result[1]), ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
581ba3862030-8
ndims: int = ADA_TOKEN_COUNT, table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME, ids: Optional[List[str]] = None, pre_delete_table: bool = False, **kwargs: Any, ) -> Hologres: """Construct Hologres wrapper from raw documents and pre- generated embeddings. Return...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
581ba3862030-9
**kwargs: Any, ) -> Hologres: """ Get intsance of an existing Hologres store.This method will return the instance of the store without inserting any new embeddings """ connection_string = cls.get_connection_string(kwargs) store = cls( connection_st...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
581ba3862030-10
""" texts = [d.page_content for d in documents] metadatas = [d.metadata for d in documents] connection_string = cls.get_connection_string(kwargs) kwargs["connection_string"] = connection_string return cls.from_texts( texts=texts, pre_delete_collection=pre_...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html
e42e95d96e59-0
Source code for langchain.vectorstores.atlas 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.schema.embeddings import Embeddings from langchain.schema.vectorstore impor...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
e42e95d96e59-1
description (str): A description for your project. 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 useful d...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
e42e95d96e59-2
"""Run more texts through the embeddings and add to the vectorstore. Args: texts (Iterable[str]): Texts to add to the vectorstore. metadatas (Optional[List[dict]], optional): Optional list of metadatas. ids (Optional[List[str]]): An optional list of ids. refresh(b...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
e42e95d96e59-3
self.project.add_embeddings(embeddings=embeddings, data=data) # Text upload case else: if metadatas is None: data = [ {"text": text, AtlasDB._ATLAS_DEFAULT_ID_FIELD: ids[i]} for i, text in enumerate(texts) ] ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
e42e95d96e59-4
Returns: List[Document]: List of documents most similar to the query text. """ if self._embedding_function is None: raise NotImplementedError( "AtlasDB requires an embedding_function for text similarity search!" ) _embedding = self._embedding_f...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
e42e95d96e59-5
embedding (Optional[Embeddings]): Embedding function. Defaults to None. metadatas (Optional[List[dict]]): List of metadatas. Defaults to None. ids (Optional[List[str]]): Optional list of document IDs. If None, ids will be auto created description (str): A description ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
e42e95d96e59-6
def from_documents( cls: Type[AtlasDB], documents: List[Document], embedding: Optional[Embeddings] = None, ids: Optional[List[str]] = None, name: Optional[str] = None, api_key: Optional[str] = None, persist_directory: Optional[str] = None, description: str...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
e42e95d96e59-7
texts = [doc.page_content for doc in documents] metadatas = [doc.metadata for doc in documents] return cls.from_texts( name=name, api_key=api_key, texts=texts, embedding=embedding, metadatas=metadatas, ids=ids, descripti...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
c4e331783e11-0
Source code for langchain.vectorstores.starrocks 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 langchain.docstore.document import Document from langchain.pydantic_v1 import BaseSettin...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
c4e331783e11-1
for idx, datum in enumerate(value): k = columns[idx][0] r[k] = datum result.append(r) debug_output(result) cursor.close() return result [docs]class StarRocksSettings(BaseSettings): """StarRocks client configuration. Attribute: StarRocks_host (str) : An URL to ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
c4e331783e11-2
"metadata": "metadata", } 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): ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
c4e331783e11-3
except ImportError: # Just in case if tqdm is not installed 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.con...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
c4e331783e11-4
[docs] def escape_str(self, value: str) -> str: return "".join(f"{self.BS}{c}" if c in self.must_escape else c for c in value) @property def embeddings(self) -> Embeddings: return self.embedding_function def _build_insert_sql(self, transac: Iterable, column_names: Iterable[str]) -> str: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
c4e331783e11-5
"""Insert more texts through the embeddings and add to the VectorStore. Args: texts: Iterable of strings to add to the VectorStore. ids: Optional list of ids to associate with the texts. batch_size: Batch size of insertion metadata: Optional column data to be inse...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
c4e331783e11-6
if t: t.join() self._insert(transac, keys) return [i for i in ids] 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, tex...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
c4e331783e11-7
"""Text representation for StarRocks Vector Store, prints backends, username and schemas. Easy to use with `str(StarRocks())` Returns: repr: string to show connection info and data schema """ _repr = f"\033[92m\033[1m{self.config.database}.{self.config.table} @ " ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
c4e331783e11-8
return _repr def _build_query_sql( self, q_emb: List[float], topk: int, where_str: Optional[str] = None ) -> str: q_emb_str = ",".join(map(str, q_emb)) if where_str: where_str = f"WHERE {where_str}" else: where_str = "" q_str = f""" SEL...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
c4e331783e11-9
""" return self.similarity_search_by_vector( self.embedding_function.embed_query(query), k, where_str, **kwargs ) [docs] def similarity_search_by_vector( self, embedding: List[float], k: int = 4, where_str: Optional[str] = None, **kwargs: Any, )...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
c4e331783e11-10
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]]: """Perform a similarity search with StarRocks Args: query (str): query string k (int, optio...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
c4e331783e11-11
f"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}", ) @property def metadata_column(self) -> str: return self.config.column_map["metadata"]
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html
9c41bedce0e7-0
Source code for langchain.vectorstores.typesense from __future__ import annotations import uuid from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union from langchain.docstore.document import Document from langchain.schema.embeddings import Embeddings from langchain.schema.vectorstore import Vecto...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
9c41bedce0e7-1
*, typesense_collection_name: Optional[str] = None, text_key: str = "text", ): """Initialize with Typesense client.""" try: from typesense import Client except ImportError: raise ImportError( "Could not import typesense python package. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
9c41bedce0e7-2
for _id, vec, text, metadata in zip(_ids, embedded_texts, texts, _metadatas) ] def _create_collection(self, num_dim: int) -> None: fields = [ {"name": "vec", "type": "float[]", "num_dim": num_dim}, {"name": f"{self._text_key}", "type": "string"}, {"name": ".*", "t...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
9c41bedce0e7-3
return [doc["id"] for doc in docs] [docs] def similarity_search_with_score( self, query: str, k: int = 10, filter: Optional[str] = "", ) -> List[Tuple[Document, float]]: """Return typesense documents most similar to query, along with scores. Args: query...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
9c41bedce0e7-4
) -> List[Document]: """Return typesense documents most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 10. Minimum 10 results would be returned. filter: typesense filter_by expression ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
9c41bedce0e7-5
"Please install it with `pip install typesense`." ) node = { "host": host, "port": str(port), "protocol": protocol, } typesense_api_key = typesense_api_key or get_from_env( "typesense_api_key", "TYPESENSE_API_KEY" ) clie...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
de5e8df2488c-0
Source code for langchain.vectorstores.myscale 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 langchain.docstore.document import Document from langchain.pydantic_v1 import BaseSettings...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
de5e8df2488c-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
de5e8df2488c-2
constraints and even sub-queries. For more information, please visit [myscale official site](https://docs.myscale.com/en/overview/) """ [docs] def __init__( self, embedding: Embeddings, config: Optional[MyScaleSettings] = None, **kwargs: Any, ) -> None: """...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
de5e8df2488c-3
logger.warning( "Lower case metric types will be deprecated " "the future. Please use one of ('IP', 'Cosine', 'L2')" ) # initialize the schema dim = len(embedding.embed_query("try this out")) index_params = ( ", " + ",".join([f"'{k}={v}'" f...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
de5e8df2488c-4
password=self.config.password, **kwargs, ) self.client.command("SET allow_experimental_object_type=1") self.client.command(schema_) @property def embeddings(self) -> Embeddings: return self._embeddings [docs] def escape_str(self, value: str) -> str: return ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
de5e8df2488c-5
ids: Optional list of ids to associate with the texts. 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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
de5e8df2488c-6
return [i for i in ids] 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: Iterable[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
de5e8df2488c-7
"""Text representation for myscale, prints backends, username and schemas. Easy to use with `str(Myscale())` Returns: repr: string to show connection info and data schema """ _repr = f"\033[92m\033[1m{self.config.database}.{self.config.table} @ " _repr += f"{self....
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
de5e8df2488c-8
AS dist {self.dist_order} LIMIT {topk} """ return q_str [docs] def similarity_search( self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any ) -> List[Document]: """Perform a similarity search with MyScale Args: query (str)...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
de5e8df2488c-9
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[Document]: List of (Document, similarity) """ q_str = self._build_q...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
de5e8df2488c-10
and cosine distance in float for each. Lower score represents more similarity. """ q_str = self._build_qstr(self._embeddings.embed_query(query), k, where_str) try: return [ ( Document( page_content=r[self.config....
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
9b1ffce7c4dd-0
Source code for langchain.vectorstores.rocksetdb 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.schema.embeddings import Embeddings from langchain.schema.vectorstore import Ve...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
9b1ffce7c4dd-1
text_key: str, embedding_key: str, workspace: str = "commons", ): """Initialize with Rockset client. Args: client: Rockset client object collection: Rockset collection to insert docs / query embeddings: Langchain Embeddings object to use to generat...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
9b1ffce7c4dd-2
ids: Optional[List[str]] = None, batch_size: int = 32, **kwargs: Any, ) -> List[str]: """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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
9b1ffce7c4dd-3
embedding_key: str = "", ids: Optional[List[str]] = None, batch_size: int = 32, **kwargs: Any, ) -> Rockset: """Create Rockset wrapper with existing texts. This is intended as a quicker way to get started. """ # Sanitize imputs assert client is not Non...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
9b1ffce7c4dd-4
distance_func (DistanceFunction): how to compute distance between two vectors in Rockset. 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 N...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
9b1ffce7c4dd-5
**kwargs: Any, ) -> List[Document]: """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 fo...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
9b1ffce7c4dd-6
But found: `{}`".format( self._text_key, type(v) ) page_content = v elif k == "dist": assert isinstance( v, float ), "Computed distance between vectors must of type `float`. \ ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
9b1ffce7c4dd-7
add_doc_res = self._client.Documents.add_documents( collection=self._collection_name, data=batch, workspace=self._workspace ) 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...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
cbe4dbd9f809-0
Source code for langchain.vectorstores.chroma from __future__ import annotations import logging import uuid from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, ) import numpy as np from langchain.docstore.document import Document from langc...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
cbe4dbd9f809-1
from langchain.embeddings.openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings() vectorstore = Chroma("langchain_store", embeddings) """ _LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain" [docs] def __init__( self, collection_name: str = _LANGCHAIN_DEFAUL...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
cbe4dbd9f809-2
if int(major) == 0 and int(minor) < 4: client_settings.chroma_db_impl = "duckdb+parquet" _client_settings = client_settings elif persist_directory: # Maintain backwards compatibility with chromadb < 0.4.0 major, minor, _ = chromadb.__ve...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
cbe4dbd9f809-3
where: Optional[Dict[str, str]] = None, where_document: Optional[Dict[str, str]] = None, **kwargs: Any, ) -> List[Document]: """Query the chroma collection.""" try: import chromadb # noqa: F401 except ImportError: raise ValueError( "Co...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
cbe4dbd9f809-4
embeddings = self._embedding_function.embed_documents(texts) if metadatas: # fill metadatas with empty dicts if somebody # did not specify metadata for all texts length_diff = len(texts) - len(metadatas) if length_diff: metadatas = metadatas + [{}]...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
cbe4dbd9f809-5
embeddings_without_metadatas = ( [embeddings[j] for j in empty_ids] if embeddings else None ) ids_without_metadatas = [ids[j] for j in empty_ids] self._collection.upsert( embeddings=embeddings_without_metadatas, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
cbe4dbd9f809-6
"""Return docs most similar to embedding vector. Args: embedding (List[float]): Embedding to look up documents similar to. k (int): Number of Documents to return. Defaults to 4. filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. Returns: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
cbe4dbd9f809-7
[docs] def similarity_search_with_score( self, query: str, k: int = DEFAULT_K, filter: Optional[Dict[str, str]] = None, where_document: Optional[Dict[str, str]] = None, **kwargs: Any, ) -> List[Tuple[Document, float]]: """Run similarity search with Chroma w...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
cbe4dbd9f809-8
- embedding dimensionality - etc. """ if self.override_relevance_score_fn: return self.override_relevance_score_fn distance = "l2" distance_key = "hnsw:space" metadata = self._collection.metadata if metadata and distance_key in metadata: di...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
cbe4dbd9f809-9
of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. Returns: List of Documents selected by maximal ma...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
cbe4dbd9f809-10
fetch_k: Number of Documents to fetch to pass to MMR algorithm. lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
cbe4dbd9f809-11
limit: The number of documents to return. Optional. offset: The offset to start returning results from. Useful for paging results with limit. Optional. where_document: A WhereDocument type dict used to filter by the documents. E.g. `{$contains: "he...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
cbe4dbd9f809-12
Args: document_id (str): ID of the document to update. document (Document): Document to update. """ return self.update_documents([document_id], [document]) [docs] def update_documents(self, ids: List[str], documents: List[Document]) -> None: """Update a document in the...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
cbe4dbd9f809-13
If a persist_directory is specified, the collection will be persisted there. Otherwise, the data will be ephemeral in-memory. Args: texts (List[str]): List of texts to add to the collection. collection_name (str): Name of the collection to create. persist_directory (O...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
cbe4dbd9f809-14
collection_metadata: Optional[Dict] = None, **kwargs: Any, ) -> Chroma: """Create a Chroma vectorstore from a list of documents. If a persist_directory is specified, the collection will be persisted there. Otherwise, the data will be ephemeral in-memory. Args: col...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
972480929cb6-0
Source code for langchain.vectorstores.usearch from __future__ import annotations from typing import Any, Dict, Iterable, List, Optional, Tuple import numpy as np from langchain.docstore.base import AddableMixin, Docstore from langchain.docstore.document import Document from langchain.docstore.in_memory import InMemory...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html
972480929cb6-1
Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ids: Optional list of unique IDs. Returns: List of ids from adding the texts into the vectorstore. """ if not isinstance(se...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html
972480929cb6-2
matches = self.index.search(np.array(query_embedding), k) docs_with_scores: List[Tuple[Document, float]] = [] for id, score in zip(matches.keys, matches.distances): doc = self.docstore.search(str(id)) if not isinstance(doc, Document): raise ValueError(f"Could not ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html
972480929cb6-3
This is a user friendly interface that: 1. Embeds documents. 2. Creates an in memory docstore 3. Initializes the USearch database This is intended to be a quick way to get started. Example: .. code-block:: python from langchain.vectorstores...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html
98554b528cc0-0
Source code for langchain.vectorstores.docarray.in_memory """Wrapper around in-memory storage.""" from __future__ import annotations from typing import Any, Dict, List, Literal, Optional from langchain.schema.embeddings import Embeddings from langchain.vectorstores.docarray.base import ( DocArrayIndex, _check_d...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html
98554b528cc0-1
[docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]] = None, **kwargs: Any, ) -> DocArrayInMemorySearch: """Create an DocArrayInMemorySearch store and insert data. Args: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html
9068ae2fd985-0
Source code for langchain.vectorstores.docarray.hnsw from __future__ import annotations from typing import Any, List, Literal, Optional from langchain.schema.embeddings import Embeddings from langchain.vectorstores.docarray.base import ( DocArrayIndex, _check_docarray_import, ) [docs]class DocArrayHnswSearch(Do...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html
9068ae2fd985-1
"cosine", "ip", and "l2". Defaults to "cosine". max_elements (int): Maximum number of vectors that can be stored. Defaults to 1024. index (bool): Whether an index should be built for this field. Defaults to True. ef_construction (int): defines a constr...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html
9068ae2fd985-2
work_dir: Optional[str] = None, n_dim: Optional[int] = None, **kwargs: Any, ) -> DocArrayHnswSearch: """Create an DocArrayHnswSearch store and insert data. Args: texts (List[str]): Text data. embedding (Embeddings): Embedding function. metadatas (O...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html
58565e88c920-0
Source code for langchain.vectorstores.docarray.base from abc import ABC from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type import numpy as np from langchain.pydantic_v1 import Field from langchain.schema import Document from langchain.schema.embeddings import Embeddings from langchain.vectors...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html
58565e88c920-1
def _get_doc_cls(**embeddings_params: Any) -> Type["BaseDoc"]: """Get docarray Document class describing the schema of DocIndex.""" from docarray import BaseDoc from docarray.typing import NdArray class DocArrayDoc(BaseDoc): text: Optional[str] embedding: Optional...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html
58565e88c920-2
self, query: str, k: int = 4, **kwargs: Any ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. Returns: List of documents most similar...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html
58565e88c920-3
"""Return docs and relevance scores, normalized on a scale from 0 to 1. 0 is dissimilar, 1 is most similar. """ raise NotImplementedError() [docs] def similarity_search_by_vector( self, embedding: List[float], k: int = 4, **kwargs: Any ) -> List[Document]: """Return docs m...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html
58565e88c920-4
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. """ query_embedding = self.embedding.embed_query(query) que...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html
7d3533edde39-0
Source code for langchain.vectorstores.redis.filters from enum import Enum from functools import wraps from numbers import Number from typing import Any, Callable, Dict, List, Optional, Union from langchain.utilities.redis import TokenEscaper # disable mypy error for dunder method overrides # mypy: disable-error-code="...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html
7d3533edde39-1
) -> None: # check that the operator is supported by this class if operator not in self.OPERATORS: raise ValueError( f"Operator {operator} not supported by {self.__class__.__name__}. " + f"Supported operators are {self.OPERATORS.values()}." ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html
7d3533edde39-2
RedisFilterOperator.EQ: "==", RedisFilterOperator.NE: "!=", RedisFilterOperator.IN: "==", } OPERATOR_MAP: Dict[RedisFilterOperator, str] = { RedisFilterOperator.EQ: "@%s:{%s}", RedisFilterOperator.NE: "(-@%s:{%s})", RedisFilterOperator.IN: "@%s:{%s}", } [docs] def ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html
7d3533edde39-3
"""Create a RedisTag inequality filter expression Args: other (Union[List[str], str]): The tag(s) to filter on. Example: >>> from langchain.vectorstores.redis import RedisTag >>> filter = RedisTag("brand") != "nike" """ self._set_tag_value(other, Redis...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html
7d3533edde39-4
RedisFilterOperator.NE: "(-@%s:[%f %f])", RedisFilterOperator.GT: "@%s:[(%f +inf]", RedisFilterOperator.LT: "@%s:[-inf (%f]", RedisFilterOperator.GE: "@%s:[%f +inf]", RedisFilterOperator.LE: "@%s:[-inf %f]", } def __str__(self) -> str: """Return the Redis Query syntax for...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html
7d3533edde39-5
"""Create a Numeric inequality filter expression Args: other (Number): The value to filter on. Example: >>> from langchain.vectorstores.redis import RedisNum >>> filter = RedisNum("zipcode") != 90210 """ self._set_value(other, Number, RedisFilterOperat...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html
7d3533edde39-6
return RedisFilterExpression(str(self)) def __le__(self, other: Union[int, float]) -> "RedisFilterExpression": """Create a Numeric less than or equal to filter expression Args: other (Number): The value to filter on. Example: >>> from langchain.vectorstores.redis impo...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html
7d3533edde39-7
"""Create a RedisText inequality filter expression Args: other (str): The text value to filter on. Example: >>> from langchain.vectorstores.redis import RedisText >>> filter = RedisText("job") != "engineer" """ self._set_value(other, str, RedisFilterOp...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html
7d3533edde39-8
by combining RedisFilterFields using the & and | operators. Examples: >>> from langchain.vectorstores.redis import RedisTag, RedisNum >>> brand_is_nike = RedisTag("brand") == "nike" >>> price_is_under_100 = RedisNum("price") < 100 >>> filter = brand_is_nike & price_is_under_100 ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html
7d3533edde39-9
operator_str = " | " if self._operator == RedisFilterOperator.OR else " " return f"({str(self._left)}{operator_str}{str(self._right)})" # check that base case, the filter is set if not self._filter: raise ValueError("Improperly initialized RedisFilterExpression") return s...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html
32a612515e5d-0
Source code for langchain.vectorstores.redis.base """Wrapper around Redis vector database.""" from __future__ import annotations import logging import os import uuid from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Mapping, Optional, Tuple, Type, Union...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html
32a612515e5d-1
def _default_relevance_score(val: float) -> float: return 1 - val [docs]def check_index_exists(client: RedisType, index_name: str) -> bool: """Check if Redis index exists.""" try: client.ft(index_name).info() except: # noqa: E722 logger.info("Index does not exist") return False ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html
32a612515e5d-2
.. code-block:: python from langchain.vectorstores import Redis from langchain.embeddings import OpenAIEmbeddings Initialize, create index, and load Documents .. code-block:: python from langchain.vectorstores import Redis from langchain.embeddings import OpenAIEmbedd...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html
32a612515e5d-3
rds = Redis.from_existing_index( embeddings, # an Embeddings object index_name="my-index", redis_url="redis://localhost:6379", ) Advanced examples: Custom vector schema can be supplied to change the way that Redis creates the underlying vector sche...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html
32a612515e5d-4
tag: - name: credit_score text: - name: user - name: job Typically, the ``credit_score`` field would be a text field since it's a string, however, we can override this behavior by specifying the field type as shown with the yaml config (can also be...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html