id stringlengths 14 15 | text stringlengths 35 2.51k | source stringlengths 61 154 |
|---|---|---|
09ea1244cd87-2 | if (
self.relevancy_threshold is None
or normalized_similarities[row] >= self.relevancy_threshold
):
top_k_results.append(Document(page_content=self.texts[row - 1]))
return top_k_results
async def _aget_relevant_documents(
self,
que... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
f02ad9be6e4d-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.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
f02ad9be6e4d-1 | def _create_schema_if_missing(self) -> None:
class_obj = {
"class": self._index_name,
"properties": [{"name": self._text_key, "dataType": ["text"]}],
"vectorizer": "text2vec-openai",
}
if not self._client.schema.exists(self._index_name):
self._clie... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
f02ad9be6e4d-2 | ) -> List[Document]:
"""Look up similar documents in Weaviate."""
query_obj = self._client.query.get(self._index_name, self._query_attrs)
if where_filter:
query_obj = query_obj.with_where(where_filter)
result = query_obj.with_hybrid(query, alpha=self.alpha).with_limit(self.k)... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
fb0bf0356a7a-0 | Source code for langchain.retrievers.chatgpt_plugin_retriever
from __future__ import annotations
from typing import Any, List, Optional
import aiohttp
import requests
from pydantic import BaseModel
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
f... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html |
fb0bf0356a7a-1 | **kwargs: Any,
) -> List[Document]:
url, json, headers = self._create_request(query)
if not self.aiosession:
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, json=json) as response:
res = await response.json(... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html |
2934b8c4dcb3-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.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
2934b8c4dcb3-1 | self.client = client
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
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
2934b8c4dcb3-2 | from elasticsearch.helpers import bulk
except ImportError:
raise ValueError(
"Could not import elasticsearch python package. "
"Please install it with `pip install elasticsearch`."
)
requests = []
ids = []
for i, text in enumerate(t... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
6b13a9e94047-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.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
6b13a9e94047-1 | except ImportError:
pass
if ids is None:
# create unique ids using hash of the text
ids = [hash_text(context) for context in contexts]
for i in _iterator:
# find end of batch
i_end = min(i + batch_size, len(contexts))
# extract batch
context_batch = contex... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
6b13a9e94047-2 | sparse_encoder: Any
index: Any
top_k: int = 4
alpha: float = 0.5
[docs] class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
[docs] def add_texts(
self,
texts: List[str],
ids: Optional[List[str]]... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
6b13a9e94047-3 | dense_vec = self.embeddings.embed_query(query)
# scale alpha with hybrid_scale
dense_vec, sparse_vec = hybrid_convex_scale(dense_vec, sparse_vec, self.alpha)
sparse_vec["values"] = [float(s1) for s1 in sparse_vec["values"]]
# query pinecone with the query parameters
result = self... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
902aaa14b12f-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 |
902aaa14b12f-1 | metadatas = metadatas or ({} for _ in texts)
docs = [Document(page_content=t, metadata=m) for t, m in zip(texts, metadatas)]
return cls(vectorizer=vectorizer, docs=docs, tfidf_array=tfidf_array, **kwargs)
[docs] @classmethod
def from_documents(
cls,
documents: Iterable[Document],
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html |
902aaa14b12f-2 | run_manager: AsyncCallbackManagerForRetrieverRun,
**kwargs: Any,
) -> List[Document]:
raise NotImplementedError | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html |
cae456563057-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.callbacks... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html |
cae456563057-1 | return cls(embeddings=embeddings, index=index, texts=texts, **kwargs)
def _get_relevant_documents(
self,
query: str,
*,
run_manager: CallbackManagerForRetrieverRun,
**kwargs: Any,
) -> List[Document]:
query_embeds = np.array(self.embeddings.embed_query(query))
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html |
cfe1b5743be3-0 | Source code for langchain.retrievers.arxiv
from typing import Any, List
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document
from langchain.utilities.arxiv import ArxivAPIWrapper
[docs]class ArxivRet... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/arxiv.html |
e7a6aeaefbee-0 | Source code for langchain.retrievers.contextual_compression
"""Retriever that wraps a base retriever and filters the results."""
from typing import Any, List
from pydantic import BaseModel, Extra
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
fro... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html |
e7a6aeaefbee-1 | else:
return []
async def _aget_relevant_documents(
self,
query: str,
*,
run_manager: AsyncCallbackManagerForRetrieverRun,
**kwargs: Any,
) -> List[Document]:
"""Get documents relevant for a query.
Args:
query: string to find releva... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html |
0191a5f3d563-0 | Source code for langchain.retrievers.wikipedia
from typing import Any, List
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document
from langchain.utilities.wikipedia import WikipediaAPIWrapper
[docs]cl... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/wikipedia.html |
1bc5789b4cc4-0 | Source code for langchain.retrievers.databerry
from typing import Any, List, Optional
import aiohttp
import requests
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document
[docs]class DataberryRetrieve... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html |
1bc5789b4cc4-1 | )
for r in data["results"]
]
async def _aget_relevant_documents(
self,
query: str,
*,
run_manager: AsyncCallbackManagerForRetrieverRun,
**kwargs: Any,
) -> List[Document]:
async with aiohttp.ClientSession() as session:
async with se... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html |
f88cc1cf64ac-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.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.embeddings.bas... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
f88cc1cf64ac-1 | top_k: int = 1
filters: Optional[Any] = None
[docs] class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
def _get_relevant_documents(
self,
query: str,
run_manager: CallbackManagerForRetrieverRun,
**kwargs: Any,
) -> Li... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
f88cc1cf64ac-2 | filter_args["where_filter"] = self.filters
search_field = ""
elif isinstance(self.index, ElasticDocIndex):
filter_args["query"] = self.filters
else:
filter_args["filter_query"] = self.filters
if self.filters:
query = (
self.index.bu... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
f88cc1cf64ac-3 | """
docs = self._search(query_emb=query_emb, top_k=20)
mmr_selected = maximal_marginal_relevance(
query_emb,
[
doc[self.search_field]
if isinstance(doc, dict)
else getattr(doc, self.search_field)
for doc in docs
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
f88cc1cf64ac-4 | if (
isinstance(value, (str, int, float, bool))
and name != self.content_field
):
lc_doc.metadata[name] = value
return lc_doc
async def _aget_relevant_documents(
self,
query: str,
run_manager: AsyncCallbackManagerForRetrieve... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
d9b9c101f814-0 | Source code for langchain.retrievers.azure_cognitive_search
"""Retriever wrapper for Azure Cognitive Search."""
from __future__ import annotations
import json
from typing import Any, Dict, List, Optional
import aiohttp
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.callbacks.manage... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
d9b9c101f814-1 | )
values["index_name"] = get_from_dict_or_env(
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: ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
d9b9c101f814-2 | return response_json["value"]
def _get_relevant_documents(
self,
query: str,
*,
run_manager: CallbackManagerForRetrieverRun,
**kwargs: Any,
) -> List[Document]:
search_results = self._search(query)
return [
Document(page_content=result.pop(self... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
e8bc7f9a280e-0 | Source code for langchain.retrievers.llama_index
from typing import Any, Dict, List, Optional, cast
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document
[docs]cl... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html |
e8bc7f9a280e-1 | **kwargs: Any,
) -> List[Document]:
raise NotImplementedError("LlamaIndexRetriever does not support async")
[docs]class LlamaIndexGraphRetriever(BaseRetriever, BaseModel):
"""Question-answering with sources over an LlamaIndex graph data structure."""
graph: Any
query_configs: List[Dict] = Field(... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html |
e8bc7f9a280e-2 | self,
query: str,
*,
run_manager: AsyncCallbackManagerForRetrieverRun,
**kwargs: Any,
) -> List[Document]:
raise NotImplementedError("LlamaIndexGraphRetriever does not support async") | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html |
17a71cc33619-0 | Source code for langchain.retrievers.merger_retriever
from typing import Any, List
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document
[docs]class MergerRetriever(BaseRetriever):
"""
This cl... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
17a71cc33619-1 | Returns:
A list of relevant documents.
"""
# Merge the results of the retrievers.
merged_documents = await self.amerge_documents(query, run_manager)
return merged_documents
[docs] def merge_documents(
self, query: str, run_manager: CallbackManagerForRetrieverRun
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
17a71cc33619-2 | retriever_docs = [
await retriever.aget_relevant_documents(
query, callbacks=run_manager.get_child("retriever_{}".format(i + 1))
)
for i, retriever in enumerate(self.retrievers)
]
# Merge the results of the retrievers.
merged_documents = []
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
5177c34b43aa-0 | Source code for langchain.retrievers.zep
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document
if TYPE_CH... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html |
5177c34b43aa-1 | self, results: List[MemorySearchResult]
) -> List[Document]:
return [
Document(
page_content=r.message.pop("content"),
metadata={"score": r.dist, **r.message},
)
for r in results
if r.message
]
def _get_relevant_docu... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html |
018bc90889aa-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.callbacks.manager import (... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
018bc90889aa-1 | default_salience: Optional[float] = None
"""The salience to assign memories not retrieved from the vector store.
None assigns no salience to documents not fetched from the vector store.
"""
[docs] class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
018bc90889aa-2 | self,
query: str,
*,
run_manager: CallbackManagerForRetrieverRun,
**kwargs: Any,
) -> List[Document]:
"""Return documents that are relevant to the query."""
current_time = datetime.datetime.now()
docs_and_scores = {
doc.metadata["buffer_idx"]: (doc... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
018bc90889aa-3 | current_time = kwargs.get("current_time")
if current_time is None:
current_time = datetime.datetime.now()
# Avoid mutating input documents
dup_docs = [deepcopy(d) for d in documents]
for i, doc in enumerate(dup_docs):
if "last_accessed_at" not in doc.metadata:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
5f6f83abb598-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.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
5f6f83abb598-1 | page_content = child["fields"].pop(self._content_field, "")
if self._metadata_fields == "*":
metadata = child["fields"]
else:
metadata = {mf: child["fields"].get(mf) for mf in self._metadata_fields}
metadata["id"] = child["id"]
docs.append(... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
5f6f83abb598-2 | sources: Union[Sequence[str], Literal["*"], None] = None,
_filter: Optional[str] = None,
yql: Optional[str] = None,
**kwargs: Any,
) -> VespaRetriever:
"""Instantiate retriever from params.
Args:
url (str): Vespa app URL.
content_field (str): Field in ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
5f6f83abb598-3 | _fields = ", ".join([content_field] + list(metadata_fields or []))
_sources = ", ".join(sources) if isinstance(sources, Sequence) else "*"
_filter = f" and {_filter}" if _filter else ""
yql = f"select {_fields} from sources {_sources} where userQuery(){_filter}"
body["yql"] =... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
8b2c33caf34d-0 | Source code for langchain.retrievers.remote_retriever
from typing import Any, List, Optional
import aiohttp
import requests
from pydantic import BaseModel
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/remote_retriever.html |
8b2c33caf34d-1 | result = await response.json()
return [
Document(
page_content=r[self.page_content_key], metadata=r[self.metadata_key]
)
for r in result[self.response_key]
] | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/remote_retriever.html |
ecaa4a2c994c-0 | Source code for langchain.retrievers.pubmed
"""A retriever that uses PubMed API to retrieve documents."""
from typing import Any, List
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document
from langch... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pubmed.html |
b79d273a7a4b-0 | Source code for langchain.retrievers.metal
from typing import Any, List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document
[docs]class MetalRetriever(BaseRetriever):
"""Retriever that... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/metal.html |
2746e42b9c1b-0 | Source code for langchain.retrievers.multi_query
import logging
from typing import Any, List
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.chains.llm import LLMChain
from langchain.llms.base i... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html |
2746e42b9c1b-1 | """Given a user query, use an LLM to write a set of queries.
Retrieve docs for each query. Rake the unique union of all retrieved docs."""
def __init__(
self,
retriever: BaseRetriever,
llm_chain: LLMChain,
verbose: bool = True,
parser_key: str = "lines",
) -> None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html |
2746e42b9c1b-2 | parser_key=parser_key,
)
def _get_relevant_documents(
self,
query: str,
run_manager: CallbackManagerForRetrieverRun,
**kwargs: Any,
) -> List[Document]:
"""Get relevated documents given a user query.
Args:
question: user query
Returns:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html |
2746e42b9c1b-3 | queries: query list
Returns:
List of retrived Documents
"""
documents = []
for query in queries:
docs = self.retriever.get_relevant_documents(
query, callbacks=run_manager.get_child()
)
documents.extend(docs)
return ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html |
f8d15d33f442-0 | Source code for langchain.retrievers.self_query.weaviate
"""Logic for converting internal query language to a valid Weaviate query."""
from typing import Dict, Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/weaviate.html |
757a1c2d5fc7-0 | Source code for langchain.retrievers.self_query.chroma
"""Logic for converting internal query language to a valid Chroma query."""
from typing import Dict, Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
[d... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/chroma.html |
7309b34e5828-0 | Source code for langchain.retrievers.self_query.myscale
import datetime
import re
from typing import Any, Callable, Dict, Tuple
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
[docs]def DEFAULT_COMPOSER(op_name: str) ->... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/myscale.html |
7309b34e5828-1 | Comparator.LIKE,
]
map_dict = {
Operator.AND: DEFAULT_COMPOSER("AND"),
Operator.OR: DEFAULT_COMPOSER("OR"),
Operator.NOT: DEFAULT_COMPOSER("NOT"),
Comparator.EQ: DEFAULT_COMPOSER("="),
Comparator.GT: DEFAULT_COMPOSER(">"),
Comparator.GTE: DEFAULT_COMPOSER(">="),
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/myscale.html |
7309b34e5828-2 | # convert timestamp for datetime objects
if type(value) is datetime.date:
attr = f"parseDateTime32BestEffort({attr})"
value = f"parseDateTime32BestEffort('{value.strftime('%Y-%m-%d')}')"
# string pattern match
if comp is Comparator.LIKE:
value = f"'%{value[1:-... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/myscale.html |
79e1fdb72f0e-0 | Source code for langchain.retrievers.self_query.qdrant
"""Logic for converting internal query language to a valid Qdrant query."""
from __future__ import annotations
from typing import TYPE_CHECKING, Tuple
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/qdrant.html |
79e1fdb72f0e-1 | ) -> Tuple[str, dict]:
try:
from qdrant_client.http import models as rest
except ImportError as e:
raise ImportError(
"Cannot import qdrant_client. Please install with `pip install "
"qdrant-client`."
) from e
if structured_quer... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/qdrant.html |
c0c2bb0be774-0 | Source code for langchain.retrievers.self_query.pinecone
"""Logic for converting internal query language to a valid Pinecone query."""
from typing import Dict, Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/pinecone.html |
a0ab4946b1b9-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 |
a0ab4946b1b9-1 | MyScale: MyScaleTranslator,
}
if vectorstore_cls not in BUILTIN_TRANSLATORS:
raise ValueError(
f"Self query retriever with Vector Store type {vectorstore_cls}"
f" not supported."
)
if isinstance(vectorstore, Qdrant):
return QdrantTranslator(metadata_key=vector... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
a0ab4946b1b9-2 | values["structured_query_translator"] = _get_builtin_translator(
values["vectorstore"]
)
return values
def _get_relevant_documents(
self,
query: str,
*,
run_manager: CallbackManagerForRetrieverRun,
**kwargs: Any,
) -> List[Document]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
a0ab4946b1b9-3 | document_contents: str,
metadata_field_info: List[AttributeInfo],
structured_query_translator: Optional[Visitor] = None,
chain_kwargs: Optional[Dict] = None,
enable_limit: bool = False,
use_original_query: bool = False,
**kwargs: Any,
) -> "SelfQueryRetriever":
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
ac31faafcabc-0 | Source code for langchain.retrievers.document_compressors.cohere_rerank
from __future__ import annotations
from typing import TYPE_CHECKING, Dict, Optional, Sequence
from pydantic import Extra, root_validator
from langchain.callbacks.manager import Callbacks
from langchain.retrievers.document_compressors.base import Ba... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html |
ac31faafcabc-1 | self,
documents: Sequence[Document],
query: str,
callbacks: Optional[Callbacks] = None,
) -> Sequence[Document]:
if len(documents) == 0: # to avoid empty api call
return []
doc_list = list(documents)
_docs = [d.page_content for d in doc_list]
resu... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html |
b2b95a2855d6-0 | Source code for langchain.retrievers.document_compressors.chain_filter
"""Filter that uses an LLM to drop documents that aren't relevant to the query."""
from typing import Any, Callable, Dict, Optional, Sequence
from langchain import BasePromptTemplate, LLMChain, PromptTemplate
from langchain.base_language import Base... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html |
b2b95a2855d6-1 | filtered_docs = []
for doc in documents:
_input = self.get_input(query, doc)
include_doc = self.llm_chain.predict_and_parse(
**_input, callbacks=callbacks
)
if include_doc:
filtered_docs.append(doc)
return filtered_docs
[doc... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html |
a650a1e7ad3b-0 | Source code for langchain.retrievers.document_compressors.embeddings_filter
"""Document compressor that uses embeddings to drop documents unrelated to the query."""
from typing import Callable, Dict, Optional, Sequence
import numpy as np
from pydantic import root_validator
from langchain.callbacks.manager import Callba... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html |
a650a1e7ad3b-1 | if values["k"] is None and values["similarity_threshold"] is None:
raise ValueError("Must specify one of `k` or `similarity_threshold`.")
return values
[docs] def compress_documents(
self,
documents: Sequence[Document],
query: str,
callbacks: Optional[Callbacks] = ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html |
e3397df29fbd-0 | Source code for langchain.retrievers.document_compressors.chain_extract
"""DocumentFilter that uses an LLM chain to extract the relevant parts of documents."""
from __future__ import annotations
import asyncio
from typing import Any, Callable, Dict, Optional, Sequence
from langchain import LLMChain, PromptTemplate
from... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
e3397df29fbd-1 | get_input: Callable[[str, Document], dict] = default_get_input
"""Callable for constructing the chain input from the query and a Document."""
[docs] def compress_documents(
self,
documents: Sequence[Document],
query: str,
callbacks: Optional[Callbacks] = None,
) -> Sequence[Do... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
e3397df29fbd-2 | get_input: Optional[Callable[[str, Document], str]] = None,
llm_chain_kwargs: Optional[dict] = None,
) -> LLMChainExtractor:
"""Initialize from LLM."""
_prompt = prompt if prompt is not None else _get_default_chain_prompt()
_get_input = get_input if get_input is not None else default... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
47766083c1cf-0 | Source code for langchain.retrievers.document_compressors.base
"""Interface for retrieved document compressors."""
from abc import ABC, abstractmethod
from inspect import signature
from typing import List, Optional, Sequence, Union
from pydantic import BaseModel
from langchain.callbacks.manager import Callbacks
from la... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html |
47766083c1cf-1 | if isinstance(_transformer, BaseDocumentCompressor):
accepts_callbacks = (
signature(_transformer.compress_documents).parameters.get(
"callbacks"
)
is not None
)
if accepts_callbacks:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html |
977d232a293f-0 | Source code for langchain.utilities.wolfram_alpha
"""Util that calls WolframAlpha."""
from typing import Any, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class WolframAlphaAPIWrapper(BaseModel):
"""Wrapper for Wolfram Alpha.
Docs fo... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html |
977d232a293f-1 | """Run query through WolframAlpha and parse result."""
res = self.wolfram_client.query(query)
try:
assumption = next(res.pods).text
answer = next(res.results).text
except StopIteration:
return "Wolfram Alpha wasn't able to answer it"
if answer is None ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html |
b4d4a337bf0b-0 | Source code for langchain.utilities.bing_search
"""Util that calls Bing Search.
In order to set this up, follow instructions at:
https://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e
"""
from typing import Dict, List
import requests
from pydantic import BaseModel, Extra, ro... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
b4d4a337bf0b-1 | """Validate that api key and endpoint exists in environment."""
bing_subscription_key = get_from_dict_or_env(
values, "bing_subscription_key", "BING_SUBSCRIPTION_KEY"
)
values["bing_subscription_key"] = bing_subscription_key
bing_search_url = get_from_dict_or_env(
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
b4d4a337bf0b-2 | metadata_result = {
"snippet": result["snippet"],
"title": result["name"],
"link": result["url"],
}
metadata_results.append(metadata_result)
return metadata_results | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
c37eebb68728-0 | Source code for langchain.utilities.zapier
"""Util that can interact with Zapier NLA.
Full docs here: https://nla.zapier.com/start/
Note: this wrapper currently only implemented the `api_key` auth method for testing
and server-side production use cases (using the developer's connected accounts on
Zapier.com)
For use-ca... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
c37eebb68728-1 | your own provider and generate credentials.
"""
zapier_nla_api_key: str
zapier_nla_oauth_access_token: str
zapier_nla_api_base: str = "https://nla.zapier.com/api/v1/"
[docs] class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
def _format_headers(self) ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
c37eebb68728-2 | {
"instructions": instructions,
}
)
if preview_only:
data.update({"preview_only": True})
return data
def _create_action_url(self, action_id: str) -> str:
"""Create a url for an action."""
return self.zapier_nla_api_base + f"exposed/{act... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
c37eebb68728-3 | return values
[docs] async def alist(self) -> List[Dict]:
"""Returns a list of all exposed (enabled) actions associated with
current user (associated with the set api_key). Change your exposed
actions here: https://nla.zapier.com/demo/start/
The return list can be empty if no actions ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
c37eebb68728-4 | """
session = self._get_session()
try:
response = session.get(self.zapier_nla_api_base + "exposed/")
response.raise_for_status()
except requests.HTTPError as http_err:
if response.status_code == 401:
if self.zapier_nla_oauth_access_token:
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
c37eebb68728-5 | ) -> Dict:
"""Executes an action that is identified by action_id, must be exposed
(enabled) by the current user (associated with the set api_key). Change
your exposed actions here: https://nla.zapier.com/demo/start/
The return JSON is guaranteed to be less than ~500 words (350
to... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
c37eebb68728-6 | response = await self._arequest(
"POST",
self._create_action_url(action_id),
json=self._create_action_payload(instructions, params, preview_only=True),
)
return response["result"]
[docs] def run_as_str(self, *args, **kwargs) -> str: # type: ignore[no-untyped-def]
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
c37eebb68728-7 | """Same as list, but returns a stringified version of the JSON for
insertting back into an LLM."""
actions = self.list()
return json.dumps(actions)
[docs] async def alist_as_str(self) -> str: # type: ignore[no-untyped-def]
"""Same as list, but returns a stringified version of the JSO... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
25e0f3253b65-0 | Source code for langchain.utilities.apify
from typing import Any, Callable, Dict, Optional
from pydantic import BaseModel, root_validator
from langchain.document_loaders import ApifyDatasetLoader
from langchain.document_loaders.base import Document
from langchain.utils import get_from_dict_or_env
[docs]class ApifyWrapp... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
25e0f3253b65-1 | *,
build: Optional[str] = None,
memory_mbytes: Optional[int] = None,
timeout_secs: Optional[int] = None,
) -> ApifyDatasetLoader:
"""Run an Actor on the Apify platform and wait for results to be ready.
Args:
actor_id (str): The ID or name of the Actor on the Apify... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
25e0f3253b65-2 | memory_mbytes: Optional[int] = None,
timeout_secs: Optional[int] = None,
) -> ApifyDatasetLoader:
"""Run an Actor on the Apify platform and wait for results to be ready.
Args:
actor_id (str): The ID or name of the Actor on the Apify platform.
run_input (Dict): The inp... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
25e0f3253b65-3 | timeout_secs: Optional[int] = None,
) -> ApifyDatasetLoader:
"""Run a saved Actor task on Apify and wait for results to be ready.
Args:
task_id (str): The ID or name of the task on the Apify platform.
task_input (Dict): The input object of the task that you're trying to run.
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
25e0f3253b65-4 | timeout_secs: Optional[int] = None,
) -> ApifyDatasetLoader:
"""Run a saved Actor task on Apify and wait for results to be ready.
Args:
task_id (str): The ID or name of the task on the Apify platform.
task_input (Dict): The input object of the task that you're trying to run.
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
1e456a6bbf90-0 | Source code for langchain.utilities.powerbi
"""Wrapper around a Power BI endpoint."""
from __future__ import annotations
import asyncio
import logging
import os
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union
import aiohttp
import requests
from aiohttp import ServerTimeoutError
from pydanti... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
1e456a6bbf90-1 | def fix_table_names(cls, table_names: List[str]) -> List[str]:
"""Fix the table names."""
return [fix_table_name(table) for table in table_names]
[docs] @root_validator(pre=True, allow_reuse=True)
def token_or_credential_present(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Validate ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
1e456a6bbf90-2 | except Exception as exc: # pylint: disable=broad-exception-caught
raise ClientAuthenticationError(
"Could not get a token from the supplied credentials."
) from exc
raise ClientAuthenticationError("No credential or token supplied.")
[docs] def get_table_na... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.