id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
53
121
9b163cce2644-7
) return [doc for doc, _ in docs_and_scores] [docs] def similarity_search( self, query: str, k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any, ) -> List[Document]: """Return docs most similar to query. Ar...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
9b163cce2644-8
k: Number of Documents to return. Defaults to 4. fetch_k: Number of Documents to fetch before filtering to pass to MMR algorithm. lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
9b163cce2644-9
selected_indices = [indices[0][i] for i in mmr_selected] selected_scores = [scores[0][i] for i in mmr_selected] docs_and_scores = [] for i, score in zip(selected_indices, selected_scores): if i == -1: # This happens when not enough docs are returned. c...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
9b163cce2644-10
Returns: List of Documents selected by maximal marginal relevance. """ docs_and_scores = self.max_marginal_relevance_search_with_score_by_vector( embedding, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult, filter=filter ) return [doc for doc, _ in docs_and_scores] [...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
9b163cce2644-11
[docs] def merge_from(self, target: FAISS) -> None: """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 isinstan...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
9b163cce2644-12
) -> FAISS: faiss = dependable_faiss_import() index = faiss.IndexFlatL2(len(embeddings[0])) vector = np.array(embeddings, dtype=np.float32) if normalize_L2: faiss.normalize_L2(vector) index.add(vector) documents = [] if ids is None: ids = [...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
9b163cce2644-13
faiss = FAISS.from_texts(texts, embeddings) """ embeddings = embedding.embed_documents(texts) return cls.__from( texts, embeddings, embedding, metadatas=metadatas, ids=ids, **kwargs, ) [docs] @classmethod def ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
9b163cce2644-14
"""Save FAISS index, docstore, and index_to_docstore_id to disk. Args: folder_path: folder path to save index, docstore, and index_to_docstore_id to. index_name: for saving with a specific index file name """ path = Path(folder_path) path.mkdir(exi...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
9b163cce2644-15
) # load docstore and index_to_docstore_id with open(path / "{index_name}.pkl".format(index_name=index_name), "rb") as f: docstore, index_to_docstore_id = pickle.load(f) return cls(embeddings.embed_query, index, docstore, index_to_docstore_id) def _similarity_search_with_relevanc...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
d26caf541610-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/stable/_modules/langchain/vectorstores/clarifai.html
d26caf541610-1
""" try: from clarifai.auth.helper import DEFAULT_BASE, ClarifaiAuthHelper from clarifai.client import create_stub except ImportError: raise ValueError( "Could not import clarifai python package. " "Please install it with `pip install c...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clarifai.html
d26caf541610-2
Args: text (str): Text to post. metadata (dict): Metadata to post. Returns: str: ID of the input. """ try: from clarifai_grpc.grpc.api import resources_pb2, service_pb2 from clarifai_grpc.grpc.api.status import status_code_pb2 ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clarifai.html
d26caf541610-3
to a Clarifai application. Application use base workflow that create and store embedding for each text. Make sure you are using a base workflow that is compatible with text (such as Language Understanding). Args: texts (Iterable[str]): Texts to add to the vectorstore. ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clarifai.html
d26caf541610-4
Args: query (str): Query text to search for. k (int): Number of results to return. Defaults to 4. filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. Returns: List[Document]: List of documents most simmilar to the query text. ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clarifai.html
d26caf541610-5
"Post searches failed, status: " + post_annotations_searches_response.status.description ) # Retrieve hits hits = post_annotations_searches_response.hits docs_and_scores = [] # Iterate over hits and retrieve metadata and text for hit in hits: ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clarifai.html
d26caf541610-6
user_id: Optional[str] = None, app_id: Optional[str] = None, pat: Optional[str] = None, number_of_docs: Optional[int] = None, api_base: Optional[str] = None, **kwargs: Any, ) -> Clarifai: """Create a Clarifai vectorstore from a list of texts. Args: ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clarifai.html
d26caf541610-7
api_base: Optional[str] = None, **kwargs: Any, ) -> Clarifai: """Create a Clarifai vectorstore from a list of documents. Args: user_id (str): User ID. app_id (str): App ID. documents (List[Document]): List of documents to add. pat (Optional[str...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/clarifai.html
9c8692f05232-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/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-1
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: "localhost:19530" uri (str): The uri of Milvus instance. Example uri: "http://randomw...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-2
Args: embedding_function (Embeddings): Function used to embed the text. collection_name (str): Which Milvus collection to use. Defaults to "LangChainCollection". connection_args (Optional[dict[str, any]]): The arguments for connection to Milvus/Zilliz ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-3
"RHNSW_SQ": {"metric_type": "L2", "params": {"ef": 10}}, "RHNSW_PQ": {"metric_type": "L2", "params": {"ef": 10}}, "IVF_HNSW": {"metric_type": "L2", "params": {"nprobe": 10, "ef": 10}}, "ANNOY": {"metric_type": "L2", "params": {"search_k": 10}}, "AUTOINDEX": {"metric_type"...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-4
if drop_old and isinstance(self.col, Collection): self.col.drop() self.col = None # Initialize the vector store self._init() def _create_connection_alias(self, connection_args: dict) -> str: """Create the connection to the Milvus server.""" from pymilvus impor...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-5
and (addr["user"] == tmp_user) ): logger.debug("Using previous connection: %s", con[0]) return con[0] # Generate a new connection if one doesnt exist alias = uuid4().hex try: connections.connect(alias=alias, **connection_args) ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-6
if dtype == DataType.UNKNOWN or dtype == DataType.NONE: logger.error( "Failure to create collection, unrecognized dtype for key: %s", key, ) raise ValueError(f"Unrecognized datatype for {key}.") #...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-7
for x in schema.fields: self.fields.append(x.name) # 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 pymil...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-8
using=self.alias, ) logger.debug( "Successfully created an index on collection: %s", self.collection_name, ) except MilvusException as e: logger.error( "Failed to create an index o...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-9
embedding and the columns are decided by the first metadata dict. Metada keys will need to be present for all inserted values. At the moment there is no None equivalent in Milvus. Args: texts (Iterable[str]): The texts to embed, it is assumed that they all fit in memo...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-10
for key, value in d.items(): if key in self.fields: insert_dict.setdefault(key, []).append(value) # Total insert count vectors: list = insert_dict[self._vector_field] total_count = len(vectors) pks: list[str] = [] assert isinstance(self...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-11
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 results for search. """ ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-12
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] def similarity_search_with_score( self, query: str, k: int = 4, param: O...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-13
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/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-14
# 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/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-15
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...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-16
to maximum diversity and 1 to minimum diversity. 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 lon...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-17
) # 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_relevance( np....
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
9c8692f05232-18
"LangChainCollection". connection_args (dict[str, Any], optional): Connection args to use. Defaults to DEFAULT_MILVUS_CONNECTION. consistency_level (str, optional): Which consistency level to use. Defaults to "Session". index_params (Optional[dict], op...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/milvus.html
adfb97a6e613-0
Source code for langchain.vectorstores.sklearn """ Wrapper around scikit-learn NearestNeighbors implementation. The vector store can be persisted in json, bson or parquet format. """ import json import math import os from abc import ABC, abstractmethod from typing import Any, Dict, Iterable, List, Literal, Optional, Tu...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/sklearn.html
adfb97a6e613-1
with open(self.persist_path, "r") as fp: return json.load(fp) class BsonSerializer(BaseSerializer): """Serializes data in binary json using the bson python package.""" def __init__(self, persist_path: str) -> None: super().__init__(persist_path) self.bson = guard_import("bson") @...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/sklearn.html
adfb97a6e613-2
raise exc else: os.remove(backup_path) else: self.pq.write_table(table, self.persist_path) def load(self) -> Any: table = self.pq.read_table(self.persist_path) df = table.to_pandas() return {col: series.tolist() for col, series in df.items()} S...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/sklearn.html
adfb97a6e613-3
self._serializer = serializer_cls(persist_path=self._persist_path) # data properties self._embeddings: List[List[float]] = [] self._texts: List[str] = [] self._metadatas: List[dict] = [] self._ids: List[str] = [] # cache properties self._embeddings_np: Any = np.as...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/sklearn.html
adfb97a6e613-4
**kwargs: Any, ) -> List[str]: _texts = list(texts) _ids = ids or [str(uuid4()) for _ in _texts] self._texts.extend(_texts) self._embeddings.extend(self._embedding_function.embed_documents(_texts)) self._metadatas.extend(metadatas or ([{}] * len(_texts))) self._ids.ex...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/sklearn.html
adfb97a6e613-5
query_embedding = self._embedding_function.embed_query(query) indices_dists = self._similarity_index_search_with_score( query_embedding, k=k, **kwargs ) return [ ( Document( page_content=self._texts[idx], metadata={"...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/sklearn.html
adfb97a6e613-6
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...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/sklearn.html
adfb97a6e613-7
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. lambda_mult: Number between 0 and 1 that determines the degree ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/sklearn.html
67e1e46d7fe8-0
Source code for langchain.vectorstores.tigris from __future__ import annotations import itertools from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple from langchain.embeddings.base import Embeddings from langchain.schema import Document from langchain.vectorstores import VectorStore if TYPE_CHECKING:...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tigris.html
67e1e46d7fe8-1
metadatas: Optional list of metadatas associated with the texts. ids: Optional list of ids for documents. Ids will be autogenerated if not provided. kwargs: vectorstore specific parameters Returns: List of ids from adding the texts into the vectorstore. ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tigris.html
67e1e46d7fe8-2
vector=vector, k=k, filter_by=filter ) docs: List[Tuple[Document, float]] = [] for r in result: docs.append( ( Document( page_content=r.doc["text"], metadata=r.doc.get("metadata") ), r...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tigris.html
67e1e46d7fe8-3
"text": t, "embeddings": e or [], "metadata": m or {}, } if _id: doc["id"] = _id docs.append(doc) return docs
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tigris.html
b5d17a829d69-0
Source code for langchain.vectorstores.qdrant """Wrapper around Qdrant vector database.""" from __future__ import annotations import uuid import warnings from itertools import islice from operator import itemgetter from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Opti...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-1
metadata_payload_key: str = METADATA_KEY, embedding_function: Optional[Callable] = None, # deprecated ): """Initialize with necessary components.""" try: import qdrant_client except ImportError: raise ValueError( "Could not import qdrant-clien...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-2
"Using `embeddings` as `embedding_function` which is deprecated" ) self._embeddings_function = embeddings self.embeddings = None [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[Sequence[str]] =...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-3
ids=batch_ids, vectors=self._embed_texts(batch_texts), payloads=self._build_payloads( batch_texts, batch_metadatas, self.content_payload_key, self.metadata_payload_key, ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-4
- 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 pr...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-5
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...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-6
**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. searc...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-7
**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:...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-8
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 cosine distance in float for each. Lower score represents more similarity. """ if filter is not No...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-9
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 d...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-10
) embeddings = [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.me...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-11
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_typ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-12
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. ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-13
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 per...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-14
import qdrant_client except ImportError: raise ValueError( "Could not import qdrant-client python package. " "Please install it with `pip install qdrant-client`." ) from qdrant_client.http import models as rest # Just do a single quick embe...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-15
metadatas_iterator = iter(metadatas or []) ids_iterator = iter(ids or [uuid.uuid4().hex for _ in iter(texts)]) while batch_texts := list(islice(texts_iterator, batch_size)): # Take the corresponding metadata and id for each text in a batch batch_metadatas = list(islice(metadatas_...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-16
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/stable/_modules/langchain/vectorstores/qdrant.html
b5d17a829d69-17
for condition in self._build_condition(key, value) ] ) def _embed_query(self, query: str) -> List[float]: """Embed query text. Used to provide backward compatibility with `embedding_function` argument. Args: query: Query text. Returns: List...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/qdrant.html
df5e2d8836cf-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...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/annoy.html
df5e2d8836cf-1
): """Initialize with necessary components.""" self.embedding_function = embedding_function self.index = index self.metric = metric self.docstore = docstore self.index_to_docstore_id = index_to_docstore_id [docs] def add_texts( self, texts: Iterable[str...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/annoy.html
df5e2d8836cf-2
Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. search_k: inspect up to search_k nodes which defaults to n_trees * n if not provided Returns: List of Documents most similar to the query and score ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/annoy.html
df5e2d8836cf-3
k: Number of Documents to return. Defaults to 4. search_k: inspect up to search_k nodes which defaults to n_trees * n if not provided Returns: List of Documents most similar to the query and score for each """ embedding = self.embedding_function(query) ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/annoy.html
df5e2d8836cf-4
Returns: List of Documents most similar to the embedding. """ docs_and_scores = self.similarity_search_with_score_by_index( docstore_index, k, search_k ) return [doc for doc, _ in docs_and_scores] [docs] def similarity_search( self, query: str, k: int =...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/annoy.html
df5e2d8836cf-5
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. """ idxs = self.index.get_nns_by_vector( ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/annoy.html
df5e2d8836cf-6
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...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/annoy.html
df5e2d8836cf-7
documents = [] for i, text in enumerate(texts): metadata = metadatas[i] if metadatas else {} documents.append(Document(page_content=text, metadata=metadata)) index_to_id = {i: str(uuid.uuid4()) for i in range(len(documents))} docstore = InMemoryDocstore( {inde...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/annoy.html
df5e2d8836cf-8
from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() index = Annoy.from_texts(texts, embeddings) """ embeddings = embedding.embed_documents(texts) return cls.__from( texts, embeddings, embedding, metadatas, metric, trees, n...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/annoy.html
df5e2d8836cf-9
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] return cls.__from( texts, embeddings, embedding, meta...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/annoy.html
df5e2d8836cf-10
Args: folder_path: folder path to load index, docstore, and index_to_docstore_id from. embeddings: Embeddings to use when generating queries. """ path = Path(folder_path) # load index separately since it is not picklable annoy = dependable_annoy_im...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/annoy.html
785b30d08915-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/stable/_modules/langchain/vectorstores/mongodb_atlas.html
785b30d08915-1
""" 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/stable/_modules/langchain/vectorstores/mongodb_atlas.html
785b30d08915-2
""" batch_size = kwargs.get("batch_size", DEFAULT_INSERT_BATCH_SIZE) _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...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/mongodb_atlas.html
785b30d08915-3
"""Return MongoDB documents most similar to query, along with scores. 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 earl...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/mongodb_atlas.html
785b30d08915-4
docs.append((Document(page_content=text, metadata=res), score)) return docs [docs] def similarity_search( self, query: str, k: int = 4, pre_filter: Optional[dict] = None, post_filter_pipeline: Optional[List[Dict]] = None, **kwargs: Any, ) -> List[Document]:...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/mongodb_atlas.html
785b30d08915-5
collection: Optional[Collection[MongoDBDocumentType]] = None, **kwargs: Any, ) -> MongoDBAtlasVectorSearch: """Construct MongoDBAtlasVectorSearch wrapper from raw documents. This is a user-friendly interface that: 1. Embeds documents. 2. Adds the documents to a provid...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/mongodb_atlas.html
5533f41d5f69-0
Source code for langchain.vectorstores.tair """Wrapper around Tair Vector.""" from __future__ import annotations import json import logging import uuid from typing import Any, Iterable, List, Optional, Type from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from langchain....
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tair.html
5533f41d5f69-1
index_type: str, data_type: str, **kwargs: Any, ) -> bool: index = self.client.tvs_get_index(self.index_name) if index is not None: logger.info("Index already exists") return False self.client.tvs_create_index( self.index_name, ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tair.html
5533f41d5f69-2
""" 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 simila...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tair.html
5533f41d5f69-3
if "tair_url" in kwargs: kwargs.pop("tair_url") distance_type = tairvector.DistanceMetric.InnerProduct if "distance_type" in kwargs: distance_type = kwargs.pop("distance_typ") index_type = tairvector.IndexType.HNSW if "index_type" in kwargs: index_type...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tair.html
5533f41d5f69-4
cls, documents: List[Document], embedding: Embeddings, metadatas: Optional[List[dict]] = None, index_name: str = "langchain", content_key: str = "content", metadata_key: str = "metadata", **kwargs: Any, ) -> Tair: texts = [d.page_content for d in docum...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tair.html
5533f41d5f69-5
# index not exist logger.info("Index does not exist") return False return True [docs] @classmethod def from_existing_index( cls, embedding: Embeddings, index_name: str = "langchain", content_key: str = "content", metadata_key: str = "metadat...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/tair.html
86da44d311d1-0
Source code for langchain.vectorstores.lancedb """Wrapper around LanceDB vector database""" from __future__ import annotations import uuid from typing import Any, Iterable, List, Optional from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from langchain.vectorstores.base i...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/lancedb.html
86da44d311d1-1
self._id_key = id_key self._text_key = text_key [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any, ) -> List[str]: """Turn texts into embedding and add it to the database...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/lancedb.html
86da44d311d1-2
""" embedding = self._embedding.embed_query(query) docs = self._connection.search(embedding).limit(k).to_df() return [ Document( page_content=row[self._text_key], metadata=row[docs.columns != self._text_key], ) for _, row in doc...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/lancedb.html
1f7b062637aa-0
Source code for langchain.vectorstores.hologres """VectorStore wrapper around a Hologres database.""" from __future__ import annotations import json import logging import uuid from typing import Any, Dict, Iterable, List, Optional, Tuple, Type from langchain.docstore.document import Document from langchain.embeddings.b...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/hologres.html
1f7b062637aa-1
'{"embedding":{"algorithm":"Graph", "distance_method":"SquaredEuclidean", "build_params":{"min_flush_proxima_row_count" : 1, "min_compaction_proxima_row_count" : 1, "max_total_size_to_merge_mb" : 2000}}}');""" ) self.conn.commit() def get_by_id(self, id: str) -> List[Tuple]: statement = ( ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/hologres.html
1f7b062637aa-2
params.append(key) params.append(val) filter_clause = "where " + " and ".join(conjuncts) sql = ( f"select document, metadata::text, " f"pm_approx_squared_euclidean_distance(array{json.dumps(embedding)}" f"::float4[], embedding) as distance from" ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/hologres.html
1f7b062637aa-3
self.connection_string = connection_string self.ndims = ndims self.table_name = table_name self.embedding_function = embedding_function self.pre_delete_table = pre_delete_table self.logger = logger or logging.getLogger(__name__) self.__post_init__() def __post_init__(...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/hologres.html
1f7b062637aa-4
embedding_function=embedding_function, ndims=ndims, table_name=table_name, pre_delete_table=pre_delete_table, ) store.add_embeddings( texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs ) return store [docs] def ad...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/hologres.html
1f7b062637aa-5
List of ids from adding the texts into the vectorstore. """ 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] self.add_embeddings(tex...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/hologres.html
1f7b062637aa-6
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] def similarity_search_with_score( ...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/hologres.html
1f7b062637aa-7
] return docs [docs] @classmethod def from_texts( cls: Type[Hologres], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ndims: int = ADA_TOKEN_COUNT, table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME, ids: Optional[List...
https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/hologres.html