id stringlengths 14 16 | text stringlengths 4 1.28k | source stringlengths 54 121 |
|---|---|---|
1145c28da0ec-1 | json={
"query": query,
**({"topK": self.top_k} if self.top_k is not None else {}),
},
headers={
"Content-Type": "application/json",
**(
{"Authorization": f"Bearer {self.api_key}"}
if self.api_... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html |
1145c28da0ec-2 | self.datastore_url,
json={
"query": query,
**({"topK": self.top_k} if self.top_k is not None else {}),
},
headers={
"Content-Type": "application/json",
**(
{"Authorizat... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html |
0b68dbbd0555-0 | Source code for langchain.retrievers.time_weighted_retriever
"""Retriever that combines embedding similarity with recency in retrieving values."""
import datetime
from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
from pydantic import BaseModel, Field
from langchain.schema import BaseRetrieve... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
0b68dbbd0555-1 | search_kwargs: dict = Field(default_factory=lambda: dict(k=100))
"""Keyword arguments to pass to the vectorstore similarity search."""
# TODO: abstract as a queue
memory_stream: List[Document] = Field(default_factory=list)
"""The memory_stream of documents to search through."""
decay_rate: float = F... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
0b68dbbd0555-2 | None assigns no salience to documents not fetched from the vector store.
"""
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
def _get_combined_score(
self,
document: Document,
vector_relevance: Optional[float],
curren... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
0b68dbbd0555-3 | return score
[docs] def get_salient_docs(self, query: str) -> Dict[int, Tuple[Document, float]]:
"""Return documents that are salient to the query."""
docs_and_scores: List[Tuple[Document, float]]
docs_and_scores = self.vectorstore.similarity_search_with_relevance_scores(
query, *... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
0b68dbbd0555-4 | current_time = datetime.datetime.now()
docs_and_scores = {
doc.metadata["buffer_idx"]: (doc, self.default_salience)
for doc in self.memory_stream[-self.k :]
}
# If a doc is considered salient, update the salience score
docs_and_scores.update(self.get_salient_docs(... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
0b68dbbd0555-5 | buffered_doc.metadata["last_accessed_at"] = current_time
result.append(buffered_doc)
return result
[docs] async def aget_relevant_documents(self, query: str) -> List[Document]:
"""Return documents that are relevant to the query."""
raise NotImplementedError
[docs] def add_docum... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
0b68dbbd0555-6 | doc.metadata["created_at"] = current_time
doc.metadata["buffer_idx"] = len(self.memory_stream) + i
self.memory_stream.extend(dup_docs)
return self.vectorstore.add_documents(dup_docs, **kwargs)
[docs] async def aadd_documents(
self, documents: List[Document], **kwargs: Any
) ->... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
0b68dbbd0555-7 | doc.metadata["created_at"] = current_time
doc.metadata["buffer_idx"] = len(self.memory_stream) + i
self.memory_stream.extend(dup_docs)
return await self.vectorstore.aadd_documents(dup_docs, **kwargs) | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
d613f7988167-0 | Source code for langchain.retrievers.tfidf
"""TF-IDF Retriever.
Largely based on
https://github.com/asvskartheek/Text-Retrieval/blob/master/TF-IDF%20Search%20Engine%20(SKLEARN).ipynb"""
from __future__ import annotations
from typing import Any, Dict, Iterable, List, Optional
from pydantic import BaseModel
from langchai... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html |
d613f7988167-1 | texts: Iterable[str],
metadatas: Optional[Iterable[dict]] = None,
tfidf_params: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> TFIDFRetriever:
try:
from sklearn.feature_extraction.text import TfidfVectorizer
except ImportError:
raise ImportError(... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html |
d613f7988167-2 | return cls(vectorizer=vectorizer, docs=docs, tfidf_array=tfidf_array, **kwargs)
[docs] @classmethod
def from_documents(
cls,
documents: Iterable[Document],
*,
tfidf_params: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> TFIDFRetriever:
texts, metadatas = ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html |
d613f7988167-3 | [query]
) # Ip -- (n_docs,x), Op -- (n_docs,n_Feats)
results = cosine_similarity(self.tfidf_array, query_vec).reshape(
(-1,)
) # Op -- (n_docs,1) -- Cosine Sim with each doc
return_docs = [self.docs[i] for i in results.argsort()[-self.k :][::-1]]
return return_docs
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html |
ca139ff1c7d4-0 | Source code for langchain.retrievers.milvus
"""Milvus Retriever"""
import warnings
from typing import Any, Dict, List, Optional
from langchain.embeddings.base import Embeddings
from langchain.schema import BaseRetriever, Document
from langchain.vectorstores.milvus import Milvus
# TODO: Update to MilvusClient + Hybrid S... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/milvus.html |
ca139ff1c7d4-1 | embedding_function,
collection_name,
connection_args,
consistency_level,
)
self.retriever = self.store.as_retriever(search_kwargs={"param": search_params})
[docs] def add_texts(
self, texts: List[str], metadatas: Optional[List[dict]] = None
) -> None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/milvus.html |
ca139ff1c7d4-2 | raise NotImplementedError
def MilvusRetreiver(*args: Any, **kwargs: Any) -> MilvusRetriever:
"""Deprecated MilvusRetreiver. Please use MilvusRetriever ('i' before 'e') instead.
Args:
*args:
**kwargs:
Returns:
MilvusRetriever
"""
warnings.warn(
"MilvusRetreiver will be... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/milvus.html |
0dae097ddc8c-0 | Source code for langchain.retrievers.arxiv
from typing import List
from langchain.schema import BaseRetriever, Document
from langchain.utilities.arxiv import ArxivAPIWrapper
[docs]class ArxivRetriever(BaseRetriever, ArxivAPIWrapper):
"""
It is effectively a wrapper for ArxivAPIWrapper.
It wraps load() to ge... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/arxiv.html |
eb3c7f3bbc06-0 | Source code for langchain.retrievers.docarray
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import numpy as np
from pydantic import BaseModel
from langchain.embeddings.base import Embeddings
from langchain.schema import BaseRetriever, Document
from langchain.vectorstores.utils import maximal... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
eb3c7f3bbc06-1 | Attributes:
index: One of the above-mentioned index instances
embeddings: Embedding model to represent text as vectors
search_field: Field to consider for searching in the documents.
Should be an embedding/vector/tensor.
content_field: Field that represents the main content i... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
eb3c7f3bbc06-2 | arbitrary_types_allowed = True
[docs] def get_relevant_documents(self, query: str) -> List[Document]:
"""Get documents relevant for a query.
Args:
query: string to find relevant documents for
Returns:
List of relevant documents
"""
query_emb = np.array(... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
eb3c7f3bbc06-3 | ) -> List[Union[Dict[str, Any], Any]]:
"""
Perform a search using the query embedding and return top_k documents.
Args:
query_emb: Query represented as an embedding
top_k: Number of documents to return
Returns:
A list of top_k documents matching the qu... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
eb3c7f3bbc06-4 | .find(
query=query_emb, search_field=search_field
) # add vector similarity search
.filter(**filter_args) # add filter search
.build(limit=top_k) # build the query
)
# execute the combined query and return the results
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
eb3c7f3bbc06-5 | """
docs = self._search(query_emb=query_emb, top_k=self.top_k)
results = [self._docarray_to_langchain_doc(doc) for doc in docs]
return results
def _mmr_search(self, query_emb: np.ndarray) -> List[Document]:
"""
Perform a maximal marginal relevance (mmr) search.
Args:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
eb3c7f3bbc06-6 | k=self.top_k,
)
results = [self._docarray_to_langchain_doc(docs[idx]) for idx in mmr_selected]
return results
def _docarray_to_langchain_doc(self, doc: Union[Dict[str, Any], Any]) -> Document:
"""
Convert a DocArray document (which also might be a dict)
to a langchain... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
eb3c7f3bbc06-7 | if self.content_field not in fields:
raise ValueError(
f"Document does not contain the content field - {self.content_field}."
)
lc_doc = Document(
page_content=doc[self.content_field]
if isinstance(doc, dict)
else getattr(doc, self.cont... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
791a149715e7-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/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
791a149715e7-1 | except ImportError:
raise ImportError(
"Could not import weaviate python package. "
"Please install it with `pip install weaviate-client`."
)
if not isinstance(client, weaviate.Client):
raise ValueError(
f"client should be an in... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
791a149715e7-2 | "class": self._index_name,
"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:
"""Configurat... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
791a149715e7-3 | metadata = doc.metadata or {}
data_properties = {self._text_key: doc.page_content, **metadata}
# If the UUID of one of the objects already exists
# then the existing objectwill be replaced by the new object.
if "uuids" in kwargs:
_id = ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
791a149715e7-4 | 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/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
7c8893047924-0 | Source code for langchain.retrievers.kendra
import re
from typing import Any, Dict, List, Literal, Optional
from pydantic import BaseModel, Extra
from langchain.docstore.document import Document
from langchain.schema import BaseRetriever
def clean_excerpt(excerpt: str) -> str:
if not excerpt:
return excerpt... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
7c8893047924-1 | Type: Optional[str]
class TextWithHighLights(BaseModel, extra=Extra.allow):
Text: str
Highlights: Optional[Any]
class AdditionalResultAttribute(BaseModel, extra=Extra.allow):
Key: str
ValueType: Literal["TEXT_WITH_HIGHLIGHTS_VALUE"]
Value: Optional[TextWithHighLights]
def get_value_text(self) ->... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
7c8893047924-2 | def get_attribute_value(self) -> str:
if not self.AdditionalAttributes:
return ""
if not self.AdditionalAttributes[0]:
return ""
else:
return self.AdditionalAttributes[0].get_value_text()
def get_excerpt(self) -> str:
if (
self.Addition... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
7c8893047924-3 | metadata = {"source": source, "title": title, "excerpt": excerpt, "type": type}
return Document(page_content=page_content, metadata=metadata)
class QueryResult(BaseModel, extra=Extra.allow):
ResultItems: List[QueryResultItem]
def get_top_k_docs(self, top_n: int) -> List[Document]:
items_len = le... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
7c8893047924-4 | Value: DocumentAttributeValue
class RetrieveResultItem(BaseModel, extra=Extra.allow):
Content: Optional[str]
DocumentAttributes: Optional[List[DocumentAttribute]] = []
DocumentId: Optional[str]
DocumentTitle: Optional[str]
DocumentURI: Optional[str]
Id: Optional[str]
def get_excerpt(self) ->... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
7c8893047924-5 | QueryId: str
ResultItems: List[RetrieveResultItem]
def get_top_k_docs(self, top_n: int) -> List[Document]:
items_len = len(self.ResultItems)
count = items_len if items_len < top_n else top_n
docs = [self.ResultItems[i].to_doc() for i in range(0, count)]
return docs
[docs]class Am... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
7c8893047924-6 | or ~/.aws/config files, which has either access keys or role information
specified. If not specified, the default credential profile or, if on an
EC2 instance, credentials from IMDS will be used.
top_k: No of results to return
attribute_filter: Additional filtering of results bas... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
7c8893047924-7 | top_k: int = 3,
attribute_filter: Optional[Dict] = None,
client: Optional[Any] = None,
):
self.index_id = index_id
self.top_k = top_k
self.attribute_filter = attribute_filter
if client is not None:
self.client = client
return
try:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
7c8893047924-8 | "Please install it with `pip install boto3`."
)
except Exception as e:
raise ValueError(
"Could not load credentials to authenticate with AWS client. "
"Please check that credentials in the specified "
"profile name are valid."
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
7c8893047924-9 | )
r_result = RetrieveResult.parse_obj(response)
result_len = len(r_result.ResultItems)
if result_len == 0:
# retrieve API returned 0 results, call query API
if attribute_filter is not None:
response = self.client.query(
IndexId=self.ind... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
7c8893047924-10 | """Run search on Kendra index and get top k documents
Example:
.. code-block:: python
docs = retriever.get_relevant_documents('This is my query')
"""
docs = self._kendra_query(query, self.top_k, self.attribute_filter)
return docs
[docs] async def aget_relevant_docu... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
abe24011d56f-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/latest/_modules/langchain/retrievers/vespa_retriever.html |
abe24011d56f-1 | def _query(self, body: Dict) -> List[Document]:
response = self._application.query(body)
if not str(response.status_code).startswith("2"):
raise RuntimeError(
"Could not retrieve data from Vespa. Error code: {}".format(
response.status_code
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
abe24011d56f-2 | 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: str) -> List[Document]:
raise NotImplementedError
[docs] def get... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
abe24011d56f-3 | cls,
url: str,
content_field: str,
*,
k: Optional[int] = None,
metadata_fields: Union[Sequence[str], Literal["*"]] = (),
sources: Union[Sequence[str], Literal["*"], None] = None,
_filter: Optional[str] = None,
yql: Optional[str] = None,
**kwargs: A... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
abe24011d56f-4 | 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/latest/_modules/langchain/retrievers/vespa_retriever.html |
abe24011d56f-5 | raise ValueError(
"yql should only be specified if both sources and _filter are not "
"specified."
)
else:
if metadata_fields == "*":
_fields = "*"
body["summary"] = "short"
else:
_fields = ", ".j... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
fb84ba6ffcec-0 | Source code for langchain.retrievers.knn
"""KNN Retriever.
Largely based on
https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb"""
from __future__ import annotations
import concurrent.futures
from typing import Any, List, Optional
import numpy as np
from pydantic import BaseModel
from langchain.embedding... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html |
fb84ba6ffcec-1 | return np.array(list(executor.map(embeddings.embed_query, contexts)))
[docs]class KNNRetriever(BaseRetriever, BaseModel):
"""KNN Retriever."""
embeddings: Embeddings
index: Any
texts: List[str]
k: int = 4
relevancy_threshold: Optional[float] = None
class Config:
"""Configuration for ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html |
fb84ba6ffcec-2 | query_embeds = np.array(self.embeddings.embed_query(query))
# calc L2 norm
index_embeds = self.index / np.sqrt((self.index**2).sum(1, keepdims=True))
query_embeds = query_embeds / np.sqrt((query_embeds**2).sum())
similarities = index_embeds.dot(query_embeds)
sorted_ix = np.argsor... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html |
fb84ba6ffcec-3 | )
]
return top_k_results
[docs] async def aget_relevant_documents(self, query: str) -> List[Document]:
raise NotImplementedError | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html |
74668f4cd461-0 | Source code for langchain.retrievers.llama_index
from typing import Any, Dict, List, cast
from pydantic import BaseModel, Field
from langchain.schema import BaseRetriever, Document
[docs]class LlamaIndexRetriever(BaseRetriever, BaseModel):
"""Question-answering with sources over an LlamaIndex data structure."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html |
74668f4cd461-1 | response = index.query(query, response_mode="no_text", **self.query_kwargs)
response = cast(Response, response)
# parse source nodes
docs = []
for source_node in response.source_nodes:
metadata = source_node.extra_info or {}
docs.append(
Document(p... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html |
74668f4cd461-2 | [docs] def get_relevant_documents(self, query: str) -> List[Document]:
"""Get documents relevant for a query."""
try:
from llama_index.composability.graph import (
QUERY_CONFIG_TYPE,
ComposableGraph,
)
from llama_index.response.schem... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html |
74668f4cd461-3 | # parse source nodes
docs = []
for source_node in response.source_nodes:
metadata = source_node.extra_info or {}
docs.append(
Document(page_content=source_node.source_text, metadata=metadata)
)
return docs
[docs] async def aget_relevant_docu... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html |
51ac6a4127e8-0 | Source code for langchain.retrievers.azure_cognitive_search
"""Retriever wrapper for Azure Cognitive Search."""
from __future__ import annotations
import json
from typing import Dict, List, Optional
import aiohttp
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.schema import BaseRet... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
51ac6a4127e8-1 | recommended to use a Query key."""
api_version: str = "2020-06-30"
"""API version"""
aiosession: Optional[aiohttp.ClientSession] = None
"""ClientSession, in case we want to reuse connection for better performance."""
content_key: str = "content"
"""Key in a retrieved result to set as the Documen... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
51ac6a4127e8-2 | values, "index_name", "AZURE_COGNITIVE_SEARCH_INDEX_NAME"
)
values["api_key"] = get_from_dict_or_env(
values, "api_key", "AZURE_COGNITIVE_SEARCH_API_KEY"
)
return values
def _build_search_url(self, query: str) -> str:
base_url = f"https://{self.service_name}.searc... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
51ac6a4127e8-3 | search_url = self._build_search_url(query)
response = requests.get(search_url, headers=self._headers)
if response.status_code != 200:
raise Exception(f"Error in search request: {response}")
return json.loads(response.text)["value"]
async def _asearch(self, query: str) -> List[dic... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
51ac6a4127e8-4 | return response_json["value"]
[docs] def get_relevant_documents(self, query: str) -> List[Document]:
search_results = self._search(query)
return [
Document(page_content=result.pop(self.content_key), metadata=result)
for result in search_results
]
[docs] async def ag... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
d9153b81f673-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/latest/_modules/langchain/retrievers/contextual_compression.html |
d9153b81f673-1 | arbitrary_types_allowed = True
[docs] def get_relevant_documents(self, query: str) -> List[Document]:
"""Get documents relevant for a query.
Args:
query: string to find relevant documents for
Returns:
Sequence of relevant documents
"""
docs = self.base_... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html |
d9153b81f673-2 | if docs:
compressed_docs = await self.base_compressor.acompress_documents(
docs, query
)
return list(compressed_docs)
else:
return [] | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html |
3289514fbb05-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/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
3289514fbb05-1 | Elastic Cloud console at https://cloud.elastic.co, selecting your deployment, and
navigating to the "Deployments" page.
To obtain your Elastic Cloud password for the default "elastic" user:
1. Log in to the Elastic Cloud console at https://cloud.elastic.co
2. Go to "Security" > "Users"
3. Locate the... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
3289514fbb05-2 | 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(elasticsearch_url)
# Define the index settings and ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
3289514fbb05-3 | }
}
}
# Create the index with the specified settings and mappings
es.indices.create(index=index_name, mappings=mappings, settings=settings)
return cls(es, index_name)
[docs] def add_texts(
self,
texts: Iterable[str],
refresh_indices: bool = True,
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
3289514fbb05-4 | )
requests = []
ids = []
for i, text in enumerate(texts):
_id = str(uuid.uuid4())
request = {
"_op_type": "index",
"_index": self.index_name,
"content": text,
"_id": _id,
}
ids.append(... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
3289514fbb05-5 | return docs
[docs] async def aget_relevant_documents(self, query: str) -> List[Document]:
raise NotImplementedError | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
b4f2961750cf-0 | Source code for langchain.retrievers.svm
"""SMV Retriever.
Largely based on
https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb"""
from __future__ import annotations
import concurrent.futures
from typing import Any, List, Optional
import numpy as np
from pydantic import BaseModel
from langchain.embedding... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
b4f2961750cf-1 | return np.array(list(executor.map(embeddings.embed_query, contexts)))
[docs]class SVMRetriever(BaseRetriever, BaseModel):
"""SVM Retriever."""
embeddings: Embeddings
index: Any
texts: List[str]
k: int = 4
relevancy_threshold: Optional[float] = None
class Config:
"""Configuration for ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
b4f2961750cf-2 | from sklearn import svm
query_embeds = np.array(self.embeddings.embed_query(query))
x = np.concatenate([query_embeds[None, ...], self.index])
y = np.zeros(x.shape[0])
y[0] = 1
clf = svm.LinearSVC(
class_weight="balanced", verbose=False, max_iter=10000, tol=1e-6, C=0.1... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
b4f2961750cf-3 | zero_index = np.where(sorted_ix == 0)[0][0]
if zero_index != 0:
sorted_ix[0], sorted_ix[zero_index] = sorted_ix[zero_index], sorted_ix[0]
denominator = np.max(similarities) - np.min(similarities) + 1e-6
normalized_similarities = (similarities - np.min(similarities)) / denominator
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
88e84ae6f613-0 | Source code for langchain.retrievers.pinecone_hybrid_search
"""Taken from: https://docs.pinecone.io/docs/hybrid-search"""
import hashlib
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
from langchain.schema import BaseRe... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
88e84ae6f613-1 | ) -> None:
"""
Create a Pinecone index from a list of contexts.
Modifies the index argument in-place.
Args:
contexts: List of contexts to embed.
index: Pinecone index to use.
embeddings: Embeddings model to use.
sparse_encoder: Sparse encoder to use.
ids: List of ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
88e84ae6f613-2 | for i in _iterator:
# find end of batch
i_end = min(i + batch_size, len(contexts))
# extract batch
context_batch = contexts[i:i_end]
batch_ids = ids[i:i_end]
metadata_batch = (
metadatas[i:i_end] if metadatas else [{} for _ in context_batch]
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
88e84ae6f613-3 | vectors = []
# loop through the data and create dictionaries for upserts
for doc_id, sparse, dense, metadata in zip(
batch_ids, sparse_embeds, dense_embeds, meta
):
vectors.append(
{
"id": doc_id,
"sparse_values": sp... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
88e84ae6f613-4 | arbitrary_types_allowed = True
[docs] def add_texts(
self,
texts: List[str],
ids: Optional[List[str]] = None,
metadatas: Optional[List[dict]] = None,
) -> None:
create_index(
texts,
self.index,
self.embeddings,
self.sparse_en... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
88e84ae6f613-5 | except ImportError:
raise ValueError(
"Could not import pinecone_text python package. "
"Please install it with `pip install pinecone_text`."
)
return values
[docs] def get_relevant_documents(self, query: str) -> List[Document]:
from pinecone_te... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
88e84ae6f613-6 | sparse_vector=sparse_vec,
top_k=self.top_k,
include_metadata=True,
)
final_result = []
for res in result["matches"]:
context = res["metadata"].pop("context")
final_result.append(
Document(page_content=context, metadata=res["metadata... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
bf13bf62f544-0 | Source code for langchain.retrievers.merger_retriever
from typing import List
from langchain.schema import BaseRetriever, Document
[docs]class MergerRetriever(BaseRetriever):
"""
This class merges the results of multiple retrievers.
Args:
retrievers: A list of retrievers to merge.
"""
def __... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
bf13bf62f544-1 | query: The query to search for.
Returns:
A list of relevant documents.
"""
# Merge the results of the retrievers.
merged_documents = self.merge_documents(query)
return merged_documents
[docs] async def aget_relevant_documents(self, query: str) -> List[Document]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
bf13bf62f544-2 | Returns:
A list of merged documents.
"""
# Get the results of all retrievers.
retriever_docs = [
retriever.get_relevant_documents(query) for retriever in self.retrievers
]
# Merge the results of the retrievers.
merged_documents = []
max_doc... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
bf13bf62f544-3 | """
# Get the results of all retrievers.
retriever_docs = [
await retriever.aget_relevant_documents(query)
for retriever in self.retrievers
]
# Merge the results of the retrievers.
merged_documents = []
max_docs = max(len(docs) for docs in retrieve... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
e68cad9e2426-0 | Source code for langchain.retrievers.wikipedia
from typing import List
from langchain.schema import BaseRetriever, Document
from langchain.utilities.wikipedia import WikipediaAPIWrapper
[docs]class WikipediaRetriever(BaseRetriever, WikipediaAPIWrapper):
"""
It is effectively a wrapper for WikipediaAPIWrapper.
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/wikipedia.html |
04756fa1bedc-0 | Source code for langchain.retrievers.metal
from typing import Any, List, Optional
from langchain.schema import BaseRetriever, Document
[docs]class MetalRetriever(BaseRetriever):
"""Retriever that uses the Metal API."""
def __init__(self, client: Any, params: Optional[dict] = None):
from metal_sdk.metal ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/metal.html |
04756fa1bedc-1 | final_results = []
for r in results["data"]:
metadata = {k: v for k, v in r.items() if k != "text"}
final_results.append(Document(page_content=r["text"], metadata=metadata))
return final_results
[docs] async def aget_relevant_documents(self, query: str) -> List[Document]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/metal.html |
74a86f1ec770-0 | Source code for langchain.retrievers.pupmed
from typing import List
from langchain.schema import BaseRetriever, Document
from langchain.utilities.pupmed import PubMedAPIWrapper
[docs]class PubMedRetriever(BaseRetriever, PubMedAPIWrapper):
"""
It is effectively a wrapper for PubMedAPIWrapper.
It wraps load()... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pupmed.html |
3e1730bd54da-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/latest/_modules/langchain/retrievers/remote_retriever.html |
3e1730bd54da-1 | )
for r in result[self.response_key]
]
[docs] async def aget_relevant_documents(self, query: str) -> List[Document]:
async with aiohttp.ClientSession() as session:
async with session.request(
"POST", self.url, headers=self.headers, json={self.input_key: query}
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/remote_retriever.html |
b5d7faf75d72-0 | Source code for langchain.retrievers.zilliz
"""Zilliz Retriever"""
import warnings
from typing import Any, Dict, List, Optional
from langchain.embeddings.base import Embeddings
from langchain.schema import BaseRetriever, Document
from langchain.vectorstores.zilliz import Zilliz
# TODO: Update to ZillizClient + Hybrid S... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zilliz.html |
b5d7faf75d72-1 | embedding_function,
collection_name,
connection_args,
consistency_level,
)
self.retriever = self.store.as_retriever(search_kwargs={"param": search_params})
[docs] def add_texts(
self, texts: List[str], metadatas: Optional[List[dict]] = None
) -> None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zilliz.html |
b5d7faf75d72-2 | raise NotImplementedError
def ZillizRetreiver(*args: Any, **kwargs: Any) -> ZillizRetriever:
"""
Deprecated ZillizRetreiver. Please use ZillizRetriever ('i' before 'e') instead.
Args:
*args:
**kwargs:
Returns:
ZillizRetriever
"""
warnings.warn(
"ZillizRetreiver wi... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zilliz.html |
5c7ef22eeb66-0 | Source code for langchain.retrievers.self_query.base
"""Retriever that generates and executes structured queries over its own data source."""
from typing import Any, Dict, List, Optional, Type, cast
from pydantic import BaseModel, Field, root_validator
from langchain import LLMChain
from langchain.base_language import ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
5c7ef22eeb66-1 | from langchain.retrievers.self_query.weaviate import WeaviateTranslator
from langchain.schema import BaseRetriever, Document
from langchain.vectorstores import (
Chroma,
MyScale,
Pinecone,
Qdrant,
VectorStore,
Weaviate,
)
def _get_builtin_translator(vectorstore: VectorStore) -> Visitor:
"""G... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
5c7ef22eeb66-2 | raise ValueError(
f"Self query retriever with Vector Store type {vectorstore_cls}"
f" not supported."
)
if isinstance(vectorstore, Qdrant):
return QdrantTranslator(metadata_key=vectorstore.metadata_payload_key)
elif isinstance(vectorstore, MyScale):
return MyScale... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
5c7ef22eeb66-3 | """The search type to perform on the vector store."""
search_kwargs: dict = Field(default_factory=dict)
"""Keyword arguments to pass in to the vector store search."""
structured_query_translator: Visitor
"""Translator for turning internal query language into vectorstore search params."""
verbose: bo... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
5c7ef22eeb66-4 | self, query: str, callbacks: Callbacks = None
) -> List[Document]:
"""Get documents relevant for a query.
Args:
query: string to find relevant documents for
Returns:
List of relevant documents
"""
inputs = self.llm_chain.prep_inputs({"query": query})
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
5c7ef22eeb66-5 | docs = self.vectorstore.search(new_query, self.search_type, **search_kwargs)
return docs
[docs] async def aget_relevant_documents(self, query: str) -> List[Document]:
raise NotImplementedError
[docs] @classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
vectorstore: V... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.