id stringlengths 14 16 | text stringlengths 29 2.73k | source stringlengths 50 116 |
|---|---|---|
ae72e5742c75-4 | # Write data to redis
pipeline = self.client.pipeline(transaction=False)
for i, text in enumerate(texts):
# Use provided values by default or fallback
key = keys[i] if keys else _redis_key(prefix)
metadata = metadatas[i] if metadatas else {}
embedding = em... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
ae72e5742c75-5 | Returns the most similar indexed documents to the query text within the
score_threshold range.
Args:
query (str): The query text for which to find similar documents.
k (int): The number of documents to return. Default is 4.
score_threshold (float): The minimum matchin... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
ae72e5742c75-6 | )
[docs] def similarity_search_with_score(
self, query: str, k: int = 4
) -> 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.
Returns:
... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
ae72e5742c75-7 | " Weaviate constructor to normalize scores"
)
docs_and_scores = self.similarity_search_with_score(query, k=k)
return [(doc, self.relevance_score_fn(score)) for doc, score in docs_and_scores]
[docs] @classmethod
def from_texts(
cls: Type[Redis],
texts: List[str],
... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
ae72e5742c75-8 | # Create instance
instance = cls(
redis_url=redis_url,
index_name=index_name,
embedding_function=embedding.embed_query,
content_key=content_key,
metadata_key=metadata_key,
vector_key=vector_key,
**kwargs,
)
# Cre... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
ae72e5742c75-9 | # Check if index exists
try:
client.ft(index_name).dropindex(delete_documents)
logger.info("Drop index")
return True
except: # noqa: E722
# Index not exist
return False
[docs] @classmethod
def from_existing_index(
cls,
e... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
ae72e5742c75-10 | metadata_key=metadata_key,
vector_key=vector_key,
**kwargs,
)
[docs] def as_retriever(self, **kwargs: Any) -> BaseRetriever:
return RedisVectorStoreRetriever(vectorstore=self, **kwargs)
class RedisVectorStoreRetriever(BaseRetriever, BaseModel):
vectorstore: Redis
searc... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
ae72e5742c75-11 | """Add documents to vectorstore."""
return self.vectorstore.add_documents(documents, **kwargs)
async def aadd_documents(
self, documents: List[Document], **kwargs: Any
) -> List[str]:
"""Add documents to vectorstore."""
return await self.vectorstore.aadd_documents(documents, **kw... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
c7c3352ec5ed-0 | Source code for langchain.vectorstores.supabase
from __future__ import annotations
from itertools import repeat
from typing import (
TYPE_CHECKING,
Any,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
)
import numpy as np
from langchain.docstore.document import Document
from langchain.embe... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
c7c3352ec5ed-1 | embedding: Embeddings,
table_name: str,
query_name: Union[str, None] = None,
) -> None:
"""Initialize with supabase client."""
try:
import supabase # noqa: F401
except ImportError:
raise ValueError(
"Could not import supabase python pa... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
c7c3352ec5ed-2 | if not table_name:
raise ValueError("Supabase document table_name is required.")
embeddings = embedding.embed_documents(texts)
docs = cls._texts_to_documents(texts, metadatas)
_ids = cls._add_vectors(client, table_name, embeddings, docs)
return cls(
client=client,... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
c7c3352ec5ed-3 | self, query: List[float], k: int
) -> List[Tuple[Document, float]]:
match_documents_params = dict(query_embedding=query, match_count=k)
res = self._client.rpc(self.query_name, match_documents_params).execute()
match_result = [
(
Document(
metad... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
c7c3352ec5ed-4 | metadatas: Optional[Iterable[dict[Any, Any]]] = None,
) -> List[Document]:
"""Return list of Documents from list of texts and metadatas."""
if metadatas is None:
metadatas = repeat({})
docs = [
Document(page_content=text, metadata=metadata)
for text, metad... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
c7c3352ec5ed-5 | return id_list
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
c7c3352ec5ed-6 | k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
c7c3352ec5ed-7 | $$;```
"""
embedding = self._embedding.embed_documents([query])
docs = self.max_marginal_relevance_search_by_vector(
embedding[0], k, fetch_k, lambda_mult=lambda_mult
)
return docs
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
cc31a9c28de1-0 | Source code for langchain.vectorstores.qdrant
"""Wrapper around Qdrant vector database."""
from __future__ import annotations
import uuid
from hashlib import md5
from operator import itemgetter
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, Union
from langchain.docstore.document import D... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
cc31a9c28de1-1 | if not isinstance(client, qdrant_client.QdrantClient):
raise ValueError(
f"client should be an instance of qdrant_client.QdrantClient, "
f"got {type(client)}"
)
self.client: qdrant_client.QdrantClient = client
self.collection_name = collection_name... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
cc31a9c28de1-2 | k: int = 4,
filter: Optional[MetadataFilter] = None,
**kwargs: Any,
) -> List[Document]:
"""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: Filter by met... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
cc31a9c28de1-3 | 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/qdrant.html |
cc31a9c28de1-4 | embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
location: Optional[str] = None,
url: Optional[str] = None,
port: Optional[int] = 6333,
grpc_port: int = 6334,
prefer_grpc: bool = False,
https: Optional[bool] = None,
api_key: Optional[str] = N... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
cc31a9c28de1-5 | grpc_port: Port of the gRPC interface. Default: 6334
prefer_grpc:
If true - use gPRC interface whenever possible in custom methods.
Default: False
https: If true - use HTTPS(SSL) protocol. Default: None
api_key: API key for authentication in Qdrant Clo... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
cc31a9c28de1-6 | 2. Initializes the Qdrant database as an in-memory docstore by default
(and overridable to a remote docstore)
3. Adds the text embeddings to the Qdrant database
This is intended to be a quick way to get started.
Example:
.. code-block:: python
from ... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
cc31a9c28de1-7 | ),
)
# Now generate the embeddings for all the texts
embeddings = embedding.embed_documents(texts)
client.upsert(
collection_name=collection_name,
points=rest.Batch.construct(
ids=[md5(text.encode("utf-8")).hexdigest() for text in texts],
... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
cc31a9c28de1-8 | metadata_payload_key: str,
) -> Document:
return Document(
page_content=scored_point.payload.get(content_payload_key),
metadata=scored_point.payload.get(metadata_payload_key) or {},
)
def _qdrant_filter_from_dict(self, filter: Optional[MetadataFilter]) -> Any:
if ... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
f64865aede8e-0 | Source code for langchain.vectorstores.milvus
"""Wrapper around the Milvus vector database."""
from __future__ import annotations
import logging
from typing import Any, Iterable, List, Optional, Tuple, Union
from uuid import uuid4
import numpy as np
from langchain.docstore.document import Document
from langchain.embedd... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-1 | The connection args used for this class comes in the form of a dict,
here are a few of the options:
address (str): The actual address of Milvus
instance. Example address: "localhost:19530"
uri (str): The uri of Milvus instance. Example uri:
"http://randomw... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-2 | Args:
embedding_function (Embeddings): Function used to embed the text.
collection_name (str): Which Milvus collection to use. Defaults to
"LangChainCollection".
connection_args (Optional[dict[str, any]]): The arguments for connection to
Milvus/Zilliz ... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-3 | "RHNSW_SQ": {"metric_type": "L2", "params": {"ef": 10}},
"RHNSW_PQ": {"metric_type": "L2", "params": {"ef": 10}},
"IVF_HNSW": {"metric_type": "L2", "params": {"nprobe": 10, "ef": 10}},
"ANNOY": {"metric_type": "L2", "params": {"search_k": 10}},
"AUTOINDEX": {"metric_type"... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-4 | if drop_old and isinstance(self.col, Collection):
self.col.drop()
self.col = None
# Initialize the vector store
self._init()
def _create_connection_alias(self, connection_args: dict) -> str:
"""Create the connection to the Milvus server."""
from pymilvus impor... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-5 | and ("user" in addr)
and (addr["user"] == tmp_user)
):
logger.debug("Using previous connection: %s", con[0])
return con[0]
# Generate a new connection if one doesnt exist
alias = uuid4().hex
try:
connections.... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-6 | # Datatype isnt compatible
if dtype == DataType.UNKNOWN or dtype == DataType.NONE:
logger.error(
"Failure to create collection, unrecognized dtype for key: %s",
key,
)
raise ValueError(f"Unrecogni... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-7 | schema = self.col.schema
for x in schema.fields:
self.fields.append(x.name)
# Since primary field is auto-id, no need to track it
self.fields.remove(self._primary_field)
def _get_index(self) -> Optional[dict[str, Any]]:
"""Return the vector index informati... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-8 | using=self.alias,
)
logger.debug(
"Successfully created an index on collection: %s",
self.collection_name,
)
except MilvusException as e:
logger.error(
"Failed to create an index o... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-9 | embedding and the columns are decided by the first metadata dict.
Metada keys will need to be present for all inserted values. At
the moment there is no None equivalent in Milvus.
Args:
texts (Iterable[str]): The texts to embed, it is assumed
that they all fit in memo... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-10 | for key, value in d.items():
if key in self.fields:
insert_dict.setdefault(key, []).append(value)
# Total insert count
vectors: list = insert_dict[self._vector_field]
total_count = len(vectors)
pks: list[str] = []
assert isinstance(self... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-11 | Defaults to None.
expr (str, optional): Filtering expression. Defaults to None.
timeout (int, optional): How long to wait before timeout error.
Defaults to None.
kwargs: Collection.search() keyword arguments.
Returns:
List[Document]: Document resul... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-12 | return []
res = self.similarity_search_with_score_by_vector(
embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs
)
return [doc for doc, _ in res]
[docs] def similarity_search_with_score(
self,
query: str,
k: int = 4,
param: O... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-13 | output_fields = self.fields[:]
output_fields.remove(self._vector_field)
res = self.similarity_search_with_score_by_vector(
embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs
)
return res
[docs] def similarity_search_with_score_by_vector(
se... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-14 | # Determine result metadata fields.
output_fields = self.fields[:]
output_fields.remove(self._vector_field)
# Perform the search.
res = self.col.search(
data=[embedding],
anns_field=self._vector_field,
param=param,
limit=k,
expr... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-15 | to maximum diversity and 1 to minimum diversity.
Defaults to 0.5
param (dict, optional): The search params for the specified index.
Defaults to None.
expr (str, optional): Filtering expression. Defaults to None.
timeout (int, optional): How lon... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-16 | lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5
param (dict, optional): The search params for the specif... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-17 | output_fields=[self._primary_field, self._vector_field],
timeout=timeout,
)
# Reorganize the results from query to match search order.
vectors = {x[self._primary_field]: x[self._vector_field] for x in vectors}
ordered_result_embeddings = [vectors[x] for x in ids]
# Ge... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
f64865aede8e-18 | Defaults to None.
collection_name (str, optional): Collection name to use. Defaults to
"LangChainCollection".
connection_args (dict[str, Any], optional): Connection args to use. Defaults
to DEFAULT_MILVUS_CONNECTION.
consistency_level (str, optional): ... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
1a1b159ea9a6-0 | Source code for langchain.vectorstores.chroma
"""Wrapper around ChromaDB embeddings platform."""
from __future__ import annotations
import logging
import uuid
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Type
import numpy as np
from langchain.docstore.document import Document
from langc... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
1a1b159ea9a6-1 | """
_LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain"
def __init__(
self,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
embedding_function: Optional[Embeddings] = None,
persist_directory: Optional[str] = None,
client_settings: Optional[chromadb.config.Settings... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
1a1b159ea9a6-2 | self,
query_texts: Optional[List[str]] = None,
query_embeddings: Optional[List[List[float]]] = None,
n_results: int = 4,
where: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Document]:
"""Query the chroma collection."""
try:
import chro... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
1a1b159ea9a6-3 | ids (Optional[List[str]], optional): Optional list of IDs.
Returns:
List[str]: List of IDs of the added texts.
"""
# TODO: Handle the case where the user doesn't provide ids on the Collection
if ids is None:
ids = [str(uuid.uuid1()) for _ in texts]
embeddi... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
1a1b159ea9a6-4 | """Return docs most similar to embedding vector.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
Returns:
List of Documents most similar to the query vector.
"""
results = self.__query_collec... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
1a1b159ea9a6-5 | k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
filter: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversi... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
1a1b159ea9a6-6 | self,
query: str,
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
filter: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes f... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
1a1b159ea9a6-7 | return self._collection.get()
[docs] def persist(self) -> None:
"""Persist the collection.
This can be used to explicitly persist the data to disk.
It will also be called automatically when the object is destroyed.
"""
if self._persist_directory is None:
raise Valu... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
1a1b159ea9a6-8 | Args:
texts (List[str]): List of texts to add to the collection.
collection_name (str): Name of the collection to create.
persist_directory (Optional[str]): Directory to persist the collection.
embedding (Optional[Embeddings]): Embedding function. Defaults to None.
... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
1a1b159ea9a6-9 | Otherwise, the data will be ephemeral in-memory.
Args:
collection_name (str): Name of the collection to create.
persist_directory (Optional[str]): Directory to persist the collection.
ids (Optional[List[str]]): List of document IDs. Defaults to None.
documents (Li... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
34c1b993f34d-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 |
34c1b993f34d-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 |
34c1b993f34d-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 |
34c1b993f34d-3 | del kwargs["overwrite"]
self.ds = deeplake.empty(
dataset_path, token=token, overwrite=True, **kwargs
)
with self.ds:
self.ds.create_tensor(
"text",
htype="text",
create_id_tensor=False,
... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
34c1b993f34d-4 | ids (Optional[List[str]], optional): Optional list of IDs.
Returns:
List[str]: List of IDs of the added texts.
"""
if ids is None:
ids = [str(uuid.uuid1()) for _ in texts]
text_list = list(texts)
if metadatas is None:
metadatas = [{}] * len(tex... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
34c1b993f34d-5 | **kwargs,
)
self.ds.commit(allow_empty=True)
self.ds.summary()
return ids
def _search_helper(
self,
query: Any[str, None] = None,
embedding: Any[float, None] = None,
k: int = 4,
distance_metric: str = "L2",
use_maximal_marginal_relevanc... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
34c1b993f34d-6 | return_score: Whether to return the score. Defaults to False.
Returns:
List of Documents selected by the specified distance metric,
if return_score True, return a tuple of (Document, score)
"""
view = self.ds
# attribute based filtering
if filter is not No... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
34c1b993f34d-7 | view = view[indices]
scores = [scores[i] for i in indices]
docs = [
Document(
page_content=el["text"].data()["value"],
metadata=el["metadata"].data()["value"],
)
for el in view
]
if return_score:
retu... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
34c1b993f34d-8 | [docs] def similarity_search_by_vector(
self, embedding: List[float], k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to embedding vector.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defau... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
34c1b993f34d-9 | [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... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
34c1b993f34d-10 | Args:
query: Text 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 among th... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
34c1b993f34d-11 | To write to Deep Lake cloud datasets,
ensure that you are logged in to Deep Lake
(use 'activeloop login' from command line)
- AWS S3 path of the form ``s3://bucketname/path/to/dataset``.
Credentials are required in either the environment
... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
34c1b993f34d-12 | ) -> bool:
"""Delete the entities in the dataset
Args:
ids (Optional[List[str]], optional): The document_ids to delete.
Defaults to None.
filter (Optional[Dict[str, str]], optional): The filter to delete by.
Defaults to None.
delete_all... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
34c1b993f34d-13 | """Persist the collection."""
self.ds.flush()
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 02, 2023. | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
7b39e697abd8-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 |
7b39e697abd8-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))
[docs]class Weaviate(VectorStore):
"""Wrapper around Weaviate vector database.
To... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7b39e697abd8-2 | self._embedding = embedding
self._text_key = text_key
self._query_attrs = [self._text_key]
self._relevance_score_fn = relevance_score_fn
if attributes is not None:
self._query_attrs.extend(attributes)
[docs] def add_texts(
self,
texts: Iterable[str],
... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7b39e697abd8-3 | self, query: str, k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
Returns:
List of Documents most similar to the query.... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7b39e697abd8-4 | 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... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7b39e697abd8-5 | [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... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7b39e697abd8-6 | text = payload[idx].pop(self._text_key)
payload[idx].pop("_additional")
meta = payload[idx]
docs.append(Document(page_content=text, metadata=meta))
return docs
[docs] def similarity_search_with_score(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Tuple[... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7b39e697abd8-7 | """Return docs and relevance scores, normalized on a scale from 0 to 1.
0 is dissimilar, 1 is most similar.
"""
if self._relevance_score_fn is None:
raise ValueError(
"relevance_score_fn must be provided to"
" Weaviate constructor to normalize scores"
... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7b39e697abd8-8 | from weaviate.util import get_valid_uuid
index_name = kwargs.get("index_name", f"LangChain_{uuid4().hex}")
embeddings = embedding.embed_documents(texts) if embedding else None
text_key = "text"
schema = _default_schema(index_name)
attributes = list(metadatas[0].keys()) if metadat... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
21f9eb2c1541-0 | Source code for langchain.vectorstores.analyticdb
"""VectorStore wrapper around a Postgres/PGVector database."""
from __future__ import annotations
import logging
import uuid
from typing import Any, Dict, Iterable, List, Optional, Tuple
import sqlalchemy
from sqlalchemy import REAL, Index
from sqlalchemy.dialects.postg... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
21f9eb2c1541-1 | """
created = False
collection = cls.get_by_name(session, name)
if collection:
return collection, created
collection = cls(name=name, cmetadata=cmetadata)
session.add(collection)
session.commit()
created = True
return collection, created
class ... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
21f9eb2c1541-2 | - `connection_string` is a postgres connection string.
- `embedding_function` any embedding function implementing
`langchain.embeddings.base.Embeddings` interface.
- `collection_name` is the name of the collection to use. (default: langchain)
- NOTE: This is not the name of the table, but the na... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
21f9eb2c1541-3 | return conn
[docs] def create_tables_if_not_exists(self) -> None:
Base.metadata.create_all(self._conn)
[docs] def drop_tables(self) -> None:
Base.metadata.drop_all(self._conn)
[docs] def create_collection(self) -> None:
if self.pre_delete_collection:
self.delete_collection()... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
21f9eb2c1541-4 | embeddings = self.embedding_function.embed_documents(list(texts))
if not metadatas:
metadatas = [{} for _ in texts]
with Session(self._conn) as session:
collection = self.get_collection(session)
if not collection:
raise ValueError("Collection not found... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
21f9eb2c1541-5 | """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.
Returns:
List of Documents most similar to th... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
21f9eb2c1541-6 | EmbeddingStore.collection_id == CollectionStore.uuid,
)
.limit(k)
.all()
)
docs = [
(
Document(
page_content=result.EmbeddingStore.document,
metadata=result.EmbeddingStore.cmetadata,
)... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
21f9eb2c1541-7 | Return VectorStore initialized from texts and embeddings.
Postgres connection string is required
Either pass it as a parameter
or set the PGVECTOR_CONNECTION_STRING environment variable.
"""
connection_string = cls.get_connection_string(kwargs)
store = cls(
co... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
21f9eb2c1541-8 | metadatas = [d.metadata for d in documents]
connection_string = cls.get_connection_string(kwargs)
kwargs["connection_string"] = connection_string
return cls.from_texts(
texts=texts,
pre_delete_collection=pre_delete_collection,
embedding=embedding,
... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
e4c3864aa260-0 | Source code for langchain.vectorstores.elastic_vector_search
"""Wrapper around Elasticsearch vector database."""
from __future__ import annotations
import uuid
from abc import ABC
from typing import Any, Dict, Iterable, List, Optional, Tuple
from langchain.docstore.document import Document
from langchain.embeddings.bas... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
e4c3864aa260-1 | # and attributes.
[docs]class ElasticVectorSearch(VectorStore, ABC):
"""Wrapper around Elasticsearch as a vector database.
To connect to an Elasticsearch instance that does not require
login credentials, pass the Elasticsearch URL and index name along with the
embedding object to the constructor.
Ex... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
e4c3864aa260-2 | Example:
.. code-block:: python
from langchain import ElasticVectorSearch
from langchain.embeddings import OpenAIEmbeddings
embedding = OpenAIEmbeddings()
elastic_host = "cluster_id.region_id.gcp.cloud.es.io"
elasticsearch_url = f"https://username:pass... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
e4c3864aa260-3 | [docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
refresh_indices: bool = True,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of ... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
e4c3864aa260-4 | "metadata": metadata,
"_id": _id,
}
ids.append(_id)
requests.append(request)
bulk(self.client, requests)
if refresh_indices:
self.client.indices.refresh(index=self.index_name)
return ids
[docs] def similarity_search(
self... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
e4c3864aa260-5 | (
Document(
page_content=hit["_source"]["text"],
metadata=hit["_source"]["metadata"],
),
hit["_score"],
)
for hit in hits
]
return docs_and_scores
[docs] @classmethod
def from_texts(
... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
e4c3864aa260-6 | except ValueError as e:
raise ValueError(
"Your elasticsearch client string is misformatted. " f"Got error: {e} "
)
index_name = kwargs.get("index_name", uuid.uuid4().hex)
embeddings = embedding.embed_documents(texts)
dim = len(embeddings[0])
mappi... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
2bee036c9c06-0 | Source code for langchain.vectorstores.pinecone
"""Wrapper around Pinecone vector database."""
from __future__ import annotations
import uuid
from typing import Any, Callable, Iterable, List, Optional, Tuple
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
2bee036c9c06-1 | 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: Optional[List[str]] = None,
namespace: Optional[str] = None,
... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
2bee036c9c06-2 | 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 return. Defaults to 4... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
2bee036c9c06-3 | namespace: Namespace to search in. Default will search in '' namespace.
Returns:
List of Documents most similar to the query and score for each
"""
if namespace is None:
namespace = self._namespace
query_obj = self._embedding_function(query)
docs = []
... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
2bee036c9c06-4 | pinecone.init(api_key="***", environment="...")
embeddings = OpenAIEmbeddings()
pinecone = Pinecone.from_texts(
texts,
embeddings,
index_name="langchain-demo"
)
"""
try:
import pinecon... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
2bee036c9c06-5 | metadata = metadatas[i:i_end]
else:
metadata = [{} for _ in range(i, i_end)]
for j, line in enumerate(lines_batch):
metadata[j][text_key] = line
to_upsert = zip(ids_batch, embeds, metadata)
# upsert to Pinecone
index.upsert(vect... | https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
6607a9e20659-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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.