id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
8e649523b3f0-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... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
8e649523b3f0-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",
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
8e649523b3f0-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",
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
8e649523b3f0-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... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
3c67ba3b8083-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, Type
from langchain.schema.document import Document
from langchain.schema.embeddings import Embeddings
from langch... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
3c67ba3b8083-1 | using this module.
See usage in
docs/modules/indexes/vectorstores/examples/matchingengine.ipynb.
Note that this implementation is mostly meant for reading if you are
planning to do a real time implementation. While reading is a real time
operation, updating the index takes close ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
3c67ba3b8083-2 | "google-cloud-aiplatform google-cloud-storage`"
"to use the MatchingEngine Vectorstore."
)
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the emb... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
3c67ba3b8083-3 | )
self.index = self.index.update_embeddings(
contents_delta_uri=f"gs://{self.gcs_bucket_name}/{filename_prefix}/"
)
logger.debug("Updated index with new configuration.")
return ids
def _upload_to_gcs(self, data: str, gcs_location: str) -> None:
"""Uploads data to ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
3c67ba3b8083-4 | )
if len(response) == 0:
return []
logger.debug(f"Found {len(response)} matches for the query {query}.")
results = []
# I'm only getting the first one because queries receives an array
# and the similarity_search method only receives one query. This
# means th... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
3c67ba3b8083-5 | texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> "MatchingEngine":
"""Use from components instead."""
raise NotImplementedError(
"This method is not implemented. Instead, you should initialize the class"
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
3c67ba3b8083-6 | credentials = cls._create_credentials_from_file(credentials_path)
index = cls._create_index_by_id(index_id, project_id, region, credentials)
endpoint = cls._create_endpoint_by_id(
endpoint_id, project_id, region, credentials
)
gcs_client = cls._get_gcs_client(credentials, pro... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
3c67ba3b8083-7 | An optional of Credentials or None, in which case the default
will be used.
"""
from google.oauth2 import service_account
credentials = None
if json_credentials_path is not None:
credentials = service_account.Credentials.from_service_account_file(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
3c67ba3b8083-8 | logger.debug(f"Creating endpoint with id {endpoint_id}.")
return aiplatform.MatchingEngineIndexEndpoint(
index_endpoint_name=endpoint_id,
project=project_id,
location=region,
credentials=credentials,
)
@classmethod
def _get_gcs_client(
cls,... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
3c67ba3b8083-9 | """This function returns the default embedding.
Returns:
Default TensorflowHubEmbeddings to use.
"""
from langchain.embeddings import TensorflowHubEmbeddings
return TensorflowHubEmbeddings() | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
750901657dd9-0 | Source code for langchain.vectorstores.faiss
from __future__ import annotations
import operator
import os
import pickle
import uuid
import warnings
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Sized,
Tuple,
)
import numpy as np
from langcha... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-1 | "or `pip install faiss-cpu` (depending on Python version)."
)
return faiss
def _len_check_if_sized(x: Any, y: Any, x_name: str, y_name: str) -> None:
if isinstance(x, Sized) and isinstance(y, Sized) and len(x) != len(y):
raise ValueError(
f"{x_name} and {y_name} expected to be equal ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-2 | self.distance_strategy = distance_strategy
self.override_relevance_score_fn = relevance_score_fn
self._normalize_L2 = normalize_L2
if (
self.distance_strategy != DistanceStrategy.EUCLIDEAN_DISTANCE
and self._normalize_L2
):
warnings.warn(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-3 | self.index.add(vector)
# Add information to docstore and index.
ids = ids or [str(uuid.uuid4()) for _ in texts]
self.docstore.add({id_: doc for id_, doc in zip(ids, documents)})
starting_len = len(self.index_to_docstore_id)
index_to_id = {starting_len + j: id_ for j, id_ in enume... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-4 | text_embeddings: Iterable pairs of string and embedding to
add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
ids: Optional list of unique IDs.
Returns:
List of ids from adding the texts into the vectorstore.
"""
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-5 | if self._normalize_L2:
faiss.normalize_L2(vector)
scores, indices = self.index.search(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.
conti... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-6 | **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.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-7 | 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... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-8 | among selected documents.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch before filtering to
pass to MMR algorithm.
lambda_mult: Number between... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-9 | np.array([embedding], dtype=np.float32),
embeddings,
k=k,
lambda_mult=lambda_mult,
)
selected_indices = [indices[0][i] for i in mmr_selected]
selected_scores = [scores[0][i] for i in mmr_selected]
docs_and_scores = []
for i, score in zip(select... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-10 | to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
Returns:
List of Documents selected by maximal marginal relevance.
"""
docs_and_scores = self.max_marginal_relevance_search_with_score_by_vector(
embedding, k=k, fetch_k=fetch_k, lam... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-11 | filter=filter,
**kwargs,
)
return docs
[docs] def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:
"""Delete by ID. These are the IDs in the vectorstore.
Args:
ids: List of ids to delete.
Returns:
Optional[bool... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-12 | Returns:
None.
"""
if not isinstance(self.docstore, AddableMixin):
raise ValueError("Cannot merge with this type of docstore")
# Numerical index for target docs are incremental on existing ones
starting_len = len(self.index_to_docstore_id)
# Merge two Inde... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-13 | else:
# Default to L2, currently other metric types not initialized.
index = faiss.IndexFlatL2(len(embeddings[0]))
vecstore = cls(
embedding.embed_query,
index,
InMemoryDocstore(),
{},
normalize_L2=normalize_L2,
dist... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-14 | cls,
text_embeddings: Iterable[Tuple[str, List[float]]],
embedding: Embeddings,
metadatas: Optional[Iterable[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> FAISS:
"""Construct FAISS wrapper from raw documents.
This is a user friendly inter... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-15 | path = Path(folder_path)
path.mkdir(exist_ok=True, parents=True)
# save index separately since it is not picklable
faiss = dependable_faiss_import()
faiss.write_index(
self.index, str(path / "{index_name}.faiss".format(index_name=index_name))
)
# save docstore... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-16 | )
[docs] def serialize_to_bytes(self) -> bytes:
"""Serialize FAISS index, docstore, and index_to_docstore_id to bytes."""
return pickle.dumps((self.index, self.docstore, self.index_to_docstore_id))
[docs] @classmethod
def deserialize_from_bytes(
cls,
serialized: bytes,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
750901657dd9-17 | return self._cosine_relevance_score_fn
else:
raise ValueError(
"Unknown distance strategy, must be cosine, max_inner_product,"
" or euclidean"
)
def _similarity_search_with_relevance_scores(
self,
query: str,
k: int = 4,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
b49543a44918-0 | Source code for langchain.vectorstores.dingo
from __future__ import annotations
import logging
import uuid
from typing import Any, Iterable, List, Optional, Tuple
import numpy as np
from langchain.docstore.document import Document
from langchain.schema.embeddings import Embeddings
from langchain.schema.vectorstore impo... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html |
b49543a44918-1 | else:
try:
# connect to dingo db
dingo_client = dingodb.DingoDB(user, password, host)
except ValueError as e:
raise ValueError(f"Dingo failed to connect: {e}")
self._text_key = text_key
self._client = dingo_client
if index_n... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html |
b49543a44918-2 | embeds = self._embedding.embed_documents(texts)
for i, text in enumerate(texts):
metadata = metadatas[i] if metadatas else {}
metadata[self._text_key] = text
metadatas_list.append(metadata)
# upsert to Dingo
for i in range(0, len(list(texts)), batch_size):
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html |
b49543a44918-3 | timeout: Optional[int] = None,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return Dingo documents most similar to query, along with scores.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
search_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html |
b49543a44918-4 | among selected documents.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
lambda_mult: Number between 0 and 1 that determines the degree
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html |
b49543a44918-5 | search_params: Optional[dict] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
query: Text to look u... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html |
b49543a44918-6 | This is a user friendly interface that:
1. Embeds documents.
2. Adds the documents to a provided Dingo index
This is intended to be a quick way to get started.
Example:
.. code-block:: python
from langcha... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html |
b49543a44918-7 | metadatas_list = []
texts = list(texts)
embeds = embedding.embed_documents(texts)
for i, text in enumerate(texts):
metadata = metadatas[i] if metadatas else {}
metadata[text_key] = text
metadatas_list.append(metadata)
# upsert to Dingo
for i in... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html |
03b6483b7d90-0 | Source code for langchain.vectorstores.timescalevector
"""VectorStore wrapper around a Postgres-TimescaleVector database."""
from __future__ import annotations
import enum
import logging
import uuid
from datetime import timedelta
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-1 | from langchain.embeddings.openai import OpenAIEmbeddings
SERVICE_URL = "postgres://tsdbadmin:<password>@<id>.tsdb.cloud.timescale.com:<port>/tsdb?sslmode=require"
COLLECTION_NAME = "state_of_the_union_test"
embeddings = OpenAIEmbeddings()
vectorestore = TimescaleVector.fr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-2 | self.sync_client = client.Sync(
self.service_url,
self.collection_name,
self.num_dimensions,
self._distance_strategy.value.lower(),
time_partition_interval=self._time_partition_interval,
)
self.async_client = client.Async(
self.serv... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-3 | if service_url is None:
service_url = cls.get_service_url(kwargs)
store = cls(
service_url=service_url,
num_dimensions=num_dimensions,
collection_name=collection_name,
embedding=embedding,
distance_strategy=distance_strategy,
pr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-4 | **kwargs,
)
await store.aadd_embeddings(
texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs
)
return store
[docs] def add_embeddings(
self,
texts: Iterable[str],
embeddings: List[List[float]],
metadatas: Optional[List... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-5 | kwargs: vectorstore specific parameters
"""
if ids is None:
ids = [str(uuid.uuid1()) for _ in texts]
if not metadatas:
metadatas = [{} for _ in texts]
records = list(zip(ids, metadatas, texts, embeddings))
await self.async_client.upsert(records)
re... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-6 | kwargs: vectorstore specific parameters
Returns:
List of ids from adding the texts into the vectorstore.
"""
embeddings = self.embedding.embed_documents(list(texts))
return await self.aadd_embeddings(
texts=texts, embeddings=embeddings, metadatas=metadatas, ids=id... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-7 | Args:
query (str): Query text to search for.
k (int): Number of results to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
Returns:
List of Documents most similar to the query.
"""
embedding = self.em... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-8 | filter: Optional[Union[dict, list]] = None,
predicates: Optional[Predicates] = None,
**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. De... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-9 | filter: Optional[Union[dict, list]] = None,
predicates: Optional[Predicates] = None,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
try:
from timescale_vector import client
except ImportError:
raise ImportError(
"Could not import timescale_v... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-10 | uuid_time_filter=self.date_to_range_filter(**kwargs),
)
docs = [
(
Document(
page_content=result[client.SEARCH_RESULT_CONTENTS_IDX],
metadata=result[client.SEARCH_RESULT_METADATA_IDX],
),
result[client.SE... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-11 | Args:
embedding: Embedding 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.
Returns:
List of Documents most similar to the query vector.
"""
d... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-12 | cls: Type[TimescaleVector],
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,
ids: Optional[List[str]] = None,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-13 | Postgres connection string is required
"Either pass it as a parameter
or set the TIMESCALE_SERVICE_URL environment variable.
Example:
.. code-block:: python
from langchain.vectorstores import TimescaleVector
from langchain.embeddings import OpenAIEmbed... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-14 | or set the TIMESCALE_SERVICE_URL environment variable.
Example:
.. code-block:: python
from langchain.vectorstores import TimescaleVector
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
text_embeddings ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-15 | )
return store
[docs] @classmethod
def get_service_url(cls, kwargs: Dict[str, Any]) -> str:
service_url: str = get_from_dict_or_env(
data=kwargs,
key="service_url",
env_key="TIMESCALE_SERVICE_URL",
)
if not service_url:
raise ValueEr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-16 | return self._euclidean_relevance_score_fn
elif self._distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:
return self._max_inner_product_relevance_score_fn
else:
raise ValueError(
"No supported normalization function"
f" for distance_strategy o... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
03b6483b7d90-17 | PGVECTOR_IVFFLAT = "ivfflat"
PGVECTOR_HNSW = "hnsw"
DEFAULT_INDEX_TYPE = IndexType.TIMESCALE_VECTOR
[docs] def create_index(
self, index_type: Union[IndexType, str] = DEFAULT_INDEX_TYPE, **kwargs: Any
) -> None:
try:
from timescale_vector import client
except Impor... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html |
2aadc913dc66-0 | Source code for langchain.vectorstores.tigris
from __future__ import annotations
import itertools
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple
from langchain.schema import Document
from langchain.schema.embeddings import Embeddings
from langchain.vectorstores import VectorStore
if TYPE_CHECKIN... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html |
2aadc913dc66-1 | """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 for documents.
Ids will be autogenerated... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html |
2aadc913dc66-2 | text with distance in float.
"""
vector = self._embed_fn.embed_query(query)
result = self.search_index.similarity_search(
vector=vector, k=k, filter_by=filter
)
docs: List[Tuple[Document, float]] = []
for r in result:
docs.append(
(... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html |
2aadc913dc66-3 | for t, m, e, _id in itertools.zip_longest(
texts, metadatas or [], embeddings or [], ids or []
):
doc: TigrisDocument = {
"text": t,
"embeddings": e or [],
"metadata": m or {},
}
if _id:
doc["id"] = _... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html |
161a8102aefa-0 | Source code for langchain.vectorstores.dashvector
from __future__ import annotations
import logging
import uuid
from typing import (
Any,
Iterable,
List,
Optional,
Tuple,
)
import numpy as np
from langchain.docstore.document import Document
from langchain.schema.embeddings import Embeddings
from lan... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html |
161a8102aefa-1 | )
self._collection = collection
self._embedding = embedding
self._text_field = text_field
def _similarity_search_with_score_by_vector(
self,
embedding: List[float],
k: int = 4,
filter: Optional[str] = None,
) -> List[Tuple[Document, float]]:
"""Ret... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html |
161a8102aefa-2 | List of ids from adding the texts into the vectorstore.
"""
ids = ids or [str(uuid.uuid4().hex) for _ in texts]
text_list = list(texts)
for i in range(0, len(text_list), batch_size):
# batch end
end = min(i + batch_size, len(text_list))
batch_texts = t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html |
161a8102aefa-3 | **kwargs: Any,
) -> List[Document]:
"""Return docs most similar to query.
Args:
query: Text to search documents similar to.
k: Number of documents to return. Default to 4.
filter: Doc fields filter conditions that meet the SQL where clause
spec... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html |
161a8102aefa-4 | """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: Doc fields filter conditions that meet the SQL where clause
specification.
Returns... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html |
161a8102aefa-5 | return self.max_marginal_relevance_search_by_vector(
embedding, k, fetch_k, lambda_mult, filter
)
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
filter: Opti... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html |
161a8102aefa-6 | np.array(embedding), candidate_embeddings, lambda_mult, k
)
metadatas = [ret.output[i].fields for i in mmr_selected]
return [
Document(page_content=metadata.pop(self._text_field), metadata=metadata)
for metadata in metadatas
]
[docs] @classmethod
def from_t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html |
161a8102aefa-7 | )
dashvector_client = dashvector.Client(api_key=dashvector_api_key)
dashvector_client.delete(collection_name)
collection = dashvector_client.get(collection_name)
if not collection:
dim = len(embedding.embed_query(texts[0]))
# create collection if not existed
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html |
6faa4c7997c3-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.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-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... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-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... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-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... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-4 | embeddings = self.embedding.embed_documents(list(texts))
dim = len(embeddings[0])
mapping = _default_text_mapping(dim)
# check to see if the index already exists
try:
self.client.indices.get(index=self.index_name)
except NotFoundError:
# TODO would be nice... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-5 | return documents
[docs] def similarity_search_with_score(
self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query.
Args:
query: Text to look up documents similar to.
k: Numbe... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-6 | 3. Adds the documents to the newly created Elasticsearch index.
This is intended to be a quick way to get started.
Example:
.. code-block:: python
from langchain.vectorstores import ElasticVectorSearch
from langchain.embeddings import OpenAIEmbeddings
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-7 | version_num = int(version_num)
if version_num >= 8:
response = client.search(index=index_name, query=script_query, size=size)
else:
response = client.search(
index=index_name, body={"query": script_query, "size": size}
)
return response
[docs] ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-8 | es_connection (Elasticsearch, optional): An existing Elasticsearch connection.
es_cloud_id (str, optional): The Cloud ID of your Elasticsearch Service
deployment.
es_user (str, optional): The username for your Elasticsearch Service deployment.
es_password (str, optional): The passwor... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-9 | "Use ElasticsearchStore instead. See Elasticsearch "
"integration docs on how to upgrade."
)
self.embedding = embedding
self.index_name = index_name
self.query_field = query_field
self.vector_query_field = vector_query_field
# If a pre-existing Elasticsearch c... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-10 | "field": self.vector_query_field,
"k": k,
"num_candidates": num_candidates,
}
# Case 1: `query_vector` is provided, but not `model_id` -> use query_vector
if query_vector and not model_id:
knn["query_vector"] = query_vector
# Case 2: `query` and `model... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-11 | k: Optional[int] = 10,
query_vector: Optional[List[float]] = None,
model_id: Optional[str] = None,
size: Optional[int] = 10,
source: Optional[bool] = True,
fields: Optional[
Union[List[Mapping[str, Any]], Tuple[Mapping[str, Any], ...], None]
] = None,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-12 | knn_query_body = self._default_knn_query(
query_vector=query_vector, query=query, model_id=model_id, k=k
)
# Perform the kNN search on the Elasticsearch index and return the results.
response = self.client.search(
index=self.index_name,
knn=knn_query_body,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-13 | Args:
query (str, optional): The query text to search for.
k (int, optional): The number of nearest neighbors to return.
query_vector (List[float], optional): The query vector to search for.
model_id (str, optional): The ID of the model to use for transforming the
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-14 | }
# Perform the hybrid search on the Elasticsearch index and return the results.
response = self.client.search(
index=self.index_name,
query=match_query_body,
knn=knn_query_body,
fields=fields,
size=size,
source=source,
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-15 | model_id (str, optional): The ID of the model to use for transforming the
texts into vectors.
refresh_indices (bool, optional): Whether to refresh the Elasticsearch
indices after adding the texts.
**kwargs: Arbitrary keyword arguments.
Returns:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-16 | metadatas: Optional[List[Dict[Any, Any]]] = None,
**kwargs: Any,
) -> ElasticKnnSearch:
"""
Create a new ElasticKnnSearch instance and add a list of texts to the
Elasticsearch index.
Args:
texts (List[str]): The texts to add to the index.
embedding... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
6faa4c7997c3-17 | es_password=es_password,
**optional_args,
)
# Encode the provided texts and add them to the newly created index.
knnvectorsearch.add_texts(texts, model_id=model_id, dims=dims, **optional_args)
return knnvectorsearch | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
8da5e8394a4e-0 | Source code for langchain.vectorstores.bageldb
from __future__ import annotations
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
)
if TYPE_CHECKING:
import bagel
import bagel.config
from bagel.api.types import I... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html |
8da5e8394a4e-1 | client_settings: Optional[bagel.config.Settings] = None,
embedding_function: Optional[Embeddings] = None,
cluster_metadata: Optional[Dict] = None,
client: Optional[bagel.Client] = None,
relevance_score_fn: Optional[Callable[[float], float]] = None,
) -> None:
"""Initialize wi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html |
8da5e8394a4e-2 | **kwargs: Any,
) -> List[Document]:
"""Query the BagelDB cluster based on the provided parameters."""
try:
import bagel # noqa: F401
except ImportError:
raise ValueError("Please install bagel `pip install betabageldb`.")
return self._cluster.find(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html |
8da5e8394a4e-3 | if length_diff:
metadatas = metadatas + [{}] * length_diff
empty_ids = []
non_empty_ids = []
for idx, metadata in enumerate(metadatas):
if metadata:
non_empty_ids.append(idx)
else:
empty_ids.appen... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html |
8da5e8394a4e-4 | )
return ids
[docs] def similarity_search(
self,
query: str,
k: int = DEFAULT_K,
where: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Document]:
"""
Run a similarity search with BagelDB.
Args:
query (str): The query t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html |
8da5e8394a4e-5 | return _results_to_docs_and_scores(results)
[docs] @classmethod
def from_texts(
cls: Type[Bagel],
texts: List[str],
embedding: Optional[Embeddings] = None,
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
cluster_name: str = _LANGCHAIN_DEFAU... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html |
8da5e8394a4e-6 | **kwargs,
)
_ = bagel_cluster.add_texts(
texts=texts, embeddings=text_embeddings, metadatas=metadatas, ids=ids
)
return bagel_cluster
[docs] def delete_cluster(self) -> None:
"""Delete the cluster."""
self._client.delete_cluster(self._cluster.name)
[docs] ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html |
8da5e8394a4e-7 | distance = "l2"
distance_key = "hnsw:space"
metadata = self._cluster.metadata
if metadata and distance_key in metadata:
distance = metadata[distance_key]
if distance == "cosine":
return self._cosine_relevance_score_fn
elif distance == "l2":
ret... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html |
8da5e8394a4e-8 | client (Optional[bagel.Client]): Bagel client instance.
cluster_metadata (Optional[Dict]): Metadata associated with the
Bagel cluster. Defaults to None.
Returns:
Bagel: Bagel vectorstore.
"""
texts = [doc.page_content for doc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html |
8da5e8394a4e-9 | "limit": limit,
"offset": offset,
"where_document": where_document,
}
if include is not None:
kwargs["include"] = include
return self._cluster.get(**kwargs)
[docs] def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None:
"""
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html |
2c58abcc3b7c-0 | Source code for langchain.vectorstores.clickhouse
from __future__ import annotations
import json
import logging
from hashlib import sha1
from threading import Thread
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from langchain.docstore.document import Document
from langchain.pydantic_v1 import Ba... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
2c58abcc3b7c-1 | Defaults to 'vector_table'.
metric (str) : Metric to compute distance,
supported are ('angular', 'euclidean', 'manhattan', 'hamming',
'dot'). Defaults to 'angular'.
https://github.com/spotify/annoy/blob/main/src/annoymodule.cc#L149-L169
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.