id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
658aeb7f3185-3
ids = [md5(text.encode("utf-8")).hexdigest() for text in texts] for i, doc in enumerate(texts): doc_id = ids[i] metadata = metadatas[i] if metadatas else {} succeeded = self._index_doc(doc_id, doc, metadata) if not succeeded: self._delete_doc(doc_i...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
658aeb7f3185-4
"start": 0, "num_results": k, "context_config": { "sentences_before": 3, "sentences_after": 3, }, "corpus_key": [ ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
658aeb7f3185-5
"""Return Vectara documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 5. filter: Dictionary of argument(s) to filter on metadata. For example a filter can be "doc....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
658aeb7f3185-6
vectara.add_texts(texts, metadatas) return vectara [docs] def as_retriever(self, **kwargs: Any) -> VectaraRetriever: return VectaraRetriever(vectorstore=self, **kwargs) class VectaraRetriever(VectorStoreRetriever): vectorstore: Vectara search_kwargs: dict = Field(default_factory=lambda: {"alp...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
1988082ebfab-0
Source code for langchain.vectorstores.zilliz from __future__ import annotations import logging from typing import Any, List, Optional from langchain.embeddings.base import Embeddings from langchain.vectorstores.milvus import Milvus logger = logging.getLogger(__name__) [docs]class Zilliz(Milvus): def _create_index(...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html
1988082ebfab-1
"Failed to create an index on collection: %s", self.collection_name ) raise e [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = "LangChainCollecti...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html
1988082ebfab-2
Zilliz: Zilliz Vector Store """ vector_db = cls( embedding_function=embedding, collection_name=collection_name, connection_args=connection_args, consistency_level=consistency_level, index_params=index_params, search_params=search_pa...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html
076c198ce78a-0
Source code for langchain.vectorstores.base """Interface for vector stores.""" from __future__ import annotations import asyncio import warnings from abc import ABC, abstractmethod from functools import partial from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, TypeVar from pydantic import BaseModel, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
076c198ce78a-1
Args: documents (List[Document]: Documents to add to the vectorstore. Returns: List[str]: List of IDs of the added texts. """ # TODO: Handle the case where the user doesn't provide ids on the Collection texts = [doc.page_content for doc in documents] metad...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
076c198ce78a-2
self, query: str, search_type: str, **kwargs: Any ) -> List[Document]: """Return docs most similar to query using specified search type.""" if search_type == "similarity": return await self.asimilarity_search(query, **kwargs) elif search_type == "mmr": return await se...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
076c198ce78a-3
query, k=k, **kwargs ) if any( similarity < 0.0 or similarity > 1.0 for _, similarity in docs_and_similarities ): warnings.warn( "Relevance scores must be between" f" 0 and 1, got {docs_and_similarities}" ) s...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
076c198ce78a-4
func = partial(self.similarity_search_with_relevance_scores, query, k, **kwargs) return await asyncio.get_event_loop().run_in_executor(None, func) [docs] async def asimilarity_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/base.html
076c198ce78a-5
[docs] def max_marginal_relevance_search( self, query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimiz...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
076c198ce78a-6
) 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...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
076c198ce78a-7
) -> 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.from_texts(texts, embedding, metadatas=metadatas, **kwargs) [docs] @classmethod async def afrom_document...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
076c198ce78a-8
class VectorStoreRetriever(BaseRetriever, BaseModel): vectorstore: VectorStore search_type: str = "similarity" search_kwargs: dict = Field(default_factory=dict) class Config: """Configuration for this pydantic object.""" arbitrary_types_allowed = True @root_validator() def valida...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
076c198ce78a-9
query, **self.search_kwargs ) else: raise ValueError(f"search_type of {self.search_type} not allowed.") return docs async def aget_relevant_documents(self, query: str) -> List[Document]: if self.search_type == "similarity": docs = await self.vectorstore.as...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
20346f865f71-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html
20346f865f71-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html
20346f865f71-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html
2b5c46bced14-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
2b5c46bced14-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
2b5c46bced14-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
2b5c46bced14-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
2b5c46bced14-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
2b5c46bced14-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
2b5c46bced14-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
2b5c46bced14-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
2b5c46bced14-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
2b5c46bced14-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
2b5c46bced14-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
28616f5d585f-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
28616f5d585f-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
28616f5d585f-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
28616f5d585f-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
28616f5d585f-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
28616f5d585f-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
28616f5d585f-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
28616f5d585f-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
28616f5d585f-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
28616f5d585f-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
28616f5d585f-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
28616f5d585f-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
28616f5d585f-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
8e082a667bb3-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
8e082a667bb3-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
8e082a667bb3-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
8e082a667bb3-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
8e082a667bb3-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
8e082a667bb3-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
8e082a667bb3-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
8e082a667bb3-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
df14a039e6dc-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
df14a039e6dc-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
df14a039e6dc-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
df14a039e6dc-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
df14a039e6dc-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
df14a039e6dc-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
df14a039e6dc-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
df14a039e6dc-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
df14a039e6dc-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
df14a039e6dc-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
df14a039e6dc-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
860bb0b94ce7-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
bc9a003352eb-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
bc9a003352eb-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
bc9a003352eb-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
bc9a003352eb-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
bc9a003352eb-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
bc9a003352eb-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
bc9a003352eb-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
bc9a003352eb-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
bc9a003352eb-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
bc9a003352eb-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
3100f557aa41-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
3100f557aa41-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
3100f557aa41-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
3100f557aa41-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
3100f557aa41-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
3100f557aa41-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
3100f557aa41-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
3100f557aa41-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