id
stringlengths
14
15
text
stringlengths
49
2.47k
source
stringlengths
61
166
56d932d3e8ab-6
Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters embedding – Embedding to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. 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, **kwargs: Any) → List[Document][source]¶ Return documents most similar to the query Parameters query – String to query the vectorstore with. k – Number of documents to return. Returns List of documents most similar to the query. similarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) → List[Document]¶ 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:
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.lancedb.LanceDB.html
56d932d3e8ab-7
**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(*args: Any, **kwargs: Any) → List[Tuple[Document, float]]¶ Run similarity search with distance. Examples using LanceDB¶ LanceDB
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.lancedb.LanceDB.html
3fb917695416-0
langchain.vectorstores.pgembedding.CollectionStore¶ class langchain.vectorstores.pgembedding.CollectionStore(**kwargs)[source]¶ A simple constructor that allows initialization from kwargs. Sets attributes on the constructed instance using the names and values in kwargs. Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships. Attributes cmetadata embeddings metadata name registry uuid Methods __init__(**kwargs) A simple constructor that allows initialization from kwargs. get_by_name(session, name) get_or_create(session, name[, cmetadata]) Get or create a collection. __init__(**kwargs)¶ A simple constructor that allows initialization from kwargs. Sets attributes on the constructed instance using the names and values in kwargs. Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships. classmethod get_by_name(session: Session, name: str) → Optional[CollectionStore][source]¶ classmethod get_or_create(session: Session, name: str, cmetadata: Optional[dict] = None) → Tuple[CollectionStore, bool][source]¶ Get or create a collection. Returns [Collection, bool] where the bool is True if the collection was created.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgembedding.CollectionStore.html
60c04d5f3c1b-0
langchain.vectorstores.analyticdb.AnalyticDB¶ class langchain.vectorstores.analyticdb.AnalyticDB(connection_string: str, embedding_function: Embeddings, embedding_dimension: int = 1536, collection_name: str = 'langchain_document', pre_delete_collection: bool = False, logger: Optional[Logger] = None, engine_args: Optional[dict] = None)[source]¶ VectorStore implementation using AnalyticDB. AnalyticDB is a distributed full postgresql syntax cloud-native database. - connection_string is a postgres connection string. - embedding_function any embedding function implementing langchain.embeddings.base.Embeddings interface. collection_name is the name of the collection to use. (default: langchain) NOTE: This is not the name of the table, but the name of the collection.The tables will be created when initializing the store (if not exists) So, make sure the user has the right permissions to create tables. pre_delete_collection if True, will delete the collection if it exists.(default: False) - Useful for testing. Attributes embeddings Access the query embedding object if available. Methods __init__(connection_string, embedding_function) aadd_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. aadd_texts(texts[, metadatas]) Run more texts through the embeddings and add to the vectorstore. add_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. add_texts(texts[, metadatas, ids, batch_size]) Run more texts through the embeddings and add to the vectorstore. afrom_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html
60c04d5f3c1b-1
Return VectorStore initialized from documents and embeddings. afrom_texts(texts, embedding[, metadatas]) Return VectorStore initialized from texts and embeddings. amax_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. amax_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. as_retriever(**kwargs) Return VectorStoreRetriever initialized from this VectorStore. asearch(query, search_type, **kwargs) Return docs most similar to query using specified search type. asimilarity_search(query[, k]) Return docs most similar to query. asimilarity_search_by_vector(embedding[, k]) Return docs most similar to embedding vector. asimilarity_search_with_relevance_scores(query) Return docs most similar to query. connection_string_from_db_params(driver, ...) Return connection string from database parameters. create_collection() create_table_if_not_exists() delete([ids]) Delete by vector IDs. delete_collection() from_documents(documents, embedding[, ...]) Return VectorStore initialized from documents and embeddings. from_texts(texts, embedding[, metadatas, ...]) Return VectorStore initialized from texts and embeddings. get_connection_string(kwargs) max_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. max_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. search(query, search_type, **kwargs) Return docs most similar to query using specified search type. similarity_search(query[, k, filter]) Run similarity search with AnalyticDB with distance. similarity_search_by_vector(embedding[, k, ...])
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html
60c04d5f3c1b-2
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]) Return docs most similar to query. similarity_search_with_score_by_vector(embedding) __init__(connection_string: str, embedding_function: Embeddings, embedding_dimension: int = 1536, collection_name: str = 'langchain_document', pre_delete_collection: bool = False, logger: Optional[Logger] = None, engine_args: Optional[dict] = None) → None[source]¶ 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] add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, batch_size: int = 500, **kwargs: Any) → List[str][source]¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html
60c04d5f3c1b-3
Run more texts through the embeddings and add to the vectorstore. Parameters texts – Iterable of strings to add to the vectorstore. metadatas – Optional list of metadatas associated with the texts. kwargs – vectorstore specific parameters Returns List of ids from adding the texts into the vectorstore. 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”. 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
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html
60c04d5f3c1b-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.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html
60c04d5f3c1b-5
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 most similar to query. classmethod connection_string_from_db_params(driver: str, host: str, port: int, database: str, user: str, password: str) → str[source]¶ Return connection string from database parameters. create_collection() → None[source]¶ create_table_if_not_exists() → None[source]¶ delete(ids: Optional[List[str]] = None, **kwargs: Any) → Optional[bool][source]¶ Delete by vector IDs. Parameters ids – List of ids to delete. delete_collection() → None[source]¶ classmethod from_documents(documents: List[Document], embedding: Embeddings, embedding_dimension: int = 1536, collection_name: str = 'langchain_document', ids: Optional[List[str]] = None, pre_delete_collection: bool = False, engine_args: Optional[dict] = None, **kwargs: Any) → AnalyticDB[source]¶ Return VectorStore initialized from documents and embeddings. Postgres Connection string is required Either pass it as a parameter or set the PG_CONNECTION_STRING environment variable.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html
60c04d5f3c1b-6
Either pass it as a parameter or set the PG_CONNECTION_STRING environment variable. classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, embedding_dimension: int = 1536, collection_name: str = 'langchain_document', ids: Optional[List[str]] = None, pre_delete_collection: bool = False, engine_args: Optional[dict] = None, **kwargs: Any) → AnalyticDB[source]¶ Return VectorStore initialized from texts and embeddings. Postgres Connection string is required Either pass it as a parameter or set the PG_CONNECTION_STRING environment variable. classmethod get_connection_string(kwargs: Dict[str, Any]) → str[source]¶ max_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. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters query – Text to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. 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, **kwargs: Any) → List[Document]¶ Return docs selected using the maximal marginal relevance.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html
60c04d5f3c1b-7
Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters embedding – Embedding to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. 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] = None, **kwargs: Any) → List[Document][source]¶ Run similarity search with AnalyticDB with distance. Parameters query (str) – Query text to search for. 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. similarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[dict] = 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. filter (Optional[Dict[str, str]]) – Filter by metadata. Defaults to None. Returns List of Documents most similar to the query vector.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html
60c04d5f3c1b-8
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] = None) → List[Tuple[Document, float]][source]¶ Return docs most similar to query. Parameters 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. Returns List of Documents most similar to the query and score for each similarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[dict] = None) → List[Tuple[Document, float]][source]¶ Examples using AnalyticDB¶ AnalyticDB
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html
3e12184d452c-0
langchain.vectorstores.annoy.dependable_annoy_import¶ langchain.vectorstores.annoy.dependable_annoy_import() → Any[source]¶ Import annoy if available, otherwise raise error.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.annoy.dependable_annoy_import.html
ab08383b1a4f-0
langchain.vectorstores.sklearn.SKLearnVectorStoreException¶ class langchain.vectorstores.sklearn.SKLearnVectorStoreException[source]¶ Exception raised by SKLearnVectorStore.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sklearn.SKLearnVectorStoreException.html
49355fcec31a-0
langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever¶ class langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever[source]¶ Bases: BaseRetriever Retriever that uses Azure Search to find similar documents. 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 k: int = 4¶ Number of documents to return. param metadata: Optional[Dict[str, Any]] = None¶ Optional metadata associated with the retriever. Defaults to None This metadata will be associated with each call to this retriever, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a retriever with its use case. param search_type: str = 'hybrid'¶ Type of search to perform. Options are “similarity”, “hybrid”, “semantic_hybrid”. param tags: Optional[List[str]] = None¶ Optional list of tags associated with the retriever. Defaults to None These tags will be associated with each call to this retriever, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a retriever with its use case. param vectorstore: langchain.vectorstores.azuresearch.AzureSearch [Required]¶ Azure Search instance used to find similar documents. async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, max_concurrency: Optional[int] = None) → List[Output]¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever.html
49355fcec31a-1
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) → List[Document]¶ Asynchronously get documents relevant to a query. :param query: string to find relevant documents for :param callbacks: Callback manager or list of callbacks :param tags: Optional list of tags associated with the retriever. Defaults to None These tags will be associated with each call to this retriever, and passed as arguments to the handlers defined in callbacks. Parameters metadata – Optional metadata associated with the retriever. Defaults to None This metadata will be associated with each call to this retriever, and passed as arguments to the handlers defined in callbacks. Returns List of relevant documents async ainvoke(input: str, config: Optional[RunnableConfig] = None) → List[Document]¶ async astream(input: Input, config: Optional[RunnableConfig] = None) → AsyncIterator[Output]¶ batch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, max_concurrency: Optional[int] = None) → List[Output]¶ bind(**kwargs: Any) → Runnable[Input, Output]¶ Bind arguments to a Runnable, returning a new Runnable. 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
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever.html
49355fcec31a-2
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 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¶ get_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) → List[Document]¶ Retrieve documents relevant to a query. :param query: string to find relevant documents for :param callbacks: Callback manager or list of callbacks :param tags: Optional list of tags associated with the retriever. Defaults to None These tags will be associated with each call to this retriever,
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever.html
49355fcec31a-3
These tags will be associated with each call to this retriever, and passed as arguments to the handlers defined in callbacks. Parameters metadata – Optional metadata associated with the retriever. Defaults to None This metadata will be associated with each call to this retriever, and passed as arguments to the handlers defined in callbacks. Returns List of relevant documents invoke(input: str, config: Optional[RunnableConfig] = None) → List[Document]¶ 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_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¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever.html
49355fcec31a-4
classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ stream(input: Input, config: Optional[RunnableConfig] = None) → Iterator[Output]¶ to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶ to_json_not_implemented() → SerializedNotImplemented¶ 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¶ with_fallbacks(fallbacks: ~typing.Sequence[~langchain.schema.runnable.Runnable[~langchain.schema.runnable.Input, ~langchain.schema.runnable.Output]], *, exceptions_to_handle: ~typing.Tuple[~typing.Type[BaseException]] = (<class 'Exception'>,)) → RunnableWithFallbacks[Input, Output]¶ property lc_attributes: Dict¶ Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str]¶ Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str]¶ Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool¶ Return whether or not the class is serializable.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever.html
9b708fceaad1-0
langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch¶ class langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch(doc_index: BaseDocIndex, embedding: Embeddings)[source]¶ Wrapper around HnswLib storage. To use it, you should have the docarray package with version >=0.32.0 installed. You can install it with pip install “langchain[docarray]”. Initialize a vector store from DocArray’s DocIndex. Attributes doc_cls embeddings Access the query embedding object if available. Methods __init__(doc_index, embedding) Initialize a vector store from DocArray's DocIndex. aadd_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. aadd_texts(texts[, metadatas]) Run more texts through the embeddings and add to the vectorstore. add_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. add_texts(texts[, metadatas]) Run more texts through the embeddings and add to the vectorstore. afrom_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings. afrom_texts(texts, embedding[, metadatas]) Return VectorStore initialized from texts and embeddings. amax_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. amax_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. as_retriever(**kwargs) Return VectorStoreRetriever initialized from this VectorStore. asearch(query, search_type, **kwargs) Return docs most similar to query using specified search type. asimilarity_search(query[, k])
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html
9b708fceaad1-1
asimilarity_search(query[, k]) Return docs most similar to query. asimilarity_search_by_vector(embedding[, k]) Return docs most similar to embedding vector. asimilarity_search_with_relevance_scores(query) Return docs most similar to query. delete([ids]) Delete by vector ID or other criteria. from_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings. from_params(embedding, work_dir, n_dim[, ...]) Initialize DocArrayHnswSearch store. from_texts(texts, embedding[, metadatas, ...]) Create an DocArrayHnswSearch store and insert data. max_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. max_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. search(query, search_type, **kwargs) Return docs most similar to query using specified search type. similarity_search(query[, k]) 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]) Return docs most similar to query. __init__(doc_index: BaseDocIndex, embedding: Embeddings)¶ Initialize a vector store from DocArray’s DocIndex. 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
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html
9b708fceaad1-2
(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] add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) → List[str]¶ Run more texts through the embeddings and add to the vectorstore. Parameters texts – Iterable of strings to add to the vectorstore. metadatas – Optional list of metadatas associated with the texts. Returns List of ids from adding the texts into the vectorstore. 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.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html
9b708fceaad1-3
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”. 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} )
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html
9b708fceaad1-4
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 most similar to query. delete(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] classmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) → VST¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html
9b708fceaad1-5
Return VectorStore initialized from documents and embeddings. classmethod from_params(embedding: Embeddings, work_dir: str, n_dim: int, dist_metric: Literal['cosine', 'ip', 'l2'] = 'cosine', max_elements: int = 1024, index: bool = True, ef_construction: int = 200, ef: int = 10, M: int = 16, allow_replace_deleted: bool = True, num_threads: int = 1, **kwargs: Any) → DocArrayHnswSearch[source]¶ Initialize DocArrayHnswSearch store. Parameters embedding (Embeddings) – Embedding function. work_dir (str) – path to the location where all the data will be stored. n_dim (int) – dimension of an embedding. dist_metric (str) – Distance metric for DocArrayHnswSearch can be one of: “cosine”, “ip”, and “l2”. Defaults to “cosine”. max_elements (int) – Maximum number of vectors that can be stored. Defaults to 1024. index (bool) – Whether an index should be built for this field. Defaults to True. ef_construction (int) – defines a construction time/accuracy trade-off. Defaults to 200. ef (int) – parameter controlling query time/accuracy trade-off. Defaults to 10. M (int) – parameter that defines the maximum number of outgoing connections in the graph. Defaults to 16. allow_replace_deleted (bool) – Enables replacing of deleted elements with new added ones. Defaults to True. num_threads (int) – Sets the number of cpu threads to use. Defaults to 1. **kwargs – Other keyword arguments to be passed to the get_doc_cls method.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html
9b708fceaad1-6
**kwargs – Other keyword arguments to be passed to the get_doc_cls method. classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, work_dir: Optional[str] = None, n_dim: Optional[int] = None, **kwargs: Any) → DocArrayHnswSearch[source]¶ Create an DocArrayHnswSearch store and insert data. Parameters texts (List[str]) – Text data. embedding (Embeddings) – Embedding function. metadatas (Optional[List[dict]]) – Metadata for each text if it exists. Defaults to None. work_dir (str) – path to the location where all the data will be stored. n_dim (int) – dimension of an embedding. **kwargs – Other keyword arguments to be passed to the __init__ method. Returns DocArrayHnswSearch Vector Store max_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. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters query – Text to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. Returns List of Documents selected by maximal marginal relevance.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html
9b708fceaad1-7
Defaults to 0.5. 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, **kwargs: Any) → List[Document]¶ Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters embedding – Embedding to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. 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, **kwargs: Any) → List[Document]¶ Return docs most similar to query. Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 4. Returns List of Documents most similar to the query. similarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) → List[Document]¶ 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.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html
9b708fceaad1-8
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, **kwargs: Any) → List[Tuple[Document, float]]¶ Return docs most similar to query. Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 4. Returns List of documents most similar to the query text and cosine distance in float for each. Lower score represents more similarity. Examples using DocArrayHnswSearch¶ DocArrayHnswSearch
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html
dcad328845f0-0
langchain.vectorstores.redis.Redis¶ class langchain.vectorstores.redis.Redis(redis_url: str, index_name: str, embedding_function: Callable, content_key: str = 'content', metadata_key: str = 'metadata', vector_key: str = 'content_vector', relevance_score_fn: Optional[Callable[[float], float]] = None, distance_metric: Literal['COSINE', 'IP', 'L2'] = 'COSINE', **kwargs: Any)[source]¶ Wrapper around Redis vector database. To use, you should have the redis python package installed. Example from langchain.vectorstores import Redis from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() vectorstore = Redis( redis_url="redis://username:password@localhost:6379" index_name="my-index", embedding_function=embeddings.embed_query, ) To use a redis replication setup with multiple redis server and redis sentinels set “redis_url” to “redis+sentinel://” scheme. With this url format a path is needed holding the name of the redis service within the sentinels to get the correct redis server connection. The default service name is “mymaster”. An optional username or password is used for booth connections to the rediserver and the sentinel, different passwords for server and sentinel are not supported. And as another constraint only one sentinel instance can be given: Example vectorstore = Redis( redis_url="redis+sentinel://username:password@sentinelhost:26379/mymaster/0" index_name="my-index", embedding_function=embeddings.embed_query, ) Initialize with necessary components. Attributes embeddings Access the query embedding object if available. Methods __init__(redis_url, index_name, ...[, ...])
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.Redis.html
dcad328845f0-1
Methods __init__(redis_url, index_name, ...[, ...]) Initialize with necessary components. aadd_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. aadd_texts(texts[, metadatas]) Run more texts through the embeddings and add to the vectorstore. add_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. add_texts(texts[, metadatas, embeddings, ...]) Add more texts to the vectorstore. afrom_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings. afrom_texts(texts, embedding[, metadatas]) Return VectorStore initialized from texts and embeddings. amax_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. amax_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. as_retriever(**kwargs) Return VectorStoreRetriever initialized from this VectorStore. asearch(query, search_type, **kwargs) Return docs most similar to query using specified search type. asimilarity_search(query[, k]) Return docs most similar to query. asimilarity_search_by_vector(embedding[, k]) Return docs most similar to embedding vector. asimilarity_search_with_relevance_scores(query) Return docs most similar to query. delete([ids]) Delete a Redis entry. drop_index(index_name, delete_documents, ...) Drop a Redis search index. from_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings. from_existing_index(embedding, index_name[, ...])
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.Redis.html
dcad328845f0-2
from_existing_index(embedding, index_name[, ...]) Connect to an existing Redis index. from_texts(texts, embedding[, metadatas, ...]) Create a Redis vectorstore from raw documents. from_texts_return_keys(texts, embedding[, ...]) Create a Redis vectorstore from raw documents. max_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. max_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. search(query, search_type, **kwargs) Return docs most similar to query using specified search type. similarity_search(query[, k]) Returns the most similar indexed documents to the query text. similarity_search_by_vector(embedding[, k]) Return docs most similar to embedding vector. similarity_search_limit_score(query[, k, ...]) Returns the most similar indexed documents to the query text within the score_threshold range. similarity_search_with_relevance_scores(query) Return docs and relevance scores in the range [0, 1]. similarity_search_with_score(query[, k]) Return docs most similar to query. __init__(redis_url: str, index_name: str, embedding_function: Callable, content_key: str = 'content', metadata_key: str = 'metadata', vector_key: str = 'content_vector', relevance_score_fn: Optional[Callable[[float], float]] = None, distance_metric: Literal['COSINE', 'IP', 'L2'] = 'COSINE', **kwargs: Any)[source]¶ Initialize with necessary components. async aadd_documents(documents: List[Document], **kwargs: Any) → List[str]¶ Run more documents through the embeddings and add to the vectorstore. Parameters
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.Redis.html
dcad328845f0-3
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] add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, embeddings: Optional[List[List[float]]] = None, batch_size: int = 1000, **kwargs: Any) → List[str][source]¶ Add more texts to the vectorstore. Parameters texts (Iterable[str]) – Iterable of strings/text to add to the vectorstore. metadatas (Optional[List[dict]], optional) – Optional list of metadatas. Defaults to None. embeddings (Optional[List[List[float]]], optional) – Optional pre-generated embeddings. Defaults to None. keys (List[str]) or ids (List[str]) – Identifiers of entries. Defaults to None. batch_size (int, optional) – Batch size to use for writes. Defaults to 1000. Returns List of ids added to the vectorstore Return type List[str] async classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) → VST¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.Redis.html
dcad328845f0-4
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) → RedisVectorStoreRetriever[source]¶ 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”. 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
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.Redis.html
dcad328845f0-5
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 most similar to query.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.Redis.html
dcad328845f0-6
Return docs most similar to query. static delete(ids: Optional[List[str]] = None, **kwargs: Any) → bool[source]¶ Delete a Redis entry. Parameters ids – List of ids (keys) to delete. Returns Whether or not the deletions were successful. Return type bool static drop_index(index_name: str, delete_documents: bool, **kwargs: Any) → bool[source]¶ Drop a Redis search index. Parameters index_name (str) – Name of the index to drop. delete_documents (bool) – Whether to drop the associated documents. Returns Whether or not the drop was successful. Return type bool classmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) → VST¶ Return VectorStore initialized from documents and embeddings. classmethod from_existing_index(embedding: Embeddings, index_name: str, content_key: str = 'content', metadata_key: str = 'metadata', vector_key: str = 'content_vector', **kwargs: Any) → Redis[source]¶ Connect to an existing Redis index. classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, index_name: Optional[str] = None, content_key: str = 'content', metadata_key: str = 'metadata', vector_key: str = 'content_vector', **kwargs: Any) → Redis[source]¶ Create a Redis vectorstore from raw documents. This is a user-friendly interface that: 1. Embeds documents. 2. Creates a new index for the embeddings in Redis. 3. Adds the documents to the newly created Redis index. This is intended to be a quick way to get started. Example from langchain.vectorstores import Redis from langchain.embeddings import OpenAIEmbeddings
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.Redis.html
dcad328845f0-7
from langchain.vectorstores import Redis from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() redisearch = RediSearch.from_texts( texts, embeddings, redis_url="redis://username:password@localhost:6379" ) classmethod from_texts_return_keys(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, index_name: Optional[str] = None, content_key: str = 'content', metadata_key: str = 'metadata', vector_key: str = 'content_vector', distance_metric: Literal['COSINE', 'IP', 'L2'] = 'COSINE', **kwargs: Any) → Tuple[Redis, List[str]][source]¶ Create a Redis vectorstore from raw documents. This is a user-friendly interface that: 1. Embeds documents. 2. Creates a new index for the embeddings in Redis. 3. Adds the documents to the newly created Redis index. 4. Returns the keys of the newly created documents. This is intended to be a quick way to get started. Example from langchain.vectorstores import Redis from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() redisearch, keys = RediSearch.from_texts_return_keys( texts, embeddings, redis_url="redis://username:password@localhost:6379" ) max_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. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.Redis.html
dcad328845f0-8
Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters query – Text to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. 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, **kwargs: Any) → List[Document]¶ Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters embedding – Embedding to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. 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, **kwargs: Any) → List[Document][source]¶ Returns the most similar indexed documents to the query text. Parameters query (str) – The query text for which to find similar documents.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.Redis.html
dcad328845f0-9
Parameters query (str) – The query text for which to find similar documents. k (int) – The number of documents to return. Default is 4. Returns A list of documents that are most similar to the query text. Return type List[Document] similarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) → List[Document]¶ 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_limit_score(query: str, k: int = 4, score_threshold: float = 0.2, **kwargs: Any) → List[Document][source]¶ Returns the most similar indexed documents to the query text within the score_threshold range. Parameters query (str) – The query text for which to find similar documents. k (int) – The number of documents to return. Default is 4. score_threshold (float) – The minimum matching score required for a document to be considered a match. Defaults to 0.2. Because the similarity calculation algorithm is based on cosine similarity, the smaller the angle, the higher the similarity. Returns A list of documents that are most similar to the query text,including the match score for each document. Return type List[Document] Note If there are no documents that satisfy the score_threshold value, an empty list is returned. 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].
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.Redis.html
dcad328845f0-10
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) → List[Tuple[Document, float]][source]¶ Return docs most similar to query. Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 4. Returns List of Documents most similar to the query and score for each Examples using Redis¶ Redis
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.Redis.html
d417ce30a44b-0
langchain.vectorstores.atlas.AtlasDB¶ class langchain.vectorstores.atlas.AtlasDB(name: str, embedding_function: Optional[Embeddings] = None, api_key: Optional[str] = None, description: str = 'A description for your project', is_public: bool = True, reset_project_if_exists: bool = False)[source]¶ Wrapper around Atlas: Nomic’s neural database and rhizomatic instrument. To use, you should have the nomic python package installed. Example from langchain.vectorstores import AtlasDB from langchain.embeddings.openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings() vectorstore = AtlasDB("my_project", embeddings.embed_query) Initialize the Atlas Client Parameters name (str) – The name of your project. If the project already exists, it will be loaded. embedding_function (Optional[Embeddings]) – An optional function used for embedding your data. If None, data will be embedded with Nomic’s embed model. api_key (str) – Your nomic API key description (str) – A description for your project. is_public (bool) – Whether your project is publicly accessible. True by default. reset_project_if_exists (bool) – Whether to reset this project if it already exists. Default False. Generally useful during development and testing. Attributes embeddings Access the query embedding object if available. Methods __init__(name[, embedding_function, ...]) Initialize the Atlas Client aadd_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. aadd_texts(texts[, metadatas]) Run more texts through the embeddings and add to the vectorstore. add_documents(documents, **kwargs)
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html
d417ce30a44b-1
add_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. add_texts(texts[, metadatas, ids, refresh]) Run more texts through the embeddings and add to the vectorstore. afrom_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings. afrom_texts(texts, embedding[, metadatas]) Return VectorStore initialized from texts and embeddings. amax_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. amax_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. as_retriever(**kwargs) Return VectorStoreRetriever initialized from this VectorStore. asearch(query, search_type, **kwargs) Return docs most similar to query using specified search type. asimilarity_search(query[, k]) Return docs most similar to query. asimilarity_search_by_vector(embedding[, k]) Return docs most similar to embedding vector. asimilarity_search_with_relevance_scores(query) Return docs most similar to query. create_index(**kwargs) Creates an index in your project. delete([ids]) Delete by vector ID or other criteria. from_documents(documents[, embedding, ids, ...]) Create an AtlasDB vectorstore from a list of documents. from_texts(texts[, embedding, metadatas, ...]) Create an AtlasDB vectorstore from a raw documents. max_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. max_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. search(query, search_type, **kwargs)
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html
d417ce30a44b-2
search(query, search_type, **kwargs) Return docs most similar to query using specified search type. similarity_search(query[, k]) Run similarity search with AtlasDB 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(*args, **kwargs) Run similarity search with distance. __init__(name: str, embedding_function: Optional[Embeddings] = None, api_key: Optional[str] = None, description: str = 'A description for your project', is_public: bool = True, reset_project_if_exists: bool = False) → None[source]¶ Initialize the Atlas Client Parameters name (str) – The name of your project. If the project already exists, it will be loaded. embedding_function (Optional[Embeddings]) – An optional function used for embedding your data. If None, data will be embedded with Nomic’s embed model. api_key (str) – Your nomic API key description (str) – A description for your project. is_public (bool) – Whether your project is publicly accessible. True by default. reset_project_if_exists (bool) – Whether to reset this project if it already exists. Default False. Generally useful during development and testing. 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]
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html
d417ce30a44b-3
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] add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, refresh: bool = True, **kwargs: Any) → List[str][source]¶ Run more texts through the embeddings and add to the vectorstore. Parameters texts (Iterable[str]) – Texts to add to the vectorstore. metadatas (Optional[List[dict]], optional) – Optional list of metadatas. ids (Optional[List[str]]) – An optional list of ids. refresh (bool) – Whether or not to refresh indices with the updated data. Default True. Returns List of IDs of the added texts. Return type List[str] 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.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html
d417ce30a44b-4
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”. 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} )
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html
d417ce30a44b-5
) # 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 most similar to query. create_index(**kwargs: Any) → Any[source]¶ Creates an index in your project. See https://docs.nomic.ai/atlas_api.html#nomic.project.AtlasProject.create_index for full detail.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html
d417ce30a44b-6
for full detail. delete(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] classmethod from_documents(documents: List[Document], embedding: Optional[Embeddings] = None, ids: Optional[List[str]] = None, name: Optional[str] = None, api_key: Optional[str] = None, persist_directory: Optional[str] = None, description: str = 'A description for your project', is_public: bool = True, reset_project_if_exists: bool = False, index_kwargs: Optional[dict] = None, **kwargs: Any) → AtlasDB[source]¶ Create an AtlasDB vectorstore from a list of documents. Parameters name (str) – Name of the collection to create. api_key (str) – Your nomic API key, documents (List[Document]) – List of documents to add to the vectorstore. embedding (Optional[Embeddings]) – Embedding function. Defaults to None. 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) – Whether to reset this project if it already exists. Default False. Generally useful during development and testing. index_kwargs (Optional[dict]) – Dict of kwargs for index creation. See https://docs.nomic.ai/atlas_api.html Returns Nomic’s neural database and finest rhizomatic instrument Return type AtlasDB
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html
d417ce30a44b-7
Returns Nomic’s neural database and finest rhizomatic instrument Return type AtlasDB classmethod from_texts(texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, name: Optional[str] = None, api_key: Optional[str] = None, description: str = 'A description for your project', is_public: bool = True, reset_project_if_exists: bool = False, index_kwargs: Optional[dict] = None, **kwargs: Any) → AtlasDB[source]¶ Create an AtlasDB vectorstore from a raw documents. Parameters texts (List[str]) – The list of texts to ingest. name (str) – Name of the project to create. api_key (str) – Your nomic API key, embedding (Optional[Embeddings]) – Embedding function. Defaults to None. metadatas (Optional[List[dict]]) – List of metadatas. Defaults to None. ids (Optional[List[str]]) – Optional list of document IDs. If None, ids will be auto created description (str) – A description for your project. is_public (bool) – Whether your project is publicly accessible. True by default. reset_project_if_exists (bool) – Whether to reset this project if it already exists. Default False. Generally useful during development and testing. index_kwargs (Optional[dict]) – Dict of kwargs for index creation. See https://docs.nomic.ai/atlas_api.html Returns Nomic’s neural database and finest rhizomatic instrument Return type AtlasDB max_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) → List[Document]¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html
d417ce30a44b-8
Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters query – Text to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. 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, **kwargs: Any) → List[Document]¶ Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters embedding – Embedding to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. 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, **kwargs: Any) → List[Document][source]¶ Run similarity search with AtlasDB Parameters query (str) – Query text to search for.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html
d417ce30a44b-9
Parameters query (str) – Query text to search for. k (int) – Number of results to return. Defaults to 4. Returns List of documents most similar to the query text. Return type List[Document] similarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) → List[Document]¶ 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(*args: Any, **kwargs: Any) → List[Tuple[Document, float]]¶ Run similarity search with distance. Examples using AtlasDB¶ AtlasDB Atlas
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html
426b66f6b53c-0
langchain.vectorstores.scann.normalize¶ langchain.vectorstores.scann.normalize(x: ndarray) → ndarray[source]¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.normalize.html
2fcb50aa978f-0
langchain.vectorstores.pgvector.DistanceStrategy¶ class langchain.vectorstores.pgvector.DistanceStrategy(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶ Enumerator of the Distance strategies. EUCLIDEAN = 'l2'¶ COSINE = 'cosine'¶ MAX_INNER_PRODUCT = 'inner'¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.DistanceStrategy.html
e54c7e8515e7-0
langchain.vectorstores.hologres.HologresWrapper¶ class langchain.vectorstores.hologres.HologresWrapper(connection_string: str, ndims: int, table_name: str)[source]¶ Methods __init__(connection_string, ndims, table_name) create_table([drop_if_exist]) create_vector_extension() get_by_id(id) insert(embedding, metadata, document[, id]) query_nearest_neighbours(embedding, k[, filter]) __init__(connection_string: str, ndims: int, table_name: str) → None[source]¶ create_table(drop_if_exist: bool = True) → None[source]¶ create_vector_extension() → None[source]¶ get_by_id(id: str) → List[Tuple][source]¶ insert(embedding: List[float], metadata: dict, document: str, id: Optional[str] = None) → None[source]¶ query_nearest_neighbours(embedding: List[float], k: int, filter: Optional[Dict[str, str]] = None) → List[Tuple[str, str, float]][source]¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hologres.HologresWrapper.html
02002c67bb7a-0
langchain.vectorstores.supabase.SupabaseVectorStore¶ class langchain.vectorstores.supabase.SupabaseVectorStore(client: supabase.client.Client, embedding: Embeddings, table_name: str, query_name: Union[str, None] = None)[source]¶ VectorStore for a Supabase postgres database. Assumes you have the pgvector extension installed and a match_documents (or similar) function. For more details: https://integrations.langchain.com/vectorstores?integration_name=SupabaseVectorStore You can implement your own match_documents function in order to limit the search space to a subset of documents based on your own authorization or business logic. Note that the Supabase Python client does not yet support async operations. If you’d like to use max_marginal_relevance_search, please review the instructions below on modifying the match_documents function to return matched embeddings. Examples: from langchain.embeddings.openai import OpenAIEmbeddings from langchain.schema import Document from langchain.vectorstores import SupabaseVectorStore from supabase.client import create_client docs = [ Document(page_content="foo", metadata={"id": 1}), ] embeddings = OpenAIEmbeddings() supabase_client = create_client("my_supabase_url", "my_supabase_key") vector_store = SupabaseVectorStore.from_documents( docs, embeddings, client=supabase_client, table_name="documents", query_name="match_documents", ) To load from an existing table: from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import SupabaseVectorStore from supabase.client import create_client embeddings = OpenAIEmbeddings()
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html
02002c67bb7a-1
from supabase.client import create_client embeddings = OpenAIEmbeddings() supabase_client = create_client("my_supabase_url", "my_supabase_key") vector_store = SupabaseVectorStore( client=supabase_client, embedding=embeddings, table_name="documents", query_name="match_documents", ) Initialize with supabase client. Attributes embeddings Access the query embedding object if available. Methods __init__(client, embedding, table_name[, ...]) Initialize with supabase client. aadd_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. aadd_texts(texts[, metadatas]) Run more texts through the embeddings and add to the vectorstore. add_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. add_texts(texts[, metadatas, ids]) Run more texts through the embeddings and add to the vectorstore. add_vectors(vectors, documents, ids) afrom_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings. afrom_texts(texts, embedding[, metadatas]) Return VectorStore initialized from texts and embeddings. amax_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. amax_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. as_retriever(**kwargs) Return VectorStoreRetriever initialized from this VectorStore. asearch(query, search_type, **kwargs) Return docs most similar to query using specified search type. asimilarity_search(query[, k])
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html
02002c67bb7a-2
asimilarity_search(query[, k]) Return docs most similar to query. asimilarity_search_by_vector(embedding[, k]) Return docs most similar to embedding vector. asimilarity_search_with_relevance_scores(query) Return docs most similar to query. delete([ids]) Delete by vector IDs. from_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings. from_texts(texts, embedding[, metadatas, ...]) Return VectorStore initialized from texts and embeddings. match_args(query, k, filter) max_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. max_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. 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_by_vector_returning_embeddings(...) similarity_search_by_vector_with_relevance_scores(...) similarity_search_with_relevance_scores(query) Return docs and relevance scores in the range [0, 1]. similarity_search_with_score(*args, **kwargs) Run similarity search with distance. __init__(client: supabase.client.Client, embedding: Embeddings, table_name: str, query_name: Union[str, None] = None) → None[source]¶ Initialize with supabase client. async aadd_documents(documents: List[Document], **kwargs: Any) → List[str]¶ Run more documents through the embeddings and add to the vectorstore. Parameters
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html
02002c67bb7a-3
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] add_texts(texts: Iterable[str], metadatas: Optional[List[Dict[Any, Any]]] = None, ids: Optional[List[str]] = None, **kwargs: Any) → List[str][source]¶ Run more texts through the embeddings and add to the vectorstore. Parameters texts – Iterable of strings to add to the vectorstore. metadatas – Optional list of metadatas associated with the texts. kwargs – vectorstore specific parameters Returns List of ids from adding the texts into the vectorstore. add_vectors(vectors: List[List[float]], documents: List[Document], ids: List[str]) → List[str][source]¶ 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.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html
02002c67bb7a-4
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”. 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} )
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html
02002c67bb7a-5
) # 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 most similar to query. delete(ids: Optional[List[str]] = None, **kwargs: Any) → None[source]¶ Delete by vector IDs. Parameters ids – List of ids to delete. classmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) → VST¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html
02002c67bb7a-6
Return VectorStore initialized from documents and embeddings. classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, client: Optional[supabase.client.Client] = None, table_name: Optional[str] = 'documents', query_name: Union[str, None] = 'match_documents', ids: Optional[List[str]] = None, **kwargs: Any) → SupabaseVectorStore[source]¶ Return VectorStore initialized from texts and embeddings. match_args(query: List[float], k: int, filter: Optional[Dict[str, Any]]) → Dict[str, Any][source]¶ max_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **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. Parameters query – Text to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. Returns List of Documents selected by maximal marginal relevance. max_marginal_relevance_search requires that query_name returns matched embeddings alongside the match documents. The following function demonstrates how to do this: ```sql CREATE FUNCTION match_documents_embeddings(query_embedding vector(1536), match_count int) RETURNS TABLE(id uuid, content text, metadata jsonb, embedding vector(1536), similarity float)
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html
02002c67bb7a-7
metadata jsonb, embedding vector(1536), similarity float) LANGUAGE plpgsql AS $$ # variable_conflict use_column BEGINRETURN query SELECT id, content, metadata, embedding, 1 -(docstore.embedding <=> query_embedding) AS similarity FROMdocstore ORDER BYdocstore.embedding <=> query_embedding LIMIT match_count; END; $$; ``` max_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **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. Parameters embedding – Embedding to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. 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, Any]] = 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, Any]] = None, **kwargs: Any) → List[Document][source]¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html
02002c67bb7a-8
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_by_vector_returning_embeddings(query: List[float], k: int, filter: Optional[Dict[str, Any]] = None) → List[Tuple[Document, float, ndarray[float32, Any]]][source]¶ similarity_search_by_vector_with_relevance_scores(query: List[float], k: int, filter: Optional[Dict[str, Any]] = None) → List[Tuple[Document, float]][source]¶ similarity_search_with_relevance_scores(query: str, k: int = 4, filter: Optional[Dict[str, Any]] = None, **kwargs: Any) → List[Tuple[Document, float]][source]¶ 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(*args: Any, **kwargs: Any) → List[Tuple[Document, float]]¶ Run similarity search with distance. Examples using SupabaseVectorStore¶ Supabase (Postgres)
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html
9c2080f158ae-0
langchain.vectorstores.pgvector.PGVector¶ class langchain.vectorstores.pgvector.PGVector(connection_string: str, embedding_function: Embeddings, collection_name: str = 'langchain', collection_metadata: Optional[dict] = None, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, pre_delete_collection: bool = False, logger: Optional[Logger] = None, relevance_score_fn: Optional[Callable[[float], float]] = None)[source]¶ VectorStore implementation using Postgres and pgvector. To use, you should have the pgvector python package installed. Parameters connection_string – Postgres connection string. embedding_function – Any embedding function implementing langchain.embeddings.base.Embeddings interface. collection_name – The name of the collection to use. (default: langchain) NOTE: This is not the name of the table, but the name of the collection. The tables will be created when initializing the store (if not exists) So, make sure the user has the right permissions to create tables. distance_strategy – The distance strategy to use. (default: COSINE) pre_delete_collection – If True, will delete the collection if it exists. (default: False). Useful for testing. Example from langchain.vectorstores import PGVector from langchain.embeddings.openai import OpenAIEmbeddings CONNECTION_STRING = "postgresql+psycopg2://hwc@localhost:5432/test3" COLLECTION_NAME = "state_of_the_union_test" embeddings = OpenAIEmbeddings() vectorestore = PGVector.from_documents( embedding=embeddings, documents=docs, collection_name=COLLECTION_NAME, connection_string=CONNECTION_STRING, ) Attributes distance_strategy embeddings Access the query embedding object if available. Methods __init__(connection_string, embedding_function)
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html
9c2080f158ae-1
Methods __init__(connection_string, embedding_function) aadd_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. aadd_texts(texts[, metadatas]) Run more texts through the embeddings and add to the vectorstore. add_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. add_embeddings(texts, embeddings[, ...]) Add embeddings to the vectorstore. add_texts(texts[, metadatas, ids]) Run more texts through the embeddings and add to the vectorstore. afrom_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings. afrom_texts(texts, embedding[, metadatas]) Return VectorStore initialized from texts and embeddings. amax_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. amax_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. as_retriever(**kwargs) Return VectorStoreRetriever initialized from this VectorStore. asearch(query, search_type, **kwargs) Return docs most similar to query using specified search type. asimilarity_search(query[, k]) Return docs most similar to query. asimilarity_search_by_vector(embedding[, k]) Return docs most similar to embedding vector. asimilarity_search_with_relevance_scores(query) Return docs most similar to query. connect() connection_string_from_db_params(driver, ...) Return connection string from database parameters. create_collection() create_tables_if_not_exists() create_vector_extension() delete([ids]) Delete by vector ID or other criteria. delete_collection() drop_tables()
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html
9c2080f158ae-2
Delete by vector ID or other criteria. delete_collection() drop_tables() from_documents(documents, embedding[, ...]) Return VectorStore initialized from documents and embeddings. from_embeddings(text_embeddings, embedding) Construct PGVector wrapper from raw documents and pre- generated embeddings. from_existing_index(embedding[, ...]) Get intsance of an existing PGVector store.This method will return the instance of the store without inserting any new embeddings from_texts(texts, embedding[, metadatas, ...]) Return VectorStore initialized from texts and embeddings. get_collection(session) get_connection_string(kwargs) max_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. max_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. search(query, search_type, **kwargs) Return docs most similar to query using specified search type. similarity_search(query[, k, filter]) Run similarity search with PGVector with distance. 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]) Return docs most similar to query. similarity_search_with_score_by_vector(embedding) __init__(connection_string: str, embedding_function: Embeddings, collection_name: str = 'langchain', collection_metadata: Optional[dict] = None, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, pre_delete_collection: bool = False, logger: Optional[Logger] = None, relevance_score_fn: Optional[Callable[[float], float]] = None) → None[source]¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html
9c2080f158ae-3
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] add_embeddings(texts: Iterable[str], embeddings: List[List[float]], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) → List[str][source]¶ Add embeddings to the vectorstore. Parameters texts – Iterable of strings to add to the vectorstore. embeddings – List of list of embedding vectors. metadatas – List of metadatas associated with the texts. kwargs – vectorstore specific parameters add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) → List[str][source]¶ Run more texts through the embeddings and add to the vectorstore. Parameters texts – Iterable of strings to add to the vectorstore. metadatas – Optional list of metadatas associated with the texts. kwargs – vectorstore specific parameters Returns
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html
9c2080f158ae-4
kwargs – vectorstore specific parameters Returns List of ids from adding the texts into the vectorstore. 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”. 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;
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html
9c2080f158ae-5
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]¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html
9c2080f158ae-6
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 most similar to query. connect() → Connection[source]¶ classmethod connection_string_from_db_params(driver: str, host: str, port: int, database: str, user: str, password: str) → str[source]¶ Return connection string from database parameters. create_collection() → None[source]¶ create_tables_if_not_exists() → None[source]¶ create_vector_extension() → None[source]¶ delete(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] delete_collection() → None[source]¶ drop_tables() → None[source]¶ classmethod from_documents(documents: List[Document], embedding: Embeddings, collection_name: str = 'langchain', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) → PGVector[source]¶ Return VectorStore initialized from documents and embeddings. Postgres connection string is required “Either pass it as a parameter or set the PGVECTOR_CONNECTION_STRING environment variable.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html
9c2080f158ae-7
“Either pass it as a parameter or set the PGVECTOR_CONNECTION_STRING environment variable. classmethod from_embeddings(text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) → PGVector[source]¶ Construct PGVector wrapper from raw documents and pre- generated embeddings. Return VectorStore initialized from documents and embeddings. Postgres connection string is required “Either pass it as a parameter or set the PGVECTOR_CONNECTION_STRING environment variable. Example from langchain import PGVector from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() text_embeddings = embeddings.embed_documents(texts) text_embedding_pairs = list(zip(texts, text_embeddings)) faiss = PGVector.from_embeddings(text_embedding_pairs, embeddings) classmethod from_existing_index(embedding: Embeddings, collection_name: str = 'langchain', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, pre_delete_collection: bool = False, **kwargs: Any) → PGVector[source]¶ Get intsance of an existing PGVector store.This method will return the instance of the store without inserting any new embeddings classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) → PGVector[source]¶ Return VectorStore initialized from texts and embeddings. Postgres connection string is required “Either pass it as a parameter
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html
9c2080f158ae-8
Postgres connection string is required “Either pass it as a parameter or set the PGVECTOR_CONNECTION_STRING environment variable. get_collection(session: Session) → Optional['CollectionStore'][source]¶ classmethod get_connection_string(kwargs: Dict[str, Any]) → str[source]¶ max_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. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters query – Text to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. 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, **kwargs: Any) → List[Document]¶ Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters embedding – Embedding to look up documents similar to. 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 and 1 to minimum diversity.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html
9c2080f158ae-9
to maximum diversity and 1 to minimum diversity. Defaults to 0.5. 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] = None, **kwargs: Any) → List[Document][source]¶ Run similarity search with PGVector with distance. Parameters query (str) – Query text to search for. 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. similarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[dict] = 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. filter (Optional[Dict[str, str]]) – Filter by metadata. Defaults to None. 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
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html
9c2080f158ae-10
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] = None) → List[Tuple[Document, float]][source]¶ Return docs most similar to query. Parameters 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. Returns List of Documents most similar to the query and score for each similarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[dict] = None) → List[Tuple[Document, float]][source]¶ Examples using PGVector¶ PGVector
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html
90168ec9fdb9-0
langchain.vectorstores.base.VectorStore¶ class langchain.vectorstores.base.VectorStore[source]¶ Interface for vector stores. Attributes embeddings Access the query embedding object if available. Methods __init__() aadd_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. aadd_texts(texts[, metadatas]) Run more texts through the embeddings and add to the vectorstore. add_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. add_texts(texts[, metadatas]) Run more texts through the embeddings and add to the vectorstore. afrom_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings. afrom_texts(texts, embedding[, metadatas]) Return VectorStore initialized from texts and embeddings. amax_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. amax_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. as_retriever(**kwargs) Return VectorStoreRetriever initialized from this VectorStore. asearch(query, search_type, **kwargs) Return docs most similar to query using specified search type. asimilarity_search(query[, k]) Return docs most similar to query. asimilarity_search_by_vector(embedding[, k]) Return docs most similar to embedding vector. asimilarity_search_with_relevance_scores(query) Return docs most similar to query. delete([ids]) Delete by vector ID or other criteria. from_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings. from_texts(texts, embedding[, metadatas])
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.base.VectorStore.html
90168ec9fdb9-1
from_texts(texts, embedding[, metadatas]) Return VectorStore initialized from texts and embeddings. max_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. max_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. search(query, search_type, **kwargs) Return docs most similar to query using specified search type. similarity_search(query[, k]) 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(*args, **kwargs) Run similarity search with distance. __init__()¶ async aadd_documents(documents: List[Document], **kwargs: Any) → List[str][source]¶ 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][source]¶ Run more texts through the embeddings and add to the vectorstore. add_documents(documents: List[Document], **kwargs: Any) → List[str][source]¶ 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]
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.base.VectorStore.html
90168ec9fdb9-2
Returns List of IDs of the added texts. Return type List[str] abstract add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) → List[str][source]¶ Run more texts through the embeddings and add to the vectorstore. Parameters texts – Iterable of strings to add to the vectorstore. metadatas – Optional list of metadatas associated with the texts. kwargs – vectorstore specific parameters Returns List of ids from adding the texts into the vectorstore. async classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) → VST[source]¶ Return VectorStore initialized from documents and embeddings. async classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) → VST[source]¶ 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][source]¶ 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][source]¶ Return docs selected using the maximal marginal relevance. as_retriever(**kwargs: Any) → VectorStoreRetriever[source]¶ Return VectorStoreRetriever initialized from this VectorStore. Parameters search_type (Optional[str]) – Defines the type of search that the Retriever should perform.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.base.VectorStore.html
90168ec9fdb9-3
the Retriever should perform. Can be “similarity” (default), “mmr”, or “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'}} )
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.base.VectorStore.html
90168ec9fdb9-4
search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}} ) async asearch(query: str, search_type: str, **kwargs: Any) → List[Document][source]¶ Return docs most similar to query using specified search type. async asimilarity_search(query: str, k: int = 4, **kwargs: Any) → List[Document][source]¶ Return docs most similar to query. async asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) → List[Document][source]¶ Return docs most similar to embedding vector. async asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) → List[Tuple[Document, float]][source]¶ Return docs most similar to query. delete(ids: Optional[List[str]] = None, **kwargs: Any) → Optional[bool][source]¶ 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] classmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) → VST[source]¶ Return VectorStore initialized from documents and embeddings. abstract classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) → VST[source]¶ Return VectorStore initialized from texts and embeddings.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.base.VectorStore.html
90168ec9fdb9-5
Return VectorStore initialized from texts and embeddings. max_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **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. Parameters query – Text to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. 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, **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. Parameters embedding – Embedding to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. Returns List of Documents selected by maximal marginal relevance. search(query: str, search_type: str, **kwargs: Any) → List[Document][source]¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.base.VectorStore.html
90168ec9fdb9-6
Return docs most similar to query using specified search type. abstract similarity_search(query: str, k: int = 4, **kwargs: Any) → List[Document][source]¶ Return docs most similar to query. similarity_search_by_vector(embedding: List[float], k: int = 4, **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]][source]¶ 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(*args: Any, **kwargs: Any) → List[Tuple[Document, float]][source]¶ Run similarity search with distance. Examples using VectorStore¶ BabyAGI User Guide BabyAGI with Tools
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.base.VectorStore.html
87626ca35616-0
langchain.vectorstores.weaviate.Weaviate¶ class langchain.vectorstores.weaviate.Weaviate(client: ~typing.Any, index_name: str, text_key: str, embedding: ~typing.Optional[~langchain.embeddings.base.Embeddings] = None, attributes: ~typing.Optional[~typing.List[str]] = None, relevance_score_fn: ~typing.Optional[~typing.Callable[[float], float]] = <function _default_score_normalizer>, by_text: bool = True)[source]¶ Wrapper around Weaviate vector database. To use, you should have the weaviate-client python package installed. Example import weaviate from langchain.vectorstores import Weaviate client = weaviate.Client(url=os.environ["WEAVIATE_URL"], ...) weaviate = Weaviate(client, index_name, text_key) Initialize with Weaviate client. Attributes embeddings Access the query embedding object if available. Methods __init__(client, index_name, text_key[, ...]) Initialize with Weaviate client. aadd_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. aadd_texts(texts[, metadatas]) Run more texts through the embeddings and add to the vectorstore. add_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. add_texts(texts[, metadatas]) Upload texts with metadata (properties) to Weaviate. afrom_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings. afrom_texts(texts, embedding[, metadatas]) Return VectorStore initialized from texts and embeddings. amax_marginal_relevance_search(query[, k, ...])
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html
87626ca35616-1
amax_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. amax_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. as_retriever(**kwargs) Return VectorStoreRetriever initialized from this VectorStore. asearch(query, search_type, **kwargs) Return docs most similar to query using specified search type. asimilarity_search(query[, k]) Return docs most similar to query. asimilarity_search_by_vector(embedding[, k]) Return docs most similar to embedding vector. asimilarity_search_with_relevance_scores(query) Return docs most similar to query. delete([ids]) Delete by vector IDs. from_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings. from_texts(texts, embedding[, metadatas]) Construct Weaviate wrapper from raw documents. max_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. max_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. search(query, search_type, **kwargs) Return docs most similar to query using specified search type. similarity_search(query[, k]) Return docs most similar to query. similarity_search_by_text(query[, k]) Return docs most similar to query. similarity_search_by_vector(embedding[, k]) Look up similar documents by embedding vector in Weaviate. similarity_search_with_relevance_scores(query) Return docs and relevance scores in the range [0, 1]. similarity_search_with_score(query[, k]) Return list of documents most similar to the query text and cosine distance in float for each.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html
87626ca35616-2
Return list of documents most similar to the query text and cosine distance in float for each. __init__(client: ~typing.Any, index_name: str, text_key: str, embedding: ~typing.Optional[~langchain.embeddings.base.Embeddings] = None, attributes: ~typing.Optional[~typing.List[str]] = None, relevance_score_fn: ~typing.Optional[~typing.Callable[[float], float]] = <function _default_score_normalizer>, by_text: bool = True)[source]¶ Initialize with Weaviate client. 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] add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) → List[str][source]¶ Upload texts with metadata (properties) to Weaviate. async classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) → VST¶ Return VectorStore initialized from documents and embeddings.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html
87626ca35616-3
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”. 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
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html
87626ca35616-4
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 most similar to query.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html
87626ca35616-5
Return docs most similar to query. delete(ids: Optional[List[str]] = None, **kwargs: Any) → None[source]¶ Delete by vector IDs. Parameters ids – List of ids to delete. classmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) → VST¶ Return VectorStore initialized from documents and embeddings. classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) → Weaviate[source]¶ Construct Weaviate wrapper from raw documents. This is a user-friendly interface that: Embeds documents. Creates a new index for the embeddings in the Weaviate instance. Adds the documents to the newly created Weaviate index. This is intended to be a quick way to get started. Example from langchain.vectorstores.weaviate import Weaviate from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() weaviate = Weaviate.from_texts( texts, embeddings, weaviate_url="http://localhost:8080" ) max_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **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. Parameters query – Text to look up documents similar to. 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
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html
87626ca35616-6
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 marginal relevance. max_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **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. Parameters embedding – Embedding to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. 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, **kwargs: Any) → List[Document][source]¶ Return docs most similar to query. Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 4. Returns List of Documents most similar to the query. similarity_search_by_text(query: str, k: int = 4, **kwargs: Any) → List[Document][source]¶ Return docs most similar to query. Parameters query – Text to look up documents similar to.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html
87626ca35616-7
Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 4. Returns List of Documents most similar to the query. similarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) → List[Document][source]¶ Look up similar documents by embedding vector in Weaviate. 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, **kwargs: Any) → List[Tuple[Document, float]][source]¶ Return list of documents most similar to the query text and cosine distance in float for each. Lower score represents more similarity. Examples using Weaviate¶ Weaviate Weaviate self-querying
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html
7c6dcb71fc7b-0
langchain.vectorstores.starrocks.StarRocksSettings¶ class langchain.vectorstores.starrocks.StarRocksSettings[source]¶ Bases: BaseSettings StarRocks Client Configuration Attribute: StarRocks_host (str)An URL to connect to MyScale backend.Defaults to ‘localhost’. StarRocks_port (int) : URL port to connect with HTTP. Defaults to 8443. username (str) : Username to login. Defaults to None. password (str) : Password to login. Defaults to None. database (str) : Database name to find the table. Defaults to ‘default’. table (str) : Table name to operate on. Defaults to ‘vector_table’. column_map (Dict)Column type map to project column name onto langchainsemantics. Must have keys: text, id, vector, must be same size to number of columns. For example: .. code-block:: python {‘id’: ‘text_id’, ‘embedding’: ‘text_embedding’, ‘document’: ‘text_plain’, ‘metadata’: ‘metadata_dictionary_in_json’, } Defaults to identity map. 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 column_map: Dict[str, str] = {'document': 'document', 'embedding': 'embedding', 'id': 'id', 'metadata': 'metadata'}¶ param database: str = 'default'¶ param host: str = 'localhost'¶ param password: str = ''¶ param port: int = 9030¶ param table: str = 'langchain'¶ param username: str = 'root'¶ classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocksSettings.html
7c6dcb71fc7b-1
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 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¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocksSettings.html
7c6dcb71fc7b-2
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_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¶ Examples using StarRocksSettings¶ StarRocks
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocksSettings.html
4d44f0ba2227-0
langchain.vectorstores.starrocks.StarRocks¶ class langchain.vectorstores.starrocks.StarRocks(embedding: Embeddings, config: Optional[StarRocksSettings] = None, **kwargs: Any)[source]¶ Wrapper around StarRocks vector database You need a pymysql python package, and a valid account to connect to StarRocks. Right now StarRocks has only implemented cosine_similarity function to compute distance between two vectors. And there is no vector inside right now, so we have to iterate all vectors and compute spatial distance. For more information, please visit[StarRocks official site](https://www.starrocks.io/) [StarRocks github](https://github.com/StarRocks/starrocks) StarRocks Wrapper to LangChain embedding_function (Embeddings): config (StarRocksSettings): Configuration to StarRocks Client Attributes embeddings Access the query embedding object if available. metadata_column Methods __init__(embedding[, config]) StarRocks Wrapper to LangChain aadd_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. aadd_texts(texts[, metadatas]) Run more texts through the embeddings and add to the vectorstore. add_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. add_texts(texts[, metadatas, batch_size, ids]) Insert more texts through the embeddings and add to the VectorStore. afrom_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings. afrom_texts(texts, embedding[, metadatas]) Return VectorStore initialized from texts and embeddings. amax_marginal_relevance_search(query[, k, ...])
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html
4d44f0ba2227-1
amax_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. amax_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. as_retriever(**kwargs) Return VectorStoreRetriever initialized from this VectorStore. asearch(query, search_type, **kwargs) Return docs most similar to query using specified search type. asimilarity_search(query[, k]) Return docs most similar to query. asimilarity_search_by_vector(embedding[, k]) Return docs most similar to embedding vector. asimilarity_search_with_relevance_scores(query) Return docs most similar to query. delete([ids]) Delete by vector ID or other criteria. drop() Helper function: Drop data escape_str(value) from_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings. from_texts(texts, embedding[, metadatas, ...]) Create StarRocks wrapper with existing texts max_marginal_relevance_search(query[, k, ...]) Return docs selected using the maximal marginal relevance. max_marginal_relevance_search_by_vector(...) Return docs selected using the maximal marginal relevance. search(query, search_type, **kwargs) Return docs most similar to query using specified search type. similarity_search(query[, k, where_str]) Perform a similarity search with StarRocks similarity_search_by_vector(embedding[, k, ...]) Perform a similarity search with StarRocks by vectors similarity_search_with_relevance_scores(query) Perform a similarity search with StarRocks similarity_search_with_score(*args, **kwargs) Run similarity search with distance.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html
4d44f0ba2227-2
similarity_search_with_score(*args, **kwargs) Run similarity search with distance. __init__(embedding: Embeddings, config: Optional[StarRocksSettings] = None, **kwargs: Any) → None[source]¶ StarRocks Wrapper to LangChain embedding_function (Embeddings): config (StarRocksSettings): Configuration to StarRocks Client 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] add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, batch_size: int = 32, ids: Optional[Iterable[str]] = None, **kwargs: Any) → List[str][source]¶ Insert more texts through the embeddings and add to the VectorStore. Parameters 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 inserted Returns List of ids from adding the texts into the VectorStore.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html
4d44f0ba2227-3
Returns List of ids from adding the texts into the VectorStore. 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”. 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;
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html
4d44f0ba2227-4
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]¶
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html
4d44f0ba2227-5
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 most similar to query. delete(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] drop() → None[source]¶ Helper function: Drop data escape_str(value: str) → str[source]¶ classmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) → VST¶ Return VectorStore initialized from documents and embeddings. classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]] = None, config: Optional[StarRocksSettings] = None, text_ids: Optional[Iterable[str]] = None, batch_size: int = 32, **kwargs: Any) → StarRocks[source]¶ Create StarRocks wrapper with existing texts Parameters embedding_function (Embeddings) – Function to extract text embedding texts (Iterable[str]) – List or tuple of strings to be added config (StarRocksSettings, Optional) – StarRocks configuration text_ids (Optional[Iterable], optional) – IDs for the texts. Defaults to None. batch_size (int, optional) – Batchsize when transmitting data to StarRocks. Defaults to 32. metadata (List[dict], optional) – metadata to texts. Defaults to None. Returns StarRocks Index
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html
4d44f0ba2227-6
Returns StarRocks Index max_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. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters query – Text to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. 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, **kwargs: Any) → List[Document]¶ Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters embedding – Embedding to look up documents similar to. 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 and 1 to minimum diversity. Defaults to 0.5. 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.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html
4d44f0ba2227-7
Return docs most similar to query using specified search type. similarity_search(query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any) → List[Document][source]¶ Perform a similarity search with StarRocks Parameters 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 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 of Documents Return type List[Document] similarity_search_by_vector(embedding: List[float], k: int = 4, where_str: Optional[str] = None, **kwargs: Any) → List[Document][source]¶ Perform a similarity search with StarRocks by vectors Parameters 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 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 of (Document, similarity) Return type List[Document] similarity_search_with_relevance_scores(query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any) → List[Tuple[Document, float]][source]¶ Perform a similarity search with StarRocks Parameters
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html
4d44f0ba2227-8
Perform a similarity search with StarRocks Parameters 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 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 of documents Return type List[Document] similarity_search_with_score(*args: Any, **kwargs: Any) → List[Tuple[Document, float]]¶ Run similarity search with distance. Examples using StarRocks¶ StarRocks
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html
21f14b288daa-0
langchain.vectorstores.scann.ScaNN¶ class langchain.vectorstores.scann.ScaNN(embedding: Embeddings, index: Any, docstore: Docstore, index_to_docstore_id: Dict[int, str], relevance_score_fn: Optional[Callable[[float], float]] = None, normalize_L2: bool = False, distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE, scann_config: Optional[str] = None)[source]¶ Wrapper around ScaNN vector database. To use, you should have the scann python package installed. Example from langchain.embeddings import HuggingFaceEmbeddings from langchain.vectorstores import ScaNN db = ScaNN.from_texts( ['foo', 'bar', 'barz', 'qux'], HuggingFaceEmbeddings()) db.similarity_search('foo?', k=1) Initialize with necessary components. Attributes embeddings Access the query embedding object if available. Methods __init__(embedding, index, docstore, ...[, ...]) Initialize with necessary components. aadd_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. aadd_texts(texts[, metadatas]) Run more texts through the embeddings and add to the vectorstore. add_documents(documents, **kwargs) Run more documents through the embeddings and add to the vectorstore. add_embeddings(text_embeddings[, metadatas, ids]) Run more texts through the embeddings and add to the vectorstore. add_texts(texts[, metadatas, ids]) Run more texts through the embeddings and add to the vectorstore. afrom_documents(documents, embedding, **kwargs) Return VectorStore initialized from documents and embeddings.
https://api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.ScaNN.html