id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
437e96021694-8 | raise ValueError(
"Postgres connection string is required"
"Either pass it as a parameter"
"or set the PG_CONNECTION_STRING environment variable."
)
return connection_string
[docs] @classmethod
def from_documents(
cls: Type[AnalyticDB],
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
437e96021694-9 | user: str,
password: str,
) -> str:
"""Return connection string from database parameters."""
return f"postgresql+{driver}://{user}:{password}@{host}:{port}/{database}" | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
181b83c0d97a-0 | Source code for langchain.vectorstores.deeplake
from __future__ import annotations
import logging
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
import numpy as np
try:
import deeplake
from deeplake.core.fast_forwarding import version_compare
from deeplake.core.vectorstore im... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-1 | vectorstore = DeepLake("langchain_store", embeddings.embed_query)
"""
_LANGCHAIN_DEFAULT_DEEPLAKE_PATH = "./deeplake/"
[docs] def __init__(
self,
dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH,
token: Optional[str] = None,
embedding: Optional[Embeddings] = None,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-2 | embedding (Embeddings, optional): Function to convert
either documents or query. Optional.
embedding_function (Embeddings, optional): Function to convert
either documents or query. Optional. Deprecated: keeping this
parameter for backwards compatibility.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-3 | Deep Lake's Managed Tensor Database. Not applicable when loading an
existing Vector Store. To create a Vector Store in the Managed Tensor
Database, set `runtime = {"tensor_db": True}`.
**kwargs: Other optional keyword arguments.
Raises:
ValueError: If some... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-4 | **kwargs,
)
self._embedding_function = embedding_function or embedding
self._id_tensor_name = "ids" if "ids" in self.vectorstore.tensors() else "id"
@property
def embeddings(self) -> Optional[Embeddings]:
return self._embedding_function
[docs] def add_texts(
self,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-5 | if self._id_tensor_name == "ids": # for backwards compatibility
kwargs["ids"] = ids
else:
kwargs["id"] = ids
if metadatas is None:
metadatas = [{}] * len(list(texts))
if not isinstance(texts, list):
texts = list(texts)
if texts... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-6 | - ``tensor_db`` - Hosted Managed Tensor Database for storage
and query execution. Only for data in Deep Lake Managed Database.
Use runtime = {"db_engine": True} during dataset creation.
return_score (bool): Return score with document. Default is False.
Ret... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-7 | return_score: bool = False,
exec_option: Optional[str] = None,
**kwargs: Any,
) -> Any[List[Document], List[Tuple[Document, float]]]:
"""
Return docs similar to query.
Args:
query (str, optional): Text to look up similar docs.
embedding (Union[List[flo... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-8 | - ``compute_engine`` - C++ implementation of Deep Lake Compute
Engine for the client. Not for in-memory or local datasets.
- ``tensor_db`` - Hosted Managed Tensor Database for storage
and query execution. Only for data in Deep Lake Managed Database.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-9 | if len(embedding.shape) > 1:
embedding = embedding[0]
result = self.vectorstore.search(
embedding=embedding,
k=fetch_k if use_maximal_marginal_relevance else k,
distance_metric=distance_metric,
filter=filter,
exec_option=exec_option,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-10 | >>> # Search using an embedding
>>> data = vector_store.similarity_search(
... query=<your_query>,
... k=<num_items>,
... exec_option=<preferred_exec_option>,
... )
>>> # Run tql search:
>>> data = vector_store.similarity_se... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-11 | the client. Not for in-memory or local datasets.
- 'tensor_db': Managed Tensor Database for storage and query.
Only for data in Deep Lake Managed Database.
Use `runtime = {"db_engine": True}` during dataset creation.
Returns:
List[D... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-12 | `deeplake.filter`.
Defaults to None.
exec_option (str): Options for search execution include
"python", "compute_engine", or "tensor_db". Defaults to
"python".
- "python" - Pure-python implementation running on the client.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-13 | ) -> List[Tuple[Document, float]]:
"""
Run similarity search with Deep Lake with distance returned.
Examples:
>>> data = vector_store.similarity_search_with_score(
... query=<your_query>,
... embedding=<your_embedding_function>
... k=<number_of_items_t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-14 | - "tensor_db" - Performant, fully-hosted Managed Tensor Database.
Responsible for storage and query execution. Only available for
data stored in the Deep Lake Managed Database. To store datasets
in this database, specify `runtime = {"db_engine": Tr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-15 | lambda_mult: Number between 0 and 1 determining the degree of diversity.
0 corresponds to max diversity and 1 to min diversity. Defaults to 0.5.
exec_option (str): DeepLakeVectorStore supports 3 ways for searching.
Could be "python", "compute_engine" or "tensor_db". Defaults ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-16 | lambda_mult: float = 0.5,
exec_option: Optional[str] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Examples:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-17 | datasets in this database, specify
`runtime = {"db_engine": True}` during dataset creation.
**kwargs: Additional keyword arguments
Returns:
List of Documents selected by maximal marginal relevance.
Raises:
ValueError: when MRR search is on but ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-18 | ... embedding_function = <embedding_function_for_query>,
... k = <number_of_items_to_return>,
... exec_option = <preferred_exec_option>,
... )
Args:
dataset_path (str): - The full path to the dataset. Can be:
- Deep Lake cloud path of the ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-19 | deeplake_dataset.add_texts(
texts=texts,
metadatas=metadatas,
ids=ids,
)
return deeplake_dataset
[docs] def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> bool:
"""Delete the entities in the dataset.
Args:
ids (Optional[... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
181b83c0d97a-20 | [docs] def ds(self) -> Any:
logger.warning(
"this method is deprecated and will be removed, "
"better to use `db.vectorstore.dataset` instead."
)
return self.vectorstore.dataset | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
25cc7ea0d9ee-0 | Source code for langchain.vectorstores.scann
from __future__ import annotations
import operator
import pickle
import uuid
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
import numpy as np
from langchain.docstore.base import AddableMixin, Docstore
from langchain.docstore... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
25cc7ea0d9ee-1 | """
[docs] def __init__(
self,
embedding: Embeddings,
index: Any,
docstore: Docstore,
index_to_docstore_id: Dict[int, str],
relevance_score_fn: Optional[Callable[[float], float]] = None,
normalize_L2: bool = False,
distance_strategy: DistanceStrategy = ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
25cc7ea0d9ee-2 | **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.
ids: Optional list of unique IDs.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
25cc7ea0d9ee-3 | [docs] def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:
"""Delete by vector ID or other criteria.
Args:
ids: List of ids to delete.
**kwargs: Other keyword arguments that subclasses might use.
Returns:
Optional[bool]: True... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
25cc7ea0d9ee-4 | vector = normalize(vector)
indices, scores = self.index.search_batched(
vector, k if filter is None else fetch_k
)
docs = []
for j, i in enumerate(indices[0]):
if i == -1:
# This happens when not enough docs are returned.
continue
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
25cc7ea0d9ee-5 | **kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
25cc7ea0d9ee-6 | embedding,
k,
filter=filter,
fetch_k=fetch_k,
**kwargs,
)
return [doc for doc, _ in docs_and_scores]
[docs] def similarity_search(
self,
query: str,
k: int = 4,
filter: Optional[Dict[str, Any]] = None,
fetch_k: in... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
25cc7ea0d9ee-7 | )
scann_config = kwargs.get("scann_config", None)
vector = np.array(embeddings, dtype=np.float32)
if normalize_L2:
vector = normalize(vector)
if scann_config is not None:
index = scann.scann_ops_pybind.create_searcher(vector, scann_config)
else:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
25cc7ea0d9ee-8 | )
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> ScaNN:
"""Construct ScaNN wrapper from raw documents.
This is a user... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
25cc7ea0d9ee-9 | This is intended to be a quick way to get started.
Example:
.. code-block:: python
from langchain.vectorstores import ScaNN
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
text_embeddings = embeddings.e... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
25cc7ea0d9ee-10 | def load_local(
cls,
folder_path: str,
embedding: Embeddings,
index_name: str = "index",
**kwargs: Any,
) -> ScaNN:
"""Load ScaNN index, docstore, and index_to_docstore_id from disk.
Args:
folder_path: folder path to load index, docstore,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
25cc7ea0d9ee-11 | return self.override_relevance_score_fn
# Default strategy is to rely on distance strategy provided in
# vectorstore constructor
if self.distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:
return self._max_inner_product_relevance_score_fn
elif self.distance_strategy == D... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
25cc7ea0d9ee-12 | ]
if score_threshold is not None:
docs_and_rel_scores = [
(doc, similarity)
for doc, similarity in docs_and_rel_scores
if similarity >= score_threshold
]
return docs_and_rel_scores | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
9d899b9c99f6-0 | Source code for langchain.vectorstores.lancedb
from __future__ import annotations
import uuid
from typing import Any, Iterable, List, Optional
from langchain.docstore.document import Document
from langchain.schema.embeddings import Embeddings
from langchain.schema.vectorstore import VectorStore
[docs]class LanceDB(Vect... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
9d899b9c99f6-1 | self._text_key = text_key
@property
def embeddings(self) -> Embeddings:
return self._embedding
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
9d899b9c99f6-2 | Returns:
List of documents most similar to the query.
"""
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[do... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
1921e31ae1ba-0 | Source code for langchain.vectorstores.utils
"""Utility functions for working with vectors and vectorstores."""
from enum import Enum
from typing import List, Tuple, Type
import numpy as np
from langchain.docstore.document import Document
from langchain.utils.math import cosine_similarity
[docs]class DistanceStrategy(s... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/utils.html |
1921e31ae1ba-1 | redundant_score = max(similarity_to_selected[i])
equation_score = (
lambda_mult * query_score - (1 - lambda_mult) * redundant_score
)
if equation_score > best_score:
best_score = equation_score
idx_to_add = i
idxs.append(idx_to_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/utils.html |
a286bc870533-0 | Source code for langchain.vectorstores.llm_rails
"""Wrapper around LLMRails vector database."""
from __future__ import annotations
import json
import logging
import os
import uuid
from enum import Enum
from typing import Any, Iterable, List, Optional, Tuple
import requests
from langchain.pydantic_v1 import Field
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/llm_rails.html |
a286bc870533-1 | def _get_post_headers(self) -> dict:
"""Returns headers that should be attached to each post request."""
return {
"X-API-KEY": self._api_key,
"Content-Type": "application/json",
}
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Opti... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/llm_rails.html |
a286bc870533-2 | Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 5 Max 10.
alpha: parameter for hybrid search .
Returns:
List of Documents most similar to the query and score for each.
"""
response = self._session.po... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/llm_rails.html |
a286bc870533-3 | """
docs_and_scores = self.similarity_search_with_score(query, k=k)
return [doc for doc, _ in docs_and_scores]
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Optional[Embeddings] = None,
metadatas: Optional[List[dict]] = None,
**kwarg... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/llm_rails.html |
a286bc870533-4 | """Add text to the datastore.
Args:
texts (List[str]): The text
"""
self.vectorstore.add_texts(texts) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/llm_rails.html |
c78e358b1e85-0 | Source code for langchain.vectorstores.opensearch_vector_search
from __future__ import annotations
import uuid
import warnings
from typing import Any, Dict, Iterable, List, Optional, Tuple
import numpy as np
from langchain.schema import Document
from langchain.schema.embeddings import Embeddings
from langchain.schema.v... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-1 | try:
opensearch = _import_opensearch()
client = opensearch(opensearch_url, **kwargs)
except ValueError as e:
raise ImportError(
f"OpenSearch client string provided is not in proper format. "
f"Got error: {e} "
)
return client
def _validate_embeddings_and_b... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-2 | metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
vector_field: str = "vector_field",
text_field: str = "text",
mapping: Optional[Dict] = None,
max_chunk_bytes: Optional[int] = 1 * 1024 * 1024,
is_aoss: bool = False,
) -> List[str]:
"""Bulk Ingest Embeddings into given... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-3 | vector_field: str = "vector_field",
) -> Dict:
"""For Painless Scripting or Script Scoring,the default mapping to create index."""
return {
"mappings": {
"properties": {
vector_field: {"type": "knn_vector", "dimension": dim},
}
}
}
def _default_text_ma... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-4 | return {
"size": k,
"query": {"knn": {vector_field: {"vector": query_vector, "k": k}}},
}
def _approximate_search_query_with_boolean_filter(
query_vector: List[float],
boolean_filter: Dict,
k: int = 4,
vector_field: str = "vector_field",
subquery_clause: str = "must",
) -> Dict:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-5 | if not pre_filter:
pre_filter = MATCH_ALL_QUERY
return {
"size": k,
"query": {
"script_score": {
"query": pre_filter,
"script": {
"source": "knn_score",
"lang": "knn",
"params": {
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-6 | "script": {
"source": source,
"params": {
"field": vector_field,
"query_value": query_vector,
},
},
}
},
}
def _get_kwargs_value(kwargs: Any, key: str, default_value: Any) ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-7 | metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
bulk_size: int = 500,
**kwargs: Any,
) -> List[str]:
_validate_embeddings_and_bulk_size(len(embeddings), bulk_size)
index_name = _get_kwargs_value(kwargs, "index_name", self.index_name)
text_fiel... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-8 | )
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
bulk_size: int = 500,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Ar... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-9 | text_embeddings: Iterable pairs of string and embedding to
add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
ids: Optional list of ids to associate with the texts.
bulk_size: Bulk API request count; Default: 500
Returns:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-10 | Can be set to a special value "*" to include the entire document.
Optional Args for Approximate Search:
search_type: "approximate_search"; default: "approximate_search"
boolean_filter: A Boolean filter is a post filter consists of a Boolean
query that contains a k-NN query an... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-11 | return [doc[0] for doc in docs_with_scores]
[docs] def similarity_search_with_score(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Tuple[Document, float]]:
"""Return docs and it's scores most similar to query.
By default, supports Approximate Search.
Also supports Script S... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-12 | Also supports Script Scoring and Painless Scripting.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
Returns:
List of dict with its scores most similar to the query.
Optional Args:
same as `simila... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-13 | if lucene_filter != {} and efficient_filter != {}:
raise ValueError(
"Both `lucene_filter` and `efficient_filter` are provided which "
"is invalid. `lucene_filter` is deprecated"
)
if lucene_filter != {} and boolean_filter != {}:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-14 | )
elif search_type == SCRIPT_SCORING_SEARCH:
space_type = _get_kwargs_value(kwargs, "space_type", "l2")
pre_filter = _get_kwargs_value(kwargs, "pre_filter", MATCH_ALL_QUERY)
search_query = _default_script_query(
embedding, k, space_type, pre_filter, vector_fie... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-15 | 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.
"""
vector_field = _get_kwargs_value(kwargs, "vecto... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-16 | Example:
.. code-block:: python
from langchain.vectorstores import OpenSearchVectorSearch
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
opensearch_vector_search = OpenSearchVectorSearch.from_texts(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-17 | return cls.from_embeddings(
embeddings,
texts,
embedding,
metadatas=metadatas,
bulk_size=bulk_size,
ids=ids,
**kwargs,
)
[docs] @classmethod
def from_embeddings(
cls,
embeddings: List[List[float]],
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-18 | space_type: "l2", "l1", "cosinesimil", "linf", "innerproduct"; default: "l2"
ef_search: Size of the dynamic list used during k-NN searches. Higher values
lead to more accurate but slower searches; default: 512
ef_construction: Size of the dynamic list used during k-NN graph creation.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-19 | )
is_appx_search = _get_kwargs_value(kwargs, "is_appx_search", True)
vector_field = _get_kwargs_value(kwargs, "vector_field", "vector_field")
text_field = _get_kwargs_value(kwargs, "text_field", "text")
max_chunk_bytes = _get_kwargs_value(kwargs, "max_chunk_bytes", 1 * 1024 * 1024)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
c78e358b1e85-20 | index_name,
embeddings,
texts,
ids=ids,
metadatas=metadatas,
vector_field=vector_field,
text_field=text_field,
mapping=mapping,
max_chunk_bytes=max_chunk_bytes,
is_aoss=is_aoss,
)
kwargs["engine"]... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
16ed932b09ea-0 | Source code for langchain.vectorstores.xata
from __future__ import annotations
import time
from itertools import repeat
from typing import Any, Dict, Iterable, List, Optional, Tuple, Type
from langchain.docstore.document import Document
from langchain.schema.embeddings import Embeddings
from langchain.schema.vectorstor... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html |
16ed932b09ea-1 | [docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[Dict[Any, Any]]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
ids = ids
docs = self._texts_to_documents(texts, metadatas)
vectors = self._embedding... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html |
16ed932b09ea-2 | if r.status_code != 200:
raise Exception(f"Error adding vectors to Xata: {r.status_code} {r}")
id_list.extend(r["recordIDs"])
return id_list
@staticmethod
def _texts_to_documents(
texts: Iterable[str],
metadatas: Optional[Iterable[Dict[Any, Any]]] = None,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html |
16ed932b09ea-3 | embedding=embedding,
table_name=table_name,
)
vector_db._add_vectors(embeddings, docs, ids)
return vector_db
[docs] def similarity_search(
self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any
) -> List[Document]:
"""Return docs most simila... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html |
16ed932b09ea-4 | }
if filter:
payload["filter"] = filter
r = self._client.data().vector_search(self._table_name, payload=payload)
if r.status_code != 200:
raise Exception(f"Error running similarity search: {r.status_code} {r}")
hits = r["records"]
docs_and_scores = [
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html |
16ed932b09ea-5 | ]
self._client.records().transaction(payload={"operations": operations})
else:
raise ValueError("Either ids or delete_all must be set.")
def _delete_all(self) -> None:
"""Delete all records in the table."""
while True:
r = self._client.data().query(sel... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html |
f2c475d34bb0-0 | Source code for langchain.vectorstores.tencentvectordb
"""Wrapper around the Tencent vector database."""
from __future__ import annotations
import json
import logging
import time
from typing import Any, Dict, Iterable, List, Optional, Tuple
import numpy as np
from langchain.docstore.document import Document
from langch... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html |
f2c475d34bb0-1 | index_type: str = "HNSW",
metric_type: str = "L2",
params: Optional[Dict] = None,
):
self.dimension = dimension
self.shard = shard
self.replicas = replicas
self.index_type = index_type
self.metric_type = metric_type
self.params = params
[docs]class Ten... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html |
f2c475d34bb0-2 | for db in db_list:
if database_name == db.database_name:
db_exist = True
break
if db_exist:
self.database = self.vdb_client.database(database_name)
else:
self.database = self.vdb_client.create_database(database_name)
try:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html |
f2c475d34bb0-3 | self.field_id, enum.FieldType.String, enum.IndexType.PRIMARY_KEY
),
vdb_index.VectorIndex(
self.field_vector,
self.index_params.dimension,
index_type,
metric_type,
params,
),
vdb_index.FilterI... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html |
f2c475d34bb0-4 | except NotImplementedError:
embeddings = [embedding.embed_query(texts[0])]
dimension = len(embeddings[0])
if index_params is None:
index_params = IndexParams(dimension=dimension)
else:
index_params.dimension = dimension
vector_db = cls(
emb... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html |
f2c475d34bb0-5 | metadata = json.dumps(metadatas[id])
doc = self.document.Document(
id="{}-{}-{}".format(time.time_ns(), hash(texts[id]), id),
vector=embeddings[id],
text=texts[id],
metadata=metadata,
)
docs.a... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html |
f2c475d34bb0-6 | )
return res
[docs] def similarity_search_by_vector(
self,
embedding: List[float],
k: int = 4,
param: Optional[dict] = None,
expr: Optional[str] = None,
timeout: Optional[int] = None,
**kwargs: Any,
) -> List[Document]:
"""Perform a similari... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html |
f2c475d34bb0-7 | for result in res[0]:
meta = result.get(self.field_metadata)
if meta is not None:
meta = json.loads(meta)
doc = Document(page_content=result.get(self.field_text), metadata=meta)
pair = (doc, result.get("score", 0.0))
ret.append(pair)
re... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html |
f2c475d34bb0-8 | """Perform a search and return results that are reordered by MMR."""
filter = None if expr is None else self.document.Filter(expr)
ef = 10 if param is None else param.get("ef", 10)
res: List[List[Dict]] = self.collection.search(
vectors=[embedding],
filter=filter,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html |
6f30261b411b-0 | Source code for langchain.vectorstores.tair
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.schema.embeddings import Embeddings
from langchain.schema.vectorstore import Vector... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
6f30261b411b-1 | self,
dim: int,
distance_type: str,
index_type: str,
data_type: str,
**kwargs: Any,
) -> bool:
index = self.client.tvs_get_index(self.index_name)
if index is not None:
logger.info("Index already exists")
return False
self.client... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
6f30261b411b-2 | **{
"TEXT": text,
self.content_key: text,
self.metadata_key: json.dumps(metadata),
},
)
else:
pipeline.tvs_hset(
self.index_name,
key,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
6f30261b411b-3 | cls: Type[Tair],
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
index_name: str = "langchain",
content_key: str = "content",
metadata_key: str = "metadata",
**kwargs: Any,
) -> Tair:
try:
from tair import t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
6f30261b411b-4 | metadata_key=metadata_key,
search_params=search_params,
**kwargs,
)
except ValueError as e:
raise ValueError(f"tair failed to connect: {e}")
# Create embeddings for documents
embeddings = embedding.embed_documents(texts)
tair_vector... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
6f30261b411b-5 | except ImportError:
raise ValueError(
"Could not import tair python package. "
"Please install it with `pip install tair`."
)
url = get_from_dict_or_env(kwargs, "tair_url", "TAIR_URL")
try:
if "tair_url" in kwargs:
kwarg... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
e076549b6377-0 | Source code for langchain.vectorstores.singlestoredb
from __future__ import annotations
import json
from typing import (
Any,
Callable,
ClassVar,
Collection,
Iterable,
List,
Optional,
Tuple,
Type,
)
from sqlalchemy.pool import QueuePool
from langchain.callbacks.manager import (
A... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
e076549b6377-1 | self,
embedding: Embeddings,
*,
distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,
table_name: str = "embeddings",
content_field: str = "content",
metadata_field: str = "metadata",
vector_field: str = "vector",
pool_size: int = 5,
max... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
e076549b6377-2 | max_overflow (int, optional): Determines the maximum number of connections
allowed beyond the pool_size. Defaults to 10.
timeout (float, optional): Specifies the maximum wait time in seconds for
establishing a connection. Defaults to 30.
Following arguments pertai... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
e076549b6377-3 | conv (dict[int, Callable], optional): A dictionary of data conversion
functions.
credential_type (str, optional): Specifies the type of authentication to
use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.
autocommit (bool, optional): Enables autocommits.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
e076549b6377-4 | vectorstore = SingleStoreDB(OpenAIEmbeddings())
"""
self.embedding = embedding
self.distance_strategy = distance_strategy
self.table_name = table_name
self.content_field = content_field
self.metadata_field = metadata_field
self.vector_field = vector_field
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
e076549b6377-5 | ),
)
finally:
cur.close()
finally:
conn.close()
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
embeddings: Optional[List[List[float]]] = None,
**kwargs: Any,
) -> Lis... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
e076549b6377-6 | conn.close()
return []
[docs] def similarity_search(
self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any
) -> List[Document]:
"""Returns the most similar indexed documents to the query text.
Uses cosine similarity.
Args:
query (str): The ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
e076549b6377-7 | filter: A dictionary of metadata fields and values to filter by.
Defaults to None.
Returns:
List of Documents most similar to the query and score for each
"""
# Creates embedding vector from user query
embedding = self.embedding.embed_query(query)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
e076549b6377-8 | if isinstance(self.distance_strategy, DistanceStrategy)
else self.distance_strategy,
self.vector_field,
self.table_name,
where_clause,
ORDERING_DIRECTIVE[self.distance_strategy],
)... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
e076549b6377-9 | from langchain.embeddings import OpenAIEmbeddings
s2 = SingleStoreDB.from_texts(
texts,
OpenAIEmbeddings(),
host="username:password@localhost:3306/database"
)
"""
instance = cls(
embedding,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
e076549b6377-10 | return docs
async def _aget_relevant_documents(
self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun
) -> List[Document]:
raise NotImplementedError(
"SingleStoreDBVectorStoreRetriever does not support async"
) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
8e649523b3f0-0 | Source code for langchain.vectorstores.zilliz
from __future__ import annotations
import logging
from typing import Any, Dict, List, Optional
from langchain.schema.embeddings import Embeddings
from langchain.vectorstores.milvus import Milvus
logger = logging.getLogger(__name__)
[docs]class Zilliz(Milvus):
"""`Zilliz... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.