id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
9e5865f764a7-4 | """
_query = self._embedding.embed_query(query)
docs = self.similarity_search_by_vector_with_scores(
embedding=_query,
k=k,
filter=filter,
kwargs=kwargs,
)
return docs
[docs] def similarity_search_by_vector_with_scores(
self,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html |
9e5865f764a7-5 | **kwargs: Any,
) -> List[Document]:
"""Return meilisearch documents most similar to embedding vector.
Args:
embedding (List[float]): Embedding to look up similar documents.
k (int): Number of documents to return. Defaults to 4.
filter (Optional[Dict[str, str]]): F... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html |
9e5865f764a7-6 | Example:
.. code-block:: python
from langchain.vectorstores import Meilisearch
from langchain.embeddings import OpenAIEmbeddings
import meilisearch
# The environment should be the one specified next to the API key
# in your Meil... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html |
f655d0022c59-0 | Source code for langchain.vectorstores.singlestoredb
from __future__ import annotations
import json
import re
from typing import (
Any,
Callable,
Iterable,
List,
Optional,
Tuple,
Type,
)
from sqlalchemy.pool import QueuePool
from langchain.docstore.document import Document
from langchain.sch... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f655d0022c59-1 | content_field: str = "content",
metadata_field: str = "metadata",
vector_field: str = "vector",
pool_size: int = 5,
max_overflow: int = 10,
timeout: float = 30,
**kwargs: Any,
):
"""Initialize with necessary components.
Args:
embedding (Emb... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f655d0022c59-2 | establishing a connection. Defaults to 30.
Following arguments pertain to the database connection:
host (str, optional): Specifies the hostname, IP address, or URL for the
database connection. The default scheme is "mysql".
user (str, optional): Database username.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f655d0022c59-3 | use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.
autocommit (bool, optional): Enables autocommits.
results_type (str, optional): Determines the structure of the query results:
tuples, namedtuples, dicts.
results_format (str, optional): Deprecated. This option has be... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f655d0022c59-4 | self.table_name = self._sanitize_input(table_name)
self.content_field = self._sanitize_input(content_field)
self.metadata_field = self._sanitize_input(metadata_field)
self.vector_field = self._sanitize_input(vector_field)
# Pass the rest of the kwargs to the connection.
self.conn... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f655d0022c59-5 | {} BLOB, {} JSON);""".format(
self.table_name,
self.content_field,
self.vector_field,
self.metadata_field,
),
)
finally:
cur.close()
finally:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f655d0022c59-6 | finally:
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.
U... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f655d0022c59-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
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f655d0022c59-8 | self.content_field,
self.metadata_field,
self.distance_strategy.name
if isinstance(self.distance_strategy, DistanceStrategy)
else self.distance_strategy,
self.vector_field,
sel... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f655d0022c59-9 | Example:
.. code-block:: python
from langchain.vectorstores import SingleStoreDB
from langchain.embeddings import OpenAIEmbeddings
s2 = SingleStoreDB.from_texts(
texts,
OpenAIEmbeddings(),
host="usern... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
7f5bdd22c70f-0 | Source code for langchain.vectorstores.nucliadb
import os
from typing import Any, Dict, Iterable, List, Optional, Type
from langchain.schema.document import Document
from langchain.schema.embeddings import Embeddings
from langchain.schema.vectorstore import VST, VectorStore
FIELD_TYPES = {
"f": "files",
"t": "t... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/nucliadb.html |
7f5bdd22c70f-1 | if not backend:
backend = "http://localhost:8080"
self._config["BACKEND"] = f"{backend}/api/v1"
self._config["TOKEN"] = None
NucliaAuth().nucliadb(url=backend)
NucliaAuth().kb(url=self.kb_url, interactive=False)
else:
self._config["BACK... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/nucliadb.html |
7f5bdd22c70f-2 | )
ids.append(id)
return ids
[docs] def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:
if not ids:
return None
from nuclia.sdk import NucliaResource
factory = NucliaResource()
results: List[bool] = []
for id in id... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/nucliadb.html |
7f5bdd22c70f-3 | "metadata": {
"extra": getattr(
getattr(resource, "extra", {}), "metadata", None
),
"value": value,
},
"order": paragraph.order,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/nucliadb.html |
07301f37fbdb-0 | Source code for langchain.vectorstores.hologres
from __future__ import annotations
import json
import logging
import uuid
from typing import Any, Dict, Iterable, List, Optional, Tuple, Type
from langchain.docstore.document import Document
from langchain.schema.embeddings import Embeddings
from langchain.schema.vectorst... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
07301f37fbdb-1 | array_length(embedding, 1) = {self.ndims}),
metadata json,
document text);"""
)
self.cursor.execute(
f"call set_table_property('{self.table_name}'"
+ """, 'proxima_vectors',
'{"embedding":{"algorithm":"Graph",
"distance_method":"SquaredEuclidean",
"build_params":{"min_flush_prox... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
07301f37fbdb-2 | params = []
filter_clause = ""
if filter is not None:
conjuncts = []
for key, val in filter.items():
conjuncts.append("metadata->>%s=%s")
params.append(key)
params.append(val)
filter_clause = "where " + " and ".join(conj... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
07301f37fbdb-3 | embedding_function: Embeddings,
ndims: int = ADA_TOKEN_COUNT,
table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME,
pre_delete_table: bool = False,
logger: Optional[logging.Logger] = None,
) -> None:
self.connection_string = connection_string
self.ndims = ndims
sel... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
07301f37fbdb-4 | ) -> Hologres:
if ids is None:
ids = [str(uuid.uuid1()) for _ in texts]
if not metadatas:
metadatas = [{} for _ in texts]
connection_string = cls.get_connection_string(kwargs)
store = cls(
connection_string=connection_string,
embedding_func... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
07301f37fbdb-5 | **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.
kwargs: vectorstore specific parameters... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
07301f37fbdb-6 | k: int = 4,
filter: Optional[dict] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to embedding vector.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter (Opt... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
07301f37fbdb-7 | ) -> List[Tuple[Document, float]]:
results: List[Tuple[str, str, float]] = self.storage.query_nearest_neighbours(
embedding, k, filter
)
docs = [
(
Document(
page_content=result[0],
metadata=json.loads(result[1]),
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
07301f37fbdb-8 | ndims: int = ADA_TOKEN_COUNT,
table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME,
ids: Optional[List[str]] = None,
pre_delete_table: bool = False,
**kwargs: Any,
) -> Hologres:
"""Construct Hologres wrapper from raw documents and pre-
generated embeddings.
Return... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
07301f37fbdb-9 | **kwargs: Any,
) -> Hologres:
"""
Get instance of an existing Hologres store.This method will
return the instance of the store without inserting any new
embeddings
"""
connection_string = cls.get_connection_string(kwargs)
store = cls(
connection_st... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
07301f37fbdb-10 | """
texts = [d.page_content for d in documents]
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_... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
ee245b530eaa-0 | Source code for langchain.vectorstores.utils
"""Utility functions for working with vectors and vectorstores."""
from enum import Enum
from typing import List, Tuple, Type
import numpy as np
from langchain.docstore.document import Document
from langchain.utils.math import cosine_similarity
[docs]class DistanceStrategy(s... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/utils.html |
ee245b530eaa-1 | redundant_score = max(similarity_to_selected[i])
equation_score = (
lambda_mult * query_score - (1 - lambda_mult) * redundant_score
)
if equation_score > best_score:
best_score = equation_score
idx_to_add = i
idxs.append(idx_to_... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/utils.html |
6910dad2b44b-0 | Source code for langchain.vectorstores.azure_cosmos_db
from __future__ import annotations
import logging
from enum import Enum
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generator,
Iterable,
List,
Optional,
Tuple,
TypeVar,
Union,
)
import numpy as np
from langchain.docstore.d... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html |
6910dad2b44b-1 | from pymongo import MongoClient
mongo_client = MongoClient("<YOUR-CONNECTION-STRING>")
collection = mongo_client["<db_name>"]["<collection_name>"]
embeddings = OpenAIEmbeddings()
vectorstore = AzureCosmosDBVectorSearch(collection, embeddings)
"""
[docs] def __init_... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html |
6910dad2b44b-2 | """Creates an Instance of AzureCosmosDBVectorSearch from a Connection String
Args:
connection_string: The MongoDB vCore instance connection string
namespace: The namespace (database.collection)
embedding: The embedding utility
**kwargs: Dynamic keyword arguments
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html |
6910dad2b44b-3 | similarity: CosmosDBSimilarityType = CosmosDBSimilarityType.COS,
) -> dict[str, Any]:
"""Creates an index using the index name specified at
instance construction
Setting the numLists parameter correctly is important for achieving
good accuracy and performance.
Sin... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html |
6910dad2b44b-4 | dimensions: Number of dimensions for vector similarity.
The maximum number of supported dimensions is 2000
similarity: Similarity metric to use with the IVF index.
Possible options are:
- CosmosDBSimilarityType.COS (cosine distance),
- ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html |
6910dad2b44b-5 | texts_batch = []
metadatas_batch = []
result_ids = []
for i, (text, metadata) in enumerate(zip(texts, _metadatas)):
texts_batch.append(text)
metadatas_batch.append(metadata)
if (i + 1) % batch_size == 0:
result_ids.extend(self._insert_texts(tex... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html |
6910dad2b44b-6 | collection: Optional[Collection[CosmosDBDocumentType]] = None,
**kwargs: Any,
) -> AzureCosmosDBVectorSearch:
if collection is None:
raise ValueError("Must provide 'collection' named parameter.")
vectorstore = cls(collection, embedding, **kwargs)
vectorstore.add_texts(tex... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html |
6910dad2b44b-7 | {
"$search": {
"cosmosSearch": {
"vector": embeddings,
"path": self._embedding_key,
"k": k,
},
"returnStoredSource": True,
}
},
{
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html |
6910dad2b44b-8 | **kwargs: Any,
) -> List[Document]:
# Retrieves the docs with similarity scores
# sorted by similarity scores in DESC order
docs = self._similarity_search_with_score(embedding, k=fetch_k)
# Re-ranks the docs using MMR
mmr_doc_indexes = maximal_marginal_relevance(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html |
4fcb959a9089-0 | Source code for langchain.vectorstores.deeplake
from __future__ import annotations
import logging
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
import numpy as np
try:
import deeplake
from deeplake import VectorStore as DeepLakeVectorStore
from deeplake.core.fast_forwarding ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-1 | vectorstore = DeepLake("langchain_store", embeddings.embed_query)
"""
_LANGCHAIN_DEFAULT_DEEPLAKE_PATH = "./deeplake/"
[docs] def __init__(
self,
dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH,
token: Optional[str] = None,
embedding: Optional[Embeddings] = None,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-2 | to the dataset at path if it is a Deep Lake dataset.
Tokens are normally autogenerated. Optional.
embedding (Embeddings, optional): Function to convert
either documents or query. Optional.
embedding_function (Embeddings, optional): Function to convert
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-3 | during dataset creation.
runtime (Dict, optional): Parameters for creating the Vector Store in
Deep Lake's Managed Tensor Database. Not applicable when loading an
existing Vector Store. To create a Vector Store in the Managed Tensor
Database, set `runtime = {"... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-4 | raise ImportError(
"Could not import deeplake python package. "
"Please install it with `pip install deeplake[enterprise]`."
)
if (
runtime == {"tensor_db": True}
and version_compare(deeplake.__version__, "3.6.7") == -1
):
r... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-5 | """Run more texts through the embeddings and add to the vectorstore.
Examples:
>>> ids = deeplake_vectorstore.add_texts(
... texts = <list_of_texts>,
... metadatas = <list_of_metadata_jsons>,
... ids = <list_of_ids>,
... )
Args:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-6 | text=texts,
metadata=metadatas,
embedding_data=texts,
embedding_tensor="embedding",
embedding_function=self._embedding_function.embed_documents, # type: ignore
return_ids=True,
**kwargs,
)
def _search_tql(
self,
tql: Op... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-7 | """
result = self.vectorstore.search(
query=tql,
exec_option=exec_option,
)
metadatas = result["metadata"]
texts = result["text"]
docs = [
Document(
page_content=text,
metadata=metadata,
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-8 | into embedding.
k (int): Number of Documents to return.
distance_metric (Optional[str], optional): `L2` for Euclidean, `L1` for
Nuclear, `max` for L-infinity distance, `cos` for cosine similarity,
'dot' for dot product.
filter (Union[Dict, Callable], o... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-9 | the Vector Store initialization. If True, the distance metric is set
to "deepmemory_distance", which represents the metric with which the
model was trained. The search is performed using the Deep Memory model.
If False, the distance metric is set to "COS" or whatever dist... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-10 | if len(embedding.shape) > 1:
embedding = embedding[0]
result = self.vectorstore.search(
embedding=embedding,
k=fetch_k if use_maximal_marginal_relevance else k,
distance_metric=distance_metric,
filter=filter,
exec_option=exec_option,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-11 | Examples:
>>> # Search using an embedding
>>> data = vector_store.similarity_search(
... query=<your_query>,
... k=<num_items>,
... exec_option=<preferred_exec_option>,
... )
>>> # Run tql search:
>>> data = vect... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-12 | the client. Not for in-memory or local datasets.
- 'tensor_db': Managed Tensor Database for storage and query.
Only for data in Deep Lake Managed Database.
Use `runtime = {"db_engine": True}` during dataset creation.
deep_memory (bool):... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-13 | **kwargs: Additional keyword arguments including:
filter (Union[Dict, Callable], optional):
Additional filter before embedding search.
- ``Dict`` - Key-value search on tensors of htype json. True
if all key-value filters are satisfied.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-14 | search results. Defaults to False if deep_memory is not specified
in the Vector Store initialization. If True, the distance metric
is set to "deepmemory_distance", which represents the metric with
which the model was trained. The search is performed using the ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-15 | filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
embedding_function (Callable): Embedding function to use. Defaults
to None.
exec_option (str): DeepLakeVectorStore supports 3 ways to perform
searching. It could be either... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-16 | return self._search(
query=query,
k=k,
return_score=True,
**kwargs,
)
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
exec... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-17 | option with big datasets is discouraged due to potential
memory issues.
- "compute_engine" - Performant C++ implementation of the Deep
Lake Compute Engine. Runs on the client and can be used for
any data stored in or connected to Deep Lake. It ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-18 | exec_option: Optional[str] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Examples:
>>> # Search using an embedd... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-19 | `runtime = {"db_engine": True}` during dataset creation.
deep_memory (bool): Whether to use the Deep Memory model for improving
search results. Defaults to False if deep_memory is not specified
in the Vector Store initialization. If True, the distance metric
i... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-20 | **kwargs: Any,
) -> DeepLake:
"""Create a Deep Lake dataset from a raw documents.
If a dataset_path is specified, the dataset will be persisted in that location,
otherwise by default at `./deeplake`
Examples:
>>> # Search using an embedding
>>> vector_store = DeepLake... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-21 | embedding (Optional[Embeddings]): Embedding function. Defaults to None.
Note, in other places, it is called embedding_function.
metadatas (Optional[List[dict]]): List of metadatas. Defaults to None.
ids (Optional[List[str]]): List of document IDs. Defaults to None.
**... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4fcb959a9089-22 | Raises:
ValueError: if deeplake is not installed.
"""
try:
import deeplake
except ImportError:
raise ValueError(
"Could not import deeplake python package. "
"Please install it with `pip install deeplake`."
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
3eede363533c-0 | Source code for langchain.vectorstores.pinecone
from __future__ import annotations
import logging
import uuid
import warnings
from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Optional, Tuple, Union
import numpy as np
from langchain.docstore.document import Document
from langchain.schema.embeddings impor... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
3eede363533c-1 | raise ImportError(
"Could not import pinecone python package. "
"Please install it with `pip install pinecone-client`."
)
if not isinstance(embedding, Embeddings):
warnings.warn(
"Passing in `embedding` as a Callable is deprecated. Please p... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
3eede363533c-2 | namespace: Optional[str] = None,
batch_size: int = 32,
embedding_chunk_size: int = 1000,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Upsert optimization is done by chunking the embeddings and upserting them.
This... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
3eede363533c-3 | for i in range(0, len(texts), embedding_chunk_size):
chunk_texts = texts[i : i + embedding_chunk_size]
chunk_ids = ids[i : i + embedding_chunk_size]
chunk_metadatas = metadatas[i : i + embedding_chunk_size]
embeddings = self._embed_documents(chunk_texts)
async... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
3eede363533c-4 | embedding: List[float],
*,
k: int = 4,
filter: Optional[dict] = None,
namespace: Optional[str] = None,
) -> List[Tuple[Document, float]]:
"""Return pinecone documents most similar to embedding, along with scores."""
if namespace is None:
namespace = self._... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
3eede363533c-5 | """
docs_and_scores = self.similarity_search_with_score(
query, k=k, filter=filter, namespace=namespace, **kwargs
)
return [doc for doc, _ in docs_and_scores]
def _select_relevance_score_fn(self) -> Callable[[float], float]:
"""
The 'correct' relevance function
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
3eede363533c-6 | **kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
embedding: Embedding to look up documents similar to.
k... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
3eede363533c-7 | filter: Optional[dict] = None,
namespace: Optional[str] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
3eede363533c-8 | if index_name in indexes:
index = pinecone.Index(index_name, pool_threads=pool_threads)
elif len(indexes) == 0:
raise ValueError(
"No active indexes found in your Pinecone project, "
"are you sure you're using the right Pinecone API key and Environment? "
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
3eede363533c-9 | from langchain.embeddings import OpenAIEmbeddings
import pinecone
# The environment should be the one specified next to the API key
# in your Pinecone console
pinecone.init(api_key="***", environment="...")
embeddings = OpenAIEmbeddings()
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
3eede363533c-10 | ) -> None:
"""Delete by vector IDs or filter.
Args:
ids: List of ids to delete.
filter: Dictionary of conditions to filter vectors to delete.
"""
if namespace is None:
namespace = self._namespace
if delete_all:
self._index.delete(de... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
da09e904578a-0 | Source code for langchain.vectorstores.rocksetdb
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.schema.embeddings import Embeddings
from langchain.schema.vectorstore import Ve... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
da09e904578a-1 | text_key: str,
embedding_key: str,
workspace: str = "commons",
):
"""Initialize with Rockset client.
Args:
client: Rockset client object
collection: Rockset collection to insert docs / query
embeddings: Langchain Embeddings object to use to generat... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
da09e904578a-2 | ids: Optional[List[str]] = None,
batch_size: int = 32,
**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 ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
da09e904578a-3 | embedding_key: str = "",
ids: Optional[List[str]] = None,
batch_size: int = 32,
**kwargs: Any,
) -> Rockset:
"""Create Rockset wrapper with existing texts.
This is intended as a quicker way to get started.
"""
# Sanitize inputs
assert client is not Non... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
da09e904578a-4 | distance_func (DistanceFunction): how to compute distance between two
vectors in Rockset.
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 N... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
da09e904578a-5 | **kwargs: Any,
) -> List[Document]:
"""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 fo... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
da09e904578a-6 | ).format(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(type(v))
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
da09e904578a-7 | collection=self._collection_name, data=batch, workspace=self._workspace
)
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 impo... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
55461e2fe158-0 | Source code for langchain.vectorstores.momento_vector_index
from typing import (
TYPE_CHECKING,
Any,
Iterable,
List,
Optional,
Tuple,
Type,
TypeVar,
cast,
)
from uuid import uuid4
from langchain.docstore.document import Document
from langchain.schema.embeddings import Embeddings
from... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html |
55461e2fe158-1 | client: "PreviewVectorIndexClient",
index_name: str = "default",
distance_strategy: DistanceStrategy = DistanceStrategy.COSINE,
text_field: str = "text",
ensure_index_exists: bool = True,
**kwargs: Any,
):
"""Initialize a Vector Store backed by Momento Vector Index.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html |
55461e2fe158-2 | self._ensure_index_exists = ensure_index_exists
@staticmethod
def __validate_distance_strategy(distance_strategy: DistanceStrategy) -> None:
if distance_strategy not in [
DistanceStrategy.COSINE,
DistanceStrategy.MAX_INNER_PRODUCT,
DistanceStrategy.MAX_INNER_PRODUCT,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html |
55461e2fe158-3 | **kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
texts (Iterable[str]): Iterable of strings to add to the vectorstore.
metadatas (Optional[List[dict]]): Optional list of metadatas associated with
the tex... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html |
55461e2fe158-4 | raise ValueError("Number of ids must match number of texts")
else:
ids = [str(uuid4()) for _ in range(len(embeddings))]
batch_size = 128
for i in range(0, len(embeddings), batch_size):
start = i
end = min(i + batch_size, len(embeddings))
items = [
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html |
55461e2fe158-5 | """Search for similar documents to the query string.
Args:
query (str): The query string to search for.
k (int, optional): The number of results to return. Defaults to 4.
Returns:
List[Document]: A list of documents that are similar to the query.
"""
r... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html |
55461e2fe158-6 | """Search for similar documents to the query vector.
Args:
embedding (List[float]): The query vector to search for.
k (int, optional): The number of results to return. Defaults to 4.
kwargs (Any): Vector Store specific search parameters. The following are
forw... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html |
55461e2fe158-7 | """
results = self.similarity_search_with_score_by_vector(
embedding=embedding, k=k, **kwargs
)
return [doc for doc, _ in results]
[docs] @classmethod
def from_texts(
cls: Type[VST],
texts: List[str],
embedding: Embeddings,
metadatas: Optional[L... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html |
55461e2fe158-8 | - client (PreviewVectorIndexClient): The Momento Vector Index client to use.
- api_key (Optional[str]): The configuration to use to initialize
the Vector Index with. Defaults to None. If None, the configuration
is initialized from the environment variable `MOMENTO_API_KEY`.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html |
deda41dbc8c5-0 | Source code for langchain.vectorstores.elasticsearch
import logging
import uuid
from abc import ABC, abstractmethod
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Literal,
Optional,
Tuple,
Union,
)
import numpy as np
from langchain.docstore.document impo... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-1 | filter: List of filter clauses to apply to the query.
similarity: The similarity strategy to use, or None if not using one.
Returns:
Dict: The Elasticsearch query body.
"""
[docs] @abstractmethod
def index(
self,
dims_length: Union[int, None],
vecto... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-2 | """
return True
[docs]class ApproxRetrievalStrategy(BaseRetrievalStrategy):
"""Approximate retrieval strategy using the `HNSW` algorithm."""
[docs] def __init__(
self,
query_model_id: Optional[str] = None,
hybrid: Optional[bool] = False,
rrf: Optional[Union[dict, bool]] = ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-3 | "model_id": self.query_model_id, # use 'model_id' argument
"model_text": query, # use 'query' argument
}
}
else:
raise ValueError(
"You must provide an embedding function or a"
" query_model_id to perform a similarity ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-4 | similarityAlgo = "cosine"
elif similarity is DistanceStrategy.EUCLIDEAN_DISTANCE:
similarityAlgo = "l2_norm"
elif similarity is DistanceStrategy.DOT_PRODUCT:
similarityAlgo = "dot_product"
else:
raise ValueError(f"Similarity {similarity} not supported.")
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-5 | double value = dotProduct(params.query_vector, '{vector_query_field}');
return sigmoid(1, Math.E, -value);
"""
else:
raise ValueError(f"Similarity {similarity} not supported.")
queryBool: Dict = {"match_all": {}}
if filter:
queryBool = {"bool": {"... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-6 | vector_query_field: str,
text_field: str,
filter: List[dict],
similarity: Union[DistanceStrategy, None],
) -> Dict:
return {
"query": {
"bool": {
"must": [
{
"text_expansion": {
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-7 | "mappings": {
"properties": {
vector_query_field: {
"properties": {"tokens": {"type": "rank_features"}}
}
}
},
"settings": {"default_pipeline": self._get_pipeline_name()},
}
[docs] def requ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-8 | distance_strategy: Optional. Distance strategy to use when
searching the index.
Defaults to COSINE. Can be one of COSINE,
EUCLIDEAN_DISTANCE, or DOT_PRODUCT.
If you want to use a cloud hosted Elasticsearch instance, you can pass in ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
deda41dbc8c5-9 | from langchain.embeddings.openai import OpenAIEmbeddings
vectorstore = ElasticsearchStore(
embedding=OpenAIEmbeddings(),
index_name="langchain-demo",
es_url="http://localhost:9200",
strategy=ElasticsearchStore.ExactRetrievalStrategy()
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.