Tony20100/langchain_full huggingface dataset:
Return type
RunnableWithFallbacksT[Input, Output]
with_listeners(*, on_start: Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]] = None, on_end: Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]] = None, on_error: Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]] = None) → Runnable[Input, Output][source]¶
Bind lifecycle listeners to a Runnable, returning a new Runnable.
on_start: Called before the runnable starts running, with the Run object.
on_end: Called after the runnable finishes running, with the Run object.
on_error: Called if the runnable throws an error, with the Run object.
The Run object contains information about the run, including its id,
type, input, output, error, start_time, end_time, and any tags or metadata
added to the run.
Example:
from langchain_core.runnables import RunnableLambda
from langchain_core.tracers.schemas import Run
import time
def test_runnable(time_to_sleep : int):
    time.sleep(time_to_sleep)
def fn_start(run_obj: Run):
    print("start_time:", run_obj.start_time)
def fn_end(run_obj: Run):
    print("end_time:", run_obj.end_time)
chain = RunnableLambda(test_runnable).with_listeners(
    on_start=fn_start,
    on_end=fn_end
)
chain.invoke(2)
Parameters
on_start (Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]]) – 
on_end (Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]]) –
on_error (Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]]) – 
Return type
Runnable[Input, Output]
with_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) → Runnable[Input, Output][source]¶
Create a new Runnable that retries the original runnable on exceptions.
Example:
from langchain_core.runnables import RunnableLambda
count = 0
def _lambda(x: int) -> None:
    global count
    count = count + 1
    if x == 1:
        raise ValueError("x is 1")
    else:
         pass
runnable = RunnableLambda(_lambda)
try:
    runnable.with_retry(
        stop_after_attempt=2,
        retry_if_exception_type=(ValueError,),
    ).invoke(1)
except ValueError:
    pass
