id
stringlengths
14
16
text
stringlengths
31
3.14k
source
stringlengths
58
124
9baa826ab02b-10
else: search_query = _default_approximate_search_query( embedding, size, k, vector_field ) elif search_type == SCRIPT_SCORING_SEARCH: space_type = _get_kwargs_value(kwargs, "space_type", "l2") pre_filter = _get_kwargs_value(kwargs, "pre...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
9baa826ab02b-11
return documents [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, bulk_size: int = 500, **kwargs: Any, ) -> OpenSearchVectorSearch: """Construct OpenSearchVectorSearch wrapper from...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
9baa826ab02b-12
lead to more accurate but slower searches; default: 512 ef_construction: Size of the dynamic list used during k-NN graph creation. Higher values lead to more accurate graph but slower indexing speed; default: 512 m: Number of bidirectional links created for each new eleme...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
9baa826ab02b-13
vector_field = _get_kwargs_value(kwargs, "vector_field", "vector_field") text_field = _get_kwargs_value(kwargs, "text_field", "text") if is_appx_search: engine = _get_kwargs_value(kwargs, "engine", "nmslib") space_type = _get_kwargs_value(kwargs, "space_type", "l2") e...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
132d9862be1c-0
Source code for langchain.vectorstores.analyticdb """VectorStore wrapper around a Postgres/PGVector database.""" from __future__ import annotations import logging import uuid from typing import Any, Dict, Iterable, List, Optional, Tuple import sqlalchemy from sqlalchemy import REAL, Index from sqlalchemy.dialects.postg...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
132d9862be1c-1
passive_deletes=True, ) @classmethod def get_by_name(cls, session: Session, name: str) -> Optional["CollectionStore"]: return session.query(cls).filter(cls.name == name).first() @classmethod def get_or_create( cls, session: Session, name: str, cmetadata: Optio...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
132d9862be1c-2
cmetadata = sqlalchemy.Column(JSON, nullable=True) # custom_id : any user defined id custom_id = sqlalchemy.Column(sqlalchemy.String, nullable=True) # The following line creates an index named 'langchain_pg_embedding_vector_idx' langchain_pg_embedding_vector_idx = Index( "langchain_pg_embedding_...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
132d9862be1c-3
(default: False) - Useful for testing. """ def __init__( self, connection_string: str, embedding_function: Embeddings, collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, collection_metadata: Optional[dict] = None, pre_delete_collection: bool = Fals...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
132d9862be1c-4
Base.metadata.drop_all(self._conn) [docs] def create_collection(self) -> None: if self.pre_delete_collection: self.delete_collection() with Session(self._conn) as session: CollectionStore.get_or_create( session, self.collection_name, cmetadata=self.collection_m...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
132d9862be1c-5
""" if ids is None: ids = [str(uuid.uuid1()) for _ in texts] embeddings = self.embedding_function.embed_documents(list(texts)) if not metadatas: metadatas = [{} for _ in texts] with Session(self._conn) as session: collection = self.get_collection(sessi...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
132d9862be1c-6
embedding=embedding, k=k, filter=filter, ) [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. Args: ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
132d9862be1c-7
filter_clauses.append(filter_by_metadata) filter_by = sqlalchemy.and_(filter_by, *filter_clauses) results: List[QueryResult] = ( session.query( EmbeddingStore, func.l2_distance(EmbeddingStore.embedding, embedding).label("distance"), ) ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
132d9862be1c-8
Returns: List of Documents most similar to the query vector. """ docs_and_scores = self.similarity_search_with_score_by_vector( embedding=embedding, k=k, filter=filter ) return [doc for doc, _ in docs_and_scores] [docs] @classmethod def from_texts( ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
132d9862be1c-9
data=kwargs, key="connection_string", env_key="PGVECTOR_CONNECTION_STRING", ) if not connection_string: raise ValueError( "Postgres connection string is required" "Either pass it as a parameter" "or set the PGVECTOR_CONN...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
132d9862be1c-10
cls, driver: str, host: str, port: int, database: str, user: str, password: str, ) -> str: """Return connection string from database parameters.""" return f"postgresql+{driver}://{user}:{password}@{host}:{port}/{database}" By Harrison Chase ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
9cca7ce59b56-0
Source code for langchain.vectorstores.faiss """Wrapper around FAISS vector database.""" from __future__ import annotations import math import pickle import uuid from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple import numpy as np from langchain.docstore.base import Addabl...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
9cca7ce59b56-1
# This function converts the euclidean norm of normalized embeddings # (0 is most similar, sqrt(2) most dissimilar) # to a similarity function (0 to 1) return 1.0 - score / math.sqrt(2) [docs]class FAISS(VectorStore): """Wrapper around FAISS vector database. To use, you should have the ``faiss`` pyt...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
9cca7ce59b56-2
"If trying to add texts, the underlying docstore should support " f"adding items, which {self.docstore} does not" ) documents = [] for i, text in enumerate(texts): metadata = metadatas[i] if metadatas else {} documents.append(Document(page_content=text...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
9cca7ce59b56-3
metadatas: Optional list of metadatas associated with the texts. Returns: List of ids from adding the texts into the vectorstore. """ if not isinstance(self.docstore, AddableMixin): raise ValueError( "If trying to add texts, the underlying docstore should ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
9cca7ce59b56-4
embeddings = [te[1] for te in text_embeddings] return self.__add(texts, embeddings, metadatas, **kwargs) [docs] def similarity_search_with_score_by_vector( self, embedding: List[float], k: int = 4 ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Args: ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
9cca7ce59b56-5
k: Number of Documents to return. Defaults to 4. Returns: List of Documents most similar to the query and score for each """ embedding = self.embedding_function(query) docs = self.similarity_search_with_score_by_vector(embedding, k) return docs [docs] def similarit...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
9cca7ce59b56-6
return [doc for doc, _ in docs_and_scores] [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 maxim...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
9cca7ce59b56-7
docs = [] for i in selected_indices: if i == -1: # This happens when not enough docs are returned. continue _id = self.index_to_docstore_id[i] doc = self.docstore.search(_id) if not isinstance(doc, Document): raise V...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
9cca7ce59b56-8
"""Merge another FAISS object with the current one. Add the target FAISS to the current one. Args: target: FAISS object you wish to merge into the current one Returns: None. """ if not isinstance(self.docstore, AddableMixin): raise ValueError("...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
9cca7ce59b56-9
**kwargs: Any, ) -> FAISS: faiss = dependable_faiss_import() index = faiss.IndexFlatL2(len(embeddings[0])) index.add(np.array(embeddings, dtype=np.float32)) documents = [] for i, text in enumerate(texts): metadata = metadatas[i] if metadatas else {} do...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
9cca7ce59b56-10
faiss = FAISS.from_texts(texts, embeddings) """ embeddings = embedding.embed_documents(texts) return cls.__from( texts, embeddings, embedding, metadatas, **kwargs, ) [docs] @classmethod def from_embeddings( cls, ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
9cca7ce59b56-11
embeddings, embedding, metadatas, **kwargs, ) [docs] def save_local(self, folder_path: str, index_name: str = "index") -> None: """Save FAISS index, docstore, and index_to_docstore_id to disk. Args: folder_path: folder path to save index, docsto...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
9cca7ce59b56-12
embeddings: Embeddings to use when generating queries index_name: for saving with a specific index file name """ path = Path(folder_path) # load index separately since it is not picklable faiss = dependable_faiss_import() index = faiss.read_index( str(path...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
8131cf302e6f-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...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-1
See the following documentation for how to run a Milvus instance: https://milvus.io/docs/install_standalone-docker.md If looking for a hosted Milvus, take a looka this documentation: https://zilliz.com/cloud IF USING L2/IP metric IT IS HIGHLY SUGGESTED TO NORMALIZE YOUR DATA. The...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-2
write the client.pem path. ca_pem_path (str): If use tls two-way authentication, need to write 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 th...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-3
"IVF_SQ8": {"metric_type": "L2", "params": {"nprobe": 10}}, "IVF_PQ": {"metric_type": "L2", "params": {"nprobe": 10}}, "HNSW": {"metric_type": "L2", "params": {"ef": 10}}, "RHNSW_FLAT": {"metric_type": "L2", "params": {"ef": 10}}, "RHNSW_SQ": {"metric_type": "L2", "params...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-4
self._primary_field = "pk" # In order for compatiblility, the text field will need to be called "text" self._text_field = "text" # In order for compatbility, the vector field needs to be called "vector" self._vector_field = "vector" self.fields: list[str] = [] # Create th...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-5
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...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-6
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() ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-7
elif dtype == DataType.VARCHAR: fields.append(FieldSchema(key, DataType.VARCHAR, max_length=65_535)) else: fields.append(FieldSchema(key, dtype)) # Create the text field fields.append( FieldSchema(self._text_field, DataType.VARCHAR, max...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-8
# Since primary field is auto-id, no need to track it self.fields.remove(self._primary_field) def _get_index(self) -> Optional[dict[str, Any]]: """Return the vector index information if it exists""" from pymilvus import Collection if isinstance(self.col, Collection): ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-9
self._vector_field, index_params=self.index_params, using=self.alias, ) logger.debug( "Successfully created an index on collection: %s", self.collection_name, ) except ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-10
) -> 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...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-11
if not isinstance(self.col, Collection): self._init(embeddings, metadatas) # Dict to hold all insert columns insert_dict: dict[str, list] = { self._text_field: texts, self._vector_field: embeddings, } # Collect the metadata into the insert dict. ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-12
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: query (str): The text to search. k (int, opt...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-13
"""Perform a similarity search against the query string. Args: embedding (List[float]): The embedding vector to search. k (int, optional): How many results to return. Defaults to 4. param (dict, optional): The search params for the index type. Defaults to None...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-14
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. Defaults to None. expr (str, optional): Filtering expression. Defaults to None. ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-15
**kwargs: Any, ) -> List[Tuple[Document, float]]: """Perform a search on a query string and return results with score. For more information about the search parameters, take a look at the pymilvus documentation found here: https://milvus.io/api-reference/pymilvus/v2.2.6/Collection/se...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-16
) # Organize results. ret = [] for result in res[0]: meta = {x: result.entity.get(x) for x in output_fields} doc = Document(page_content=meta.pop(self._text_field), metadata=meta) pair = (doc, result.score) ret.append(pair) return ret [docs...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-17
Returns: List[Document]: Document results for search. """ if self.col is None: logger.debug("No existing collection to search.") return [] embedding = self.embedding_func.embed_query(query) return self.max_marginal_relevance_search_by_vector( ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-18
Defaults to None. expr (str, optional): Filtering expression. Defaults to None. timeout (int, optional): How long to wait before timeout error. Defaults to None. kwargs: Collection.search() keyword arguments. Returns: List[Document]: Document resul...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-19
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] # Get the new order of results. new_ordering = maximal_marginal_r...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
8131cf302e6f-20
embedding (Embeddings): Embedding function. metadatas (Optional[List[dict]]): Metadata for each text if it exists. Defaults to None. collection_name (str, optional): Collection name to use. Defaults to "LangChainCollection". connection_args (dict[str, ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
7ec076f78d89-0
Source code for langchain.vectorstores.annoy """Wrapper around Annoy vector database.""" from __future__ import annotations import os import pickle import uuid from configparser import ConfigParser from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple import numpy as np from l...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
7ec076f78d89-1
def __init__( self, embedding_function: Callable, index: Any, metric: str, docstore: Docstore, index_to_docstore_id: Dict[int, str], ): """Initialize with necessary components.""" self.embedding_function = embedding_function self.index = index ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
7ec076f78d89-2
docs.append((doc, dist)) return docs [docs] def similarity_search_with_score_by_vector( self, embedding: List[float], k: int = 4, search_k: int = -1 ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Args: query: Text to look up documents similar ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
7ec076f78d89-3
docstore_index, k, search_k=search_k, include_distances=True ) return self.process_index_results(idxs, dists) [docs] def similarity_search_with_score( self, query: str, k: int = 4, search_k: int = -1 ) -> List[Tuple[Document, float]]: """Return docs most similar to query. ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
7ec076f78d89-4
Returns: List of Documents most similar to the embedding. """ docs_and_scores = self.similarity_search_with_score_by_vector( embedding, k, search_k ) return [doc for doc, _ in docs_and_scores] [docs] def similarity_search_by_index( self, docstore_index:...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
7ec076f78d89-5
Returns: List of Documents most similar to the query. """ docs_and_scores = self.similarity_search_with_score(query, k, search_k) return [doc for doc, _ in docs_and_scores] [docs] def max_marginal_relevance_search_by_vector( self, embedding: List[float], k:...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
7ec076f78d89-6
embeddings, k=k, lambda_mult=lambda_mult, ) # ignore the -1's if not enough docs are returned/indexed selected_indices = [idxs[i] for i in mmr_selected if i != -1] docs = [] for i in selected_indices: _id = self.index_to_docstore_id[i] ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
7ec076f78d89-7
embedding, k, fetch_k, lambda_mult=lambda_mult ) return docs @classmethod def __from( cls, texts: List[str], embeddings: List[List[float]], embedding: Embeddings, metadatas: Optional[List[dict]] = None, metric: str = DEFAULT_METRIC, trees: ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
7ec076f78d89-8
docstore = InMemoryDocstore( {index_to_id[i]: doc for i, doc in enumerate(documents)} ) return cls(embedding.embed_query, index, metric, docstore, index_to_id) [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
7ec076f78d89-9
embeddings = embedding.embed_documents(texts) return cls.__from( texts, embeddings, embedding, metadatas, metric, trees, n_jobs, **kwargs ) [docs] @classmethod def from_embeddings( cls, text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
7ec076f78d89-10
text_embeddings = embeddings.embed_documents(texts) text_embedding_pairs = list(zip(texts, text_embeddings)) db = Annoy.from_embeddings(text_embedding_pairs, embeddings) """ texts = [t[0] for t in text_embeddings] embeddings = [t[1] for t in text_embeddings] ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
7ec076f78d89-11
[docs] @classmethod def load_local( cls, folder_path: str, embeddings: Embeddings, ) -> Annoy: """Load Annoy index, docstore, and index_to_docstore_id to disk. Args: folder_path: folder path to load index, docstore, and index_to_docstore_id ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
ec2e1d66e9df-0
Source code for langchain.vectorstores.weaviate """Wrapper around weaviate vector database.""" from __future__ import annotations from typing import Any, Dict, Iterable, List, Optional, Type from uuid import uuid4 import numpy as np from langchain.docstore.document import Document from langchain.embeddings.base import ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
ec2e1d66e9df-1
if weaviate_api_key is not None else None ) client = weaviate.Client(weaviate_url, auth_client_secret=auth) return client [docs]class Weaviate(VectorStore): """Wrapper around Weaviate vector database. To use, you should have the ``weaviate-client`` python package installed. Example: ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
ec2e1d66e9df-2
if attributes is not None: self._query_attrs.extend(attributes) [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> List[str]: """Upload texts with metadata (properties) to Weaviate.""" from weav...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
ec2e1d66e9df-3
if kwargs.get("search_distance"): content["certainty"] = kwargs.get("search_distance") query_obj = self._client.query.get(self._index_name, self._query_attrs) if kwargs.get("where_filter"): query_obj = query_obj.with_where(kwargs.get("where_filter")) result = query_obj.wi...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
ec2e1d66e9df-4
result = query_obj.with_near_vector(vector).with_limit(k).do() if "errors" in result: raise ValueError(f"Error during query: {result['errors']}") docs = [] for res in result["data"]["Get"][self._index_name]: text = res.pop(self._text_key) docs.append(Document(...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
ec2e1d66e9df-5
) return self.max_marginal_relevance_search_by_vector( embedding, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult, **kwargs ) [docs] def max_marginal_relevance_search_by_vector( self, embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult:...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
ec2e1d66e9df-6
.with_near_vector(vector) .with_limit(fetch_k) .do() ) payload = results["data"]["Get"][self._index_name] embeddings = [result["_additional"]["vector"] for result in payload] mmr_selected = maximal_marginal_relevance( np.array(embedding), embeddings, k...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
ec2e1d66e9df-7
embeddings = OpenAIEmbeddings() weaviate = Weaviate.from_texts( texts, embeddings, weaviate_url="http://localhost:8080" ) """ client = _create_weaviate_client(**kwargs) from weaviate.util import get_valid...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
ec2e1d66e9df-8
"class_name": index_name, } if embeddings is not None: params["vector"] = embeddings[i] batch.add_data_object(**params) batch.flush() return cls(client, index_name, text_key, embedding, attributes) By Harrison Chase © Cop...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
8164e1dcb879-0
Source code for langchain.vectorstores.myscale """Wrapper around MyScale vector database.""" from __future__ import annotations import json import logging from hashlib import sha1 from threading import Thread from typing import Any, Dict, Iterable, List, Optional, Tuple from pydantic import BaseSettings from langchain....
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
8164e1dcb879-1
column_map (Dict) : Column type map to project column name onto langchain semantics. Must have keys: `text`, `id`, `vector`, must be same size to number of columns. For example: .. code-block:: python { ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
8164e1dcb879-2
MyScale can not only search with simple vector indexes, it also supports complex query with multiple conditions, constraints and even sub-queries. For more information, please visit [myscale official site](https://docs.myscale.com/en/overview/) """ def __init__( self, embeddi...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
8164e1dcb879-3
for k in ["id", "vector", "text", "metadata"]: assert k in self.config.column_map assert self.config.metric in ["ip", "cosine", "l2"] # initialize the schema dim = len(embedding.embed_query("try this out")) index_params = ( ", " + ",".join([f"'{k}={v}'" for k, v i...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
8164e1dcb879-4
""" self.dim = dim self.BS = "\\" self.must_escape = ("\\", "'") self.embedding_function = embedding.embed_query self.dist_order = "ASC" if self.config.metric in ["cosine", "l2"] else "DESC" # Create a connection to myscale self.client = get_client( ho...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
8164e1dcb879-5
{','.join(_data)} """ return i_str def _insert(self, transac: Iterable, column_names: Iterable[str]) -> None: _i_str = self._build_istr(transac, column_names) self.client.command(_i_str) [docs] def add_texts( self, texts: Iterable[str], metadatas: O...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
8164e1dcb879-6
} metadatas = metadatas or [{} for _ in texts] column_names[colmap_["metadata"]] = map(json.dumps, metadatas) assert len(set(colmap_) - set(column_names)) >= 0 keys, values = zip(*column_names.items()) try: t = None for v in self.pgbar( zip...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
8164e1dcb879-7
config: Optional[MyScaleSettings] = None, text_ids: Optional[Iterable[str]] = None, batch_size: int = 32, **kwargs: Any, ) -> MyScale: """Create Myscale wrapper with existing texts Args: embedding_function (Embeddings): Function to extract text embedding ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
8164e1dcb879-8
Returns: repr: string to show connection info and data schema """ _repr = f"\033[92m\033[1m{self.config.database}.{self.config.table} @ " _repr += f"{self.config.host}:{self.config.port}\033[0m\n\n" _repr += f"\033[1musername: {self.config.username}\033[0m\n\nTable Schema:\n"...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
8164e1dcb879-9
SELECT {self.config.column_map['text']}, {self.config.column_map['metadata']}, dist FROM {self.config.database}.{self.config.table} {where_str} ORDER BY distance({self.config.column_map['vector']}, [{q_emb_str}]) AS dist {self.dist_order} ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
8164e1dcb879-10
self, embedding: List[float], k: int = 4, where_str: Optional[str] = None, **kwargs: Any, ) -> List[Document]: """Perform a similarity search with MyScale by vectors Args: query (str): query string k (int, optional): Top K neighbors to retrieve...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
8164e1dcb879-11
[docs] def similarity_search_with_relevance_scores( self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any ) -> List[Tuple[Document, float]]: """Perform a similarity search with MyScale Args: query (str): query string k (int, optional): Top K ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
8164e1dcb879-12
return [] [docs] def drop(self) -> None: """ Helper function: Drop data """ self.client.command( f"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}" ) @property def metadata_column(self) -> str: return self.config.column_map["metadata...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
dd9bdee78b52-0
Source code for langchain.vectorstores.base """Interface for vector stores.""" from __future__ import annotations import asyncio from abc import ABC, abstractmethod from functools import partial from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, TypeVar from pydantic import BaseModel, Field, root_vali...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
dd9bdee78b52-1
raise NotImplementedError [docs] def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]: """Run more documents through the embeddings and add to the vectorstore. Args: documents (List[Document]: Documents to add to the vectorstore. Returns: List...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
dd9bdee78b52-2
[docs] 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. """ docs_and_similaritie...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
dd9bdee78b52-3
# asynchronous in the vector store implementations. func = partial(self.similarity_search, query, k, **kwargs) return await asyncio.get_event_loop().run_in_executor(None, func) [docs] def similarity_search_by_vector( self, embedding: List[float], k: int = 4, **kwargs: Any ) -> List[Docume...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
dd9bdee78b52-4
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 amon...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
dd9bdee78b52-5
) return await asyncio.get_event_loop().run_in_executor(None, func) [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]: """Ret...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
dd9bdee78b52-6
cls: Type[VST], documents: List[Document], embedding: Embeddings, **kwargs: Any, ) -> VST: """Return VectorStore initialized from documents and embeddings.""" texts = [d.page_content for d in documents] metadatas = [d.metadata for d in documents] return cls.fr...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
dd9bdee78b52-7
texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> VST: """Return VectorStore initialized from texts and embeddings.""" raise NotImplementedError [docs] def as_retriever(self, **kwargs: Any) -> BaseRetriever: return...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
dd9bdee78b52-8
docs = self.vectorstore.max_marginal_relevance_search( 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.se...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
559767156993-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 Any, Dict, Iterable, List, Optional, Tuple from langchain.docstore.document import Document from langchain.embeddings.bas...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
559767156993-1
# VectorStore, which defines a common interface for all vector database # implementations. By inheriting from the ABC class, ElasticVectorSearch can be # defined as an abstract base class itself, allowing the creation of subclasses with # their own specific implementations. If you plan to subclass ElasticVectorSearch, ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
559767156993-2
navigating to the "Deployments" page. To obtain your Elastic Cloud password for the default "elastic" user: 1. Log in to the Elastic Cloud console at https://cloud.elastic.co 2. Go to "Security" > "Users" 3. Locate the "elastic" user and click "Edit" 4. Click "Reset password" 5. Follow the promp...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
559767156993-3
ValueError: If the elasticsearch python package is not installed. """ def __init__(self, elasticsearch_url: str, index_name: str, embedding: Embeddings): """Initialize with necessary components.""" try: import elasticsearch except ImportError: raise ValueError( ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
559767156993-4
"Please install it with `pip install elasticsearch`." ) requests = [] ids = [] 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: ...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
559767156993-5
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]...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
559767156993-6
def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> ElasticVectorSearch: """Construct ElasticVectorSearch wrapper from raw documents. This is a user-friendly interface that: 1. E...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
559767156993-7
) index_name = kwargs.get("index_name", uuid.uuid4().hex) embeddings = embedding.embed_documents(texts) dim = len(embeddings[0]) mapping = _default_text_mapping(dim) # check to see if the index already exists try: client.indices.get(index=index_name) e...
/content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html