id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
144943ee2fe3-2
f"{response.text}" ) return False return True def _index_doc(self, doc_id: str, text: str, metadata: dict) -> bool: request: dict[str, Any] = {} request["customer_id"] = self._vectara_customer_id request["corpus_id"] = self._vectara_corpus_id request["...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
144943ee2fe3-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
144943ee2fe3-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
144943ee2fe3-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
144943ee2fe3-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
c19a1d3d6450-0
Source code for langchain.vectorstores.opensearch_vector_search """Wrapper around OpenSearch vector database.""" from __future__ import annotations import uuid from typing import Any, Dict, Iterable, List, Optional, Tuple from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c19a1d3d6450-1
try: opensearch = _import_opensearch() client = opensearch(opensearch_url, **kwargs) except ValueError as e: raise ValueError( f"OpenSearch client string provided is not in proper format. " f"Got error: {e} " ) return client def _validate_embeddings_and_bu...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c19a1d3d6450-2
request = { "_op_type": "index", "_index": index_name, vector_field: embeddings[i], text_field: text, "metadata": metadata, "_id": _id, } requests.append(request) ids.append(_id) bulk(client, requests) client.indices...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c19a1d3d6450-3
"parameters": {"ef_construction": ef_construction, "m": m}, }, } } }, } def _default_approximate_search_query( query_vector: List[float], k: int = 4, vector_field: str = "vector_field", ) -> Dict: """For Approximate k-NN Search, this is the def...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c19a1d3d6450-4
return search_query def _default_script_query( query_vector: List[float], space_type: str = "l2", pre_filter: Dict = MATCH_ALL_QUERY, vector_field: str = "vector_field", ) -> Dict: """For Script Scoring Search, this is the default query.""" return { "query": { "script_score":...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c19a1d3d6450-5
source = __get_painless_scripting_source(space_type, query_vector) return { "query": { "script_score": { "query": pre_filter, "script": { "source": source, "params": { "field": vector_field, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c19a1d3d6450-6
"""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. bulk_size: Bulk API request count; Default: 500 Returns: List ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c19a1d3d6450-7
text_field, mapping, ) [docs] def similarity_search( self, query: str, k: int = 4, **kwargs: Any ) -> List[Document]: """Return docs most similar to query. By default supports Approximate Search. Also supports Script Scoring and Painless Scripting. Args...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c19a1d3d6450-8
pre_filter: script_score query to pre-filter documents before identifying nearest neighbors; default: {"match_all": {}} Optional Args for Painless Scripting Search: search_type: "painless_scripting"; default: "approximate_search" space_type: "l2Squared", "l1Norm", "cosineSimi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c19a1d3d6450-9
if search_type == "approximate_search": boolean_filter = _get_kwargs_value(kwargs, "boolean_filter", {}) subquery_clause = _get_kwargs_value(kwargs, "subquery_clause", "must") lucene_filter = _get_kwargs_value(kwargs, "lucene_filter", {}) if boolean_filter != {} and lucen...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c19a1d3d6450-10
embedding, space_type, pre_filter, vector_field ) else: raise ValueError("Invalid `search_type` provided as an argument") response = self.client.search(index=self.index_name, body=search_query) hits = [hit for hit in response["hits"]["hits"][:k]] documents_with_sc...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c19a1d3d6450-11
vector_field: Document field embeddings are stored in. Defaults to "vector_field". text_field: Document field the text of the document is stored in. Defaults to "text". Optional Keyword Args for Approximate Search: engine: "nmslib", "faiss", "lucene"; default: "nm...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c19a1d3d6450-12
_validate_embeddings_and_bulk_size(len(embeddings), bulk_size) dim = len(embeddings[0]) # Get the index name from either from kwargs or ENV Variable # before falling back to random generation index_name = get_from_dict_or_env( kwargs, "index_name", "OPENSEARCH_INDEX_NAME", de...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c19a1d3d6450-13
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
edfbc22374a7-0
Source code for langchain.vectorstores.faiss """Wrapper around FAISS vector database.""" from __future__ import annotations import math import os import pickle import uuid from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple import numpy as np from langchain.docstore.base imp...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
edfbc22374a7-1
return faiss def _default_relevance_score_fn(score: float) -> float: """Return a similarity score on a scale [0, 1].""" # The 'correct' relevance function # may differ depending on a few things, including: # - the distance / similarity metric used by the VectorStore # - the scale of your embeddings ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
edfbc22374a7-2
self._normalize_L2 = normalize_L2 def __add( self, texts: Iterable[str], embeddings: Iterable[List[float]], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any, ) -> List[str]: if not isinstance(self.docstore, AddableMixi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
edfbc22374a7-3
return [_id for _, _id, _ in full_info] [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
edfbc22374a7-4
ids: Optional list of unique IDs. Returns: List of ids from adding the texts into the vectorstore. """ if not isinstance(self.docstore, AddableMixin): raise ValueError( "If trying to add texts, the underlying docstore should support " f"add...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
edfbc22374a7-5
raise ValueError(f"Could not find document for id {_id}, got {doc}") docs.append((doc, scores[0][j])) return docs [docs] def similarity_search_with_score( self, query: str, k: int = 4 ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Args: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
edfbc22374a7-6
Returns: List of Documents most similar to the query. """ docs_and_scores = self.similarity_search_with_score(query, k) return [doc for doc, _ in docs_and_scores] [docs] def max_marginal_relevance_search_by_vector( self, embedding: List[float], k: int = 4, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
edfbc22374a7-7
docs = [] for i in selected_indices: if i == -1: # This happens when not enough docs are returned. continue _id = self.index_to_docstore_id[i] doc = self.docstore.search(_id) if not isinstance(doc, Document): raise V...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
edfbc22374a7-8
Add the target FAISS to the current one. Args: target: FAISS object you wish to merge into the current one Returns: None. """ if not isinstance(self.docstore, AddableMixin): raise ValueError("Cannot merge with this type of docstore") # Numerica...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
edfbc22374a7-9
vector = np.array(embeddings, dtype=np.float32) if normalize_L2: faiss.normalize_L2(vector) index.add(vector) documents = [] if ids is None: ids = [str(uuid.uuid4()) for _ in texts] for i, text in enumerate(texts): metadata = metadatas[i] if me...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
edfbc22374a7-10
return cls.__from( texts, embeddings, embedding, metadatas=metadatas, ids=ids, **kwargs, ) [docs] @classmethod def from_embeddings( cls, text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
edfbc22374a7-11
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(exist_ok=True, parents=True) # save index separately since it is not...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
edfbc22374a7-12
docstore, index_to_docstore_id = pickle.load(f) return cls(embeddings.embed_query, index, docstore, index_to_docstore_id) def _similarity_search_with_relevance_scores( self, query: str, k: int = 4, **kwargs: Any, ) -> List[Tuple[Document, float]]: """Return docs a...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
2250ee167c5f-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
2250ee167c5f-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
2250ee167c5f-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
2250ee167c5f-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
2250ee167c5f-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
2250ee167c5f-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
2b979b39aa64-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
2b979b39aa64-1
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, dim, distance...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
2b979b39aa64-2
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 similar to the query text. """ # Creates embedding vector from user quer...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
2b979b39aa64-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
2b979b39aa64-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
2b979b39aa64-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
47ec3506a6cc-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
47ec3506a6cc-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
47ec3506a6cc-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
47ec3506a6cc-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
47ec3506a6cc-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
47ec3506a6cc-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
47ec3506a6cc-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
47ec3506a6cc-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
47ec3506a6cc-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
47ec3506a6cc-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
47ec3506a6cc-10
relevance_score_fn=relevance_score_fn, by_text=by_text, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
34feb71b9247-0
Source code for langchain.vectorstores.pinecone """Wrapper around Pinecone vector database.""" from __future__ import annotations import logging import uuid from typing import Any, Callable, Iterable, List, Optional, Tuple from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
34feb71b9247-1
f"got {type(index)}" ) self._index = index self._embedding_function = embedding_function self._text_key = text_key self._namespace = namespace [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Opt...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
34feb71b9247-2
k: int = 4, filter: Optional[dict] = None, namespace: Optional[str] = None, ) -> List[Tuple[Document, float]]: """Return pinecone documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to r...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
34feb71b9247-3
Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: Dictionary of argument(s) to filter on metadata namespace: Namespace to search in. Default will search in '' namespace. Returns: List of Documen...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
34feb71b9247-4
pinecone = Pinecone.from_texts( texts, embeddings, index_name="langchain-demo" ) """ try: import pinecone except ImportError: raise ValueError( "Could not import pinecone python pa...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
34feb71b9247-5
for j, line in enumerate(lines_batch): metadata[j][text_key] = line to_upsert = zip(ids_batch, embeds, metadata) # upsert to Pinecone index.upsert(vectors=list(to_upsert), namespace=namespace) return cls(index, embedding.embed_query, text_key, namespace) [docs...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
d47fec865d70-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
d47fec865d70-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
d47fec865d70-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
d47fec865d70-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
d47fec865d70-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
d47fec865d70-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
d47fec865d70-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
d47fec865d70-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
d47fec865d70-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
d47fec865d70-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
e80b11d40c49-0
Source code for langchain.vectorstores.myscale """Wrapper around MyScale vector database.""" from __future__ import annotations import json import logging from hashlib import sha1 from threading import Thread from typing import Any, Dict, Iterable, List, Optional, Tuple from pydantic import BaseSettings from langchain....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
e80b11d40c49-1
.. code-block:: python { 'id': 'text_id', 'vector': 'text_embedding', 'text': 'text_plain', 'metadata': 'metadata_dictionary_in_json', }...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
e80b11d40c49-2
config: Optional[MyScaleSettings] = None, **kwargs: Any, ) -> None: """MyScale Wrapper to LangChain embedding_function (Embeddings): config (MyScaleSettings): Configuration to MyScale Client Other keyword arguments will pass into [clickhouse-connect](https://docs....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
e80b11d40c49-3
CREATE TABLE IF NOT EXISTS {self.config.database}.{self.config.table}( {self.config.column_map['id']} String, {self.config.column_map['text']} String, {self.config.column_map['vector']} Array(Float32), {self.config.column_map['metadata']} JSON, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
e80b11d40c49-4
_data.append(f"({n})") i_str = f""" INSERT INTO TABLE {self.config.database}.{self.config.table}({ks}) VALUES {','.join(_data)} """ return i_str def _insert(self, transac: Iterable, column_names: Iterable[str]) -> N...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
e80b11d40c49-5
column_names[colmap_["metadata"]] = map(json.dumps, metadatas) assert len(set(colmap_) - set(column_names)) >= 0 keys, values = zip(*column_names.items()) try: t = None for v in self.pgbar( zip(*values), desc="Inserting data...", total=len(metadatas) ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
e80b11d40c49-6
texts (Iterable[str]): List or tuple of strings to be added config (MyScaleSettings, Optional): Myscale configuration text_ids (Optional[Iterable], optional): IDs for the texts. Defaults to None. batch_size (int, optional): Batchsi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
e80b11d40c49-7
).named_results(): _repr += ( f"|\033[94m{r['name']:24s}\033[0m|\033[96m{r['type']:24s}\033[0m|\n" ) _repr += "-" * 51 + "\n" return _repr def _build_qstr( self, q_emb: List[float], topk: int, where_str: Optional[str] = None ) -> str: q_emb...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
e80b11d40c49-8
of SQL injection. When dealing with metadatas, remember to use `{self.metadata_column}.attribute` instead of `attribute` alone. The default name for it is `metadata`. Returns: List[Document]: List of Documents """ return self.similarity_search_by_v...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
e80b11d40c49-9
] except Exception as e: logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") return [] [docs] def similarity_search_with_relevance_scores( self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any ) -> List[Tuple[Document, float]]: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
e80b11d40c49-10
return [] [docs] def drop(self) -> None: """ Helper function: Drop data """ self.client.command( f"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}" ) @property def metadata_column(self) -> str: return self.config.column_map["metadata...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
e09cf5ad6674-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
e09cf5ad6674-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
e09cf5ad6674-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
e09cf5ad6674-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
e09cf5ad6674-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
e09cf5ad6674-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
e09cf5ad6674-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
e09cf5ad6674-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
e09cf5ad6674-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
e09cf5ad6674-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
e09cf5ad6674-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
e09cf5ad6674-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
e09cf5ad6674-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
e09cf5ad6674-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
c87cb1386257-0
Source code for langchain.vectorstores.atlas """Wrapper around Atlas by Nomic.""" from __future__ import annotations import logging import uuid from typing import Any, Iterable, List, Optional, Type import numpy as np from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
c87cb1386257-1
is_public (bool): Whether your project is publicly accessible. True by default. reset_project_if_exists (bool): Whether to reset this project if it already exists. Default False. Generally userful during development and testing. """ try: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
c87cb1386257-2
metadatas (Optional[List[dict]], optional): Optional list of metadatas. ids (Optional[List[str]]): An optional list of ids. refresh(bool): Whether or not to refresh indices with the updated data. Default True. Returns: List[str]: List of IDs of the added texts...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
c87cb1386257-3
else: if metadatas is None: data = [ {"text": text, AtlasDB._ATLAS_DEFAULT_ID_FIELD: ids[i]} for i, text in enumerate(texts) ] else: for i, text in enumerate(texts): metadatas[i]["text"] =...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html