assert (count == 2)
Parameters
retry_if_exception_type (Tuple[Type[BaseException], ...]) – A tuple of exception types to retry on
wait_exponential_jitter (bool) – Whether to add jitter to the wait time
between retries
stop_after_attempt (int) – The maximum number of attempts to make before giving up
Returns
A new Runnable that retries the original runnable on exceptions.
Return type
Runnable[Input, Output]
with_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) → Runnable[Input, Output][source]¶
Bind input and output types to a Runnable, returning a new Runnable.
Parameters
input_type (Optional[Type[Input]]) –
langchain_core.runnables.utils.ConfigurableFieldMultiOption¶
class langchain_core.runnables.utils.ConfigurableFieldMultiOption(id: str, options: Mapping[str, Any], default: Sequence[str], name: Optional[str] = None, description: Optional[str] = None, is_shared: bool = False)[source]¶
Field that can be configured by the user with multiple default values.
Create new instance of ConfigurableFieldMultiOption(id, options, default, name, description, is_shared)
Attributes
default
Alias for field number 2
description
Alias for field number 4
id
Alias for field number 0
is_shared
Alias for field number 5
name
Alias for field number 3
options
Alias for field number 1
Methods
__init__()
count(value, /)
Return number of occurrences of value.
index(value[, start, stop])
Return first index of value.
Parameters
id (str) – 
options (Mapping[str, Any]) – 
default (Sequence[str]) – 
name (Optional[str]) – 
description (Optional[str]) – 
is_shared (bool) – 
__init__()¶
count(value, /)¶
Return number of occurrences of value.
index(value, start=0, stop=9223372036854775807, /)¶
Return first index of value.
Raises ValueError if the value is not present.
langchain_core.runnables.configurable.prefix_config_spec¶
langchain_core.runnables.configurable.prefix_config_spec(spec: ConfigurableFieldSpec, prefix: str) → ConfigurableFieldSpec[source]¶
Prefix the id of a ConfigurableFieldSpec.
This is useful when a RunnableConfigurableAlternatives is used as a
ConfigurableField of another RunnableConfigurableAlternatives.
Parameters
spec (ConfigurableFieldSpec) – The ConfigurableFieldSpec to prefix.
prefix (str) – The prefix to add.
Return type
ConfigurableFieldSpec
Returns:
langchain_core.runnables.base.RunnableBinding¶
class langchain_core.runnables.base.RunnableBinding[source]¶
Bases: RunnableBindingBase[Input, Output]
Wrap a Runnable with additional functionality.
A RunnableBinding can be thought of as a “runnable decorator” that
preserves the essential features of Runnable; i.e., batching, streaming,
and async support, while adding additional functionality.
Any class that inherits from Runnable can be bound to a RunnableBinding.
Runnables expose a standard set of methods for creating RunnableBindings
or sub-classes of RunnableBindings (e.g., RunnableRetry,
RunnableWithFallbacks) that add additional functionality.
These methods include:
- bind: Bind kwargs to pass to the underlying runnable when running it.
- with_config: Bind config to pass to the underlying runnable when running it.
- with_listeners:  Bind lifecycle listeners to the underlying runnable.
- with_types: Override the input and output types of the underlying runnable.
- with_retry: Bind a retry policy to the underlying runnable.
- with_fallbacks: Bind a fallback policy to the underlying runnable.
Example:
bind: Bind kwargs to pass to the underlying runnable when running it.
# Create a runnable binding that invokes the ChatModel with the
# additional kwarg `stop=['-']` when running it.
from langchain_community.chat_models import ChatOpenAI
model = ChatOpenAI()
model.invoke('Say "Parrot-MAGIC"', stop=['-']) # Should return `Parrot`
# Using it the easy way via `bind` method which returns a new
# RunnableBinding
runnable_binding = model.bind(stop=['-'])
runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
Can also be done by instantiating a RunnableBinding directly (not recommended):
Can also be done by instantiating a RunnableBinding directly (not recommended):
from langchain_core.runnables import RunnableBinding
runnable_binding = RunnableBinding(
    bound=model,
    kwargs={'stop': ['-']} # <-- Note the additional kwargs
)
runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
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]¶
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][source]¶
Bind additional kwargs to a Runnable, returning a new Runnable.
Parameters
**kwargs (Any) – The kwargs to bind to the Runnable.
Returns
A new Runnable with the same type and config as the original,
but with the additional kwargs bound.
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]
configurable_alternatives(which: ConfigurableField, *, default_key: str = 'default', prefix_keys: bool = False, **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) → RunnableSerializable[Input, Output]¶
Configure alternatives for runnables that can be set at runtime.
from langchain_anthropic import ChatAnthropic
from langchain_core.runnables.utils import ConfigurableField
from langchain_openai import ChatOpenAI
model = ChatAnthropic(
    model_name="claude-3-sonnet-20240229"
).configurable_alternatives(
    ConfigurableField(id="llm"),
).configurable_alternatives(
    ConfigurableField(id="llm"),
    default_key="anthropic",
    openai=ChatOpenAI()
)
# uses the default model ChatAnthropic
print(model.invoke("which organization created you?").content)
# uses ChatOpenAI
print(
    model.with_config(
        configurable={"llm": "openai"}
    ).invoke("which organization created you?").content
)
Parameters
which (ConfigurableField) – 
default_key (str) – 
prefix_keys (bool) – 
kwargs (Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) – 
Return type
RunnableSerializable[Input, Output]
configurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) → RunnableSerializable[Input, Output]¶
Configure particular runnable fields at runtime.
from langchain_core.runnables import ConfigurableField
from langchain_openai import ChatOpenAI
model = ChatOpenAI(max_tokens=20).configurable_fields(
    max_tokens=ConfigurableField(
        id="output_token_number",
        name="Max tokens in the output",
        description="The maximum number of tokens in the output",
    )
)
# max_tokens = 20
print(
    "max_tokens_20: ",
    model.invoke("tell me something about chess").content
)
# max_tokens = 200
print("max_tokens_200: ", model.with_config(
    configurable={"output_token_number": 200}
    ).invoke("tell me something about chess").content
)
Parameters
kwargs (Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) – 
Return type
RunnableSerializable[Input, Output]
Return type
RunnableSerializable[Input, Output]
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
new model instance
Return type
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_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.
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.
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¶
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]¶
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¶
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
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¶
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) – 
dumps_kwargs (Any) – 
Return type
unicode
classmethod lc_id() → List[str]¶
A unique identifier for this class for serialization purposes.
The unique identifier is a list of strings that describes the path
to the object.
Return type
List[str]
map() → Runnable[List[Input], List[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: 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 (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.
on_start: Asynchronously called before the runnable starts running.
on_end: Asynchronously called after the runnable finishes running.
on_error: Asynchronously called if the runnable throws an error.
The Run object contains information about the run, including its id,
The Run object contains information about the run, including its id,
type, input, output, error, start_time, end_time, and any tags or metadata
added to the run.
Example:
Parameters
on_start (Optional[AsyncListener]) – 
on_end (Optional[AsyncListener]) – 
on_error (Optional[AsyncListener]) – 
Return type
Runnable[Input, Output]
with_config(config: Optional[RunnableConfig] = None, **kwargs: Any) → Runnable[Input, Output][source]¶
Bind config to a Runnable, returning a new Runnable.
Parameters
config (Optional[RunnableConfig]) – 
kwargs (Any) – 
Return type
Runnable[Input, Output]
with_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,), exception_key: Optional[str] = None) → RunnableWithFallbacksT[Input, Output]¶
Add fallbacks to a runnable, returning a new Runnable.
Example
from typing import Iterator
from langchain_core.runnables import RunnableGenerator
def _generate_immediate_error(input: Iterator) -> Iterator[str]:
    raise ValueError()
    yield ""
def _generate(input: Iterator) -> Iterator[str]:
    yield from "foo bar"
runnable = RunnableGenerator(_generate_immediate_error).with_fallbacks(
    [RunnableGenerator(_generate)]
    )
print(''.join(runnable.stream({}))) #foo bar
Parameters
fallbacks (Sequence[Runnable[Input, Output]]) – A sequence of runnables to try if the original runnable fails.
exceptions_to_handle (Tuple[Type[BaseException], ...]) – A tuple of exception types to handle.
exception_key (Optional[str]) – If string is specified then handled exceptions will be passed
to fallbacks as part of the input under the specified key. If None,
exceptions will not be passed to fallbacks. If used, the base runnable
and its fallbacks must accept a dictionary as input.
Returns
A new Runnable that will try the original runnable, and then each
fallback in order, upon failures.
Return type
RunnableWithFallbacksT[Input, Output]
with_listeners(*, on_start: Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]] = None, on_end: Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]] = None, on_error: Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]] = None) → Runnable[Input, Output][source]¶
Bind lifecycle listeners to a Runnable, returning a new Runnable.
Parameters
on_start (Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]]) – Called before the runnable starts running, with the Run object.
on_end (Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]]) – Called after the runnable finishes running, with the Run object.
on_error (Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]]) – Called if the runnable throws an error, with the Run object.
Returns
The Run object contains information about the run, including its id,
type, input, output, error, start_time, end_time, and any tags or metadata
added to the run.
Return type
Runnable[Input, Output]
with_retry(**kwargs: Any) → Runnable[Input, Output][source]¶
with_retry(**kwargs: Any) → Runnable[Input, Output][source]¶
Create a new Runnable that retries the original runnable on exceptions.
Example:
from langchain_core.runnables import RunnableLambda
count = 0
def _lambda(x: int) -> None:
    global count
    count = count + 1
    if x == 1:
        raise ValueError("x is 1")
    else:
         pass
runnable = RunnableLambda(_lambda)
try:
    runnable.with_retry(
        stop_after_attempt=2,
        retry_if_exception_type=(ValueError,),
    ).invoke(1)
except ValueError:
    pass
assert (count == 2)
Parameters
retry_if_exception_type – A tuple of exception types to retry on
wait_exponential_jitter – Whether to add jitter to the wait time
between retries
stop_after_attempt – The maximum number of attempts to make before giving up
kwargs (Any) – 
Returns
A new Runnable that retries the original runnable on exceptions.
Return type
Runnable[Input, Output]
with_types(input_type: Optional[Union[Type[Input], BaseModel]] = None, output_type: Optional[Union[Type[Output], BaseModel]] = None) → Runnable[Input, Output][source]¶
Bind input and output types to a Runnable, returning a new Runnable.
Parameters
input_type (Optional[Union[Type[Input], BaseModel]]) – 
output_type (Optional[Union[Type[Output], BaseModel]]) – 
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.
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.