id stringlengths 14 15 | text stringlengths 35 2.51k | source stringlengths 61 154 |
|---|---|---|
27c778c1385a-7 | or set the PG_CONNECTION_STRING environment variable.
"""
connection_string = cls.get_connection_string(kwargs)
store = cls(
connection_string=connection_string,
collection_name=collection_name,
embedding_function=embedding,
embedding_dimension=emb... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
27c778c1385a-8 | metadatas = [d.metadata for d in documents]
connection_string = cls.get_connection_string(kwargs)
kwargs["connection_string"] = connection_string
return cls.from_texts(
texts=texts,
pre_delete_collection=pre_delete_collection,
embedding=embedding,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
ba91aea4fa2d-0 | Source code for langchain.vectorstores.singlestoredb
"""Wrapper around SingleStore DB."""
from __future__ import annotations
import enum
import json
from typing import Any, ClassVar, Collection, Iterable, List, Optional, Tuple, Type
from sqlalchemy.pool import QueuePool
from langchain.callbacks.manager import (
Asy... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
ba91aea4fa2d-1 | )
return s2.connect(**self.connection_kwargs)
def __init__(
self,
embedding: Embeddings,
*,
distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,
table_name: str = "embeddings",
content_field: str = "content",
metadata_field: str = "metadata... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
ba91aea4fa2d-2 | the pool. Defaults to 5.
max_overflow (int, optional): Determines the maximum number of connections
allowed beyond the pool_size. Defaults to 10.
timeout (float, optional): Specifies the maximum wait time in seconds for
establishing a connection. Defaults to 30.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
ba91aea4fa2d-3 | ssl_verify_identity (bool, optional): Verifies the server's identity.
conv (dict[int, Callable], optional): A dictionary of data conversion
functions.
credential_type (str, optional): Specifies the type of authentication to
use: auth.PASSWORD, auth.JWT, or auth.BR... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
ba91aea4fa2d-4 | from langchain.vectorstores import SingleStoreDB
os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db'
vectorstore = SingleStoreDB(OpenAIEmbeddings())
"""
self.embedding = embedding
self.distance_strategy = distance_strategy
self.table_name = t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
ba91aea4fa2d-5 | self.table_name,
self.content_field,
self.vector_field,
self.metadata_field,
),
)
finally:
cur.close()
finally:
conn.close()
[docs] def add_texts(
self,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
ba91aea4fa2d-6 | cur.close()
finally:
conn.close()
return []
[docs] def similarity_search(
self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any
) -> List[Document]:
"""Returns the most similar indexed documents to the query text.
Uses cosine similarity.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
ba91aea4fa2d-7 | k: Number of Documents to return. Defaults to 4.
filter: A dictionary of metadata fields and values to filter by.
Defaults to None.
Returns:
List of Documents most similar to the query and score for each
"""
# Creates embedding vector from user query
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
ba91aea4fa2d-8 | self.vector_field,
self.table_name,
where_clause,
ORDERING_DIRECTIVE[self.distance_strategy],
),
("[{}]".format(",".join(map(str, embedding))),)
+ tuple(where_clause_values)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
ba91aea4fa2d-9 | s2 = SingleStoreDB.from_texts(
texts,
OpenAIEmbeddings(),
host="username:password@localhost:3306/database"
)
"""
instance = cls(
embedding,
distance_strategy=distance_strategy,
table_name=tabl... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
ba91aea4fa2d-10 | run_manager: Optional[AsyncCallbackManagerForRetrieverRun] = None,
**kwargs: Any,
) -> List[Document]:
raise NotImplementedError(
"SingleStoreDBVectorStoreRetriever does not support async"
) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
70dbd217fd8f-0 | Source code for langchain.vectorstores.rocksetdb
"""Wrapper around Rockset vector database."""
from __future__ import annotations
import logging
from enum import Enum
from typing import Any, Iterable, List, Optional, Tuple
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
70dbd217fd8f-1 | client: Any,
embeddings: Embeddings,
collection_name: str,
text_key: str,
embedding_key: str,
):
"""Initialize with Rockset client.
Args:
client: Rockset client object
collection: Rockset collection to insert docs / query
embeddings... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
70dbd217fd8f-2 | """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 ids to associate with the texts.
batch_si... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
70dbd217fd8f-3 | ) -> Rockset:
"""Create Rockset wrapper with existing texts.
This is intended as a quicker way to get started.
"""
# Sanitize imputs
assert client is not None, "Rockset Client cannot be None"
assert collection_name, "Collection name cannot be empty"
assert text_ke... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
70dbd217fd8f-4 | k (int, optional): Top K neighbors to retrieve. Defaults to 4.
where_str (Optional[str], optional): Metadata filters supplied as a
SQL `where` condition string. Defaults to None.
eg. "price<=70.0 AND brand='Nintendo'"
NOTE: Please do not let end-user to fill this ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
70dbd217fd8f-5 | """Accepts a query_embedding (vector), and returns documents with
similar embeddings."""
docs_and_scores = self.similarity_search_by_vector_with_relevance_scores(
embedding, k, distance_func, where_str, **kwargs
)
return [doc for doc, _ in docs_and_scores]
[docs] def simil... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
70dbd217fd8f-6 | self._text_key, type(v)
)
page_content = v
elif k == "dist":
assert isinstance(
v, float
), "Computed distance between vectors must of type `float`. \
But found {}".format(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
70dbd217fd8f-7 | collection=self._collection_name, data=batch
)
return [doc_status._id for doc_status in add_doc_res.data]
[docs] def delete_texts(self, ids: List[str]) -> None:
"""Delete a list of docs from the Rockset collection"""
try:
from rockset.models import DeleteDocumentsRequestDa... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
3f6d820fa588-0 | Source code for langchain.vectorstores.annoy
"""Wrapper around Annoy vector database."""
from __future__ import annotations
import os
import pickle
import uuid
from configparser import ConfigParser
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
import numpy as np
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
3f6d820fa588-1 | ):
"""Initialize with necessary components."""
self.embedding_function = embedding_function
self.index = index
self.metric = metric
self.docstore = docstore
self.index_to_docstore_id = index_to_docstore_id
[docs] def add_texts(
self,
texts: Iterable[str... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
3f6d820fa588-2 | Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
search_k: inspect up to search_k nodes which defaults
to n_trees * n if not provided
Returns:
List of Documents most similar to the query and score ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
3f6d820fa588-3 | k: Number of Documents to return. Defaults to 4.
search_k: inspect up to search_k nodes which defaults
to n_trees * n if not provided
Returns:
List of Documents most similar to the query and score for each
"""
embedding = self.embedding_function(query)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
3f6d820fa588-4 | Returns:
List of Documents most similar to the embedding.
"""
docs_and_scores = self.similarity_search_with_score_by_index(
docstore_index, k, search_k
)
return [doc for doc, _ in docs_and_scores]
[docs] def similarity_search(
self, query: str, k: int =... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
3f6d820fa588-5 | of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
Returns:
List of Documents selected by maximal marginal relevance.
"""
idxs = self.index.get_nns_by_vector(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
3f6d820fa588-6 | 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 among the results with 0 corresponding
to maximum diversity... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
3f6d820fa588-7 | documents = []
for i, text in enumerate(texts):
metadata = metadatas[i] if metadatas else {}
documents.append(Document(page_content=text, metadata=metadata))
index_to_id = {i: str(uuid.uuid4()) for i in range(len(documents))}
docstore = InMemoryDocstore(
{inde... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
3f6d820fa588-8 | from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
index = Annoy.from_texts(texts, embeddings)
"""
embeddings = embedding.embed_documents(texts)
return cls.__from(
texts, embeddings, embedding, metadatas, metric, trees, n... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
3f6d820fa588-9 | text_embedding_pairs = list(zip(texts, text_embeddings))
db = Annoy.from_embeddings(text_embedding_pairs, embeddings)
"""
texts = [t[0] for t in text_embeddings]
embeddings = [t[1] for t in text_embeddings]
return cls.__from(
texts, embeddings, embedding, meta... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
3f6d820fa588-10 | Args:
folder_path: folder path to load index, docstore,
and index_to_docstore_id from.
embeddings: Embeddings to use when generating queries.
"""
path = Path(folder_path)
# load index separately since it is not picklable
annoy = dependable_annoy_im... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
4b2d6127f85e-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 |
4b2d6127f85e-1 | metadata_payload_key: str = METADATA_KEY,
vector_name: Optional[str] = VECTOR_NAME,
embedding_function: Optional[Callable] = None, # deprecated
):
"""Initialize with necessary components."""
try:
import qdrant_client
except ImportError:
raise ValueErr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-2 | )
if not isinstance(embeddings, Embeddings):
warnings.warn(
"`embeddings` should be an instance of `Embeddings`."
"Using `embeddings` as `embedding_function` which is deprecated"
)
self._embeddings_function = embeddings
self.embeddi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-3 | batch_ids = list(islice(ids_iterator, batch_size))
# Generate the embeddings for all the texts in a batch
batch_embeddings = self._embed_texts(batch_texts)
if self.vector_name is not None:
batch_embeddings = { # type: ignore[assignment]
self.vecto... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-4 | 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. for cosine similarity only higher scores will be returned.
consistency:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-5 | Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter: Filter by metadata. Defaults to None.
search_params: Additional search params
offset:
Offset of the first result to return.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-6 | self,
embedding: List[float],
k: int = 4,
filter: Optional[MetadataFilter] = None,
search_params: Optional[common_types.SearchParams] = None,
offset: int = 0,
score_threshold: Optional[float] = None,
consistency: Optional[common_types.ReadConsistency] = None,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-7 | Returns:
List of Documents most similar to the query.
"""
results = self.similarity_search_with_score_by_vector(
embedding,
k,
filter=filter,
search_params=search_params,
offset=offset,
score_threshold=score_threshold,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-8 | consistency:
Read consistency of the search. Defines how many replicas should be
queried before returning the result.
Values:
- int - number of replicas to query, values should present in all
queried replicas
- 'majo... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-9 | )
return [
(
self._document_from_scored_point(
result, self.content_payload_key, self.metadata_payload_key
),
result.score,
)
for result in results
]
def _similarity_search_with_relevance_scores(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-10 | Defaults to 20.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
Returns:
List of Do... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-11 | grpc_port: int = 6334,
prefer_grpc: bool = False,
https: Optional[bool] = None,
api_key: Optional[str] = None,
prefix: Optional[str] = None,
timeout: Optional[float] = None,
host: Optional[str] = None,
path: Optional[str] = None,
collection_name: Optional[... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-12 | length as a list of texts.
ids:
Optional list of ids to associate with the texts. Ids have to be
uuid-like strings.
location:
If `:memory:` - use in-memory Qdrant instance.
If `str` - use it as a `url` parameter.
If ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-13 | it will be created randomly. Default: None
distance_func:
Distance function. One of: "Cosine" / "Euclid" / "Dot".
Default: "Cosine"
content_payload_key:
A payload key used to store the content of the document.
Default: "page_content... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-14 | optimizers_config: Params for optimizer
wal_config: Params for Write-Ahead-Log
quantization_config:
Params for quantization, if None - quantization will be disabled
init_from:
Use data stored in another collection to initialize this collection
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-15 | prefer_grpc=prefer_grpc,
https=https,
api_key=api_key,
prefix=prefix,
timeout=timeout,
host=host,
path=path,
**kwargs,
)
vectors_config = rest.VectorParams(
size=vector_size,
distance=rest.Distanc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-16 | # Generate the embeddings for all the texts in a batch
batch_embeddings = embedding.embed_documents(batch_texts)
if vector_name is not None:
batch_embeddings = { # type: ignore[assignment]
vector_name: batch_embeddings
}
points = r... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-17 | cls,
scored_point: Any,
content_payload_key: str,
metadata_payload_key: str,
) -> Document:
return Document(
page_content=scored_point.payload.get(content_payload_key),
metadata=scored_point.payload.get(metadata_payload_key) or {},
)
def _build_con... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4b2d6127f85e-18 | Args:
query: Query text.
Returns:
List of floats representing the query embedding.
"""
if self.embeddings is not None:
embedding = self.embeddings.embed_query(query)
else:
if self._embeddings_function is not None:
embedding ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
b7bcd45dae34-0 | Source code for langchain.vectorstores.pinecone
"""Wrapper around Pinecone vector database."""
from __future__ import annotations
import logging
import uuid
from typing import Any, Callable, Iterable, List, Optional, Tuple
import numpy as np
from langchain.docstore.document import Document
from langchain.embeddings.bas... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
b7bcd45dae34-1 | f"client should be an instance of pinecone.index.Index, "
f"got {type(index)}"
)
self._index = index
self._embedding_function = embedding_function
self._text_key = text_key
self._namespace = namespace
[docs] def add_texts(
self,
texts: Itera... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
b7bcd45dae34-2 | self,
query: str,
k: int = 4,
filter: Optional[dict] = None,
namespace: Optional[str] = None,
) -> List[Tuple[Document, float]]:
"""Return pinecone documents most similar to query, along with scores.
Args:
query: Text to look up documents similar to.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
b7bcd45dae34-3 | """Return pinecone documents most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter: Dictionary of argument(s) to filter on metadata
namespace: Namespace to search in. Default will search i... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
b7bcd45dae34-4 | lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
Returns:
List of Documents selected by maximal ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
b7bcd45dae34-5 | 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 among the results with 0 corresponding
to maximum diversity... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
b7bcd45dae34-6 | embeddings = OpenAIEmbeddings()
pinecone = Pinecone.from_texts(
texts,
embeddings,
index_name="langchain-demo"
)
"""
try:
import pinecone
except ImportError:
raise ValueError(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
b7bcd45dae34-7 | else:
metadata = [{} for _ in range(i, i_end)]
for j, line in enumerate(lines_batch):
metadata[j][text_key] = line
to_upsert = zip(ids_batch, embeds, metadata)
# upsert to Pinecone
index.upsert(vectors=list(to_upsert), namespace=namespace)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
12c235326a77-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 |
12c235326a77-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."""
def __init__(self, persist_path: str) -> None:
super().__... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
12c235326a77-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:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
12c235326a77-3 | 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(persist_path=self._persist_path)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
12c235326a77-4 | self._update_neighbors()
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
_texts = list(texts)
_ids = ids or [str(uuid4()) for _ in _texts]
self... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
12c235326a77-5 | )
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]]:
query_embedding = self._embedding_function.embed_query(query)
indices_dists = self._similarity_index... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
12c235326a77-6 | lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
embedding: Embedding to look up d... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
12c235326a77-7 | 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 diversity
among selected do... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
12c235326a77-8 | vs.add_texts(texts, metadatas=metadatas, ids=ids)
return vs | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
88b96213160a-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 |
88b96213160a-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 |
88b96213160a-2 | mapping = mapping
try:
client.indices.get(index=index_name)
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 =... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
88b96213160a-3 | return {
"settings": {"index": {"knn": True, "knn.algo_param.ef_search": ef_search}},
"mappings": {
"properties": {
vector_field: {
"type": "knn_vector",
"dimension": dim,
"method": {
"name": ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
88b96213160a-4 | def _approximate_search_query_with_lucene_filter(
query_vector: List[float],
lucene_filter: Dict,
k: int = 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_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
88b96213160a-5 | + str(query_vector)
+ ", doc['"
+ vector_field
+ "']))"
)
if space_type == "cosineSimilarity":
return source_value
else:
return "1/" + source_value
def _default_painless_scripting_query(
query_vector: List[float],
space_type: str = "l2Squared",
pre_filter:... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
88b96213160a-6 | embedding_function
)
"""
def __init__(
self,
opensearch_url: str,
index_name: str,
embedding_function: Embeddings,
**kwargs: Any,
):
"""Initialize with necessary components."""
self.embedding_function = embedding_function
self.index... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
88b96213160a-7 | engine = _get_kwargs_value(kwargs, "engine", "nmslib")
space_type = _get_kwargs_value(kwargs, "space_type", "l2")
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)
vec... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
88b96213160a-8 | 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".
metadata_field: Document field that metadata is stored in. Defaults to
"metadata".
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
88b96213160a-9 | docs_with_scores = self.similarity_search_with_score(query, k, **kwargs)
return [doc[0] for doc in docs_with_scores]
[docs] def similarity_search_with_score(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Tuple[Document, float]]:
"""Return docs and it's scores most similar to query... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
88b96213160a-10 | scores most similar to query.
By default, supports Approximate Search.
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 dict with i... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
88b96213160a-11 | )
elif search_type == SCRIPT_SCORING_SEARCH:
space_type = _get_kwargs_value(kwargs, "space_type", "l2")
pre_filter = _get_kwargs_value(kwargs, "pre_filter", MATCH_ALL_QUERY)
search_query = _default_script_query(
embedding, space_type, pre_filter, vector_field
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
88b96213160a-12 | of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
Returns:
List of Documents selected by maximal marginal relevance.
"""
vector_field = _get_kwargs_value(kwargs, "vecto... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
88b96213160a-13 | .. code-block:: python
from langchain import OpenSearchVectorSearch
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
opensearch_vector_search = OpenSearchVectorSearch.from_texts(
texts,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
88b96213160a-14 | kwargs, "opensearch_url", "OPENSEARCH_URL"
)
# 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",
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
88b96213160a-15 | 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 |
4ed0c850ddc6-0 | Source code for langchain.vectorstores.redis
"""Wrapper around Redis vector database."""
from __future__ import annotations
import json
import logging
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
4ed0c850ddc6-1 | ) >= int(module["ver"]):
return
# otherwise raise error
error_message = (
"Redis cannot be used as a vector database without RediSearch >=2.4"
"Please head to https://redis.io/docs/stack/search/quick_start/"
"to know more about installing the RediSearch module within Redis St... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
4ed0c850ddc6-2 | )
"""
def __init__(
self,
redis_url: str,
index_name: str,
embedding_function: Callable,
content_key: str = "content",
metadata_key: str = "metadata",
vector_key: str = "content_vector",
relevance_score_fn: Optional[
Callable[[float], f... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
4ed0c850ddc6-3 | "Please install it with `pip install redis`."
)
# Check if index exists
if not _check_index_exists(self.client, self.index_name):
# Define schema
schema = (
TextField(name=self.content_key),
TextField(name=self.metadata_key),
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
4ed0c850ddc6-4 | Returns:
List[str]: List of ids added to the vectorstore
"""
ids = []
prefix = _redis_prefix(self.index_name)
# Get keys or ids from kwargs
# Other vectorstores use ids
keys_or_ids = kwargs.get("keys", kwargs.get("ids"))
# Write data to redis
p... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
4ed0c850ddc6-5 | """
docs_and_scores = self.similarity_search_with_score(query, k=k)
return [doc for doc, _ in docs_and_scores]
[docs] def similarity_search_limit_score(
self, query: str, k: int = 4, score_threshold: float = 0.2, **kwargs: Any
) -> List[Document]:
"""
Returns the most simi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
4ed0c850ddc6-6 | # Prepare the Query
hybrid_fields = "*"
base_query = (
f"{hybrid_fields}=>[KNN {k} @{self.vector_key} $vector AS vector_score]"
)
return_fields = [self.metadata_key, self.content_key, "vector_score"]
return (
Query(base_query)
.return_fields(*r... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
4ed0c850ddc6-7 | self,
query: str,
k: int = 4,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs and relevance scores, normalized on a scale from 0 to 1.
0 is dissimilar, 1 is most similar.
"""
if self.relevance_score_fn is None:
raise ValueError(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
4ed0c850ddc6-8 | from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
redisearch, keys = RediSearch.from_texts_return_keys(
texts,
embeddings,
redis_url="redis://username:password@localhost:6379"
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
4ed0c850ddc6-9 | This is a user-friendly interface that:
1. Embeds documents.
2. Creates a new index for the embeddings in Redis.
3. Adds the documents to the newly created Redis index.
This is intended to be a quick way to get started.
Example:
.. code-block:: python
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
4ed0c850ddc6-10 | "Please install it with `pip install redis`."
)
try:
# We need to first remove redis_url from kwargs,
# otherwise passing it to Redis will result in an error.
if "redis_url" in kwargs:
kwargs.pop("redis_url")
client = redis.from_url(url... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
4ed0c850ddc6-11 | except ValueError as e:
raise ValueError(f"Your redis connected error: {e}")
# Check if index exists
try:
client.ft(index_name).dropindex(delete_documents)
logger.info("Drop index")
return True
except: # noqa: E722
# Index not exist
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
4ed0c850ddc6-12 | redis_url,
index_name,
embedding.embed_query,
content_key=content_key,
metadata_key=metadata_key,
vector_key=vector_key,
**kwargs,
)
[docs] def as_retriever(self, **kwargs: Any) -> RedisVectorStoreRetriever:
return RedisVectorSto... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
4ed0c850ddc6-13 | query, k=self.k, score_threshold=self.score_threshold
)
else:
raise ValueError(f"search_type of {self.search_type} not allowed.")
return docs
async def _aget_relevant_documents(
self,
query: str,
*,
run_manager: Optional[AsyncCallbackManagerFor... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
675f4da9e1d4-0 | Source code for langchain.vectorstores.alibabacloud_opensearch
import json
import logging
import numbers
from hashlib import sha1
from typing import Any, Dict, Iterable, List, Optional, Tuple
from langchain.embeddings.base import Embeddings
from langchain.schema import Document
from langchain.vectorstores.base import V... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
675f4da9e1d4-1 | instance_id: str
username: str
password: str
datasource_name: str
embedding_index_name: str
field_name_mapping: Dict[str, str] = {
"id": "id",
"document": "document",
"embedding": "embedding",
"metadata_field_x": "metadata_field_x,operator",
}
def __init__(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.