id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 59 127 |
|---|---|---|
d0972190eae7-5 | }
typesense_api_key = typesense_api_key or get_from_env(
"typesense_api_key", "TYPESENSE_API_KEY"
)
client_config = {
"nodes": [node],
"api_key": typesense_api_key,
"connection_timeout_seconds": connection_timeout_seconds,
}
return ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/typesense.html |
13a93fca6586-0 | Source code for langchain.vectorstores.mongodb_atlas
from __future__ import annotations
import logging
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generator,
Iterable,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from langchain.docstore.document import Document
from langchain.embe... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/mongodb_atlas.html |
13a93fca6586-1 | """
Args:
collection: MongoDB collection to add the texts to.
embedding: Text embedding model to use.
text_key: MongoDB field that will contain the text for each
document.
embedding_key: MongoDB field that will contain the embedding for
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/mongodb_atlas.html |
13a93fca6586-2 | """
batch_size = kwargs.get("batch_size", DEFAULT_INSERT_BATCH_SIZE)
_metadatas: Union[List, Generator] = metadatas or ({} for _ in texts)
texts_batch = []
metadatas_batch = []
result_ids = []
for i, (text, metadata) in enumerate(zip(texts, _metadatas)):
texts... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/mongodb_atlas.html |
13a93fca6586-3 | """Return MongoDB documents most similar to query, along with scores.
Use the knnBeta Operator available in MongoDB Atlas Search
This feature is in early access and available only for evaluation purposes, to
validate functionality, and to gather feedback from a small closed group of
earl... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/mongodb_atlas.html |
13a93fca6586-4 | docs.append((Document(page_content=text, metadata=res), score))
return docs
[docs] def similarity_search(
self,
query: str,
k: int = 4,
pre_filter: Optional[dict] = None,
post_filter_pipeline: Optional[List[Dict]] = None,
**kwargs: Any,
) -> List[Document]:... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/mongodb_atlas.html |
13a93fca6586-5 | collection: Optional[Collection[MongoDBDocumentType]] = None,
**kwargs: Any,
) -> MongoDBAtlasVectorSearch:
"""Construct MongoDBAtlasVectorSearch wrapper from raw documents.
This is a user-friendly interface that:
1. Embeds documents.
2. Adds the documents to a provid... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/mongodb_atlas.html |
9e8db57c99ff-0 | Source code for langchain.vectorstores.milvus
"""Wrapper around the Milvus vector database."""
from __future__ import annotations
import logging
from typing import Any, Iterable, List, Optional, Tuple, Union
from uuid import uuid4
import numpy as np
from langchain.docstore.document import Document
from langchain.embedd... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-1 | The connection args used for this class comes in the form of a dict,
here are a few of the options:
address (str): The actual address of Milvus
instance. Example address: "localhost:19530"
uri (str): The uri of Milvus instance. Example uri:
"http://randomw... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-2 | Args:
embedding_function (Embeddings): Function used to embed the text.
collection_name (str): Which Milvus collection to use. Defaults to
"LangChainCollection".
connection_args (Optional[dict[str, any]]): The arguments for connection to
Milvus/Zilliz ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-3 | "RHNSW_SQ": {"metric_type": "L2", "params": {"ef": 10}},
"RHNSW_PQ": {"metric_type": "L2", "params": {"ef": 10}},
"IVF_HNSW": {"metric_type": "L2", "params": {"nprobe": 10, "ef": 10}},
"ANNOY": {"metric_type": "L2", "params": {"search_k": 10}},
"AUTOINDEX": {"metric_type"... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-4 | if drop_old and isinstance(self.col, Collection):
self.col.drop()
self.col = None
# Initialize the vector store
self._init()
def _create_connection_alias(self, connection_args: dict) -> str:
"""Create the connection to the Milvus server."""
from pymilvus impor... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-5 | and (addr["user"] == tmp_user)
):
logger.debug("Using previous connection: %s", con[0])
return con[0]
# Generate a new connection if one doesnt exist
alias = uuid4().hex
try:
connections.connect(alias=alias, **connection_args)
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-6 | if dtype == DataType.UNKNOWN or dtype == DataType.NONE:
logger.error(
"Failure to create collection, unrecognized dtype for key: %s",
key,
)
raise ValueError(f"Unrecognized datatype for {key}.")
#... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-7 | for x in schema.fields:
self.fields.append(x.name)
# Since primary field is auto-id, no need to track it
self.fields.remove(self._primary_field)
def _get_index(self) -> Optional[dict[str, Any]]:
"""Return the vector index information if it exists"""
from pymil... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-8 | using=self.alias,
)
logger.debug(
"Successfully created an index on collection: %s",
self.collection_name,
)
except MilvusException as e:
logger.error(
"Failed to create an index o... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-9 | embedding and the columns are decided by the first metadata dict.
Metada keys will need to be present for all inserted values. At
the moment there is no None equivalent in Milvus.
Args:
texts (Iterable[str]): The texts to embed, it is assumed
that they all fit in memo... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-10 | for key, value in d.items():
if key in self.fields:
insert_dict.setdefault(key, []).append(value)
# Total insert count
vectors: list = insert_dict[self._vector_field]
total_count = len(vectors)
pks: list[str] = []
assert isinstance(self... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-11 | expr (str, optional): Filtering expression. Defaults to None.
timeout (int, optional): How long to wait before timeout error.
Defaults to None.
kwargs: Collection.search() keyword arguments.
Returns:
List[Document]: Document results for search.
"""
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-12 | return []
res = self.similarity_search_with_score_by_vector(
embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs
)
return [doc for doc, _ in res]
[docs] def similarity_search_with_score(
self,
query: str,
k: int = 4,
param: O... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-13 | res = self.similarity_search_with_score_by_vector(
embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs
)
return res
[docs] def similarity_search_with_score_by_vector(
self,
embedding: List[float],
k: int = 4,
param: Optional[dict] = ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-14 | # Perform the search.
res = self.col.search(
data=[embedding],
anns_field=self._vector_field,
param=param,
limit=k,
expr=expr,
output_fields=output_fields,
timeout=timeout,
**kwargs,
)
# Organize resu... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-15 | Defaults to None.
expr (str, optional): Filtering expression. Defaults to None.
timeout (int, optional): How long to wait before timeout error.
Defaults to None.
kwargs: Collection.search() keyword arguments.
Returns:
List[Document]: Document resul... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-16 | to maximum diversity and 1 to minimum diversity.
Defaults to 0.5
param (dict, optional): The search params for the specified index.
Defaults to None.
expr (str, optional): Filtering expression. Defaults to None.
timeout (int, optional): How lon... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-17 | )
# Reorganize the results from query to match search order.
vectors = {x[self._primary_field]: x[self._vector_field] for x in vectors}
ordered_result_embeddings = [vectors[x] for x in ids]
# Get the new order of results.
new_ordering = maximal_marginal_relevance(
np.... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
9e8db57c99ff-18 | "LangChainCollection".
connection_args (dict[str, Any], optional): Connection args to use. Defaults
to DEFAULT_MILVUS_CONNECTION.
consistency_level (str, optional): Which consistency level to use. Defaults
to "Session".
index_params (Optional[dict], op... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html |
5d74f96dffd2-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:... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tigris.html |
5d74f96dffd2-1 | 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.
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tigris.html |
5d74f96dffd2-2 | 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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tigris.html |
5d74f96dffd2-3 | "text": t,
"embeddings": e or [],
"metadata": m or {},
}
if _id:
doc["id"] = _id
docs.append(doc)
return docs
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tigris.html |
d59817d2e9c9-0 | Source code for langchain.vectorstores.deeplake
"""Wrapper around Activeloop Deep Lake."""
from __future__ import annotations
import logging
import uuid
from functools import partial
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
import numpy as np
from langchain.docstore.document imp... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
d59817d2e9c9-1 | returns:
nearest_indices: List, indices of nearest neighbors
"""
if data_vectors.shape[0] == 0:
return [], []
# Calculate the distance between the query_vector and all data_vectors
distances = distance_metric_map[distance_metric](query_embedding, data_vectors)
nearest_indices = np.ar... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
d59817d2e9c9-2 | embeddings = OpenAIEmbeddings()
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,
embedd... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
d59817d2e9c9-3 | if self.verbose:
print(
f"Deep Lake Dataset in {dataset_path} already exists, "
f"loading from the storage"
)
self.ds.summary()
else:
if "overwrite" in kwargs:
del kwargs["overwrite"]
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
d59817d2e9c9-4 | **kwargs: Any,
) -> List[str]:
"""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]], opti... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
d59817d2e9c9-5 | if batch_size == 0:
return []
batched = [
elements[i : i + batch_size] for i in range(0, len(elements), batch_size)
]
ingest().eval(
batched,
self.ds,
num_workers=min(self.num_workers, len(batched) // max(self.num_workers, 1)),
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
d59817d2e9c9-6 | take [Deep Lake filter]
(https://docs.deeplake.ai/en/latest/deeplake.core.dataset.html#deeplake.core.dataset.Dataset.filter)
Defaults to None.
maximal_marginal_relevance: Whether to use maximal marginal relevance.
Defaults to False.
fetch_k: Number of ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
d59817d2e9c9-7 | distance_metric=distance_metric.lower(),
)
view = view[indices]
if use_maximal_marginal_relevance:
lambda_mult = kwargs.get("lambda_mult", 0.5)
indices = maximal_marginal_relevance(
query_emb,
embeddings[indices]... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
d59817d2e9c9-8 | maximal_marginal_relevance: Whether to use maximal marginal relevance.
Defaults to False.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
Defaults to 20.
return_score: Whether to return the score. Defaults to False.
Returns:
Lis... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
d59817d2e9c9-9 | k (int): Number of results to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
Returns:
List[Tuple[Document, float]]: List of documents most similar to the query
text with distance in float.
"""
return self._s... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
d59817d2e9c9-10 | )
[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 the maximal marginal relevance.
Maximal marginal relevance optim... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
d59817d2e9c9-11 | **kwargs: Any,
) -> DeepLake:
"""Create a Deep Lake dataset from a raw documents.
If a dataset_path is specified, the dataset will be persisted in that location,
otherwise by default at `./deeplake`
Args:
path (str, pathlib.Path): - The full path to the dataset. Can be:
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
d59817d2e9c9-12 | dataset_path=dataset_path, embedding_function=embedding, **kwargs
)
deeplake_dataset.add_texts(texts=texts, metadatas=metadatas, ids=ids)
return deeplake_dataset
[docs] def delete(
self,
ids: Any[List[str], None] = None,
filter: Any[Dict[str, str], None] = None,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
d59817d2e9c9-13 | try:
import deeplake
except ImportError:
raise ValueError(
"Could not import deeplake python package. "
"Please install it with `pip install deeplake`."
)
deeplake.delete(path, large_ok=True, force=True)
[docs] def delete_dataset(sel... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
49896c956756-0 | Source code for langchain.vectorstores.lancedb
"""Wrapper around LanceDB vector database"""
from __future__ import annotations
import uuid
from typing import Any, Iterable, List, Optional
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.base i... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/lancedb.html |
49896c956756-1 | self._id_key = id_key
self._text_key = text_key
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Turn texts into embedding and add it to the database... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/lancedb.html |
49896c956756-2 | """
embedding = self._embedding.embed_query(query)
docs = self._connection.search(embedding).limit(k).to_df()
return [
Document(
page_content=row[self._text_key],
metadata=row[docs.columns != self._text_key],
)
for _, row in doc... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/lancedb.html |
4456ff7d0475-0 | Source code for langchain.vectorstores.opensearch_vector_search
"""Wrapper around OpenSearch vector database."""
from __future__ import annotations
import uuid
from typing import Any, Dict, Iterable, List, Optional, Tuple
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
4456ff7d0475-1 | try:
opensearch = _import_opensearch()
client = opensearch(opensearch_url, **kwargs)
except ValueError as e:
raise ValueError(
f"OpenSearch client string provided is not in proper format. "
f"Got error: {e} "
)
return client
def _validate_embeddings_and_bu... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
4456ff7d0475-2 | request = {
"_op_type": "index",
"_index": index_name,
vector_field: embeddings[i],
text_field: text,
"metadata": metadata,
"_id": _id,
}
requests.append(request)
ids.append(_id)
bulk(client, requests)
client.indices... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
4456ff7d0475-3 | "parameters": {"ef_construction": ef_construction, "m": m},
},
}
}
},
}
def _default_approximate_search_query(
query_vector: List[float],
k: int = 4,
vector_field: str = "vector_field",
) -> Dict:
"""For Approximate k-NN Search, this is the def... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
4456ff7d0475-4 | search_query["query"]["knn"][vector_field]["filter"] = lucene_filter
return search_query
def _default_script_query(
query_vector: List[float],
space_type: str = "l2",
pre_filter: Dict = MATCH_ALL_QUERY,
vector_field: str = "vector_field",
) -> Dict:
"""For Script Scoring Search, this is the defa... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
4456ff7d0475-5 | """For Painless Scripting Search, this is the default query."""
source = __get_painless_scripting_source(space_type, query_vector)
return {
"query": {
"script_score": {
"query": pre_filter,
"script": {
"source": source,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
4456ff7d0475-6 | **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.
bulk_size: Bulk API request count; Defa... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
4456ff7d0475-7 | vector_field,
text_field,
mapping,
)
[docs] def similarity_search(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query.
By default supports Approximate Search.
Also supports Script Scoring and Painle... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
4456ff7d0475-8 | "hammingbit"; default: "l2"
pre_filter: script_score query to pre-filter documents before identifying
nearest neighbors; default: {"match_all": {}}
Optional Args for Painless Scripting Search:
search_type: "painless_scripting"; default: "approximate_search"
space_... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
4456ff7d0475-9 | vector_field = _get_kwargs_value(kwargs, "vector_field", "vector_field")
if search_type == "approximate_search":
boolean_filter = _get_kwargs_value(kwargs, "boolean_filter", {})
subquery_clause = _get_kwargs_value(kwargs, "subquery_clause", "must")
lucene_filter = _get_kwargs... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
4456ff7d0475-10 | search_query = _default_painless_scripting_query(
embedding, space_type, pre_filter, vector_field
)
else:
raise ValueError("Invalid `search_type` provided as an argument")
response = self.client.search(index=self.index_name, body=search_query)
hits = [hit ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
4456ff7d0475-11 | Optional Args:
vector_field: Document field embeddings are stored in. Defaults to
"vector_field".
text_field: Document field the text of the document is stored in. Defaults
to "text".
Optional Keyword Args for Approximate Search:
engine: "nmslib", "fai... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
4456ff7d0475-12 | _validate_embeddings_and_bulk_size(len(embeddings), bulk_size)
dim = len(embeddings[0])
# Get the index name from either from kwargs or ENV Variable
# before falling back to random generation
index_name = get_from_dict_or_env(
kwargs, "index_name", "OPENSEARCH_INDEX_NAME", de... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
4456ff7d0475-13 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
8c9b15903ac6-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
8c9b15903ac6-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
{
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
8c9b15903ac6-2 | to connect to ClickHouse.
ClickHouse can not only search with simple vector indexes,
it also supports complex query with multiple conditions,
constraints and even sub-queries.
For more information, please visit
[ClickHouse official site](https://clickhouse.com/clickhouse)
"""
def __init_... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
8c9b15903ac6-3 | "angular",
"euclidean",
"manhattan",
"hamming",
"dot",
]
# initialize the schema
dim = len(embedding.embed_query("test"))
index_params = (
(
",".join([f"'{k}={v}'" for k, v in self.config.index_param.items()])
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
8c9b15903ac6-4 | host=self.config.host,
port=self.config.port,
username=self.config.username,
password=self.config.password,
**kwargs,
)
# Enable JSON type
self.client.command("SET allow_experimental_object_type=1")
# Enable Annoy index
self.client.... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
8c9b15903ac6-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
8c9b15903ac6-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
8c9b15903ac6-7 | return ctx
def __repr__(self) -> str:
"""Text representation for ClickHouse Vector Store, prints backends, username
and schemas. Easy to use with `str(ClickHouse())`
Returns:
repr: string to show connection info and data schema
"""
_repr = f"\033[92m\033[1m{se... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
8c9b15903ac6-8 | q_str = f"""
SELECT {self.config.column_map['document']},
{self.config.column_map['metadata']}, dist
FROM {self.config.database}.{self.config.table}
{where_str}
ORDER BY L2Distance({self.config.column_map['embedding']}, [{q_emb_str}])
AS ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
8c9b15903ac6-9 | 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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
8c9b15903ac6-10 | 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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
37ac036f381f-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
37ac036f381f-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:
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
37ac036f381f-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
37ac036f381f-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"] =... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
37ac036f381f-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)
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
37ac036f381f-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
37ac036f381f-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
37ac036f381f-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,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
66f08dabefd1-0 | Source code for langchain.vectorstores.tair
"""Wrapper around Tair Vector."""
from __future__ import annotations
import json
import logging
import uuid
from typing import Any, Iterable, List, Optional, Type
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tair.html |
66f08dabefd1-1 | data_type: str,
**kwargs: Any,
) -> bool:
index = self.client.tvs_get_index(self.index_name)
if index is not None:
logger.info("Index already exists")
return False
self.client.tvs_create_index(
self.index_name,
dim,
distance... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tair.html |
66f08dabefd1-2 | Args:
query (str): The query text for which to find similar documents.
k (int): The number of documents to return. Default is 4.
Returns:
List[Document]: A list of documents that are most similar to the query text.
"""
# Creates embedding vector from user quer... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tair.html |
66f08dabefd1-3 | if "tair_url" in kwargs:
kwargs.pop("tair_url")
distance_type = tairvector.DistanceMetric.InnerProduct
if "distance_type" in kwargs:
distance_type = kwargs.pop("distance_typ")
index_type = tairvector.IndexType.HNSW
if "index_type" in kwargs:
index_type... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tair.html |
66f08dabefd1-4 | cls,
documents: List[Document],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
index_name: str = "langchain",
content_key: str = "content",
metadata_key: str = "metadata",
**kwargs: Any,
) -> Tair:
texts = [d.page_content for d in docum... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tair.html |
66f08dabefd1-5 | # index not exist
logger.info("Index does not exist")
return False
return True
[docs] @classmethod
def from_existing_index(
cls,
embedding: Embeddings,
index_name: str = "langchain",
content_key: str = "content",
metadata_key: str = "metadat... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tair.html |
d83fb40f8ced-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,... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
d83fb40f8ced-1 | "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_message)
def _check_index_exis... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
d83fb40f8ced-2 | 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,
**kwargs: Any,
):
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
d83fb40f8ced-3 | 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,
"FLAT",
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
d83fb40f8ced-4 | """
ids = []
prefix = _redis_prefix(self.index_name)
# Write data to redis
pipeline = self.client.pipeline(transaction=False)
for i, text in enumerate(texts):
# Use provided values by default or fallback
key = keys[i] if keys else _redis_key(prefix)
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
d83fb40f8ced-5 | ) -> List[Document]:
"""
Returns the most similar indexed documents to the query text within the
score_threshold range.
Args:
query (str): The query text for which to find similar documents.
k (int): The number of documents to return. Default is 4.
sco... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
d83fb40f8ced-6 | .paging(0, k)
.dialect(2)
)
[docs] def similarity_search_with_score(
self, query: str, k: int = 4
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
d83fb40f8ced-7 | raise ValueError(
"relevance_score_fn must be provided to"
" Redis constructor to normalize scores"
)
docs_and_scores = self.similarity_search_with_score(query, k=k)
return [(doc, self.relevance_score_fn(score)) for doc, score in docs_and_scores]
[docs] @cl... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
d83fb40f8ced-8 | kwargs.pop("redis_url")
# Name of the search index if not given
if not index_name:
index_name = uuid.uuid4().hex
# Create instance
instance = cls(
redis_url,
index_name,
embedding.embed_query,
content_key=content_key,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
d83fb40f8ced-9 | embeddings = OpenAIEmbeddings()
redisearch = RediSearch.from_texts(
texts,
embeddings,
redis_url="redis://username:password@localhost:6379"
)
"""
instance, _ = cls.from_texts_return_keys(
texts,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
d83fb40f8ced-10 | try:
client.ft(index_name).dropindex(delete_documents)
logger.info("Drop index")
return True
except: # noqa: E722
# Index not exist
return False
[docs] @classmethod
def from_existing_index(
cls,
embedding: Embeddings,
in... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
d83fb40f8ced-11 | vector_key=vector_key,
**kwargs,
)
[docs] def as_retriever(self, **kwargs: Any) -> RedisVectorStoreRetriever:
return RedisVectorStoreRetriever(vectorstore=self, **kwargs)
class RedisVectorStoreRetriever(VectorStoreRetriever, BaseModel):
vectorstore: Redis
search_type: str = "simil... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
d83fb40f8ced-12 | """Add documents to vectorstore."""
return self.vectorstore.add_documents(documents, **kwargs)
async def aadd_documents(
self, documents: List[Document], **kwargs: Any
) -> List[str]:
"""Add documents to vectorstore."""
return await self.vectorstore.aadd_documents(documents, **kw... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
ffbc7c5e91ef-0 | Source code for langchain.vectorstores.supabase
from __future__ import annotations
from itertools import repeat
from typing import (
TYPE_CHECKING,
Any,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
)
import numpy as np
from langchain.docstore.document import Document
from langchain.embe... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/supabase.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.