id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
0f02e8f768dc-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
0f02e8f768dc-8
from langchain import Annoy from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() index = Annoy.from_texts(texts, embeddings) """ embeddings = embedding.embed_documents(texts) return cls.__from( texts, embedd...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
0f02e8f768dc-9
embeddings = OpenAIEmbeddings() 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] em...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
0f02e8f768dc-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
1e901e7ca925-0
Source code for langchain.vectorstores.redis """Wrapper around Redis vector database.""" from __future__ import annotations import json import logging import uuid from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Literal, Mapping, Optional, Tuple, Type,...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
1e901e7ca925-1
"Redis cannot be used as a vector database without RediSearch >=2.4" "Please head to https://redis.io/docs/stack/search/quick_start/" "to know more about installing the RediSearch module within Redis Stack." ) logging.error(error_message) raise ValueError(error_message) def _check_index_exis...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
1e901e7ca925-2
redis_url: str, index_name: str, embedding_function: Callable, content_key: str = "content", metadata_key: str = "metadata", vector_key: str = "content_vector", relevance_score_fn: Optional[ Callable[[float], float] ] = _default_relevance_score, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
1e901e7ca925-3
) # Check if index exists if not _check_index_exists(self.client, self.index_name): # Define schema schema = ( TextField(name=self.content_key), TextField(name=self.metadata_key), VectorField( self.vector_key, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
1e901e7ca925-4
List[str]: List of ids added to the vectorstore """ ids = [] prefix = _redis_prefix(self.index_name) # Write data to redis pipeline = self.client.pipeline(transaction=False) for i, text in enumerate(texts): # Use provided values by default or fallback ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
1e901e7ca925-5
[docs] def similarity_search_limit_score( self, query: str, k: int = 4, score_threshold: float = 0.2, **kwargs: Any ) -> List[Document]: """ Returns the most similar indexed documents to the query text within the score_threshold range. Args: query (str): The qu...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
1e901e7ca925-6
return ( Query(base_query) .return_fields(*return_fields) .sort_by("vector_score") .paging(0, k) .dialect(2) ) [docs] def similarity_search_with_score( self, query: str, k: int = 4 ) -> List[Tuple[Document, float]]: """Return doc...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
1e901e7ca925-7
0 is dissimilar, 1 is most similar. """ if self.relevance_score_fn is None: raise ValueError( "relevance_score_fn must be provided to" " Redis constructor to normalize scores" ) docs_and_scores = self.similarity_search_with_score(query, k=k...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
1e901e7ca925-8
redis_url = get_from_dict_or_env(kwargs, "redis_url", "REDIS_URL") if "redis_url" in kwargs: kwargs.pop("redis_url") # Name of the search index if not given if not index_name: index_name = uuid.uuid4().hex # Create instance instance = cls( redi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
1e901e7ca925-9
Example: .. code-block:: python from langchain.vectorstores import Redis from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() redisearch = RediSearch.from_texts( texts, embedd...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
1e901e7ca925-10
except ValueError as e: raise ValueError(f"Your redis connected error: {e}") # Check if index exists try: client.ft(index_name).dropindex(delete_documents) logger.info("Drop index") return True except: # noqa: E722 # Index not exist ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
1e901e7ca925-11
return cls( redis_url, index_name, embedding.embed_query, content_key=content_key, metadata_key=metadata_key, vector_key=vector_key, **kwargs, ) [docs] def as_retriever(self, **kwargs: Any) -> RedisVectorStoreRetriever: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
1e901e7ca925-12
raise NotImplementedError("RedisVectorStoreRetriever does not support async") def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]: """Add documents to vectorstore.""" return self.vectorstore.add_documents(documents, **kwargs) async def aadd_documents( self, doc...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
5974d0f7a126-0
Source code for langchain.vectorstores.supabase from __future__ import annotations from itertools import repeat from typing import ( TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type, Union, ) import numpy as np from langchain.docstore.document import Document from langchain.embe...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
5974d0f7a126-1
embedding: Embeddings, table_name: str, query_name: Union[str, None] = None, ) -> None: """Initialize with supabase client.""" try: import supabase # noqa: F401 except ImportError: raise ValueError( "Could not import supabase python pa...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
5974d0f7a126-2
if not table_name: raise ValueError("Supabase document table_name is required.") embeddings = embedding.embed_documents(texts) docs = cls._texts_to_documents(texts, metadatas) _ids = cls._add_vectors(client, table_name, embeddings, docs) return cls( client=client,...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
5974d0f7a126-3
self, query: List[float], k: int ) -> List[Tuple[Document, float]]: match_documents_params = dict(query_embedding=query, match_count=k) res = self._client.rpc(self.query_name, match_documents_params).execute() match_result = [ ( Document( metad...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
5974d0f7a126-4
metadatas: Optional[Iterable[dict[Any, Any]]] = None, ) -> List[Document]: """Return list of Documents from list of texts and metadatas.""" if metadatas is None: metadatas = repeat({}) docs = [ Document(page_content=text, metadata=metadata) for text, metad...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
5974d0f7a126-5
return id_list [docs] def max_marginal_relevance_search_by_vector( self, embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
5974d0f7a126-6
k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
5974d0f7a126-7
$$;``` """ embedding = self._embedding.embed_documents([query]) docs = self.max_marginal_relevance_search_by_vector( embedding[0], k, fetch_k, lambda_mult=lambda_mult ) return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
a3871bec6d49-0
Source code for langchain.vectorstores.qdrant """Wrapper around Qdrant vector database.""" from __future__ import annotations import uuid import warnings from hashlib import md5 from operator import itemgetter from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional,...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
a3871bec6d49-1
"""Initialize with necessary components.""" try: import qdrant_client except ImportError: raise ValueError( "Could not import qdrant-client python package. " "Please install it with `pip install qdrant-client`." ) if not isinsta...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
a3871bec6d49-2
) self._embeddings_function = embeddings self.embeddings = None 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: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
a3871bec6d49-3
metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
a3871bec6d49-4
return list(map(itemgetter(0), results)) [docs] def similarity_search_with_score( self, query: str, k: int = 4, filter: Optional[MetadataFilter] = None ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Args: query: Text to look up documents similar to. ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
a3871bec6d49-5
Defaults to 20. lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. Returns: List of Do...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
a3871bec6d49-6
path: Optional[str] = None, collection_name: Optional[str] = None, distance_func: str = "Cosine", content_payload_key: str = CONTENT_KEY, metadata_payload_key: str = METADATA_KEY, **kwargs: Any, ) -> Qdrant: """Construct Qdrant wrapper from a list of texts. Ar...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
a3871bec6d49-7
Default: None timeout: Timeout for REST and gRPC API requests. Default: 5.0 seconds for REST and unlimited for gRPC host: Host name of Qdrant service. If url and host are None, set to 'localhost'. Default: None path: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
a3871bec6d49-8
try: 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 ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
a3871bec6d49-9
client=client, collection_name=collection_name, embeddings=embedding, content_payload_key=content_payload_key, metadata_payload_key=metadata_payload_key, ) @classmethod def _build_payloads( cls, texts: Iterable[str], metadatas: Opti...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
a3871bec6d49-10
elif isinstance(value, list): for _value in value: if isinstance(_value, dict): out.extend(self._build_condition(f"{key}[]", _value)) else: out.extend(self._build_condition(f"{key}", _value)) else: out.append( ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
4ee6122299b8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-5
and ("user" in addr) 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....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-6
# Datatype isnt compatible if dtype == DataType.UNKNOWN or dtype == DataType.NONE: logger.error( "Failure to create collection, unrecognized dtype for key: %s", key, ) raise ValueError(f"Unrecogni...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-7
schema = self.col.schema 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 informati...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-11
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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
4ee6122299b8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
0886f4c70711-0
Source code for langchain.vectorstores.chroma """Wrapper around ChromaDB embeddings platform.""" from __future__ import annotations import logging import uuid from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Type import numpy as np from langchain.docstore.document import Document from langc...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
0886f4c70711-1
vectorstore = Chroma("langchain_store", embeddings.embed_query) """ _LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain" def __init__( self, collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, embedding_function: Optional[Embeddings] = None, persist_directory: Optional[str...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
0886f4c70711-2
def __query_collection( self, query_texts: Optional[List[str]] = None, query_embeddings: Optional[List[List[float]]] = None, n_results: int = 4, where: Optional[Dict[str, str]] = None, **kwargs: Any, ) -> List[Document]: """Query the chroma collection.""" ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
0886f4c70711-3
ids (Optional[List[str]], optional): Optional list of IDs. Returns: List[str]: List of IDs of the added texts. """ # TODO: Handle the case where the user doesn't provide ids on the Collection if ids is None: ids = [str(uuid.uuid1()) for _ in texts] embeddi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
0886f4c70711-4
"""Return docs most similar to embedding vector. Args: embedding (str): Embedding to look up documents similar to. k (int): Number of Documents to return. Defaults to 4. filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. Returns: List...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
0886f4c70711-5
[docs] def max_marginal_relevance_search_by_vector( self, embedding: List[float], k: int = DEFAULT_K, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any, ) -> List[Document]: """Return docs selected u...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
0886f4c70711-6
return selected_results [docs] def max_marginal_relevance_search( self, query: str, k: int = DEFAULT_K, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any, ) -> List[Document]: """Return docs selected...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
0886f4c70711-7
"""Gets the collection. Args: include (Optional[List[str]]): List of fields to include from db. Defaults to None. """ if include is not None: return self._collection.get(include=include) else: return self._collection.get() [docs] def...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
0886f4c70711-8
) -> Chroma: """Create a Chroma vectorstore from a raw documents. If a persist_directory is specified, the collection will be persisted there. Otherwise, the data will be ephemeral in-memory. Args: texts (List[str]): List of texts to add to the collection. collect...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
0886f4c70711-9
**kwargs: Any, ) -> Chroma: """Create a Chroma vectorstore from a list of documents. If a persist_directory is specified, the collection will be persisted there. Otherwise, the data will be ephemeral in-memory. Args: collection_name (str): Name of the collection to create...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
de8aeb1155e4-0
Source code for langchain.vectorstores.deeplake """Wrapper around Activeloop Deep Lake.""" from __future__ import annotations import logging import uuid from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple import numpy as np from langchain.docstore.document imp...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
de8aeb1155e4-1
returns: nearest_indices: List, indices of nearest neighbors """ if data_vectors.shape[0] == 0: return [], [] # Calculate the distance between the query_vector and all data_vectors distances = distance_metric_map[distance_metric](query_embedding, data_vectors) nearest_indices = np.ar...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
de8aeb1155e4-2
embeddings = OpenAIEmbeddings() vectorstore = DeepLake("langchain_store", embeddings.embed_query) """ _LANGCHAIN_DEFAULT_DEEPLAKE_PATH = "./deeplake/" def __init__( self, dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH, token: Optional[str] = None, embedd...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
de8aeb1155e4-3
if self.verbose: print( f"Deep Lake Dataset in {dataset_path} already exists, " f"loading from the storage" ) self.ds.summary() else: if "overwrite" in kwargs: del kwargs["overwrite"] ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
de8aeb1155e4-4
**kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. Args: texts (Iterable[str]): Texts to add to the vectorstore. metadatas (Optional[List[dict]], optional): Optional list of metadatas. ids (Optional[List[str]], opti...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
de8aeb1155e4-5
if batch_size == 0: return [] batched = [ elements[i : i + batch_size] for i in range(0, len(elements), batch_size) ] ingest().eval( batched, self.ds, num_workers=min(self.num_workers, len(batched) // max(self.num_workers, 1)), ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
de8aeb1155e4-6
take [Deep Lake filter] (https://docs.deeplake.ai/en/latest/deeplake.core.dataset.html#deeplake.core.dataset.Dataset.filter) Defaults to None. maximal_marginal_relevance: Whether to use maximal marginal relevance. Defaults to False. fetch_k: Number of ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
de8aeb1155e4-7
distance_metric=distance_metric.lower(), ) view = view[indices] if use_maximal_marginal_relevance: lambda_mult = kwargs.get("lambda_mult", 0.5) indices = maximal_marginal_relevance( query_emb, embeddings[indices]...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
de8aeb1155e4-8
maximal_marginal_relevance: Whether to use maximal marginal relevance. Defaults to False. fetch_k: Number of Documents to fetch to pass to MMR algorithm. Defaults to 20. return_score: Whether to return the score. Defaults to False. Returns: Lis...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
de8aeb1155e4-9
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. Returns: List[Tuple[Document, float]]: List of documents most similar to the query text with distance in float. """ return self._search_helper( query=query, k=k, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
de8aeb1155e4-10
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...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
de8aeb1155e4-11
) -> DeepLake: """Create a Deep Lake dataset from a raw documents. If a dataset_path is specified, the dataset will be persisted in that location, otherwise by default at `./deeplake` Args: path (str, pathlib.Path): - The full path to the dataset. Can be: - De...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
de8aeb1155e4-12
dataset_path=dataset_path, embedding_function=embedding, **kwargs ) deeplake_dataset.add_texts(texts=texts, metadatas=metadatas, ids=ids) return deeplake_dataset [docs] def delete( self, ids: Any[List[str], None] = None, filter: Any[Dict[str, str], None] = None, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
de8aeb1155e4-13
try: import deeplake except ImportError: raise ValueError( "Could not import deeplake python package. " "Please install it with `pip install deeplake`." ) deeplake.delete(path, large_ok=True, force=True) [docs] def delete_dataset(sel...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
6ae9020b76e0-0
Source code for langchain.vectorstores.weaviate """Wrapper around weaviate vector database.""" from __future__ import annotations import datetime from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type from uuid import uuid4 import numpy as np from langchain.docstore.document import Document from ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
6ae9020b76e0-1
if weaviate_api_key is not None else None ) client = weaviate.Client(weaviate_url, auth_client_secret=auth) return client def _default_score_normalizer(val: float) -> float: return 1 - 1 / (1 + np.exp(val)) def _json_serializable(value: Any) -> Any: if isinstance(value, datetime.datetime): ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
6ae9020b76e0-2
) if not isinstance(client, weaviate.Client): raise ValueError( f"client should be an instance of weaviate.Client, got {type(client)}" ) self._client = client self._index_name = index_name self._embedding = embedding self._text_key = text_k...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
6ae9020b76e0-3
class_name=self._index_name, uuid=_id, vector=vector, ) ids.append(_id) return ids [docs] def similarity_search( self, query: str, k: int = 4, **kwargs: Any ) -> List[Document]: """Return docs most similar to query. ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
6ae9020b76e0-4
if kwargs.get("where_filter"): query_obj = query_obj.with_where(kwargs.get("where_filter")) if kwargs.get("additional"): query_obj = query_obj.with_additional(kwargs.get("additional")) result = query_obj.with_near_text(content).with_limit(k).do() if "errors" in result: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
6ae9020b76e0-5
k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
6ae9020b76e0-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
6ae9020b76e0-7
raise ValueError( "_embedding cannot be None for similarity_search_with_score" ) content: Dict[str, Any] = {"concepts": [query]} if kwargs.get("search_distance"): content["certainty"] = kwargs.get("search_distance") query_obj = self._client.query.get(self....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
6ae9020b76e0-8
""" if self._relevance_score_fn is None: raise ValueError( "relevance_score_fn must be provided to" " Weaviate constructor to normalize scores" ) docs_and_scores = self.similarity_search_with_score(query, k=k, **kwargs) return [ ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
6ae9020b76e0-9
text_key = "text" schema = _default_schema(index_name) attributes = list(metadatas[0].keys()) if metadatas else None # check whether the index already exists if not client.schema.contains(schema): client.schema.create_class(schema) with client.batch as batch: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
6ae9020b76e0-10
relevance_score_fn=relevance_score_fn, by_text=by_text, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
c3d2f6527c31-0
Source code for langchain.vectorstores.typesense """Wrapper around Typesense vector search""" from __future__ import annotations import uuid from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings fro...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
c3d2f6527c31-1
*, typesense_collection_name: Optional[str] = None, text_key: str = "text", ): """Initialize with Typesense client.""" try: from typesense import Client except ImportError: raise ValueError( "Could not import typesense python package. "...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
c3d2f6527c31-2
] def _create_collection(self, num_dim: int) -> None: fields = [ {"name": "vec", "type": "float[]", "num_dim": num_dim}, {"name": f"{self._text_key}", "type": "string"}, {"name": ".*", "type": "auto"}, ] self._typesense_client.collections.create( ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
c3d2f6527c31-3
self, query: str, k: int = 4, filter: Optional[str] = "", ) -> List[Tuple[Document, float]]: """Return typesense documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to return. De...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
c3d2f6527c31-4
k: Number of Documents to return. Defaults to 4. filter: typesense filter_by expression to filter documents on Returns: List of Documents most similar to the query and score for each """ docs_and_score = self.similarity_search_with_score(query, k=k, filter=filter) ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
c3d2f6527c31-5
} typesense_api_key = typesense_api_key or get_from_env( "typesense_api_key", "TYPESENSE_API_KEY" ) client_config = { "nodes": [node], "api_key": typesense_api_key, "connection_timeout_seconds": connection_timeout_seconds, } return ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
f62bb8e7646a-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...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
f62bb8e7646a-1
""" Get or create a collection. Returns [Collection, bool] where the bool is True if the collection was created. """ created = False collection = cls.get_by_name(session, name) if collection: return collection, created collection = cls(name=name, cmeta...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
f62bb8e7646a-2
""" VectorStore implementation using AnalyticDB. AnalyticDB is a distributed full PostgresSQL syntax cloud-native database. - `connection_string` is a postgres connection string. - `embedding_function` any embedding function implementing `langchain.embeddings.base.Embeddings` interface. - `c...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
f62bb8e7646a-3
engine = sqlalchemy.create_engine(self.connection_string) conn = engine.connect() return conn [docs] def create_tables_if_not_exists(self) -> None: Base.metadata.create_all(self._conn) [docs] def drop_tables(self) -> None: Base.metadata.drop_all(self._conn) [docs] def create_col...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html