id stringlengths 14 16 | text stringlengths 4 1.28k | source stringlengths 54 121 |
|---|---|---|
825682b7a014-6 | """Return docs most similar to embedding vector.
No support for `filter` query (on metadata) along with vector search.
Args:
embedding (str): Embedding to look up documents similar to.
k (int): Number of Documents to return. Defaults to 4.
Returns:
List of (Do... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
825682b7a014-7 | ),
0.5 + 0.5 * hit["distance"],
hit["document_id"],
)
for hit in hits
]
[docs] def similarity_search_with_score_id(
self,
query: str,
k: int = 4,
**kwargs: Any,
) -> List[Tuple[Document, float, str]]:
embeddin... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
825682b7a014-8 | No support for `filter` query (on metadata) along with vector search.
Args:
embedding (str): Embedding to look up documents similar to.
k (int): Number of Documents to return. Defaults to 4.
Returns:
List of (Document, score), the most similar to the query vector.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
825682b7a014-9 | embedding_vector,
k,
**kwargs,
)
[docs] def similarity_search_by_vector(
self,
embedding: List[float],
k: int = 4,
**kwargs: Any,
) -> List[Document]:
return [
doc
for doc, _ in self.similarity_search_with_score_by_ve... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
825682b7a014-10 | # it is apparently used by VectorSearch parent class
# in an exposed method (`similarity_search_with_relevance_scores`).
# So we implement it (hmm).
def _similarity_search_with_relevance_scores(
self,
query: str,
k: int = 4,
**kwargs: Any,
) -> List[Tuple[Document, float]... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
825682b7a014-11 | ) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documen... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
825682b7a014-12 | mmrChosenIndices = maximal_marginal_relevance(
np.array(embedding, dtype=np.float32),
[pfHit["embedding_vector"] for pfHit in prefetchHits],
k=k,
lambda_mult=lambda_mult,
)
mmrHits = [
pfHit
for pfIndex, pfHit in enumerate(prefetchH... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
825682b7a014-13 | **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://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
825682b7a014-14 | lambda_mult=lambda_mult,
)
[docs] @classmethod
def from_texts(
cls: Type[CVST],
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> CVST:
"""Create a Cassandra vectorstore from raw texts.
No suppo... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
825682b7a014-15 | return cassandraStore
[docs] @classmethod
def from_documents(
cls: Type[CVST],
documents: List[Document],
embedding: Embeddings,
**kwargs: Any,
) -> CVST:
"""Create a Cassandra vectorstore from a document list.
No support for specifying text IDs
Returns... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
825682b7a014-16 | keyspace=keyspace,
table_name=table_name,
) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
025cdcc65654-0 | Source code for langchain.vectorstores.lancedb
"""Wrapper around LanceDB vector database"""
from __future__ import annotations
import uuid
from typing import Any, Iterable, List, Optional
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.base i... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
025cdcc65654-1 | self,
connection: Any,
embedding: Embeddings,
vector_key: Optional[str] = "vector",
id_key: Optional[str] = "id",
text_key: Optional[str] = "text",
):
"""Initialize with Lance DB connection"""
try:
import lancedb
except ImportError:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
025cdcc65654-2 | self._id_key = id_key
self._text_key = text_key
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Turn texts into embedding and add it to the database... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
025cdcc65654-3 | for idx, text in enumerate(texts):
embedding = embeddings[idx]
metadata = metadatas[idx] if metadatas else {}
docs.append(
{
self._vector_key: embedding,
self._id_key: ids[idx],
self._text_key: text,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
025cdcc65654-4 | docs = self._connection.search(embedding).limit(k).to_df()
return [
Document(
page_content=row[self._text_key],
metadata=row[docs.columns != self._text_key],
)
for _, row in docs.iterrows()
]
[docs] @classmethod
def from_texts(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
025cdcc65654-5 | text_key,
)
instance.add_texts(texts, metadatas=metadatas, **kwargs)
return instance | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
350b4bdc00d9-0 | Source code for langchain.vectorstores.sklearn
""" Wrapper around scikit-learn NearestNeighbors implementation.
The vector store can be persisted in json, bson or parquet format.
"""
import json
import math
import os
from abc import ABC, abstractmethod
from typing import Any, Dict, Iterable, List, Literal, Optional, Tu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
350b4bdc00d9-1 | def __init__(self, persist_path: str) -> None:
self.persist_path = persist_path
@classmethod
@abstractmethod
def extension(cls) -> str:
"""The file extension suggested by this serializer (without dot)."""
@abstractmethod
def save(self, data: Any) -> None:
"""Saves the data to... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
350b4bdc00d9-2 | def load(self) -> Any:
with open(self.persist_path, "r") as fp:
return json.load(fp)
class BsonSerializer(BaseSerializer):
"""Serializes data in binary json using the bson python package."""
def __init__(self, persist_path: str) -> None:
super().__init__(persist_path)
self.bs... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
350b4bdc00d9-3 | class ParquetSerializer(BaseSerializer):
"""Serializes data in Apache Parquet format using the pyarrow package."""
def __init__(self, persist_path: str) -> None:
super().__init__(persist_path)
self.pd = guard_import("pandas")
self.pa = guard_import("pyarrow")
self.pq = guard_impo... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
350b4bdc00d9-4 | except Exception as exc:
os.rename(backup_path, self.persist_path)
raise exc
else:
os.remove(backup_path)
else:
self.pq.write_table(table, self.persist_path)
def load(self) -> Any:
table = self.pq.read_table(self.persist_path)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
350b4bdc00d9-5 | NearestNeighbors implementation."""
def __init__(
self,
embedding: Embeddings,
*,
persist_path: Optional[str] = None,
serializer: Literal["json", "bson", "parquet"] = "json",
metric: str = "cosine",
**kwargs: Any,
) -> None:
np = guard_import("nump... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
350b4bdc00d9-6 | serializer_cls = SERIALIZER_MAP[serializer]
self._serializer = serializer_cls(persist_path=self._persist_path)
# data properties
self._embeddings: List[List[float]] = []
self._texts: List[str] = []
self._metadatas: List[dict] = []
self._ids: List[str] = []
# c... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
350b4bdc00d9-7 | "ids": self._ids,
"texts": self._texts,
"metadatas": self._metadatas,
"embeddings": self._embeddings,
}
self._serializer.save(data)
def _load(self) -> None:
if self._serializer is None:
raise SKLearnVectorStoreException(
"You mu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
350b4bdc00d9-8 | ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
_texts = list(texts)
_ids = ids or [str(uuid4()) for _ in _texts]
self._texts.extend(_texts)
self._embeddings.extend(self._embedding_function.embed_documents(_texts))
self._metadatas.extend(metadatas or (... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
350b4bdc00d9-9 | self._neighbors_fitted = True
def _similarity_index_search_with_score(
self, query_embedding: List[float], *, k: int = DEFAULT_K, **kwargs: Any
) -> List[Tuple[int, float]]:
"""Search k embeddings similar to the query embedding. Returns a list of
(index, distance) tuples."""
if n... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
350b4bdc00d9-10 | ) -> List[Tuple[Document, float]]:
query_embedding = self._embedding_function.embed_query(query)
indices_dists = self._similarity_index_search_with_score(
query_embedding, k=k, **kwargs
)
return [
(
Document(
page_content=self._... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
350b4bdc00d9-11 | self, query: str, k: int = DEFAULT_K, **kwargs: Any
) -> List[Tuple[Document, float]]:
docs_dists = self.similarity_search_with_score(query, k=k, **kwargs)
docs, dists = zip(*docs_dists)
scores = [1 / math.exp(dist) for dist in dists]
return list(zip(list(docs), scores))
[docs] de... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
350b4bdc00d9-12 | among selected documents.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
lambda_mult: Number between 0 and 1 that determines the degree
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
350b4bdc00d9-13 | self._np.array(embedding, dtype=self._np.float32),
result_embeddings,
k=k,
lambda_mult=lambda_mult,
)
mmr_indices = [indices[i] for i in mmr_selected]
return [
Document(
page_content=self._texts[idx],
metadata={"id":... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
350b4bdc00d9-14 | among selected documents.
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
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
350b4bdc00d9-15 | )
return docs
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
persist_path: Optional[str] = None,
**kwargs: Any,
) -> "SKLearnVectorStore"... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
b46e99187f0b-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, Sequence, Tuple, Type
from sqlalchemy import REAL, Column, String, Table, create_engine, ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-1 | [docs]class AnalyticDB(VectorStore):
"""VectorStore implementation using AnalyticDB.
AnalyticDB is a distributed full PostgresSQL syntax cloud-native database.
- `connection_string` is a postgres connection string.
- `embedding_function` any embedding function implementing
`langchain.embeddings.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-2 | def __init__(
self,
connection_string: str,
embedding_function: Embeddings,
embedding_dimension: int = _LANGCHAIN_DEFAULT_EMBEDDING_DIM,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
pre_delete_collection: bool = False,
logger: Optional[logging.Logger... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-3 | self.create_collection()
[docs] def create_table_if_not_exists(self) -> None:
# Define the dynamic table
Table(
self.collection_name,
Base.metadata,
Column("id", TEXT, primary_key=True, default=uuid.uuid4),
Column("embedding", ARRAY(REAL)),
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-4 | """
)
result = conn.execute(index_query).scalar()
# Create the index if it doesn't exist
if not result:
index_statement = text(
f"""
CREATE INDEX {index_name}
ON {s... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-5 | with self.engine.connect() as conn:
with conn.begin():
conn.execute(drop_statement)
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
batch_size: int = 500,
**kwargs: A... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-6 | embeddings = self.embedding_function.embed_documents(list(texts))
if not metadatas:
metadatas = [{} for _ in texts]
# Define the table schema
chunks_table = Table(
self.collection_name,
Base.metadata,
Column("id", TEXT, primary_key=True),
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-7 | "document": document,
"metadata": metadata,
}
)
# Execute the batch insert when the batch size is reached
if len(chunks_table_data) == batch_size:
conn.execute(insert(chunks_table).val... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-8 | Args:
query (str): Query text to search for.
k (int): Number of results to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
Returns:
List of Documents most similar to the query.
"""
embedding = self.em... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-9 | 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 the query and score for each
"""
embedding = self.embedding_function.embed_query(query)
docs = self... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-10 | Args:
query: input text
k: Number of Documents to return. Defaults to 4.
**kwargs: kwargs to be passed to similarity search. Should include:
score_threshold: Optional, a floating point value between 0 to 1 to
filter the resulting set of retrieved d... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-11 | conditions = [
f"metadata->>{key!r} = {value!r}" for key, value in filter.items()
]
filter_condition = f"WHERE {' AND '.join(conditions)}"
# Define the base query
sql_query = f"""
SELECT *, l2_distance(embedding, :embedding) as distance
FRO... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-12 | metadata=result.metadata,
),
result.distance if self.embedding_function is not None else None,
)
for result in results
]
return documents_with_scores
[docs] def similarity_search_by_vector(
self,
embedding: List[float],
k... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-13 | embedding=embedding, k=k, filter=filter
)
return [doc for doc, _ in docs_and_scores]
[docs] @classmethod
def from_texts(
cls: Type[AnalyticDB],
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
embedding_dimension: int = _LANG... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-14 | """
connection_string = cls.get_connection_string(kwargs)
store = cls(
connection_string=connection_string,
collection_name=collection_name,
embedding_function=embedding,
embedding_dimension=embedding_dimension,
pre_delete_collection=pre_delete... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-15 | )
return connection_string
[docs] @classmethod
def from_documents(
cls: Type[AnalyticDB],
documents: List[Document],
embedding: Embeddings,
embedding_dimension: int = _LANGCHAIN_DEFAULT_EMBEDDING_DIM,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
b46e99187f0b-16 | kwargs["connection_string"] = connection_string
return cls.from_texts(
texts=texts,
pre_delete_collection=pre_delete_collection,
embedding=embedding,
embedding_dimension=embedding_dimension,
metadatas=metadatas,
ids=ids,
collect... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
34df3f3a0fa1-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
import numpy as np
from langchain.embeddings.base import Embeddings
from langchain.schema import D... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-1 | """Import OpenSearch if available, otherwise raise error."""
try:
from opensearchpy import OpenSearch
except ImportError:
raise ValueError(IMPORT_OPENSEARCH_PY_ERROR)
return OpenSearch
def _import_bulk() -> Any:
"""Import bulk if available, otherwise raise error."""
try:
from... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-2 | """Get OpenSearch client from the opensearch_url, otherwise raise error."""
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. "
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-3 | )
def _bulk_ingest_embeddings(
client: Any,
index_name: str,
embeddings: List[List[float]],
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
vector_field: str = "vector_field",
text_field: str = "text",
mapping: Optional[Dict] = None,
) -... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-4 | for i, text in enumerate(texts):
metadata = metadatas[i] if metadatas else {}
_id = ids[i] if ids else str(uuid.uuid4())
request = {
"_op_type": "index",
"_index": index_name,
vector_field: embeddings[i],
text_field: text,
"metadata": m... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-5 | "properties": {
vector_field: {"type": "knn_vector", "dimension": dim},
}
}
}
def _default_text_mapping(
dim: int,
engine: str = "nmslib",
space_type: str = "l2",
ef_search: int = 512,
ef_construction: int = 512,
m: int = 16,
vector_field: str = "vecto... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-6 | "dimension": dim,
"method": {
"name": "hnsw",
"space_type": space_type,
"engine": engine,
"parameters": {"ef_construction": ef_construction, "m": m},
},
}
}... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-7 | boolean_filter: Dict,
k: int = 4,
vector_field: str = "vector_field",
subquery_clause: str = "must",
) -> Dict:
"""For Approximate k-NN Search, with Boolean Filter."""
return {
"size": k,
"query": {
"bool": {
"filter": boolean_filter,
subqu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-8 | search_query = _default_approximate_search_query(
query_vector, k=k, vector_field=vector_field
)
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: Optional[Dic... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-9 | "field": vector_field,
"query_value": query_vector,
"space_type": space_type,
},
},
}
}
}
def __get_painless_scripting_source(
space_type: str, query_vector: List[float], vector_field: str = "vector_field"
) ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-10 | query_vector: List[float],
space_type: str = "l2Squared",
pre_filter: Optional[Dict] = None,
vector_field: str = "vector_field",
) -> Dict:
"""For Painless Scripting Search, this is the default query."""
if not pre_filter:
pre_filter = MATCH_ALL_QUERY
source = __get_painless_scripting_so... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-11 | """Get the value of the key if present. Else get the default_value."""
if key in kwargs:
return kwargs.get(key)
return default_value
[docs]class OpenSearchVectorSearch(VectorStore):
"""Wrapper around OpenSearch as a vector database.
Example:
.. code-block:: python
from langch... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-12 | self.index_name = index_name
self.client = _get_opensearch_client(opensearch_url, **kwargs)
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
bulk_size: int = 500,
**kwargs: Any,
) -> ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-13 | 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".
"""
embeddings = self.embedding_function.embed_documents(list(texts))
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-14 | vector_field = _get_kwargs_value(kwargs, "vector_field", "vector_field")
mapping = _default_text_mapping(
dim, engine, space_type, ef_search, ef_construction, m, vector_field
)
return _bulk_ingest_embeddings(
self.client,
self.index_name,
embedding... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-15 | 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.
Optional Args:
vector_field: Document field embeddings are stored in. Defaults to
"vector_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-16 | subquery_clause: Query clause on the knn vector field; default: "must"
lucene_filter: the Lucene algorithm decides whether to perform an exact
k-NN search with pre-filtering or an approximate search with modified
post-filtering.
Optional Args for Script Scoring Search:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-17 | space_type: "l2Squared", "l1Norm", "cosineSimilarity"; default: "l2Squared"
pre_filter: script_score query to pre-filter documents before identifying
nearest neighbors; default: {"match_all": {}}
"""
docs_with_scores = self.similarity_search_with_score(query, k, **kwargs)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-18 | k: Number of Documents to return. Defaults to 4.
Returns:
List of Documents along with its scores most similar to the query.
Optional Args:
same as `similarity_search`
"""
text_field = _get_kwargs_value(kwargs, "text_field", "text")
metadata_field = _get_k... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-19 | ]
return documents_with_scores
def _raw_similarity_search_with_score(
self, query: str, k: int = 4, **kwargs: Any
) -> List[dict]:
"""Return raw opensearch documents (dict) including vectors,
scores most similar to query.
By default, supports Approximate Search.
A... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-20 | 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://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-21 | elif lucene_filter != {}:
search_query = _approximate_search_query_with_lucene_filter(
embedding, lucene_filter, k=k, vector_field=vector_field
)
else:
search_query = _default_approximate_search_query(
embedding, k=k, ve... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-22 | 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)
return [hit ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-23 | k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
Defaults to 20.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-24 | results = self._raw_similarity_search_with_score(query, fetch_k, **kwargs)
embeddings = [result["_source"][vector_field] for result in results]
# Rerank top k results using MMR, (mmr_selected is a list of indices)
mmr_selected = maximal_marginal_relevance(
np.array(embedding), embedd... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-25 | bulk_size: int = 500,
**kwargs: Any,
) -> OpenSearchVectorSearch:
"""Construct OpenSearchVectorSearch wrapper from raw documents.
Example:
.. code-block:: python
from langchain import OpenSearchVectorSearch
from langchain.embeddings import OpenAIEm... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-26 | "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", "faiss", "lucene"; default: "nmslib"
space_type: "l2", "l1", "cosinesimil", "linf", "innerproduct"... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-27 | on memory consumption. Between 2 and 100; default: 16
Keyword Args for Script Scoring or Painless Scripting:
is_appx_search: False
"""
opensearch_url = get_from_dict_or_env(
kwargs, "opensearch_url", "OPENSEARCH_URL"
)
# List of arguments that needs to be ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-28 | 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", default=uuid.uuid4().hex
)
is_appx_search = _get_kwargs_v... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
34df3f3a0fa1-29 | ef_construction = _get_kwargs_value(kwargs, "ef_construction", 512)
m = _get_kwargs_value(kwargs, "m", 16)
mapping = _default_text_mapping(
dim, engine, space_type, ef_search, ef_construction, m, vector_field
)
else:
mapping = _default_scripting_te... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
90d40b6cee25-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://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-1 | to load FAISS with no AVX2 optimization.
Args:
no_avx2: Load FAISS strictly with no AVX2 optimization
so that the vectorstore is portable and compatible with other devices.
"""
if no_avx2 is None and "FAISS_NO_AVX2" in os.environ:
no_avx2 = bool(os.getenv("FAISS_NO_AVX2"))
tr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-2 | )
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 embed... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-3 | """Wrapper around FAISS vector database.
To use, you should have the ``faiss`` python package installed.
Example:
.. code-block:: python
from langchain import FAISS
faiss = FAISS(embedding_function, index, docstore, index_to_docstore_id)
"""
def __init__(
self,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-4 | self.relevance_score_fn = relevance_score_fn
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]:... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-5 | if ids is None:
ids = [str(uuid.uuid4()) for _ in texts]
# Add to the index, the index_to_id mapping, and the docstore.
starting_len = len(self.index_to_docstore_id)
faiss = dependable_faiss_import()
vector = np.array(embeddings, dtype=np.float32)
if self._normalize_L... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-6 | self.index_to_docstore_id.update(index_to_id)
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... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-7 | raise ValueError(
"If trying to add texts, the underlying docstore should support "
f"adding items, which {self.docstore} does not"
)
# Embed and create the documents.
embeddings = [self.embedding_function(text) for text in texts]
return self.__add(tex... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-8 | add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
ids: Optional list of unique IDs.
Returns:
List of ids from adding the texts into the vectorstore.
"""
if not isinstance(self.docstore, AddableMixin):
raise Va... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-9 | k: int = 4,
filter: Optional[Dict[str, Any]] = None,
fetch_k: int = 20,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query.
Args:
embedding: Embedding vector to look up documents similar to.
k: Number of Documents to... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-10 | Returns:
List of documents most similar to the query text and L2 distance
in float for each. Lower score represents more similarity.
"""
faiss = dependable_faiss_import()
vector = np.array([embedding], dtype=np.float32)
if self._normalize_L2:
faiss.nor... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-11 | if filter is not None:
filter = {
key: [value] if not isinstance(value, list) else value
for key, value in filter.items()
}
if all(doc.metadata.get(key) in value for key, value in filter.items()):
docs.append((do... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-12 | fetch_k: int = 20,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by meta... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-13 | **kwargs,
)
return docs
[docs] def similarity_search_by_vector(
self,
embedding: List[float],
k: int = 4,
filter: Optional[Dict[str, Any]] = None,
fetch_k: int = 20,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to embeddin... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-14 | """
docs_and_scores = self.similarity_search_with_score_by_vector(
embedding,
k,
filter=filter,
fetch_k=fetch_k,
**kwargs,
)
return [doc for doc, _ in docs_and_scores]
[docs] def similarity_search(
self,
query: str,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-15 | fetch_k: (Optional[int]) Number of Documents to fetch before filtering.
Defaults to 20.
Returns:
List of Documents most similar to the query.
"""
docs_and_scores = self.similarity_search_with_score(
query, k, filter=filter, fetch_k=fetch_k, **kwargs
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-16 | Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch before filtering to
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-17 | filtered_indices = []
for i in indices[0]:
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, ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-18 | embeddings,
k=k,
lambda_mult=lambda_mult,
)
selected_indices = [indices[0][i] for i in mmr_selected]
docs = []
for i in selected_indices:
if i == -1:
# This happens when not enough docs are returned.
continue
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-19 | filter: Optional[Dict[str, Any]] = None,
**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 loo... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.