id
stringlengths
14
15
text
stringlengths
49
2.47k
source
stringlengths
61
166
a3995490ca87-2
4. Click "Reset password" 5. Follow the prompts to reset the password The format for Elastic Cloud URLs is https://username:password@cluster_id.region_id.gcp.cloud.es.io:9243. Example: .. code-block:: python from langchain import ElasticVectorSearch from langchain.embeddings import OpenAIEmbeddings embedding = OpenAIEmbeddings() elastic_host = "cluster_id.region_id.gcp.cloud.es.io" elasticsearch_url = f"https://username:password@{elastic_host}:9243" elastic_vector_search = ElasticVectorSearch( elasticsearch_url=elasticsearch_url, index_name="test_index", embedding=embedding ) Args: elasticsearch_url (str): The URL for the Elasticsearch instance. index_name (str): The name of the Elasticsearch index for the embeddings. embedding (Embeddings): An object that provides the ability to embed text. It should be an instance of a class that subclasses the Embeddings abstract base class, such as OpenAIEmbeddings() Raises: ValueError: If the elasticsearch python package is not installed. """ [docs] def __init__( self, elasticsearch_url: str, index_name: str, embedding: Embeddings, *, ssl_verify: Optional[Dict[str, Any]] = None, ): """Initialize with necessary components.""" try: import elasticsearch except ImportError: raise ImportError( "Could not import elasticsearch python package. " "Please install it with `pip install elasticsearch`." ) self.embedding = embedding self.index_name = index_name
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
a3995490ca87-3
) self.embedding = embedding self.index_name = index_name _ssl_verify = ssl_verify or {} try: self.client = elasticsearch.Elasticsearch(elasticsearch_url, **_ssl_verify) except ValueError as e: raise ValueError( f"Your elasticsearch client string is mis-formatted. Got error: {e} " ) @property def embeddings(self) -> Embeddings: return self.embedding [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, refresh_indices: bool = True, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ids: Optional list of unique IDs. refresh_indices: bool to refresh ElasticSearch indices Returns: List of ids from adding the texts into the vectorstore. """ try: from elasticsearch.exceptions import NotFoundError from elasticsearch.helpers import bulk except ImportError: raise ImportError( "Could not import elasticsearch python package. " "Please install it with `pip install elasticsearch`." ) requests = [] ids = ids or [str(uuid.uuid4()) for _ in texts] embeddings = self.embedding.embed_documents(list(texts)) dim = len(embeddings[0]) mapping = _default_text_mapping(dim) # check to see if the index already exists try:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
a3995490ca87-4
# check to see if the index already exists try: self.client.indices.get(index=self.index_name) except NotFoundError: # TODO would be nice to create index before embedding, # just to save expensive steps for last self.create_index(self.client, self.index_name, mapping) for i, text in enumerate(texts): metadata = metadatas[i] if metadatas else {} request = { "_op_type": "index", "_index": self.index_name, "vector": embeddings[i], "text": text, "metadata": metadata, "_id": ids[i], } requests.append(request) bulk(self.client, requests) if refresh_indices: self.client.indices.refresh(index=self.index_name) return ids [docs] def similarity_search( self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any ) -> List[Document]: """Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. Returns: List of Documents most similar to the query. """ docs_and_scores = self.similarity_search_with_score(query, k, filter=filter) documents = [d[0] for d in docs_and_scores] return documents [docs] def similarity_search_with_score( self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Args:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
a3995490ca87-5
"""Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. Returns: List of Documents most similar to the query. """ embedding = self.embedding.embed_query(query) script_query = _default_script_query(embedding, filter) response = self.client_search( self.client, self.index_name, script_query, size=k ) hits = [hit for hit in response["hits"]["hits"]] docs_and_scores = [ ( Document( page_content=hit["_source"]["text"], metadata=hit["_source"]["metadata"], ), hit["_score"], ) for hit in hits ] return docs_and_scores [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, index_name: Optional[str] = None, refresh_indices: bool = True, **kwargs: Any, ) -> ElasticVectorSearch: """Construct ElasticVectorSearch wrapper from raw documents. This is a user-friendly interface that: 1. Embeds documents. 2. Creates a new index for the embeddings in the Elasticsearch instance. 3. Adds the documents to the newly created Elasticsearch index. This is intended to be a quick way to get started. Example: .. code-block:: python from langchain import ElasticVectorSearch from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings()
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
a3995490ca87-6
embeddings = OpenAIEmbeddings() elastic_vector_search = ElasticVectorSearch.from_texts( texts, embeddings, elasticsearch_url="http://localhost:9200" ) """ elasticsearch_url = get_from_dict_or_env( kwargs, "elasticsearch_url", "ELASTICSEARCH_URL" ) if "elasticsearch_url" in kwargs: del kwargs["elasticsearch_url"] index_name = index_name or uuid.uuid4().hex vectorsearch = cls(elasticsearch_url, index_name, embedding, **kwargs) vectorsearch.add_texts( texts, metadatas=metadatas, ids=ids, refresh_indices=refresh_indices ) return vectorsearch [docs] def create_index(self, client: Any, index_name: str, mapping: Dict) -> None: version_num = client.info()["version"]["number"][0] version_num = int(version_num) if version_num >= 8: client.indices.create(index=index_name, mappings=mapping) else: client.indices.create(index=index_name, body={"mappings": mapping}) [docs] def client_search( self, client: Any, index_name: str, script_query: Dict, size: int ) -> Any: version_num = client.info()["version"]["number"][0] version_num = int(version_num) if version_num >= 8: response = client.search(index=index_name, query=script_query, size=size) else: response = client.search( index=index_name, body={"query": script_query, "size": size} ) return response
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
a3995490ca87-7
) return response [docs] def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None: """Delete by vector IDs. Args: ids: List of ids to delete. """ if ids is None: raise ValueError("No ids provided to delete.") # TODO: Check if this can be done in bulk for id in ids: self.client.delete(index=self.index_name, id=id) [docs]class ElasticKnnSearch(VectorStore, ABC): """ ElasticKnnSearch is a class for performing k-nearest neighbor (k-NN) searches on text data using Elasticsearch. This class is used to create an Elasticsearch index of text data that can be searched using k-NN search. The text data is transformed into vector embeddings using a provided embedding model, and these embeddings are stored in the Elasticsearch index. Attributes: index_name (str): The name of the Elasticsearch index. embedding (Embeddings): The embedding model to use for transforming text data into vector embeddings. es_connection (Elasticsearch, optional): An existing Elasticsearch connection. es_cloud_id (str, optional): The Cloud ID of your Elasticsearch Service deployment. es_user (str, optional): The username for your Elasticsearch Service deployment. es_password (str, optional): The password for your Elasticsearch Service deployment. vector_query_field (str, optional): The name of the field in the Elasticsearch index that contains the vector embeddings. query_field (str, optional): The name of the field in the Elasticsearch index that contains the original text data. Usage: >>> from embeddings import Embeddings >>> embedding = Embeddings.load('glove')
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
a3995490ca87-8
>>> from embeddings import Embeddings >>> embedding = Embeddings.load('glove') >>> es_search = ElasticKnnSearch('my_index', embedding) >>> es_search.add_texts(['Hello world!', 'Another text']) >>> results = es_search.knn_search('Hello') [(Document(page_content='Hello world!', metadata={}), 0.9)] """ [docs] def __init__( self, index_name: str, embedding: Embeddings, es_connection: Optional["Elasticsearch"] = None, es_cloud_id: Optional[str] = None, es_user: Optional[str] = None, es_password: Optional[str] = None, vector_query_field: Optional[str] = "vector", query_field: Optional[str] = "text", ): try: import elasticsearch except ImportError: raise ImportError( "Could not import elasticsearch python package. " "Please install it with `pip install elasticsearch`." ) self.embedding = embedding self.index_name = index_name self.query_field = query_field self.vector_query_field = vector_query_field # If a pre-existing Elasticsearch connection is provided, use it. if es_connection is not None: self.client = es_connection else: # If credentials for a new Elasticsearch connection are provided, # create a new connection. if es_cloud_id and es_user and es_password: self.client = elasticsearch.Elasticsearch( cloud_id=es_cloud_id, basic_auth=(es_user, es_password) ) else: raise ValueError( """Either provide a pre-existing Elasticsearch connection, \
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
a3995490ca87-9
raise ValueError( """Either provide a pre-existing Elasticsearch connection, \ or valid credentials for creating a new connection.""" ) @staticmethod def _default_knn_mapping( dims: int, similarity: Optional[str] = "dot_product" ) -> Dict: return { "properties": { "text": {"type": "text"}, "vector": { "type": "dense_vector", "dims": dims, "index": True, "similarity": similarity, }, } } def _default_knn_query( self, query_vector: Optional[List[float]] = None, query: Optional[str] = None, model_id: Optional[str] = None, k: Optional[int] = 10, num_candidates: Optional[int] = 10, ) -> Dict: knn: Dict = { "field": self.vector_query_field, "k": k, "num_candidates": num_candidates, } # Case 1: `query_vector` is provided, but not `model_id` -> use query_vector if query_vector and not model_id: knn["query_vector"] = query_vector # Case 2: `query` and `model_id` are provided, -> use query_vector_builder elif query and model_id: knn["query_vector_builder"] = { "text_embedding": { "model_id": model_id, # use 'model_id' argument "model_text": query, # use 'query' argument } } else: raise ValueError(
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
a3995490ca87-10
} } else: raise ValueError( "Either `query_vector` or `model_id` must be provided, but not both." ) return knn [docs] def similarity_search( self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any ) -> List[Document]: """ Pass through to `knn_search` """ results = self.knn_search(query=query, k=k, **kwargs) return [doc for doc, score in results] [docs] def similarity_search_with_score( self, query: str, k: int = 10, **kwargs: Any ) -> List[Tuple[Document, float]]: """Pass through to `knn_search including score`""" return self.knn_search(query=query, k=k, **kwargs) [docs] def knn_search( self, query: Optional[str] = None, k: Optional[int] = 10, query_vector: Optional[List[float]] = None, model_id: Optional[str] = None, size: Optional[int] = 10, source: Optional[bool] = True, fields: Optional[ Union[List[Mapping[str, Any]], Tuple[Mapping[str, Any], ...], None] ] = None, page_content: Optional[str] = "text", ) -> List[Tuple[Document, float]]: """ Perform a k-NN search on the Elasticsearch index. Args: query (str, optional): The query text to search for. k (int, optional): The number of nearest neighbors to return.
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
a3995490ca87-11
k (int, optional): The number of nearest neighbors to return. query_vector (List[float], optional): The query vector to search for. model_id (str, optional): The ID of the model to use for transforming the query text into a vector. size (int, optional): The number of search results to return. source (bool, optional): Whether to return the source of the search results. fields (List[Mapping[str, Any]], optional): The fields to return in the search results. page_content (str, optional): The name of the field that contains the page content. Returns: A list of tuples, where each tuple contains a Document object and a score. """ # if not source and (fields == None or page_content not in fields): if not source and ( fields is None or not any(page_content in field for field in fields) ): raise ValueError("If source=False `page_content` field must be in `fields`") knn_query_body = self._default_knn_query( query_vector=query_vector, query=query, model_id=model_id, k=k ) # Perform the kNN search on the Elasticsearch index and return the results. response = self.client.search( index=self.index_name, knn=knn_query_body, size=size, source=source, fields=fields, ) hits = [hit for hit in response["hits"]["hits"]] docs_and_scores = [ ( Document( page_content=hit["_source"][page_content] if source else hit["fields"][page_content][0], metadata=hit["fields"] if fields else {}, ),
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
a3995490ca87-12
metadata=hit["fields"] if fields else {}, ), hit["_score"], ) for hit in hits ] return docs_and_scores [docs] def knn_hybrid_search( self, query: Optional[str] = None, k: Optional[int] = 10, query_vector: Optional[List[float]] = None, model_id: Optional[str] = None, size: Optional[int] = 10, source: Optional[bool] = True, knn_boost: Optional[float] = 0.9, query_boost: Optional[float] = 0.1, fields: Optional[ Union[List[Mapping[str, Any]], Tuple[Mapping[str, Any], ...], None] ] = None, page_content: Optional[str] = "text", ) -> List[Tuple[Document, float]]: """ Perform a hybrid k-NN and text search on the Elasticsearch index. Args: query (str, optional): The query text to search for. k (int, optional): The number of nearest neighbors to return. query_vector (List[float], optional): The query vector to search for. model_id (str, optional): The ID of the model to use for transforming the query text into a vector. size (int, optional): The number of search results to return. source (bool, optional): Whether to return the source of the search results. knn_boost (float, optional): The boost value to apply to the k-NN search results. query_boost (float, optional): The boost value to apply to the text search results.
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
a3995490ca87-13
results. fields (List[Mapping[str, Any]], optional): The fields to return in the search results. page_content (str, optional): The name of the field that contains the page content. Returns: A list of tuples, where each tuple contains a Document object and a score. """ # if not source and (fields == None or page_content not in fields): if not source and ( fields is None or not any(page_content in field for field in fields) ): raise ValueError("If source=False `page_content` field must be in `fields`") knn_query_body = self._default_knn_query( query_vector=query_vector, query=query, model_id=model_id, k=k ) # Modify the knn_query_body to add a "boost" parameter knn_query_body["boost"] = knn_boost # Generate the body of the standard Elasticsearch query match_query_body = { "match": {self.query_field: {"query": query, "boost": query_boost}} } # Perform the hybrid search on the Elasticsearch index and return the results. response = self.client.search( index=self.index_name, query=match_query_body, knn=knn_query_body, fields=fields, size=size, source=source, ) hits = [hit for hit in response["hits"]["hits"]] docs_and_scores = [ ( Document( page_content=hit["_source"][page_content] if source else hit["fields"][page_content][0], metadata=hit["fields"] if fields else {}, ), hit["_score"], ) for hit in hits
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
a3995490ca87-14
), hit["_score"], ) for hit in hits ] return docs_and_scores [docs] def create_knn_index(self, mapping: Dict) -> None: """ Create a new k-NN index in Elasticsearch. Args: mapping (Dict): The mapping to use for the new index. Returns: None """ self.client.indices.create(index=self.index_name, mappings=mapping) [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[Dict[Any, Any]]] = None, model_id: Optional[str] = None, refresh_indices: bool = False, **kwargs: Any, ) -> List[str]: """ Add a list of texts to the Elasticsearch index. Args: texts (Iterable[str]): The texts to add to the index. metadatas (List[Dict[Any, Any]], optional): A list of metadata dictionaries to associate with the texts. model_id (str, optional): The ID of the model to use for transforming the texts into vectors. refresh_indices (bool, optional): Whether to refresh the Elasticsearch indices after adding the texts. **kwargs: Arbitrary keyword arguments. Returns: A list of IDs for the added texts. """ # Check if the index exists. if not self.client.indices.exists(index=self.index_name): dims = kwargs.get("dims") if dims is None: raise ValueError("ElasticKnnSearch requires 'dims' parameter") similarity = kwargs.get("similarity") optional_args = {} if similarity is not None:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
a3995490ca87-15
optional_args = {} if similarity is not None: optional_args["similarity"] = similarity mapping = self._default_knn_mapping(dims=dims, **optional_args) self.create_knn_index(mapping) embeddings = self.embedding.embed_documents(list(texts)) # body = [] body: List[Mapping[str, Any]] = [] for text, vector in zip(texts, embeddings): body.extend( [ {"index": {"_index": self.index_name}}, {"text": text, "vector": vector}, ] ) responses = self.client.bulk(operations=body) ids = [ item["index"]["_id"] for item in responses["items"] if item["index"]["result"] == "created" ] if refresh_indices: self.client.indices.refresh(index=self.index_name) return ids [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]] = None, **kwargs: Any, ) -> ElasticKnnSearch: """ Create a new ElasticKnnSearch instance and add a list of texts to the Elasticsearch index. Args: texts (List[str]): The texts to add to the index. embedding (Embeddings): The embedding model to use for transforming the texts into vectors. metadatas (List[Dict[Any, Any]], optional): A list of metadata dictionaries to associate with the texts. **kwargs: Arbitrary keyword arguments. Returns: A new ElasticKnnSearch instance. """
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
a3995490ca87-16
Returns: A new ElasticKnnSearch instance. """ index_name = kwargs.get("index_name", str(uuid.uuid4())) es_connection = kwargs.get("es_connection") es_cloud_id = kwargs.get("es_cloud_id") es_user = kwargs.get("es_user") es_password = kwargs.get("es_password") vector_query_field = kwargs.get("vector_query_field", "vector") query_field = kwargs.get("query_field", "text") model_id = kwargs.get("model_id") dims = kwargs.get("dims") if dims is None: raise ValueError("ElasticKnnSearch requires 'dims' parameter") optional_args = {} if vector_query_field is not None: optional_args["vector_query_field"] = vector_query_field if query_field is not None: optional_args["query_field"] = query_field knnvectorsearch = cls( index_name=index_name, embedding=embedding, es_connection=es_connection, es_cloud_id=es_cloud_id, es_user=es_user, es_password=es_password, **optional_args, ) # Encode the provided texts and add them to the newly created index. knnvectorsearch.add_texts(texts, model_id=model_id, dims=dims, **optional_args) return knnvectorsearch
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
9f60b6d53214-0
Source code for langchain.vectorstores.redis """Wrapper around Redis vector database.""" from __future__ import annotations import json import logging import uuid from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Literal, Mapping, Optional, Tuple, Type, ) import numpy as np from pydantic import root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForRetrieverRun, CallbackManagerForRetrieverRun, ) from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from langchain.utilities.redis import get_client from langchain.utils import get_from_dict_or_env from langchain.vectorstores.base import VectorStore, VectorStoreRetriever logger = logging.getLogger(__name__) if TYPE_CHECKING: from redis.client import Redis as RedisType from redis.commands.search.query import Query # required modules REDIS_REQUIRED_MODULES = [ {"name": "search", "ver": 20400}, {"name": "searchlight", "ver": 20400}, ] # distance mmetrics REDIS_DISTANCE_METRICS = Literal["COSINE", "IP", "L2"] def _check_redis_module_exist(client: RedisType, required_modules: List[dict]) -> None: """Check if the correct Redis modules are installed.""" installed_modules = client.module_list() installed_modules = { module[b"name"].decode("utf-8"): module for module in installed_modules } for module in required_modules: if module["name"] in installed_modules and int( installed_modules[module["name"]][b"ver"] ) >= int(module["ver"]):
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
9f60b6d53214-1
) >= int(module["ver"]): return # otherwise raise error error_message = ( "Redis cannot be used as a vector database without RediSearch >=2.4" "Please head to https://redis.io/docs/stack/search/quick_start/" "to know more about installing the RediSearch module within Redis Stack." ) logger.error(error_message) raise ValueError(error_message) def _check_index_exists(client: RedisType, index_name: str) -> bool: """Check if Redis index exists.""" try: client.ft(index_name).info() except: # noqa: E722 logger.info("Index does not exist") return False logger.info("Index already exists") return True def _redis_key(prefix: str) -> str: """Redis key schema for a given prefix.""" return f"{prefix}:{uuid.uuid4().hex}" def _redis_prefix(index_name: str) -> str: """Redis key prefix for a given index.""" return f"doc:{index_name}" def _default_relevance_score(val: float) -> float: return 1 - val [docs]class Redis(VectorStore): """Wrapper around Redis vector database. To use, you should have the ``redis`` python package installed. Example: .. code-block:: python 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, )
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
9f60b6d53214-2
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: .. code-block:: python vectorstore = Redis( redis_url="redis+sentinel://username:password@sentinelhost:26379/mymaster/0" index_name="my-index", embedding_function=embeddings.embed_query, ) """ [docs] def __init__( self, 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: REDIS_DISTANCE_METRICS = "COSINE", **kwargs: Any, ): """Initialize with necessary components.""" self.embedding_function = embedding_function self.index_name = index_name try: redis_client = get_client(redis_url=redis_url, **kwargs) # check if redis has redisearch module installed _check_redis_module_exist(redis_client, REDIS_REQUIRED_MODULES) except ValueError as e:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
9f60b6d53214-3
except ValueError as e: raise ValueError(f"Redis failed to connect: {e}") self.client = redis_client self.content_key = content_key self.metadata_key = metadata_key self.vector_key = vector_key self.distance_metric = distance_metric self.relevance_score_fn = relevance_score_fn @property def embeddings(self) -> Optional[Embeddings]: # TODO: Accept embedding object directly return None def _select_relevance_score_fn(self) -> Callable[[float], float]: if self.relevance_score_fn: return self.relevance_score_fn if self.distance_metric == "COSINE": return self._cosine_relevance_score_fn elif self.distance_metric == "IP": return self._max_inner_product_relevance_score_fn elif self.distance_metric == "L2": return self._euclidean_relevance_score_fn else: return _default_relevance_score def _create_index(self, dim: int = 1536) -> None: try: from redis.commands.search.field import TextField, VectorField from redis.commands.search.indexDefinition import IndexDefinition, IndexType except ImportError: raise ValueError( "Could not import redis python package. " "Please install it with `pip install redis`." ) # Check if index exists if not _check_index_exists(self.client, self.index_name): # Define schema schema = ( TextField(name=self.content_key), TextField(name=self.metadata_key), VectorField( self.vector_key, "FLAT", { "TYPE": "FLOAT32", "DIM": dim, "DISTANCE_METRIC": self.distance_metric, },
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
9f60b6d53214-4
"DISTANCE_METRIC": self.distance_metric, }, ), ) prefix = _redis_prefix(self.index_name) # Create Redis Index self.client.ft(self.index_name).create_index( fields=schema, definition=IndexDefinition(prefix=[prefix], index_type=IndexType.HASH), ) [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, embeddings: Optional[List[List[float]]] = None, batch_size: int = 1000, **kwargs: Any, ) -> List[str]: """Add more texts to the vectorstore. Args: 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[str]: List of ids added to the vectorstore """ ids = [] prefix = _redis_prefix(self.index_name) # Get keys or ids from kwargs # Other vectorstores use ids keys_or_ids = kwargs.get("keys", kwargs.get("ids")) # Write data to redis pipeline = self.client.pipeline(transaction=False) for i, text in enumerate(texts): # Use provided values by default or fallback
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
9f60b6d53214-5
# Use provided values by default or fallback key = keys_or_ids[i] if keys_or_ids else _redis_key(prefix) metadata = metadatas[i] if metadatas else {} embedding = embeddings[i] if embeddings else self.embedding_function(text) pipeline.hset( key, mapping={ self.content_key: text, self.vector_key: np.array(embedding, dtype=np.float32).tobytes(), self.metadata_key: json.dumps(metadata), }, ) ids.append(key) # Write batch if i % batch_size == 0: pipeline.execute() # Cleanup final batch pipeline.execute() return ids [docs] def similarity_search( self, query: str, k: int = 4, **kwargs: Any ) -> List[Document]: """ Returns the most similar indexed documents to the query text. Args: query (str): The query text for which to find similar documents. k (int): The number of documents to return. Default is 4. Returns: List[Document]: A list of documents that are most similar to the query text. """ docs_and_scores = self.similarity_search_with_score(query, k=k) return [doc for doc, _ in docs_and_scores] [docs] def similarity_search_limit_score( self, query: str, k: int = 4, score_threshold: float = 0.2, **kwargs: Any ) -> List[Document]: """ Returns the most similar indexed documents to the query text within the score_threshold range. Args: query (str): The query text for which to find similar documents.
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
9f60b6d53214-6
Args: 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: List[Document]: A list of documents that are most similar to the query text, including the match score for each document. Note: If there are no documents that satisfy the score_threshold value, an empty list is returned. """ docs_and_scores = self.similarity_search_with_score(query, k=k) return [doc for doc, score in docs_and_scores if score < score_threshold] def _prepare_query(self, k: int) -> Query: try: from redis.commands.search.query import Query except ImportError: raise ValueError( "Could not import redis python package. " "Please install it with `pip install redis`." ) # Prepare the Query hybrid_fields = "*" base_query = ( f"{hybrid_fields}=>[KNN {k} @{self.vector_key} $vector AS vector_score]" ) return_fields = [self.metadata_key, self.content_key, "vector_score", "id"] return ( Query(base_query) .return_fields(*return_fields) .sort_by("vector_score") .paging(0, k) .dialect(2) ) [docs] def similarity_search_with_score( self, query: str, k: int = 4
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
9f60b6d53214-7
self, query: str, k: int = 4 ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. Returns: List of Documents most similar to the query and score for each """ # Creates embedding vector from user query embedding = self.embedding_function(query) # Creates Redis query redis_query = self._prepare_query(k) params_dict: Mapping[str, str] = { "vector": np.array(embedding) # type: ignore .astype(dtype=np.float32) .tobytes() } # Perform vector search results = self.client.ft(self.index_name).search(redis_query, params_dict) # Prepare document results docs_and_scores: List[Tuple[Document, float]] = [] for result in results.docs: metadata = {**json.loads(result.metadata), "id": result.id} doc = Document(page_content=result.content, metadata=metadata) docs_and_scores.append((doc, float(result.vector_score))) return docs_and_scores [docs] @classmethod def from_texts_return_keys( cls, 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: REDIS_DISTANCE_METRICS = "COSINE", **kwargs: Any, ) -> Tuple[Redis, List[str]]:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
9f60b6d53214-8
**kwargs: Any, ) -> Tuple[Redis, List[str]]: """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: .. code-block:: python 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" ) """ redis_url = get_from_dict_or_env(kwargs, "redis_url", "REDIS_URL") if "redis_url" in kwargs: kwargs.pop("redis_url") # Name of the search index if not given if not index_name: index_name = uuid.uuid4().hex # Create instance instance = cls( redis_url, index_name, embedding.embed_query, content_key=content_key, metadata_key=metadata_key, vector_key=vector_key, distance_metric=distance_metric, **kwargs, ) # Create embeddings over documents embeddings = embedding.embed_documents(texts) # Create the search index instance._create_index(dim=len(embeddings[0])) # Add data to Redis keys = instance.add_texts(texts, metadatas, embeddings) return instance, keys [docs] @classmethod
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
9f60b6d53214-9
return instance, keys [docs] @classmethod def from_texts( cls: Type[Redis], 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: """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: .. code-block:: python 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" ) """ instance, _ = cls.from_texts_return_keys( texts, embedding, metadatas=metadatas, index_name=index_name, content_key=content_key, metadata_key=metadata_key, vector_key=vector_key, **kwargs, ) return instance [docs] @staticmethod def delete( ids: Optional[List[str]] = None, **kwargs: Any, ) -> bool: """ Delete a Redis entry. Args:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
9f60b6d53214-10
) -> bool: """ Delete a Redis entry. Args: ids: List of ids (keys) to delete. Returns: bool: Whether or not the deletions were successful. """ redis_url = get_from_dict_or_env(kwargs, "redis_url", "REDIS_URL") if ids is None: raise ValueError("'ids' (keys)() were not provided.") try: import redis # noqa: F401 except ImportError: raise ValueError( "Could not import redis python package. " "Please install it with `pip install redis`." ) try: # We need to first remove redis_url from kwargs, # otherwise passing it to Redis will result in an error. if "redis_url" in kwargs: kwargs.pop("redis_url") client = get_client(redis_url=redis_url, **kwargs) except ValueError as e: raise ValueError(f"Your redis connected error: {e}") # Check if index exists try: client.delete(*ids) logger.info("Entries deleted") return True except: # noqa: E722 # ids does not exist return False [docs] @staticmethod def drop_index( index_name: str, delete_documents: bool, **kwargs: Any, ) -> bool: """ Drop a Redis search index. Args: index_name (str): Name of the index to drop. delete_documents (bool): Whether to drop the associated documents. Returns: bool: Whether or not the drop was successful. """
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
9f60b6d53214-11
Returns: bool: Whether or not the drop was successful. """ redis_url = get_from_dict_or_env(kwargs, "redis_url", "REDIS_URL") try: import redis # noqa: F401 except ImportError: raise ValueError( "Could not import redis python package. " "Please install it with `pip install redis`." ) try: # We need to first remove redis_url from kwargs, # otherwise passing it to Redis will result in an error. if "redis_url" in kwargs: kwargs.pop("redis_url") client = get_client(redis_url=redis_url, **kwargs) except ValueError as e: raise ValueError(f"Your redis connected error: {e}") # Check if index exists try: client.ft(index_name).dropindex(delete_documents) logger.info("Drop index") return True except: # noqa: E722 # Index not exist return False [docs] @classmethod def from_existing_index( cls, embedding: Embeddings, index_name: str, content_key: str = "content", metadata_key: str = "metadata", vector_key: str = "content_vector", **kwargs: Any, ) -> Redis: """Connect to an existing Redis index.""" redis_url = get_from_dict_or_env(kwargs, "redis_url", "REDIS_URL") try: import redis # noqa: F401 except ImportError: raise ValueError( "Could not import redis python package. " "Please install it with `pip install redis`." ) try:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
9f60b6d53214-12
"Please install it with `pip install redis`." ) try: # We need to first remove redis_url from kwargs, # otherwise passing it to Redis will result in an error. if "redis_url" in kwargs: kwargs.pop("redis_url") client = get_client(redis_url=redis_url, **kwargs) # check if redis has redisearch module installed _check_redis_module_exist(client, REDIS_REQUIRED_MODULES) # ensure that the index already exists assert _check_index_exists( client, index_name ), f"Index {index_name} does not exist" except Exception as e: raise ValueError(f"Redis failed to connect: {e}") return cls( redis_url, index_name, embedding.embed_query, content_key=content_key, metadata_key=metadata_key, vector_key=vector_key, **kwargs, ) [docs] def as_retriever(self, **kwargs: Any) -> RedisVectorStoreRetriever: tags = kwargs.pop("tags", None) or [] tags.extend(self._get_retriever_tags()) return RedisVectorStoreRetriever(vectorstore=self, **kwargs, tags=tags) [docs]class RedisVectorStoreRetriever(VectorStoreRetriever): """Retriever for Redis VectorStore.""" vectorstore: Redis """Redis VectorStore.""" search_type: str = "similarity" """Type of search to perform. Can be either 'similarity' or 'similarity_limit'.""" k: int = 4 """Number of documents to return.""" score_threshold: float = 0.4 """Score threshold for similarity_limit search."""
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
9f60b6d53214-13
"""Score threshold for similarity_limit search.""" class Config: """Configuration for this pydantic object.""" arbitrary_types_allowed = True @root_validator() def validate_search_type(cls, values: Dict) -> Dict: """Validate search type.""" if "search_type" in values: search_type = values["search_type"] if search_type not in ("similarity", "similarity_limit"): raise ValueError(f"search_type of {search_type} not allowed.") return values def _get_relevant_documents( self, query: str, *, run_manager: CallbackManagerForRetrieverRun ) -> List[Document]: if self.search_type == "similarity": docs = self.vectorstore.similarity_search(query, k=self.k) elif self.search_type == "similarity_limit": docs = self.vectorstore.similarity_search_limit_score( query, k=self.k, score_threshold=self.score_threshold ) else: raise ValueError(f"search_type of {self.search_type} not allowed.") return docs async def _aget_relevant_documents( self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun ) -> List[Document]: raise NotImplementedError("RedisVectorStoreRetriever does not support async") [docs] def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]: """Add documents to vectorstore.""" return self.vectorstore.add_documents(documents, **kwargs) [docs] async def aadd_documents( self, documents: List[Document], **kwargs: Any ) -> List[str]: """Add documents to vectorstore."""
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
9f60b6d53214-14
) -> List[str]: """Add documents to vectorstore.""" return await self.vectorstore.aadd_documents(documents, **kwargs)
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
7b8d04498303-0
Source code for langchain.vectorstores.singlestoredb """Wrapper around SingleStore DB.""" from __future__ import annotations import json from typing import ( Any, Callable, ClassVar, Collection, Iterable, List, Optional, Tuple, Type, ) from sqlalchemy.pool import QueuePool from langchain.callbacks.manager import ( AsyncCallbackManagerForRetrieverRun, CallbackManagerForRetrieverRun, ) from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from langchain.vectorstores.base import VectorStore, VectorStoreRetriever from langchain.vectorstores.utils import DistanceStrategy DEFAULT_DISTANCE_STRATEGY = DistanceStrategy.DOT_PRODUCT ORDERING_DIRECTIVE: dict = { DistanceStrategy.EUCLIDEAN_DISTANCE: "", DistanceStrategy.DOT_PRODUCT: "DESC", } [docs]class SingleStoreDB(VectorStore): """ This class serves as a Pythonic interface to the SingleStore DB database. The prerequisite for using this class is the installation of the ``singlestoredb`` Python package. The SingleStoreDB vectorstore can be created by providing an embedding function and the relevant parameters for the database connection, connection pool, and optionally, the names of the table and the fields to use. """ def _get_connection(self: SingleStoreDB) -> Any: try: import singlestoredb as s2 except ImportError: raise ImportError( "Could not import singlestoredb python package. " "Please install it with `pip install singlestoredb`." ) return s2.connect(**self.connection_kwargs) [docs] def __init__( self,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
7b8d04498303-1
[docs] def __init__( self, embedding: Embeddings, *, distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, table_name: str = "embeddings", content_field: str = "content", metadata_field: str = "metadata", vector_field: str = "vector", pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any, ): """Initialize with necessary components. Args: embedding (Embeddings): A text embedding model. distance_strategy (DistanceStrategy, optional): Determines the strategy employed for calculating the distance between vectors in the embedding space. Defaults to DOT_PRODUCT. Available options are: - DOT_PRODUCT: Computes the scalar product of two vectors. This is the default behavior - EUCLIDEAN_DISTANCE: Computes the Euclidean distance between two vectors. This metric considers the geometric distance in the vector space, and might be more suitable for embeddings that rely on spatial relationships. table_name (str, optional): Specifies the name of the table in use. Defaults to "embeddings". content_field (str, optional): Specifies the field to store the content. Defaults to "content". metadata_field (str, optional): Specifies the field to store metadata. Defaults to "metadata". vector_field (str, optional): Specifies the field to store the vector. Defaults to "vector". Following arguments pertain to the connection pool: pool_size (int, optional): Determines the number of active connections in the pool. Defaults to 5. max_overflow (int, optional): Determines the maximum number of connections
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
7b8d04498303-2
max_overflow (int, optional): Determines the maximum number of connections allowed beyond the pool_size. Defaults to 10. timeout (float, optional): Specifies the maximum wait time in seconds for establishing a connection. Defaults to 30. Following arguments pertain to the database connection: host (str, optional): Specifies the hostname, IP address, or URL for the database connection. The default scheme is "mysql". user (str, optional): Database username. password (str, optional): Database password. port (int, optional): Database port. Defaults to 3306 for non-HTTP connections, 80 for HTTP connections, and 443 for HTTPS connections. database (str, optional): Database name. Additional optional arguments provide further customization over the database connection: pure_python (bool, optional): Toggles the connector mode. If True, operates in pure Python mode. local_infile (bool, optional): Allows local file uploads. charset (str, optional): Specifies the character set for string values. ssl_key (str, optional): Specifies the path of the file containing the SSL key. ssl_cert (str, optional): Specifies the path of the file containing the SSL certificate. ssl_ca (str, optional): Specifies the path of the file containing the SSL certificate authority. ssl_cipher (str, optional): Sets the SSL cipher list. ssl_disabled (bool, optional): Disables SSL usage. ssl_verify_cert (bool, optional): Verifies the server's certificate. Automatically enabled if ``ssl_ca`` is specified. ssl_verify_identity (bool, optional): Verifies the server's identity. conv (dict[int, Callable], optional): A dictionary of data conversion
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
7b8d04498303-3
conv (dict[int, Callable], optional): A dictionary of data conversion functions. credential_type (str, optional): Specifies the type of authentication to use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO. autocommit (bool, optional): Enables autocommits. results_type (str, optional): Determines the structure of the query results: tuples, namedtuples, dicts. results_format (str, optional): Deprecated. This option has been renamed to results_type. Examples: Basic Usage: .. code-block:: python from langchain.embeddings import OpenAIEmbeddings from langchain.vectorstores import SingleStoreDB vectorstore = SingleStoreDB( OpenAIEmbeddings(), host="https://user:password@127.0.0.1:3306/database" ) Advanced Usage: .. code-block:: python from langchain.embeddings import OpenAIEmbeddings from langchain.vectorstores import SingleStoreDB vectorstore = SingleStoreDB( OpenAIEmbeddings(), distance_strategy=DistanceStrategy.EUCLIDEAN_DISTANCE, host="127.0.0.1", port=3306, user="user", password="password", database="db", table_name="my_custom_table", pool_size=10, timeout=60, ) Using environment variables: .. code-block:: python from langchain.embeddings import OpenAIEmbeddings from langchain.vectorstores import SingleStoreDB os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db' vectorstore = SingleStoreDB(OpenAIEmbeddings())
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
7b8d04498303-4
vectorstore = SingleStoreDB(OpenAIEmbeddings()) """ self.embedding = embedding self.distance_strategy = distance_strategy self.table_name = table_name self.content_field = content_field self.metadata_field = metadata_field self.vector_field = vector_field """Pass the rest of the kwargs to the connection.""" self.connection_kwargs = kwargs """Add program name and version to connection attributes.""" if "conn_attrs" not in self.connection_kwargs: self.connection_kwargs["conn_attrs"] = dict() self.connection_kwargs["conn_attrs"]["_connector_name"] = "langchain python sdk" self.connection_kwargs["conn_attrs"]["_connector_version"] = "1.0.0" """Create connection pool.""" self.connection_pool = QueuePool( self._get_connection, max_overflow=max_overflow, pool_size=pool_size, timeout=timeout, ) self._create_table() @property def embeddings(self) -> Embeddings: return self.embedding def _select_relevance_score_fn(self) -> Callable[[float], float]: return self._max_inner_product_relevance_score_fn def _create_table(self: SingleStoreDB) -> None: """Create table if it doesn't exist.""" conn = self.connection_pool.connect() try: cur = conn.cursor() try: cur.execute( """CREATE TABLE IF NOT EXISTS {} ({} TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci, {} BLOB, {} JSON);""".format( self.table_name, self.content_field, self.vector_field, self.metadata_field, ), ) finally: cur.close()
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
7b8d04498303-5
), ) finally: cur.close() finally: conn.close() [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, embeddings: Optional[List[List[float]]] = None, **kwargs: Any, ) -> List[str]: """Add more texts to the vectorstore. Args: 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. Returns: List[str]: empty list """ conn = self.connection_pool.connect() try: cur = conn.cursor() try: # Write data to singlestore db for i, text in enumerate(texts): # Use provided values by default or fallback metadata = metadatas[i] if metadatas else {} embedding = ( embeddings[i] if embeddings else self.embedding.embed_documents([text])[0] ) cur.execute( "INSERT INTO {} VALUES (%s, JSON_ARRAY_PACK(%s), %s)".format( self.table_name ), ( text, "[{}]".format(",".join(map(str, embedding))), json.dumps(metadata), ), ) finally: cur.close() finally: conn.close() return [] [docs] def similarity_search(
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
7b8d04498303-6
conn.close() return [] [docs] def similarity_search( self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any ) -> List[Document]: """Returns the most similar indexed documents to the query text. Uses cosine similarity. Args: query (str): The query text for which to find similar documents. k (int): The number of documents to return. Default is 4. filter (dict): A dictionary of metadata fields and values to filter by. Returns: List[Document]: A list of documents that are most similar to the query text. Examples: .. code-block:: python from langchain.vectorstores import SingleStoreDB from langchain.embeddings import OpenAIEmbeddings s2 = SingleStoreDB.from_documents( docs, OpenAIEmbeddings(), host="username:password@localhost:3306/database" ) s2.similarity_search("query text", 1, {"metadata_field": "metadata_value"}) """ docs_and_scores = self.similarity_search_with_score( query=query, k=k, filter=filter ) return [doc for doc, _ in docs_and_scores] [docs] def similarity_search_with_score( self, query: str, k: int = 4, filter: Optional[dict] = None ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Uses cosine similarity. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: A dictionary of metadata fields and values to filter by.
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
7b8d04498303-7
filter: A dictionary of metadata fields and values to filter by. Defaults to None. Returns: List of Documents most similar to the query and score for each """ # Creates embedding vector from user query embedding = self.embedding.embed_query(query) conn = self.connection_pool.connect() result = [] where_clause: str = "" where_clause_values: List[Any] = [] if filter: where_clause = "WHERE " arguments = [] def build_where_clause( where_clause_values: List[Any], sub_filter: dict, prefix_args: List[str] = [], ) -> None: for key in sub_filter.keys(): if isinstance(sub_filter[key], dict): build_where_clause( where_clause_values, sub_filter[key], prefix_args + [key] ) else: arguments.append( "JSON_EXTRACT_JSON({}, {}) = %s".format( self.metadata_field, ", ".join(["%s"] * (len(prefix_args) + 1)), ) ) where_clause_values += prefix_args + [key] where_clause_values.append(json.dumps(sub_filter[key])) build_where_clause(where_clause_values, filter) where_clause += " AND ".join(arguments) try: cur = conn.cursor() try: cur.execute( """SELECT {}, {}, {}({}, JSON_ARRAY_PACK(%s)) as __score FROM {} {} ORDER BY __score {} LIMIT %s""".format( self.content_field, self.metadata_field, self.distance_strategy, self.vector_field, self.table_name, where_clause, ORDERING_DIRECTIVE[self.distance_strategy], ),
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
7b8d04498303-8
where_clause, ORDERING_DIRECTIVE[self.distance_strategy], ), ("[{}]".format(",".join(map(str, embedding))),) + tuple(where_clause_values) + (k,), ) for row in cur.fetchall(): doc = Document(page_content=row[0], metadata=row[1]) result.append((doc, float(row[2]))) finally: cur.close() finally: conn.close() return result [docs] @classmethod def from_texts( cls: Type[SingleStoreDB], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, table_name: str = "embeddings", content_field: str = "content", metadata_field: str = "metadata", vector_field: str = "vector", pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any, ) -> SingleStoreDB: """Create a SingleStoreDB vectorstore from raw documents. This is a user-friendly interface that: 1. Embeds documents. 2. Creates a new table for the embeddings in SingleStoreDB. 3. Adds the documents to the newly created table. This is intended to be a quick way to get started. Example: .. code-block:: python from langchain.vectorstores import SingleStoreDB from langchain.embeddings import OpenAIEmbeddings s2 = SingleStoreDB.from_texts( texts, OpenAIEmbeddings(),
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
7b8d04498303-9
texts, OpenAIEmbeddings(), host="username:password@localhost:3306/database" ) """ instance = cls( embedding, distance_strategy=distance_strategy, table_name=table_name, content_field=content_field, metadata_field=metadata_field, vector_field=vector_field, pool_size=pool_size, max_overflow=max_overflow, timeout=timeout, **kwargs, ) instance.add_texts(texts, metadatas, embedding.embed_documents(texts), **kwargs) return instance [docs] def as_retriever(self, **kwargs: Any) -> SingleStoreDBRetriever: tags = kwargs.pop("tags", None) or [] tags.extend(self._get_retriever_tags()) return SingleStoreDBRetriever(vectorstore=self, **kwargs, tags=tags) [docs]class SingleStoreDBRetriever(VectorStoreRetriever): """Retriever for SingleStoreDB vector stores.""" vectorstore: SingleStoreDB k: int = 4 allowed_search_types: ClassVar[Collection[str]] = ("similarity",) def _get_relevant_documents( self, query: str, *, run_manager: CallbackManagerForRetrieverRun ) -> List[Document]: if self.search_type == "similarity": docs = self.vectorstore.similarity_search(query, k=self.k) else: raise ValueError(f"search_type of {self.search_type} not allowed.") return docs async def _aget_relevant_documents( self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun ) -> List[Document]: raise NotImplementedError(
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
7b8d04498303-10
) -> List[Document]: raise NotImplementedError( "SingleStoreDBVectorStoreRetriever does not support async" )
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
f84046fabc8a-0
Source code for langchain.vectorstores.azuresearch """Wrapper around Azure Cognitive Search.""" from __future__ import annotations import base64 import json import logging import uuid from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, ) import numpy as np from pydantic import root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForRetrieverRun, CallbackManagerForRetrieverRun, ) from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from langchain.schema import BaseRetriever from langchain.utils import get_from_env from langchain.vectorstores.base import VectorStore logger = logging.getLogger() if TYPE_CHECKING: from azure.search.documents import SearchClient from azure.search.documents.indexes.models import ( ScoringProfile, SearchField, SemanticSettings, VectorSearch, ) # Allow overriding field names for Azure Search FIELDS_ID = get_from_env( key="AZURESEARCH_FIELDS_ID", env_key="AZURESEARCH_FIELDS_ID", default="id" ) FIELDS_CONTENT = get_from_env( key="AZURESEARCH_FIELDS_CONTENT", env_key="AZURESEARCH_FIELDS_CONTENT", default="content", ) FIELDS_CONTENT_VECTOR = get_from_env( key="AZURESEARCH_FIELDS_CONTENT_VECTOR", env_key="AZURESEARCH_FIELDS_CONTENT_VECTOR", default="content_vector", ) FIELDS_METADATA = get_from_env( key="AZURESEARCH_FIELDS_TAG", env_key="AZURESEARCH_FIELDS_TAG", default="metadata" ) MAX_UPLOAD_BATCH_SIZE = 1000 def _get_search_client(
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
f84046fabc8a-1
) MAX_UPLOAD_BATCH_SIZE = 1000 def _get_search_client( endpoint: str, key: str, index_name: str, semantic_configuration_name: Optional[str] = None, fields: Optional[List[SearchField]] = None, vector_search: Optional[VectorSearch] = None, semantic_settings: Optional[SemanticSettings] = None, scoring_profiles: Optional[List[ScoringProfile]] = None, default_scoring_profile: Optional[str] = None, default_fields: Optional[List[SearchField]] = None, ) -> SearchClient: from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import ResourceNotFoundError from azure.identity import DefaultAzureCredential from azure.search.documents import SearchClient from azure.search.documents.indexes import SearchIndexClient from azure.search.documents.indexes.models import ( PrioritizedFields, SearchIndex, SemanticConfiguration, SemanticField, SemanticSettings, VectorSearch, VectorSearchAlgorithmConfiguration, ) default_fields = default_fields or [] if key is None: credential = DefaultAzureCredential() else: credential = AzureKeyCredential(key) index_client: SearchIndexClient = SearchIndexClient( endpoint=endpoint, credential=credential, user_agent="langchain" ) try: index_client.get_index(name=index_name) except ResourceNotFoundError: # Fields configuration if fields is not None: # Check mandatory fields fields_types = {f.name: f.type for f in fields} mandatory_fields = {df.name: df.type for df in default_fields} # Check for missing keys missing_fields = { key: mandatory_fields[key]
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
f84046fabc8a-2
missing_fields = { key: mandatory_fields[key] for key, value in set(mandatory_fields.items()) - set(fields_types.items()) } if len(missing_fields) > 0: fmt_err = lambda x: ( # noqa: E731 f"{x} current type: '{fields_types.get(x, 'MISSING')}'. It has to " f"be '{mandatory_fields.get(x)}' or you can point to a different " f"'{mandatory_fields.get(x)}' field name by using the env variable " f"'AZURESEARCH_FIELDS_{x.upper()}'" ) error = "\n".join([fmt_err(x) for x in missing_fields]) raise ValueError( f"You need to specify at least the following fields " f"{missing_fields} or provide alternative field names in the env " f"variables.\n\n{error}" ) else: fields = default_fields # Vector search configuration if vector_search is None: vector_search = VectorSearch( algorithm_configurations=[ VectorSearchAlgorithmConfiguration( name="default", kind="hnsw", hnsw_parameters={ # type: ignore "m": 4, "efConstruction": 400, "efSearch": 500, "metric": "cosine", }, ) ] ) # Create the semantic settings with the configuration if semantic_settings is None and semantic_configuration_name is not None: semantic_settings = SemanticSettings( configurations=[ SemanticConfiguration( name=semantic_configuration_name, prioritized_fields=PrioritizedFields( prioritized_content_fields=[
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
f84046fabc8a-3
prioritized_fields=PrioritizedFields( prioritized_content_fields=[ SemanticField(field_name=FIELDS_CONTENT) ], ), ) ] ) # Create the search index with the semantic settings and vector search index = SearchIndex( name=index_name, fields=fields, vector_search=vector_search, semantic_settings=semantic_settings, scoring_profiles=scoring_profiles, default_scoring_profile=default_scoring_profile, ) index_client.create_index(index) # Create the search client return SearchClient( endpoint=endpoint, index_name=index_name, credential=credential, user_agent="langchain", ) [docs]class AzureSearch(VectorStore): """Azure Cognitive Search vector store.""" [docs] def __init__( self, azure_search_endpoint: str, azure_search_key: str, index_name: str, embedding_function: Callable, search_type: str = "hybrid", semantic_configuration_name: Optional[str] = None, semantic_query_language: str = "en-us", fields: Optional[List[SearchField]] = None, vector_search: Optional[VectorSearch] = None, semantic_settings: Optional[SemanticSettings] = None, scoring_profiles: Optional[List[ScoringProfile]] = None, default_scoring_profile: Optional[str] = None, **kwargs: Any, ): from azure.search.documents.indexes.models import ( SearchableField, SearchField, SearchFieldDataType, SimpleField, ) """Initialize with necessary components.""" # Initialize base class self.embedding_function = embedding_function
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
f84046fabc8a-4
# Initialize base class self.embedding_function = embedding_function default_fields = [ SimpleField( name=FIELDS_ID, type=SearchFieldDataType.String, key=True, filterable=True, ), SearchableField( name=FIELDS_CONTENT, type=SearchFieldDataType.String, ), SearchField( name=FIELDS_CONTENT_VECTOR, type=SearchFieldDataType.Collection(SearchFieldDataType.Single), searchable=True, vector_search_dimensions=len(embedding_function("Text")), vector_search_configuration="default", ), SearchableField( name=FIELDS_METADATA, type=SearchFieldDataType.String, ), ] self.client = _get_search_client( azure_search_endpoint, azure_search_key, index_name, semantic_configuration_name=semantic_configuration_name, fields=fields, vector_search=vector_search, semantic_settings=semantic_settings, scoring_profiles=scoring_profiles, default_scoring_profile=default_scoring_profile, default_fields=default_fields, ) self.search_type = search_type self.semantic_configuration_name = semantic_configuration_name self.semantic_query_language = semantic_query_language self.fields = fields if fields else default_fields @property def embeddings(self) -> Optional[Embeddings]: # TODO: Support embedding object directly return None [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> List[str]: """Add texts data to an existing index.""" keys = kwargs.get("keys") ids = [] # Write data to index
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
f84046fabc8a-5
ids = [] # Write data to index data = [] for i, text in enumerate(texts): # Use provided key otherwise use default key key = keys[i] if keys else str(uuid.uuid4()) # Encoding key for Azure Search valid characters key = base64.urlsafe_b64encode(bytes(key, "utf-8")).decode("ascii") metadata = metadatas[i] if metadatas else {} # Add data to index # Additional metadata to fields mapping doc = { "@search.action": "upload", FIELDS_ID: key, FIELDS_CONTENT: text, FIELDS_CONTENT_VECTOR: np.array( self.embedding_function(text), dtype=np.float32 ).tolist(), FIELDS_METADATA: json.dumps(metadata), } if metadata: additional_fields = { k: v for k, v in metadata.items() if k in [x.name for x in self.fields] } doc.update(additional_fields) data.append(doc) ids.append(key) # Upload data in batches if len(data) == MAX_UPLOAD_BATCH_SIZE: response = self.client.upload_documents(documents=data) # Check if all documents were successfully uploaded if not all([r.succeeded for r in response]): raise Exception(response) # Reset data data = [] # Considering case where data is an exact multiple of batch-size entries if len(data) == 0: return ids # Upload data to index response = self.client.upload_documents(documents=data) # Check if all documents were successfully uploaded if all([r.succeeded for r in response]): return ids else:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
f84046fabc8a-6
return ids else: raise Exception(response) [docs] def similarity_search( self, query: str, k: int = 4, **kwargs: Any ) -> List[Document]: search_type = kwargs.get("search_type", self.search_type) if search_type == "similarity": docs = self.vector_search(query, k=k, **kwargs) elif search_type == "hybrid": docs = self.hybrid_search(query, k=k, **kwargs) elif search_type == "semantic_hybrid": docs = self.semantic_hybrid_search(query, k=k, **kwargs) else: raise ValueError(f"search_type of {search_type} not allowed.") return docs [docs] def vector_search(self, query: str, k: int = 4, **kwargs: Any) -> List[Document]: """ Returns the most similar indexed documents to the query text. Args: query (str): The query text for which to find similar documents. k (int): The number of documents to return. Default is 4. Returns: List[Document]: A list of documents that are most similar to the query text. """ docs_and_scores = self.vector_search_with_score( query, k=k, filters=kwargs.get("filters", None) ) return [doc for doc, _ in docs_and_scores] [docs] def vector_search_with_score( self, query: str, k: int = 4, filters: Optional[str] = None ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Args: query: Text to look up documents similar to.
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
f84046fabc8a-7
Args: 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 """ results = self.client.search( search_text="", vector=np.array(self.embedding_function(query), dtype=np.float32).tolist(), top_k=k, vector_fields=FIELDS_CONTENT_VECTOR, select=[FIELDS_ID, FIELDS_CONTENT, FIELDS_METADATA], filter=filters, ) # Convert results to Document objects docs = [ ( Document( page_content=result[FIELDS_CONTENT], metadata=json.loads(result[FIELDS_METADATA]), ), float(result["@search.score"]), ) for result in results ] return docs [docs] def hybrid_search(self, query: str, k: int = 4, **kwargs: Any) -> List[Document]: """ Returns the most similar indexed documents to the query text. Args: query (str): The query text for which to find similar documents. k (int): The number of documents to return. Default is 4. Returns: List[Document]: A list of documents that are most similar to the query text. """ docs_and_scores = self.hybrid_search_with_score( query, k=k, filters=kwargs.get("filters", None) ) return [doc for doc, _ in docs_and_scores] [docs] def hybrid_search_with_score( self, query: str, k: int = 4, filters: Optional[str] = None ) -> List[Tuple[Document, float]]:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
f84046fabc8a-8
) -> List[Tuple[Document, float]]: """Return docs most similar to query with an hybrid query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. Returns: List of Documents most similar to the query and score for each """ results = self.client.search( search_text=query, vector=np.array(self.embedding_function(query), dtype=np.float32).tolist(), top_k=k, vector_fields=FIELDS_CONTENT_VECTOR, select=[FIELDS_ID, FIELDS_CONTENT, FIELDS_METADATA], filter=filters, top=k, ) # Convert results to Document objects docs = [ ( Document( page_content=result[FIELDS_CONTENT], metadata=json.loads(result[FIELDS_METADATA]), ), float(result["@search.score"]), ) for result in results ] return docs [docs] def semantic_hybrid_search( self, query: str, k: int = 4, **kwargs: Any ) -> List[Document]: """ Returns the most similar indexed documents to the query text. Args: query (str): The query text for which to find similar documents. k (int): The number of documents to return. Default is 4. Returns: List[Document]: A list of documents that are most similar to the query text. """ docs_and_scores = self.semantic_hybrid_search_with_score( query, k=k, filters=kwargs.get("filters", None) ) return [doc for doc, _ in docs_and_scores] [docs] def semantic_hybrid_search_with_score(
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
f84046fabc8a-9
[docs] def semantic_hybrid_search_with_score( self, query: str, k: int = 4, filters: Optional[str] = None ) -> List[Tuple[Document, float]]: """Return docs most similar to query with an hybrid query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. Returns: List of Documents most similar to the query and score for each """ results = self.client.search( search_text=query, vector=np.array(self.embedding_function(query), dtype=np.float32).tolist(), top_k=50, # Hardcoded value to maximize L2 retrieval vector_fields=FIELDS_CONTENT_VECTOR, select=[FIELDS_ID, FIELDS_CONTENT, FIELDS_METADATA], filter=filters, query_type="semantic", query_language=self.semantic_query_language, semantic_configuration_name=self.semantic_configuration_name, query_caption="extractive", query_answer="extractive", top=k, ) # Get Semantic Answers semantic_answers = results.get_answers() or [] semantic_answers_dict: Dict = {} for semantic_answer in semantic_answers: semantic_answers_dict[semantic_answer.key] = { "text": semantic_answer.text, "highlights": semantic_answer.highlights, } # Convert results to Document objects docs = [ ( Document( page_content=result["content"], metadata={ **json.loads(result["metadata"]), **{ "captions": { "text": result.get("@search.captions", [{}])[0].text,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
f84046fabc8a-10
"text": result.get("@search.captions", [{}])[0].text, "highlights": result.get("@search.captions", [{}])[ 0 ].highlights, } if result.get("@search.captions") else {}, "answers": semantic_answers_dict.get( json.loads(result["metadata"]).get("key"), "" ), }, }, ), float(result["@search.score"]), ) for result in results ] return docs [docs] @classmethod def from_texts( cls: Type[AzureSearch], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, azure_search_endpoint: str = "", azure_search_key: str = "", index_name: str = "langchain-index", **kwargs: Any, ) -> AzureSearch: # Creating a new Azure Search instance azure_search = cls( azure_search_endpoint, azure_search_key, index_name, embedding.embed_query, ) azure_search.add_texts(texts, metadatas, **kwargs) return azure_search [docs]class AzureSearchVectorStoreRetriever(BaseRetriever): """Retriever that uses Azure Search to find similar documents.""" vectorstore: AzureSearch """Azure Search instance used to find similar documents.""" search_type: str = "hybrid" """Type of search to perform. Options are "similarity", "hybrid", "semantic_hybrid".""" k: int = 4 """Number of documents to return.""" class Config:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
f84046fabc8a-11
"""Number of documents to return.""" class Config: """Configuration for this pydantic object.""" arbitrary_types_allowed = True @root_validator() def validate_search_type(cls, values: Dict) -> Dict: """Validate search type.""" if "search_type" in values: search_type = values["search_type"] if search_type not in ("similarity", "hybrid", "semantic_hybrid"): raise ValueError(f"search_type of {search_type} not allowed.") return values def _get_relevant_documents( self, query: str, *, run_manager: CallbackManagerForRetrieverRun, ) -> List[Document]: if self.search_type == "similarity": docs = self.vectorstore.vector_search(query, k=self.k) elif self.search_type == "hybrid": docs = self.vectorstore.hybrid_search(query, k=self.k) elif self.search_type == "semantic_hybrid": docs = self.vectorstore.semantic_hybrid_search(query, k=self.k) else: raise ValueError(f"search_type of {self.search_type} not allowed.") return docs async def _aget_relevant_documents( self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun, ) -> List[Document]: raise NotImplementedError( "AzureSearchVectorStoreRetriever does not support async" )
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
3e0354471797-0
Source code for langchain.vectorstores.marqo """Wrapper around weaviate vector database.""" from __future__ import annotations import json import uuid from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, Union, ) from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from langchain.vectorstores.base import VectorStore if TYPE_CHECKING: import marqo [docs]class Marqo(VectorStore): """Wrapper around Marqo database. Marqo indexes have their own models associated with them to generate your embeddings. This means that you can selected from a range of different models and also use CLIP models to create multimodal indexes with images and text together. Marqo also supports more advanced queries with multiple weighted terms, see See https://docs.marqo.ai/latest/#searching-using-weights-in-queries. This class can flexibly take strings or dictionaries for weighted queries in its similarity search methods. To use, you should have the `marqo` python package installed, you can do this with `pip install marqo`. Example: .. code-block:: python import marqo from langchain.vectorstores import Marqo client = marqo.Client(url=os.environ["MARQO_URL"], ...) vectorstore = Marqo(client, index_name) """ [docs] def __init__( self, client: marqo.Client, index_name: str, add_documents_settings: Optional[Dict[str, Any]] = None,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html
3e0354471797-1
add_documents_settings: Optional[Dict[str, Any]] = None, searchable_attributes: Optional[List[str]] = None, page_content_builder: Optional[Callable[[Dict[str, Any]], str]] = None, ): """Initialize with Marqo client.""" try: import marqo except ImportError: raise ValueError( "Could not import marqo python package. " "Please install it with `pip install marqo`." ) if not isinstance(client, marqo.Client): raise ValueError( f"client should be an instance of marqo.Client, got {type(client)}" ) self._client = client self._index_name = index_name self._add_documents_settings = ( {} if add_documents_settings is None else add_documents_settings ) self._searchable_attributes = searchable_attributes self.page_content_builder = page_content_builder self._non_tensor_fields = ["metadata"] self._document_batch_size = 1024 @property def embeddings(self) -> Optional[Embeddings]: return None [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> List[str]: """Upload texts with metadata (properties) to Marqo. You can either have marqo generate ids for each document or you can provide your own by including a "_id" field in the metadata objects. Args: texts (Iterable[str]): am iterator of texts - assumed to preserve an order that matches the metadatas.
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html
3e0354471797-2
order that matches the metadatas. metadatas (Optional[List[dict]], optional): a list of metadatas. Raises: ValueError: if metadatas is provided and the number of metadatas differs from the number of texts. Returns: List[str]: The list of ids that were added. """ if self._client.index(self._index_name).get_settings()["index_defaults"][ "treat_urls_and_pointers_as_images" ]: raise ValueError( "Marqo.add_texts is disabled for multimodal indexes. To add documents " "with a multimodal index use the Python client for Marqo directly." ) documents: List[Dict[str, str]] = [] num_docs = 0 for i, text in enumerate(texts): doc = { "text": text, "metadata": json.dumps(metadatas[i]) if metadatas else json.dumps({}), } documents.append(doc) num_docs += 1 ids = [] for i in range(0, num_docs, self._document_batch_size): response = self._client.index(self._index_name).add_documents( documents[i : i + self._document_batch_size], non_tensor_fields=self._non_tensor_fields, **self._add_documents_settings, ) if response["errors"]: err_msg = ( f"Error in upload for documents in index range [{i}," f"{i + self._document_batch_size}], " f"check Marqo logs." ) raise RuntimeError(err_msg) ids += [item["_id"] for item in response["items"]] return ids
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html
3e0354471797-3
ids += [item["_id"] for item in response["items"]] return ids [docs] def similarity_search( self, query: Union[str, Dict[str, float]], k: int = 4, **kwargs: Any, ) -> List[Document]: """Search the marqo index for the most similar documents. Args: query (Union[str, Dict[str, float]]): The query for the search, either as a string or a weighted query. k (int, optional): The number of documents to return. Defaults to 4. Returns: List[Document]: k documents ordered from best to worst match. """ results = self.marqo_similarity_search(query=query, k=k) documents = self._construct_documents_from_results_without_score(results) return documents [docs] def similarity_search_with_score( self, query: Union[str, Dict[str, float]], k: int = 4, ) -> List[Tuple[Document, float]]: """Return documents from Marqo that are similar to the query as well as their scores. Args: query (str): The query to search with, either as a string or a weighted query. k (int, optional): The number of documents to return. Defaults to 4. Returns: List[Tuple[Document, float]]: The matching documents and their scores, ordered by descending score. """ results = self.marqo_similarity_search(query=query, k=k) scored_documents = self._construct_documents_from_results_with_score(results) return scored_documents [docs] def bulk_similarity_search( self,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html
3e0354471797-4
return scored_documents [docs] def bulk_similarity_search( self, queries: Iterable[Union[str, Dict[str, float]]], k: int = 4, **kwargs: Any, ) -> List[List[Document]]: """Search the marqo index for the most similar documents in bulk with multiple queries. Args: queries (Iterable[Union[str, Dict[str, float]]]): An iterable of queries to execute in bulk, queries in the list can be strings or dictionaries of weighted queries. k (int, optional): The number of documents to return for each query. Defaults to 4. Returns: List[List[Document]]: A list of results for each query. """ bulk_results = self.marqo_bulk_similarity_search(queries=queries, k=k) bulk_documents: List[List[Document]] = [] for results in bulk_results["result"]: documents = self._construct_documents_from_results_without_score(results) bulk_documents.append(documents) return bulk_documents [docs] def bulk_similarity_search_with_score( self, queries: Iterable[Union[str, Dict[str, float]]], k: int = 4, **kwargs: Any, ) -> List[List[Tuple[Document, float]]]: """Return documents from Marqo that are similar to the query as well as their scores using a batch of queries. Args: query (Iterable[Union[str, Dict[str, float]]]): An iterable of queries to execute in bulk, queries in the list can be strings or dictionaries of weighted queries. k (int, optional): The number of documents to return. Defaults to 4.
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html
3e0354471797-5
k (int, optional): The number of documents to return. Defaults to 4. Returns: List[Tuple[Document, float]]: A list of lists of the matching documents and their scores for each query """ bulk_results = self.marqo_bulk_similarity_search(queries=queries, k=k) bulk_documents: List[List[Tuple[Document, float]]] = [] for results in bulk_results["result"]: documents = self._construct_documents_from_results_with_score(results) bulk_documents.append(documents) return bulk_documents def _construct_documents_from_results_with_score( self, results: Dict[str, List[Dict[str, str]]] ) -> List[Tuple[Document, Any]]: """Helper to convert Marqo results into documents. Args: results (List[dict]): A marqo results object with the 'hits'. include_scores (bool, optional): Include scores alongside documents. Defaults to False. Returns: Union[List[Document], List[Tuple[Document, float]]]: The documents or document score pairs if `include_scores` is true. """ documents: List[Tuple[Document, Any]] = [] for res in results["hits"]: if self.page_content_builder is None: text = res["text"] else: text = self.page_content_builder(res) metadata = json.loads(res.get("metadata", "{}")) documents.append( (Document(page_content=text, metadata=metadata), res["_score"]) ) return documents def _construct_documents_from_results_without_score( self, results: Dict[str, List[Dict[str, str]]] ) -> List[Document]:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html
3e0354471797-6
) -> List[Document]: """Helper to convert Marqo results into documents. Args: results (List[dict]): A marqo results object with the 'hits'. include_scores (bool, optional): Include scores alongside documents. Defaults to False. Returns: Union[List[Document], List[Tuple[Document, float]]]: The documents or document score pairs if `include_scores` is true. """ documents: List[Document] = [] for res in results["hits"]: if self.page_content_builder is None: text = res["text"] else: text = self.page_content_builder(res) metadata = json.loads(res.get("metadata", "{}")) documents.append(Document(page_content=text, metadata=metadata)) return documents [docs] def marqo_similarity_search( self, query: Union[str, Dict[str, float]], k: int = 4, ) -> Dict[str, List[Dict[str, str]]]: """Return documents from Marqo exposing Marqo's output directly Args: query (str): The query to search with. k (int, optional): The number of documents to return. Defaults to 4. Returns: List[Dict[str, Any]]: This hits from marqo. """ results = self._client.index(self._index_name).search( q=query, searchable_attributes=self._searchable_attributes, limit=k ) return results [docs] def marqo_bulk_similarity_search( self, queries: Iterable[Union[str, Dict[str, float]]], k: int = 4
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html
3e0354471797-7
) -> Dict[str, List[Dict[str, List[Dict[str, str]]]]]: """Return documents from Marqo using a bulk search, exposes Marqo's output directly Args: queries (Iterable[Union[str, Dict[str, float]]]): A list of queries. k (int, optional): The number of documents to return for each query. Defaults to 4. Returns: Dict[str, Dict[List[Dict[str, Dict[str, Any]]]]]: A bulk search results object """ bulk_results = self._client.bulk_search( [ { "index": self._index_name, "q": query, "searchableAttributes": self._searchable_attributes, "limit": k, } for query in queries ] ) return bulk_results [docs] @classmethod def from_documents( cls: Type[Marqo], documents: List[Document], embedding: Union[Embeddings, None] = None, **kwargs: Any, ) -> Marqo: """Return VectorStore initialized from documents. Note that Marqo does not need embeddings, we retain the parameter to adhere to the Liskov substitution principle. Args: documents (List[Document]): Input documents embedding (Any, optional): Embeddings (not required). Defaults to None. Returns: VectorStore: A Marqo vectorstore """ texts = [d.page_content for d in documents] metadatas = [d.metadata for d in documents] return cls.from_texts(texts, metadatas=metadatas, **kwargs)
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html
3e0354471797-8
return cls.from_texts(texts, metadatas=metadatas, **kwargs) [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Any = None, metadatas: Optional[List[dict]] = None, index_name: str = "", url: str = "http://localhost:8882", api_key: str = "", add_documents_settings: Optional[Dict[str, Any]] = {}, searchable_attributes: Optional[List[str]] = None, page_content_builder: Optional[Callable[[Dict[str, str]], str]] = None, index_settings: Optional[Dict[str, Any]] = {}, verbose: bool = True, **kwargs: Any, ) -> Marqo: """Return Marqo initialized from texts. Note that Marqo does not need embeddings, we retain the parameter to adhere to the Liskov substitution principle. This is a quick way to get started with marqo - simply provide your texts and metadatas and this will create an instance of the data store and index the provided data. To know the ids of your documents with this approach you will need to include them in under the key "_id" in your metadatas for each text Example: .. code-block:: python from langchain.vectorstores import Marqo datastore = Marqo(texts=['text'], index_name='my-first-index', url='http://localhost:8882') Args: texts (List[str]): A list of texts to index into marqo upon creation. embedding (Any, optional): Embeddings (not required). Defaults to None.
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html
3e0354471797-9
embedding (Any, optional): Embeddings (not required). Defaults to None. index_name (str, optional): The name of the index to use, if none is provided then one will be created with a UUID. Defaults to None. url (str, optional): The URL for Marqo. Defaults to "http://localhost:8882". api_key (str, optional): The API key for Marqo. Defaults to "". metadatas (Optional[List[dict]], optional): A list of metadatas, to accompany the texts. Defaults to None. this is only used when a new index is being created. Defaults to "cpu". Can be "cpu" or "cuda". add_documents_settings (Optional[Dict[str, Any]], optional): Settings for adding documents, see https://docs.marqo.ai/0.0.16/API-Reference/documents/#query-parameters. Defaults to {}. index_settings (Optional[Dict[str, Any]], optional): Index settings if the index doesn't exist, see https://docs.marqo.ai/0.0.16/API-Reference/indexes/#index-defaults-object. Defaults to {}. Returns: Marqo: An instance of the Marqo vector store """ try: import marqo except ImportError: raise ValueError( "Could not import marqo python package. " "Please install it with `pip install marqo`." ) if not index_name: index_name = str(uuid.uuid4()) client = marqo.Client(url=url, api_key=api_key) try: client.create_index(index_name, settings_dict=index_settings) if verbose:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html
3e0354471797-10
client.create_index(index_name, settings_dict=index_settings) if verbose: print(f"Created {index_name} successfully.") except Exception: if verbose: print(f"Index {index_name} exists.") instance: Marqo = cls( client, index_name, searchable_attributes=searchable_attributes, add_documents_settings=add_documents_settings, page_content_builder=page_content_builder, ) instance.add_texts(texts, metadatas) return instance [docs] def get_indexes(self) -> List[Dict[str, str]]: """Helper to see your available indexes in marqo, useful if the from_texts method was used without an index name specified Returns: List[Dict[str, str]]: The list of indexes """ return self._client.get_indexes()["results"] [docs] def get_number_of_documents(self) -> int: """Helper to see the number of documents in the index Returns: int: The number of documents """ return self._client.index(self._index_name).get_stats()["numberOfDocuments"]
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html
13ba630d8980-0
Source code for langchain.vectorstores.qdrant """Wrapper around Qdrant vector database.""" from __future__ import annotations import asyncio import functools import uuid import warnings from itertools import islice from operator import itemgetter from typing import ( TYPE_CHECKING, Any, Callable, Dict, Generator, Iterable, List, Optional, Sequence, Tuple, Type, Union, ) import numpy as np from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from langchain.vectorstores import VectorStore from langchain.vectorstores.utils import maximal_marginal_relevance if TYPE_CHECKING: from qdrant_client import grpc # noqa from qdrant_client.conversions import common_types from qdrant_client.http import models as rest DictFilter = Dict[str, Union[str, int, bool, dict, list]] MetadataFilter = Union[DictFilter, common_types.Filter] [docs]class QdrantException(Exception): """Base class for all the Qdrant related exceptions""" [docs]def sync_call_fallback(method: Callable) -> Callable: """ Decorator to call the synchronous method of the class if the async method is not implemented. This decorator might be only used for the methods that are defined as async in the class. """ @functools.wraps(method) async def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any: try: return await method(self, *args, **kwargs) except NotImplementedError: # If the async method is not implemented, call the synchronous method
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-1
except NotImplementedError: # If the async method is not implemented, call the synchronous method # by removing the first letter from the method name. For example, # if the async method is called ``aaad_texts``, the synchronous method # will be called ``aad_texts``. sync_method = functools.partial( getattr(self, method.__name__[1:]), *args, **kwargs ) return await asyncio.get_event_loop().run_in_executor(None, sync_method) return wrapper [docs]class Qdrant(VectorStore): """Wrapper around Qdrant vector database. To use you should have the ``qdrant-client`` package installed. Example: .. code-block:: python from qdrant_client import QdrantClient from langchain import Qdrant client = QdrantClient() collection_name = "MyCollection" qdrant = Qdrant(client, collection_name, embedding_function) """ CONTENT_KEY = "page_content" METADATA_KEY = "metadata" VECTOR_NAME = None [docs] def __init__( self, client: Any, collection_name: str, embeddings: Optional[Embeddings] = None, content_payload_key: str = CONTENT_KEY, metadata_payload_key: str = METADATA_KEY, distance_strategy: str = "COSINE", vector_name: Optional[str] = VECTOR_NAME, embedding_function: Optional[Callable] = None, # deprecated ): """Initialize with necessary components.""" try: import qdrant_client except ImportError: raise ValueError( "Could not import qdrant-client python package. "
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-2
raise ValueError( "Could not import qdrant-client python package. " "Please install it with `pip install qdrant-client`." ) if not isinstance(client, qdrant_client.QdrantClient): raise ValueError( f"client should be an instance of qdrant_client.QdrantClient, " f"got {type(client)}" ) if embeddings is None and embedding_function is None: raise ValueError( "`embeddings` value can't be None. Pass `Embeddings` instance." ) if embeddings is not None and embedding_function is not None: raise ValueError( "Both `embeddings` and `embedding_function` are passed. " "Use `embeddings` only." ) self._embeddings = embeddings self._embeddings_function = embedding_function self.client: qdrant_client.QdrantClient = client self.collection_name = collection_name self.content_payload_key = content_payload_key or self.CONTENT_KEY self.metadata_payload_key = metadata_payload_key or self.METADATA_KEY self.vector_name = vector_name or self.VECTOR_NAME if embedding_function is not None: warnings.warn( "Using `embedding_function` is deprecated. " "Pass `Embeddings` instance to `embeddings` instead." ) if not isinstance(embeddings, Embeddings): warnings.warn( "`embeddings` should be an instance of `Embeddings`." "Using `embeddings` as `embedding_function` which is deprecated" ) self._embeddings_function = embeddings self._embeddings = None self.distance_strategy = distance_strategy.upper() @property
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-3
self.distance_strategy = distance_strategy.upper() @property def embeddings(self) -> Optional[Embeddings]: return self._embeddings [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[Sequence[str]] = None, batch_size: int = 64, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ids: Optional list of ids to associate with the texts. Ids have to be uuid-like strings. batch_size: How many vectors upload per-request. Default: 64 Returns: List of ids from adding the texts into the vectorstore. """ added_ids = [] for batch_ids, points in self._generate_rest_batches( texts, metadatas, ids, batch_size ): self.client.upsert( collection_name=self.collection_name, points=points, **kwargs ) added_ids.extend(batch_ids) return added_ids [docs] @sync_call_fallback async def aadd_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[Sequence[str]] = None, batch_size: int = 64, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. Args:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-4
"""Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ids: Optional list of ids to associate with the texts. Ids have to be uuid-like strings. batch_size: How many vectors upload per-request. Default: 64 Returns: List of ids from adding the texts into the vectorstore. """ from qdrant_client import grpc # noqa from qdrant_client.conversions.conversion import RestToGrpc added_ids = [] for batch_ids, points in self._generate_rest_batches( texts, metadatas, ids, batch_size ): await self.client.async_grpc_points.Upsert( grpc.UpsertPoints( collection_name=self.collection_name, points=[RestToGrpc.convert_point_struct(point) for point in points], ) ) added_ids.extend(batch_ids) return added_ids [docs] def similarity_search( self, query: str, k: int = 4, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, offset: int = 0, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any, ) -> List[Document]: """Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4.
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-5
k: Number of Documents to return. Defaults to 4. filter: Filter by metadata. Defaults to None. search_params: Additional search params offset: Offset of the first result to return. May be used to paginate results. Note: large offset values may cause performance issues. score_threshold: Define a minimal score threshold for the result. If defined, less similar results will not be returned. Score of the returned result might be higher or smaller than the threshold depending on the Distance function used. E.g. for cosine similarity only higher scores will be returned. consistency: Read consistency of the search. Defines how many replicas should be queried before returning the result. Values: - int - number of replicas to query, values should present in all queried replicas - 'majority' - query all replicas, but return values present in the majority of replicas - 'quorum' - query the majority of replicas, return values present in all of them - 'all' - query all replicas, and return values present in all replicas Returns: List of Documents most similar to the query. """ results = self.similarity_search_with_score( query, k, filter=filter, search_params=search_params, offset=offset, score_threshold=score_threshold, consistency=consistency, **kwargs, ) return list(map(itemgetter(0), results)) [docs] @sync_call_fallback async def asimilarity_search( self, query: str, k: int = 4, filter: Optional[MetadataFilter] = None, **kwargs: Any,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-6
filter: Optional[MetadataFilter] = None, **kwargs: Any, ) -> List[Document]: """Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: Filter by metadata. Defaults to None. Returns: List of Documents most similar to the query. """ results = await self.asimilarity_search_with_score(query, k, filter, **kwargs) return list(map(itemgetter(0), results)) [docs] def similarity_search_with_score( self, query: str, k: int = 4, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, offset: int = 0, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any, ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: Filter by metadata. Defaults to None. search_params: Additional search params offset: Offset of the first result to return. May be used to paginate results. Note: large offset values may cause performance issues. score_threshold: Define a minimal score threshold for the result. If defined, less similar results will not be returned. Score of the returned result might be higher or smaller than the threshold depending on the Distance function used.
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-7
threshold depending on the Distance function used. E.g. for cosine similarity only higher scores will be returned. consistency: Read consistency of the search. Defines how many replicas should be queried before returning the result. Values: - int - number of replicas to query, values should present in all queried replicas - 'majority' - query all replicas, but return values present in the majority of replicas - 'quorum' - query the majority of replicas, return values present in all of them - 'all' - query all replicas, and return values present in all replicas Returns: List of documents most similar to the query text and distance for each. """ return self.similarity_search_with_score_by_vector( self._embed_query(query), k, filter=filter, search_params=search_params, offset=offset, score_threshold=score_threshold, consistency=consistency, **kwargs, ) [docs] @sync_call_fallback async def asimilarity_search_with_score( self, query: str, k: int = 4, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, offset: int = 0, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any, ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4.
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-8
k: Number of Documents to return. Defaults to 4. filter: Filter by metadata. Defaults to None. search_params: Additional search params offset: Offset of the first result to return. May be used to paginate results. Note: large offset values may cause performance issues. score_threshold: Define a minimal score threshold for the result. If defined, less similar results will not be returned. Score of the returned result might be higher or smaller than the threshold depending on the Distance function used. E.g. for cosine similarity only higher scores will be returned. consistency: Read consistency of the search. Defines how many replicas should be queried before returning the result. Values: - int - number of replicas to query, values should present in all queried replicas - 'majority' - query all replicas, but return values present in the majority of replicas - 'quorum' - query the majority of replicas, return values present in all of them - 'all' - query all replicas, and return values present in all replicas Returns: List of documents most similar to the query text and distance for each. """ return await self.asimilarity_search_with_score_by_vector( self._embed_query(query), k, filter=filter, search_params=search_params, offset=offset, score_threshold=score_threshold, consistency=consistency, **kwargs, ) [docs] def similarity_search_by_vector( self, embedding: List[float], k: int = 4, filter: Optional[MetadataFilter] = None,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-9
filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, offset: int = 0, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any, ) -> List[Document]: """Return docs most similar to embedding vector. Args: embedding: Embedding vector to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: Filter by metadata. Defaults to None. search_params: Additional search params offset: Offset of the first result to return. May be used to paginate results. Note: large offset values may cause performance issues. score_threshold: Define a minimal score threshold for the result. If defined, less similar results will not be returned. Score of the returned result might be higher or smaller than the threshold depending on the Distance function used. E.g. for cosine similarity only higher scores will be returned. consistency: Read consistency of the search. Defines how many replicas should be queried before returning the result. Values: - int - number of replicas to query, values should present in all queried replicas - 'majority' - query all replicas, but return values present in the majority of replicas - 'quorum' - query the majority of replicas, return values present in all of them - 'all' - query all replicas, and return values present in all replicas Returns: List of Documents most similar to the query. """ results = self.similarity_search_with_score_by_vector( embedding, k,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-10
embedding, k, filter=filter, search_params=search_params, offset=offset, score_threshold=score_threshold, consistency=consistency, **kwargs, ) return list(map(itemgetter(0), results)) [docs] @sync_call_fallback async def asimilarity_search_by_vector( self, embedding: List[float], k: int = 4, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, offset: int = 0, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any, ) -> List[Document]: """Return docs most similar to embedding vector. Args: embedding: Embedding vector to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: Filter by metadata. Defaults to None. search_params: Additional search params offset: Offset of the first result to return. May be used to paginate results. Note: large offset values may cause performance issues. score_threshold: Define a minimal score threshold for the result. If defined, less similar results will not be returned. Score of the returned result might be higher or smaller than the threshold depending on the Distance function used. E.g. for cosine similarity only higher scores will be returned. consistency: Read consistency of the search. Defines how many replicas should be queried before returning the result. Values: - int - number of replicas to query, values should present in all queried replicas
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-11
- int - number of replicas to query, values should present in all queried replicas - 'majority' - query all replicas, but return values present in the majority of replicas - 'quorum' - query the majority of replicas, return values present in all of them - 'all' - query all replicas, and return values present in all replicas Returns: List of Documents most similar to the query. """ results = await self.asimilarity_search_with_score_by_vector( embedding, k, filter=filter, search_params=search_params, offset=offset, score_threshold=score_threshold, consistency=consistency, **kwargs, ) return list(map(itemgetter(0), results)) [docs] def similarity_search_with_score_by_vector( self, embedding: List[float], k: int = 4, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, offset: int = 0, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any, ) -> List[Tuple[Document, float]]: """Return docs most similar to embedding vector. Args: embedding: Embedding vector to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: Filter by metadata. Defaults to None. search_params: Additional search params offset: Offset of the first result to return. May be used to paginate results. Note: large offset values may cause performance issues. score_threshold:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-12
Note: large offset values may cause performance issues. score_threshold: Define a minimal score threshold for the result. If defined, less similar results will not be returned. Score of the returned result might be higher or smaller than the threshold depending on the Distance function used. E.g. for cosine similarity only higher scores will be returned. consistency: Read consistency of the search. Defines how many replicas should be queried before returning the result. Values: - int - number of replicas to query, values should present in all queried replicas - 'majority' - query all replicas, but return values present in the majority of replicas - 'quorum' - query the majority of replicas, return values present in all of them - 'all' - query all replicas, and return values present in all replicas Returns: List of documents most similar to the query text and distance for each. """ if filter is not None and isinstance(filter, dict): warnings.warn( "Using dict as a `filter` is deprecated. Please use qdrant-client " "filters directly: " "https://qdrant.tech/documentation/concepts/filtering/", DeprecationWarning, ) qdrant_filter = self._qdrant_filter_from_dict(filter) else: qdrant_filter = filter query_vector = embedding if self.vector_name is not None: query_vector = (self.vector_name, embedding) # type: ignore[assignment] results = self.client.search( collection_name=self.collection_name, query_vector=query_vector, query_filter=qdrant_filter, search_params=search_params, limit=k,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-13
search_params=search_params, limit=k, offset=offset, with_payload=True, with_vectors=False, # Langchain does not expect vectors to be returned score_threshold=score_threshold, consistency=consistency, **kwargs, ) return [ ( self._document_from_scored_point( result, self.content_payload_key, self.metadata_payload_key ), result.score, ) for result in results ] [docs] @sync_call_fallback async def asimilarity_search_with_score_by_vector( self, embedding: List[float], k: int = 4, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, offset: int = 0, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any, ) -> List[Tuple[Document, float]]: """Return docs most similar to embedding vector. Args: embedding: Embedding vector to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: Filter by metadata. Defaults to None. search_params: Additional search params offset: Offset of the first result to return. May be used to paginate results. Note: large offset values may cause performance issues. score_threshold: Define a minimal score threshold for the result. If defined, less similar results will not be returned. Score of the returned result might be higher or smaller than the threshold depending on the Distance function used.
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-14
threshold depending on the Distance function used. E.g. for cosine similarity only higher scores will be returned. consistency: Read consistency of the search. Defines how many replicas should be queried before returning the result. Values: - int - number of replicas to query, values should present in all queried replicas - 'majority' - query all replicas, but return values present in the majority of replicas - 'quorum' - query the majority of replicas, return values present in all of them - 'all' - query all replicas, and return values present in all replicas Returns: List of documents most similar to the query text and distance for each. """ from qdrant_client import grpc # noqa from qdrant_client.conversions.conversion import RestToGrpc from qdrant_client.http import models as rest if filter is not None and isinstance(filter, dict): warnings.warn( "Using dict as a `filter` is deprecated. Please use qdrant-client " "filters directly: " "https://qdrant.tech/documentation/concepts/filtering/", DeprecationWarning, ) qdrant_filter = self._qdrant_filter_from_dict(filter) else: qdrant_filter = filter if qdrant_filter is not None and isinstance(qdrant_filter, rest.Filter): qdrant_filter = RestToGrpc.convert_filter(qdrant_filter) response = await self.client.async_grpc_points.Search( grpc.SearchPoints( collection_name=self.collection_name, vector_name=self.vector_name, vector=embedding, filter=qdrant_filter, params=search_params, limit=k,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-15
filter=qdrant_filter, params=search_params, limit=k, offset=offset, with_payload=grpc.WithPayloadSelector(enable=True), with_vectors=grpc.WithVectorsSelector(enable=False), score_threshold=score_threshold, read_consistency=consistency, **kwargs, ) ) return [ ( self._document_from_scored_point_grpc( result, self.content_payload_key, self.metadata_payload_key ), result.score, ) for result in response.result ] [docs] def max_marginal_relevance_search( self, query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: 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. Defaults to 20. 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. """ query_embedding = self._embed_query(query) return self.max_marginal_relevance_search_by_vector( query_embedding, k, fetch_k, lambda_mult, **kwargs )
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-16
query_embedding, k, fetch_k, lambda_mult, **kwargs ) [docs] @sync_call_fallback async def amax_marginal_relevance_search( self, query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: 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. Defaults to 20. 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. """ query_embedding = self._embed_query(query) return await self.amax_marginal_relevance_search_by_vector( query_embedding, k, fetch_k, lambda_mult, **kwargs ) [docs] def max_marginal_relevance_search_by_vector( self, 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.
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-17
Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: 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. """ results = self.max_marginal_relevance_search_with_score_by_vector( embedding=embedding, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult, **kwargs ) return list(map(itemgetter(0), results)) [docs] @sync_call_fallback async def amax_marginal_relevance_search_by_vector( self, 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. Args: 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. Defaults to 20. 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/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-18
to maximum diversity and 1 to minimum diversity. Defaults to 0.5. Returns: List of Documents selected by maximal marginal relevance and distance for each. """ results = await self.amax_marginal_relevance_search_with_score_by_vector( embedding, k, fetch_k, lambda_mult, **kwargs ) return list(map(itemgetter(0), results)) [docs] def max_marginal_relevance_search_with_score_by_vector( self, embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Tuple[Document, float]]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: 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. Defaults to 20. 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 and distance for each. """ query_vector = embedding if self.vector_name is not None: query_vector = (self.vector_name, query_vector) # type: ignore[assignment] results = self.client.search( collection_name=self.collection_name, query_vector=query_vector, with_payload=True,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-19
query_vector=query_vector, with_payload=True, with_vectors=True, limit=fetch_k, ) embeddings = [ result.vector.get(self.vector_name) # type: ignore[index, union-attr] if self.vector_name is not None else result.vector for result in results ] mmr_selected = maximal_marginal_relevance( np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult ) return [ ( self._document_from_scored_point( results[i], self.content_payload_key, self.metadata_payload_key ), results[i].score, ) for i in mmr_selected ] [docs] @sync_call_fallback async def amax_marginal_relevance_search_with_score_by_vector( self, embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Tuple[Document, float]]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: 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. Defaults to 20. 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:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-20
Defaults to 0.5. Returns: List of Documents selected by maximal marginal relevance and distance for each. """ from qdrant_client import grpc # noqa from qdrant_client.conversions.conversion import GrpcToRest response = await self.client.async_grpc_points.Search( grpc.SearchPoints( collection_name=self.collection_name, vector_name=self.vector_name, vector=embedding, with_payload=grpc.WithPayloadSelector(enable=True), with_vectors=grpc.WithVectorsSelector(enable=True), limit=fetch_k, ) ) results = [ GrpcToRest.convert_vectors(result.vectors) for result in response.result ] embeddings: List[List[float]] = [ result.get(self.vector_name) # type: ignore if isinstance(result, dict) else result for result in results ] mmr_selected: List[int] = maximal_marginal_relevance( np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult, ) return [ ( self._document_from_scored_point_grpc( response.result[i], self.content_payload_key, self.metadata_payload_key, ), response.result[i].score, ) for i in mmr_selected ] [docs] def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: """Delete by vector ID or other criteria. Args: ids: List of ids to delete. **kwargs: Other keyword arguments that subclasses might use. Returns: Optional[bool]: True if deletion is successful,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-21
Returns: Optional[bool]: True if deletion is successful, False otherwise, None if not implemented. """ from qdrant_client.http import models as rest result = self.client.delete( collection_name=self.collection_name, points_selector=ids, ) return result.status == rest.UpdateStatus.COMPLETED [docs] @classmethod def from_texts( cls: Type[Qdrant], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[Sequence[str]] = None, location: Optional[str] = None, url: Optional[str] = None, port: Optional[int] = 6333, grpc_port: int = 6334, prefer_grpc: bool = False, https: Optional[bool] = None, api_key: Optional[str] = None, prefix: Optional[str] = None, timeout: Optional[float] = None, host: Optional[str] = None, path: Optional[str] = None, collection_name: Optional[str] = None, distance_func: str = "Cosine", content_payload_key: str = CONTENT_KEY, metadata_payload_key: str = METADATA_KEY, vector_name: Optional[str] = VECTOR_NAME, batch_size: int = 64, shard_number: Optional[int] = None, replication_factor: Optional[int] = None, write_consistency_factor: Optional[int] = None, on_disk_payload: Optional[bool] = None, hnsw_config: Optional[common_types.HnswConfigDiff] = None,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-22
hnsw_config: Optional[common_types.HnswConfigDiff] = None, optimizers_config: Optional[common_types.OptimizersConfigDiff] = None, wal_config: Optional[common_types.WalConfigDiff] = None, quantization_config: Optional[common_types.QuantizationConfig] = None, init_from: Optional[common_types.InitFrom] = None, on_disk: Optional[bool] = None, force_recreate: bool = False, **kwargs: Any, ) -> Qdrant: """Construct Qdrant wrapper from a list of texts. Args: texts: A list of texts to be indexed in Qdrant. embedding: A subclass of `Embeddings`, responsible for text vectorization. metadatas: An optional list of metadata. If provided it has to be of the same length as a list of texts. ids: Optional list of ids to associate with the texts. Ids have to be uuid-like strings. location: If `:memory:` - use in-memory Qdrant instance. If `str` - use it as a `url` parameter. If `None` - fallback to relying on `host` and `port` parameters. url: either host or str of "Optional[scheme], host, Optional[port], Optional[prefix]". Default: `None` port: Port of the REST API interface. Default: 6333 grpc_port: Port of the gRPC interface. Default: 6334 prefer_grpc: If true - use gPRC interface whenever possible in custom methods. Default: False https: If true - use HTTPS(SSL) protocol. Default: None
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-23
https: If true - use HTTPS(SSL) protocol. Default: None api_key: API key for authentication in Qdrant Cloud. Default: None prefix: If not None - add prefix to the REST URL path. Example: service/v1 will result in http://localhost:6333/service/v1/{qdrant-endpoint} for REST API. Default: None timeout: Timeout for REST and gRPC API requests. Default: 5.0 seconds for REST and unlimited for gRPC host: Host name of Qdrant service. If url and host are None, set to 'localhost'. Default: None path: Path in which the vectors will be stored while using local mode. Default: None collection_name: Name of the Qdrant collection to be used. If not provided, it will be created randomly. Default: None distance_func: Distance function. One of: "Cosine" / "Euclid" / "Dot". Default: "Cosine" content_payload_key: A payload key used to store the content of the document. Default: "page_content" metadata_payload_key: A payload key used to store the metadata of the document. Default: "metadata" vector_name: Name of the vector to be used internally in Qdrant. Default: None batch_size: How many vectors upload per-request. Default: 64 shard_number: Number of shards in collection. Default is 1, minimum is 1. replication_factor: Replication factor for collection. Default is 1, minimum is 1. Defines how many copies of each shard will be created.
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-24
Defines how many copies of each shard will be created. Have effect only in distributed mode. write_consistency_factor: Write consistency factor for collection. Default is 1, minimum is 1. Defines how many replicas should apply the operation for us to consider it successful. Increasing this number will make the collection more resilient to inconsistencies, but will also make it fail if not enough replicas are available. Does not have any performance impact. Have effect only in distributed mode. on_disk_payload: If true - point`s payload will not be stored in memory. It will be read from the disk every time it is requested. This setting saves RAM by (slightly) increasing the response time. Note: those payload values that are involved in filtering and are indexed - remain in RAM. hnsw_config: Params for HNSW index optimizers_config: Params for optimizer wal_config: Params for Write-Ahead-Log quantization_config: Params for quantization, if None - quantization will be disabled init_from: Use data stored in another collection to initialize this collection force_recreate: Force recreating the collection **kwargs: Additional arguments passed directly into REST client initialization This is a user-friendly interface that: 1. Creates embeddings, one for each text 2. Initializes the Qdrant database as an in-memory docstore by default (and overridable to a remote docstore) 3. Adds the text embeddings to the Qdrant database This is intended to be a quick way to get started. Example: .. code-block:: python from langchain import Qdrant
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-25
Example: .. code-block:: python from langchain import Qdrant from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() qdrant = Qdrant.from_texts(texts, embeddings, "localhost") """ qdrant = cls._construct_instance( texts, embedding, location, url, port, grpc_port, prefer_grpc, https, api_key, prefix, timeout, host, path, collection_name, distance_func, content_payload_key, metadata_payload_key, vector_name, shard_number, replication_factor, write_consistency_factor, on_disk_payload, hnsw_config, optimizers_config, wal_config, quantization_config, init_from, on_disk, force_recreate, **kwargs, ) qdrant.add_texts(texts, metadatas, ids, batch_size) return qdrant [docs] @classmethod @sync_call_fallback async def afrom_texts( cls: Type[Qdrant], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[Sequence[str]] = None, location: Optional[str] = None, url: Optional[str] = None, port: Optional[int] = 6333, grpc_port: int = 6334, prefer_grpc: bool = False, https: Optional[bool] = None, api_key: Optional[str] = None,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-26
api_key: Optional[str] = None, prefix: Optional[str] = None, timeout: Optional[float] = None, host: Optional[str] = None, path: Optional[str] = None, collection_name: Optional[str] = None, distance_func: str = "Cosine", content_payload_key: str = CONTENT_KEY, metadata_payload_key: str = METADATA_KEY, vector_name: Optional[str] = VECTOR_NAME, batch_size: int = 64, shard_number: Optional[int] = None, replication_factor: Optional[int] = None, write_consistency_factor: Optional[int] = None, on_disk_payload: Optional[bool] = None, hnsw_config: Optional[common_types.HnswConfigDiff] = None, optimizers_config: Optional[common_types.OptimizersConfigDiff] = None, wal_config: Optional[common_types.WalConfigDiff] = None, quantization_config: Optional[common_types.QuantizationConfig] = None, init_from: Optional[common_types.InitFrom] = None, on_disk: Optional[bool] = None, force_recreate: bool = False, **kwargs: Any, ) -> Qdrant: """Construct Qdrant wrapper from a list of texts. Args: texts: A list of texts to be indexed in Qdrant. embedding: A subclass of `Embeddings`, responsible for text vectorization. metadatas: An optional list of metadata. If provided it has to be of the same length as a list of texts. ids: Optional list of ids to associate with the texts. Ids have to be
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-27
Optional list of ids to associate with the texts. Ids have to be uuid-like strings. location: If `:memory:` - use in-memory Qdrant instance. If `str` - use it as a `url` parameter. If `None` - fallback to relying on `host` and `port` parameters. url: either host or str of "Optional[scheme], host, Optional[port], Optional[prefix]". Default: `None` port: Port of the REST API interface. Default: 6333 grpc_port: Port of the gRPC interface. Default: 6334 prefer_grpc: If true - use gPRC interface whenever possible in custom methods. Default: False https: If true - use HTTPS(SSL) protocol. Default: None api_key: API key for authentication in Qdrant Cloud. Default: None prefix: If not None - add prefix to the REST URL path. Example: service/v1 will result in http://localhost:6333/service/v1/{qdrant-endpoint} for REST API. Default: None timeout: Timeout for REST and gRPC API requests. Default: 5.0 seconds for REST and unlimited for gRPC host: Host name of Qdrant service. If url and host are None, set to 'localhost'. Default: None path: Path in which the vectors will be stored while using local mode. Default: None collection_name: Name of the Qdrant collection to be used. If not provided, it will be created randomly. Default: None distance_func:
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-28
it will be created randomly. Default: None distance_func: Distance function. One of: "Cosine" / "Euclid" / "Dot". Default: "Cosine" content_payload_key: A payload key used to store the content of the document. Default: "page_content" metadata_payload_key: A payload key used to store the metadata of the document. Default: "metadata" vector_name: Name of the vector to be used internally in Qdrant. Default: None batch_size: How many vectors upload per-request. Default: 64 shard_number: Number of shards in collection. Default is 1, minimum is 1. replication_factor: Replication factor for collection. Default is 1, minimum is 1. Defines how many copies of each shard will be created. Have effect only in distributed mode. write_consistency_factor: Write consistency factor for collection. Default is 1, minimum is 1. Defines how many replicas should apply the operation for us to consider it successful. Increasing this number will make the collection more resilient to inconsistencies, but will also make it fail if not enough replicas are available. Does not have any performance impact. Have effect only in distributed mode. on_disk_payload: If true - point`s payload will not be stored in memory. It will be read from the disk every time it is requested. This setting saves RAM by (slightly) increasing the response time. Note: those payload values that are involved in filtering and are indexed - remain in RAM. hnsw_config: Params for HNSW index optimizers_config: Params for optimizer
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-29
optimizers_config: Params for optimizer wal_config: Params for Write-Ahead-Log quantization_config: Params for quantization, if None - quantization will be disabled init_from: Use data stored in another collection to initialize this collection force_recreate: Force recreating the collection **kwargs: Additional arguments passed directly into REST client initialization This is a user-friendly interface that: 1. Creates embeddings, one for each text 2. Initializes the Qdrant database as an in-memory docstore by default (and overridable to a remote docstore) 3. Adds the text embeddings to the Qdrant database This is intended to be a quick way to get started. Example: .. code-block:: python from langchain import Qdrant from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() qdrant = await Qdrant.afrom_texts(texts, embeddings, "localhost") """ qdrant = cls._construct_instance( texts, embedding, location, url, port, grpc_port, prefer_grpc, https, api_key, prefix, timeout, host, path, collection_name, distance_func, content_payload_key, metadata_payload_key, vector_name, shard_number, replication_factor, write_consistency_factor, on_disk_payload, hnsw_config, optimizers_config, wal_config, quantization_config, init_from, on_disk, force_recreate, **kwargs, )
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-30
on_disk, force_recreate, **kwargs, ) await qdrant.aadd_texts(texts, metadatas, ids, batch_size) return qdrant @classmethod def _construct_instance( cls: Type[Qdrant], texts: List[str], embedding: Embeddings, location: Optional[str] = None, url: Optional[str] = None, port: Optional[int] = 6333, grpc_port: int = 6334, prefer_grpc: bool = False, https: Optional[bool] = None, api_key: Optional[str] = None, prefix: Optional[str] = None, timeout: Optional[float] = None, host: Optional[str] = None, path: Optional[str] = None, collection_name: Optional[str] = None, distance_func: str = "Cosine", content_payload_key: str = CONTENT_KEY, metadata_payload_key: str = METADATA_KEY, vector_name: Optional[str] = VECTOR_NAME, shard_number: Optional[int] = None, replication_factor: Optional[int] = None, write_consistency_factor: Optional[int] = None, on_disk_payload: Optional[bool] = None, hnsw_config: Optional[common_types.HnswConfigDiff] = None, optimizers_config: Optional[common_types.OptimizersConfigDiff] = None, wal_config: Optional[common_types.WalConfigDiff] = None, quantization_config: Optional[common_types.QuantizationConfig] = None, init_from: Optional[common_types.InitFrom] = None,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-31
init_from: Optional[common_types.InitFrom] = None, on_disk: Optional[bool] = None, force_recreate: bool = False, **kwargs: Any, ) -> Qdrant: try: import qdrant_client except ImportError: raise ValueError( "Could not import qdrant-client python package. " "Please install it with `pip install qdrant-client`." ) from grpc import RpcError from qdrant_client.http import models as rest from qdrant_client.http.exceptions import UnexpectedResponse # Just do a single quick embedding to get vector size partial_embeddings = embedding.embed_documents(texts[:1]) vector_size = len(partial_embeddings[0]) collection_name = collection_name or uuid.uuid4().hex distance_func = distance_func.upper() client = qdrant_client.QdrantClient( location=location, url=url, port=port, grpc_port=grpc_port, prefer_grpc=prefer_grpc, https=https, api_key=api_key, prefix=prefix, timeout=timeout, host=host, path=path, **kwargs, ) try: # Skip any validation in case of forced collection recreate. if force_recreate: raise ValueError # Get the vector configuration of the existing collection and vector, if it # was specified. If the old configuration does not match the current one, # an exception is being thrown. collection_info = client.get_collection(collection_name=collection_name) current_vector_config = collection_info.config.params.vectors
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-32
current_vector_config = collection_info.config.params.vectors if isinstance(current_vector_config, dict) and vector_name is not None: if vector_name not in current_vector_config: raise QdrantException( f"Existing Qdrant collection {collection_name} does not " f"contain vector named {vector_name}. Did you mean one of the " f"existing vectors: {', '.join(current_vector_config.keys())}? " f"If you want to recreate the collection, set `force_recreate` " f"parameter to `True`." ) current_vector_config = current_vector_config.get( vector_name ) # type: ignore[assignment] elif isinstance(current_vector_config, dict) and vector_name is None: raise QdrantException( f"Existing Qdrant collection {collection_name} uses named vectors. " f"If you want to reuse it, please set `vector_name` to any of the " f"existing named vectors: " f"{', '.join(current_vector_config.keys())}." # noqa f"If you want to recreate the collection, set `force_recreate` " f"parameter to `True`." ) elif ( not isinstance(current_vector_config, dict) and vector_name is not None ): raise QdrantException( f"Existing Qdrant collection {collection_name} doesn't use named " f"vectors. If you want to reuse it, please set `vector_name` to " f"`None`. If you want to recreate the collection, set " f"`force_recreate` parameter to `True`." ) # Check if the vector configuration has the same dimensionality.
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-33
) # Check if the vector configuration has the same dimensionality. if current_vector_config.size != vector_size: # type: ignore[union-attr] raise QdrantException( f"Existing Qdrant collection is configured for vectors with " f"{current_vector_config.size} " # type: ignore[union-attr] f"dimensions. Selected embeddings are {vector_size}-dimensional. " f"If you want to recreate the collection, set `force_recreate` " f"parameter to `True`." ) current_distance_func = ( current_vector_config.distance.name.upper() # type: ignore[union-attr] ) if current_distance_func != distance_func: raise QdrantException( f"Existing Qdrant collection is configured for " f"{current_distance_func} similarity, but requested " f"{distance_func}. Please set `distance_func` parameter to " f"`{current_distance_func}` if you want to reuse it. " f"If you want to recreate the collection, set `force_recreate` " f"parameter to `True`." ) except (UnexpectedResponse, RpcError, ValueError): vectors_config = rest.VectorParams( size=vector_size, distance=rest.Distance[distance_func], on_disk=on_disk, ) # If vector name was provided, we're going to use the named vectors feature # with just a single vector. if vector_name is not None: vectors_config = { # type: ignore[assignment] vector_name: vectors_config, } client.recreate_collection( collection_name=collection_name, vectors_config=vectors_config,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-34
collection_name=collection_name, vectors_config=vectors_config, shard_number=shard_number, replication_factor=replication_factor, write_consistency_factor=write_consistency_factor, on_disk_payload=on_disk_payload, hnsw_config=hnsw_config, optimizers_config=optimizers_config, wal_config=wal_config, quantization_config=quantization_config, init_from=init_from, timeout=timeout, # type: ignore[arg-type] ) qdrant = cls( client=client, collection_name=collection_name, embeddings=embedding, content_payload_key=content_payload_key, metadata_payload_key=metadata_payload_key, distance_strategy=distance_func, vector_name=vector_name, ) return qdrant def _select_relevance_score_fn(self) -> Callable[[float], float]: """ The 'correct' relevance function may differ depending on a few things, including: - the distance / similarity metric used by the VectorStore - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) - embedding dimensionality - etc. """ if self.distance_strategy == "COSINE": return self._cosine_relevance_score_fn elif self.distance_strategy == "DOT": return self._max_inner_product_relevance_score_fn elif self.distance_strategy == "EUCLID": return self._euclidean_relevance_score_fn else: raise ValueError( "Unknown distance strategy, must be cosine, " "max_inner_product, or euclidean" ) def _similarity_search_with_relevance_scores(
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
13ba630d8980-35
) def _similarity_search_with_relevance_scores( self, 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. Args: 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) """ return self.similarity_search_with_score(query, k, **kwargs) @classmethod def _build_payloads( cls, texts: Iterable[str], metadatas: Optional[List[dict]], content_payload_key: str, metadata_payload_key: str, ) -> List[dict]: payloads = [] for i, text in enumerate(texts): if text is None: raise ValueError( "At least one of the texts is None. Please remove it before " "calling .from_texts or .add_texts on Qdrant instance." ) metadata = metadatas[i] if metadatas is not None else None payloads.append( { content_payload_key: text, metadata_payload_key: metadata, } ) return payloads @classmethod def _document_from_scored_point( cls, scored_point: Any, content_payload_key: str,
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html