Tony20100/langchain_full huggingface dataset:
langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever¶
class langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever[source]¶
Bases: BaseRetriever
Retriever that combines embedding similarity with
recency in retrieving values.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param decay_rate: float = 0.01¶
The exponential decay factor used as (1.0-decay_rate)**(hrs_passed).
param 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.
param k: int = 4¶
The maximum number of documents to retrieve in a given call.
param memory_stream: List[Document] [Optional]¶
The memory_stream of documents to search through.
param metadata: Optional[Dict[str, Any]] = None¶
Optional metadata associated with the retriever. Defaults to None
This metadata will be associated with each call to this retriever,
and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a retriever with its
use case.
param other_score_keys: List[str] = []¶
Other keys in the metadata to factor into the score, e.g. ‘importance’.
param search_kwargs: dict [Optional]¶
Keyword arguments to pass to the vectorstore similarity search.
param tags: Optional[List[str]] = None¶
Optional list of tags associated with the retriever. Defaults to None
These tags will be associated with each call to this retriever,
and passed as arguments to the handlers defined in callbacks.
and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a retriever with its
use case.
param vectorstore: VectorStore [Required]¶
The vectorstore to store documents and determine salience.
async aadd_documents(documents: List[Document], **kwargs: Any) → List[str][source]¶
Add documents to vectorstore.
Parameters
documents (List[Document]) – 
kwargs (Any) – 
Return type
List[str]
async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶
Default implementation runs ainvoke in parallel using asyncio.gather.
The default implementation of batch works well for IO bound runnables.
Subclasses should override this method if they can batch more efficiently;
e.g., if the underlying runnable uses an API which supports a batch mode.
Parameters
inputs (List[Input]) – 
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
List[Output]
async abatch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → AsyncIterator[Tuple[int, Union[Output, Exception]]]¶
Run ainvoke in parallel on a list of inputs,
yielding results as they complete.
Parameters
inputs (Sequence[Input]) – 
config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
AsyncIterator[Tuple[int, Union[Output, Exception]]]
add_documents(documents: List[Document], **kwargs: Any) → List[str][source]¶
Add documents to vectorstore.
Parameters
documents (List[Document]) – 
kwargs (Any) – 
Return type
List[str]
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) → List[Document]¶
[Deprecated] Asynchronously get documents relevant to a query.
Users should favor using .ainvoke or .abatch rather than
aget_relevant_documents directly.
Parameters
query (str) – string to find relevant documents for
callbacks (Callbacks) – Callback manager or list of callbacks
tags (Optional[List[str]]) – Optional list of tags associated with the retriever. Defaults to None
These tags will be associated with each call to this retriever,
and passed as arguments to the handlers defined in callbacks.
metadata (Optional[Dict[str, Any]]) – Optional metadata associated with the retriever. Defaults to None
This metadata will be associated with each call to this retriever,
and passed as arguments to the handlers defined in callbacks.
run_name (Optional[str]) – Optional name for the run.
kwargs (Any) – 
Returns
List of relevant documents
Return type
List[Document]
Notes
Deprecated since version langchain-core==0.1.46: Use ainvoke instead.
async aget_salient_docs(query: str) → Dict[int, Tuple[Document, float]][source]¶
Return documents that are salient to the query.
Parameters
Return documents that are salient to the query.
Parameters
query (str) – 
Return type
Dict[int, Tuple[Document, float]]
async ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Any) → List[Document]¶
Asynchronously invoke the retriever to get relevant documents.
Main entry point for asynchronous retriever invocations.
Parameters
input (str) – The query string
config (Optional[RunnableConfig]) – Configuration for the retriever
**kwargs (Any) – Additional arguments to pass to the retriever
Returns
List of relevant documents
Return type
List[Document]
Examples:
await retriever.ainvoke("query")
assign(**kwargs: Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any], Mapping[str, Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any]]]]) → RunnableSerializable[Any, Any]¶
Assigns new fields to the dict output of this runnable.
Returns a new runnable.
from langchain_community.llms.fake import FakeStreamingListLLM
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import SystemMessagePromptTemplate
from langchain_core.runnables import Runnable
from operator import itemgetter
prompt = (
    SystemMessagePromptTemplate.from_template("You are a nice assistant.")
    + "{question}"
)
llm = FakeStreamingListLLM(responses=["foo-lish"])
chain: Runnable = prompt | llm | {"str": StrOutputParser()}
chain_with_assign = chain.assign(hello=itemgetter("str") | llm)
print(chain_with_assign.input_schema.schema())
# {'title': 'PromptInput', 'type': 'object', 'properties':
Returns
List of relevant documents
Return type
List[Document]
Notes
Deprecated since version langchain-core==0.1.46: Use invoke instead.
get_salient_docs(query: str) → Dict[int, Tuple[Document, float]][source]¶
Return documents that are salient to the query.
Parameters
query (str) – 
Return type
Dict[int, Tuple[Document, float]]
invoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Any) → List[Document]¶
Invoke the retriever to get relevant documents.
Main entry point for synchronous retriever invocations.
Parameters
input (str) – The query string
config (Optional[RunnableConfig]) – Configuration for the retriever
**kwargs (Any) – Additional arguments to pass to the retriever
Returns
List of relevant documents
Return type
List[Document]
Examples:
retriever.invoke("query")
classmethod is_lc_serializable() → bool¶
Is this class serializable?
Return type
bool
json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶
Generate a JSON representation of the model, include and exclude arguments as per dict().
encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) –
output_type (Optional[Type[Output]]) – 
Return type
Runnable[Input, Output]
property InputType: Type[Input]¶
The type of input this runnable accepts specified as a type annotation.
property OutputType: Type[Output]¶
The type of output this runnable produces specified as a type annotation.
property config_specs: List[ConfigurableFieldSpec]¶
List configurable fields for this runnable.
property input_schema: Type[BaseModel]¶
The type of input this runnable accepts specified as a pydantic model.
property lc_attributes: Dict¶
List of attribute names that should be included in the serialized kwargs.
These attributes must be accepted by the constructor.
property lc_secrets: Dict[str, str]¶
A map of constructor argument names to secret ids.
For example,{“openai_api_key”: “OPENAI_API_KEY”}
name: Optional[str] = None¶
The name of the runnable. Used for debugging and tracing.
property output_schema: Type[BaseModel]¶
The type of output this runnable produces specified as a pydantic model.
Examples using TimeWeightedVectorStoreRetriever¶
How to use a time-weighted vector store retriever
langchain_community.retrievers.web_research.SearchQueries¶
class langchain_community.retrievers.web_research.SearchQueries[source]¶
Bases: BaseModel
Search queries to research for the user’s goal.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param queries: List[str] [Required]¶
List of search queries to look up on Google
classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) – 
values (Any) – 
Return type
Model
copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to include in new model
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include
update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating
the new model: you should trust this data
deep (bool) – set to True to make a deep copy of the model
self (Model) – 
Returns
langchain_community.retrievers.web_research.WebResearchRetriever¶
class langchain_community.retrievers.web_research.WebResearchRetriever[source]¶
Bases: BaseRetriever
Google Search API retriever.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param llm_chain: LLMChain [Required]¶
param metadata: Optional[Dict[str, Any]] = None¶
Optional metadata associated with the retriever. Defaults to None
This metadata will be associated with each call to this retriever,
and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a retriever with its
use case.
param num_search_results: int = 1¶
Number of pages per Google search
param search: GoogleSearchAPIWrapper [Required]¶
Google Search API Wrapper
param tags: Optional[List[str]] = None¶
Optional list of tags associated with the retriever. Defaults to None
These tags will be associated with each call to this retriever,
and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a retriever with its
use case.
param text_splitter: TextSplitter = <langchain_text_splitters.character.RecursiveCharacterTextSplitter object>¶
Text splitter for splitting web pages into chunks
param trust_env: bool = False¶
Whether to use the http_proxy/https_proxy env variables or check .netrc for proxy configuration
param url_database: List[str] [Optional]¶
List of processed URLs
param vectorstore: VectorStore [Required]¶
Vector store for storing web pages
param vectorstore: VectorStore [Required]¶
Vector store for storing web pages
async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶
Default implementation runs ainvoke in parallel using asyncio.gather.
The default implementation of batch works well for IO bound runnables.
Subclasses should override this method if they can batch more efficiently;
e.g., if the underlying runnable uses an API which supports a batch mode.
Parameters
inputs (List[Input]) – 
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
List[Output]
async abatch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → AsyncIterator[Tuple[int, Union[Output, Exception]]]¶
Run ainvoke in parallel on a list of inputs,
yielding results as they complete.
Parameters
inputs (Sequence[Input]) – 
config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
AsyncIterator[Tuple[int, Union[Output, Exception]]]
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) → List[Document]¶
[Deprecated] Asynchronously get documents relevant to a query.
yielding results as they complete.
Parameters
inputs (Sequence[Input]) – 
config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
Iterator[Tuple[int, Union[Output, Exception]]]
bind(**kwargs: Any) → Runnable[Input, Output]¶
Bind arguments to a Runnable, returning a new Runnable.
Useful when a runnable in a chain requires an argument that is not
in the output of the previous runnable or included in the user input.
Example:
from langchain_community.chat_models import ChatOllama
from langchain_core.output_parsers import StrOutputParser
llm = ChatOllama(model='llama2')
# Without bind.
chain = (
    llm
    | StrOutputParser()
)
chain.invoke("Repeat quoted words exactly: 'One two three four five.'")
# Output is 'One two three four five.'
# With bind.
chain = (
    llm.bind(stop=["three"])
    | StrOutputParser()
)
chain.invoke("Repeat quoted words exactly: 'One two three four five.'")
# Output is 'One two'
Parameters
kwargs (Any) – 
Return type
Runnable[Input, Output]
clean_search_query(query: str) → str[source]¶
Parameters
query (str) – 
Return type
str
config_schema(*, include: Optional[Sequence[str]] = None) → Type[BaseModel]¶
The type of config this runnable accepts specified as a pydantic model.
To mark a field as configurable, see the configurable_fields
and configurable_alternatives methods.
Parameters
include (Optional[Sequence[str]]) – A list of fields to include in the config schema.
Returns
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include
update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating
the new model: you should trust this data
deep (bool) – set to True to make a deep copy of the model
self (Model) – 
Returns
new model instance
Return type
Model
dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
by_alias (bool) – 
skip_defaults (Optional[bool]) – 
exclude_unset (bool) – 
exclude_defaults (bool) – 
exclude_none (bool) – 
Return type
DictStrAny
exclude_none (bool) – 
Return type
DictStrAny
classmethod from_llm(vectorstore: ~langchain_core.vectorstores.VectorStore, llm: ~langchain_core.language_models.llms.BaseLLM, search: ~langchain_community.utilities.google_search.GoogleSearchAPIWrapper, prompt: ~typing.Optional[~langchain_core.prompts.base.BasePromptTemplate] = None, num_search_results: int = 1, text_splitter: ~langchain_text_splitters.character.RecursiveCharacterTextSplitter = <langchain_text_splitters.character.RecursiveCharacterTextSplitter object>, trust_env: bool = False) → WebResearchRetriever[source]¶
Initialize from llm using default template.
Parameters
vectorstore (VectorStore) – Vector store for storing web pages
llm (BaseLLM) – llm for search question generation
search (GoogleSearchAPIWrapper) – GoogleSearchAPIWrapper
prompt (Optional[BasePromptTemplate]) – prompt to generating search questions
num_search_results (int) – Number of pages per Google search
text_splitter (RecursiveCharacterTextSplitter) – Text splitter for splitting web pages into chunks
trust_env (bool) – Whether to use the http_proxy/https_proxy env variables
or check .netrc for proxy configuration
Returns
WebResearchRetriever
Return type
WebResearchRetriever
classmethod from_orm(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
Model
get_graph(config: Optional[RunnableConfig] = None) → Graph¶
Return a graph representation of this runnable.
Parameters
config (Optional[RunnableConfig]) – 
Return type
Graph
get_input_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶
Get a pydantic model that can be used to validate input to the runnable.
Example
from langchain_core.runnables import RunnableLambda
def add_one(x: int) -> int:
    return x + 1
def mul_two(x: int) -> int:
    return x * 2
runnable_1 = RunnableLambda(add_one)
runnable_2 = RunnableLambda(mul_two)
sequence = runnable_1.pipe(runnable_2)
# Or equivalently:
# sequence = runnable_1 | runnable_2
# sequence = RunnableSequence(first=runnable_1, last=runnable_2)
sequence.invoke(1)
await sequence.ainvoke(1)
# -> 4
sequence.batch([1, 2, 3])
await sequence.abatch([1, 2, 3])
# -> [4, 6, 8]
Parameters
others (Union[Runnable[Any, Other], Callable[[Any], Other]]) – 
name (Optional[str]) – 
Return type
RunnableSerializable[Input, Other]
classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶
Parameters
by_alias (bool) – 
ref_template (unicode) – 
Return type
DictStrAny
classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶
Parameters
by_alias (bool) – 
ref_template (unicode) – 
dumps_kwargs (Any) – 
Return type
unicode
search_tool(query: str, num_search_results: int = 1) → List[dict][source]¶
Returns num_search_results pages per Google search.
Parameters
query (str) – 
num_search_results (int) – 
Return type
List[dict]
num_search_results (int) – 
Return type
List[dict]
stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Iterator[Output]¶
Default implementation of stream, which calls invoke.
Subclasses should override this method if they support streaming output.
Parameters
input (Input) – 
config (Optional[RunnableConfig]) – 
kwargs (Optional[Any]) – 
Return type
Iterator[Output]
to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶
Serialize the runnable to JSON.
Return type
Union[SerializedConstructor, SerializedNotImplemented]
to_json_not_implemented() → SerializedNotImplemented¶
Return type
SerializedNotImplemented
transform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Iterator[Output]¶
Default implementation of transform, which buffers input and then calls stream.
Subclasses should override this method if they can start producing output while
input is still being generated.
Parameters
input (Iterator[Input]) – 
config (Optional[RunnableConfig]) – 
kwargs (Optional[Any]) – 
Return type
Iterator[Output]
classmethod update_forward_refs(**localns: Any) → None¶
Try to update ForwardRefs on fields based on this Model, globalns and localns.
Parameters
localns (Any) – 
Return type
None
classmethod validate(value: Any) → Model¶
Parameters
value (Any) – 
Return type
Model
with_alisteners(*, on_start: Optional[AsyncListener] = None, on_end: Optional[AsyncListener] = None, on_error: Optional[AsyncListener] = None) → Runnable[Input, Output]¶
Bind asynchronous lifecycle listeners to a Runnable, returning a new Runnable.
langchain_community.retrievers.bm25.BM25Retriever¶
class langchain_community.retrievers.bm25.BM25Retriever[source]¶
Bases: BaseRetriever
BM25 retriever without Elasticsearch.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param docs: List[Document] [Required]¶
List of documents.
param k: int = 4¶
Number of documents to return.
param metadata: Optional[Dict[str, Any]] = None¶
Optional metadata associated with the retriever. Defaults to None
This metadata will be associated with each call to this retriever,
and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a retriever with its
use case.
param preprocess_func: Callable[[str], List[str]] = <function default_preprocessing_func>¶
Preprocessing function to use on the text before BM25 vectorization.
param tags: Optional[List[str]] = None¶
Optional list of tags associated with the retriever. Defaults to None
These tags will be associated with each call to this retriever,
and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a retriever with its
use case.
param vectorizer: Any = None¶
BM25 vectorizer.
async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶
Default implementation runs ainvoke in parallel using asyncio.gather.
The default implementation of batch works well for IO bound runnables.
update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating
the new model: you should trust this data
deep (bool) – set to True to make a deep copy of the model
self (Model) – 
Returns
new model instance
Return type
Model
dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
by_alias (bool) – 
skip_defaults (Optional[bool]) – 
exclude_unset (bool) – 
exclude_defaults (bool) – 
exclude_none (bool) – 
Return type
DictStrAny
classmethod from_documents(documents: ~typing.Iterable[~langchain_core.documents.base.Document], *, bm25_params: ~typing.Optional[~typing.Dict[str, ~typing.Any]] = None, preprocess_func: ~typing.Callable[[str], ~typing.List[str]] = <function default_preprocessing_func>, **kwargs: ~typing.Any) → BM25Retriever[source]¶
Create a BM25Retriever from a list of Documents.
:param documents: A list of Documents to vectorize.
:param bm25_params: Parameters to pass to the BM25 vectorizer.