id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
02adcd0feed6-5 | k: int = 4,
filter: Optional[dict] = None,
) -> 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]]): Filte... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
02adcd0feed6-6 | .order_by(EmbeddingStore.embedding.op("<->")(embedding))
.join(
CollectionStore,
EmbeddingStore.collection_id == CollectionStore.uuid,
)
.limit(k)
.all()
)
docs = [
(
Document(
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
02adcd0feed6-7 | **kwargs: Any,
) -> AnalyticDB:
"""
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_conne... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
02adcd0feed6-8 | """
texts = [d.page_content for d in documents]
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_... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
9203fb02fc8b-0 | Source code for langchain.vectorstores.zilliz
from __future__ import annotations
import logging
from typing import Any, List, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.milvus import Milvus
logger = logging.getLogger(__name__)
[docs]class Zilliz(Milvus):
def _create_index(... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
9203fb02fc8b-1 | "Failed to create an index on collection: %s", self.collection_name
)
raise e
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
collection_name: str = "LangChainCollecti... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
9203fb02fc8b-2 | Zilliz: Zilliz Vector Store
"""
vector_db = cls(
embedding_function=embedding,
collection_name=collection_name,
connection_args=connection_args,
consistency_level=consistency_level,
index_params=index_params,
search_params=search_pa... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
81d2a0589a39-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 |
81d2a0589a39-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 |
81d2a0589a39-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 |
81d2a0589a39-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 |
81d2a0589a39-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 |
81d2a0589a39-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 |
81d2a0589a39-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 |
81d2a0589a39-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 |
81d2a0589a39-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 |
81d2a0589a39-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 |
81d2a0589a39-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 |
81d2a0589a39-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 |
81d2a0589a39-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 |
81d2a0589a39-13 | res = self.similarity_search_with_score_by_vector(
embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs
)
return res
[docs] def similarity_search_with_score_by_vector(
self,
embedding: List[float],
k: int = 4,
param: Optional[dict] = ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
81d2a0589a39-14 | # Perform the search.
res = self.col.search(
data=[embedding],
anns_field=self._vector_field,
param=param,
limit=k,
expr=expr,
output_fields=output_fields,
timeout=timeout,
**kwargs,
)
# Organize resu... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
81d2a0589a39-15 | Defaults to None.
expr (str, optional): Filtering expression. Defaults to None.
timeout (int, optional): How long to wait before timeout error.
Defaults to None.
kwargs: Collection.search() keyword arguments.
Returns:
List[Document]: Document resul... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
81d2a0589a39-16 | to maximum diversity and 1 to minimum diversity.
Defaults to 0.5
param (dict, optional): The search params for the specified index.
Defaults to None.
expr (str, optional): Filtering expression. Defaults to None.
timeout (int, optional): How lon... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
81d2a0589a39-17 | )
# Reorganize the results from query to match search order.
vectors = {x[self._primary_field]: x[self._vector_field] for x in vectors}
ordered_result_embeddings = [vectors[x] for x in ids]
# Get the new order of results.
new_ordering = maximal_marginal_relevance(
np.... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
81d2a0589a39-18 | "LangChainCollection".
connection_args (dict[str, Any], optional): Connection args to use. Defaults
to DEFAULT_MILVUS_CONNECTION.
consistency_level (str, optional): Which consistency level to use. Defaults
to "Session".
index_params (Optional[dict], op... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
bd2122fec564-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 |
bd2122fec564-1 | vectorstore = Chroma("langchain_store", embeddings.embed_query)
"""
_LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain"
def __init__(
self,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
embedding_function: Optional[Embeddings] = None,
persist_directory: Optional[str... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
bd2122fec564-2 | def __query_collection(
self,
query_texts: Optional[List[str]] = None,
query_embeddings: Optional[List[List[float]]] = None,
n_results: int = 4,
where: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Document]:
"""Query the chroma collection."""
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
bd2122fec564-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 |
bd2122fec564-4 | """Return docs most similar to embedding vector.
Args:
embedding (str): Embedding to look up documents similar to.
k (int): Number of Documents to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
Returns:
List... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
bd2122fec564-5 | [docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = DEFAULT_K,
fetch_k: int = 20,
lambda_mult: float = 0.5,
filter: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected u... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
bd2122fec564-6 | return selected_results
[docs] def max_marginal_relevance_search(
self,
query: str,
k: int = DEFAULT_K,
fetch_k: int = 20,
lambda_mult: float = 0.5,
filter: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
bd2122fec564-7 | """Gets the collection.
Args:
include (Optional[List[str]]): List of fields to include from db.
Defaults to None.
"""
if include is not None:
return self._collection.get(include=include)
else:
return self._collection.get()
[docs] def... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
bd2122fec564-8 | ) -> Chroma:
"""Create a Chroma vectorstore from a raw documents.
If a persist_directory is specified, the collection will be persisted there.
Otherwise, the data will be ephemeral in-memory.
Args:
texts (List[str]): List of texts to add to the collection.
collect... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
bd2122fec564-9 | **kwargs: Any,
) -> Chroma:
"""Create a Chroma vectorstore from a list of documents.
If a persist_directory is specified, the collection will be persisted there.
Otherwise, the data will be ephemeral in-memory.
Args:
collection_name (str): Name of the collection to create... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
02eefeaa0deb-0 | Source code for langchain.vectorstores.redis
"""Wrapper around Redis vector database."""
from __future__ import annotations
import json
import logging
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
02eefeaa0deb-1 | "Redis cannot be used as a vector database without RediSearch >=2.4"
"Please head to https://redis.io/docs/stack/search/quick_start/"
"to know more about installing the RediSearch module within Redis Stack."
)
logging.error(error_message)
raise ValueError(error_message)
def _check_index_exis... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
02eefeaa0deb-2 | redis_url: str,
index_name: str,
embedding_function: Callable,
content_key: str = "content",
metadata_key: str = "metadata",
vector_key: str = "content_vector",
relevance_score_fn: Optional[
Callable[[float], float]
] = _default_relevance_score,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
02eefeaa0deb-3 | )
# Check if index exists
if not _check_index_exists(self.client, self.index_name):
# Define schema
schema = (
TextField(name=self.content_key),
TextField(name=self.metadata_key),
VectorField(
self.vector_key,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
02eefeaa0deb-4 | List[str]: List of ids added to the vectorstore
"""
ids = []
prefix = _redis_prefix(self.index_name)
# Write data to redis
pipeline = self.client.pipeline(transaction=False)
for i, text in enumerate(texts):
# Use provided values by default or fallback
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
02eefeaa0deb-5 | [docs] def similarity_search_limit_score(
self, query: str, k: int = 4, score_threshold: float = 0.2, **kwargs: Any
) -> List[Document]:
"""
Returns the most similar indexed documents to the query text within the
score_threshold range.
Args:
query (str): The qu... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
02eefeaa0deb-6 | return (
Query(base_query)
.return_fields(*return_fields)
.sort_by("vector_score")
.paging(0, k)
.dialect(2)
)
[docs] def similarity_search_with_score(
self, query: str, k: int = 4
) -> List[Tuple[Document, float]]:
"""Return doc... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
02eefeaa0deb-7 | 0 is dissimilar, 1 is most similar.
"""
if self.relevance_score_fn is None:
raise ValueError(
"relevance_score_fn must be provided to"
" Redis constructor to normalize scores"
)
docs_and_scores = self.similarity_search_with_score(query, k=k... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
02eefeaa0deb-8 | redis_url = get_from_dict_or_env(kwargs, "redis_url", "REDIS_URL")
if "redis_url" in kwargs:
kwargs.pop("redis_url")
# Name of the search index if not given
if not index_name:
index_name = uuid.uuid4().hex
# Create instance
instance = cls(
redi... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
02eefeaa0deb-9 | Example:
.. code-block:: python
from langchain.vectorstores import Redis
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
redisearch = RediSearch.from_texts(
texts,
embedd... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
02eefeaa0deb-10 | except ValueError as e:
raise ValueError(f"Your redis connected error: {e}")
# Check if index exists
try:
client.ft(index_name).dropindex(delete_documents)
logger.info("Drop index")
return True
except: # noqa: E722
# Index not exist
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
02eefeaa0deb-11 | return cls(
redis_url,
index_name,
embedding.embed_query,
content_key=content_key,
metadata_key=metadata_key,
vector_key=vector_key,
**kwargs,
)
[docs] def as_retriever(self, **kwargs: Any) -> RedisVectorStoreRetriever:
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
02eefeaa0deb-12 | raise NotImplementedError("RedisVectorStoreRetriever does not support async")
def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]:
"""Add documents to vectorstore."""
return self.vectorstore.add_documents(documents, **kwargs)
async def aadd_documents(
self, doc... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
4ce739f1d8ae-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 |
4ce739f1d8ae-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 |
4ce739f1d8ae-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 |
4ce739f1d8ae-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 |
4ce739f1d8ae-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 |
4ce739f1d8ae-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 |
4ce739f1d8ae-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 |
4ce739f1d8ae-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 |
b316be2a9057-0 | Source code for langchain.vectorstores.faiss
"""Wrapper around FAISS vector database."""
from __future__ import annotations
import math
import os
import pickle
import uuid
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
import numpy as np
from langchain.docstore.base imp... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
b316be2a9057-1 | return faiss
def _default_relevance_score_fn(score: float) -> float:
"""Return a similarity score on a scale [0, 1]."""
# The 'correct' relevance function
# may differ depending on a few things, including:
# - the distance / similarity metric used by the VectorStore
# - the scale of your embeddings ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
b316be2a9057-2 | self._normalize_L2 = normalize_L2
def __add(
self,
texts: Iterable[str],
embeddings: Iterable[List[float]],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
if not isinstance(self.docstore, AddableMixi... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
b316be2a9057-3 | return [_id for _, _id, _ in full_info]
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
b316be2a9057-4 | ids: Optional list of unique IDs.
Returns:
List of ids from adding the texts into the vectorstore.
"""
if not isinstance(self.docstore, AddableMixin):
raise ValueError(
"If trying to add texts, the underlying docstore should support "
f"add... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
b316be2a9057-5 | raise ValueError(f"Could not find document for id {_id}, got {doc}")
docs.append((doc, scores[0][j]))
return docs
[docs] def similarity_search_with_score(
self, query: str, k: int = 4
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query.
Args:
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
b316be2a9057-6 | Returns:
List of Documents most similar to the query.
"""
docs_and_scores = self.similarity_search_with_score(query, k)
return [doc for doc, _ in docs_and_scores]
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
b316be2a9057-7 | docs = []
for i in selected_indices:
if i == -1:
# This happens when not enough docs are returned.
continue
_id = self.index_to_docstore_id[i]
doc = self.docstore.search(_id)
if not isinstance(doc, Document):
raise V... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
b316be2a9057-8 | Add the target FAISS to the current one.
Args:
target: FAISS object you wish to merge into the current one
Returns:
None.
"""
if not isinstance(self.docstore, AddableMixin):
raise ValueError("Cannot merge with this type of docstore")
# Numerica... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
b316be2a9057-9 | vector = np.array(embeddings, dtype=np.float32)
if normalize_L2:
faiss.normalize_L2(vector)
index.add(vector)
documents = []
if ids is None:
ids = [str(uuid.uuid4()) for _ in texts]
for i, text in enumerate(texts):
metadata = metadatas[i] if me... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
b316be2a9057-10 | return cls.__from(
texts,
embeddings,
embedding,
metadatas=metadatas,
ids=ids,
**kwargs,
)
[docs] @classmethod
def from_embeddings(
cls,
text_embeddings: List[Tuple[str, List[float]]],
embedding: Embeddings,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
b316be2a9057-11 | Args:
folder_path: folder path to save index, docstore,
and index_to_docstore_id to.
index_name: for saving with a specific index file name
"""
path = Path(folder_path)
path.mkdir(exist_ok=True, parents=True)
# save index separately since it is not... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
b316be2a9057-12 | docstore, index_to_docstore_id = pickle.load(f)
return cls(embeddings.embed_query, index, docstore, index_to_docstore_id)
def _similarity_search_with_relevance_scores(
self,
query: str,
k: int = 4,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs a... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
dcde2486da8f-0 | Source code for langchain.vectorstores.typesense
"""Wrapper around Typesense vector search"""
from __future__ import annotations
import uuid
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
fro... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
dcde2486da8f-1 | *,
typesense_collection_name: Optional[str] = None,
text_key: str = "text",
):
"""Initialize with Typesense client."""
try:
from typesense import Client
except ImportError:
raise ValueError(
"Could not import typesense python package. "... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
dcde2486da8f-2 | ]
def _create_collection(self, num_dim: int) -> None:
fields = [
{"name": "vec", "type": "float[]", "num_dim": num_dim},
{"name": f"{self._text_key}", "type": "string"},
{"name": ".*", "type": "auto"},
]
self._typesense_client.collections.create(
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
dcde2486da8f-3 | self,
query: str,
k: int = 4,
filter: Optional[str] = "",
) -> List[Tuple[Document, float]]:
"""Return typesense documents most similar to query, along with scores.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. De... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
dcde2486da8f-4 | k: Number of Documents to return. Defaults to 4.
filter: typesense filter_by expression to filter documents on
Returns:
List of Documents most similar to the query and score for each
"""
docs_and_score = self.similarity_search_with_score(query, k=k, filter=filter)
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
dcde2486da8f-5 | }
typesense_api_key = typesense_api_key or get_from_env(
"typesense_api_key", "TYPESENSE_API_KEY"
)
client_config = {
"nodes": [node],
"api_key": typesense_api_key,
"connection_timeout_seconds": connection_timeout_seconds,
}
return ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
eecc4721e403-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 |
eecc4721e403-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 |
eecc4721e403-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 |
eecc4721e403-3 | if self.verbose:
print(
f"Deep Lake Dataset in {dataset_path} already exists, "
f"loading from the storage"
)
self.ds.summary()
else:
if "overwrite" in kwargs:
del kwargs["overwrite"]
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
eecc4721e403-4 | **kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
texts (Iterable[str]): Texts to add to the vectorstore.
metadatas (Optional[List[dict]], optional): Optional list of metadatas.
ids (Optional[List[str]], opti... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
eecc4721e403-5 | if batch_size == 0:
return []
batched = [
elements[i : i + batch_size] for i in range(0, len(elements), batch_size)
]
ingest().eval(
batched,
self.ds,
num_workers=min(self.num_workers, len(batched) // max(self.num_workers, 1)),
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
eecc4721e403-6 | take [Deep Lake filter]
(https://docs.deeplake.ai/en/latest/deeplake.core.dataset.html#deeplake.core.dataset.Dataset.filter)
Defaults to None.
maximal_marginal_relevance: Whether to use maximal marginal relevance.
Defaults to False.
fetch_k: Number of ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
eecc4721e403-7 | distance_metric=distance_metric.lower(),
)
view = view[indices]
if use_maximal_marginal_relevance:
lambda_mult = kwargs.get("lambda_mult", 0.5)
indices = maximal_marginal_relevance(
query_emb,
embeddings[indices]... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
eecc4721e403-8 | maximal_marginal_relevance: Whether to use maximal marginal relevance.
Defaults to False.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
Defaults to 20.
return_score: Whether to return the score. Defaults to False.
Returns:
Lis... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
eecc4721e403-9 | filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
Returns:
List[Tuple[Document, float]]: List of documents most similar to the query
text with distance in float.
"""
return self._search_helper(
query=query,
k=k,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
eecc4721e403-10 | self,
query: str,
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
amon... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
eecc4721e403-11 | ) -> DeepLake:
"""Create a Deep Lake dataset from a raw documents.
If a dataset_path is specified, the dataset will be persisted in that location,
otherwise by default at `./deeplake`
Args:
path (str, pathlib.Path): - The full path to the dataset. Can be:
- De... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
eecc4721e403-12 | dataset_path=dataset_path, embedding_function=embedding, **kwargs
)
deeplake_dataset.add_texts(texts=texts, metadatas=metadatas, ids=ids)
return deeplake_dataset
[docs] def delete(
self,
ids: Any[List[str], None] = None,
filter: Any[Dict[str, str], None] = None,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
eecc4721e403-13 | try:
import deeplake
except ImportError:
raise ValueError(
"Could not import deeplake python package. "
"Please install it with `pip install deeplake`."
)
deeplake.delete(path, large_ok=True, force=True)
[docs] def delete_dataset(sel... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
127e71536697-0 | Source code for langchain.vectorstores.base
"""Interface for vector stores."""
from __future__ import annotations
import asyncio
import warnings
from abc import ABC, abstractmethod
from functools import partial
from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, TypeVar
from pydantic import BaseModel, ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
127e71536697-1 | Args:
documents (List[Document]: Documents to add to the vectorstore.
Returns:
List[str]: List of IDs of the added texts.
"""
# TODO: Handle the case where the user doesn't provide ids on the Collection
texts = [doc.page_content for doc in documents]
metad... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
127e71536697-2 | self, query: str, search_type: str, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query using specified search type."""
if search_type == "similarity":
return await self.asimilarity_search(query, **kwargs)
elif search_type == "mmr":
return await se... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
127e71536697-3 | query, k=k, **kwargs
)
if any(
similarity < 0.0 or similarity > 1.0
for _, similarity in docs_and_similarities
):
warnings.warn(
"Relevance scores must be between"
f" 0 and 1, got {docs_and_similarities}"
)
s... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
127e71536697-4 | func = partial(self.similarity_search_with_relevance_scores, query, k, **kwargs)
return await asyncio.get_event_loop().run_in_executor(None, func)
[docs] async def asimilarity_search(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query."""... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
127e71536697-5 | [docs] def max_marginal_relevance_search(
self,
query: str,
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimiz... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
127e71536697-6 | )
return await asyncio.get_event_loop().run_in_executor(None, func)
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Ret... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
127e71536697-7 | ) -> VST:
"""Return VectorStore initialized from documents and embeddings."""
texts = [d.page_content for d in documents]
metadatas = [d.metadata for d in documents]
return cls.from_texts(texts, embedding, metadatas=metadatas, **kwargs)
[docs] @classmethod
async def afrom_document... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
127e71536697-8 | class VectorStoreRetriever(BaseRetriever, BaseModel):
vectorstore: VectorStore
search_type: str = "similarity"
search_kwargs: dict = Field(default_factory=dict)
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
@root_validator()
def valida... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
127e71536697-9 | query, **self.search_kwargs
)
else:
raise ValueError(f"search_type of {self.search_type} not allowed.")
return docs
async def aget_relevant_documents(self, query: str) -> List[Document]:
if self.search_type == "similarity":
docs = await self.vectorstore.as... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.