Tony20100/langchain_full huggingface dataset:
langchain_core.runnables.passthrough.RunnableAssign¶
class langchain_core.runnables.passthrough.RunnableAssign[source]¶
Bases: RunnableSerializable[Dict[str, Any], Dict[str, Any]]
Runnable that assigns key-value pairs to Dict[str, Any] inputs.
The RunnableAssign class takes input dictionaries and, through a
RunnableParallel instance, applies transformations, then combines
these with the original data, introducing new key-value pairs based
on the mapper’s logic.
Examples
# This is a RunnableAssign
from typing import Dict
from langchain_core.runnables.passthrough import (
    RunnableAssign,
    RunnableParallel,
)
from langchain_core.runnables.base import RunnableLambda
def add_ten(x: Dict[str, int]) -> Dict[str, int]:
    return {"added": x["input"] + 10}
mapper = RunnableParallel(
    {"add_step": RunnableLambda(add_ten),}
)
runnable_assign = RunnableAssign(mapper)
# Synchronous example
runnable_assign.invoke({"input": 5})
# returns {'input': 5, 'add_step': {'added': 15}}
# Asynchronous example
await runnable_assign.ainvoke({"input": 5})
# returns {'input': 5, 'add_step': {'added': 15}}
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 mapper: RunnableParallel[Dict[str, Any]] [Required]¶
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.
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 ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) → Dict[str, Any][source]¶
Default implementation of ainvoke, calls invoke from a thread.
The default implementation allows usage of async code even if
the runnable did not implement a native async version of invoke.
Subclasses should override this method if they can run asynchronously.
Parameters
input (Dict[str, Any]) – 
config (Optional[RunnableConfig]) – 
kwargs (Any) – 
Return type
Dict[str, Any]
kwargs (Any) – 
Return type
Dict[str, Any]
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':
{'question': {'title': 'Question', 'type': 'string'}}}
print(chain_with_assign.output_schema.schema()) #
{'title': 'RunnableSequenceOutput', 'type': 'object', 'properties':
{'str': {'title': 'Str',
'type': 'string'}, 'hello': {'title': 'Hello', 'type': 'string'}}}
Parameters
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]]]]) – 
Return type
RunnableSerializable[Any, Any]
Return type
RunnableSerializable[Any, Any]
async astream(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) → AsyncIterator[Dict[str, Any]][source]¶
Default implementation of astream, which calls ainvoke.
Subclasses should override this method if they support streaming output.
Parameters
input (Dict[str, Any]) – 
config (Optional[RunnableConfig]) – 
kwargs (Any) – 
Return type
AsyncIterator[Dict[str, Any]]
astream_events(input: Any, config: Optional[RunnableConfig] = None, *, version: Literal['v1', 'v2'], include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Any) → AsyncIterator[StreamEvent]¶
[Beta] Generate a stream of events.
Use to create an iterator over StreamEvents that provide real-time information
about the progress of the runnable, including StreamEvents from intermediate
results.
A StreamEvent is a dictionary with the following schema:
event: str - Event names are of theformat: on_[runnable_type]_(start|stream|end).
name: str - The name of the runnable that generated the event.
run_id: str - randomly generated ID associated with the given execution ofthe runnable that emitted the event.
A child runnable that gets invoked as part of the execution of a
parent runnable is assigned its own unique ID.
parent_ids: List[str] - The IDs of the parent runnables thatgenerated the event. The root runnable will have an empty list.
exclude_tags (Optional[Sequence[str]]) – Exclude logs with these tags.
kwargs (Any) – 
Return type
Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]
async atransform(input: AsyncIterator[Dict[str, Any]], config: Optional[RunnableConfig] = None, **kwargs: Any) → AsyncIterator[Dict[str, Any]][source]¶
Default implementation of atransform, which buffers input and calls astream.
Subclasses should override this method if they can start producing output while
input is still being generated.
Parameters
input (AsyncIterator[Dict[str, Any]]) – 
config (Optional[RunnableConfig]) – 
kwargs (Any) – 
Return type
AsyncIterator[Dict[str, Any]]
batch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶
Default implementation runs invoke in parallel using a thread pool executor.
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]
batch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → Iterator[Tuple[int, Union[Output, Exception]]]¶
Run invoke in parallel on a list of inputs,
yielding results as they complete.
Parameters
Runnables that leverage the configurable_fields and configurable_alternatives
methods will have a dynamic input schema that depends on which
configuration the runnable is invoked with.
This method allows to get an input schema for a specific configuration.
Parameters
config (Optional[RunnableConfig]) – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate input.
Return type
Type[BaseModel]
classmethod get_lc_namespace() → List[str][source]¶
Get the namespace of the langchain object.
Return type
List[str]
get_name(suffix: Optional[str] = None, *, name: Optional[str] = None) → str[source]¶
Get the name of the runnable.
Parameters
suffix (Optional[str]) – 
name (Optional[str]) – 
Return type
str
get_output_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel][source]¶
Get a pydantic model that can be used to validate output to the runnable.
Runnables that leverage the configurable_fields and configurable_alternatives
methods will have a dynamic output schema that depends on which
configuration the runnable is invoked with.
This method allows to get an output schema for a specific configuration.
Parameters
config (Optional[RunnableConfig]) – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate output.
Return type
Type[BaseModel]
get_prompts(config: Optional[RunnableConfig] = None) → List[BasePromptTemplate]¶
Parameters
config (Optional[RunnableConfig]) – 
Return type
List[BasePromptTemplate]
invoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) → Dict[str, Any][source]¶
Transform a single input into an output. Override to implement.
Parameters
input (Dict[str, Any]) – The input to the runnable.
config (Optional[RunnableConfig]) – A config to use when invoking the runnable.
The config supports standard keys like ‘tags’, ‘metadata’ for tracing
purposes, ‘max_concurrency’ for controlling how much work to do
in parallel, and other keys. Please refer to the RunnableConfig
for more details.
kwargs (Any) – 
Returns
The output of the runnable.
Return type
Dict[str, Any]
classmethod is_lc_serializable() → bool[source]¶
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]]) – 
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
by_alias (bool) – 
skip_defaults (Optional[bool]) – 
exclude_unset (bool) – 
exclude_defaults (bool) – 
exclude_none (bool) – 
encoder (Optional[Callable[[Any], Any]]) – 
models_as_dict (bool) –
Parameters
by_alias (bool) – 
ref_template (unicode) – 
dumps_kwargs (Any) – 
Return type
unicode
stream(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) → Iterator[Dict[str, Any]][source]¶
Default implementation of stream, which calls invoke.
Subclasses should override this method if they support streaming output.
Parameters
input (Dict[str, Any]) – 
config (Optional[RunnableConfig]) – 
kwargs (Any) – 
Return type
Iterator[Dict[str, Any]]
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[Dict[str, Any]], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Iterator[Dict[str, Any]][source]¶
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[Dict[str, Any]]) – 
config (Optional[RunnableConfig]) – 
kwargs (Optional[Any]) – 
Return type
Iterator[Dict[str, Any]]
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
langchain_core.runnables.base.RunnableBindingBase¶
class langchain_core.runnables.base.RunnableBindingBase[source]¶
Bases: RunnableSerializable[Input, Output]
Runnable that delegates calls to another Runnable with a set of kwargs.
Use only if creating a new RunnableBinding subclass with different __init__ args.
See documentation for RunnableBinding for more details.
Create a RunnableBinding from a runnable and kwargs.
Parameters
bound – The underlying runnable that this runnable delegates calls to.
kwargs – optional kwargs to pass to the underlying runnable, when running
the underlying runnable (e.g., via invoke, batch,
transform, or stream or async variants)
config – config_factories:
config_factories – optional list of config factories to apply to the
custom_input_type – Specify to override the input type of the underlying
runnable with a custom type.
custom_output_type – Specify to override the output type of the underlying
runnable with a custom type.
**other_kwargs – Unpacked into the base class.
param bound: Runnable[Input, Output] [Required]¶
The underlying runnable that this runnable delegates to.
param config: RunnableConfig [Optional]¶
The config to bind to the underlying runnable.
param config_factories: List[Callable[[RunnableConfig], RunnableConfig]] [Optional]¶
The config factories to bind to the underlying runnable.
param custom_input_type: Optional[Any] = None¶
Override the input type of the underlying runnable with a custom type.
The type can be a pydantic model, or a type annotation (e.g., List[str]).
param custom_output_type: Optional[Any] = None¶
Override the output type of the underlying runnable with a custom type.
The type can be a pydantic model, or a type annotation (e.g., List[str]).
param kwargs: Mapping[str, Any] [Optional]¶
kwargs to pass to the underlying runnable when running.
For example, when the runnable binding is invoked the underlying
runnable will be invoked with the same input but with these additional
kwargs.
async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output][source]¶
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: Literal[False] = False, **kwargs: Optional[Any]) → AsyncIterator[Tuple[int, Output]][source]¶
async abatch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: Literal[True], **kwargs: Optional[Any]) → AsyncIterator[Tuple[int, Union[Output, Exception]]]
Run ainvoke in parallel on a list of inputs,
yielding results as they complete.
async ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Output[source]¶
Default implementation of ainvoke, calls invoke from a thread.
Parameters
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]]]]) – 
Return type
RunnableSerializable[Any, Any]
async astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[Output][source]¶
Default implementation of astream, which calls ainvoke.
Subclasses should override this method if they support streaming output.
Parameters
input (Input) – 
config (Optional[RunnableConfig]) – 
kwargs (Optional[Any]) – 
Return type
AsyncIterator[Output]
async astream_events(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[StreamEvent][source]¶
[Beta] Generate a stream of events.
Use to create an iterator over StreamEvents that provide real-time information
about the progress of the runnable, including StreamEvents from intermediate
results.
A StreamEvent is a dictionary with the following schema:
event: str - Event names are of theformat: on_[runnable_type]_(start|stream|end).
name: str - The name of the runnable that generated the event.
run_id: str - randomly generated ID associated with the given execution ofthe runnable that emitted the event.
A child runnable that gets invoked as part of the execution of a
parent runnable is assigned its own unique ID.
parent_ids: List[str] - The IDs of the parent runnables thatgenerated the event. The root runnable will have an empty list.
The order of the parent IDs is from the root to the immediate parent.
Only available for v2 version of the API. The v1 version of the API
will return an empty list.
exclude_tags (Optional[Sequence[str]]) – Exclude logs with these tags.
kwargs (Any) – 
Return type
Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]
async atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) → AsyncIterator[Output][source]¶
Default implementation of atransform, which buffers input and calls astream.
Subclasses should override this method if they can start producing output while
input is still being generated.
Parameters
input (AsyncIterator[Input]) – 
config (Optional[RunnableConfig]) – 
kwargs (Any) – 
Return type
AsyncIterator[Output]
batch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output][source]¶
Default implementation runs invoke in parallel using a thread pool executor.
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]
batch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: Literal[False] = False, **kwargs: Any) → Iterator[Tuple[int, Output]][source]¶
batch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: Literal[True], **kwargs: Any) → Iterator[Tuple[int, Union[Output, Exception]]]
Run invoke in parallel on a list of inputs,
yielding results as they complete.
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]
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
A pydantic model that can be used to validate config.
Return type
Type[BaseModel]
Runnables that leverage the configurable_fields and configurable_alternatives
methods will have a dynamic input schema that depends on which
configuration the runnable is invoked with.
This method allows to get an input schema for a specific configuration.
Parameters
config (Optional[RunnableConfig]) – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate input.
Return type
Type[BaseModel]
classmethod get_lc_namespace() → List[str][source]¶
Get the namespace of the langchain object.
Return type
List[str]
get_name(suffix: Optional[str] = None, *, name: Optional[str] = None) → str[source]¶
Get the name of the runnable.
Parameters
suffix (Optional[str]) – 
name (Optional[str]) – 
Return type
str
get_output_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel][source]¶
Get a pydantic model that can be used to validate output to the runnable.
Runnables that leverage the configurable_fields and configurable_alternatives
methods will have a dynamic output schema that depends on which
configuration the runnable is invoked with.
This method allows to get an output schema for a specific configuration.
Parameters
config (Optional[RunnableConfig]) – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate output.
Return type
Type[BaseModel]
get_prompts(config: Optional[RunnableConfig] = None) → List[BasePromptTemplate]¶
Parameters
config (Optional[RunnableConfig]) – 
Return type
List[BasePromptTemplate]
invoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Output[source]¶
Transform a single input into an output. Override to implement.
Parameters
Transform a single input into an output. Override to implement.
Parameters
input (Input) – The input to the runnable.
config (Optional[RunnableConfig]) – A config to use when invoking the runnable.
The config supports standard keys like ‘tags’, ‘metadata’ for tracing
purposes, ‘max_concurrency’ for controlling how much work to do
in parallel, and other keys. Please refer to the RunnableConfig
for more details.
kwargs (Optional[Any]) – 
Returns
The output of the runnable.
Return type
Output
classmethod is_lc_serializable() → bool[source]¶
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]]) – 
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
by_alias (bool) – 
skip_defaults (Optional[bool]) – 
exclude_unset (bool) – 
exclude_defaults (bool) – 
exclude_none (bool) – 
encoder (Optional[Callable[[Any], Any]]) – 
models_as_dict (bool) –