id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 53 121 |
|---|---|---|
1f7b062637aa-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/stable/_modules/langchain/vectorstores/hologres.html |
1f7b062637aa-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/stable/_modules/langchain/vectorstores/hologres.html |
1f7b062637aa-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/stable/_modules/langchain/vectorstores/hologres.html |
3b43d401b136-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/stable/_modules/langchain/vectorstores/azuresearch.html |
3b43d401b136-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/stable/_modules/langchain/vectorstores/azuresearch.html |
3b43d401b136-2 | algorithm_configurations=[
VectorSearchAlgorithmConfiguration(
name="default",
kind="hnsw",
hnsw_parameters={
"m": 4,
"efConstruction": 400,
"efSearch": 500,
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/azuresearch.html |
3b43d401b136-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/stable/_modules/langchain/vectorstores/azuresearch.html |
3b43d401b136-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/stable/_modules/langchain/vectorstores/azuresearch.html |
3b43d401b136-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/stable/_modules/langchain/vectorstores/azuresearch.html |
3b43d401b136-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/stable/_modules/langchain/vectorstores/azuresearch.html |
3b43d401b136-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/stable/_modules/langchain/vectorstores/azuresearch.html |
3b43d401b136-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/stable/_modules/langchain/vectorstores/azuresearch.html |
3b43d401b136-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/stable/_modules/langchain/vectorstores/azuresearch.html |
e184309cf1eb-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/stable/_modules/langchain/vectorstores/base.html |
e184309cf1eb-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/stable/_modules/langchain/vectorstores/base.html |
e184309cf1eb-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/stable/_modules/langchain/vectorstores/base.html |
e184309cf1eb-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/stable/_modules/langchain/vectorstores/base.html |
e184309cf1eb-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/stable/_modules/langchain/vectorstores/base.html |
e184309cf1eb-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/stable/_modules/langchain/vectorstores/base.html |
e184309cf1eb-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/stable/_modules/langchain/vectorstores/base.html |
e184309cf1eb-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/stable/_modules/langchain/vectorstores/base.html |
e184309cf1eb-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/stable/_modules/langchain/vectorstores/base.html |
e184309cf1eb-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/stable/_modules/langchain/vectorstores/base.html |
e184309cf1eb-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/stable/_modules/langchain/vectorstores/base.html |
ca2097f82127-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/stable/_modules/langchain/vectorstores/singlestoredb.html |
ca2097f82127-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/stable/_modules/langchain/vectorstores/singlestoredb.html |
ca2097f82127-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/stable/_modules/langchain/vectorstores/singlestoredb.html |
ca2097f82127-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/stable/_modules/langchain/vectorstores/singlestoredb.html |
ca2097f82127-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/stable/_modules/langchain/vectorstores/singlestoredb.html |
ca2097f82127-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/stable/_modules/langchain/vectorstores/singlestoredb.html |
ca2097f82127-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/stable/_modules/langchain/vectorstores/singlestoredb.html |
ca2097f82127-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/stable/_modules/langchain/vectorstores/singlestoredb.html |
ca2097f82127-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/stable/_modules/langchain/vectorstores/singlestoredb.html |
ca2097f82127-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/stable/_modules/langchain/vectorstores/singlestoredb.html |
22ee2b57ec94-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/stable/_modules/langchain/vectorstores/vectara.html |
22ee2b57ec94-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/stable/_modules/langchain/vectorstores/vectara.html |
22ee2b57ec94-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/stable/_modules/langchain/vectorstores/vectara.html |
22ee2b57ec94-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/stable/_modules/langchain/vectorstores/vectara.html |
22ee2b57ec94-4 | {
"query": [
{
"query": query,
"start": 0,
"num_results": k,
"context_config": {
"sentences_before": n_sentence_context,
"sentences_... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/vectara.html |
22ee2b57ec94-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/stable/_modules/langchain/vectorstores/vectara.html |
22ee2b57ec94-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/stable/_modules/langchain/vectorstores/vectara.html |
22ee2b57ec94-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/stable/_modules/langchain/vectorstores/vectara.html |
7282acd08717-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/stable/_modules/langchain/vectorstores/elastic_vector_search.html |
7282acd08717-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/stable/_modules/langchain/vectorstores/elastic_vector_search.html |
7282acd08717-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/stable/_modules/langchain/vectorstores/elastic_vector_search.html |
7282acd08717-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/stable/_modules/langchain/vectorstores/elastic_vector_search.html |
7282acd08717-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/stable/_modules/langchain/vectorstores/elastic_vector_search.html |
7282acd08717-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/stable/_modules/langchain/vectorstores/elastic_vector_search.html |
7282acd08717-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/stable/_modules/langchain/vectorstores/elastic_vector_search.html |
7282acd08717-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/stable/_modules/langchain/vectorstores/elastic_vector_search.html |
7282acd08717-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/stable/_modules/langchain/vectorstores/elastic_vector_search.html |
7282acd08717-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/stable/_modules/langchain/vectorstores/elastic_vector_search.html |
7282acd08717-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/stable/_modules/langchain/vectorstores/elastic_vector_search.html |
7282acd08717-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/stable/_modules/langchain/vectorstores/elastic_vector_search.html |
7282acd08717-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/stable/_modules/langchain/vectorstores/elastic_vector_search.html |
f6676a6cf2f8-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/stable/_modules/langchain/vectorstores/zilliz.html |
f6676a6cf2f8-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/stable/_modules/langchain/vectorstores/zilliz.html |
f6676a6cf2f8-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/stable/_modules/langchain/vectorstores/zilliz.html |
cdc5db4a7c9d-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/stable/_modules/langchain/vectorstores/chroma.html |
cdc5db4a7c9d-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/stable/_modules/langchain/vectorstores/chroma.html |
cdc5db4a7c9d-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/stable/_modules/langchain/vectorstores/chroma.html |
cdc5db4a7c9d-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/stable/_modules/langchain/vectorstores/chroma.html |
cdc5db4a7c9d-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/stable/_modules/langchain/vectorstores/chroma.html |
cdc5db4a7c9d-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/stable/_modules/langchain/vectorstores/chroma.html |
cdc5db4a7c9d-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/stable/_modules/langchain/vectorstores/chroma.html |
cdc5db4a7c9d-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/stable/_modules/langchain/vectorstores/chroma.html |
cdc5db4a7c9d-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/stable/_modules/langchain/vectorstores/chroma.html |
cdc5db4a7c9d-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/stable/_modules/langchain/vectorstores/chroma.html |
cdc5db4a7c9d-10 | client: Optional[chromadb.Client] = None, # Add this line
**kwargs: Any,
) -> Chroma:
"""Create a Chroma vectorstore from a list of documents.
If a persist_directory is specified, the collection will be persisted there.
Otherwise, the data will be ephemeral in-memory.
Args:
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/chroma.html |
cd14f973de02-0 | Source code for langchain.vectorstores.redis
"""Wrapper around Redis vector database."""
from __future__ import annotations
import json
import logging
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
cd14f973de02-1 | "Redis cannot be used as a vector database without RediSearch >=2.4"
"Please head to https://redis.io/docs/stack/search/quick_start/"
"to know more about installing the RediSearch module within Redis Stack."
)
logging.error(error_message)
raise ValueError(error_message)
def _check_index_exis... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
cd14f973de02-2 | index_name: str,
embedding_function: Callable,
content_key: str = "content",
metadata_key: str = "metadata",
vector_key: str = "content_vector",
relevance_score_fn: Optional[
Callable[[float], float]
] = _default_relevance_score,
**kwargs: Any,
):
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
cd14f973de02-3 | if not _check_index_exists(self.client, self.index_name):
# Define schema
schema = (
TextField(name=self.content_key),
TextField(name=self.metadata_key),
VectorField(
self.vector_key,
"FLAT",
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
cd14f973de02-4 | prefix = _redis_prefix(self.index_name)
# Get keys or ids from kwargs
# Other vectorstores use ids
keys_or_ids = kwargs.get("keys", kwargs.get("ids"))
# Write data to redis
pipeline = self.client.pipeline(transaction=False)
for i, text in enumerate(texts):
# U... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
cd14f973de02-5 | [docs] def similarity_search_limit_score(
self, query: str, k: int = 4, score_threshold: float = 0.2, **kwargs: Any
) -> List[Document]:
"""
Returns the most similar indexed documents to the query text within the
score_threshold range.
Args:
query (str): The qu... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
cd14f973de02-6 | return (
Query(base_query)
.return_fields(*return_fields)
.sort_by("vector_score")
.paging(0, k)
.dialect(2)
)
[docs] def similarity_search_with_score(
self, query: str, k: int = 4
) -> List[Tuple[Document, float]]:
"""Return doc... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
cd14f973de02-7 | 0 is dissimilar, 1 is most similar.
"""
if self.relevance_score_fn is None:
raise ValueError(
"relevance_score_fn must be provided to"
" Redis constructor to normalize scores"
)
docs_and_scores = self.similarity_search_with_score(query, k=k... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
cd14f973de02-8 | )
"""
redis_url = get_from_dict_or_env(kwargs, "redis_url", "REDIS_URL")
if "redis_url" in kwargs:
kwargs.pop("redis_url")
# Name of the search index if not given
if not index_name:
index_name = uuid.uuid4().hex
# Create instance
instance =... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
cd14f973de02-9 | Example:
.. code-block:: python
from langchain.vectorstores import Redis
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
redisearch = RediSearch.from_texts(
texts,
embedd... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
cd14f973de02-10 | except ValueError as e:
raise ValueError(f"Your redis connected error: {e}")
# Check if index exists
try:
client.delete(*ids)
logger.info("Entries deleted")
return True
except: # noqa: E722
# ids does not exist
return False... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
cd14f973de02-11 | [docs] @classmethod
def from_existing_index(
cls,
embedding: Embeddings,
index_name: str,
content_key: str = "content",
metadata_key: str = "metadata",
vector_key: str = "content_vector",
**kwargs: Any,
) -> Redis:
"""Connect to an existing Redi... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
cd14f973de02-12 | return RedisVectorStoreRetriever(vectorstore=self, **kwargs)
class RedisVectorStoreRetriever(VectorStoreRetriever, BaseModel):
vectorstore: Redis
search_type: str = "similarity"
k: int = 4
score_threshold: float = 0.4
class Config:
"""Configuration for this pydantic object."""
arbitr... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
cd14f973de02-13 | ) -> List[str]:
"""Add documents to vectorstore."""
return await self.vectorstore.aadd_documents(documents, **kwargs) | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/redis.html |
7c5e42ad336a-0 | Source code for langchain.vectorstores.docarray.hnsw
"""Wrapper around Hnswlib store."""
from __future__ import annotations
from typing import Any, List, Literal, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.docarray.base import (
DocArrayIndex,
_check_docarray_import,
)... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/docarray/hnsw.html |
7c5e42ad336a-1 | "cosine", "ip", and "l2". Defaults to "cosine".
max_elements (int): Maximum number of vectors that can be stored.
Defaults to 1024.
index (bool): Whether an index should be built for this field.
Defaults to True.
ef_construction (int): defines a constr... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/docarray/hnsw.html |
7c5e42ad336a-2 | work_dir: Optional[str] = None,
n_dim: Optional[int] = None,
**kwargs: Any,
) -> DocArrayHnswSearch:
"""Create an DocArrayHnswSearch store and insert data.
Args:
texts (List[str]): Text data.
embedding (Embeddings): Embedding function.
metadatas (O... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/docarray/hnsw.html |
53664280d687-0 | Source code for langchain.vectorstores.docarray.in_memory
"""Wrapper around in-memory storage."""
from __future__ import annotations
from typing import Any, Dict, List, Literal, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.docarray.base import (
DocArrayIndex,
_check_doc... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/docarray/in_memory.html |
53664280d687-1 | [docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[Dict[Any, Any]]] = None,
**kwargs: Any,
) -> DocArrayInMemorySearch:
"""Create an DocArrayInMemorySearch store and insert data.
Args:
... | https://api.python.langchain.com/en/stable/_modules/langchain/vectorstores/docarray/in_memory.html |
f2ebb89c901a-0 | Source code for langchain.retrievers.remote_retriever
from typing import List, Optional
import aiohttp
import requests
from pydantic import BaseModel
from langchain.schema import BaseRetriever, Document
[docs]class RemoteLangChainRetriever(BaseRetriever, BaseModel):
url: str
headers: Optional[dict] = None
i... | https://api.python.langchain.com/en/stable/_modules/langchain/retrievers/remote_retriever.html |
6c257a2db6a0-0 | Source code for langchain.retrievers.elastic_search_bm25
"""Wrapper around Elasticsearch vector database."""
from __future__ import annotations
import uuid
from typing import Any, Iterable, List
from langchain.docstore.document import Document
from langchain.schema import BaseRetriever
[docs]class ElasticSearchBM25Retr... | https://api.python.langchain.com/en/stable/_modules/langchain/retrievers/elastic_search_bm25.html |
6c257a2db6a0-1 | self.index_name = index_name
[docs] @classmethod
def create(
cls, elasticsearch_url: str, index_name: str, k1: float = 2.0, b: float = 0.75
) -> ElasticSearchBM25Retriever:
from elasticsearch import Elasticsearch
# Create an Elasticsearch client instance
es = Elasticsearch(ela... | https://api.python.langchain.com/en/stable/_modules/langchain/retrievers/elastic_search_bm25.html |
6c257a2db6a0-2 | raise ValueError(
"Could not import elasticsearch python package. "
"Please install it with `pip install elasticsearch`."
)
requests = []
ids = []
for i, text in enumerate(texts):
_id = str(uuid.uuid4())
request = {
... | https://api.python.langchain.com/en/stable/_modules/langchain/retrievers/elastic_search_bm25.html |
44261d310041-0 | Source code for langchain.retrievers.contextual_compression
"""Retriever that wraps a base retriever and filters the results."""
from typing import List
from pydantic import BaseModel, Extra
from langchain.retrievers.document_compressors.base import (
BaseDocumentCompressor,
)
from langchain.schema import BaseRetri... | https://api.python.langchain.com/en/stable/_modules/langchain/retrievers/contextual_compression.html |
44261d310041-1 | compressed_docs = await self.base_compressor.acompress_documents(
docs, query
)
return list(compressed_docs)
else:
return [] | https://api.python.langchain.com/en/stable/_modules/langchain/retrievers/contextual_compression.html |
56cbf798a7f6-0 | Source code for langchain.retrievers.weaviate_hybrid_search
"""Wrapper around weaviate vector database."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from uuid import uuid4
from pydantic import Extra
from langchain.docstore.document import Document
from langchain.schema import BaseR... | https://api.python.langchain.com/en/stable/_modules/langchain/retrievers/weaviate_hybrid_search.html |
56cbf798a7f6-1 | "properties": [{"name": self._text_key, "dataType": ["text"]}],
"vectorizer": "text2vec-openai",
}
if not self._client.schema.exists(self._index_name):
self._client.schema.create_class(class_obj)
[docs] class Config:
"""Configuration for this pydantic object."""
... | https://api.python.langchain.com/en/stable/_modules/langchain/retrievers/weaviate_hybrid_search.html |
56cbf798a7f6-2 | if where_filter:
query_obj = query_obj.with_where(where_filter)
result = query_obj.with_hybrid(query, alpha=self.alpha).with_limit(self.k).do()
if "errors" in result:
raise ValueError(f"Error during query: {result['errors']}")
docs = []
for res in result["data"]["... | https://api.python.langchain.com/en/stable/_modules/langchain/retrievers/weaviate_hybrid_search.html |
a88beb0c6680-0 | Source code for langchain.retrievers.vespa_retriever
"""Wrapper for retrieving documents from Vespa."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Sequence, Union
from langchain.schema import BaseRetriever, Document
if TYPE_CHECKING:
from ves... | https://api.python.langchain.com/en/stable/_modules/langchain/retrievers/vespa_retriever.html |
a88beb0c6680-1 | docs.append(Document(page_content=page_content, metadata=metadata))
return docs
[docs] def get_relevant_documents(self, query: str) -> List[Document]:
body = self._query_body.copy()
body["query"] = query
return self._query(body)
[docs] async def aget_relevant_documents(self, query:... | https://api.python.langchain.com/en/stable/_modules/langchain/retrievers/vespa_retriever.html |
a88beb0c6680-2 | document metadata. Defaults to empty tuple ().
sources (Sequence[str] or "*" or None): Sources to retrieve
from. Defaults to None.
_filter (Optional[str]): Document filter condition expressed in YQL.
Defaults to None.
yql (Optional[str]): Full YQL quer... | https://api.python.langchain.com/en/stable/_modules/langchain/retrievers/vespa_retriever.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.