id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
7e2ddef7886f-4 | # Clear the chunks_table_data list for the next batch
chunks_table_data.clear()
# Insert any remaining records that didn't make up a full batch
if chunks_table_data:
conn.execute(insert(chunks_table).values(chunks_table_data))
return id... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
7e2ddef7886f-5 | """
embedding = self.embedding_function.embed_query(query)
docs = self.similarity_search_with_score_by_vector(
embedding=embedding, k=k, filter=filter
)
return docs
[docs] def similarity_search_with_score_by_vector(
self,
embedding: List[float],
k: ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
7e2ddef7886f-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
7e2ddef7886f-7 | conn.execute(chunks_table.delete().where(delete_condition))
return True
except Exception as e:
print("Delete operation failed:", str(e))
return False
[docs] @classmethod
def from_texts(
cls: Type[AnalyticDB],
texts: List[str],
embedding:... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
7e2ddef7886f-8 | raise ValueError(
"Postgres connection string is required"
"Either pass it as a parameter"
"or set the PG_CONNECTION_STRING environment variable."
)
return connection_string
[docs] @classmethod
def from_documents(
cls: Type[AnalyticDB],
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
7e2ddef7886f-9 | user: str,
password: str,
) -> str:
"""Return connection string from database parameters."""
return f"postgresql+{driver}://{user}:{password}@{host}:{port}/{database}" | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
c03189824e43-0 | Source code for langchain.vectorstores.pgvecto_rs
from __future__ import annotations
import uuid
from typing import Any, Iterable, List, Literal, Optional, Tuple, Type
import numpy as np
import sqlalchemy
from sqlalchemy import insert, select
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm import Declara... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvecto_rs.html |
c03189824e43-1 | )
text: Mapped[str] = mapped_column(sqlalchemy.String)
meta: Mapped[dict] = mapped_column(postgresql.JSONB)
embedding: Mapped[np.ndarray] = mapped_column(Vector(dimension))
self._engine = sqlalchemy.create_engine(db_url)
self._table = _Table
self._table.__tabl... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvecto_rs.html |
c03189824e43-2 | ) -> PGVecto_rs:
"""Return VectorStore initialized from documents."""
texts = [document.page_content for document in documents]
metadatas = [document.metadata for document in documents]
return cls.from_texts(
texts, embedding, metadatas, db_url, collection_name, **kwargs
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvecto_rs.html |
c03189824e43-3 | results: List[str] = []
for text, embedding, metadata in zip(
texts, embeddings, metadatas or [dict()] * len(list(texts))
):
t = insert(self._table).values(
text=text, meta=metadata, embedding=embedding
)
id = _s... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvecto_rs.html |
c03189824e43-4 | if distance_func == "neg_dot_prod"
else self._table.embedding.negative_cosine_distance
if distance_func == "ned_cos"
else None
)
if real_distance_func is None:
raise ValueError("Invalid distance function")
t = (
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvecto_rs.html |
c03189824e43-5 | )
[docs] def similarity_search(
self,
query: str,
k: int = 4,
distance_func: Literal[
"sqrt_euclid", "neg_dot_prod", "ned_cos"
] = "sqrt_euclid",
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to query."""
query_vector =... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvecto_rs.html |
d29ff38a3a7c-0 | Source code for langchain.vectorstores.elastic_vector_search
from __future__ import annotations
import uuid
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterable,
List,
Mapping,
Optional,
Tuple,
Union,
)
from langchain._api import deprecated
from langchain.docstore.... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-1 | to uses the approx HNSW algorithm which performs better on large datasets.
ElasticsearchStore also supports metadata filtering, customising the
query retriever and much more!
You can read more on ElasticsearchStore:
https://python.langchain.com/docs/integrations/vectorstores/elasticsearch
To connec... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-2 | 5. Follow the prompts to reset the password
The format for Elastic Cloud URLs is
https://username:password@cluster_id.region_id.gcp.cloud.es.io:9243.
Example:
.. code-block:: python
from langchain.vectorstores import ElasticVectorSearch
from langchain.embeddings import OpenAI... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-3 | raise ImportError(
"Could not import elasticsearch python package. "
"Please install it with `pip install elasticsearch`."
)
self.embedding = embedding
self.index_name = index_name
_ssl_verify = ssl_verify or {}
try:
self.client = e... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-4 | from elasticsearch.helpers import bulk
except ImportError:
raise ImportError(
"Could not import elasticsearch python package. "
"Please install it with `pip install elasticsearch`."
)
requests = []
ids = ids or [str(uuid.uuid4()) for _ in t... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-5 | Returns:
List of Documents most similar to the query.
"""
docs_and_scores = self.similarity_search_with_score(query, k, filter=filter)
documents = [d[0] for d in docs_and_scores]
return documents
[docs] def similarity_search_with_score(
self, query: str, k: int = 4... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-6 | ) -> ElasticVectorSearch:
"""Construct ElasticVectorSearch wrapper from raw documents.
This is a user-friendly interface that:
1. Embeds documents.
2. Creates a new index for the embeddings in the Elasticsearch instance.
3. Adds the documents to the newly created Elas... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-7 | [docs] def client_search(
self, client: Any, index_name: str, script_query: Dict, size: int
) -> Any:
version_num = client.info()["version"]["number"][0]
version_num = int(version_num)
if version_num >= 8:
response = client.search(index=index_name, query=script_query, ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-8 | are stored in the Elasticsearch index.
Attributes:
index_name (str): The name of the Elasticsearch index.
embedding (Embeddings): The embedding model to use for transforming text data
into vector embeddings.
es_connection (Elasticsearch, optional): An existing Elasticsearch conne... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-9 | raise ImportError(
"Could not import elasticsearch python package. "
"Please install it with `pip install elasticsearch`."
)
warnings.warn(
"ElasticKnnSearch will be removed in a future release."
"Use ElasticsearchStore instead. See Elasticsear... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-10 | model_id: Optional[str] = None,
k: Optional[int] = 10,
num_candidates: Optional[int] = 10,
) -> Dict:
knn: Dict = {
"field": self.vector_query_field,
"k": k,
"num_candidates": num_candidates,
}
# Case 1: `query_vector` is provided, but not ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-11 | """Pass through to `knn_search including score`"""
return self.knn_search(query=query, k=k, **kwargs)
[docs] def knn_search(
self,
query: Optional[str] = None,
k: Optional[int] = 10,
query_vector: Optional[List[float]] = None,
model_id: Optional[str] = None,
si... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-12 | if not source and (
fields is None or not any(page_content in field for field in fields)
):
raise ValueError("If source=False `page_content` field must be in `fields`")
knn_query_body = self._default_knn_query(
query_vector=query_vector, query=query, model_id=model_id... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-13 | ] = None,
page_content: Optional[str] = "text",
) -> List[Tuple[Document, float]]:
"""
Perform a hybrid k-NN and text search on the Elasticsearch index.
Args:
query (str, optional): The query text to search for.
k (int, optional): The number of nearest neighbo... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-14 | )
# Modify the knn_query_body to add a "boost" parameter
knn_query_body["boost"] = knn_boost
# Generate the body of the standard Elasticsearch query
match_query_body = {
"match": {self.query_field: {"query": query, "boost": query_boost}}
}
# Perform the hybrid... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-15 | **kwargs: Any,
) -> List[str]:
"""
Add a list of texts to the Elasticsearch index.
Args:
texts (Iterable[str]): The texts to add to the index.
metadatas (List[Dict[Any, Any]], optional): A list of metadata dictionaries
to associate with the texts.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-16 | if item["index"]["result"] == "created"
]
if refresh_indices:
self.client.indices.refresh(index=self.index_name)
return ids
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[Dict[Any, Any]... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
d29ff38a3a7c-17 | if query_field is not None:
optional_args["query_field"] = query_field
knnvectorsearch = cls(
index_name=index_name,
embedding=embedding,
es_connection=es_connection,
es_cloud_id=es_cloud_id,
es_user=es_user,
es_password=es_pass... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
19aa06699be3-0 | Source code for langchain.vectorstores.zilliz
from __future__ import annotations
import logging
from typing import Any, Dict, List, Optional
from langchain.schema.embeddings import Embeddings
from langchain.vectorstores.milvus import Milvus
logger = logging.getLogger(__name__)
[docs]class Zilliz(Milvus):
"""`Zilliz... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
19aa06699be3-1 | instance. Example address: "localhost:19530"
uri (str): The uri of Zilliz instance. Example uri:
"https://in03-ba4234asae.api.gcp-us-west1.zillizcloud.com",
host (str): The host of Zilliz instance. Default at "localhost",
PyMilvus will fill in the default host if only port is pro... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
19aa06699be3-2 | embedding = OpenAIEmbeddings()
# Connect to a Zilliz instance
milvus_store = Milvus(
embedding_function = embedding,
collection_name = "LangChainCollection",
connection_args = {
"uri": "https://in03-ba4234asae.api.gcp-us-west1.zillizcloud.com",
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
19aa06699be3-3 | }
self.col.create_index(
self._vector_field,
index_params=self.index_params,
using=self.alias,
)
logger.debug(
"Successfully created an index on collection: %s",
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
19aa06699be3-4 | Defaults to None.
search_params (Optional[dict], optional): Which search params to use.
Defaults to None.
drop_old (Optional[bool], optional): Whether to drop the collection with
that name if it exists. Defaults to False.
Returns:
Zilliz: Zilli... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
6ab8567287fd-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
6ab8567287fd-1 | json.dump(data, fp)
[docs] def load(self) -> Any:
with open(self.persist_path, "r") as fp:
return json.load(fp)
[docs]class BsonSerializer(BaseSerializer):
"""Serializes data in binary json using the `bson` python package."""
[docs] def __init__(self, persist_path: str) -> None:
su... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
6ab8567287fd-2 | os.rename(self.persist_path, backup_path)
try:
self.pq.write_table(table, self.persist_path)
except Exception as exc:
os.rename(backup_path, self.persist_path)
raise exc
else:
os.remove(backup_path)
else:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
6ab8567287fd-3 | self._neighbors_fitted = False
self._embedding_function = embedding
self._persist_path = persist_path
self._serializer: Optional[BaseSerializer] = None
if self._persist_path is not None:
serializer_cls = SERIALIZER_MAP[serializer]
self._serializer = serializer_cls... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
6ab8567287fd-4 | self._texts = data["texts"]
self._metadatas = data["metadatas"]
self._ids = data["ids"]
self._update_neighbors()
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
6ab8567287fd-5 | )
neigh_dists, neigh_idxs = self._neighbors.kneighbors(
[query_embedding], n_neighbors=k
)
return list(zip(neigh_idxs[0], neigh_dists[0]))
[docs] def similarity_search_with_score(
self, query: str, *, k: int = DEFAULT_K, **kwargs: Any
) -> List[Tuple[Document, float]]:... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
6ab8567287fd-6 | self,
embedding: List[float],
k: int = DEFAULT_K,
fetch_k: int = DEFAULT_FETCH_K,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
6ab8567287fd-7 | self,
query: str,
k: int = DEFAULT_K,
fetch_k: int = DEFAULT_FETCH_K,
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 d... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
6ab8567287fd-8 | vs = SKLearnVectorStore(embedding, persist_path=persist_path, **kwargs)
vs.add_texts(texts, metadatas=metadatas, ids=ids)
return vs | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
43878bab6695-0 | Source code for langchain.vectorstores.scann
from __future__ import annotations
import operator
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 import AddableMixin, Docstore
from langchain.docstore... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
43878bab6695-1 | """
[docs] def __init__(
self,
embedding: Embeddings,
index: Any,
docstore: Docstore,
index_to_docstore_id: Dict[int, str],
relevance_score_fn: Optional[Callable[[float], float]] = None,
normalize_L2: bool = False,
distance_strategy: DistanceStrategy = ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
43878bab6695-2 | **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.
ids: Optional list of unique IDs.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
43878bab6695-3 | [docs] def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:
"""Delete by vector ID or other criteria.
Args:
ids: List of ids to delete.
**kwargs: Other keyword arguments that subclasses might use.
Returns:
Optional[bool]: True... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
43878bab6695-4 | vector = normalize(vector)
indices, scores = self.index.search_batched(
vector, k if filter is None else fetch_k
)
docs = []
for j, i in enumerate(indices[0]):
if i == -1:
# This happens when not enough docs are returned.
continue
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
43878bab6695-5 | **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 metadata. Defaults to None.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
43878bab6695-6 | embedding,
k,
filter=filter,
fetch_k=fetch_k,
**kwargs,
)
return [doc for doc, _ in docs_and_scores]
[docs] def similarity_search(
self,
query: str,
k: int = 4,
filter: Optional[Dict[str, Any]] = None,
fetch_k: in... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
43878bab6695-7 | )
scann_config = kwargs.get("scann_config", None)
vector = np.array(embeddings, dtype=np.float32)
if normalize_L2:
vector = normalize(vector)
if scann_config is not None:
index = scann.scann_ops_pybind.create_searcher(vector, scann_config)
else:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
43878bab6695-8 | )
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> ScaNN:
"""Construct ScaNN wrapper from raw documents.
This is a user... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
43878bab6695-9 | This is intended to be a quick way to get started.
Example:
.. code-block:: python
from langchain.vectorstores import ScaNN
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
text_embeddings = embeddings.e... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
43878bab6695-10 | def load_local(
cls,
folder_path: str,
embedding: Embeddings,
index_name: str = "index",
**kwargs: Any,
) -> ScaNN:
"""Load ScaNN index, docstore, and index_to_docstore_id from disk.
Args:
folder_path: folder path to load index, docstore,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
43878bab6695-11 | return self.override_relevance_score_fn
# Default strategy is to rely on distance strategy provided in
# vectorstore constructor
if self.distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:
return self._max_inner_product_relevance_score_fn
elif self.distance_strategy == D... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
43878bab6695-12 | ]
if score_threshold is not None:
docs_and_rel_scores = [
(doc, similarity)
for doc, similarity in docs_and_rel_scores
if similarity >= score_threshold
]
return docs_and_rel_scores | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
448739961ed5-0 | Source code for langchain.vectorstores.opensearch_vector_search
from __future__ import annotations
import uuid
import warnings
from typing import Any, Dict, Iterable, List, Optional, Tuple
import numpy as np
from langchain.schema import Document
from langchain.schema.embeddings import Embeddings
from langchain.schema.v... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-1 | try:
opensearch = _import_opensearch()
client = opensearch(opensearch_url, **kwargs)
except ValueError as e:
raise ImportError(
f"OpenSearch client string provided is not in proper format. "
f"Got error: {e} "
)
return client
def _validate_embeddings_and_b... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-2 | metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
vector_field: str = "vector_field",
text_field: str = "text",
mapping: Optional[Dict] = None,
max_chunk_bytes: Optional[int] = 1 * 1024 * 1024,
is_aoss: bool = False,
) -> List[str]:
"""Bulk Ingest Embeddings into given... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-3 | vector_field: str = "vector_field",
) -> Dict:
"""For Painless Scripting or Script Scoring,the default mapping to create index."""
return {
"mappings": {
"properties": {
vector_field: {"type": "knn_vector", "dimension": dim},
}
}
}
def _default_text_ma... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-4 | return {
"size": k,
"query": {"knn": {vector_field: {"vector": query_vector, "k": k}}},
}
def _approximate_search_query_with_boolean_filter(
query_vector: List[float],
boolean_filter: Dict,
k: int = 4,
vector_field: str = "vector_field",
subquery_clause: str = "must",
) -> Dict:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-5 | if not pre_filter:
pre_filter = MATCH_ALL_QUERY
return {
"size": k,
"query": {
"script_score": {
"query": pre_filter,
"script": {
"source": "knn_score",
"lang": "knn",
"params": {
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-6 | "script": {
"source": source,
"params": {
"field": vector_field,
"query_value": query_vector,
},
},
}
},
}
[docs]class OpenSearchVectorSearch(VectorStore):
"""`Amazon O... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-7 | index_name = kwargs.get("index_name", self.index_name)
text_field = kwargs.get("text_field", "text")
dim = len(embeddings[0])
engine = kwargs.get("engine", "nmslib")
space_type = kwargs.get("space_type", "l2")
ef_search = kwargs.get("ef_search", 512)
ef_construction = kwa... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-8 | Args:
texts: Iterable of strings to add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
ids: Optional list of ids to associate with the texts.
bulk_size: Bulk API request count; Default: 500
Returns:
List of ids fro... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-9 | 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".
"""
texts, embeddings = zip(*text_embeddings)
return self.__add(
list(texts),
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-10 | 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. (deprecated, use `efficient_filter`)
efficient_filter: the Lucene Engine or Faiss Engine decides whether to
perfor... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-11 | 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 as `similarity_search`
"""
text_field = kwar... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-12 | vector_field = kwargs.get("vector_field", "vector_field")
index_name = kwargs.get("index_name", self.index_name)
filter = kwargs.get("filter", {})
if (
self.is_aoss
and search_type != "approximate_search"
and search_type != SCRIPT_SCORING_SEARCH
):
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-13 | efficient_filter = filter
else:
boolean_filter = filter
if boolean_filter != {}:
search_query = _approximate_search_query_with_boolean_filter(
embedding,
boolean_filter,
k=k,
v... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-14 | response = self.client.search(index=index_name, body=search_query)
return [hit for hit in response["hits"]["hits"]]
[docs] def max_marginal_relevance_search(
self,
query: str,
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> list... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-15 | mmr_selected = maximal_marginal_relevance(
np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult
)
return [
Document(
page_content=results[i]["_source"][text_field],
metadata=results[i]["_source"][metadata_field],
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-16 | space_type: "l2", "l1", "cosinesimil", "linf", "innerproduct"; default: "l2"
ef_search: Size of the dynamic list used during k-NN searches. Higher values
lead to more accurate but slower searches; default: 512
ef_construction: Size of the dynamic list used during k-NN graph creation.... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-17 | embeddings = embedder.embed_documents(["foo", "bar"])
opensearch_vector_search = OpenSearchVectorSearch.from_embeddings(
embeddings,
texts,
embedder,
opensearch_url="http://localhost:9200"
)
OpenSearc... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-18 | )
# List of arguments that needs to be removed from kwargs
# before passing kwargs to get opensearch client
keys_list = [
"opensearch_url",
"index_name",
"is_appx_search",
"vector_field",
"text_field",
"engine",
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
448739961ed5-19 | ef_search = kwargs.get("ef_search", 512)
ef_construction = kwargs.get("ef_construction", 512)
m = kwargs.get("m", 16)
_validate_aoss_with_engines(is_aoss, engine)
mapping = _default_text_mapping(
dim, engine, space_type, ef_search, ef_construction, m, vect... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
a6ad2e704c72-0 | Source code for langchain.vectorstores.matching_engine
from __future__ import annotations
import json
import logging
import time
import uuid
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type
from langchain.schema.document import Document
from langchain.schema.embeddings import Embeddings
from... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
a6ad2e704c72-1 | While the embeddings are stored in the Matching Engine, the embedded
documents will be stored in GCS.
An existing Index and corresponding Endpoint are preconditions for
using this module.
See usage in
docs/modules/indexes/vectorstores/examples/matchingengine.ipynb.
Note t... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
a6ad2e704c72-2 | from google.oauth2 import service_account # noqa: F401
except ImportError:
raise ImportError(
"You must run `pip install --upgrade "
"google-cloud-aiplatform google-cloud-storage`"
"to use the MatchingEngine Vectorstore."
)
[docs] def a... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
a6ad2e704c72-3 | json_["metadata"] = metadatas[idx]
jsons.append(json_)
self._upload_to_gcs(text, f"documents/{id}")
logger.debug(f"Uploaded {len(ids)} documents to GCS.")
# Creating json lines from the embedded documents.
result_str = "\n".join([json.dumps(x) for x in jsons])
fil... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
a6ad2e704c72-4 | Args:
query: String query look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter: Optional. A list of Namespaces for filtering
the matching results.
For example:
[Namespace("color", ["red"], []), Namespace... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
a6ad2e704c72-5 | will match datapoints that satisfy "red color" but not include
datapoints with "squared shape". Please refer to
https://cloud.google.com/vertex-ai/docs/matching-engine/filtering#json
for more detail.
Returns:
List[Tuple[Document, float]]: List of docum... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
a6ad2e704c72-6 | filter: Optional[List[Namespace]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to query.
Args:
query: The string that will be used to search for similar documents.
k: The amount of neighbors that will be retrieved.
filter: Option... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
a6ad2e704c72-7 | datapoints with "squared shape". Please refer to
https://cloud.google.com/vertex-ai/docs/matching-engine/filtering#json
for more detail.
Returns:
A list of k matching documents.
"""
docs_and_scores = self.similarity_search_by_vector_with_score(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
a6ad2e704c72-8 | """Use from components instead."""
raise NotImplementedError(
"This method is not implemented. Instead, you should initialize the class"
" with `MatchingEngine.from_components(...)` and then call "
"`add_texts`"
)
[docs] @classmethod
def from_components(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
a6ad2e704c72-9 | endpoint_id, project_id, region, credentials
)
gcs_client = cls._get_gcs_client(credentials, project_id)
cls._init_aiplatform(project_id, region, gcs_bucket_name, credentials)
return cls(
project_id=project_id,
index=index,
endpoint=endpoint,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
a6ad2e704c72-10 | credentials = service_account.Credentials.from_service_account_file(
json_credentials_path
)
return credentials
@classmethod
def _create_index_by_id(
cls, index_id: str, project_id: str, region: str, credentials: "Credentials"
) -> MatchingEngineIndex:
"""... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
a6ad2e704c72-11 | location=region,
credentials=credentials,
)
@classmethod
def _get_gcs_client(
cls, credentials: "Credentials", project_id: str
) -> "storage.Client":
"""Lazily creates a GCS client.
Returns:
A configured GCS client.
"""
from google.clou... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
a6ad2e704c72-12 | """
from langchain.embeddings import TensorflowHubEmbeddings
return TensorflowHubEmbeddings() | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
5b7db5d31643-0 | Source code for langchain.vectorstores.clarifai
from __future__ import annotations
import logging
import os
import traceback
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Iterable, List, Optional, Tuple
import requests
from langchain.docstore.document import Document
from langchain.schema.em... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
5b7db5d31643-1 | ValueError: If user ID, app ID or personal access token is not provided.
"""
try:
from clarifai.auth.helper import DEFAULT_BASE, ClarifaiAuthHelper
from clarifai.client import create_stub
except ImportError:
raise ImportError(
"Could not import... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
5b7db5d31643-2 | ) -> List[str]:
"""Post text to Clarifai and return the ID of the input.
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, se... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
5b7db5d31643-3 | )
input_ids = []
for input in post_inputs_response.inputs:
input_ids.append(input.id)
return input_ids
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
5b7db5d31643-4 | result_ids = self._post_texts_as_inputs(batch_texts, batch_metadatas)
input_ids.extend(result_ids)
logger.debug(f"Input {result_ids} posted successfully.")
except Exception as error:
logger.warning(f"Post inputs failed: {error}")
traceback.prin... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
5b7db5d31643-5 | user_app_id=self._userDataObject,
searches=[
resources_pb2.Search(
query=resources_pb2.Query(
ranks=[
resources_pb2.Rank(
annotation=resources_pb2.Annotation(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
5b7db5d31643-6 | off input: {hit.input.id}, text: {requested_text[:125]}"
)
return (Document(page_content=requested_text, metadata=metadata), hit.score)
# Iterate over hits and retrieve metadata and text
futures = [executor.submit(hit_to_document, hit) for hit in hits]
docs_and_scores = [... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
5b7db5d31643-7 | texts (List[str]): List of texts to add.
pat (Optional[str]): Personal access token. Defaults to None.
number_of_docs (Optional[int]): Number of documents to return
during vector search. Defaults to None.
api_base (Optional[str]): API base. Defaults to None.
m... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
5b7db5d31643-8 | during vector search. Defaults to None.
api_base (Optional[str]): API base. Defaults to None.
Returns:
Clarifai: Clarifai vectorstore.
"""
texts = [doc.page_content for doc in documents]
metadatas = [doc.metadata for doc in documents]
return cls.from_texts... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
9cdde1982c83-0 | Source code for langchain.vectorstores.supabase
from __future__ import annotations
import uuid
from itertools import repeat
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
)
import numpy as np
from langchain.docstore.document import Docume... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.