id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 54 121 |
|---|---|---|
5d704991e9bc-7 | # TODO: Check if this can be done in bulk
for id in ids:
self.client.delete(index=self.index_name, id=id)
class ElasticKnnSearch(ElasticVectorSearch):
"""
A class for performing k-Nearest Neighbors (k-NN) search on an Elasticsearch index.
The class is designed for a text search scenario ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
5d704991e9bc-8 | )
self.embedding = embedding
self.index_name = index_name
self.query_field = query_field
self.vector_query_field = vector_query_field
# If a pre-existing Elasticsearch connection is provided, use it.
if es_connection is not None:
self.client = es_connection
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
5d704991e9bc-9 | "k": k,
"num_candidates": num_candidates,
}
# Case 1: `query_vector` is provided, but not `model_id` -> use query_vector
if query_vector and not model_id:
knn["query_vector"] = query_vector
# Case 2: `query` and `model_id` are provided, -> use query_vector_builder... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
5d704991e9bc-10 | search on the Elasticsearch index and returns the results.
Args:
query: The query or queries to be used for the search. Required if
`query_vector` is not provided.
k: The number of nearest neighbors to return. Defaults to 10.
query_vector: The query vector to ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
5d704991e9bc-11 | model_id: Optional[str] = None,
size: Optional[int] = 10,
source: Optional[bool] = True,
knn_boost: Optional[float] = 0.9,
query_boost: Optional[float] = 0.1,
fields: Optional[
Union[List[Mapping[str, Any]], Tuple[Mapping[str, Any], ...], None]
] = None,
)... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
5d704991e9bc-12 | included. Defaults to None.
vector_query_field: Field name to use in knn search if not default 'vector'
query_field: Field name to use in search if not default 'text'
Returns:
The search results.
Raises:
ValueError: If neither `query_vector` nor `model_id`... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
f0755b0d2bd6-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,
TypeVar,
Union,
)
from langchain.docstore.document import Document
from langchain.embe... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
f0755b0d2bd6-1 | """
Args:
collection: MongoDB collection to add the texts to.
embedding: Text embedding model to use.
text_key: MongoDB field that will contain the text for each
document.
embedding_key: MongoDB field that will contain the embedding for
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
f0755b0d2bd6-2 | """
batch_size = kwargs.get("batch_size", DEFAULT_INSERT_BATCH_SIZE)
_metadatas: Union[List, Generator] = metadatas or ({} for _ in texts)
texts_batch = []
metadatas_batch = []
result_ids = []
for i, (text, metadata) in enumerate(zip(texts, _metadatas)):
texts... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
f0755b0d2bd6-3 | """Return MongoDB documents most similar to query, along with scores.
Use the knnBeta Operator available in MongoDB Atlas Search
This feature is in early access and available only for evaluation purposes, to
validate functionality, and to gather feedback from a small closed group of
earl... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
f0755b0d2bd6-4 | docs.append((Document(page_content=text, metadata=res), score))
return docs
[docs] def similarity_search(
self,
query: str,
k: int = 4,
pre_filter: Optional[dict] = None,
post_filter_pipeline: Optional[List[Dict]] = None,
**kwargs: Any,
) -> List[Document]:... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
f0755b0d2bd6-5 | collection: Optional[Collection[MongoDBDocumentType]] = None,
**kwargs: Any,
) -> MongoDBAtlasVectorSearch:
"""Construct MongoDBAtlasVectorSearch wrapper from raw documents.
This is a user-friendly interface that:
1. Embeds documents.
2. Adds the documents to a provid... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
93d38bec2ae3-0 | Source code for langchain.vectorstores.clarifai
from __future__ import annotations
import logging
import os
import traceback
from typing import Any, Iterable, List, Optional, Tuple
import requests
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.vectorstor... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
93d38bec2ae3-1 | """
try:
from clarifai.auth.helper import DEFAULT_BASE, ClarifaiAuthHelper
from clarifai.client import create_stub
except ImportError:
raise ValueError(
"Could not import clarifai python package. "
"Please install it with `pip install c... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
93d38bec2ae3-2 | Args:
text (str): Text to post.
metadata (dict): Metadata to post.
Returns:
str: ID of the input.
"""
try:
from clarifai_grpc.grpc.api import resources_pb2, service_pb2
from clarifai_grpc.grpc.api.status import status_code_pb2
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
93d38bec2ae3-3 | to a Clarifai application.
Application use base workflow that create and store embedding for each text.
Make sure you are using a base workflow that is compatible with text
(such as Language Understanding).
Args:
texts (Iterable[str]): Texts to add to the vectorstore.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
93d38bec2ae3-4 | 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[Document]: List of documents most simmilar to the query text.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
93d38bec2ae3-5 | "Post searches failed, status: "
+ post_annotations_searches_response.status.description
)
# Retrieve hits
hits = post_annotations_searches_response.hits
docs_and_scores = []
# Iterate over hits and retrieve metadata and text
for hit in hits:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
93d38bec2ae3-6 | user_id: Optional[str] = None,
app_id: Optional[str] = None,
pat: Optional[str] = None,
number_of_docs: Optional[int] = None,
api_base: Optional[str] = None,
**kwargs: Any,
) -> Clarifai:
"""Create a Clarifai vectorstore from a list of texts.
Args:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
93d38bec2ae3-7 | api_base: Optional[str] = None,
**kwargs: Any,
) -> Clarifai:
"""Create a Clarifai vectorstore from a list of documents.
Args:
user_id (str): User ID.
app_id (str): App ID.
documents (List[Document]): List of documents to add.
pat (Optional[str... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
5a87e9b3d92c-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://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
5a87e9b3d92c-1 | embeddings = OpenAIEmbeddings()
vectorstore = Chroma("langchain_store", embeddings)
"""
_LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain"
def __init__(
self,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
embedding_function: Optional[Embeddings] = None,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
5a87e9b3d92c-2 | @xor_args(("query_texts", "query_embeddings"))
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[Documen... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
5a87e9b3d92c-3 | ids = [str(uuid.uuid1()) for _ in texts]
embeddings = None
if self._embedding_function is not None:
embeddings = self._embedding_function.embed_documents(list(texts))
self._collection.upsert(
metadatas=metadatas, embeddings=embeddings, documents=texts, ids=ids
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
5a87e9b3d92c-4 | Returns:
List of Documents most similar to the query vector.
"""
results = self.__query_collection(
query_embeddings=embedding, n_results=k, where=filter
)
return _results_to_docs(results)
[docs] def similarity_search_with_score(
self,
query: st... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
5a87e9b3d92c-5 | return self.similarity_search_with_score(query, k, **kwargs)
[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: An... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
5a87e9b3d92c-6 | lambda_mult=lambda_mult,
)
candidates = _results_to_docs(results)
selected_results = [r for i, r in enumerate(candidates) if i in mmr_selected]
return selected_results
[docs] def max_marginal_relevance_search(
self,
query: str,
k: int = DEFAULT_K,
fetch... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
5a87e9b3d92c-7 | )
return docs
[docs] def delete_collection(self) -> None:
"""Delete the collection."""
self._client.delete_collection(self._collection.name)
[docs] def get(
self,
ids: Optional[OneOrMany[ID]] = None,
where: Optional[Where] = None,
limit: Optional[int] = None... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
5a87e9b3d92c-8 | kwargs["include"] = include
return self._collection.get(**kwargs)
[docs] def persist(self) -> None:
"""Persist the collection.
This can be used to explicitly persist the data to disk.
It will also be called automatically when the object is destroyed.
"""
if self._persi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
5a87e9b3d92c-9 | client: Optional[chromadb.Client] = None,
**kwargs: Any,
) -> 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 (Li... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
5a87e9b3d92c-10 | client: Optional[chromadb.Client] = None, # Add this line
**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:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
bab0078bf4c2-0 | Source code for langchain.vectorstores.qdrant
"""Wrapper around Qdrant vector database."""
from __future__ import annotations
import uuid
import warnings
from itertools import islice
from operator import itemgetter
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Opti... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-1 | metadata_payload_key: str = METADATA_KEY,
embedding_function: Optional[Callable] = None, # deprecated
):
"""Initialize with necessary components."""
try:
import qdrant_client
except ImportError:
raise ValueError(
"Could not import qdrant-clien... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-2 | "Using `embeddings` as `embedding_function` which is deprecated"
)
self._embeddings_function = embeddings
self.embeddings = None
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[Sequence[str]] =... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-3 | ids=batch_ids,
vectors=self._embed_texts(batch_texts),
payloads=self._build_payloads(
batch_texts,
batch_metadatas,
self.content_payload_key,
self.metadata_payload_key,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-4 | - int - number of replicas to query, values should present in all
queried replicas
- 'majority' - query all replicas, but return values present in the
majority of replicas
- 'quorum' - query the majority of replicas, return values pr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-5 | score_threshold:
Define a minimal score threshold for the result.
If defined, less similar results will not be returned.
Score of the returned result might be higher or smaller than the
threshold depending on the Distance function used.
E.g... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-6 | **kwargs: Any,
) -> List[Document]:
"""Return docs most similar to embedding vector.
Args:
embedding: Embedding vector to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter: Filter by metadata. Defaults to None.
searc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-7 | **kwargs,
)
return list(map(itemgetter(0), results))
[docs] def similarity_search_with_score_by_vector(
self,
embedding: List[float],
k: int = 4,
filter: Optional[MetadataFilter] = None,
search_params: Optional[common_types.SearchParams] = None,
offset:... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-8 | all of them
- 'all' - query all replicas, and return values present in all replicas
Returns:
List of documents most similar to the query text and cosine
distance in float for each.
Lower score represents more similarity.
"""
if filter is not No... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-9 | 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/qdrant.html |
bab0078bf4c2-10 | )
embeddings = [result.vector for result in results]
mmr_selected = maximal_marginal_relevance(
np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult
)
return [
self._document_from_scored_point(
results[i], self.content_payload_key, self.me... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-11 | hnsw_config: Optional[common_types.HnswConfigDiff] = None,
optimizers_config: Optional[common_types.OptimizersConfigDiff] = None,
wal_config: Optional[common_types.WalConfigDiff] = None,
quantization_config: Optional[common_types.QuantizationConfig] = None,
init_from: Optional[common_typ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-12 | prefix:
If not None - add prefix to the REST URL path.
Example: service/v1 will result in
http://localhost:6333/service/v1/{qdrant-endpoint} for REST API.
Default: None
timeout:
Timeout for REST and gRPC API requests.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-13 | Defines how many replicas should apply the operation for us to consider
it successful. Increasing this number will make the collection more
resilient to inconsistencies, but will also make it fail if not enough
replicas are available.
Does not have any per... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-14 | import qdrant_client
except ImportError:
raise ValueError(
"Could not import qdrant-client python package. "
"Please install it with `pip install qdrant-client`."
)
from qdrant_client.http import models as rest
# Just do a single quick embe... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-15 | metadatas_iterator = iter(metadatas or [])
ids_iterator = iter(ids or [uuid.uuid4().hex for _ in iter(texts)])
while batch_texts := list(islice(texts_iterator, batch_size)):
# Take the corresponding metadata and id for each text in a batch
batch_metadatas = list(islice(metadatas_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-16 | payloads.append(
{
content_payload_key: text,
metadata_payload_key: metadata,
}
)
return payloads
@classmethod
def _document_from_scored_point(
cls,
scored_point: Any,
content_payload_key: str,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bab0078bf4c2-17 | for condition in self._build_condition(key, value)
]
)
def _embed_query(self, query: str) -> List[float]:
"""Embed query text.
Used to provide backward compatibility with `embedding_function` argument.
Args:
query: Query text.
Returns:
List... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
e7b997dd36d6-0 | Source code for langchain.vectorstores.azuresearch
"""Wrapper around Azure Cognitive Search."""
from __future__ import annotations
import base64
import json
import logging
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
)
im... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
e7b997dd36d6-1 | from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import ResourceNotFoundError
from azure.identity import DefaultAzureCredential
from azure.search.documents import SearchClient
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.ind... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
e7b997dd36d6-2 | algorithm_configurations=[
VectorSearchAlgorithmConfiguration(
name="default",
kind="hnsw",
hnsw_parameters={
"m": 4,
"efConstruction": 400,
"efSearch": 500,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
e7b997dd36d6-3 | azure_search_endpoint,
azure_search_key,
index_name,
embedding_function,
semantic_configuration_name,
)
self.search_type = search_type
self.semantic_configuration_name = semantic_configuration_name
self.semantic_query_language = semantic_qu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
e7b997dd36d6-4 | raise Exception(response)
# Reset data
data = []
# Considering case where data is an exact multiple of batch-size entries
if len(data) == 0:
return ids
# Upload data to index
response = self.client.upload_documents(documents=data)
# Che... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
e7b997dd36d6-5 | query, k=k, filters=kwargs.get("filters", None)
)
return [doc for doc, _ in docs_and_scores]
[docs] def vector_search_with_score(
self, query: str, k: int = 4, filters: Optional[str] = None
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query.
Args:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
e7b997dd36d6-6 | Returns:
List[Document]: A list of documents that are most similar to the query text.
"""
docs_and_scores = self.hybrid_search_with_score(
query, k=k, filters=kwargs.get("filters", None)
)
return [doc for doc, _ in docs_and_scores]
[docs] def hybrid_search_with... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
e7b997dd36d6-7 | ) -> List[Document]:
"""
Returns the most similar indexed documents to the query text.
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 d... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
e7b997dd36d6-8 | query_answer="extractive",
top=k,
)
# Get Semantic Answers
semantic_answers = results.get_answers()
semantic_answers_dict = {}
for semantic_answer in semantic_answers:
semantic_answers_dict[semantic_answer.key] = {
"text": semantic_answer.t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
e7b997dd36d6-9 | azure_search_key,
index_name,
embedding.embed_query,
)
azure_search.add_texts(texts, metadatas, **kwargs)
return azure_search
class AzureSearchVectorStoreRetriever(BaseRetriever, BaseModel):
vectorstore: AzureSearch
search_type: str = "hybrid"
k: int = 4
c... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
f4a04940c247-0 | Source code for langchain.vectorstores.cassandra
"""Wrapper around Cassandra vector-store capabilities, based on cassIO."""
from __future__ import annotations
import hashlib
import typing
from typing import Any, Iterable, List, Optional, Tuple, Type, TypeVar
import numpy as np
if typing.TYPE_CHECKING:
from cassandr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
f4a04940c247-1 | )
return self._embedding_dimension
def __init__(
self,
embedding: Embeddings,
session: Session,
keyspace: str,
table_name: str,
ttl_seconds: int | None = CASSANDRA_VECTORSTORE_DEFAULT_TTL_SECONDS,
) -> None:
try:
from cassio.vector impo... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
f4a04940c247-2 | ids: Optional[List[str]] = None,
**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.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
f4a04940c247-3 | """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 |
f4a04940c247-4 | """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 |
f4a04940c247-5 | embedding_vector,
k,
)
# Even though this is a `_`-method,
# 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,
quer... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
f4a04940c247-6 | metric="cos",
metric_threshold=None,
)
# let the mmr utility pick the *indices* in the above array
mmrChosenIndices = maximal_marginal_relevance(
np.array(embedding, dtype=np.float32),
[pfHit["embedding_vector"] for pfHit in prefetchHits],
k=k,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
f4a04940c247-7 | return self.max_marginal_relevance_search_by_vector(
embedding_vector,
k,
fetch_k,
lambda_mult=lambda_mult,
)
[docs] @classmethod
def from_texts(
cls: Type[CVST],
texts: List[str],
embedding: Embeddings,
metadatas: Optional[L... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
f4a04940c247-8 | return cls.from_texts(
texts=texts,
metadatas=metadatas,
embedding=embedding,
session=session,
keyspace=keyspace,
table_name=table_name,
) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
5cf61cd6372d-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 |
5cf61cd6372d-1 | 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 |
5cf61cd6372d-2 | """
embedding = self._embedding.embed_query(query)
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 doc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
fce4160e68f6-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 |
fce4160e68f6-1 | 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.bson = guard_import("bson")
@... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
fce4160e68f6-2 | 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)
df = table.to_pandas()
return {col: series.tolist() for col, series in df.items()}
S... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
fce4160e68f6-3 | 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] = []
# cache properties
self._embeddings_np: Any = np.as... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
fce4160e68f6-4 | **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 ([{}] * len(_texts)))
self._ids.ex... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
fce4160e68f6-5 | 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._texts[idx],
metadata={"... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
fce4160e68f6-6 | 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
of diversity... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
fce4160e68f6-7 | 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 |
075545cdf350-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 |
075545cdf350-1 | - Useful for testing.
"""
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,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
075545cdf350-2 | """
)
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 |
075545cdf350-3 | 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),
Column("embedding", ARRAY(REAL)),
Column("document", String... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
075545cdf350-4 | 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.embedding_function.embed_query(text=query)
return self.similari... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
075545cdf350-5 | **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 docs
Returns:
List of Tuples of (doc, similarity_score)
"""
return self.si... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
075545cdf350-6 | )
for result in results
]
return documents_with_scores
[docs] def similarity_search_by_vector(
self,
embedding: List[float],
k: int = 4,
filter: Optional[dict] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to em... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
075545cdf350-7 | connection_string=connection_string,
collection_name=collection_name,
embedding_function=embedding,
embedding_dimension=embedding_dimension,
pre_delete_collection=pre_delete_collection,
)
store.add_texts(texts=texts, metadatas=metadatas, ids=ids, **kwargs)... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
075545cdf350-8 | return cls.from_texts(
texts=texts,
pre_delete_collection=pre_delete_collection,
embedding=embedding,
embedding_dimension=embedding_dimension,
metadatas=metadatas,
ids=ids,
collection_name=collection_name,
**kwargs,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
73bbcb23f714-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 |
73bbcb23f714-1 | """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 |
73bbcb23f714-2 | except not_found_error:
client.indices.create(index=index_name, body=mapping)
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,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
73bbcb23f714-3 | "mappings": {
"properties": {
vector_field: {
"type": "knn_vector",
"dimension": dim,
"method": {
"name": "hnsw",
"space_type": space_type,
"engine": engine,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
73bbcb23f714-4 | vector_field: str = "vector_field",
) -> Dict:
"""For Approximate k-NN Search, with Lucene Filter."""
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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
73bbcb23f714-5 | return source_value
else:
return "1/" + source_value
def _default_painless_scripting_query(
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 qu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
73bbcb23f714-6 | **kwargs: Any,
):
"""Initialize with necessary components."""
self.embedding_function = embedding_function
self.index_name = index_name
self.client = _get_opensearch_client(opensearch_url, **kwargs)
[docs] def add_texts(
self,
texts: Iterable[str],
metadata... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
73bbcb23f714-7 | ef_search = _get_kwargs_value(kwargs, "ef_search", 512)
ef_construction = _get_kwargs_value(kwargs, "ef_construction", 512)
m = _get_kwargs_value(kwargs, "m", 16)
vector_field = _get_kwargs_value(kwargs, "vector_field", "vector_field")
mapping = _default_text_mapping(
dim, en... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
73bbcb23f714-8 | search_type: "approximate_search"; default: "approximate_search"
boolean_filter: A Boolean filter consists of a Boolean query that
contains a k-NN query and a filter.
subquery_clause: Query clause on the knn vector field; default: "must"
lucene_filter: the Lucene algorith... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
73bbcb23f714-9 | Also supports Script Scoring and Painless Scripting.
Args:
query: Text to look up documents similar to.
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... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
73bbcb23f714-10 | """
embedding = self.embedding_function.embed_query(query)
search_type = _get_kwargs_value(kwargs, "search_type", "approximate_search")
vector_field = _get_kwargs_value(kwargs, "vector_field", "vector_field")
if search_type == "approximate_search":
boolean_filter = _get_kwarg... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
73bbcb23f714-11 | space_type = _get_kwargs_value(kwargs, "space_type", "l2Squared")
pre_filter = _get_kwargs_value(kwargs, "pre_filter", MATCH_ALL_QUERY)
search_query = _default_painless_scripting_query(
embedding, space_type, pre_filter, vector_field
)
else:
raise ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.