viruPVS/langchain-docs huggingface dataset:
max_marginal_relevance_search(query[, k, ...])
Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param query: Text to look up documents similar to. :type query: str :param k: Number of Documents to return. :type k: int = 4 :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. :type fetch_k: int = 20 :param 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. Optional. :type lambda_mult: float = 0.5.
max_marginal_relevance_search_by_vector(...)
Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param embedding: Embedding to look up documents similar to. :param k: Number of Documents to return. :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. :param 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.
search(query, search_type, **kwargs)
Return docs most similar to query using specified search type.
similarity_search(query[, k, filter])
Return docs most similar to query.
similarity_search_by_vector(embedding[, k, ...])
Return docs most similar to embedding vector.
similarity_search_with_relevance_scores(query)
Return docs and relevance scores in the range [0, 1].
similarity_search_with_score(query[, k, filter])
Run similarity search with distance.
similarity_search_with_score_by_vector(embedding)
Run similarity search with distance.
similarity_search_with_score_by_vector(embedding)
Return docs most similar to embedding vector.
similarity_search_with_score_id(query[, k, ...])
similarity_search_with_score_id_by_vector(...)
Return docs most similar to embedding vector.
__init__(*, embedding: Embeddings, collection_name: str, token: Optional[str] = None, api_endpoint: Optional[str] = None, astra_db_client: Optional[Any] = None, namespace: Optional[str] = None, metric: Optional[str] = None, batch_size: Optional[int] = None, bulk_insert_batch_concurrency: Optional[int] = None, bulk_insert_overwrite_concurrency: Optional[int] = None, bulk_delete_concurrency: Optional[int] = None, pre_delete_collection: bool = False) → None[source]¶
Create an AstraDB vector store object. See class docstring for help.
async aadd_documents(documents: List[Document], **kwargs: Any) → List[str]¶
Run more documents through the embeddings and add to the vectorstore.
Parameters
(List[Document] (documents) – Documents to add to the vectorstore.
Returns
List of IDs of the added texts.
Return type
List[str]
async aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) → List[str]¶
Run more texts through the embeddings and add to the vectorstore.
add_documents(documents: List[Document], **kwargs: Any) → List[str]¶
Run more documents through the embeddings and add to the vectorstore.
Parameters
(List[Document] (documents) – Documents to add to the vectorstore.
Returns
List of IDs of the added texts.
Return type
List[str]
Returns
List of IDs of the added texts.
Return type
List[str]
add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, *, batch_size: Optional[int] = None, batch_concurrency: Optional[int] = None, overwrite_concurrency: Optional[int] = None, **kwargs: Any) → List[str][source]¶
Run texts through the embeddings and add them to the vectorstore.
If passing explicit ids, those entries whose id is in the store already
will be replaced.
Parameters
texts (Iterable[str]) – Texts to add to the vectorstore.
metadatas (Optional[List[dict]], optional) – Optional list of metadatas.
ids (Optional[List[str]], optional) – Optional list of ids.
batch_size (Optional[int]) – Number of documents in each API call.
Check the underlying Astra DB HTTP API specs for the max value
(20 at the time of writing this). If not provided, defaults
to the instance-level setting.
batch_concurrency (Optional[int]) – number of threads to process
insertion batches concurrently. Defaults to instance-level
setting if not provided.
overwrite_concurrency (Optional[int]) – number of threads to process
pre-existing documents in each batch (which require individual
API calls). Defaults to instance-level setting if not provided.
A note on metadata: there are constraints on the allowed field names
in this dictionary, coming from the underlying Astra DB API.
For instance, the $ (dollar sign) cannot be used in the dict keys.
See this document for details:
docs.datastax.com/en/astra-serverless/docs/develop/dev-with-json.html
Returns
List of ids of the added texts.
Return type
List[str]
Returns
List of ids of the added texts.
Return type
List[str]
async adelete(ids: Optional[List[str]] = None, **kwargs: Any) → Optional[bool]¶
Delete by vector ID or other criteria.
Parameters
ids – List of ids to delete.
**kwargs – Other keyword arguments that subclasses might use.
Returns
True if deletion is successful,
False otherwise, None if not implemented.
Return type
Optional[bool]
async classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) → VST¶
Return VectorStore initialized from documents and embeddings.
async classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) → VST¶
Return VectorStore initialized from texts and embeddings.
async amax_marginal_relevance_search(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.
async amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) → List[Document]¶
Return docs selected using the maximal marginal relevance.
as_retriever(**kwargs: Any) → VectorStoreRetriever¶
Return VectorStoreRetriever initialized from this VectorStore.
Parameters
search_type (Optional[str]) – Defines the type of search that
the Retriever should perform.
Can be “similarity” (default), “mmr”, or
“similarity_score_threshold”.
“similarity_score_threshold”.
search_kwargs (Optional[Dict]) – Keyword arguments to pass to the
search function. Can include things like:
k: Amount of documents to return (Default: 4)
score_threshold: Minimum relevance threshold
for similarity_score_threshold
fetch_k: Amount of documents to pass to MMR algorithm (Default: 20)
lambda_mult: Diversity of results returned by MMR;
1 for minimum diversity and 0 for maximum. (Default: 0.5)
filter: Filter by document metadata
Returns
Retriever class for VectorStore.
Return type
VectorStoreRetriever
Examples:
# Retrieve more documents with higher diversity
# Useful if your dataset has many similar documents
docsearch.as_retriever(
    search_type="mmr",
    search_kwargs={'k': 6, 'lambda_mult': 0.25}
)
# Fetch more documents for the MMR algorithm to consider
# But only return the top 5
docsearch.as_retriever(
    search_type="mmr",
    search_kwargs={'k': 5, 'fetch_k': 50}
)
# Only retrieve documents that have a relevance score
# Above a certain threshold
docsearch.as_retriever(
    search_type="similarity_score_threshold",
    search_kwargs={'score_threshold': 0.8}
)
# Only get the single most similar document from the dataset
docsearch.as_retriever(search_kwargs={'k': 1})
# Use a filter to only retrieve documents from a specific paper
docsearch.as_retriever(
    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}
)
async asearch(query: str, search_type: str, **kwargs: Any) → List[Document]¶
Return docs most similar to query using specified search type.
async asimilarity_search(query: str, k: int = 4, **kwargs: Any) → List[Document]¶
Return docs most similar to query.
async asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) → List[Document]¶
Return docs most similar to embedding vector.
async asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) → List[Tuple[Document, float]]¶
Return docs and relevance scores in the range [0, 1], asynchronously.
0 is dissimilar, 1 is most similar.
Parameters
query – input text
k – Number of Documents to return. Defaults to 4.
**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)
async asimilarity_search_with_score(*args: Any, **kwargs: Any) → List[Tuple[Document, float]]¶
Run similarity search with distance asynchronously.
clear() → None[source]¶
Empty the collection of all its stored entries.
delete(ids: Optional[List[str]] = None, concurrency: Optional[int] = None, **kwargs: Any) → Optional[bool][source]¶
Delete by vector ids.
Parameters
ids (Optional[List[str]]) – List of ids to delete.
concurrency (Optional[int]) – max number of threads issuing
single-doc delete requests. Defaults to instance-level setting.
Returns
True if deletion is successful,False otherwise, None if not implemented.
Return type
Optional[bool]
Return type
Optional[bool]
delete_by_document_id(document_id: str) → bool[source]¶
Remove a single document from the store, given its document_id (str).
Return True if a document has indeed been deleted, False if ID not found.
delete_collection() → None[source]¶
Completely delete the collection from the database (as opposed
to ‘clear()’, which empties it only).
Stored data is lost and unrecoverable, resources are freed.
Use with caution.
classmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) → ADBVST[source]¶
Create an Astra DB vectorstore from a document list.
Utility method that defers to ‘from_texts’ (see that one).
Args: see ‘from_texts’, except here you have to supply ‘documents’in place of ‘texts’ and ‘metadatas’.
Returns
an AstraDB vectorstore.
classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) → ADBVST[source]¶
Create an Astra DB vectorstore from raw texts.
Parameters
texts (List[str]) – the texts to insert.
embedding (Embeddings) – the embedding function to use in the store.
metadatas (Optional[List[dict]]) – metadata dicts for the texts.
ids (Optional[List[str]]) – ids to associate to the texts.
arguments* (*Additional) – you can pass any argument that you would
to ‘add_texts’ and/or to the ‘AstraDB’ class constructor
(see these methods for details). These arguments will be
routed to the respective methods as they are.
Returns
an AstraDb vectorstore.
Returns
an AstraDb vectorstore.
max_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any) → List[Document][source]¶
Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
:param query: Text to look up documents similar to.
:type query: str
:param k: Number of Documents to return.
:type k: int = 4
:param fetch_k: Number of Documents to fetch to pass to MMR algorithm.
:type fetch_k: int = 20
:param 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.
Optional.
Returns
List of Documents selected by maximal marginal relevance.
max_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any) → List[Document][source]¶
Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
:param embedding: Embedding to look up documents similar to.
:param k: Number of Documents to return.
:param fetch_k: Number of Documents to fetch to pass to MMR algorithm.
:param 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.
Returns
List of Documents selected by maximal marginal relevance.
Returns
List of Documents selected by maximal marginal relevance.
search(query: str, search_type: str, **kwargs: Any) → List[Document]¶
Return docs most similar to query using specified search type.
similarity_search(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None, **kwargs: Any) → List[Document][source]¶
Return docs most similar to query.
similarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None, **kwargs: Any) → List[Document][source]¶
Return docs most similar to embedding vector.
Parameters
embedding – Embedding to look up documents similar to.
k – Number of Documents to return. Defaults to 4.
Returns
List of Documents most similar to the query vector.
similarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) → List[Tuple[Document, float]]¶
Return docs and relevance scores in the range [0, 1].
0 is dissimilar, 1 is most similar.
Parameters
query – input text
k – Number of Documents to return. Defaults to 4.
**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)
similarity_search_with_score(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None) → List[Tuple[Document, float]][source]¶
Run similarity search with distance.
Run similarity search with distance.
similarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None) → List[Tuple[Document, float]][source]¶
Return docs most similar to embedding vector.
Parameters
embedding (str) – Embedding to look up documents similar to.
k (int) – Number of Documents to return. Defaults to 4.
Returns
List of (Document, score), the most similar to the query vector.
similarity_search_with_score_id(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None) → List[Tuple[Document, float, str]][source]¶
similarity_search_with_score_id_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None) → List[Tuple[Document, float, str]][source]¶
Return docs most similar to embedding vector.
Parameters
embedding (str) – Embedding to look up documents similar to.
k (int) – Number of Documents to return. Defaults to 4.
Returns
List of (Document, score, id), the most similar to the query vector.
langchain_community.vectorstores.redis.schema.HNSWVectorField¶
class langchain_community.vectorstores.redis.schema.HNSWVectorField[source]¶
Bases: RedisVectorField
Schema for HNSW vector fields in Redis.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param algorithm: Literal['HNSW'] = 'HNSW'¶
param datatype: str = 'FLOAT32'¶
param dims: int [Required]¶
param distance_metric: langchain_community.vectorstores.redis.schema.RedisDistanceMetric = 'COSINE'¶
param ef_construction: int = 200¶
param ef_runtime: int = 10¶
param epsilon: float = 0.01¶
param initial_cap: Optional[int] = None¶
param m: int = 16¶
param name: str [Required]¶
as_field() → VectorField[source]¶
classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values
copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include – fields to include in new model
exclude – fields to exclude from new model, as with values this takes precedence over include
exclude – fields to exclude from new model, as with values this takes precedence over include
update – values to change/add in the new model. Note: the data is not validated before creating
the new model: you should trust this data
deep – set to True to make a deep copy of the model
Returns
new model instance
dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
classmethod from_orm(obj: Any) → Model¶
json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶
Generate a JSON representation of the model, include and exclude arguments as per dict().
encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().
classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
classmethod parse_obj(obj: Any) → Model¶
classmethod parse_obj(obj: Any) → Model¶
classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶
classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶
classmethod update_forward_refs(**localns: Any) → None¶
Try to update ForwardRefs on fields based on this Model, globalns and localns.
classmethod validate(value: Any) → Model¶
langchain_community.vectorstores.singlestoredb.SingleStoreDB¶
class langchain_community.vectorstores.singlestoredb.SingleStoreDB(embedding: Embeddings, *, distance_strategy: DistanceStrategy = DistanceStrategy.DOT_PRODUCT, table_name: str = 'embeddings', content_field: str = 'content', metadata_field: str = 'metadata', vector_field: str = 'vector', pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any)[source]¶
SingleStore DB vector store.
The prerequisite for using this class is the installation of the singlestoredb
Python package.
The SingleStoreDB vectorstore can be created by providing an embedding function and
the relevant parameters for the database connection, connection pool, and
optionally, the names of the table and the fields to use.
Initialize with necessary components.
Parameters
embedding (Embeddings) – A text embedding model.
distance_strategy (DistanceStrategy, optional) – Determines the strategy employed for calculating
the distance between vectors in the embedding space.
Defaults to DOT_PRODUCT.
Available options are:
- DOT_PRODUCT: Computes the scalar product of two vectors.
This is the default behavior
EUCLIDEAN_DISTANCE: Computes the Euclidean distance betweentwo vectors. This metric considers the geometric distance in
the vector space, and might be more suitable for embeddings
that rely on spatial relationships.
table_name (str, optional) – Specifies the name of the table in use.
Defaults to “embeddings”.
content_field (str, optional) – Specifies the field to store the content.
Defaults to “content”.
metadata_field (str, optional) – Specifies the field to store metadata.
Defaults to “metadata”.
vector_field (str, optional) – Specifies the field to store the vector.
Defaults to “vector”.
Defaults to “vector”.
pool (Following arguments pertain to the connection) – 
pool_size (int, optional) – Determines the number of active connections in
the pool. Defaults to 5.
max_overflow (int, optional) – Determines the maximum number of connections
allowed beyond the pool_size. Defaults to 10.
timeout (float, optional) – Specifies the maximum wait time in seconds for
establishing a connection. Defaults to 30.
connection (database) – 
host (str, optional) – Specifies the hostname, IP address, or URL for the
database connection. The default scheme is “mysql”.
user (str, optional) – Database username.
password (str, optional) – Database password.
port (int, optional) – Database port. Defaults to 3306 for non-HTTP
connections, 80 for HTTP connections, and 443 for HTTPS connections.
database (str, optional) – Database name.
the (Additional optional arguments provide further customization over) – 
connection – 
pure_python (bool, optional) – Toggles the connector mode. If True,
operates in pure Python mode.
local_infile (bool, optional) – Allows local file uploads.
charset (str, optional) – Specifies the character set for string values.
ssl_key (str, optional) – Specifies the path of the file containing the SSL
key.
ssl_cert (str, optional) – Specifies the path of the file containing the SSL
certificate.
ssl_ca (str, optional) – Specifies the path of the file containing the SSL
certificate authority.
ssl_cipher (str, optional) – Sets the SSL cipher list.
ssl_disabled (bool, optional) – Disables SSL usage.
ssl_verify_cert (bool, optional) – Verifies the server’s certificate.
Automatically enabled if ssl_ca is specified.
Automatically enabled if ssl_ca is specified.
ssl_verify_identity (bool, optional) – Verifies the server’s identity.
conv (dict[int, Callable], optional) – A dictionary of data conversion
functions.
credential_type (str, optional) – Specifies the type of authentication to
use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.
autocommit (bool, optional) – Enables autocommits.
results_type (str, optional) – Determines the structure of the query results:
tuples, namedtuples, dicts.
results_format (str, optional) – Deprecated. This option has been renamed to
results_type.
Examples
Basic Usage:
from langchain_community.embeddings import OpenAIEmbeddings
from langchain_community.vectorstores import SingleStoreDB
vectorstore = SingleStoreDB(
    OpenAIEmbeddings(),
    host="https://user:password@127.0.0.1:3306/database"
)
Advanced Usage:
from langchain_community.embeddings import OpenAIEmbeddings
from langchain_community.vectorstores import SingleStoreDB
vectorstore = SingleStoreDB(
    OpenAIEmbeddings(),
    distance_strategy=DistanceStrategy.EUCLIDEAN_DISTANCE,
    host="127.0.0.1",
    port=3306,
    user="user",
    password="password",
    database="db",
    table_name="my_custom_table",
    pool_size=10,
    timeout=60,
)
Using environment variables:
from langchain_community.embeddings import OpenAIEmbeddings
from langchain_community.vectorstores import SingleStoreDB
os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db'
vectorstore = SingleStoreDB(OpenAIEmbeddings())
Attributes
embeddings