id stringlengths 14 16 | text stringlengths 29 2.73k | source stringlengths 49 117 |
|---|---|---|
364279978df9-4 | request = {
"_op_type": "index",
"_index": self.index_name,
"vector": embeddings[i],
"text": text,
"metadata": metadata,
"_id": _id,
}
ids.append(_id)
requests.append(request)
bulk... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
364279978df9-5 | self.client, self.index_name, script_query, size=k
)
hits = [hit for hit in response["hits"]["hits"]]
docs_and_scores = [
(
Document(
page_content=hit["_source"]["text"],
metadata=hit["_source"]["metadata"],
),
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
364279978df9-6 | )
index_name = index_name or uuid.uuid4().hex
vectorsearch = cls(elasticsearch_url, index_name, embedding, **kwargs)
vectorsearch.add_texts(
texts, metadatas=metadatas, refresh_indices=refresh_indices
)
return vectorsearch
[docs] def create_index(self, client: Any,... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d60c7e0e145e-0 | Source code for langchain.vectorstores.vectara
"""Wrapper around Vectara vector database."""
from __future__ import annotations
import json
import logging
import os
from hashlib import md5
from typing import Any, Iterable, List, Optional, Tuple, Type
import requests
from pydantic import Field
from langchain.embeddings.... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
d60c7e0e145e-1 | or self._vectara_api_key is None
):
logging.warning(
"Cant find Vectara credentials, customer_id or corpus_id in "
"environment."
)
else:
logging.debug(f"Using corpus id {self._vectara_corpus_id}")
self._session = requests.Sessi... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
d60c7e0e145e-2 | f"{response.text}"
)
return False
return True
def _index_doc(self, doc_id: str, text: str, metadata: dict) -> bool:
request: dict[str, Any] = {}
request["customer_id"] = self._vectara_customer_id
request["corpus_id"] = self._vectara_corpus_id
request["... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
d60c7e0e145e-3 | for i, doc in enumerate(texts):
doc_id = ids[i]
metadata = metadatas[i] if metadatas else {}
succeeded = self._index_doc(doc_id, doc, metadata)
if not succeeded:
self._delete_doc(doc_id)
self._index_doc(doc_id, doc, metadata)
return... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
d60c7e0e145e-4 | "context_config": {
"sentences_before": 3,
"sentences_after": 3,
},
"corpus_key": [
{
"customer_id": self._vectara_customer_id,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
d60c7e0e145e-5 | Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 5.
filter: Dictionary of argument(s) to filter on metadata. For example a
filter can be "doc.rating > 3.0 and part.lang = 'deu'"} see
https://docs.vectara.... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
d60c7e0e145e-6 | return VectaraRetriever(vectorstore=self, **kwargs)
class VectaraRetriever(VectorStoreRetriever):
vectorstore: Vectara
search_kwargs: dict = Field(default_factory=lambda: {"alpha": 0.025, "k": 5})
"""Search params.
k: Number of Documents to return. Defaults to 5.
alpha: parameter for hybrid ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
78f9d3444a18-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 |
78f9d3444a18-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 |
78f9d3444a18-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 |
78f9d3444a18-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 |
78f9d3444a18-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 |
78f9d3444a18-5 | 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:
query: Text to look up documents similar to.
k: Number of Docum... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
78f9d3444a18-6 | """
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,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwa... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
78f9d3444a18-7 | 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 ValueError(f"Could ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
78f9d3444a18-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 |
78f9d3444a18-9 | 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 metadatas else {}
documents.append(Document(pa... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
78f9d3444a18-10 | embedding,
metadatas=metadatas,
ids=ids,
**kwargs,
)
[docs] @classmethod
def from_embeddings(
cls,
text_embeddings: List[Tuple[str, List[float]]],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
ids: Optional[List[... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
78f9d3444a18-11 | 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 picklable
faiss = dependable_faiss_import()
faiss.write_index(
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
78f9d3444a18-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 |
9641740eaab1-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 |
9641740eaab1-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 |
9641740eaab1-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 |
9641740eaab1-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 |
9641740eaab1-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 |
9641740eaab1-5 | 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.connect(alias=alias, **connection_args)
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9641740eaab1-6 | if dtype == DataType.UNKNOWN or dtype == DataType.NONE:
logger.error(
"Failure to create collection, unrecognized dtype for key: %s",
key,
)
raise ValueError(f"Unrecognized datatype for {key}.")
#... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9641740eaab1-7 | 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 information if it exists"""
from pymil... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9641740eaab1-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 |
9641740eaab1-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 |
9641740eaab1-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 |
9641740eaab1-11 | 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 results for search.
"""
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
9641740eaab1-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 |
9641740eaab1-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 |
9641740eaab1-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 |
9641740eaab1-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 |
9641740eaab1-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 |
9641740eaab1-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 |
9641740eaab1-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 |
17ac47c2da1f-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 |
17ac47c2da1f-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 |
17ac47c2da1f-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 |
17ac47c2da1f-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 |
17ac47c2da1f-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 |
17ac47c2da1f-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 |
17ac47c2da1f-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 |
17ac47c2da1f-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 |
17ac47c2da1f-8 | ids: Optional[List[str]] = None,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
persist_directory: Optional[str] = None,
client_settings: Optional[chromadb.config.Settings] = None,
client: Optional[chromadb.Client] = None,
**kwargs: Any,
) -> Chroma:
"""Cr... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
17ac47c2da1f-9 | ids: Optional[List[str]] = None,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
persist_directory: Optional[str] = None,
client_settings: Optional[chromadb.config.Settings] = None,
client: Optional[chromadb.Client] = None, # Add this line
**kwargs: Any,
) -> Chro... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
2cfcd48cc9cc-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 |
2cfcd48cc9cc-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 |
2cfcd48cc9cc-2 | 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,
**kwargs: Any,
):
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
2cfcd48cc9cc-3 | 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,
"FLAT",
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
2cfcd48cc9cc-4 | """
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
key = keys[i] if keys else _redis_key(prefix)
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
2cfcd48cc9cc-5 | ) -> List[Document]:
"""
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.
sco... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
2cfcd48cc9cc-6 | .paging(0, k)
.dialect(2)
)
[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 ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
2cfcd48cc9cc-7 | 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)
return [(doc, self.relevance_score_fn(score)) for doc, score in docs_and_scores]
[docs] @cl... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
2cfcd48cc9cc-8 | 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(
redis_url,
index_name,
embedding.embed_query,
content_key=content_key,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
2cfcd48cc9cc-9 | embeddings = OpenAIEmbeddings()
redisearch = RediSearch.from_texts(
texts,
embeddings,
redis_url="redis://username:password@localhost:6379"
)
"""
instance, _ = cls.from_texts_return_keys(
texts,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
2cfcd48cc9cc-10 | 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,
embedding: Embeddings,
in... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
2cfcd48cc9cc-11 | vector_key=vector_key,
**kwargs,
)
[docs] def as_retriever(self, **kwargs: Any) -> RedisVectorStoreRetriever:
return RedisVectorStoreRetriever(vectorstore=self, **kwargs)
class RedisVectorStoreRetriever(VectorStoreRetriever, BaseModel):
vectorstore: Redis
search_type: str = "simil... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
2cfcd48cc9cc-12 | """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 |
84d48ed7cbb8-0 | Source code for langchain.vectorstores.mongodb_atlas
from __future__ import annotations
import logging
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generator,
Iterable,
List,
Optional,
Tuple,
Union,
)
from langchain.docstore.document import Document
from langchain.embeddings.base i... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
84d48ed7cbb8-1 | text_key: MongoDB field that will contain the text for each
document.
embedding_key: MongoDB field that will contain the embedding for
each document.
"""
self._client = client
db_name, collection_name = namespace.split(".")
self._collection = c... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
84d48ed7cbb8-2 | texts_batch = []
metadatas_batch = []
result_ids = []
for i, (text, metadata) in enumerate(zip(texts, _metadatas)):
texts_batch.append(text)
metadatas_batch.append(metadata)
if (i + 1) % batch_size == 0:
result_ids.extend(self._insert_texts(tex... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
84d48ed7cbb8-3 | validate functionality, and to gather feedback from a small closed group of
early access users. It is not recommended for production deployments as we
may introduce breaking changes.
For more: https://www.mongodb.com/docs/atlas/atlas-search/knn-beta
Args:
query: Text to look ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
84d48ed7cbb8-4 | pre_filter: Optional[dict] = None,
post_filter_pipeline: Optional[List[Dict]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return MongoDB documents most similar to query.
Use the knnBeta Operator available in MongoDB Atlas Search
This feature is in early access and availabl... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
84d48ed7cbb8-5 | This is a user-friendly interface that:
1. Embeds documents.
2. Adds the documents to a provided MongoDB Atlas Vector Search index
(Lucene)
This is intended to be a quick way to get started.
Example:
.. code-block:: python
from pymongo ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
001dcc6a4211-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 |
001dcc6a4211-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 |
001dcc6a4211-2 | 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,
embedding=embeddin... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
001dcc6a4211-3 | ) -> 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(
metadata=search.get("metadata", {}), # ty... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
001dcc6a4211-4 | ) -> 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, metadata in zip(texts, metadatas)
]
return docs... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
001dcc6a4211-5 | 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 marginal relevance optimizes for similarity to query AND diversity
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
001dcc6a4211-6 | **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 ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
001dcc6a4211-7 | )
return docs
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 02, 2023. | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
55e56c1ff020-0 | Source code for langchain.vectorstores.opensearch_vector_search
"""Wrapper around OpenSearch vector database."""
from __future__ import annotations
import uuid
from typing import Any, Dict, Iterable, List, Optional, Tuple
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
55e56c1ff020-1 | try:
opensearch = _import_opensearch()
client = opensearch(opensearch_url, **kwargs)
except ValueError as e:
raise ValueError(
f"OpenSearch client string provided is not in proper format. "
f"Got error: {e} "
)
return client
def _validate_embeddings_and_bu... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
55e56c1ff020-2 | request = {
"_op_type": "index",
"_index": index_name,
vector_field: embeddings[i],
text_field: text,
"metadata": metadata,
"_id": _id,
}
requests.append(request)
ids.append(_id)
bulk(client, requests)
client.indices... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
55e56c1ff020-3 | "parameters": {"ef_construction": ef_construction, "m": m},
},
}
}
},
}
def _default_approximate_search_query(
query_vector: List[float],
k: int = 4,
vector_field: str = "vector_field",
) -> Dict:
"""For Approximate k-NN Search, this is the def... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
55e56c1ff020-4 | search_query["query"]["knn"][vector_field]["filter"] = lucene_filter
return search_query
def _default_script_query(
query_vector: List[float],
space_type: str = "l2",
pre_filter: Dict = MATCH_ALL_QUERY,
vector_field: str = "vector_field",
) -> Dict:
"""For Script Scoring Search, this is the defa... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
55e56c1ff020-5 | """For Painless Scripting Search, this is the default query."""
source = __get_painless_scripting_source(space_type, query_vector)
return {
"query": {
"script_score": {
"query": pre_filter,
"script": {
"source": source,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
55e56c1ff020-6 | **kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
bulk_size: Bulk API request count; Defa... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
55e56c1ff020-7 | vector_field,
text_field,
mapping,
)
[docs] def similarity_search(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query.
By default supports Approximate Search.
Also supports Script Scoring and Painle... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
55e56c1ff020-8 | "hammingbit"; default: "l2"
pre_filter: script_score query to pre-filter documents before identifying
nearest neighbors; default: {"match_all": {}}
Optional Args for Painless Scripting Search:
search_type: "painless_scripting"; default: "approximate_search"
space_... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
55e56c1ff020-9 | vector_field = _get_kwargs_value(kwargs, "vector_field", "vector_field")
if search_type == "approximate_search":
boolean_filter = _get_kwargs_value(kwargs, "boolean_filter", {})
subquery_clause = _get_kwargs_value(kwargs, "subquery_clause", "must")
lucene_filter = _get_kwargs... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
55e56c1ff020-10 | search_query = _default_painless_scripting_query(
embedding, space_type, pre_filter, vector_field
)
else:
raise ValueError("Invalid `search_type` provided as an argument")
response = self.client.search(index=self.index_name, body=search_query)
hits = [hit ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
55e56c1ff020-11 | Optional Args:
vector_field: Document field embeddings are stored in. Defaults to
"vector_field".
text_field: Document field the text of the document is stored in. Defaults
to "text".
Optional Keyword Args for Approximate Search:
engine: "nmslib", "fai... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
55e56c1ff020-12 | _validate_embeddings_and_bulk_size(len(embeddings), bulk_size)
dim = len(embeddings[0])
# Get the index name from either from kwargs or ENV Variable
# before falling back to random generation
index_name = get_from_dict_or_env(
kwargs, "index_name", "OPENSEARCH_INDEX_NAME", de... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
55e56c1ff020-13 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 02, 2023. | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
5077cc32b452-0 | Source code for langchain.vectorstores.tair
"""Wrapper around Tair Vector."""
from __future__ import annotations
import json
import logging
import uuid
from typing import Any, Iterable, List, Optional, Type
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
5077cc32b452-1 | data_type: str,
**kwargs: Any,
) -> bool:
index = self.client.tvs_get_index(self.index_name)
if index is not None:
logger.info("Index already exists")
return False
self.client.tvs_create_index(
self.index_name,
dim,
distance... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
5077cc32b452-2 | Args:
query (str): The query text for which to find similar documents.
k (int): The number of documents to return. Default is 4.
Returns:
List[Document]: A list of documents that are most similar to the query text.
"""
# Creates embedding vector from user quer... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
5077cc32b452-3 | if "tair_url" in kwargs:
kwargs.pop("tair_url")
distance_type = tairvector.DistanceMetric.InnerProduct
if "distance_type" in kwargs:
distance_type = kwargs.pop("distance_typ")
index_type = tairvector.IndexType.HNSW
if "index_type" in kwargs:
index_type... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
5077cc32b452-4 | cls,
documents: List[Document],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
index_name: str = "langchain",
content_key: str = "content",
metadata_key: str = "metadata",
**kwargs: Any,
) -> Tair:
texts = [d.page_content for d in docum... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
5077cc32b452-5 | # index not exist
logger.info("Index does not exist")
return False
return True
[docs] @classmethod
def from_existing_index(
cls,
embedding: Embeddings,
index_name: str = "langchain",
content_key: str = "content",
metadata_key: str = "metadat... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
c3da804ad8d4-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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.