id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 53 121 |
|---|---|---|
510b6adefef9-6 | self._text_key, type(v)
)
page_content = v
elif k == "dist":
assert isinstance(
v, float
), "Computed distance between vectors must of type `float`. \
But found {}".format(
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/rocksetdb.html |
510b6adefef9-7 | collection=self._collection_name, data=batch
)
return [doc_status._id for doc_status in add_doc_res.data]
[docs] def delete_texts(self, ids: List[str]) -> None:
"""Delete a list of docs from the Rockset collection"""
try:
from rockset.models import DeleteDocumentsRequestDa... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/rocksetdb.html |
1d8a4ce620f9-0 | Source code for langchain.vectorstores.myscale
"""Wrapper around MyScale vector database."""
from __future__ import annotations
import json
import logging
from hashlib import sha1
from threading import Thread
from typing import Any, Dict, Iterable, List, Optional, Tuple
from pydantic import BaseSettings
from langchain.... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
1d8a4ce620f9-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/stable/_modules/langchain/vectorstores/myscale.html |
1d8a4ce620f9-2 | constraints and even sub-queries.
For more information, please visit
[myscale official site](https://docs.myscale.com/en/overview/)
"""
def __init__(
self,
embedding: Embeddings,
config: Optional[MyScaleSettings] = None,
**kwargs: Any,
) -> None:
"""MyScal... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
1d8a4ce620f9-3 | dim = len(embedding.embed_query("try this out"))
index_params = (
", " + ",".join([f"'{k}={v}'" for k, v in self.config.index_param.items()])
if self.config.index_param
else ""
)
schema_ = f"""
CREATE TABLE IF NOT EXISTS {self.config.database}.{sel... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
1d8a4ce620f9-4 | def _build_istr(self, transac: Iterable, column_names: Iterable[str]) -> str:
ks = ",".join(column_names)
_data = []
for n in transac:
n = ",".join([f"'{self.escape_str(str(_n))}'" for _n in n])
_data.append(f"({n})")
i_str = f"""
INSERT INTO TABLE... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
1d8a4ce620f9-5 | column_names = {
colmap_["id"]: ids,
colmap_["text"]: texts,
colmap_["vector"]: map(self.embedding_function, texts),
}
metadatas = metadatas or [{} for _ in texts]
column_names[colmap_["metadata"]] = map(json.dumps, metadatas)
assert len(set(colmap_) -... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
1d8a4ce620f9-6 | batch_size: int = 32,
**kwargs: Any,
) -> MyScale:
"""Create Myscale wrapper with existing texts
Args:
embedding_function (Embeddings): Function to extract text embedding
texts (Iterable[str]): List or tuple of strings to be added
config (MyScaleSettings, ... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
1d8a4ce620f9-7 | for r in self.client.query(
f"DESC {self.config.database}.{self.config.table}"
).named_results():
_repr += (
f"|\033[94m{r['name']:24s}\033[0m|\033[96m{r['type']:24s}\033[0m|\n"
)
_repr += "-" * 51 + "\n"
return _repr
def _build_qstr(
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
1d8a4ce620f9-8 | NOTE: Please do not let end-user to fill this and always be aware
of SQL injection. When dealing with metadatas, remember to
use `{self.metadata_column}.attribute` instead of `attribute`
alone. The default name for it is `metadata`.
Returns:
List... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
1d8a4ce620f9-9 | ]
except Exception as e:
logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m")
return []
[docs] def similarity_search_with_relevance_scores(
self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any
) -> List[Tuple[Document, float]]:
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
1d8a4ce620f9-10 | ]
except Exception as e:
logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m")
return []
[docs] def drop(self) -> None:
"""
Helper function: Drop data
"""
self.client.command(
f"DROP TABLE IF EXISTS {self.config.database}.... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
1743af7e15ad-0 | Source code for langchain.vectorstores.atlas
"""Wrapper around Atlas by Nomic."""
from __future__ import annotations
import logging
import uuid
from typing import Any, Iterable, List, Optional, Type
import numpy as np
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
1743af7e15ad-1 | is_public (bool): Whether your project is publicly accessible.
True by default.
reset_project_if_exists (bool): Whether to reset this project if it
already exists. Default False.
Generally userful during development and testing.
"""
try:
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
1743af7e15ad-2 | metadatas (Optional[List[dict]], optional): Optional list of metadatas.
ids (Optional[List[str]]): An optional list of ids.
refresh(bool): Whether or not to refresh indices with the updated data.
Default True.
Returns:
List[str]: List of IDs of the added texts... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
1743af7e15ad-3 | else:
if metadatas is None:
data = [
{"text": text, AtlasDB._ATLAS_DEFAULT_ID_FIELD: ids[i]}
for i, text in enumerate(texts)
]
else:
for i, text in enumerate(texts):
metadatas[i]["text"] =... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
1743af7e15ad-4 | """
if self._embedding_function is None:
raise NotImplementedError(
"AtlasDB requires an embedding_function for text similarity search!"
)
_embedding = self._embedding_function.embed_documents([query])[0]
embedding = np.array(_embedding).reshape(1, -1)
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
1743af7e15ad-5 | ids (Optional[List[str]]): Optional list of document IDs. If None,
ids will be auto created
description (str): A description for your project.
is_public (bool): Whether your project is publicly accessible.
True by default.
reset_project_if_exists (bool... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
1743af7e15ad-6 | ids: Optional[List[str]] = None,
name: Optional[str] = None,
api_key: Optional[str] = None,
persist_directory: Optional[str] = None,
description: str = "A description for your project",
is_public: bool = True,
reset_project_if_exists: bool = False,
index_kwargs: O... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
1743af7e15ad-7 | return cls.from_texts(
name=name,
api_key=api_key,
texts=texts,
embedding=embedding,
metadatas=metadatas,
ids=ids,
description=description,
is_public=is_public,
reset_project_if_exists=reset_project_if_exists,
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/atlas.html |
204c4f4d5cd9-0 | Source code for langchain.vectorstores.clickhouse
"""Wrapper around open source ClickHouse VectorSearch capability."""
from __future__ import annotations
import json
import logging
from hashlib import sha1
from threading import Thread
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from pydantic im... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
204c4f4d5cd9-1 | Defaults to 'vector_table'.
metric (str) : Metric to compute distance,
supported are ('angular', 'euclidean', 'manhattan', 'hamming',
'dot'). Defaults to 'angular'.
https://github.com/spotify/annoy/blob/main/src/annoymodule.cc#L149-L169
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
204c4f4d5cd9-2 | return getattr(self, item)
class Config:
env_file = ".env"
env_prefix = "clickhouse_"
env_file_encoding = "utf-8"
[docs]class Clickhouse(VectorStore):
"""Wrapper around ClickHouse vector database
You need a `clickhouse-connect` python package, and a valid account
to connect to Cl... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
204c4f4d5cd9-3 | assert self.config
assert self.config.host and self.config.port
assert (
self.config.column_map
and self.config.database
and self.config.table
and self.config.metric
)
for k in ["id", "embedding", "document", "metadata", "uuid"]:
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
204c4f4d5cd9-4 | """
self.dim = dim
self.BS = "\\"
self.must_escape = ("\\", "'")
self.embedding_function = embedding
self.dist_order = "ASC" # Only support ConsingDistance and L2Distance
# Create a connection to clickhouse
self.client = get_client(
host=self.config.h... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
204c4f4d5cd9-5 | [docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
batch_size: int = 32,
ids: Optional[Iterable[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Insert more texts through the embeddings and add to the VectorStore.
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
204c4f4d5cd9-6 | transac.append(v)
if len(transac) == batch_size:
if t:
t.join()
t = Thread(target=self._insert, args=[transac, keys])
t.start()
transac = []
if len(transac) > 0:
if t:
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
204c4f4d5cd9-7 | Returns:
ClickHouse Index
"""
ctx = cls(embedding, config, **kwargs)
ctx.add_texts(texts, ids=text_ids, batch_size=batch_size, metadatas=metadatas)
return ctx
def __repr__(self) -> str:
"""Text representation for ClickHouse Vector Store, prints backends, username
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
204c4f4d5cd9-8 | else:
where_str = ""
settings_strs = []
if self.config.index_query_params:
for k in self.config.index_query_params:
settings_strs.append(f"SETTING {k}={self.config.index_query_params[k]}")
q_str = f"""
SELECT {self.config.column_map['document']... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
204c4f4d5cd9-9 | self,
embedding: List[float],
k: int = 4,
where_str: Optional[str] = None,
**kwargs: Any,
) -> List[Document]:
"""Perform a similarity search with ClickHouse by vectors
Args:
query (str): query string
k (int, optional): Top K neighbors to retri... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
204c4f4d5cd9-10 | Args:
query (str): query string
k (int, optional): Top K neighbors to retrieve. Defaults to 4.
where_str (Optional[str], optional): where condition string.
Defaults to None.
NOTE: Please do not let end-user to fill this and... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clickhouse.html |
d9b6d2cefefd-0 | Source code for langchain.vectorstores.analyticdb
"""VectorStore wrapper around a Postgres/PGVector database."""
from __future__ import annotations
import logging
import uuid
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Type
from sqlalchemy import REAL, Column, String, Table, create_engine, ... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html |
d9b6d2cefefd-1 | - Useful for testing.
"""
def __init__(
self,
connection_string: str,
embedding_function: Embeddings,
embedding_dimension: int = _LANGCHAIN_DEFAULT_EMBEDDING_DIM,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
pre_delete_collection: bool = False,
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html |
d9b6d2cefefd-2 | """
)
result = conn.execute(index_query).scalar()
# Create the index if it doesn't exist
if not result:
index_statement = text(
f"""
CREATE INDEX {index_name}
ON {s... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html |
d9b6d2cefefd-3 | if not metadatas:
metadatas = [{} for _ in texts]
# Define the table schema
chunks_table = Table(
self.collection_name,
Base.metadata,
Column("id", TEXT, primary_key=True),
Column("embedding", ARRAY(REAL)),
Column("document", String... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html |
d9b6d2cefefd-4 | k (int): Number of results to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
Returns:
List of Documents most similar to the query.
"""
embedding = self.embedding_function.embed_query(text=query)
return self.similari... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html |
d9b6d2cefefd-5 | **kwargs: kwargs to be passed to similarity search. Should include:
score_threshold: Optional, a floating point value between 0 to 1 to
filter the resulting set of retrieved docs
Returns:
List of Tuples of (doc, similarity_score)
"""
return self.si... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html |
d9b6d2cefefd-6 | )
for result in results
]
return documents_with_scores
[docs] def similarity_search_by_vector(
self,
embedding: List[float],
k: int = 4,
filter: Optional[dict] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to em... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html |
d9b6d2cefefd-7 | connection_string=connection_string,
collection_name=collection_name,
embedding_function=embedding,
embedding_dimension=embedding_dimension,
pre_delete_collection=pre_delete_collection,
)
store.add_texts(texts=texts, metadatas=metadatas, ids=ids, **kwargs)... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html |
d9b6d2cefefd-8 | return cls.from_texts(
texts=texts,
pre_delete_collection=pre_delete_collection,
embedding=embedding,
embedding_dimension=embedding_dimension,
metadatas=metadatas,
ids=ids,
collection_name=collection_name,
**kwargs,
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html |
061a63379962-0 | Source code for langchain.vectorstores.pinecone
"""Wrapper around Pinecone vector database."""
from __future__ import annotations
import logging
import uuid
from typing import Any, Callable, Iterable, List, Optional, Tuple
import numpy as np
from langchain.docstore.document import Document
from langchain.embeddings.bas... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/pinecone.html |
061a63379962-1 | f"client should be an instance of pinecone.index.Index, "
f"got {type(index)}"
)
self._index = index
self._embedding_function = embedding_function
self._text_key = text_key
self._namespace = namespace
[docs] def add_texts(
self,
texts: Itera... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/pinecone.html |
061a63379962-2 | self,
query: str,
k: int = 4,
filter: Optional[dict] = None,
namespace: Optional[str] = None,
) -> List[Tuple[Document, float]]:
"""Return pinecone documents most similar to query, along with scores.
Args:
query: Text to look up documents similar to.
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/pinecone.html |
061a63379962-3 | """Return pinecone documents most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter: Dictionary of argument(s) to filter on metadata
namespace: Namespace to search in. Default will search i... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/pinecone.html |
061a63379962-4 | lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
Returns:
List of Documents selected by maximal ... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/pinecone.html |
061a63379962-5 | k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/pinecone.html |
061a63379962-6 | embeddings = OpenAIEmbeddings()
pinecone = Pinecone.from_texts(
texts,
embeddings,
index_name="langchain-demo"
)
"""
try:
import pinecone
except ImportError:
raise ValueError(
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/pinecone.html |
061a63379962-7 | else:
metadata = [{} for _ in range(i, i_end)]
for j, line in enumerate(lines_batch):
metadata[j][text_key] = line
to_upsert = zip(ids_batch, embeds, metadata)
# upsert to Pinecone
index.upsert(vectors=list(to_upsert), namespace=namespace)
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/pinecone.html |
714330012b76-0 | Source code for langchain.vectorstores.deeplake
"""Wrapper around Activeloop Deep Lake."""
from __future__ import annotations
import logging
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
import numpy as np
try:
import deeplake
from deeplake.core.fast_forwarding import version_co... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-1 | vectorstore = DeepLake("langchain_store", embeddings.embed_query)
"""
_LANGCHAIN_DEFAULT_DEEPLAKE_PATH = "./deeplake/"
def __init__(
self,
dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH,
token: Optional[str] = None,
embedding_function: Optional[Embeddings] = None,
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-2 | read_only (bool): Open dataset in read-only mode. Default is False.
ingestion_batch_size (int): During data ingestion, data is divided
into batches. Batch size is the size of each batch.
Default is 1000.
num_workers (int): Number of workers to use during data inge... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-3 | "Please install it with `pip install deeplake`."
)
if version_compare(deeplake.__version__, "3.6.2") == -1:
raise ValueError(
"deeplake version should be >= 3.6.3, but you've installed"
f" {deeplake.__version__}. Consider upgrading deeplake version \
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-4 | ids (Optional[List[str]], optional): Optional list of IDs.
**kwargs: other optional keyword arguments.
Returns:
List[str]: List of IDs of the added texts.
"""
kwargs = {}
if ids:
if self._id_tensor_name == "ids": # for backwards compatibility
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-5 | Engine for the client. Not for in-memory or local datasets.
- ``tensor_db`` - Hosted Managed Tensor Database for storage
and query execution. Only for data in Deep Lake Managed Database.
Use runtime = {"db_engine": True} during dataset creation.
re... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-6 | """
Return docs similar to query.
Args:
query (str, optional): Text to look up similar docs.
embedding (Union[List[float], np.ndarray], optional): Query's embedding.
embedding_function (Callable, optional): Function to convert `query`
into embedding.
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-7 | and query execution. Only for data in Deep Lake Managed Database.
Use runtime = {"db_engine": True} during dataset creation.
**kwargs: Additional keyword arguments.
Returns:
List of Documents by the specified distance metric,
if return_score True, return a... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-8 | )
scores = result["score"]
embeddings = result["embedding"]
metadatas = result["metadata"]
texts = result["text"]
if use_maximal_marginal_relevance:
lambda_mult = kwargs.get("lambda_mult", 0.5)
indices = maximal_marginal_relevance( # type: ignore
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-9 | ... exec_option="compute_engine",
... )
Args:
k (int): Number of Documents to return. Defaults to 4.
query (str): Text to look up similar documents.
**kwargs: Additional keyword arguments include:
embedding (Callable): Embedding function to use... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-10 | k=k,
use_maximal_marginal_relevance=False,
return_score=False,
**kwargs,
)
[docs] def similarity_search_by_vector(
self,
embedding: Union[List[float], np.ndarray],
k: int = 4,
**kwargs: Any,
) -> List[Document]:
"""
Retur... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-11 | - "compute_engine" - Performant C++ implementation of the Deep
Lake Compute Engine. Runs on the client and can be used for
any data stored in or connected to Deep Lake. It cannot be
used with in-memory or local datasets.
- "tens... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-12 | ... )
Args:
query (str): Query text to search for.
k (int): Number of results to return. Defaults to 4.
**kwargs: Additional keyword arguments. Some of these arguments are:
distance_metric: `L2` for Euclidean, `L1` for Nuclear, `max` L-infinity
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-13 | text with distance in float."""
return self._search(
query=query,
k=k,
return_score=True,
**kwargs,
)
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-14 | option with big datasets is discouraged due to potential
memory issues.
- "compute_engine" - Performant C++ implementation of the Deep
Lake Compute Engine. Runs on the client and can be used for
any data stored in or connected to Deep Lake. It ... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-15 | ... embedding_function = <embedding_function_for_query>,
... k = <number_of_items_to_return>,
... exec_option = <preferred_exec_option>,
... )
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-16 | "For MMR search, you must specify an embedding function on"
" `creation` or during add call."
)
return self._search(
query=query,
k=k,
fetch_k=fetch_k,
use_maximal_marginal_relevance=True,
lambda_mult=lambda_mult,
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-17 | (use 'activeloop login' from command line)
- AWS S3 path of the form ``s3://bucketname/path/to/dataset``.
Credentials are required in either the environment
- Google Cloud Storage path of the form
``gcs://bucketname/path/to/dataset`` Credentials ar... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
714330012b76-18 | metadatas=metadatas,
ids=ids,
embedding_function=embedding.embed_documents, # type: ignore
)
return deeplake_dataset
[docs] def delete(
self,
ids: Any[List[str], None] = None,
filter: Any[Dict[str, str], None] = None,
delete_all: Any[bool, None... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/deeplake.html |
4611c72b7f8a-0 | Source code for langchain.vectorstores.matching_engine
"""Vertex Matching Engine implementation of the vector store."""
from __future__ import annotations
import json
import logging
import time
import uuid
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Type
from langchain.docstore.document import Docu... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
4611c72b7f8a-1 | using this module.
See usage in
docs/modules/indexes/vectorstores/examples/matchingengine.ipynb.
Note that this implementation is mostly meant for reading if you are
planning to do a real time implementation. While reading is a real time
operation, updating the index takes close ... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
4611c72b7f8a-2 | "to use the MatchingEngine Vectorstore."
)
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
te... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
4611c72b7f8a-3 | )
logger.debug("Updated index with new configuration.")
return ids
def _upload_to_gcs(self, data: str, gcs_location: str) -> None:
"""Uploads data to gcs_location.
Args:
data: The data that will be stored.
gcs_location: The location where the data will be stor... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
4611c72b7f8a-4 | page_content = self._download_from_gcs(f"documents/{doc.id}")
results.append(Document(page_content=page_content))
logger.debug("Downloaded documents for query.")
return results
def _get_index_id(self) -> str:
"""Gets the correct index id for the endpoint.
Returns:
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
4611c72b7f8a-5 | )
[docs] @classmethod
def from_components(
cls: Type["MatchingEngine"],
project_id: str,
region: str,
gcs_bucket_name: str,
index_id: str,
endpoint_id: str,
credentials_path: Optional[str] = None,
embedding: Optional[Embeddings] = None,
) -> "Ma... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
4611c72b7f8a-6 | return cls(
project_id=project_id,
index=index,
endpoint=endpoint,
embedding=embedding or cls._get_default_embeddings(),
gcs_client=gcs_client,
credentials=credentials,
gcs_bucket_name=gcs_bucket_name,
)
@classmethod
def... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
4611c72b7f8a-7 | ) -> MatchingEngineIndex:
"""Creates a MatchingEngineIndex object by id.
Args:
index_id: The created index id.
project_id: The project to retrieve index from.
region: Location to retrieve index from.
credentials: GCS credentials.
Returns:
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
4611c72b7f8a-8 | A configured GCS client.
"""
from google.cloud import storage
return storage.Client(credentials=credentials, project=project_id)
@classmethod
def _init_aiplatform(
cls,
project_id: str,
region: str,
gcs_bucket_name: str,
credentials: "Credentials",... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
d92f6d843e94-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
import numpy as np
from langchain.embeddings.base import Embeddings
from langchain.schema import D... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
d92f6d843e94-1 | """Get OpenSearch client from the opensearch_url, otherwise raise error."""
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. "
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
d92f6d843e94-2 | except not_found_error:
client.indices.create(index=index_name, body=mapping)
for i, text in enumerate(texts):
metadata = metadatas[i] if metadatas else {}
_id = ids[i] if ids else str(uuid.uuid4())
request = {
"_op_type": "index",
"_index": index_name,
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
d92f6d843e94-3 | "mappings": {
"properties": {
vector_field: {
"type": "knn_vector",
"dimension": dim,
"method": {
"name": "hnsw",
"space_type": space_type,
"engine": engine,
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
d92f6d843e94-4 | vector_field: str = "vector_field",
) -> Dict:
"""For Approximate k-NN Search, with Lucene Filter."""
search_query = _default_approximate_search_query(
query_vector, k=k, vector_field=vector_field
)
search_query["query"]["knn"][vector_field]["filter"] = lucene_filter
return search_query
def ... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
d92f6d843e94-5 | return source_value
else:
return "1/" + source_value
def _default_painless_scripting_query(
query_vector: List[float],
space_type: str = "l2Squared",
pre_filter: Optional[Dict] = None,
vector_field: str = "vector_field",
) -> Dict:
"""For Painless Scripting Search, this is the default qu... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
d92f6d843e94-6 | **kwargs: Any,
):
"""Initialize with necessary components."""
self.embedding_function = embedding_function
self.index_name = index_name
self.client = _get_opensearch_client(opensearch_url, **kwargs)
[docs] def add_texts(
self,
texts: Iterable[str],
metadata... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
d92f6d843e94-7 | ef_search = _get_kwargs_value(kwargs, "ef_search", 512)
ef_construction = _get_kwargs_value(kwargs, "ef_construction", 512)
m = _get_kwargs_value(kwargs, "m", 16)
vector_field = _get_kwargs_value(kwargs, "vector_field", "vector_field")
mapping = _default_text_mapping(
dim, en... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
d92f6d843e94-8 | search_type: "approximate_search"; default: "approximate_search"
boolean_filter: A Boolean filter consists of a Boolean query that
contains a k-NN query and a filter.
subquery_clause: Query clause on the knn vector field; default: "must"
lucene_filter: the Lucene algorith... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
d92f6d843e94-9 | Also supports Script Scoring and Painless Scripting.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
Returns:
List of Documents along with its scores most similar to the query.
Optional Args:
same... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
d92f6d843e94-10 | """
embedding = self.embedding_function.embed_query(query)
search_type = _get_kwargs_value(kwargs, "search_type", "approximate_search")
vector_field = _get_kwargs_value(kwargs, "vector_field", "vector_field")
if search_type == "approximate_search":
boolean_filter = _get_kwarg... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
d92f6d843e94-11 | space_type = _get_kwargs_value(kwargs, "space_type", "l2Squared")
pre_filter = _get_kwargs_value(kwargs, "pre_filter", MATCH_ALL_QUERY)
search_query = _default_painless_scripting_query(
embedding, space_type, pre_filter, vector_field
)
else:
raise ... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
d92f6d843e94-12 | metadata_field = _get_kwargs_value(kwargs, "metadata_field", "metadata")
# Get embedding of the user query
embedding = self.embedding_function.embed_query(query)
# Do ANN/KNN search to get top fetch_k results where fetch_k >= k
results = self._raw_similarity_search_with_score(query, fetc... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
d92f6d843e94-13 | and lucene engines recommended for large datasets. Also supports brute force
search through Script Scoring and Painless Scripting.
Optional Args:
vector_field: Document field embeddings are stored in. Defaults to
"vector_field".
text_field: Document field the text of ... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
d92f6d843e94-14 | "ef_search",
"ef_construction",
"m",
]
embeddings = embedding.embed_documents(texts)
_validate_embeddings_and_bulk_size(len(embeddings), bulk_size)
dim = len(embeddings[0])
# Get the index name from either from kwargs or ENV Variable
# before falli... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
d92f6d843e94-15 | metadatas=metadatas,
vector_field=vector_field,
text_field=text_field,
mapping=mapping,
)
return cls(opensearch_url, index_name, embedding, **kwargs) | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/opensearch_vector_search.html |
9b163cce2644-0 | Source code for langchain.vectorstores.faiss
"""Wrapper around FAISS vector database."""
from __future__ import annotations
import math
import os
import pickle
import uuid
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
import numpy as np
from langchain.docstore.base imp... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html |
9b163cce2644-1 | return faiss
def _default_relevance_score_fn(score: float) -> float:
"""Return a similarity score on a scale [0, 1]."""
# The 'correct' relevance function
# may differ depending on a few things, including:
# - the distance / similarity metric used by the VectorStore
# - the scale of your embeddings ... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html |
9b163cce2644-2 | self._normalize_L2 = normalize_L2
def __add(
self,
texts: Iterable[str],
embeddings: Iterable[List[float]],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
if not isinstance(self.docstore, AddableMixi... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html |
9b163cce2644-3 | return [_id for _, _id, _ in full_info]
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html |
9b163cce2644-4 | ids: Optional list of unique IDs.
Returns:
List of ids from adding the texts into the vectorstore.
"""
if not isinstance(self.docstore, AddableMixin):
raise ValueError(
"If trying to add texts, the underlying docstore should support "
f"add... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html |
9b163cce2644-5 | vector = np.array([embedding], dtype=np.float32)
if self._normalize_L2:
faiss.normalize_L2(vector)
scores, indices = self.index.search(vector, k if filter is None else fetch_k)
docs = []
for j, i in enumerate(indices[0]):
if i == -1:
# This happens... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html |
9b163cce2644-6 | Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
fetch_k: (Optional[int]) Number of Documents to fetch before filtering.
Defau... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.