id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 53 121 |
|---|---|---|
e4e5434bc9d7-2 | Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
search_k: inspect up to search_k nodes which defaults
to n_trees * n if not provided
Returns:
List of Documents most similar to the query and score ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
e4e5434bc9d7-3 | k: Number of Documents to return. Defaults to 4.
search_k: inspect up to search_k nodes which defaults
to n_trees * n if not provided
Returns:
List of Documents most similar to the query and score for each
"""
embedding = self.embedding_function(query)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
e4e5434bc9d7-4 | Returns:
List of Documents most similar to the embedding.
"""
docs_and_scores = self.similarity_search_with_score_by_index(
docstore_index, k, search_k
)
return [doc for doc, _ in docs_and_scores]
[docs] def similarity_search(
self, query: str, k: int =... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
e4e5434bc9d7-5 | of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
Returns:
List of Documents selected by maximal marginal relevance.
"""
idxs = self.index.get_nns_by_vector(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
e4e5434bc9d7-6 | k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
e4e5434bc9d7-7 | documents = []
for i, text in enumerate(texts):
metadata = metadatas[i] if metadatas else {}
documents.append(Document(page_content=text, metadata=metadata))
index_to_id = {i: str(uuid.uuid4()) for i in range(len(documents))}
docstore = InMemoryDocstore(
{inde... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
e4e5434bc9d7-8 | from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
index = Annoy.from_texts(texts, embeddings)
"""
embeddings = embedding.embed_documents(texts)
return cls.__from(
texts, embeddings, embedding, metadatas, metric, trees, n... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
e4e5434bc9d7-9 | text_embedding_pairs = list(zip(texts, text_embeddings))
db = Annoy.from_embeddings(text_embedding_pairs, embeddings)
"""
texts = [t[0] for t in text_embeddings]
embeddings = [t[1] for t in text_embeddings]
return cls.__from(
texts, embeddings, embedding, meta... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
e4e5434bc9d7-10 | Args:
folder_path: folder path to load index, docstore,
and index_to_docstore_id from.
embeddings: Embeddings to use when generating queries.
"""
path = Path(folder_path)
# load index separately since it is not picklable
annoy = dependable_annoy_im... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
7b5b99f2bfe5-0 | Source code for langchain.vectorstores.mongodb_atlas
from __future__ import annotations
import logging
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generator,
Iterable,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from langchain.docstore.document import Document
from langchain.embe... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
7b5b99f2bfe5-1 | """
Args:
collection: MongoDB collection to add the texts to.
embedding: Text embedding model to use.
text_key: MongoDB field that will contain the text for each
document.
embedding_key: MongoDB field that will contain the embedding for
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
7b5b99f2bfe5-2 | """
batch_size = kwargs.get("batch_size", DEFAULT_INSERT_BATCH_SIZE)
_metadatas: Union[List, Generator] = metadatas or ({} for _ in texts)
texts_batch = []
metadatas_batch = []
result_ids = []
for i, (text, metadata) in enumerate(zip(texts, _metadatas)):
texts... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
7b5b99f2bfe5-3 | """Return MongoDB documents most similar to query, along with scores.
Use the knnBeta Operator available in MongoDB Atlas Search
This feature is in early access and available only for evaluation purposes, to
validate functionality, and to gather feedback from a small closed group of
earl... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
7b5b99f2bfe5-4 | docs.append((Document(page_content=text, metadata=res), score))
return docs
[docs] def similarity_search(
self,
query: str,
k: int = 4,
pre_filter: Optional[dict] = None,
post_filter_pipeline: Optional[List[Dict]] = None,
**kwargs: Any,
) -> List[Document]:... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
7b5b99f2bfe5-5 | collection: Optional[Collection[MongoDBDocumentType]] = None,
**kwargs: Any,
) -> MongoDBAtlasVectorSearch:
"""Construct MongoDBAtlasVectorSearch wrapper from raw documents.
This is a user-friendly interface that:
1. Embeds documents.
2. Adds the documents to a provid... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
f084adf76b42-0 | Source code for langchain.vectorstores.tair
"""Wrapper around Tair Vector."""
from __future__ import annotations
import json
import logging
import uuid
from typing import Any, Iterable, List, Optional, Type
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
f084adf76b42-1 | index_type: str,
data_type: str,
**kwargs: Any,
) -> bool:
index = self.client.tvs_get_index(self.index_name)
if index is not None:
logger.info("Index already exists")
return False
self.client.tvs_create_index(
self.index_name,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
f084adf76b42-2 | """
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/tair.html |
f084adf76b42-3 | if "tair_url" in kwargs:
kwargs.pop("tair_url")
distance_type = tairvector.DistanceMetric.InnerProduct
if "distance_type" in kwargs:
distance_type = kwargs.pop("distance_typ")
index_type = tairvector.IndexType.HNSW
if "index_type" in kwargs:
index_type... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
f084adf76b42-4 | cls,
documents: List[Document],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
index_name: str = "langchain",
content_key: str = "content",
metadata_key: str = "metadata",
**kwargs: Any,
) -> Tair:
texts = [d.page_content for d in docum... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
f084adf76b42-5 | # index not exist
logger.info("Index does not exist")
return False
return True
[docs] @classmethod
def from_existing_index(
cls,
embedding: Embeddings,
index_name: str = "langchain",
content_key: str = "content",
metadata_key: str = "metadat... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
4e008ca515ab-0 | Source code for langchain.vectorstores.lancedb
"""Wrapper around LanceDB vector database"""
from __future__ import annotations
import uuid
from typing import Any, Iterable, List, Optional
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.base i... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
4e008ca515ab-1 | self._id_key = id_key
self._text_key = text_key
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Turn texts into embedding and add it to the database... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
4e008ca515ab-2 | """
embedding = self._embedding.embed_query(query)
docs = self._connection.search(embedding).limit(k).to_df()
return [
Document(
page_content=row[self._text_key],
metadata=row[docs.columns != self._text_key],
)
for _, row in doc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
90fc2f1b7340-0 | Source code for langchain.vectorstores.hologres
"""VectorStore wrapper around a Hologres database."""
from __future__ import annotations
import json
import logging
import uuid
from typing import Any, Dict, Iterable, List, Optional, Tuple, Type
from langchain.docstore.document import Document
from langchain.embeddings.b... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
90fc2f1b7340-1 | '{"embedding":{"algorithm":"Graph",
"distance_method":"SquaredEuclidean",
"build_params":{"min_flush_proxima_row_count" : 1,
"min_compaction_proxima_row_count" : 1,
"max_total_size_to_merge_mb" : 2000}}}');"""
)
self.conn.commit()
def get_by_id(self, id: str) -> List[Tuple]:
statement = (
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
90fc2f1b7340-2 | params.append(key)
params.append(val)
filter_clause = "where " + " and ".join(conjuncts)
sql = (
f"select document, metadata::text, "
f"pm_approx_squared_euclidean_distance(array{json.dumps(embedding)}"
f"::float4[], embedding) as distance from"
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
90fc2f1b7340-3 | self.connection_string = connection_string
self.ndims = ndims
self.table_name = table_name
self.embedding_function = embedding_function
self.pre_delete_table = pre_delete_table
self.logger = logger or logging.getLogger(__name__)
self.__post_init__()
def __post_init__(... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
90fc2f1b7340-4 | embedding_function=embedding_function,
ndims=ndims,
table_name=table_name,
pre_delete_table=pre_delete_table,
)
store.add_embeddings(
texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs
)
return store
[docs] def ad... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
90fc2f1b7340-5 | List of ids from adding the texts into the vectorstore.
"""
if ids is None:
ids = [str(uuid.uuid1()) for _ in texts]
embeddings = self.embedding_function.embed_documents(list(texts))
if not metadatas:
metadatas = [{} for _ in texts]
self.add_embeddings(tex... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
90fc2f1b7340-6 | Returns:
List of Documents most similar to the query vector.
"""
docs_and_scores = self.similarity_search_with_score_by_vector(
embedding=embedding, k=k, filter=filter
)
return [doc for doc, _ in docs_and_scores]
[docs] def similarity_search_with_score(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
90fc2f1b7340-7 | ]
return docs
[docs] @classmethod
def from_texts(
cls: Type[Hologres],
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
ndims: int = ADA_TOKEN_COUNT,
table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME,
ids: Optional[List... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
90fc2f1b7340-8 | Return VectorStore initialized from documents and embeddings.
Postgres connection string is required
"Either pass it as a parameter
or set the HOLOGRES_CONNECTION_STRING environment variable.
Example:
.. code-block:: python
from langchain import Hologres
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
90fc2f1b7340-9 | embedding_function=embedding,
pre_delete_table=pre_delete_table,
)
return store
[docs] @classmethod
def get_connection_string(cls, kwargs: Dict[str, Any]) -> str:
connection_string: str = get_from_dict_or_env(
data=kwargs,
key="connection_string",
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
90fc2f1b7340-10 | ndims=ndims,
table_name=table_name,
**kwargs,
)
[docs] @classmethod
def connection_string_from_db_params(
cls,
host: str,
port: int,
database: str,
user: str,
password: str,
) -> str:
"""Return connection string from data... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
1e6d615e6aba-0 | Source code for langchain.vectorstores.azuresearch
"""Wrapper around Azure Cognitive Search."""
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,
)
im... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
1e6d615e6aba-1 | from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import ResourceNotFoundError
from azure.identity import DefaultAzureCredential
from azure.search.documents import SearchClient
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.ind... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
1e6d615e6aba-2 | algorithm_configurations=[
VectorSearchAlgorithmConfiguration(
name="default",
kind="hnsw",
hnsw_parameters={
"m": 4,
"efConstruction": 400,
"efSearch": 500,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
1e6d615e6aba-3 | azure_search_endpoint,
azure_search_key,
index_name,
embedding_function,
semantic_configuration_name,
)
self.search_type = search_type
self.semantic_configuration_name = semantic_configuration_name
self.semantic_query_language = semantic_qu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
1e6d615e6aba-4 | 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 |
1e6d615e6aba-5 | query, k=k, filters=kwargs.get("filters", None)
)
return [doc for doc, _ in docs_and_scores]
[docs] def vector_search_with_score(
self, query: str, k: int = 4, filters: Optional[str] = None
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query.
Args:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
1e6d615e6aba-6 | Returns:
List[Document]: A list of documents that are most similar to the query text.
"""
docs_and_scores = self.hybrid_search_with_score(
query, k=k, filters=kwargs.get("filters", None)
)
return [doc for doc, _ in docs_and_scores]
[docs] def hybrid_search_with... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
1e6d615e6aba-7 | ) -> List[Document]:
"""
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 d... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
1e6d615e6aba-8 | query_answer="extractive",
top=k,
)
# Get Semantic Answers
semantic_answers = results.get_answers()
semantic_answers_dict = {}
for semantic_answer in semantic_answers:
semantic_answers_dict[semantic_answer.key] = {
"text": semantic_answer.t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
1e6d615e6aba-9 | azure_search_key,
index_name,
embedding.embed_query,
)
azure_search.add_texts(texts, metadatas, **kwargs)
return azure_search
class AzureSearchVectorStoreRetriever(BaseRetriever, BaseModel):
vectorstore: AzureSearch
search_type: str = "hybrid"
k: int = 4
c... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
0a8fd0f65e70-0 | Source code for langchain.vectorstores.base
"""Interface for vector stores."""
from __future__ import annotations
import asyncio
import warnings
from abc import ABC, abstractmethod
from functools import partial
from typing import (
Any,
ClassVar,
Collection,
Dict,
Iterable,
List,
Optional,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
0a8fd0f65e70-1 | )
[docs] async def aadd_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore."""
raise NotImplementedError
[docs] def add_documents(self, doc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
0a8fd0f65e70-2 | if search_type == "similarity":
return self.similarity_search(query, **kwargs)
elif search_type == "mmr":
return self.max_marginal_relevance_search(query, **kwargs)
else:
raise ValueError(
f"search_type of {search_type} not allowed. Expected "
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
0a8fd0f65e70-3 | k: Number of Documents to return. Defaults to 4.
**kwargs: kwargs to be passed to similarity search. Should include:
score_threshold: Optional, a floating point value between 0 to 1 to
filter the resulting set of retrieved docs
Returns:
List of Tuples ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
0a8fd0f65e70-4 | raise NotImplementedError
[docs] async def asimilarity_search_with_relevance_scores(
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
# asynchronou... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
0a8fd0f65e70-5 | self, embedding: List[float], k: int = 4, **kwargs: Any
) -> 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 v... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
0a8fd0f65e70-6 | lambda_mult: float = 0.5,
**kwargs: Any,
) -> 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... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
0a8fd0f65e70-7 | 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 |
0a8fd0f65e70-8 | 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
[docs] def as_retriever(self, **kwargs: Any) -> Vecto... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
0a8fd0f65e70-9 | def get_relevant_documents(self, query: str) -> List[Document]:
if self.search_type == "similarity":
docs = self.vectorstore.similarity_search(query, **self.search_kwargs)
elif self.search_type == "similarity_score_threshold":
docs_and_similarities = (
self.vector... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
0a8fd0f65e70-10 | """Add documents to vectorstore."""
return self.vectorstore.add_documents(documents, **kwargs)
async def aadd_documents(
self, documents: List[Document], **kwargs: Any
) -> List[str]:
"""Add documents to vectorstore."""
return await self.vectorstore.aadd_documents(documents, **kw... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
f043c01c49f2-0 | Source code for langchain.vectorstores.singlestoredb
"""Wrapper around SingleStore DB."""
from __future__ import annotations
import enum
import json
from typing import (
Any,
ClassVar,
Collection,
Iterable,
List,
Optional,
Tuple,
Type,
)
from sqlalchemy.pool import QueuePool
from langcha... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f043c01c49f2-1 | def __init__(
self,
embedding: Embeddings,
*,
distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,
table_name: str = "embeddings",
content_field: str = "content",
metadata_field: str = "metadata",
vector_field: str = "vector",
pool_size... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f043c01c49f2-2 | max_overflow (int, optional): Determines the maximum number of connections
allowed beyond the pool_size. Defaults to 10.
timeout (float, optional): Specifies the maximum wait time in seconds for
establishing a connection. Defaults to 30.
Following arguments pertai... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f043c01c49f2-3 | conv (dict[int, Callable], optional): A dictionary of data conversion
functions.
credential_type (str, optional): Specifies the type of authentication to
use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.
autocommit (bool, optional): Enables autocommits.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f043c01c49f2-4 | vectorstore = SingleStoreDB(OpenAIEmbeddings())
"""
self.embedding = embedding
self.distance_strategy = distance_strategy
self.table_name = table_name
self.content_field = content_field
self.metadata_field = metadata_field
self.vector_field = vector_field
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f043c01c49f2-5 | finally:
cur.close()
finally:
conn.close()
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
embeddings: Optional[List[List[float]]] = None,
**kwargs: Any,
) -> List[str]:
"""Add more texts... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f043c01c49f2-6 | ) -> List[Document]:
"""Returns the most similar indexed documents to the query text.
Uses cosine similarity.
Args:
query (str): The query text for which to find similar documents.
k (int): The number of documents to return. Default is 4.
filter (dict): A dict... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f043c01c49f2-7 | # Creates embedding vector from user query
embedding = self.embedding.embed_query(query)
conn = self.connection_pool.connect()
result = []
where_clause: str = ""
where_clause_values: List[Any] = []
if filter:
where_clause = "WHERE "
arguments = []
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f043c01c49f2-8 | + (k,),
)
for row in cur.fetchall():
doc = Document(page_content=row[0], metadata=row[1])
result.append((doc, float(row[2])))
finally:
cur.close()
finally:
conn.close()
return result
[docs] ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
f043c01c49f2-9 | embedding,
distance_strategy=distance_strategy,
table_name=table_name,
content_field=content_field,
metadata_field=metadata_field,
vector_field=vector_field,
pool_size=pool_size,
max_overflow=max_overflow,
timeout=timeout,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
c74ef7671545-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 |
c74ef7671545-1 | or self._vectara_api_key is None
):
logging.warning(
"Cant find Vectara credentials, customer_id or corpus_id in "
"environment."
)
else:
logging.debug(f"Using corpus id {self._vectara_corpus_id}")
self._session = requests.Sessi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
c74ef7671545-2 | f"{response.status_code}, reason {response.reason}, text "
f"{response.text}"
)
return False
return True
def _index_doc(self, doc: dict) -> bool:
request: dict[str, Any] = {}
request["customer_id"] = self._vectara_customer_id
request["corpus_id... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
c74ef7671545-3 | metadatas = [{} for _ in texts]
doc = {
"document_id": doc_id,
"metadataJson": json.dumps({"source": "langchain"}),
"parts": [
{"text": text, "metadataJson": json.dumps(md)}
for text, md in zip(texts, metadatas)
],
}
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
c74ef7671545-4 | {
"query": [
{
"query": query,
"start": 0,
"num_results": k,
"context_config": {
"sentences_before": n_sentence_context,
"sentences_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
c74ef7671545-5 | self,
query: str,
k: int = 5,
lambda_val: float = 0.025,
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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
c74ef7671545-6 | Example:
.. code-block:: python
from langchain import Vectara
vectara = Vectara.from_texts(
texts,
vectara_customer_id=customer_id,
vectara_corpus_id=corpus_id,
vectara_api_key=api_key,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
c74ef7671545-7 | ) -> None:
"""Add text to the Vectara vectorstore.
Args:
texts (List[str]): The text
metadatas (List[dict]): Metadata dicts, must line up with existing store
"""
self.vectorstore.add_texts(texts, metadatas) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
2ba5e24e6c42-0 | Source code for langchain.vectorstores.elastic_vector_search
"""Wrapper around Elasticsearch vector database."""
from __future__ import annotations
import uuid
from abc import ABC
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterable,
List,
Mapping,
Optional,
Tuple,
Union,
)
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
2ba5e24e6c42-1 | # defined as an abstract base class itself, allowing the creation of subclasses with
# their own specific implementations. If you plan to subclass ElasticVectorSearch,
# you can inherit from it and define your own implementation of the necessary methods
# and attributes.
[docs]class ElasticVectorSearch(VectorStore, ABC... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
2ba5e24e6c42-2 | 4. Click "Reset password"
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 import ElasticVectorSearch
from langchain.embeddi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
2ba5e24e6c42-3 | self.index_name = index_name
_ssl_verify = ssl_verify or {}
try:
self.client = elasticsearch.Elasticsearch(elasticsearch_url, **_ssl_verify)
except ValueError as e:
raise ValueError(
f"Your elasticsearch client string is mis-formatted. Got error: {e} "
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
2ba5e24e6c42-4 | # just to save expensive steps for last
self.create_index(self.client, self.index_name, mapping)
for i, text in enumerate(texts):
metadata = metadatas[i] if metadatas else {}
request = {
"_op_type": "index",
"_index": self.index_name,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
2ba5e24e6c42-5 | Returns:
List of Documents most similar to the query.
"""
embedding = self.embedding.embed_query(query)
script_query = _default_script_query(embedding, filter)
response = self.client_search(
self.client, self.index_name, script_query, size=k
)
hits... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
2ba5e24e6c42-6 | elasticsearch_url="http://localhost:9200"
)
"""
elasticsearch_url = elasticsearch_url or get_from_env(
"elasticsearch_url", "ELASTICSEARCH_URL"
)
index_name = index_name or uuid.uuid4().hex
vectorsearch = cls(elasticsearch_url, index_name, embedding, *... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
2ba5e24e6c42-7 | # TODO: Check if this can be done in bulk
for id in ids:
self.client.delete(index=self.index_name, id=id)
class ElasticKnnSearch(ElasticVectorSearch):
"""
A class for performing k-Nearest Neighbors (k-NN) search on an Elasticsearch index.
The class is designed for a text search scenario ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
2ba5e24e6c42-8 | )
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 connection is provided, use it.
if es_connection is not None:
self.client = es_connection
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
2ba5e24e6c42-9 | "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_id` are provided, -> use query_vector_builder... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
2ba5e24e6c42-10 | search on the Elasticsearch index and returns the results.
Args:
query: The query or queries to be used for the search. Required if
`query_vector` is not provided.
k: The number of nearest neighbors to return. Defaults to 10.
query_vector: The query vector to ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
2ba5e24e6c42-11 | model_id: Optional[str] = None,
size: Optional[int] = 10,
source: Optional[bool] = True,
knn_boost: Optional[float] = 0.9,
query_boost: Optional[float] = 0.1,
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 |
2ba5e24e6c42-12 | included. Defaults to None.
vector_query_field: Field name to use in knn search if not default 'vector'
query_field: Field name to use in search if not default 'text'
Returns:
The search results.
Raises:
ValueError: If neither `query_vector` nor `model_id`... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
467dacdbe65a-0 | Source code for langchain.vectorstores.zilliz
from __future__ import annotations
import logging
from typing import Any, List, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.milvus import Milvus
logger = logging.getLogger(__name__)
[docs]class Zilliz(Milvus):
def _create_index(... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
467dacdbe65a-1 | "Failed to create an index on collection: %s", self.collection_name
)
raise e
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
collection_name: str = "LangChainCollecti... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
467dacdbe65a-2 | """
vector_db = cls(
embedding_function=embedding,
collection_name=collection_name,
connection_args=connection_args,
consistency_level=consistency_level,
index_params=index_params,
search_params=search_params,
drop_old=drop_old,... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
eedabc04c945-0 | Source code for langchain.vectorstores.chroma
"""Wrapper around ChromaDB embeddings platform."""
from __future__ import annotations
import logging
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 langc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
eedabc04c945-1 | embeddings = OpenAIEmbeddings()
vectorstore = Chroma("langchain_store", embeddings)
"""
_LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain"
def __init__(
self,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
embedding_function: Optional[Embeddings] = None,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
eedabc04c945-2 | @xor_args(("query_texts", "query_embeddings"))
def __query_collection(
self,
query_texts: Optional[List[str]] = None,
query_embeddings: Optional[List[List[float]]] = None,
n_results: int = 4,
where: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Documen... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
eedabc04c945-3 | ids = [str(uuid.uuid1()) for _ in texts]
embeddings = None
if self._embedding_function is not None:
embeddings = self._embedding_function.embed_documents(list(texts))
self._collection.upsert(
metadatas=metadatas, embeddings=embeddings, documents=texts, ids=ids
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
eedabc04c945-4 | Returns:
List of Documents most similar to the query vector.
"""
results = self.__query_collection(
query_embeddings=embedding, n_results=k, where=filter
)
return _results_to_docs(results)
[docs] def similarity_search_with_score(
self,
query: st... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
eedabc04c945-5 | return self.similarity_search_with_score(query, k, **kwargs)
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = DEFAULT_K,
fetch_k: int = 20,
lambda_mult: float = 0.5,
filter: Optional[Dict[str, str]] = None,
**kwargs: An... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
eedabc04c945-6 | lambda_mult=lambda_mult,
)
candidates = _results_to_docs(results)
selected_results = [r for i, r in enumerate(candidates) if i in mmr_selected]
return selected_results
[docs] def max_marginal_relevance_search(
self,
query: str,
k: int = DEFAULT_K,
fetch... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
eedabc04c945-7 | )
return docs
[docs] def delete_collection(self) -> None:
"""Delete the collection."""
self._client.delete_collection(self._collection.name)
[docs] def get(
self,
ids: Optional[OneOrMany[ID]] = None,
where: Optional[Where] = None,
limit: Optional[int] = None... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
eedabc04c945-8 | kwargs["include"] = include
return self._collection.get(**kwargs)
[docs] def persist(self) -> None:
"""Persist the collection.
This can be used to explicitly persist the data to disk.
It will also be called automatically when the object is destroyed.
"""
if self._persi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
eedabc04c945-9 | client: Optional[chromadb.Client] = None,
**kwargs: Any,
) -> Chroma:
"""Create a Chroma vectorstore from a raw documents.
If a persist_directory is specified, the collection will be persisted there.
Otherwise, the data will be ephemeral in-memory.
Args:
texts (Li... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.