id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
28a31fa6c2bd-0 | Source code for langchain.vectorstores.sklearn
""" Wrapper around scikit-learn NearestNeighbors implementation.
The vector store can be persisted in json, bson or parquet format.
"""
import json
import math
import os
from abc import ABC, abstractmethod
from typing import Any, Dict, Iterable, List, Literal, Optional, Tu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
28a31fa6c2bd-1 | json.dump(data, fp)
[docs] def load(self) -> Any:
with open(self.persist_path, "r") as fp:
return json.load(fp)
[docs]class BsonSerializer(BaseSerializer):
"""Serializes data in binary json using the bson python package."""
[docs] def __init__(self, persist_path: str) -> None:
supe... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
28a31fa6c2bd-2 | os.rename(self.persist_path, backup_path)
try:
self.pq.write_table(table, self.persist_path)
except Exception as exc:
os.rename(backup_path, self.persist_path)
raise exc
else:
os.remove(backup_path)
else:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
28a31fa6c2bd-3 | self._neighbors_fitted = False
self._embedding_function = embedding
self._persist_path = persist_path
self._serializer: Optional[BaseSerializer] = None
if self._persist_path is not None:
serializer_cls = SERIALIZER_MAP[serializer]
self._serializer = serializer_cls... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
28a31fa6c2bd-4 | self._texts = data["texts"]
self._metadatas = data["metadatas"]
self._ids = data["ids"]
self._update_neighbors()
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
28a31fa6c2bd-5 | )
neigh_dists, neigh_idxs = self._neighbors.kneighbors(
[query_embedding], n_neighbors=k
)
return list(zip(neigh_idxs[0], neigh_dists[0]))
[docs] def similarity_search_with_score(
self, query: str, *, k: int = DEFAULT_K, **kwargs: Any
) -> List[Tuple[Document, float]]:... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
28a31fa6c2bd-6 | self,
embedding: List[float],
k: int = DEFAULT_K,
fetch_k: int = DEFAULT_FETCH_K,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
28a31fa6c2bd-7 | self,
query: str,
k: int = DEFAULT_K,
fetch_k: int = DEFAULT_FETCH_K,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND d... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
28a31fa6c2bd-8 | vs = SKLearnVectorStore(embedding, persist_path=persist_path, **kwargs)
vs.add_texts(texts, metadatas=metadatas, ids=ids)
return vs | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
fc4a8ea6da8e-0 | Source code for langchain.vectorstores.starrocks
"""Wrapper around open source StarRocks VectorSearch capability."""
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
from pydantic import Base... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fc4a8ea6da8e-1 | r = {}
for idx, datum in enumerate(value):
k = columns[idx][0]
r[k] = datum
result.append(r)
debug_output(result)
cursor.close()
return result
[docs]class StarRocksSettings(BaseSettings):
"""StarRocks Client Configuration
Attribute:
StarRocks_host (str... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fc4a8ea6da8e-2 | "metadata": "metadata",
}
database: str = "default"
table: str = "langchain"
def __getitem__(self, item: str) -> Any:
return getattr(self, item)
class Config:
env_file = ".env"
env_prefix = "starrocks_"
env_file_encoding = "utf-8"
[docs]class StarRocks(VectorStore):
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fc4a8ea6da8e-3 | except ImportError:
# Just in case if tqdm is not installed
self.pgbar = lambda x, **kwargs: x
super().__init__()
if config is not None:
self.config = config
else:
self.config = StarRocksSettings()
assert self.config
assert self.con... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fc4a8ea6da8e-4 | [docs] def escape_str(self, value: str) -> str:
return "".join(f"{self.BS}{c}" if c in self.must_escape else c for c in value)
@property
def embeddings(self) -> Embeddings:
return self.embedding_function
def _build_insert_sql(self, transac: Iterable, column_names: Iterable[str]) -> str:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fc4a8ea6da8e-5 | """Insert more texts through the embeddings and add to the VectorStore.
Args:
texts: Iterable of strings to add to the VectorStore.
ids: Optional list of ids to associate with the texts.
batch_size: Batch size of insertion
metadata: Optional column data to be inse... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fc4a8ea6da8e-6 | if t:
t.join()
self._insert(transac, keys)
return [i for i in ids]
except Exception as e:
logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m")
return []
[docs] @classmethod
def from_texts(
cls,
tex... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fc4a8ea6da8e-7 | """Text representation for StarRocks Vector Store, prints backends, username
and schemas. Easy to use with `str(StarRocks())`
Returns:
repr: string to show connection info and data schema
"""
_repr = f"\033[92m\033[1m{self.config.database}.{self.config.table} @ "
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fc4a8ea6da8e-8 | return _repr
def _build_query_sql(
self, q_emb: List[float], topk: int, where_str: Optional[str] = None
) -> str:
q_emb_str = ",".join(map(str, q_emb))
if where_str:
where_str = f"WHERE {where_str}"
else:
where_str = ""
q_str = f"""
SEL... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fc4a8ea6da8e-9 | """
return self.similarity_search_by_vector(
self.embedding_function.embed_query(query), k, where_str, **kwargs
)
[docs] def similarity_search_by_vector(
self,
embedding: List[float],
k: int = 4,
where_str: Optional[str] = None,
**kwargs: Any,
)... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fc4a8ea6da8e-10 | return []
[docs] def similarity_search_with_relevance_scores(
self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any
) -> List[Tuple[Document, float]]:
"""Perform a similarity search with StarRocks
Args:
query (str): query string
k (int, optio... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fc4a8ea6da8e-11 | f"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}",
)
@property
def metadata_column(self) -> str:
return self.config.column_map["metadata"] | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
7a8e146b1c0f-0 | Source code for langchain.vectorstores.vectara
"""Wrapper around Vectara vector database."""
from __future__ import annotations
import json
import logging
import os
from hashlib import md5
from typing import Any, Iterable, List, Optional, Tuple, Type
import requests
from pydantic import Field
from langchain.embeddings.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
7a8e146b1c0f-1 | or self._vectara_corpus_id is None
or self._vectara_api_key is None
):
logger.warning(
"Can't find Vectara credentials, customer_id or corpus_id in "
"environment."
)
else:
logger.debug(f"Using corpus id {self._vectara_corpu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
7a8e146b1c0f-2 | headers=self._get_post_headers(),
timeout=self.vectara_api_timeout,
)
if response.status_code != 200:
logger.error(
f"Delete request failed for doc_id = {doc_id} with status code "
f"{response.status_code}, reason {response.reason}, text "
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
7a8e146b1c0f-3 | pre-processing and chunking occurs internally in an optimal way
This method provides a way to use that API in LangChain
Args:
files_list: Iterable of strings, each representing a local file path.
Files could be text, HTML, PDF, markdown, doc/docx, ppt/pptx, etc.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
7a8e146b1c0f-4 | doc_ids.append(doc_id)
else:
logger.info(f"Error indexing file {file}: {response.json()}")
return doc_ids
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
doc_metadata: Optional[dict] = None,
**kwargs... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
7a8e146b1c0f-5 | ],
}
success_str = self._index_doc(doc)
if success_str == "E_ALREADY_EXISTS":
self._delete_doc(doc_id)
self._index_doc(doc)
elif success_str == "E_NO_PERMISSIONS":
print(
"""No permissions to add document to Vectara.
Ch... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
7a8e146b1c0f-6 | "num_results": k,
"context_config": {
"sentences_before": n_sentence_context,
"sentences_after": n_sentence_context,
},
"corpus_key": [
{
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
7a8e146b1c0f-7 | filter: Optional[str] = None,
n_sentence_context: int = 0,
**kwargs: Any,
) -> List[Document]:
"""Return Vectara documents most similar to query, along with scores.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
7a8e146b1c0f-8 | vectara_corpus_id=corpus_id,
vectara_api_key=api_key,
)
"""
# Note: Vectara generates its own embeddings, so we ignore the provided
# embeddings (required by interface)
doc_metadata = kwargs.pop("doc_metadata", {})
vectara = cls(**kwargs)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
7a8e146b1c0f-9 | return VectaraRetriever(vectorstore=self, **kwargs, tags=tags)
[docs]class VectaraRetriever(VectorStoreRetriever):
"""Retriever class for Vectara."""
vectorstore: Vectara
"""Vectara vectorstore."""
search_kwargs: dict = Field(
default_factory=lambda: {
"lambda_val": 0.025,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
6115aae89bfd-0 | Source code for langchain.vectorstores.opensearch_vector_search
"""Wrapper around OpenSearch vector database."""
from __future__ import annotations
import uuid
import warnings
from typing import Any, Dict, Iterable, List, Optional, Tuple
import numpy as np
from langchain.embeddings.base import Embeddings
from langchain... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-1 | """Get OpenSearch client from the opensearch_url, otherwise raise error."""
try:
opensearch = _import_opensearch()
client = opensearch(opensearch_url, **kwargs)
except ValueError as e:
raise ValueError(
f"OpenSearch client string provided is not in proper format. "
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-2 | index_name: str,
embeddings: List[List[float]],
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
vector_field: str = "vector_field",
text_field: str = "text",
mapping: Optional[Dict] = None,
max_chunk_bytes: Optional[int] = 1 * 1024 * 1024,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-3 | return return_ids
def _default_scripting_text_mapping(
dim: int,
vector_field: str = "vector_field",
) -> Dict:
"""For Painless Scripting or Script Scoring,the default mapping to create index."""
return {
"mappings": {
"properties": {
vector_field: {"type": "knn_vecto... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-4 | return {
"size": k,
"query": {"knn": {vector_field: {"vector": query_vector, "k": k}}},
}
def _approximate_search_query_with_boolean_filter(
query_vector: List[float],
boolean_filter: Dict,
k: int = 4,
vector_field: str = "vector_field",
subquery_clause: str = "must",
) -> Dict:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-5 | if not pre_filter:
pre_filter = MATCH_ALL_QUERY
return {
"size": k,
"query": {
"script_score": {
"query": pre_filter,
"script": {
"source": "knn_score",
"lang": "knn",
"params": {
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-6 | "script": {
"source": source,
"params": {
"field": vector_field,
"query_value": query_vector,
},
},
}
},
}
def _get_kwargs_value(kwargs: Any, key: str, default_value: Any) ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-7 | bulk_size: int = 500,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
ids: Opti... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-8 | mapping = _default_text_mapping(
dim, engine, space_type, ef_search, ef_construction, m, vector_field
)
return _bulk_ingest_embeddings(
self.client,
self.index_name,
embeddings,
texts,
metadatas=metadatas,
ids=ids,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-9 | subquery_clause: Query clause on the knn vector field; default: "must"
lucene_filter: the Lucene algorithm decides whether to perform an exact
k-NN search with pre-filtering or an approximate search with modified
post-filtering. (deprecated, use `efficient_filter`)
effici... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-10 | By default, supports Approximate Search.
Also supports Script Scoring and Painless Scripting.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
Returns:
List of Documents along with its scores most similar to t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-11 | """
embedding = self.embedding_function.embed_query(query)
search_type = _get_kwargs_value(kwargs, "search_type", "approximate_search")
vector_field = _get_kwargs_value(kwargs, "vector_field", "vector_field")
if (
self.is_aoss
and search_type != "approximate_searc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-12 | embedding,
boolean_filter,
k=k,
vector_field=vector_field,
subquery_clause=subquery_clause,
)
elif efficient_filter != {}:
search_query = _approximate_search_query_with_efficient_filter(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-13 | return [hit for hit in response["hits"]["hits"]]
[docs] def max_marginal_relevance_search(
self,
query: str,
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> list[Document]:
"""Return docs selected using the maximal marginal rele... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-14 | mmr_selected = maximal_marginal_relevance(
np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult
)
return [
Document(
page_content=results[i]["_source"][text_field],
metadata=results[i]["_source"][metadata_field],
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-15 | space_type: "l2", "l1", "cosinesimil", "linf", "innerproduct"; default: "l2"
ef_search: Size of the dynamic list used during k-NN searches. Higher values
lead to more accurate but slower searches; default: 512
ef_construction: Size of the dynamic list used during k-NN graph creation.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-16 | )
is_appx_search = _get_kwargs_value(kwargs, "is_appx_search", True)
vector_field = _get_kwargs_value(kwargs, "vector_field", "vector_field")
text_field = _get_kwargs_value(kwargs, "text_field", "text")
max_chunk_bytes = _get_kwargs_value(kwargs, "max_chunk_bytes", 1 * 1024 * 1024)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6115aae89bfd-17 | embeddings,
texts,
metadatas=metadatas,
vector_field=vector_field,
text_field=text_field,
mapping=mapping,
max_chunk_bytes=max_chunk_bytes,
is_aoss=is_aoss,
)
return cls(opensearch_url, index_name, embedding, **kwargs) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
a6c34110f9a0-0 | Source code for langchain.vectorstores.base
"""Interface for vector stores."""
from __future__ import annotations
import asyncio
import logging
import math
import warnings
from abc import ABC, abstractmethod
from functools import partial
from typing import (
Any,
Callable,
ClassVar,
Collection,
Dict... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
a6c34110f9a0-1 | )
return None
[docs] def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:
"""Delete by vector ID or other criteria.
Args:
ids: List of ids to delete.
**kwargs: Other keyword arguments that subclasses might use.
Returns:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
a6c34110f9a0-2 | documents (List[Document]: Documents to add to the vectorstore.
Returns:
List[str]: List of IDs of the added texts.
"""
texts = [doc.page_content for doc in documents]
metadatas = [doc.metadata for doc in documents]
return await self.aadd_texts(texts, metadatas, **kwa... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
a6c34110f9a0-3 | self, query: str, k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query."""
@staticmethod
def _euclidean_relevance_score_fn(distance: float) -> float:
"""Return a similarity score on a scale [0, 1]."""
# The 'correct' relevance function
# may dif... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
a6c34110f9a0-4 | - the distance / similarity metric used by the VectorStore
- the scale of your embeddings (OpenAI's are unit normed. Many others are not!)
- embedding dimensionality
- etc.
Vectorstores should define their own selection based method of relevance.
"""
raise NotImplementedE... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
a6c34110f9a0-5 | k: int = 4,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs and relevance scores in the range [0, 1].
0 is dissimilar, 1 is most similar.
Args:
query: input text
k: Number of Documents to return. Defaults to 4.
**kwargs: kwargs to ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
a6c34110f9a0-6 | self, query: str, k: int = 4, **kwargs: Any
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query."""
# This is a temporary workaround to make the similarity search
# asynchronous. The proper solution is to make the similarity search
# asynchronous in the vector sto... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
a6c34110f9a0-7 | ) -> List[Document]:
"""Return docs most similar to embedding vector."""
# This is a temporary workaround to make the similarity search
# asynchronous. The proper solution is to make the similarity search
# asynchronous in the vector store implementations.
func = partial(self.sim... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
a6c34110f9a0-8 | ) -> List[Document]:
"""Return docs selected using the maximal marginal relevance."""
# This is a temporary workaround to make the similarity search
# asynchronous. The proper solution is to make the similarity search
# asynchronous in the vector store implementations.
func = par... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
a6c34110f9a0-9 | k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance."""
raise NotImplementedError
[docs] @classmethod
def from_documents(
cls: Type[VST],
documents: Li... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
a6c34110f9a0-10 | cls: Type[VST],
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> VST:
"""Return VectorStore initialized from texts and embeddings."""
raise NotImplementedError
def _get_retriever_tags(self) -> List[str]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
a6c34110f9a0-11 | docsearch.as_retriever(
search_type="mmr",
search_kwargs={'k': 6, 'lambda_mult': 0.25}
)
# Fetch more documents for the MMR algorithm to consider
# But only return the top 5
docsearch.as_retriever(
search_type="mmr",
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
a6c34110f9a0-12 | "similarity",
"similarity_score_threshold",
"mmr",
)
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
@root_validator()
def validate_search_type(cls, values: Dict) -> Dict:
"""Validate search type."""
search_type =... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
a6c34110f9a0-13 | query, **self.search_kwargs
)
else:
raise ValueError(f"search_type of {self.search_type} not allowed.")
return docs
async def _aget_relevant_documents(
self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun
) -> List[Document]:
if self.searc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
983a7e2a71b8-0 | Source code for langchain.vectorstores.typesense
"""Wrapper around Typesense vector search"""
from __future__ import annotations
import uuid
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
fro... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
983a7e2a71b8-1 | typesense_client: Client,
embedding: Embeddings,
*,
typesense_collection_name: Optional[str] = None,
text_key: str = "text",
):
"""Initialize with Typesense client."""
try:
from typesense import Client
except ImportError:
raise ValueErr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
983a7e2a71b8-2 | for _id, vec, text, metadata in zip(_ids, embedded_texts, texts, _metadatas)
]
def _create_collection(self, num_dim: int) -> None:
fields = [
{"name": "vec", "type": "float[]", "num_dim": num_dim},
{"name": f"{self._text_key}", "type": "string"},
{"name": ".*", "t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
983a7e2a71b8-3 | return [doc["id"] for doc in docs]
[docs] def similarity_search_with_score(
self,
query: str,
k: int = 10,
filter: Optional[str] = "",
) -> List[Tuple[Document, float]]:
"""Return typesense documents most similar to query, along with scores.
Args:
query... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
983a7e2a71b8-4 | ) -> List[Document]:
"""Return typesense documents most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 10.
Minimum 10 results would be returned.
filter: typesense filter_by expression ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
983a7e2a71b8-5 | "Please install it with `pip install typesense`."
)
node = {
"host": host,
"port": str(port),
"protocol": protocol,
}
typesense_api_key = typesense_api_key or get_from_env(
"typesense_api_key", "TYPESENSE_API_KEY"
)
clie... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
a42cfa39495e-0 | Source code for langchain.vectorstores.faiss
"""Wrapper around FAISS vector database."""
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, Tuple
import numpy as np
from langcha... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
a42cfa39495e-1 | )
return faiss
[docs]class FAISS(VectorStore):
"""Wrapper around FAISS vector database.
To use, you should have the ``faiss`` python package installed.
Example:
.. code-block:: python
from langchain import FAISS
faiss = FAISS(embedding_function, index, docstore, index_to_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
a42cfa39495e-2 | metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
if not isinstance(self.docstore, AddableMixin):
raise ValueError(
"If trying to add texts, the underlying docstore should support "
f"adding ite... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
a42cfa39495e-3 | metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**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... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
a42cfa39495e-4 | if not isinstance(self.docstore, AddableMixin):
raise ValueError(
"If trying to add texts, the underlying docstore should support "
f"adding items, which {self.docstore} does not"
)
# Embed and create the documents.
texts, embeddings = zip(*text_em... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
a42cfa39495e-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 |
a42cfa39495e-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 |
a42cfa39495e-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 |
a42cfa39495e-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 |
a42cfa39495e-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 |
a42cfa39495e-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 |
a42cfa39495e-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 |
a42cfa39495e-12 | starting_len = len(self.index_to_docstore_id)
# Merge two IndexFlatL2
self.index.merge_from(target.index)
# Get id and docs from target FAISS object
full_info = []
for i, target_id in target.index_to_docstore_id.items():
doc = target.docstore.search(target_id)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
a42cfa39495e-13 | if normalize_L2 and distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE:
faiss.normalize_L2(vector)
index.add(vector)
documents = []
if ids is None:
ids = [str(uuid.uuid4()) for _ in texts]
for i, text in enumerate(texts):
metadata = metadatas[i] ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
a42cfa39495e-14 | embeddings = OpenAIEmbeddings()
faiss = FAISS.from_texts(texts, embeddings)
"""
embeddings = embedding.embed_documents(texts)
return cls.__from(
texts,
embeddings,
embedding,
metadatas=metadatas,
ids=ids,
**k... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
a42cfa39495e-15 | ids=ids,
**kwargs,
)
[docs] def save_local(self, folder_path: str, index_name: str = "index") -> None:
"""Save FAISS index, docstore, and index_to_docstore_id to disk.
Args:
folder_path: folder path to save index, docstore,
and index_to_docstore_id to.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
a42cfa39495e-16 | faiss = dependable_faiss_import()
index = faiss.read_index(
str(path / "{index_name}.faiss".format(index_name=index_name))
)
# load docstore and index_to_docstore_id
with open(path / "{index_name}.pkl".format(index_name=index_name), "rb") as f:
docstore, index_to_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
a42cfa39495e-17 | return self.override_relevance_score_fn
# Default strategy is to rely on distance strategy provided in
# vectorstore constructor
if self.distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:
return self._max_inner_product_relevance_score_fn
elif self.distance_strategy == D... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
9f961c2b8419-0 | Source code for langchain.vectorstores.pgvector
"""VectorStore wrapper around a Postgres/PGVector database."""
from __future__ import annotations
import enum
import logging
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
)
i... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
9f961c2b8419-1 | collection_name: The name of the collection to use. (default: langchain)
NOTE: This is not the name of the table, but the name of the collection.
The tables will be created when initializing the store (if not exists)
So, make sure the user has the right permissions to create tables.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
9f961c2b8419-2 | self.collection_metadata = collection_metadata
self._distance_strategy = distance_strategy
self.pre_delete_collection = pre_delete_collection
self.logger = logger or logging.getLogger(__name__)
self.override_relevance_score_fn = relevance_score_fn
self.__post_init__()
def __p... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
9f961c2b8419-3 | self.delete_collection()
with Session(self._conn) as session:
self.CollectionStore.get_or_create(
session, self.collection_name, cmetadata=self.collection_metadata
)
[docs] def delete_collection(self) -> None:
self.logger.debug("Trying to delete collection")
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
9f961c2b8419-4 | **kwargs,
)
store.add_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[dict]]... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
9f961c2b8419-5 | ids: Optional[List[str]] = None,
**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.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
9f961c2b8419-6 | """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.
Returns:
List of Documents most similar to th... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
9f961c2b8419-7 | for key, value in filter.items():
IN = "in"
if isinstance(value, dict) and IN in map(str.lower, value):
value_case_insensitive = {
k.lower(): v for k, v in value.items()
}
filter_b... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
9f961c2b8419-8 | ) -> 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 (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
Returns:... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
9f961c2b8419-9 | )
[docs] @classmethod
def from_embeddings(
cls,
text_embeddings: List[Tuple[str, List[float]]],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
distance_strategy: DistanceStrategy = DEFAULT_D... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
9f961c2b8419-10 | cls: Type[PGVector],
embedding: Embeddings,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,
pre_delete_collection: bool = False,
**kwargs: Any,
) -> PGVector:
"""
Get intsance of an ex... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
9f961c2b8419-11 | """
Return VectorStore initialized from documents and embeddings.
Postgres connection string is required
"Either pass it as a parameter
or set the PGVECTOR_CONNECTION_STRING environment variable.
"""
texts = [d.page_content for d in documents]
metadatas = [d.metad... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
9f961c2b8419-12 | # Default strategy is to rely on distance strategy provided
# in vectorstore constructor
if self._distance_strategy == DistanceStrategy.COSINE:
return self._cosine_relevance_score_fn
elif self._distance_strategy == DistanceStrategy.EUCLIDEAN:
return self._euclidean_releva... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.