id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
2fa4c578ba06-42 | raise QdrantException(
f"Existing Qdrant collection {collection_name} uses named vectors. "
f"If you want to reuse it, please set `vector_name` to any of the "
f"existing named vectors: "
f"{', '.join(current_vector_config.keys())}." # noq... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
2fa4c578ba06-43 | f"Existing Qdrant collection is configured for "
f"{current_vector_config.distance} " # type: ignore[union-attr]
f"similarity. Please set `distance_func` parameter to "
f"`{distance_func}` if you want to reuse it. If you want to "
f"recrea... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
2fa4c578ba06-44 | distance_strategy=distance_func,
vector_name=vector_name,
)
return qdrant
def _select_relevance_score_fn(self) -> Callable[[float], float]:
"""
The 'correct' relevance function
may differ depending on a few things, including:
- the distance / similarity me... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
2fa4c578ba06-45 | Returns:
List of Tuples of (doc, similarity_score)
"""
return self.similarity_search_with_score(query, k, **kwargs)
@classmethod
def _build_payloads(
cls,
texts: Iterable[str],
metadatas: Optional[List[dict]],
content_payload_key: str,
metadata... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
2fa4c578ba06-46 | metadata=payload.get(metadata_payload_key) or {},
)
def _build_condition(self, key: str, value: Any) -> List[rest.FieldCondition]:
from qdrant_client.http import models as rest
out = []
if isinstance(value, dict):
for _key, value in value.items():
out.exte... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
2fa4c578ba06-47 | else:
if self._embeddings_function is not None:
embedding = self._embeddings_function(query)
else:
raise ValueError("Neither of embeddings or embedding_function is set")
return embedding.tolist() if hasattr(embedding, "tolist") else embedding
def _embe... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
2fa4c578ba06-48 | embeddings = []
for text in texts:
embedding = self._embeddings_function(text)
if hasattr(embeddings, "tolist"):
embedding = embedding.tolist()
embeddings.append(embedding)
else:
raise ValueError("Neither of embeddings o... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
2fa4c578ba06-49 | self.content_payload_key,
self.metadata_payload_key,
),
)
]
yield batch_ids, points
async def _agenerate_rest_batches(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
bde927c3ded9-0 | Source code for langchain.vectorstores.marqo
from __future__ import annotations
import json
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
)
from langchain.docstore.document import Document
from langchain.schema.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
bde927c3ded9-1 | searchable_attributes: Optional[List[str]] = None,
page_content_builder: Optional[Callable[[Dict[str, Any]], str]] = None,
):
"""Initialize with Marqo client."""
try:
import marqo
except ImportError:
raise ValueError(
"Could not import marqo py... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
bde927c3ded9-2 | Raises:
ValueError: if metadatas is provided and the number of metadatas differs
from the number of texts.
Returns:
List[str]: The list of ids that were added.
"""
if self._client.index(self._index_name).get_settings()["index_defaults"][
"treat_url... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
bde927c3ded9-3 | k: int = 4,
**kwargs: Any,
) -> List[Document]:
"""Search the marqo index for the most similar documents.
Args:
query (Union[str, Dict[str, float]]): The query for the search, either
as a string or a weighted query.
k (int, optional): The number of documen... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
bde927c3ded9-4 | **kwargs: Any,
) -> List[List[Document]]:
"""Search the marqo index for the most similar documents in bulk with multiple
queries.
Args:
queries (Iterable[Union[str, Dict[str, float]]]): An iterable of queries to
execute in bulk, queries in the list can be strings or d... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
bde927c3ded9-5 | documents and their scores for each query
"""
bulk_results = self.marqo_bulk_similarity_search(queries=queries, k=k)
bulk_documents: List[List[Tuple[Document, float]]] = []
for results in bulk_results["result"]:
documents = self._construct_documents_from_results_with_score(re... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
bde927c3ded9-6 | results (List[dict]): A marqo results object with the 'hits'.
include_scores (bool, optional): Include scores alongside documents.
Defaults to False.
Returns:
Union[List[Document], List[Tuple[Document, float]]]: The documents or
document score pairs if `include_sc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
bde927c3ded9-7 | """Return documents from Marqo using a bulk search, exposes Marqo's
output directly
Args:
queries (Iterable[Union[str, Dict[str, float]]]): A list of queries.
k (int, optional): The number of documents to return for each query.
Defaults to 4.
Returns:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
bde927c3ded9-8 | cls,
texts: List[str],
embedding: Any = None,
metadatas: Optional[List[dict]] = None,
index_name: str = "",
url: str = "http://localhost:8882",
api_key: str = "",
add_documents_settings: Optional[Dict[str, Any]] = None,
searchable_attributes: Optional[List... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
bde927c3ded9-9 | provided then one will be created with a UUID. Defaults to None.
url (str, optional): The URL for Marqo. Defaults to "http://localhost:8882".
api_key (str, optional): The API key for Marqo. Defaults to "".
metadatas (Optional[List[dict]], optional): A list of metadatas, to
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
bde927c3ded9-10 | if verbose:
print(f"Index {index_name} exists.")
instance: Marqo = cls(
client,
index_name,
searchable_attributes=searchable_attributes,
add_documents_settings=add_documents_settings or {},
page_content_builder=page_content_builder,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html |
2ced55ce827c-0 | Source code for langchain.vectorstores.milvus
from __future__ import annotations
import logging
from typing import Any, Iterable, List, Optional, Tuple, Union
from uuid import uuid4
import numpy as np
from langchain.docstore.document import Document
from langchain.schema.embeddings import Embeddings
from langchain.sche... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-1 | index_params (Optional[dict]): Which index params to use. Defaults to
HNSW/AUTOINDEX depending on service.
search_params (Optional[dict]): Which search params to use. Defaults to
default of index.
drop_old (Optional[bool]): Whether to drop the current collection. Defaults
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-2 | secure (bool): Default is false. If set to true, tls will be enabled.
client_key_path (str): If use tls two-way authentication, need to
write the client.key path.
client_pem_path (str): If use tls two-way authentication, need to
write the client.pem path.
ca_pem_path (str... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-3 | ):
"""Initialize the Milvus vector store."""
try:
from pymilvus import Collection, utility
except ImportError:
raise ValueError(
"Could not import pymilvus python package. "
"Please install it with `pip install pymilvus`."
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-4 | self.search_params = search_params
self.consistency_level = consistency_level
# In order for a collection to be compatible, pk needs to be auto'id and int
self._primary_field = primary_field
# In order for compatibility, the text field will need to be called "text"
self._text_fie... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-5 | uri: str = connection_args.get("uri", None)
user = connection_args.get("user", None)
# Order of use is host/port, uri, address
if host is not None and port is not None:
given_address = str(host) + ":" + str(port)
elif uri is not None:
given_address = uri.split("ht... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-6 | ) -> None:
if embeddings is not None:
self._create_collection(embeddings, metadatas)
self._extract_fields()
self._create_index()
self._create_search_params()
self._load()
def _create_collection(
self, embeddings: list, metadatas: Optional[list[dict]] = Non... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-7 | # Create the primary key field
fields.append(
FieldSchema(
self._primary_field, DataType.INT64, is_primary=True, auto_id=True
)
)
# Create the vector field, supports binary or float vectors
fields.append(
FieldSchema(self._vector_field,... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-8 | from pymilvus import Collection, MilvusException
if isinstance(self.col, Collection) and self._get_index() is None:
try:
# If no index params, use a default HNSW based one
if self.index_params is None:
self.index_params = {
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-9 | index_type: str = index["index_param"]["index_type"]
metric_type: str = index["index_param"]["metric_type"]
self.search_params = self.default_search_params[index_type]
self.search_params["metric_type"] = metric_type
def _load(self) -> None:
"""Load the collect... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-10 | Raises:
MilvusException: Failure to add texts
Returns:
List[str]: The resulting keys for each inserted element.
"""
from pymilvus import Collection, MilvusException
texts = list(texts)
try:
embeddings = self.embedding_func.embed_documents(texts... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-11 | # Insert into the collection.
try:
res: Collection
res = self.col.insert(insert_list, timeout=timeout, **kwargs)
pks.extend(res.primary_keys)
except MilvusException as e:
logger.error(
"Failed to insert batch sta... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-12 | self,
embedding: List[float],
k: int = 4,
param: Optional[dict] = None,
expr: Optional[str] = None,
timeout: Optional[int] = None,
**kwargs: Any,
) -> List[Document]:
"""Perform a similarity search against the query string.
Args:
embedding ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-13 | documentation found here:
https://milvus.io/api-reference/pymilvus/v2.2.6/Collection/search().md
Args:
query (str): The text being searched.
k (int, optional): The amount of results to return. Defaults to 4.
param (dict): The search params for the specified index.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-14 | Args:
embedding (List[float]): The embedding vector being searched.
k (int, optional): The amount of results to return. Defaults to 4.
param (dict): The search params for the specified index.
Defaults to None.
expr (str, optional): Filtering expression. De... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-15 | lambda_mult: float = 0.5,
param: Optional[dict] = None,
expr: Optional[str] = None,
timeout: Optional[int] = None,
**kwargs: Any,
) -> List[Document]:
"""Perform a search and return results that are reordered by MMR.
Args:
query (str): The text being searc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-16 | self,
embedding: list[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
param: Optional[dict] = None,
expr: Optional[str] = None,
timeout: Optional[int] = None,
**kwargs: Any,
) -> List[Document]:
"""Perform a search and return r... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-17 | anns_field=self._vector_field,
param=param,
limit=fetch_k,
expr=expr,
output_fields=output_fields,
timeout=timeout,
**kwargs,
)
# Organize results.
ids = []
documents = []
scores = []
for result in re... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-18 | collection_name: str = "LangChainCollection",
connection_args: dict[str, Any] = DEFAULT_MILVUS_CONNECTION,
consistency_level: str = "Session",
index_params: Optional[dict] = None,
search_params: Optional[dict] = None,
drop_old: bool = False,
**kwargs: Any,
) -> Milvus... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
2ced55ce827c-19 | drop_old=drop_old,
**kwargs,
)
vector_db.add_texts(texts=texts, metadatas=metadatas)
return vector_db | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
8f56c3209e0c-0 | Source code for langchain.vectorstores.vearch
from __future__ import annotations
import os
import time
import uuid
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Type
import numpy as np
from langchain.docstore.document import Document
from langchain.schema.embeddings import Embeddings
fro... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html |
8f56c3209e0c-1 | self.using_db_name = db_name
self.url = path_or_url
self.vearch = vearch_cluster.VearchCluster(path_or_url)
else:
if path_or_url is None:
metadata_path = os.getcwd().replace("\\", "/")
else:
metadata_path = path_or_url
i... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html |
8f56c3209e0c-2 | embedding=embedding,
metadatas=metadatas,
path_or_url=path_or_url,
table_name=table_name,
db_name=db_name,
flag=flag,
**kwargs,
)
[docs] @classmethod
def from_texts(
cls: Type[Vearch],
texts: List[str],
embedd... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html |
8f56c3209e0c-3 | engine_info = {
"index_size": 10000,
"retrieval_type": "IVFPQ",
"retrieval_param": {"ncentroids": 2048, "nsubvector": 32},
}
fields = [
vearch.GammaFieldInfo(fi["field"], type_dict[fi["type"]])
for fi in field_list
]
vector_fiel... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html |
8f56c3209e0c-4 | "text": {
"type": "string",
},
"metadata": {
"type": "string",
},
"text_embedding": {
"type": "vector",
"index": True,
"dimension": dim,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html |
8f56c3209e0c-5 | for text, metadata, embed in zip(texts, metadatas, embeddings):
profiles: dict[str, Any] = {}
profiles["text"] = text
profiles["metadata"] = metadata["source"]
embed_np = np.array(embed)
profiles["text_embedding"] = {
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html |
8f56c3209e0c-6 | docid = self.vearch.add(doc_items)
t_time = 0
while len(docid) != len(embeddings):
time.sleep(0.5)
if t_time > 6:
break
t_time += 1
self.vearch.dump()
return docid
def _load(se... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html |
8f56c3209e0c-7 | k: int = DEFAULT_TOPN,
**kwargs: Any,
) -> List[Document]:
"""
Return docs most similar to query.
"""
if self.embedding_func is None:
raise ValueError("embedding_func is None!!!")
embeddings = self.embedding_func.embed_query(query)
docs = self.simi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html |
8f56c3209e0c-8 | "feature": embed / np.linalg.norm(embed),
}
],
"fields": [],
"is_brute_search": 1,
"retrieval_param": {"metric_type": "InnerProduct", "nprobe": 20},
"topn": k,
}
query_result = self.vearch.search(... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html |
8f56c3209e0c-9 | if self.flag:
query_data = {
"query": {
"sum": [
{
"field": "text_embedding",
"feature": (embed / np.linalg.norm(embed)).tolist(),
}
],
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html |
8f56c3209e0c-10 | tmp_res = (Document(page_content=content, metadata=meta_data), score)
results.append(tmp_res)
return results
def _similarity_search_with_relevance_scores(
self,
query: str,
k: int = 4,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
return self.simil... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html |
8f56c3209e0c-11 | Returns:
Documents which satisfy the input conditions.
"""
results: Dict[str, Document] = {}
if ids is None or ids.__len__() == 0:
return results
if self.flag:
query_data = {"query": {"ids": ids}}
docs_detail = self.vearch.mget_by_ids(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html |
34536f75a885-0 | Source code for langchain.vectorstores.supabase
from __future__ import annotations
import uuid
from itertools import repeat
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
)
import numpy as np
from langchain.docstore.document import Docume... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
34536f75a885-1 | ]
embeddings = OpenAIEmbeddings()
supabase_client = create_client("my_supabase_url", "my_supabase_key")
vector_store = SupabaseVectorStore.from_documents(
docs,
embeddings,
client=supabase_client,
table_name="documents",
query_name="mat... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
34536f75a885-2 | @property
def embeddings(self) -> Embeddings:
return self._embedding
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[Dict[Any, Any]]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
ids = ids or [str(uu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
34536f75a885-3 | client=client,
embedding=embedding,
table_name=table_name,
query_name=query_name,
)
[docs] def add_vectors(
self,
vectors: List[List[float]],
documents: List[Document],
ids: List[str],
) -> List[str]:
return self._add_vectors(sel... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
34536f75a885-4 | vector, k=k, filter=filter
)
[docs] def match_args(
self, query: List[float], filter: Optional[Dict[str, Any]]
) -> Dict[str, Any]:
ret: Dict[str, Any] = dict(query_embedding=query)
if filter:
ret["filter"] = filter
return ret
[docs] def similarity_search_by... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
34536f75a885-5 | postgrest_filter: Optional[str] = None,
) -> List[Tuple[Document, float, np.ndarray[np.float32, Any]]]:
match_documents_params = self.match_args(query, filter)
query_builder = self._client.rpc(self.query_name, match_documents_params)
if postgrest_filter:
query_builder.params = qu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
34536f75a885-6 | ]
return docs
@staticmethod
def _add_vectors(
client: supabase.client.Client,
table_name: str,
vectors: List[List[float]],
documents: List[Document],
ids: List[str],
) -> List[str]:
"""Add vectors to Supabase table."""
rows: List[Dict[str, Any]... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
34536f75a885-7 | ) -> 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: Number of Documen... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
34536f75a885-8 | Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among th... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
34536f75a885-9 | Args:
ids: List of ids to delete.
"""
if ids is None:
raise ValueError("No ids provided to delete.")
rows: List[Dict[str, Any]] = [
{
"id": id,
}
for id in ids
]
# TODO: Check if this can be done in bulk
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
79999d7ac902-0 | Source code for langchain.vectorstores.azuresearch
from __future__ import annotations
import base64
import json
import logging
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
)
import numpy as np
from langchain.callbacks.man... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
79999d7ac902-1 | def _get_search_client(
endpoint: str,
key: str,
index_name: str,
semantic_configuration_name: Optional[str] = None,
fields: Optional[List[SearchField]] = None,
vector_search: Optional[VectorSearch] = None,
semantic_settings: Optional[SemanticSettings] = None,
scoring_profiles: Optional[... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
79999d7ac902-2 | # Check for missing keys
missing_fields = {
key: mandatory_fields[key]
for key, value in set(mandatory_fields.items())
- set(fields_types.items())
}
if len(missing_fields) > 0:
fmt_err = lambda x: ( # noqa: E731
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
79999d7ac902-3 | name=semantic_configuration_name,
prioritized_fields=PrioritizedFields(
prioritized_content_fields=[
SemanticField(field_name=FIELDS_CONTENT)
],
),
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
79999d7ac902-4 | )
"""Initialize with necessary components."""
# Initialize base class
self.embedding_function = embedding_function
default_fields = [
SimpleField(
name=FIELDS_ID,
type=SearchFieldDataType.String,
key=True,
filter... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
79999d7ac902-5 | [docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> List[str]:
"""Add texts data to an existing index."""
keys = kwargs.get("keys")
ids = []
# Write data to index
data = []
fo... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
79999d7ac902-6 | raise Exception(response)
# Reset data
data = []
# Considering case where data is an exact multiple of batch-size entries
if len(data) == 0:
return ids
# Upload data to index
response = self.client.upload_documents(documents=data)
# Che... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
79999d7ac902-7 | """
Returns the most similar indexed documents to the query text.
Args:
query (str): The query text for which to find similar documents.
k (int): The number of documents to return. Default is 4.
Returns:
List[Document]: A list of documents that are most simila... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
79999d7ac902-8 | },
),
float(result["@search.score"]),
)
for result in results
]
return docs
[docs] def hybrid_search(self, query: str, k: int = 4, **kwargs: Any) -> List[Document]:
"""
Returns the most similar indexed documents to the query text... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
79999d7ac902-9 | )
# Convert results to Document objects
docs = [
(
Document(
page_content=result.pop(FIELDS_CONTENT),
metadata=json.loads(result[FIELDS_METADATA])
if FIELDS_METADATA in result
else {
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
79999d7ac902-10 | """
from azure.search.documents.models import Vector
results = self.client.search(
search_text=query,
vectors=[
Vector(
value=np.array(
self.embedding_function(query), dtype=np.float32
).tolist(),
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
79999d7ac902-11 | ),
},
},
),
float(result["@search.score"]),
)
for result in results
]
return docs
[docs] @classmethod
def from_texts(
cls: Type[AzureSearch],
texts: List[str],
embedding: Em... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
79999d7ac902-12 | if search_type not in ("similarity", "hybrid", "semantic_hybrid"):
raise ValueError(f"search_type of {search_type} not allowed.")
return values
def _get_relevant_documents(
self,
query: str,
run_manager: CallbackManagerForRetrieverRun,
**kwargs: Any,
) -> ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
649330cc3eca-0 | Source code for langchain.vectorstores.epsilla
"""Wrapper around Epsilla vector database."""
from __future__ import annotations
import logging
import uuid
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Type
from langchain.docstore.document import Document
from langchain.schema.embeddings import Embedd... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html |
649330cc3eca-1 | """
_LANGCHAIN_DEFAULT_DB_NAME = "langchain_store"
_LANGCHAIN_DEFAULT_DB_PATH = "/tmp/langchain-epsilla"
_LANGCHAIN_DEFAULT_TABLE_NAME = "langchain_collection"
[docs] def __init__(
self,
client: Any,
embeddings: Embeddings,
db_path: Optional[str] = _LANGCHAIN_DEFAULT_DB_PA... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html |
649330cc3eca-2 | """
self._collection_name = collection_name
[docs] def clear_data(self, collection_name: str = "") -> None:
"""
Clear data in a collection.
Args:
collection_name (Optional[str]): The name of the collection.
If not provided, the default collection will be us... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html |
649330cc3eca-3 | dim = len(embeddings[0])
fields: List[dict] = [
{"name": "id", "dataType": "INT"},
{"name": "text", "dataType": "STRING"},
{"name": "embeddings", "dataType": "VECTOR_FLOAT", "dimensions": dim},
]
if metadatas is not None:
field_names = [field["name... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html |
649330cc3eca-4 | drop_old: Optional[bool] = False,
**kwargs: Any,
) -> List[str]:
"""
Embed texts and add them to the database.
Args:
texts (Iterable[str]): The texts to embed.
metadatas (Optional[List[dict]]): Metadata dicts
attached to each of the tex... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html |
649330cc3eca-5 | metadata = metadatas[index].items()
for key, value in metadata:
record[key] = value
records.append(record)
status_code, response = self._client.insert(
table_name=collection_name, records=records
)
if status_code != 200:
log... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html |
649330cc3eca-6 | return list(
map(
lambda item: Document(
page_content=item["text"],
metadata={
key: item[key] for key in item if key not in exclude_keys
},
),
response["result"],
)... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html |
649330cc3eca-7 | drop_old (Optional[bool]): Whether to drop the previous collection
and create a new one. Defaults to False.
Returns:
Epsilla: Epsilla vector store.
"""
instance = Epsilla(client, embedding, db_path=db_path, db_name=db_name)
instance.add_texts(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html |
649330cc3eca-8 | collection_name (Optional[str]): Which collection to use.
Defaults to "langchain_collection".
If provided, default collection name will be set as well.
drop_old (Optional[bool]): Whether to drop the previous collection
and create a new one. Default... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html |
ef9c205968e7-0 | Source code for langchain.vectorstores.sqlitevss
from __future__ import annotations
import json
import logging
import warnings
from typing import (
TYPE_CHECKING,
Any,
Iterable,
List,
Optional,
Tuple,
Type,
)
from langchain.docstore.document import Document
from langchain.schema.embeddings i... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sqlitevss.html |
ef9c205968e7-1 | self._embedding = embedding
self.create_table_if_not_exists()
[docs] def create_table_if_not_exists(self) -> None:
self._connection.execute(
f"""
CREATE TABLE IF NOT EXISTS {self._table}
(
rowid INTEGER PRIMARY KEY AUTOINCREMENT,
text TE... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sqlitevss.html |
ef9c205968e7-2 | max_id = 0
embeds = self._embedding.embed_documents(list(texts))
if not metadatas:
metadatas = [{} for _ in texts]
data_input = [
(text, json.dumps(metadata), json.dumps(embed))
for text, metadata, embed in zip(texts, metadatas, embeds)
]
self.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sqlitevss.html |
ef9c205968e7-3 | documents.append((doc, row["distance"]))
return documents
[docs] def similarity_search(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query."""
embedding = self._embedding.embed_query(query)
documents = self.similarity_sear... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sqlitevss.html |
ef9c205968e7-4 | connection = cls.create_connection(db_file)
vss = cls(
table=table, connection=connection, db_file=db_file, embedding=embedding
)
vss.add_texts(texts=texts, metadatas=metadatas)
return vss
[docs] @staticmethod
def create_connection(db_file: str) -> sqlite3.Connection:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sqlitevss.html |
17adba3b76c4-0 | Source code for langchain.vectorstores.weaviate
from __future__ import annotations
import datetime
import os
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple,
)
from uuid import uuid4
import numpy as np
from langchain.docstore.document import Docum... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
17adba3b76c4-1 | return 1 - 1 / (1 + np.exp(val))
def _json_serializable(value: Any) -> Any:
if isinstance(value, datetime.datetime):
return value.isoformat()
return value
[docs]class Weaviate(VectorStore):
"""`Weaviate` vector store.
To use, you should have the ``weaviate-client`` python package installed.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
17adba3b76c4-2 | self._query_attrs = [self._text_key]
self.relevance_score_fn = relevance_score_fn
self._by_text = by_text
if attributes is not None:
self._query_attrs.extend(attributes)
@property
def embeddings(self) -> Optional[Embeddings]:
return self._embedding
def _select_rel... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
17adba3b76c4-3 | if "uuids" in kwargs:
_id = kwargs["uuids"][i]
elif "ids" in kwargs:
_id = kwargs["ids"][i]
batch.add_data_object(
data_object=data_properties,
class_name=self._index_name,
uuid=_id,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
17adba3b76c4-4 | """
content: Dict[str, Any] = {"concepts": [query]}
if kwargs.get("search_distance"):
content["certainty"] = kwargs.get("search_distance")
query_obj = self._client.query.get(self._index_name, self._query_attrs)
if kwargs.get("where_filter"):
query_obj = query_obj.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
17adba3b76c4-5 | for res in result["data"]["Get"][self._index_name]:
text = res.pop(self._text_key)
docs.append(Document(page_content=text, metadata=res))
return docs
[docs] def max_marginal_relevance_search(
self,
query: str,
k: int = 4,
fetch_k: int = 20,
lamb... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
17adba3b76c4-6 | k: int = 4,
fetch_k: int = 20,
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... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
17adba3b76c4-7 | payload[idx].pop("_additional")
meta = payload[idx]
docs.append(Document(page_content=text, metadata=meta))
return docs
[docs] def similarity_search_with_score(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Tuple[Document, float]]:
"""
Return list o... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
17adba3b76c4-8 | text = res.pop(self._text_key)
score = np.dot(res["_additional"]["vector"], embedded_query)
docs_and_scores.append((Document(page_content=text, metadata=res), score))
return docs_and_scores
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embeddin... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
17adba3b76c4-9 | from the ``Details`` tab. Can be passed in as a named param or by
setting the environment variable ``WEAVIATE_URL``. Should not be
specified if client is provided.
weaviate_api_key: The Weaviate API key. If enabled and using Weaviate Cloud
Services, get it fro... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
17adba3b76c4-10 | url=weaviate_url,
api_key=weaviate_api_key,
)
if batch_size:
client.batch.configure(batch_size=batch_size)
index_name = index_name or f"LangChain_{uuid4().hex}"
schema = _default_schema(index_name)
# check whether the index already exists
if not cl... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
17adba3b76c4-11 | batch.flush()
return cls(
client,
index_name,
text_key,
embedding=embedding,
attributes=attributes,
relevance_score_fn=relevance_score_fn,
by_text=by_text,
**kwargs,
)
[docs] def delete(self, ids: Optional... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.