id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
deda41dbc8c5-10 | strategy: BaseRetrievalStrategy = ApproxRetrievalStrategy(),
):
self.embedding = embedding
self.index_name = index_name
self.query_field = query_field
self.vector_query_field = vector_query_field
self.distance_strategy = (
DistanceStrategy.COSINE
if di... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-11 | "Please install it with `pip install elasticsearch`."
)
if es_url and cloud_id:
raise ValueError(
"Both es_url and cloud_id are defined. Please provide only one."
)
connection_params: Dict[str, Any] = {}
if es_url:
connection_params... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-12 | filter: Array of Elasticsearch filter clauses to apply to the query.
Returns:
List of Documents most similar to the query,
in descending order of similarity.
"""
results = self._search(
query=query, k=k, fetch_k=fetch_k, filter=filter, **kwargs
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-13 | if fields is None:
fields = [self.vector_query_field]
elif self.vector_query_field not in fields:
fields.append(self.vector_query_field)
else:
remove_vector_query_field_from_metadata = False
# Embed the query
query_embedding = self.embedding.embed_quer... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-14 | [docs] def similarity_search_by_vector_with_relevance_scores(
self,
embedding: List[float],
k: int = 4,
filter: Optional[List[Dict]] = None,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return Elasticsearch documents most similar to query, along with scores... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-15 | Defaults to 50.
fields: List of fields to return from Elasticsearch.
Defaults to only returning the text field.
filter: Array of Elasticsearch filter clauses to apply to the query.
custom_query: Function to modify the Elasticsearch
query b... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-16 | doc_builder = doc_builder or default_doc_builder
docs_and_scores = []
for hit in response["hits"]["hits"]:
for field in fields:
if field in hit["_source"] and field not in [
"metadata",
self.query_field,
]:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-17 | logger.error(f"Error deleting texts: {e}")
firstError = e.errors[0].get("index", {}).get("error", {})
logger.error(f"First error reason: {firstError.get('reason')}")
raise e
else:
logger.debug("No texts to delete from index")
return False
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-18 | texts: Iterable[str],
embeddings: Optional[List[List[float]]],
metadatas: Optional[List[Dict[Any, Any]]] = None,
ids: Optional[List[str]] = None,
refresh_indices: bool = True,
create_index_if_not_exists: bool = True,
bulk_kwargs: Optional[Dict] = None,
**kwargs: A... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-19 | **bulk_kwargs,
)
logger.debug(
f"Added {success} and failed to add {failed} texts to index"
)
logger.debug(f"added texts {ids} to index")
return ids
except BulkIndexError as e:
logger.error(f"... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-20 | Returns:
List of ids from adding the texts into the vectorstore.
"""
if self.embedding is not None:
# If no search_type requires inference, we use the provided
# embedding function to embed the texts.
embeddings = self.embedding.embed_documents(list(texts)... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-21 | *bulk_kwargs: Additional arguments to pass to Elasticsearch bulk.
- chunk_size: Optional. Number of texts to add to the
index at a time. Defaults to 500.
Returns:
List of ids from adding the texts into the vectorstore.
"""
texts, embeddings = zip(*... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-22 | index_name: Name of the Elasticsearch index to create.
es_url: URL of the Elasticsearch instance to connect to.
cloud_id: Cloud ID of the Elasticsearch instance to connect to.
es_user: Username to use when connecting to Elasticsearch.
es_password: Password to use when con... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-23 | es_user = kwargs.get("es_user")
es_password = kwargs.get("es_password")
es_api_key = kwargs.get("es_api_key")
vector_query_field = kwargs.get("vector_query_field")
query_field = kwargs.get("query_field")
distance_strategy = kwargs.get("distance_strategy")
strategy = kwarg... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-24 | es_url="http://localhost:9200"
)
Args:
texts: List of texts to add to the Elasticsearch index.
embedding: Embedding function to use to embed the texts.
Do not provide if using a strategy
that doesn't require inference.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-25 | hybrid: Optional[bool] = False,
rrf: Optional[Union[dict, bool]] = True,
) -> "ApproxRetrievalStrategy":
"""Used to perform approximate nearest neighbor search
using the HNSW algorithm.
At build index time, this strategy will create a
dense vector field in the index and store... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-26 | """Used to perform sparse vector search via text_expansion.
Used for when you want to use ELSER model to perform document search.
At build index time, this strategy will create a pipeline that
will embed the text using the ELSER model and store the
resulting tokens in the index.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
924dcd67ade9-0 | Source code for langchain.vectorstores.vald
"""Wrapper around Vald vector database."""
from __future__ import annotations
from typing import Any, Iterable, List, Optional, Tuple, Type
import numpy as np
from langchain.docstore.document import Document
from langchain.schema.embeddings import Embeddings
from langchain.sc... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html |
924dcd67ade9-1 | metadatas: Optional[List[dict]] = None,
skip_strict_exist_check: bool = False,
**kwargs: Any,
) -> List[str]:
"""
Args:
skip_strict_exist_check: Deprecated. This is not used basically.
"""
try:
import grpc
from vald.v1.payload impor... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html |
924dcd67ade9-2 | ) -> Optional[bool]:
"""
Args:
skip_strict_exist_check: Deprecated. This is not used basically.
"""
try:
import grpc
from vald.v1.payload import payload_pb2
from vald.v1.vald import remove_pb2_grpc
except ImportError:
ra... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html |
924dcd67ade9-3 | docs.append(doc)
return docs
[docs] def similarity_search_with_score(
self,
query: str,
k: int = 4,
radius: float = -1.0,
epsilon: float = 0.01,
timeout: int = 3000000000,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
emb = self._embeddi... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html |
924dcd67ade9-4 | from vald.v1.vald import search_pb2_grpc
except ImportError:
raise ValueError(
"Could not import vald-client-python python package. "
"Please install it with `pip install vald-client-python`."
)
channel = grpc.insecure_channel(self.target, options=... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html |
924dcd67ade9-5 | timeout=timeout,
lambda_mult=lambda_mult,
)
return docs
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
radius: float = -1.0,
epsilon: float =... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html |
924dcd67ade9-6 | docs.append(doc)
mmr = maximal_marginal_relevance(
np.array(embedding),
embs,
lambda_mult=lambda_mult,
k=k,
)
channel.close()
return [docs[i] for i in mmr]
[docs] @classmethod
def from_texts(
cls: Type[Vald],
texts: L... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html |
924dcd67ade9-7 | # ) -> List[str]:
# pass
#
# def _select_relevance_score_fn(self) -> Callable[[float], float]:
# pass
#
# def _similarity_search_with_relevance_scores(
# self,
# query: str,
# k: int = 4,
# **kwargs: Any,
# ) -> List[Tuple[Document, float]]:
# pass
#
# def... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html |
9fe3a1ab7e46-0 | Source code for langchain.vectorstores.marqo
from __future__ import annotations
import json
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
)
from langchain.docstore.document import Document
from langchain.schema.... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
9fe3a1ab7e46-1 | searchable_attributes: Optional[List[str]] = None,
page_content_builder: Optional[Callable[[Dict[str, Any]], str]] = None,
):
"""Initialize with Marqo client."""
try:
import marqo
except ImportError:
raise ImportError(
"Could not import marqo p... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
9fe3a1ab7e46-2 | Raises:
ValueError: if metadatas is provided and the number of metadatas differs
from the number of texts.
Returns:
List[str]: The list of ids that were added.
"""
if self._client.index(self._index_name).get_settings()["index_defaults"][
"treat_url... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
9fe3a1ab7e46-3 | k: int = 4,
**kwargs: Any,
) -> List[Document]:
"""Search the marqo index for the most similar documents.
Args:
query (Union[str, Dict[str, float]]): The query for the search, either
as a string or a weighted query.
k (int, optional): The number of documen... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
9fe3a1ab7e46-4 | **kwargs: Any,
) -> List[List[Document]]:
"""Search the marqo index for the most similar documents in bulk with multiple
queries.
Args:
queries (Iterable[Union[str, Dict[str, float]]]): An iterable of queries to
execute in bulk, queries in the list can be strings or d... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
9fe3a1ab7e46-5 | documents and their scores for each query
"""
bulk_results = self.marqo_bulk_similarity_search(queries=queries, k=k)
bulk_documents: List[List[Tuple[Document, float]]] = []
for results in bulk_results["result"]:
documents = self._construct_documents_from_results_with_score(re... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
9fe3a1ab7e46-6 | results (List[dict]): A marqo results object with the 'hits'.
include_scores (bool, optional): Include scores alongside documents.
Defaults to False.
Returns:
Union[List[Document], List[Tuple[Document, float]]]: The documents or
document score pairs if `include_sc... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
9fe3a1ab7e46-7 | """Return documents from Marqo using a bulk search, exposes Marqo's
output directly
Args:
queries (Iterable[Union[str, Dict[str, float]]]): A list of queries.
k (int, optional): The number of documents to return for each query.
Defaults to 4.
Returns:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
9fe3a1ab7e46-8 | cls,
texts: List[str],
embedding: Any = None,
metadatas: Optional[List[dict]] = None,
index_name: str = "",
url: str = "http://localhost:8882",
api_key: str = "",
add_documents_settings: Optional[Dict[str, Any]] = None,
searchable_attributes: Optional[List... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
9fe3a1ab7e46-9 | provided then one will be created with a UUID. Defaults to None.
url (str, optional): The URL for Marqo. Defaults to "http://localhost:8882".
api_key (str, optional): The API key for Marqo. Defaults to "".
metadatas (Optional[List[dict]], optional): A list of metadatas, to
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
9fe3a1ab7e46-10 | if verbose:
print(f"Index {index_name} exists.")
instance: Marqo = cls(
client,
index_name,
searchable_attributes=searchable_attributes,
add_documents_settings=add_documents_settings or {},
page_content_builder=page_content_builder,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
9f102ce8fba8-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 typing import Any, Iterable, List, Optional, Tuple
import requests
from langchain.pydantic_v1 import Field
from langchain.schema import... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/llm_rails.html |
9f102ce8fba8-1 | [docs] def add_texts(
self,
texts: Iterable[str],
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.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/llm_rails.html |
9f102ce8fba8-2 | see API docs for full list
Returns:
List of ids associated with each of the files indexed
"""
files = []
for file in files_list:
if not os.path.exists(file):
logging.error(f"File {file} does not exist, skipping")
continue
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/llm_rails.html |
9f102ce8fba8-3 | timeout=10,
)
if response.status_code != 200:
logging.error(
"Query failed %s",
f"(code {response.status_code}, reason {response.reason}, details "
f"{response.text})",
)
return []
results = response.json()["resu... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/llm_rails.html |
9f102ce8fba8-4 | .. code-block:: python
from langchain.vectorstores import LLMRails
llm_rails = LLMRails.from_texts(
texts,
datastore_id=datastore_id,
api_key=llm_rails_api_key
)
"""
# Note: LLMRails generates its... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/llm_rails.html |
b57c5a0a0ddc-0 | Source code for langchain.vectorstores.milvus
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.schema.embeddings import Embeddings
from langchain.sche... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-1 | index_params (Optional[dict]): Which index params to use. Defaults to
HNSW/AUTOINDEX depending on service.
search_params (Optional[dict]): Which search params to use. Defaults to
default of index.
drop_old (Optional[bool]): Whether to drop the current collection. Defaults
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-2 | secure (bool): Default is false. If set to true, tls will be enabled.
client_key_path (str): If use tls two-way authentication, need to
write the client.key path.
client_pem_path (str): If use tls two-way authentication, need to
write the client.pem path.
ca_pem_path (str... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-3 | ):
"""Initialize the Milvus vector store."""
try:
from pymilvus import Collection, utility
except ImportError:
raise ValueError(
"Could not import pymilvus python package. "
"Please install it with `pip install pymilvus`."
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-4 | self.search_params = search_params
self.consistency_level = consistency_level
# In order for a collection to be compatible, pk needs to be auto'id and int
self._primary_field = primary_field
# In order for compatibility, the text field will need to be called "text"
self._text_fie... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-5 | uri: str = connection_args.get("uri", None)
user = connection_args.get("user", None)
# Order of use is host/port, uri, address
if host is not None and port is not None:
given_address = str(host) + ":" + str(port)
elif uri is not None:
given_address = uri.split("ht... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-6 | ) -> None:
if embeddings is not None:
self._create_collection(embeddings, metadatas)
self._extract_fields()
self._create_index()
self._create_search_params()
self._load()
def _create_collection(
self, embeddings: list, metadatas: Optional[list[dict]] = Non... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-7 | # Create the primary key field
fields.append(
FieldSchema(
self._primary_field, DataType.INT64, is_primary=True, auto_id=True
)
)
# Create the vector field, supports binary or float vectors
fields.append(
FieldSchema(self._vector_field,... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-8 | from pymilvus import Collection, MilvusException
if isinstance(self.col, Collection) and self._get_index() is None:
try:
# If no index params, use a default HNSW based one
if self.index_params is None:
self.index_params = {
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-9 | index_type: str = index["index_param"]["index_type"]
metric_type: str = index["index_param"]["metric_type"]
self.search_params = self.default_search_params[index_type]
self.search_params["metric_type"] = metric_type
def _load(self) -> None:
"""Load the collect... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-10 | Raises:
MilvusException: Failure to add texts
Returns:
List[str]: The resulting keys for each inserted element.
"""
from pymilvus import Collection, MilvusException
texts = list(texts)
try:
embeddings = self.embedding_func.embed_documents(texts... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-11 | # Insert into the collection.
try:
res: Collection
res = self.col.insert(insert_list, timeout=timeout, **kwargs)
pks.extend(res.primary_keys)
except MilvusException as e:
logger.error(
"Failed to insert batch sta... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-12 | 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 similarity search against the query string.
Args:
embedding ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-13 | documentation found here:
https://milvus.io/api-reference/pymilvus/v2.2.6/Collection/search().md
Args:
query (str): The text being searched.
k (int, optional): The amount of results to return. Defaults to 4.
param (dict): The search params for the specified index.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-14 | Args:
embedding (List[float]): The embedding vector being searched.
k (int, optional): The amount of results to return. Defaults to 4.
param (dict): The search params for the specified index.
Defaults to None.
expr (str, optional): Filtering expression. De... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-15 | lambda_mult: float = 0.5,
param: Optional[dict] = None,
expr: Optional[str] = None,
timeout: Optional[int] = None,
**kwargs: Any,
) -> List[Document]:
"""Perform a search and return results that are reordered by MMR.
Args:
query (str): The text being searc... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-16 | self,
embedding: list[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
param: Optional[dict] = None,
expr: Optional[str] = None,
timeout: Optional[int] = None,
**kwargs: Any,
) -> List[Document]:
"""Perform a search and return r... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-17 | anns_field=self._vector_field,
param=param,
limit=fetch_k,
expr=expr,
output_fields=output_fields,
timeout=timeout,
**kwargs,
)
# Organize results.
ids = []
documents = []
scores = []
for result in re... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-18 | collection_name: str = "LangChainCollection",
connection_args: dict[str, Any] = DEFAULT_MILVUS_CONNECTION,
consistency_level: str = "Session",
index_params: Optional[dict] = None,
search_params: Optional[dict] = None,
drop_old: bool = False,
**kwargs: Any,
) -> Milvus... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
b57c5a0a0ddc-19 | drop_old=drop_old,
**kwargs,
)
vector_db.add_texts(texts=texts, metadatas=metadatas)
return vector_db | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
537c741cc790-0 | Source code for langchain.vectorstores.tiledb
"""Wrapper around TileDB vector database."""
from __future__ import annotations
import pickle
import random
import sys
from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple
import numpy as np
from langchain.docstore.document import Document
from langchain.s... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-1 | [docs]def get_documents_array_uri(uri: str) -> str:
return f"{uri}/{DOCUMENTS_ARRAY_NAME}"
[docs]class TileDB(VectorStore):
"""Wrapper around TileDB vector database.
To use, you should have the ``tiledb-vector-search`` python package installed.
Example:
.. code-block:: python
from la... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-2 | group.close()
self.timestamp = timestamp
if self.index_type == "FLAT":
self.vector_index = tiledb_vs.flat_index.FlatIndex(
uri=self.vector_index_uri,
config=self.config,
timestamp=self.timestamp,
**kw... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-3 | self.docs_array_uri, "r", timestamp=self.timestamp, config=self.config
)
for idx, score in zip(ids, scores):
if idx == 0 and score == 0:
continue
if idx == MAX_UINT64 and score == MAX_FLOAT_32:
continue
doc = docs_array[idx]
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-4 | """Return docs most similar to query.
Args:
embedding: Embedding vector to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter (Optional[Dict[str, Any]]): Filter by metadata. Defaults to None.
fetch_k: (Optional[int]) Number of Do... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-5 | 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.
fetch_k: (Optional[int]) Number of Documents to fetch before filtering.
Defau... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-6 | )
return [doc for doc, _ in docs_and_scores]
[docs] def similarity_search(
self,
query: str,
k: int = 4,
filter: Optional[Dict[str, Any]] = None,
fetch_k: int = 20,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to query.
Ar... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-7 | 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 before filtering to
pass to MMR algorithm.
lambda_mult: Number between 0 and 1 that determines the degre... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-8 | [docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
filter: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-9 | **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:
query: Text to look up documents similar to.
k: Number ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-10 | vector_index_uri = get_vector_index_uri(group.uri)
docs_uri = get_documents_array_uri(group.uri)
if index_type == "FLAT":
tiledb_vs.flat_index.create(
uri=vector_index_uri,
dimensions=dimensions,
vector_type=vector_type,... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-11 | embeddings: List[List[float]],
embedding: Embeddings,
index_uri: str,
*,
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
metric: str = DEFAULT_METRIC,
index_type: str = "FLAT",
config: Optional[Mapping[str, Any]] = None,
in... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-12 | input_vectors=input_vectors,
external_ids=external_ids,
index_timestamp=index_timestamp if index_timestamp != 0 else None,
config=config,
**kwargs,
)
with tiledb.open(docs_uri, "w") as A:
if external_ids is None:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-13 | self.vector_index.delete_batch(
external_ids=external_ids, timestamp=timestamp if timestamp != 0 else None
)
return True
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
times... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-14 | metadata_attr = np.empty([len(metadatas)], dtype=object)
i = 0
for metadata in metadatas:
metadata_attr[i] = np.frombuffer(pickle.dumps(metadata), dtype=np.uint8)
i += 1
docs["metadata"] = metadata_attr
docs_array = tiledb.open(
sel... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-15 | index_timestamp: Optional, timestamp to write new texts with.
Example:
.. code-block:: python
from langchain import TileDB
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
index = TileDB.from_texts(texts... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-16 | metric: Optional, Metric to use for indexing. Defaults to "euclidean".
index_type: Optional, Vector index type ("FLAT", IVF_FLAT")
config: Optional, TileDB config
index_timestamp: Optional, timestamp to write new texts with.
Example:
.. code-block:: python
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
537c741cc790-17 | metric: Optional, Metric to use for indexing. Defaults to "euclidean".
config: Optional, TileDB config
timestamp: Optional, timestamp to use for opening the arrays.
"""
return cls(
embedding=embedding,
index_uri=index_uri,
metric=metric,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html |
6954469a780b-0 | Source code for langchain.vectorstores.weaviate
from __future__ import annotations
import datetime
import os
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple,
)
from uuid import uuid4
import numpy as np
from langchain.docstore.document import Docum... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6954469a780b-1 | return 1 - 1 / (1 + np.exp(val))
def _json_serializable(value: Any) -> Any:
if isinstance(value, datetime.datetime):
return value.isoformat()
return value
[docs]class Weaviate(VectorStore):
"""`Weaviate` vector store.
To use, you should have the ``weaviate-client`` python package installed.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6954469a780b-2 | self._query_attrs = [self._text_key]
self.relevance_score_fn = relevance_score_fn
self._by_text = by_text
if attributes is not None:
self._query_attrs.extend(attributes)
@property
def embeddings(self) -> Optional[Embeddings]:
return self._embedding
def _select_rel... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6954469a780b-3 | if "uuids" in kwargs:
_id = kwargs["uuids"][i]
elif "ids" in kwargs:
_id = kwargs["ids"][i]
batch.add_data_object(
data_object=data_properties,
class_name=self._index_name,
uuid=_id,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6954469a780b-4 | """
content: Dict[str, Any] = {"concepts": [query]}
if kwargs.get("search_distance"):
content["certainty"] = kwargs.get("search_distance")
query_obj = self._client.query.get(self._index_name, self._query_attrs)
if kwargs.get("where_filter"):
query_obj = query_obj.... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6954469a780b-5 | if "errors" in result:
raise ValueError(f"Error during query: {result['errors']}")
docs = []
for res in result["data"]["Get"][self._index_name]:
text = res.pop(self._text_key)
docs.append(Document(page_content=text, metadata=res))
return docs
[docs] def max... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6954469a780b-6 | [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.
Maximal marg... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6954469a780b-7 | np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult
)
docs = []
for idx in mmr_selected:
text = payload[idx].pop(self._text_key)
payload[idx].pop("_additional")
meta = payload[idx]
docs.append(Document(page_content=text, metadata=meta))
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6954469a780b-8 | .with_limit(k)
.with_additional("vector")
.do()
)
if "errors" in result:
raise ValueError(f"Error during query: {result['errors']}")
docs_and_scores = []
for res in result["data"]["Get"][self._index_name]:
text = res.pop(self._t... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6954469a780b-9 | embedding: Text embedding model to use.
metadatas: Metadata associated with each text.
client: weaviate.Client to use.
weaviate_url: The Weaviate URL. If using Weaviate Cloud Services get it
from the ``Details`` tab. Can be passed in as a named param or by
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6954469a780b-10 | except ImportError as e:
raise ImportError(
"Could not import weaviate python package. "
"Please install it with `pip install weaviate-client`"
) from e
client = client or _create_weaviate_client(
url=weaviate_url,
api_key=weaviate... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6954469a780b-11 | # like text2vec-contextionary for example
params = {
"uuid": _id,
"data_object": data_properties,
"class_name": index_name,
}
if embeddings is not None:
params["vector"] = embeddings[i]
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
c16601bbdd12-0 | Source code for langchain.vectorstores.faiss
from __future__ import annotations
import asyncio
import logging
import operator
import os
import pickle
import uuid
import warnings
from functools import partial
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Optio... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c16601bbdd12-1 | raise ImportError(
"Could not import faiss python package. "
"Please install it with `pip install faiss-gpu` (for CUDA supported GPU) "
"or `pip install faiss-cpu` (depending on Python version)."
)
return faiss
def _len_check_if_sized(x: Any, y: Any, x_name: str, y_name: ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c16601bbdd12-2 | distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE,
):
"""Initialize with necessary components."""
if not isinstance(embedding_function, Embeddings):
logger.warning(
"`embedding_function` is expected to be an Embeddings object, support "
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c16601bbdd12-3 | # )
raise Exception(
"`embedding_function` is expected to be an Embeddings object, support "
"for passing in a function will soon be removed."
)
def _embed_query(self, text: str) -> List[float]:
if isinstance(self.embedding_function, Embeddings):
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c16601bbdd12-4 | _len_check_if_sized(documents, embeddings, "documents", "embeddings")
_len_check_if_sized(documents, ids, "documents", "ids")
# Add to the index.
vector = np.array(embeddings, dtype=np.float32)
if self._normalize_L2:
faiss.normalize_L2(vector)
self.index.add(vector)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c16601bbdd12-5 | 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
asynchronously.
Args:
texts: Iterable of str... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c16601bbdd12-6 | self,
embedding: List[float],
k: int = 4,
filter: Optional[Dict[str, Any]] = None,
fetch_k: int = 20,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query.
Args:
embedding: Embedding vector to look up documents sim... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c16601bbdd12-7 | if filter is not None:
filter = {
key: [value] if not isinstance(value, list) else value
for key, value in filter.items()
}
if all(doc.metadata.get(key) in value for key, value in filter.items()):
docs.append((do... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c16601bbdd12-8 | score_threshold: Optional, a floating point value between 0 to 1 to
filter the resulting set of retrieved docs
Returns:
List of documents most similar to the query text and L2 distance
in float for each. Lower score represents more similarity.
"""
# Th... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.