id stringlengths 14 16 | text stringlengths 4 1.28k | source stringlengths 54 121 |
|---|---|---|
e557f61be02a-14 | Returns:
List of Documents selected by maximal marginal relevance.
"""
raise NotImplementedError
[docs] async def amax_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-15 | metadatas = [d.metadata for d in documents]
return cls.from_texts(texts, embedding, metadatas=metadatas, **kwargs)
[docs] @classmethod
async def afrom_documents(
cls: Type[VST],
documents: List[Document],
embedding: Embeddings,
**kwargs: Any,
) -> VST:
"""Retur... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-16 | embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> VST:
"""Return VectorStore initialized from texts and embeddings."""
[docs] @classmethod
async def afrom_texts(
cls: Type[VST],
texts: List[str],
embedding: Embeddings,
m... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-17 | search_kwargs: dict = Field(default_factory=dict)
allowed_search_types: ClassVar[Collection[str]] = (
"similarity",
"similarity_score_threshold",
"mmr",
)
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
@root_validator()
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-18 | if (score_threshold is None) or (not isinstance(score_threshold, float)):
raise ValueError(
"`score_threshold` is not specified with a float value(0~1) "
"in `search_kwargs`."
)
return values
def get_relevant_documents(self, query: str)... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-19 | query, **self.search_kwargs
)
else:
raise ValueError(f"search_type of {self.search_type} not allowed.")
return docs
async def aget_relevant_documents(self, query: str) -> List[Document]:
if self.search_type == "similarity":
docs = await self.vectorstore.as... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-20 | )
else:
raise ValueError(f"search_type of {self.search_type} not allowed.")
return docs
def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]:
"""Add documents to vectorstore."""
return self.vectorstore.add_documents(documents, **kwargs)
async... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
da6ef1aa6afc-0 | Source code for langchain.vectorstores.awadb
"""Wrapper around AwaDB for embedding vectors"""
from __future__ import annotations
import logging
import uuid
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type
from langchain.docstore.document import Document
from langchain.embeddings.base import ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
da6ef1aa6afc-1 | log_and_data_dir: Optional[str] = None,
client: Optional[awadb.Client] = None,
) -> None:
"""Initialize with AwaDB client."""
try:
import awadb
except ImportError:
raise ValueError(
"Could not import awadb python package. "
"Ple... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
da6ef1aa6afc-2 | self.awadb_client.Create(table_name)
self.table2embeddings: dict[str, Embeddings] = {}
if embedding_model is not None:
self.table2embeddings[table_name] = embedding_model
self.using_table_name = table_name
[docs] def add_texts(
self,
texts: Iterable[str],
m... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
da6ef1aa6afc-3 | Returns:
List of ids from adding the texts into the vectorstore.
"""
if self.awadb_client is None:
raise ValueError("AwaDB client is None!!!")
embeddings = None
if self.using_table_name in self.table2embeddings:
embeddings = self.table2embeddings[self.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
da6ef1aa6afc-4 | return self.awadb_client.Load(table_name)
[docs] def similarity_search(
self,
query: str,
k: int = DEFAULT_TOPN,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to query."""
if self.awadb_client is None:
raise ValueError("AwaDB client is... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
da6ef1aa6afc-5 | self,
query: str,
k: int = DEFAULT_TOPN,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs and relevance scores, normalized on a scale from 0 to 1.
0 is dissimilar, 1 is most similar.
"""
if self.awadb_client is None:
raise ValueErro... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
da6ef1aa6afc-6 | scores: List[float] = []
retrieval_docs = self.similarity_search_by_vector(embedding, k, scores)
L2_Norm = 0.0
for score in scores:
L2_Norm = L2_Norm + score * score
L2_Norm = pow(L2_Norm, 0.5)
doc_no = 0
for doc in retrieval_docs:
doc_tuple = (doc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
da6ef1aa6afc-7 | """Return docs and relevance scores, normalized on a scale from 0 to 1.
0 is dissimilar, 1 is most similar.
"""
if self.awadb_client is None:
raise ValueError("AwaDB client is None!!!")
embedding = None
if self.using_table_name in self.table2embeddings:
em... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
da6ef1aa6afc-8 | for score in scores:
L2_Norm = L2_Norm + score * score
L2_Norm = pow(L2_Norm, 0.5)
doc_no = 0
for doc in retrieval_docs:
doc_tuple = (doc, 1 - scores[doc_no] / L2_Norm)
results.append(doc_tuple)
doc_no = doc_no + 1
return results
[docs] ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
da6ef1aa6afc-9 | k: Number of Documents to return. Defaults to 4.
Returns:
List of Documents most similar to the query vector.
"""
if self.awadb_client is None:
raise ValueError("AwaDB client is None!!!")
results: List[Document] = []
if embedding is None:
retur... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
da6ef1aa6afc-10 | elif item_key == "embedding_text":
content = item_detail[item_key]
elif (
item_key == "Field@1" or item_key == "text_embedding"
): # embedding field for the document
continue
elif item_key == "score": # L2 dist... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
da6ef1aa6afc-11 | if ret:
self.using_table_name = table_name
return ret
[docs] def use(
self,
table_name: str,
**kwargs: Any,
) -> bool:
"""Use the specified table. Don't know the tables, please invoke list_tables."""
if self.awadb_client is None:
return Fals... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
da6ef1aa6afc-12 | **kwargs: Any,
) -> str:
"""Get the current table."""
return self.using_table_name
[docs] @classmethod
def from_texts(
cls: Type[AwaDB],
texts: List[str],
embedding: Optional[Embeddings] = None,
metadatas: Optional[List[dict]] = None,
table_name: str = ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
da6ef1aa6afc-13 | metadatas (Optional[List[dict]]): List of metadatas. Defaults to None.
table_name (str): Name of the table to create.
logging_and_data_dir (Optional[str]): Directory of logging and persistence.
client (Optional[awadb.Client]): AwaDB client
Returns:
AwaDB: AwaDB ve... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
da6ef1aa6afc-14 | table_name: str = _DEFAULT_TABLE_NAME,
logging_and_data_dir: Optional[str] = None,
client: Optional[awadb.Client] = None,
**kwargs: Any,
) -> AwaDB:
"""Create an AwaDB vectorstore from a list of documents.
If a logging_and_data_dir specified, the table will be persisted there... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
da6ef1aa6afc-15 | """
texts = [doc.page_content for doc in documents]
metadatas = [doc.metadata for doc in documents]
return cls.from_texts(
texts=texts,
embedding=embedding,
metadatas=metadatas,
table_name=table_name,
logging_and_data_dir=logging_and_da... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
9ecd582ad92e-0 | Source code for langchain.vectorstores.milvus
"""Wrapper around the Milvus vector database."""
from __future__ import annotations
import logging
from typing import Any, Iterable, List, Optional, Tuple, Union
from uuid import uuid4
import numpy as np
from langchain.docstore.document import Document
from langchain.embedd... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-1 | embedding_function: Embeddings,
collection_name: str = "LangChainCollection",
connection_args: Optional[dict[str, Any]] = None,
consistency_level: str = "Session",
index_params: Optional[dict] = None,
search_params: Optional[dict] = None,
drop_old: Optional[bool] = False,... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-2 | https://zilliz.com/cloud
IF USING L2/IP metric IT IS HIGHLY SUGGESTED TO NORMALIZE YOUR DATA.
The connection args used for this class comes in the form of a dict,
here are a few of the options:
address (str): The actual address of Milvus
instance. Example address: "lo... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-3 | port (str/int): The port of Milvus instance. Default at 19530, PyMilvus
will fill in the default port if only host is provided.
user (str): Use which user to connect to Milvus instance. If user and
password are provided, we will add related header in every RPC call.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-4 | the ca.pem path.
server_pem_path (str): If use tls one-way authentication, need to
write the server.pem path.
server_name (str): If use tls, need to write the common name.
Args:
embedding_function (Embeddings): Function used to embed the text.
coll... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-5 | default of index.
drop_old (Optional[bool]): Whether to drop the current collection. Defaults
to False.
"""
try:
from pymilvus import Collection, utility
except ImportError:
raise ValueError(
"Could not import pymilvus python pa... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-6 | "HNSW": {"metric_type": "L2", "params": {"ef": 10}},
"RHNSW_FLAT": {"metric_type": "L2", "params": {"ef": 10}},
"RHNSW_SQ": {"metric_type": "L2", "params": {"ef": 10}},
"RHNSW_PQ": {"metric_type": "L2", "params": {"ef": 10}},
"IVF_HNSW": {"metric_type": "L2", "params": {"... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-7 | self.collection_name = collection_name
self.index_params = index_params
self.search_params = search_params
self.consistency_level = consistency_level
# In order for a collection to be compatible, pk needs to be auto'id and int
self._primary_field = "pk"
# In order for com... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-8 | if utility.has_collection(self.collection_name, using=self.alias):
self.col = Collection(
self.collection_name,
using=self.alias,
)
# If need to drop old, drop it
if drop_old and isinstance(self.col, Collection):
self.col.drop()
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-9 | uri: str = connection_args.get("uri", None)
user = connection_args.get("user", None)
# Order of use is host/port, uri, address
if host is not None and port is not None:
given_address = str(host) + ":" + str(port)
elif uri is not None:
given_address = uri.split("ht... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-10 | for con in connections.list_connections():
addr = connections.get_connection_addr(con[0])
if (
con[1]
and ("address" in addr)
and (addr["address"] == given_address)
and ("user" in addr)
an... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-11 | raise e
def _init(
self, embeddings: Optional[list] = None, metadatas: Optional[list[dict]] = None
) -> None:
if embeddings is not None:
self._create_collection(embeddings, metadatas)
self._extract_fields()
self._create_index()
self._create_search_params()
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-12 | # Determine metadata schema
if metadatas:
# Create FieldSchema for each entry in metadata.
for key, value in metadatas[0].items():
# Infer the corresponding datatype of the metadata
dtype = infer_dtype_bydata(value)
# Datatype isnt compatib... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-13 | fields.append(
FieldSchema(self._text_field, DataType.VARCHAR, max_length=65_535)
)
# Create the primary key field
fields.append(
FieldSchema(
self._primary_field, DataType.INT64, is_primary=True, auto_id=True
)
)
# Create the v... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-14 | logger.error(
"Failed to create collection: %s error: %s", self.collection_name, e
)
raise e
def _extract_fields(self) -> None:
"""Grab the existing fields from the Collection"""
from pymilvus import Collection
if isinstance(self.col, Collection):
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-15 | return None
def _create_index(self) -> None:
"""Create a index on the collection"""
from pymilvus import Collection, MilvusException
if isinstance(self.col, Collection) and self._get_index() is None:
try:
# If no index params, use a default HNSW based one
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-16 | except MilvusException:
# Use AUTOINDEX based index
self.index_params = {
"metric_type": "L2",
"index_type": "AUTOINDEX",
"params": {},
}
self.col.create_index(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-17 | index = self._get_index()
if index is not None:
index_type: str = index["index_param"]["index_type"]
metric_type: str = index["index_param"]["metric_type"]
self.search_params = self.default_search_params[index_type]
self.search_params["metric_t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-18 | ) -> List[str]:
"""Insert text data into Milvus.
Inserting data when the collection has not be made yet will result
in creating a new Collection. The data of the first entity decides
the schema of the new collection, the dim is extracted from the first
embedding and the columns a... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-19 | Defaults to 1000.
Raises:
MilvusException: Failure to add texts
Returns:
List[str]: The resulting keys for each inserted element.
"""
from pymilvus import Collection, MilvusException
texts = list(texts)
try:
embeddings = self.embedding_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-20 | self._text_field: texts,
self._vector_field: embeddings,
}
# Collect the metadata into the insert dict.
if metadatas is not None:
for d in metadatas:
for key, value in d.items():
if key in self.fields:
insert_dic... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-21 | # Insert into the collection.
try:
res: Collection
res = self.col.insert(insert_list, timeout=timeout, **kwargs)
pks.extend(res.primary_keys)
except MilvusException as e:
logger.error(
"Failed to insert batch sta... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-22 | k (int, optional): How many results to return. Defaults to 4.
param (dict, optional): The search params for the index type.
Defaults to None.
expr (str, optional): Filtering expression. Defaults to None.
timeout (int, optional): How long to wait before timeout error.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-23 | embedding: List[float],
k: int = 4,
param: Optional[dict] = None,
expr: Optional[str] = None,
timeout: Optional[int] = None,
**kwargs: Any,
) -> List[Document]:
"""Perform a similarity search against the query string.
Args:
embedding (List[float]):... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-24 | """
if self.col is None:
logger.debug("No existing collection to search.")
return []
res = self.similarity_search_with_score_by_vector(
embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs
)
return [doc for doc, _ in res]
[docs] ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-25 | documentation found here:
https://milvus.io/api-reference/pymilvus/v2.2.6/Collection/search().md
Args:
query (str): The text being searched.
k (int, optional): The amount of results ot return. Defaults to 4.
param (dict): The search params for the specified index.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-26 | res = self.similarity_search_with_score_by_vector(
embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs
)
return res
[docs] def similarity_search_with_score_by_vector(
self,
embedding: List[float],
k: int = 4,
param: Optional[dict] = ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-27 | Args:
embedding (List[float]): The embedding vector being searched.
k (int, optional): The amount of results ot return. Defaults to 4.
param (dict): The search params for the specified index.
Defaults to None.
expr (str, optional): Filtering expression. De... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-28 | # Perform the search.
res = self.col.search(
data=[embedding],
anns_field=self._vector_field,
param=param,
limit=k,
expr=expr,
output_fields=output_fields,
timeout=timeout,
**kwargs,
)
# Organize resu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-29 | fetch_k: int = 20,
lambda_mult: float = 0.5,
param: Optional[dict] = None,
expr: Optional[str] = None,
timeout: Optional[int] = None,
**kwargs: Any,
) -> List[Document]:
"""Perform a search and return results that are reordered by MMR.
Args:
query ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-30 | Defaults to 0.5
param (dict, optional): The search params for the specified index.
Defaults to None.
expr (str, optional): Filtering expression. Defaults to None.
timeout (int, optional): How long to wait before timeout error.
Defaults to None.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-31 | **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,
param: Optional[dict] = None,
expr: Optional[str] = None,
timeout: Optional[int] = None,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-32 | 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
param (dict, optional): The ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-33 | output_fields = self.fields[:]
output_fields.remove(self._vector_field)
# Perform the search.
res = self.col.search(
data=[embedding],
anns_field=self._vector_field,
param=param,
limit=fetch_k,
expr=expr,
output_fields=outpu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-34 | output_fields=[self._primary_field, self._vector_field],
timeout=timeout,
)
# Reorganize the results from query to match search order.
vectors = {x[self._primary_field]: x[self._vector_field] for x in vectors}
ordered_result_embeddings = [vectors[x] for x in ids]
# Ge... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-35 | def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
collection_name: str = "LangChainCollection",
connection_args: dict[str, Any] = DEFAULT_MILVUS_CONNECTION,
consistency_level: str = "Session",
index_param... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-36 | Defaults to None.
collection_name (str, optional): Collection name to use. Defaults to
"LangChainCollection".
connection_args (dict[str, Any], optional): Connection args to use. Defaults
to DEFAULT_MILVUS_CONNECTION.
consistency_level (str, optional): ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9ecd582ad92e-37 | collection_name=collection_name,
connection_args=connection_args,
consistency_level=consistency_level,
index_params=index_params,
search_params=search_params,
drop_old=drop_old,
**kwargs,
)
vector_db.add_texts(texts=texts, metadatas... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
69f09aa7de54-0 | Source code for langchain.vectorstores.elastic_vector_search
"""Wrapper around Elasticsearch vector database."""
from __future__ import annotations
import uuid
from abc import ABC
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterable,
List,
Mapping,
Optional,
Tuple,
Union,
)
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-1 | }
}
def _default_script_query(query_vector: List[float], filter: Optional[dict]) -> Dict:
if filter:
((key, value),) = filter.items()
filter = {"match": {f"metadata.{key}.keyword": f"{value}"}}
else:
filter = {"match_all": {}}
return {
"script_score": {
"query... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-2 | # defined as an abstract base class itself, allowing the creation of subclasses with
# their own specific implementations. If you plan to subclass ElasticVectorSearch,
# you can inherit from it and define your own implementation of the necessary methods
# and attributes.
[docs]class ElasticVectorSearch(VectorStore, ABC... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-3 | embedding=embedding
)
To connect to an Elasticsearch instance that requires login credentials,
including Elastic Cloud, use the Elasticsearch URL format
https://username:password@es_host:9243. For example, to connect to Elastic
Cloud, create the Elasticsearch URL with the required authentica... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-4 | 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.embeddi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-5 | 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:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-6 | )
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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-7 | metadatas: Optional list of metadatas associated with the texts.
refresh_indices: bool to refresh ElasticSearch indices
Returns:
List of ids from adding the texts into the vectorstore.
"""
try:
from elasticsearch.exceptions import NotFoundError
fro... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-8 | 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 {}
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-9 | ) -> 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.simi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-10 | 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... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-11 | elasticsearch_url: Optional[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 documen... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-12 | )
"""
elasticsearch_url = elasticsearch_url or get_from_env(
"elasticsearch_url", "ELASTICSEARCH_URL"
)
index_name = index_name or uuid.uuid4().hex
vectorsearch = cls(elasticsearch_url, index_name, embedding, **kwargs)
vectorsearch.add_texts(
texts... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-13 | [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, ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-14 | class ElasticKnnSearch(ElasticVectorSearch):
"""
A class for performing k-Nearest Neighbors (k-NN) search on an Elasticsearch index.
The class is designed for a text search scenario where documents are text strings
and their embeddings are vector representations of those strings.
"""
def __init_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-15 | Elasticsearch client.
Args:
index_name: The name of the Elasticsearch index.
embedding: An instance of the Embeddings class, used to generate vector
representations of text strings.
es_connection: An existing Elasticsearch connection.
es_cloud_id: ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-16 | 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 pr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-17 | return {
"properties": {
"text": {"type": "text"},
"vector": {
"type": "dense_vector",
"dims": dims,
"index": True,
"similarity": "dot_product",
},
}
}
def ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-18 | }
# 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_vecto... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-19 | 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], .... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-20 | Args:
query: The query or queries to be used for the search. Required if
`query_vector` is not provided.
k: The number of nearest neighbors to return. Defaults to 10.
query_vector: The query vector to be used for the search. Required if
`query` is not ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-21 | The search results.
Raises:
ValueError: If neither `query_vector` nor `model_id` is provided, or if
both are provided.
"""
knn_query_body = self._default_knn_query(
query_vector=query_vector, query=query, model_id=model_id, k=k
)
# Perform ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-22 | 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,
) -> Dict[Any, Any]:
"""Performs ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-23 | results.
Args:
query: The query or queries to be used for the search. Required if
`query_vector` is not provided.
k: The number of nearest neighbors to return. Defaults to 10.
query_vector: The query vector to be used for the search. Required if
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-24 | included. Defaults to None.
vector_query_field: Field name to use in knn search if not default 'vector'
query_field: Field name to use in search if not default 'text'
Returns:
The search results.
Raises:
ValueError: If neither `query_vector` nor `model_id`... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
69f09aa7de54-25 | }
# Perform the hybrid search on the Elasticsearch index and return the results.
res = self.client.search(
index=self.index_name,
query=match_query_body,
knn=knn_query_body,
fields=fields,
size=size,
source=source,
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
1085b2eba275-0 | Source code for langchain.vectorstores.mongodb_atlas
from __future__ import annotations
import logging
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generator,
Iterable,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from langchain.docstore.document import Document
from langchain.embe... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
1085b2eba275-1 | - a connection string associated with a MongoDB Atlas Cluster having deployed an
Atlas Search index
Example:
.. code-block:: python
from langchain.vectorstores import MongoDBAtlasVectorSearch
from langchain.embeddings.openai import OpenAIEmbeddings
from pymongo im... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
1085b2eba275-2 | ):
"""
Args:
collection: MongoDB collection to add the texts to.
embedding: Text embedding model to use.
text_key: MongoDB field that will contain the text for each
document.
embedding_key: MongoDB field that will contain the embedding for
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
1085b2eba275-3 | "`pip install pymongo`."
)
client: MongoClient = MongoClient(connection_string)
db_name, collection_name = namespace.split(".")
collection = client[db_name][collection_name]
return cls(collection, embedding, **kwargs)
[docs] def add_texts(
self,
texts: Iter... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
1085b2eba275-4 | _metadatas: Union[List, Generator] = metadatas or ({} for _ in texts)
texts_batch = []
metadatas_batch = []
result_ids = []
for i, (text, metadata) in enumerate(zip(texts, _metadatas)):
texts_batch.append(text)
metadatas_batch.append(metadata)
if (i + ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
1085b2eba275-5 | if not texts:
return []
# Embed and create the documents
embeddings = self._embedding.embed_documents(texts)
to_insert = [
{self._text_key: t, self._embedding_key: embedding, **m}
for t, m, embedding in zip(texts, metadatas, embeddings)
]
# ins... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
1085b2eba275-6 | Use the knnBeta Operator available in MongoDB Atlas Search
This feature is in early access and available only for evaluation purposes, to
validate functionality, and to gather feedback from a small closed group of
early access users. It is not recommended for production deployments as we
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
1085b2eba275-7 | "path": self._embedding_key,
"k": k,
}
if pre_filter:
knn_beta["filter"] = pre_filter
pipeline = [
{
"$search": {
"index": self._index_name,
"knnBeta": knn_beta,
}
},
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
1085b2eba275-8 | self,
query: str,
k: int = 4,
pre_filter: Optional[dict] = None,
post_filter_pipeline: Optional[List[Dict]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return MongoDB documents most similar to query.
Use the knnBeta Operator available in MongoDB Atlas Searc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
1085b2eba275-9 | pre_filter: Optional Dictionary of argument(s) to prefilter on document
fields.
post_filter_pipeline: Optional Pipeline of MongoDB aggregation stages
following the knnBeta search.
Returns:
List of Documents most similar to the query and score for each
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
1085b2eba275-10 | ) -> MongoDBAtlasVectorSearch:
"""Construct MongoDBAtlasVectorSearch wrapper from raw documents.
This is a user-friendly interface that:
1. Embeds documents.
2. Adds the documents to a provided MongoDB Atlas Vector Search index
(Lucene)
This is intended to... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
1085b2eba275-11 | )
"""
if collection is None:
raise ValueError("Must provide 'collection' named parameter.")
vecstore = cls(collection, embedding, **kwargs)
vecstore.add_texts(texts, metadatas=metadatas)
return vecstore | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
d13c8ecaa8b9-0 | Source code for langchain.vectorstores.clarifai
from __future__ import annotations
import logging
import os
import traceback
from typing import Any, Iterable, List, Optional, Tuple
import requests
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.vectorstor... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.