
    D_icR             	      ,   S r SSKJr  SSKrSSKrSSKrSSKrSSKrSSKrSSK	J
r
Jr  SSKJrJrJrJrJrJrJrJr  SSKJrJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJ r J!r!J"r"J#r#J$r$J%r%J&r&J'r'J(r(J)r)  SSK*J+r+J,r,J-r-J.r.  SSK/J0r0  SSK1J2r2  SSK3J4r4J5r5  SSK6J7r7J8r8J9r9  SSK:J;r;J<r<J=r=J>r>J?r?J@r@JArAJBrBJCrCJDrDJErEJFrF  SSKGJHrHJIrIJJrJJKrKJLrLJMrMJNrNJOrOJPrPJQrQJRrRJSrSJTrTJUrUJVrVJWrWJXrXJYrY  SSKZJ[r[  SSK\J]r]J^r^  SSK_J`r`Jara  SSKbJcrcJdrd  SSKeJfrfJgrg  SSKhJiri  SSKjJkrk  \ (       a@  SSK3JlrlJmrm  SSKnJoro  SSKpJqrr  SSKsJtrt  SSKuJvrv  SSKwJxrx  SS KyJzrz  SS!K_J{r{J|r|  SS"KbJ}r}  SS#K~Jr  \%" S$5      rS%r " S& S'\
\"\L\M4   5      r " S( S)\7\\L\M4   5      r      SJS* jr      SJS+ jrS%r " S, S-\\L\M4   5      r " S. S/\\L\\\!4   4   5      r\r " S0 S1\\L\M4   5      r " S2 S3\\L\M4   5      r " S4 S5\\\L   \\M   4   5      r " S6 S7\\L\M4   5      r " S8 S9\\L\M4   5      r " S: S;\\L\M4   5      r " S< S=\$\L\M4   5      r " S> S?\$\L\M4   5      r " S@ SA\$\L\M4   5      r " SB SC\$\L\M4   5      r\\L\M4   \\L/\M4   -  \\L/\\M   4   -  \\\L   /\\M   4   -  \\\L   /\\M   4   -  \\L\M4   -  \\L\M4   -  \\L\M4   -  \\L\M4   -  \\\!4   -  rSKSD jr\)    SLSE j5       r\)    SMSF j5       r\)    SNSG j5       r\)    SOSH j5       r    SPSI jrg)Qz+Base classes and utilities for `Runnable`s.    )annotationsN)ABCabstractmethod)AsyncGeneratorAsyncIterator	AwaitableCallable	CoroutineIteratorMappingSequence)FIRST_COMPLETEDwait)wraps)tee)
itemgetter)GenericAlias)
TYPE_CHECKINGAnyGenericLiteralProtocolTypeVarcastget_argsget_type_hintsoverload)	BaseModel
ConfigDictField	RootModel)override)beta_decorator)AsyncCallbackManagerCallbackManager)SerializableSerializedConstructorSerializedNotImplemented)RunnableConfigacall_func_with_variable_argscall_func_with_variable_argsensure_config%get_async_callback_manager_for_configget_callback_manager_for_configget_config_listget_executor_for_configmerge_configspatch_configrun_in_executorset_config_context)AddableDictAnyConfigurableFieldConfigurableFieldConfigurableFieldSpecInputOutputaccepts_configaccepts_run_managercoro_with_context
gated_corogather_with_concurrency get_function_first_arg_dict_keysget_function_nonlocalsget_lambda_sourceget_unique_config_specsindent_lines_after_firstis_async_callableis_async_generator)_StreamingCallbackHandler)!_astream_events_implementation_v1!_astream_events_implementation_v2LogStreamCallbackHandler_astream_log_implementation)AsyncRootListenersTracerRootListenersTracer)aclosingatee)safetee)create_model_v2)AsyncCallbackManagerForChainRunCallbackManagerForChainRunBasePromptTemplateRunnableWithFallbacksGraph)ExponentialJitterParams)StreamEvent)BaseTool)RunLogRunLogPatch)AsyncListener)RunOther   c                  l   \ rS rSr% SrS\S'    SMSS.SNS jjjr\SOS j5       r\SPS	 j5       r	\SQS
 j5       r
 SM   SRS jjr SM   SSS jjr\SQS j5       r SM   SRS jjr SM   SSS jjr\STS j5       rSS.SUS jjrSS.   SVS jjrSMSWS jjr SM   SXS jjr    SYS jr    SZS jrSS.     S[S jjrS\S jr    S]S jr \ SM       S^S jj5       r SM       S^S jjr SMSS.         S_S jjjr\ SMSS.         S`S  jjj5       r\ SM         SaS! jj5       r SMSS.         SbS" jjjr SMSS.         S_S# jjjr \ SMSS.         ScS$ jjj5       r!\ SM         SdS% jj5       r! SMSS.         SeS& jjjr! SM       SfS' jjr" SM       SgS( jjr#\ SMS)S)SSSSSSS*.                       ShS+ jjj5       r$\ SMS)SSSSSSS,.                       SiS- jjj5       r$ SMS)S)SSSSSSS*.                       SjS. jjjr$ SMS/SSSSSSS0.                     SkS1 jjjr% SM       SlS2 jjr& SM       SmS3 jjr'SnS4 jr( SM     SoS5 jjr)SSSS6.       SpS7 jjr*SSSS6.       SqS8 jjr+SSS9.     SrS: jjr,\-4S)SS;S<.         SsS= jjr.StS> jr/\-4SS?.       SuS@ jjr0   Sv             SwSA jjr1  Sv             SxSB jjr2 SMSSSC.             SySD jjjr3 SMSSSC.             SzSE jjjr4 SM           S{SF jjr5 SM           S|SG jjr6\7Rp                  " SHSI9 SMSSSSJ.         S}SK jjj5       r9SLr:g)~Runnable|   a  A unit of work that can be invoked, batched, streamed, transformed and composed.

Key Methods
===========

- `invoke`/`ainvoke`: Transforms a single input into an output.
- `batch`/`abatch`: Efficiently transforms multiple inputs into outputs.
- `stream`/`astream`: Streams output from a single input as it's produced.
- `astream_log`: Streams output and selected intermediate results from an
    input.

Built-in optimizations:

- **Batch**: By default, batch runs invoke() in parallel using a thread pool
    executor. Override to optimize batching.

- **Async**: Methods with `'a'` suffix are asynchronous. By default, they execute
    the sync counterpart using asyncio's thread pool.
    Override for native async.

All methods accept an optional config argument, which can be used to configure
execution, add tags and metadata for tracing and debugging etc.

Runnables expose schematic information about their input, output and config via
the `input_schema` property, the `output_schema` property and `config_schema`
method.

Composition
===========

Runnable objects can be composed together to create chains in a declarative way.

Any chain constructed this way will automatically have sync, async, batch, and
streaming support.

The main composition primitives are `RunnableSequence` and `RunnableParallel`.

**`RunnableSequence`** invokes a series of runnables sequentially, with
one Runnable's output serving as the next's input. Construct using
the `|` operator or by passing a list of runnables to `RunnableSequence`.

**`RunnableParallel`** invokes runnables concurrently, providing the same input
to each. Construct it using a dict literal within a sequence or by passing a
dict to `RunnableParallel`.


For example,

```python
from langchain_core.runnables import RunnableLambda

# A RunnableSequence constructed using the `|` operator
sequence = RunnableLambda(lambda x: x + 1) | RunnableLambda(lambda x: x * 2)
sequence.invoke(1)  # 4
sequence.batch([1, 2, 3])  # [4, 6, 8]


# A sequence that contains a RunnableParallel constructed using a dict literal
sequence = RunnableLambda(lambda x: x + 1) | {
    "mul_2": RunnableLambda(lambda x: x * 2),
    "mul_5": RunnableLambda(lambda x: x * 5),
}
sequence.invoke(1)  # {'mul_2': 4, 'mul_5': 10}
```

Standard Methods
================

All `Runnable`s expose additional methods that can be used to modify their
behavior (e.g., add a retry policy, add lifecycle listeners, make them
configurable, etc.).

These methods will work on any `Runnable`, including `Runnable` chains
constructed by composing other `Runnable`s.
See the individual methods for details.

For example,

```python
from langchain_core.runnables import RunnableLambda

import random

def add_one(x: int) -> int:
    return x + 1


def buggy_double(y: int) -> int:
    """Buggy code that will fail 70% of the time"""
    if random.random() > 0.3:
        print('This code failed, and will probably be retried!')  # noqa: T201
        raise ValueError('Triggered buggy code')
    return y * 2

sequence = (
    RunnableLambda(add_one) |
    RunnableLambda(buggy_double).with_retry( # Retry on failure
        stop_after_attempt=10,
        wait_exponential_jitter=False
    )
)

print(sequence.input_schema.model_json_schema()) # Show inferred input schema
print(sequence.output_schema.model_json_schema()) # Show inferred output schema
print(sequence.invoke(2)) # invoke the sequence (note the retry above!!)
```

Debugging and tracing
=====================

As the chains get longer, it can be useful to be able to see intermediate results
to debug and trace the chain.

You can set the global debug flag to True to enable debug output for all chains:

```python
from langchain_core.globals import set_debug

set_debug(True)
```

Alternatively, you can pass existing or custom callbacks to any given chain:

```python
from langchain_core.tracers import ConsoleCallbackHandler

chain.invoke(..., config={"callbacks": [ConsoleCallbackHandler()]})
```

For a UI (and much more) checkout [LangSmith](https://docs.langchain.com/langsmith/home).


str | NonenameNrh   c                  U(       a  UnO[        U S5      (       a  U R                  (       a  U R                  nOcU R                  n[        US5      (       a:  SUR                  ;   a*  UR                  S   b  UR                  S   R                  nOUR                  nU(       a@  US   R                  5       (       a  X1R                  5       -   $ US-   UR                  5       -   $ U$ )zGet the name of the `Runnable`.

Args:
    suffix: An optional suffix to append to the name.
    name: An optional name to use instead of the `Runnable`'s name.

Returns:
    The name of the `Runnable`.
rh   __pydantic_generic_metadata__originr   _)hasattrrh   	__class__rk   __name__isuppertitlelower)selfsuffixrh   name_clss        W/home/james-whalen/.local/lib/python3.13/site-packages/langchain_core/runnables/base.pyget_nameRunnable.get_name  s     ET6""tyyIIE ..C 3   A AA55h?K99(CLLQx!!||~--3;//    c                   U R                   R                  5        HT  n[        US5      (       d  M  UR                  nSU;   d  M*  [	        US   5      [
        :X  d  MB  [        SUS   S   5      s  $    U R                   R                   H;  n[        U5      nU(       d  M  [	        U5      [
        :X  d  M,  [        SUS   5      s  $    SU R                  5        S3n[        U5      e)zInput type.

The type of input this `Runnable` accepts specified as a type annotation.

Raises:
    TypeError: If the input type cannot be inferred.
rk   argstype[Input]r   	Runnable z` doesn't have an inferable InputType. Override the InputType property to specify the input type.ro   mrorn   rk   len_RUNNABLE_GENERIC_NUM_ARGSr   __orig_bases__r   ry   	TypeErrorrt   basemetadatarw   	type_argsmsgs         rx   	InputTypeRunnable.InputType+  s     NN&&(Dt<====h&HV,-1KKx/?/BCC ) >>00C IyS^/IIM9Q<88 1 ( )I I 	 nr{   c                   U R                   R                  5        HT  n[        US5      (       d  M  UR                  nSU;   d  M*  [	        US   5      [
        :X  d  MB  [        SUS   S   5      s  $    U R                   R                   H;  n[        U5      nU(       d  M  [	        U5      [
        :X  d  M,  [        SUS   5      s  $    SU R                  5        S3n[        U5      e)zOutput Type.

The type of output this `Runnable` produces specified as a type annotation.

Raises:
    TypeError: If the output type cannot be inferred.
rk   r}   type[Output]   r   zc doesn't have an inferable OutputType. Override the OutputType property to specify the output type.r   r   s         rx   
OutputTypeRunnable.OutputTypeN  s     NN&&(Dt<====h&HV,-1KK0@0CDD ) >>00C IyS^/IINIaL99 1 ( )K K 	 nr{   c                "    U R                  5       $ )zHThe type of input this `Runnable` accepts specified as a Pydantic model.)get_input_schemart   s    rx   input_schemaRunnable.input_schemam  s     $$&&r{   c                   U R                   n[        R                  " U5      (       a,  [        U[        5      (       d  [        U[        5      (       a  U$ [        U R                  S5      UU R                  R                  S9$ )a  Get a Pydantic model that can be used to validate input to the `Runnable`.

`Runnable` objects 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.

Args:
    config: A config to use when generating the schema.

Returns:
    A Pydantic model that can be used to validate input.
r9   rootmodule_name)r   inspectisclass
isinstancer   
issubclassr   rR   ry   ro   
__module__rt   config	root_types      rx   r   Runnable.get_input_schemar  si    $ NN	 OOI&&y,779i00MM'" 11
 	
r{   c                @    U R                  U5      R                  5       $ )a  Get a JSON schema that represents the input to the `Runnable`.

Args:
    config: A config to use when generating the schema.

Returns:
    A JSON schema that represents the input to the `Runnable`.

Example:
    ```python
    from langchain_core.runnables import RunnableLambda


    def add_one(x: int) -> int:
        return x + 1


    runnable = RunnableLambda(add_one)

    print(runnable.get_input_jsonschema())
    ```

!!! version-added "Added in `langchain-core` 0.3.0"

)r   model_json_schemart   r   s     rx   get_input_jsonschemaRunnable.get_input_jsonschema  s    8 $$V,>>@@r{   c                "    U R                  5       $ )z[Output schema.

The type of output this `Runnable` produces specified as a Pydantic model.
)get_output_schemar   s    rx   output_schemaRunnable.output_schema  s     %%''r{   c                   U R                   n[        R                  " U5      (       a,  [        U[        5      (       d  [        U[        5      (       a  U$ [        U R                  S5      UU R                  R                  S9$ )a  Get a Pydantic model that can be used to validate output to the `Runnable`.

`Runnable` objects 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.

Args:
    config: A config to use when generating the schema.

Returns:
    A Pydantic model that can be used to validate output.
r:   r   )r   r   r   r   r   r   r   rR   ry   ro   r   r   s      rx   r   Runnable.get_output_schema  si    $ OO	 OOI&&y,779i00MM(# 11
 	
r{   c                @    U R                  U5      R                  5       $ )a  Get a JSON schema that represents the output of the `Runnable`.

Args:
    config: A config to use when generating the schema.

Returns:
    A JSON schema that represents the output of the `Runnable`.

Example:
    ```python
    from langchain_core.runnables import RunnableLambda


    def add_one(x: int) -> int:
        return x + 1


    runnable = RunnableLambda(add_one)

    print(runnable.get_output_jsonschema())
    ```

!!! version-added "Added in `langchain-core` 0.3.0"

)r   r   r   s     rx   get_output_jsonschemaRunnable.get_output_jsonschema  s    8 %%f-??AAr{   c                    / $ )z-List configurable fields for this `Runnable`. r   s    rx   config_specsRunnable.config_specs  s	     	r{   includec                  U=(       d    / nU R                   nU(       aY  [        SU Vs0 s HC  nUR                  UR                  [	        UR
                  UR                  UR                  S94_ME     snS9OSn0 U(       a  SUS40O0 E[        [        5      R                  5        VVVs0 s H(  u  pVXQ Vs/ s H  owS:w  d  M
  UPM     sn;   d  M$  XVS4_M*     snnnEn[        U R                  S5      US9$ s  snf s  snf s  snnnf )a>  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.

Args:
    include: A list of fields to include in the config schema.

Returns:
    A Pydantic model that can be used to validate config.

Configurable)rr   descriptionfield_definitionsNconfigurableConfig)r   rR   id
annotationr    defaultrh   r   r   r)   itemsry   )	rt   r   r   specr   
field_name
field_typei
all_fieldss	            rx   config_schemaRunnable.config_schema  s%    -R((   !-# !- GG LL		tGWGW  !-#  	$
9Et 452
 /=^.L.R.R.T.T*JW!LW^8K!W!LL /
...T

 t}}X6*UU/#( "Ms*   A
C9
+D
7	C>C>
D
D
>D
c               <    U R                  US9R                  5       $ )a  Get a JSON schema that represents the config of the `Runnable`.

Args:
    include: A list of fields to include in the config schema.

Returns:
    A JSON schema that represents the config of the `Runnable`.

!!! version-added "Added in `langchain-core` 0.3.0"

r   )r   r   )rt   r   s     rx   get_config_jsonschemaRunnable.get_config_jsonschema6  s!     !!'!2DDFFr{   c                   SSK Jn  U" 5       n UR                  U R                  U5      5      nUR                  X(       a  UR                  S5      OSS9n UR                  U R                  U5      5      nUR                  XE5        UR                  XV5        U$ ! [         a,    UR                  [        U R                  S5      5      5      n Nf = f! [         a,    UR                  [        U R                  S5      5      5      n Nf = f)z1Return a graph representation of this `Runnable`.r   rY   r9   r   N)r   r:   )
langchain_core.runnables.graphrZ   add_noder   r   rR   ry   getr   add_edge)rt   r   rZ   graph
input_noderunnable_nodeoutput_nodes          rx   	get_graphRunnable.get_graphF  s     	9	Q(=(=f(EFJ V6::j1 ' 
	S..)?)?)GHK 	z1}2  	Qg8N(OPJ	Q  	S..x9P)QRK	Ss#    B  C 3CC3D
	D
c                    SSK Jn  U R                  US9R                  R	                  5        Vs/ s H,  n[        UR                  U5      (       d  M   UR                  PM.     sn$ s  snf )z1Return a list of prompts used by this `Runnable`.r   rU   r   )langchain_core.prompts.baserV   r   nodesvaluesr   data)rt   r   rV   nodes       rx   get_promptsRunnable.get_prompts[  s^    
 	C f5;;BBD
D$))%78 DIID
 	
 
s   A&A&c                ,    [        U [        U5      5      $ )zRunnable "or" operator.

Compose this `Runnable` with another object to create a
`RunnableSequence`.

Args:
    other: Another `Runnable` or a `Runnable`-like object.

Returns:
    A new `Runnable`.
RunnableSequencecoerce_to_runnablert   others     rx   __or__Runnable.__or__h  s    &  &8&?@@r{   c                ,    [        [        U5      U 5      $ )zRunnable "reverse-or" operator.

Compose this `Runnable` with another object to create a
`RunnableSequence`.

Args:
    other: Another `Runnable` or a `Runnable`-like object.

Returns:
    A new `Runnable`.
r   r   s     rx   __ror__Runnable.__ror__}  s    &   25 94@@r{   c                    [        U /UQ7SU06$ )a  Pipe `Runnable` objects.

Compose this `Runnable` with `Runnable`-like objects to make a
`RunnableSequence`.

Equivalent to `RunnableSequence(self, *others)` or `self | others[0] | ...`

Example:
    ```python
    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]
    ```

Args:
    *others: Other `Runnable` or `Runnable`-like objects to compose
    name: An optional name for the resulting `RunnableSequence`.

Returns:
    A new `Runnable`.
rh   )r   )rt   rh   otherss      rx   pipeRunnable.pipe  s    ^  9v9D99r{   c                "    SSK Jn  X" U5      -  $ )a  Pick keys from the output `dict` of this `Runnable`.

!!! example "Pick a single key"

    ```python
    import json

    from langchain_core.runnables import RunnableLambda, RunnableMap

    as_str = RunnableLambda(str)
    as_json = RunnableLambda(json.loads)
    chain = RunnableMap(str=as_str, json=as_json)

    chain.invoke("[1, 2, 3]")
    # -> {"str": "[1, 2, 3]", "json": [1, 2, 3]}

    json_only_chain = chain.pick("json")
    json_only_chain.invoke("[1, 2, 3]")
    # -> [1, 2, 3]
    ```

!!! example "Pick a list of keys"

    ```python
    from typing import Any

    import json

    from langchain_core.runnables import RunnableLambda, RunnableMap

    as_str = RunnableLambda(str)
    as_json = RunnableLambda(json.loads)


    def as_bytes(x: Any) -> bytes:
        return bytes(x, "utf-8")


    chain = RunnableMap(
        str=as_str, json=as_json, bytes=RunnableLambda(as_bytes)
    )

    chain.invoke("[1, 2, 3]")
    # -> {"str": "[1, 2, 3]", "json": [1, 2, 3], "bytes": b"[1, 2, 3]"}

    json_and_bytes_chain = chain.pick(["json", "bytes"])
    json_and_bytes_chain.invoke("[1, 2, 3]")
    # -> {"json": [1, 2, 3], "bytes": b"[1, 2, 3]"}
    ```

Args:
    keys: A key or list of keys to pick from the output dict.

Returns:
    a new `Runnable`.

r   )RunnablePick)$langchain_core.runnables.passthroughr   )rt   keysr   s      rx   pickRunnable.pick  s    v 	Fl4(((r{   c                ^    SSK Jn  X" [        [        [        [
        4      " U5      5      -  $ )a  Assigns new fields to the `dict` output of this `Runnable`.

```python
from langchain_core.language_models.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}"
)
model = FakeStreamingListLLM(responses=["foo-lish"])

chain: Runnable = prompt | model | {"str": StrOutputParser()}

chain_with_assign = chain.assign(hello=itemgetter("str") | model)

print(chain_with_assign.input_schema.model_json_schema())
# {'title': 'PromptInput', 'type': 'object', 'properties':
{'question': {'title': 'Question', 'type': 'string'}}}
print(chain_with_assign.output_schema.model_json_schema())
# {'title': 'RunnableSequenceOutput', 'type': 'object', 'properties':
{'str': {'title': 'Str',
'type': 'string'}, 'hello': {'title': 'Hello', 'type': 'string'}}}
```

Args:
    **kwargs: A mapping of keys to `Runnable` or `Runnable`-like objects
        that will be invoked with the entire output dict of this `Runnable`.

Returns:
    A new `Runnable`.

r   )RunnableAssign)r   r   RunnableParalleldictstrr   )rt   kwargsr   s      rx   assignRunnable.assign  s,    V 	Hn%5d38n%Ef%MNNNr{   c                    ga  Transform a single input into an output.

Args:
    input: The input to the `Runnable`.
    config: 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 `RunnableConfig` for more details.

Returns:
    The output of the `Runnable`.
Nr   rt   inputr   r   s       rx   invokeRunnable.invoke3  s    r{   c                L   #    [        X R                  X40 UD6I Sh  vN $  N7fr   )r3   r  r   s       rx   ainvokeRunnable.ainvokeJ  s#     * %V[[%R6RRRRs   $"$Freturn_exceptionsc               F  ^ ^^ U(       d  / $ [        U[        U5      5      nSUUU 4S jjn[        U5      S:X  a  [        SU" US   US   5      /5      $ [        US   5       n[        S[	        UR                  XaU5      5      5      sSSS5        $ ! , (       d  f       g= f)aa  Default implementation runs invoke in parallel using a thread pool executor.

The default implementation of batch works well for IO bound runnables.

Subclasses must override this method if they can batch more efficiently;
e.g., if the underlying `Runnable` uses an API which supports a batch mode.

Args:
    inputs: A list of inputs to the `Runnable`.
    config: 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 `RunnableConfig` for more details.
    return_exceptions: Whether to return exceptions instead of raising them.
    **kwargs: Additional keyword arguments to pass to the `Runnable`.

Returns:
    A list of outputs from the `Runnable`.
c                   > T(       a   TR                   " X40 TD6$ TR                   " X40 TD6$ ! [         a  nUs S nA$ S nAff = fNr  	Exception)input_r   er   r  rt   s      rx   r  Runnable.batch.<locals>.invoke  sL     ;;v@@@ {{6<V<< ! Hs   0 
AAAAr   list[Output]r   N)r  r9   r   r)   returnOutput | Exception)r/   r   r   r0   listmap)rt   inputsr   r  r   configsr  executors   `  ``   rx   batchRunnable.batcha  s    : I!&#f+6	= 	= v;!q	71:)F(GHH$WQZ0HX\\&'-R(ST 100s   #%B
B c                   g r  r   rt   r  r   r  r   s        rx   batch_as_completedRunnable.batch_as_completed       (+r{   c                   g r  r   r  s        rx   r  r         47r{   c             +    ^ ^^#    U(       d  g[        U[        U5      5      n        SUUU 4S jjn[        U5      S:X  a  U" SUS   US   5      v   g[        US   5       n[        [	        XSS95       VV	Vs1 s H  u  nu  pUR                  XhX5      iM     n
n	nn U
(       aI  [        U
[        S9u  pU(       a)  UR                  5       R                  5       v   U(       a  M)  U
(       a  MI  U
 H  nUR                  5         M      SSS5        gs  snn	nf ! U
 H  nUR                  5         M     f = f! , (       d  f       g= f7f)	a  Run `invoke` in parallel on a list of inputs.

Yields results as they complete.

Args:
    inputs: A list of inputs to the `Runnable`.
    config: 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 `RunnableConfig` for more details.
    return_exceptions: Whether to return exceptions instead of raising them.
    **kwargs: Additional keyword arguments to pass to the `Runnable`.

Yields:
    Tuples of the index of the input and the output from the `Runnable`.

Nc                   > T(       a   TR                   " X40 TD6nX4$ TR                   " X40 TD6nX4$ ! [         a  nUn S nAX4$ S nAff = fr  r  r   r  r   outr  r   r  rt   s        rx   r  +Runnable.batch_as_completed.<locals>.invoke  se     !.2kk&.SF.SC 8O kk&;F;8O ! C 8Os   6 
A A		Ar   r   Fstrictreturn_whenr   intr  r9   r   r)   r  ztuple[int, Output | Exception])r/   r   r0   	enumeratezipsubmitr   r   popresultcancel)rt   r  r   r  r   r  r  r  r   r  futuresdonefutures   `  ``        rx   r  r    s=    8 !&#f+6		!	+9	+	 	 v;!F1Iwqz22$WQZ0H ,5SQV5W+X+X'A' 6:+X  
$$(o$NMD"hhj//11 $ g
 &FMMO & 10 &FMMO & 10sO   A E%D;=!D
D;#AD*D3D;	ED;D88D;;
E	Ec                  ^ ^^#    U(       d  / $ [        U[        U5      5      nSUUU 4S jjn[        XaU5      n[        US   R	                  S5      /UQ76 I Sh  vN $  N7f)ab  Default implementation runs `ainvoke` in parallel using `asyncio.gather`.

The default implementation of `batch` works well for IO bound runnables.

Subclasses must override this method if they can batch more efficiently;
e.g., if the underlying `Runnable` uses an API which supports a batch mode.

Args:
    inputs: A list of inputs to the `Runnable`.
    config: 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 `RunnableConfig` for more details.
    return_exceptions: Whether to return exceptions instead of raising them.
    **kwargs: Additional keyword arguments to pass to the `Runnable`.

Returns:
    A list of outputs from the `Runnable`.

c                   >#    T(       a   TR                   " X40 TD6I S h  vN $ TR                   " X40 TD6I S h  vN $  N! [         a  nUs S nA$ S nAff = f N7fr  r  r  )valuer   r  r   r  rt   s      rx   r   Runnable.abatch.<locals>.ainvoke  s_      !%e!Fv!FFF "\\%B6BBB	 G  H CsM   AA AA AAAA 
AAAAAAr   max_concurrencyN)r9  r9   r   r)   r  r  )r/   r   r  r?   r   )rt   r  r   r  r   r  r  coross   `  ``   rx   abatchRunnable.abatch  s_     > I!&#f+6	C 	C GW-,WQZ^^<M-NWQVWWWWs   AA"A A"c                   g r  r   r  s        rx   abatch_as_completedRunnable.abatch_as_completed       -0r{   c                   g r  r   r  s        rx   r@  rA  "       9<r{   c                ^ ^^#    U(       d  g[        U[        U5      5      nU(       a  US   R                  S5      OSnU(       a  [        R                  " U5      OSn        SUUU 4S jjn[        [        XSS95       V	V
Vs/ s H*  u  n	u  pU(       a  [        Xx" XU5      5      OU" XU5      PM,     nn
n	n[        R                  " U5       H  nUI Sh  vN 7v   M     gs  snn
n	f  N7f)a  Run `ainvoke` in parallel on a list of inputs.

Yields results as they complete.

Args:
    inputs: A list of inputs to the `Runnable`.
    config: 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 `RunnableConfig` for more details.
    return_exceptions: Whether to return exceptions instead of raising them.
    **kwargs: Additional keyword arguments to pass to the `Runnable`.

Yields:
    A tuple of the index of the input and the output from the `Runnable`.

Nr   r;  c                   >#    T(       a   TR                   " X40 TD6I S h  vN nX4$ TR                   " X40 TD6I S h  vN nX4$  N%! [         a  nUn S nAX4$ S nAff = f N$7fr  r8  r$  s        rx   ainvoke_task2Runnable.abatch_as_completed.<locals>.ainvoke_taskP  s      !48LL5*05 /C 8O !LLB6BB8O/ ! C 8O	 CsI   A'A
 AA
 A' A%A'A
 

A"AA'A""A'Fr'  r+  )	r/   r   r   asyncio	Semaphorer-  r.  r>   as_completed)rt   r  r   r  r   r  r;  	semaphorerG  r   r  r<  coros   `  ``        rx   r@  rA  ,  s     8 !&#f+6?F'!*..):;D:IG%%o6t			!	+9	+	 	$ (1VU1S'T	
 (U##F  y,q&"ABa01 (U	 	 
 ((/D* 0
 s   BC11C(9"C1C/C1c              +  6   #    U R                   " X40 UD6v   g7f)aU  Default implementation of `stream`, which calls `invoke`.

Subclasses must override this method if they support streaming output.

Args:
    input: The input to the `Runnable`.
    config: The config to use for the `Runnable`.
    **kwargs: Additional keyword arguments to pass to the `Runnable`.

Yields:
    The output of the `Runnable`.

N)r  r   s       rx   streamRunnable.streamh  s     & kk%2622s   c               L   #    U R                   " X40 UD6I Sh  vN 7v   g N7f)aW  Default implementation of `astream`, which calls `ainvoke`.

Subclasses must override this method if they support streaming output.

Args:
    input: The input to the `Runnable`.
    config: The config to use for the `Runnable`.
    **kwargs: Additional keyword arguments to pass to the `Runnable`.

Yields:
    The output of the `Runnable`.

N)r  r   s       rx   astreamRunnable.astream}  s!     & LL9&9999s   $"	$T)diffwith_streamed_output_listinclude_namesinclude_typesinclude_tagsexclude_namesexclude_typesexclude_tagsc                   g r  r   rt   r  r   rT  rU  rV  rW  rX  rY  rZ  r[  r   s               rx   astream_logRunnable.astream_log  s     &)r{   )rU  rV  rW  rX  rY  rZ  r[  c                   g r  r   r]  s               rx   r^  r_    s     !$r{   c              v   #    [        SUUUUU	U
SS9n[        U UU4UUUS.UD6  Sh  vN nU7v   M   N
 g7f)a  Stream all output from a `Runnable`, as reported to the callback system.

This includes all inner runs of LLMs, Retrievers, Tools, etc.

Output is streamed as Log objects, which include a list of
Jsonpatch ops that describe how the state of the run has changed in each
step, and the final state of the run.

The Jsonpatch ops can be applied in order to construct state.

Args:
    input: The input to the `Runnable`.
    config: The config to use for the `Runnable`.
    diff: Whether to yield diffs between each step or the current state.
    with_streamed_output_list: Whether to yield the `streamed_output` list.
    include_names: Only include logs with these names.
    include_types: Only include logs with these types.
    include_tags: Only include logs with these tags.
    exclude_names: Exclude logs with these names.
    exclude_types: Exclude logs with these types.
    exclude_tags: Exclude logs with these tags.
    **kwargs: Additional keyword arguments to pass to the `Runnable`.

Yields:
    A `RunLogPatch` or `RunLog` object.

Foriginal)
auto_closerV  rW  rX  rY  rZ  r[  _schema_format)rT  rO  rU  NrJ   )rt   r  r   rT  rU  rV  rW  rX  rY  rZ  r[  r   rO  items                 rx   r^  r_    so     T *''%''%%	
 6
 &?
 
 		$ J		 
s   #9757979v2)versionrV  rW  rX  rY  rZ  r[  c              B  #    US:X  a  [        U U4UUUUUUU	S.U
D6nO)US:X  a  [        U U4UUUUUUU	S.U
D6nOSn[        U5      e[        U5       ISh  vN   U  Sh  vN nU7v   M   N N
 SSS5      ISh  vN    g! , ISh  vN  (       d  f       g= f7f)a$  Generate a stream of events.

Use to create an iterator over `StreamEvent` that provide real-time information
about the progress of the `Runnable`, including `StreamEvent` from intermediate
results.

A `StreamEvent` is a dictionary with the following schema:

- `event`: Event names are of the format:
    `on_[runnable_type]_(start|stream|end)`.
- `name`: The name of the `Runnable` that generated the event.
- `run_id`: Randomly generated ID associated with the given execution of the
    `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`: The IDs of the parent runnables that generated 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.
- `tags`: The tags of the `Runnable` that generated the event.
- `metadata`: The metadata of the `Runnable` that generated the event.
- `data`: The data associated with the event. The contents of this field
    depend on the type of event. See the table below for more details.

Below is a table that illustrates some events that might be emitted by various
chains. Metadata fields have been omitted from the table for brevity.
Chain definitions have been included after the table.

!!! note
    This reference table is for the v2 version of the schema.

| event                  | name                 | chunk                               | input                                             | output                                              |
| ---------------------- | -------------------- | ----------------------------------- | ------------------------------------------------- | --------------------------------------------------- |
| `on_chat_model_start`  | `'[model name]'`     |                                     | `{"messages": [[SystemMessage, HumanMessage]]}`   |                                                     |
| `on_chat_model_stream` | `'[model name]'`     | `AIMessageChunk(content="hello")`   |                                                   |                                                     |
| `on_chat_model_end`    | `'[model name]'`     |                                     | `{"messages": [[SystemMessage, HumanMessage]]}`   | `AIMessageChunk(content="hello world")`             |
| `on_llm_start`         | `'[model name]'`     |                                     | `{'input': 'hello'}`                              |                                                     |
| `on_llm_stream`        | `'[model name]'`     | `'Hello' `                          |                                                   |                                                     |
| `on_llm_end`           | `'[model name]'`     |                                     | `'Hello human!'`                                  |                                                     |
| `on_chain_start`       | `'format_docs'`      |                                     |                                                   |                                                     |
| `on_chain_stream`      | `'format_docs'`      | `'hello world!, goodbye world!'`    |                                                   |                                                     |
| `on_chain_end`         | `'format_docs'`      |                                     | `[Document(...)]`                                 | `'hello world!, goodbye world!'`                    |
| `on_tool_start`        | `'some_tool'`        |                                     | `{"x": 1, "y": "2"}`                              |                                                     |
| `on_tool_end`          | `'some_tool'`        |                                     |                                                   | `{"x": 1, "y": "2"}`                                |
| `on_retriever_start`   | `'[retriever name]'` |                                     | `{"query": "hello"}`                              |                                                     |
| `on_retriever_end`     | `'[retriever name]'` |                                     | `{"query": "hello"}`                              | `[Document(...), ..]`                               |
| `on_prompt_start`      | `'[template_name]'`  |                                     | `{"question": "hello"}`                           |                                                     |
| `on_prompt_end`        | `'[template_name]'`  |                                     | `{"question": "hello"}`                           | `ChatPromptValue(messages: [SystemMessage, ...])`   |

In addition to the standard events, users can also dispatch custom events (see example below).

Custom events will be only be surfaced with in the v2 version of the API!

A custom event has following format:

| Attribute   | Type   | Description                                                                                               |
| ----------- | ------ | --------------------------------------------------------------------------------------------------------- |
| `name`      | `str`  | A user defined name for the event.                                                                        |
| `data`      | `Any`  | The data associated with the event. This can be anything, though we suggest making it JSON serializable.  |

Here are declarations associated with the standard events shown above:

`format_docs`:

```python
def format_docs(docs: list[Document]) -> str:
    '''Format the docs.'''
    return ", ".join([doc.page_content for doc in docs])


format_docs = RunnableLambda(format_docs)
```

`some_tool`:

```python
@tool
def some_tool(x: int, y: str) -> dict:
    '''Some_tool.'''
    return {"x": x, "y": y}
```

`prompt`:

```python
template = ChatPromptTemplate.from_messages(
    [
        ("system", "You are Cat Agent 007"),
        ("human", "{question}"),
    ]
).with_config({"run_name": "my_template", "tags": ["my_template"]})
```

!!! example

    ```python
    from langchain_core.runnables import RunnableLambda


    async def reverse(s: str) -> str:
        return s[::-1]


    chain = RunnableLambda(func=reverse)

    events = [
        event async for event in chain.astream_events("hello", version="v2")
    ]

    # Will produce the following events
    # (run_id, and parent_ids has been omitted for brevity):
    [
        {
            "data": {"input": "hello"},
            "event": "on_chain_start",
            "metadata": {},
            "name": "reverse",
            "tags": [],
        },
        {
            "data": {"chunk": "olleh"},
            "event": "on_chain_stream",
            "metadata": {},
            "name": "reverse",
            "tags": [],
        },
        {
            "data": {"output": "olleh"},
            "event": "on_chain_end",
            "metadata": {},
            "name": "reverse",
            "tags": [],
        },
    ]
    ```

```python title="Dispatch custom event"
from langchain_core.callbacks.manager import (
    adispatch_custom_event,
)
from langchain_core.runnables import RunnableLambda, RunnableConfig
import asyncio


async def slow_thing(some_input: str, config: RunnableConfig) -> str:
    """Do something that takes a long time."""
    await asyncio.sleep(1) # Placeholder for some slow operation
    await adispatch_custom_event(
        "progress_event",
        {"message": "Finished step 1 of 3"},
        config=config # Must be included for python < 3.10
    )
    await asyncio.sleep(1) # Placeholder for some slow operation
    await adispatch_custom_event(
        "progress_event",
        {"message": "Finished step 2 of 3"},
        config=config # Must be included for python < 3.10
    )
    await asyncio.sleep(1) # Placeholder for some slow operation
    return "Done"

slow_thing = RunnableLambda(slow_thing)

async for event in slow_thing.astream_events("some_input", version="v2"):
    print(event)
```

Args:
    input: The input to the `Runnable`.
    config: The config to use for the `Runnable`.
    version: The version of the schema to use, either `'v2'` or `'v1'`.

        Users should use `'v2'`.

        `'v1'` is for backwards compatibility and will be deprecated
        in `0.4.0`.

        No default will be assigned until the API is stabilized.
        custom events will only be surfaced in `'v2'`.
    include_names: Only include events from `Runnable` objects with matching names.
    include_types: Only include events from `Runnable` objects with matching types.
    include_tags: Only include events from `Runnable` objects with matching tags.
    exclude_names: Exclude events from `Runnable` objects with matching names.
    exclude_types: Exclude events from `Runnable` objects with matching types.
    exclude_tags: Exclude events from `Runnable` objects with matching tags.
    **kwargs: Additional keyword arguments to pass to the `Runnable`.

        These will be passed to `astream_log` as this implementation
        of `astream_events` is built on top of `astream_log`.

Yields:
    An async stream of `StreamEvent`.

Raises:
    NotImplementedError: If the version is not `'v1'` or `'v2'`.

rf  )r   rV  rW  rX  rY  rZ  r[  v1zAOnly versions "v1" and "v2" of the schema is currently supported.N)rI   rH   NotImplementedErrorrO   )rt   r  r   rg  rV  rW  rX  rY  rZ  r[  r   event_streamr   events                 rx   astream_eventsRunnable.astream_events  s     d d?< ++)++) L _ = ++)++) L VC%c**L))+ e *| *)))))sl   ABA.BBA2"A0#A2&B.B0A22B3B>B?BBBBBc              +     #    SnU H  nU(       d  UnSnM   WU-   nM     U(       a  U R                  " WU40 UD6 Sh  vN   gg! [          a    Un MN  f = f N7f)a  Transform inputs to outputs.

Default implementation of transform, which buffers input and calls `astream`.

Subclasses must override this method if they can start producing output while
input is still being generated.

Args:
    input: An iterator of inputs to the `Runnable`.
    config: The config to use for the `Runnable`.
    **kwargs: Additional keyword arguments to pass to the `Runnable`.

Yields:
    The output of the `Runnable`.

FTN)r   rO  )rt   r  r   r   got_first_valichunkfinals          rx   	transformRunnable.transform  sq     . F ! $#!FNE " {{5&;F;;;  ! #"E# <s2   AA"AA AAAAAc                  #    SnU  Sh  vN nU(       d  UnSnM   WU-   nM   N! [          a    Un M/  f = f
 U(       a'  U R                  " WU40 UD6  Sh  vN  nU7v   M  
 gg7f)a  Transform inputs to outputs.

Default implementation of atransform, which buffers input and calls `astream`.

Subclasses must override this method if they can start producing output while
input is still being generated.

Args:
    input: An async iterator of inputs to the `Runnable`.
    config: The config to use for the `Runnable`.
    **kwargs: Additional keyword arguments to pass to the `Runnable`.

Yields:
    The output of the `Runnable`.

FNT)r   rR  )rt   r  r   r   rp  rq  rr  outputs           rx   
atransformRunnable.atransform  s     . ! 	#& ! $#!FNE	# ! #"E# ""  $UF Ef E  f !F sM   A*:%:A*'A*:7A*7A*A'AA'A*c                    [        X0 S9$ )aZ  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.

Args:
    **kwargs: The arguments to bind to the `Runnable`.

Returns:
    A new `Runnable` with the arguments bound.

Example:
    ```python
    from langchain_ollama import ChatOllama
    from langchain_core.output_parsers import StrOutputParser

    model = ChatOllama(model="llama3.1")

    # Without bind
    chain = model | StrOutputParser()

    chain.invoke("Repeat quoted words exactly: 'One two three four five.'")
    # Output is 'One two three four five.'

    # With bind
    chain = model.bind(stop=["three"]) | StrOutputParser()

    chain.invoke("Repeat quoted words exactly: 'One two three four five.'")
    # Output is 'One two'
    ```
)boundr   r   RunnableBindingrt   r   s     rx   bindRunnable.bindH  s    @ TDDr{   c           	     F    [        U [        S0 U=(       d    0 EUE5      0 S9$ )zBind config to a `Runnable`, returning a new `Runnable`.

Args:
    config: The config to bind to the `Runnable`.
    **kwargs: Additional keyword arguments to pass to the `Runnable`.

Returns:
    A new `Runnable` with the config bound.

r)   )rz  r   r   )r|  r   rt   r   r   s      rx   with_configRunnable.with_configj  s5       ,FLb,V, 
 	
r{   on_starton_endon_errorc               *   ^^^ [        U UUU4S j/S9$ )aK  Bind lifecycle listeners to a `Runnable`, returning a new `Runnable`.

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.

Args:
    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.

Returns:
    A new `Runnable` with the listeners bound.

Example:
    ```python
    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)
    ```
c                "   > S[        U TTTS9/0$ N	callbacks)r   r  r  r  rN   r   r  r  r  s    rx   <lambda>)Runnable.with_listeners.<locals>.<lambda>  s$    +#)%-#)%-	"	 r{   rz  config_factoriesr{  rt   r  r  r  s    ```rx   with_listenersRunnable.with_listeners  s     p 	
 	
r{   c               *   ^^^ [        U UUU4S j/S9$ )aM
  Bind async lifecycle listeners to a `Runnable`.

Returns a new `Runnable`.

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.

Args:
    on_start: Called asynchronously before the `Runnable` starts running,
        with the `Run` object.
    on_end: Called asynchronously after the `Runnable` finishes running,
        with the `Run` object.
    on_error: Called asynchronously if the `Runnable` throws an error,
        with the `Run` object.

Returns:
    A new `Runnable` with the listeners bound.

Example:
    ```python
    from langchain_core.runnables import RunnableLambda, Runnable
    from datetime import datetime, timezone
    import time
    import asyncio


    def format_t(timestamp: float) -> str:
        return datetime.fromtimestamp(timestamp, tz=timezone.utc).isoformat()


    async def test_runnable(time_to_sleep: int):
        print(f"Runnable[{time_to_sleep}s]: starts at {format_t(time.time())}")
        await asyncio.sleep(time_to_sleep)
        print(f"Runnable[{time_to_sleep}s]: ends at {format_t(time.time())}")


    async def fn_start(run_obj: Runnable):
        print(f"on start callback starts at {format_t(time.time())}")
        await asyncio.sleep(3)
        print(f"on start callback ends at {format_t(time.time())}")


    async def fn_end(run_obj: Runnable):
        print(f"on end callback starts at {format_t(time.time())}")
        await asyncio.sleep(2)
        print(f"on end callback ends at {format_t(time.time())}")


    runnable = RunnableLambda(test_runnable).with_alisteners(
        on_start=fn_start, on_end=fn_end
    )


    async def concurrent_runs():
        await asyncio.gather(runnable.ainvoke(2), runnable.ainvoke(3))


    asyncio.run(concurrent_runs())
    # Result:
    # on start callback starts at 2025-03-01T07:05:22.875378+00:00
    # on start callback starts at 2025-03-01T07:05:22.875495+00:00
    # on start callback ends at 2025-03-01T07:05:25.878862+00:00
    # on start callback ends at 2025-03-01T07:05:25.878947+00:00
    # Runnable[2s]: starts at 2025-03-01T07:05:25.879392+00:00
    # Runnable[3s]: starts at 2025-03-01T07:05:25.879804+00:00
    # Runnable[2s]: ends at 2025-03-01T07:05:27.881998+00:00
    # on end callback starts at 2025-03-01T07:05:27.882360+00:00
    # Runnable[3s]: ends at 2025-03-01T07:05:28.881737+00:00
    # on end callback starts at 2025-03-01T07:05:28.882428+00:00
    # on end callback ends at 2025-03-01T07:05:29.883893+00:00
    # on end callback ends at 2025-03-01T07:05:30.884831+00:00
    ```
c                "   > S[        U TTTS9/0$ r  )rM   r  s    rx   r  *Runnable.with_alisteners.<locals>.<lambda>  s$    0#)%-#)%-	"	 r{   r  r{  r  s    ```rx   with_alistenersRunnable.with_alisteners  s     b 	
 	
r{   )
input_typeoutput_typec                   [        U UU0 S9$ )zBind input and output types to a `Runnable`, returning a new `Runnable`.

Args:
    input_type: The input type to bind to the `Runnable`.
    output_type: The output type to bind to the `Runnable`.

Returns:
    A new `Runnable` with the types bound.
)rz  custom_input_typecustom_output_typer   r{  rt   r  r  s      rx   
with_typesRunnable.with_types,  s     (*	
 	
r{      )retry_if_exception_typewait_exponential_jitterexponential_jitter_paramsstop_after_attemptc          
     &    SSK Jn  U" U 0 0 UUUUS9$ )aQ  Create a new `Runnable` that retries the original `Runnable` on exceptions.

Args:
    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.
    exponential_jitter_params: Parameters for
        `tenacity.wait_exponential_jitter`. Namely: `initial`, `max`,
        `exp_base`, and `jitter` (all `float` values).

Returns:
    A new `Runnable` that retries the original `Runnable` on exceptions.

Example:
    ```python
    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
    ```
r   )RunnableRetry)rz  r   r   retry_exception_typesr  max_attempt_numberr  )langchain_core.runnables.retryr  )rt   r  r  r  r  r  s         rx   
with_retryRunnable.with_retryB  s+    h 	A"9$;1&?
 	
r{   c                    [        U S9$ )a  Return a new `Runnable` that maps a list of inputs to a list of outputs.

Calls `invoke` with each input.

Returns:
    A new `Runnable` that maps a list of inputs to a list of outputs.

Example:
    ```python
    from langchain_core.runnables import RunnableLambda


    def _lambda(x: int) -> int:
        return x + 1


    runnable = RunnableLambda(_lambda)
    print(runnable.map().invoke([1, 2, 3]))  # [2, 3, 4]
    ```
rz  )RunnableEachr   s    rx   r  Runnable.map  s    * $''r{   )exceptions_to_handleexception_keyc                    SSK Jn  U" U UUUS9$ )a>  Add fallbacks to a `Runnable`, returning a new `Runnable`.

The new `Runnable` will try the original `Runnable`, and then each fallback
in order, upon failures.

Args:
    fallbacks: A sequence of runnables to try if the original `Runnable`
        fails.
    exceptions_to_handle: A tuple of exception types to handle.
    exception_key: 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.

Example:
    ```python
    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
    ```

Args:
    fallbacks: A sequence of runnables to try if the original `Runnable`
        fails.
    exceptions_to_handle: A tuple of exception types to handle.
    exception_key: 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.
r   rW   )runnable	fallbacksr  r  )"langchain_core.runnables.fallbacksrX   )rt   r  r  r  rX   s        rx   with_fallbacksRunnable.with_fallbacks  s#    F	
 %!5'	
 	
r{   c                   [        U5      n[        U5      nUR                  UUUUR                  S5      =(       d    U R	                  5       UR                  SS5      S9n [        X8R                  5       S9n	[        U	5       n
[        SU
R                  " [        UUUU40 UD65      nSSS5        UR                  W5        U$ ! , (       d  f       N!= f! [         a  nUR                  U5        e SnAff = f)zCall with config.

Helper method to transform an `Input` value to an `Output` value,
with callbacks.

Use this method to implement `invoke` in subclasses.

run_namerun_idNrun_typerh   r  r  r:   )r,   r.   on_chain_startr   ry   r0  r2   	get_childr4   r   runr+   on_chain_endBaseExceptionon_chain_error)rt   funcr  r   r  
serializedr   callback_managerrun_managerchild_configcontextrv  r  s                rx   _call_with_configRunnable._call_with_config  s    & v&:6B&55J':4==?::h- 6 
	':O:O:QRL#L1WKK4# !
 2  $$V,M# 21  	&&q)	s0   !"C &C)C 
CC 
C6C11C6c           
     .  #    [        U5      n[        U5      nUR                  UUUUR                  S5      =(       d    U R	                  5       UR                  SS5      S9I Sh  vN n [        X8R                  5       S9n	[        U	5       n
[        XX840 UD6n[        X5      I Sh  vN nSSS5        UR                  W5      I Sh  vN   U$  Nk N)! , (       d  f       N-= f N! [         a   nUR                  U5      I Sh  vN    e SnAff = f7f)zAsync call with config.

Helper method to transform an `Input` value to an `Output` value,
with callbacks.

Use this method to implement `ainvoke` in subclasses.
r  r  Nr  r  )r,   r-   r  r   ry   r0  r2   r  r4   r*   r=   r  r  r  )rt   r  r  r   r  r  r   r  r  r  r  rM  rv  r  s                 rx   _acall_with_configRunnable._acall_with_config  s    ( v&@H,;;J':4==?::h- < 
 
	':O:O:QRL#L1W4&9? (9'G!G	 2 **6222M'
 "H	 21 3	  	,,Q///	s~   A#D%C&D+"C( C)C*C.C( 6D
C&DC
C#C( &D(
D2DD	DDD)r  r  c                  U(       d  / $ [        U[        U5      5      nU Vs/ s H  n[        U5      PM     n	n[        XUSS9 V
VVs/ s HO  u  pnU
R	                  SUUUR                  S5      =(       d    U R                  5       UR                  SS5      S9PMQ     nnn
n [        U5      (       a7  [        X|SS9 VVs/ s H  u  p[        XR                  5       S9PM     snnUS'   [        U5      (       a  XS	'   U" U40 UD6nSn[        XSS9 HJ  u  nn[        U[        5      (       a  U=(       d    UnUR                  U5        M9  UR                  U5        ML     U(       d  Uc  [!        S
U5      $ Ues  snf s  snnn
f s  snnf ! ["         aO  nU H  nUR                  U5        M     U(       a(  [!        S
U Vs/ s H  nUPM     Os  snf sn5      s SnA$ e SnAff = f)zTransform a list of inputs to a list of outputs, with callbacks.

Helper method to transform an `Input` value to an `Output` value,
with callbacks. Use this method to implement `invoke` in subclasses.

Fr'  Nr  r  r  r  r   r  r  )r/   r   r.   r.  r  r   ry   r0  r;   r2   r  r<   r   r  r  r  r   r  )rt   r  r  r   r  r  r   r  ccallback_managersr  r  run_managersrmrv  first_exceptionr  r%  r  rm   s                       rx   _batch_with_configRunnable._batch_with_configE  s   . I!&#f+6IPQA<Q?Q 58!755
50 & ++!ZZ
+>t}}zz(D1 , 5 	 
	"d## "%W5!I$!I !lln=!I$x  #4(((4}%&+F+F 15O$'U$K Sc9--&5&<O..s3,,S1 %L !O$;NF33!!M R
$  	+**1-  , N,?1Q,?@@	sN   E:	AE?$F #F$$F F 
G%+G GG G%G  G%c          
       ^ ^^#    U(       d  / $ [        U[        U5      5      nU Vs/ s H  n[        U5      PM     n	n[        R                  " UU 4S j[        XUSS9 5       6 I Sh  vN n
 [        U5      (       a7  [        XzSS9 VVs/ s H  u  p[        XR                  5       S9PM     snnUS'   [        U5      (       a  XS'   U" U40 UD6I Sh  vN nSn/ n[        XSS9 Hh  u  nn[        U[        5      (       a-  U=(       d    UnUR                  UR                  U5      5        MH  UR                  UR                  U5      5        Mj     [        R                  " U6 I Sh  vN   U(       d  Uc  [        SU5      $ Ues  snf  GN$s  snnf  N N,! [          a[  m[        R                  " U4S	 jU
 5       6 I Sh  vN    U(       a(  [        SU Vs/ s H  nTPM     Os  snf sn5      s Sm@$ e Sm@ff = f7f)
zTransform a list of inputs to a list of outputs, with callbacks.

Helper method to transform an `Input` value to an `Output` value,
with callbacks.

Use this method to implement `invoke` in subclasses.

c              3     >#    U  HQ  u  pnUR                  S UTUR                  S5      =(       d    TR                  5       UR                  SS 5      S9v   MS     g 7f)Nr  r  r  r  r   ry   r0  ).0r  r  r   r  rt   s       rx   	<genexpr>/Runnable._abatch_with_config.<locals>.<genexpr>  s`      94$f !//%J/B4==?!::h5 0 9s   AAFr'  Nr  r   r  r  c              3  D   >#    U  H  oR                  T5      v   M     g 7fr  r  )r  r  r  s     rx   r  r    s     P<K,,Q//<    )r/   r   r-   rI  gatherr.  r;   r2   r  r<   r   r  appendr  r  r   r  )rt   r  r  r   r  r  r   r  r  r  r  r  rv  r  r<  r  r%  rm   r  s   `    `            @rx   _abatch_with_configRunnable._abatch_with_config  s    4 I!&#f+6OVWw!B1EwWDKNN 9<%wu9E
 ?
	"d## "%W5!I$!I !lln=!I$x  #4(((4}%1&11F 15O+-E$'U$K Sc9--&5&<OLL!;!;C!@ALL!9!9#!>? %L ..%((( O$;NF33!!W X?
 $ 2" )!  	..P<P   !N,?1Q,?@@	s   #HF,H)F*H/F #F/'F FF BH+F,"HF H
G?$ G:GG:G('G:3G?4H9G::G??Hc           
   +  2  #    UR                  SS5      n[        US5      u  px[        US5      n	Sn
SnSn[        U5      n[	        U5      nUR                  SSS0UUR                  S5      =(       d    U R                  5       UR                  S	S5      US
9n [        X>R                  5       S9n[        U5      (       a  XS'   [        U5      (       a  XS'   [        U5       nUR                  " X(40 UD6n[        S UR                   5       S5      =n(       a  UR                  UR                   U5      n  UR                  [        U5      nUv   U(       a  Uc  UnO	 UU-   nOUnM2  ! ["         a    UnSn Nf = f! [$        [&        4 a     Of = fU H0  nU
(       a$  U	c  Un	M   U	U-   n	M  ! ["         a    Un	Sn
 M*  f = fUn	M2     SSS5        O! , (       d  f       O= fUR)                  XS9  g! [*         a  nUR-                  UU	S9  e SnAff = f7f)zTransform a stream with config.

Helper method to transform an `Iterator` of `Input` values into an
`Iterator` of `Output` values, with callbacks.

Use this to implement `stream` or `transform` in `Runnable` subclasses.

defers_inputsFrc   NTr   r  r  r  rh   r  r  r  r   r  c              3  h   #    U  H(  n[        U[        5      (       d  M  [        S U5      v   M*     g7frG   Nr   rG   r   r  hs     rx   r  9Runnable._transform_stream_with_config.<locals>.<genexpr>	  /      !5A%a)BC =8!<<!5   22r  )r0  r   nextr,   r.   r  r   ry   r2   r  r;   r<   r4   r  handlerstap_output_iterr  r   StopIterationGeneratorExitr  r  r  )rt   r  transformerr   r  r   r  input_for_tracinginput_for_transformfinal_inputfinal_input_supportedfinal_outputfinal_output_supportedr  r  r  r  iteratorstream_handlerchunkrq  r  s                         rx   _transform_stream_with_config&Runnable._transform_stream_with_config  sW    , 

?E: 25VQ.$():D$A $&*!%v&:6B&55bMJ':4==?::h-' 6 
6	G':O:O:QRLk**#/x ";//(3}%#L1W";;{R6R%)!,!5!5 & >   .==#**H H(/D((C#1+3/4!C3?%3GL
 ,1L  (1 !C38L=B$:!C
 &}5 /F,&.*0K>.9F.B#, >.48= 5> '- 0A 211` $$\$F	  	&&q&=	s   BHA
G4 "AG7(E> E*%E>*E;8E>:E;;E>>FGFG(F/-G/G=G G	G
	G4 
G!G4 $H4
H>HHHc           
    d  #    UR                  SS5      n[        US5      u  px[        US5      I Sh  vN n	Sn
SnSn[        U5      n[	        U5      nUR                  SSS0UUR                  S5      =(       d    U R                  5       UR                  S	S5      US
9I Sh  vN n [        X>R                  5       S9n[        U5      (       a  XS'   [        U5      (       a  XS'   [        U5       nUR                  " X(40 UD6n[        S UR                   5       S5      =n(       a  UR!                  UR"                  U5      nOUn  [%        [        U5      U5      I Sh  vN nU7v   U(       a  Uc  UnO	 UU-   nOUnM:   GNS N N&! [&         a    UnSn Nf = f! [(         a     Of = fU  Sh  vN  nU
(       a$  U	c  Un	M   U	U-   n	M   ! [&         a    Un	Sn
 M1  f = fUn	M9  
 SSS5        O! , (       d  f       O= fUR+                  XS9I Sh  vN    O,! [,         a  nUR/                  UU	S9I Sh  vN    e SnAff = f Wb,  [1        US5      (       a  UR3                  5       I Sh  vN    ggg! Wb,  [1        US5      (       a  UR3                  5       I Sh  vN    f f f = f7f)zTransform a stream with config.

Helper method to transform an Async `Iterator` of `Input` values into an
Async `Iterator` of `Output` values, with callbacks.

Use this to implement `astream` or `atransform` in `Runnable` subclasses.

r  Frc   NTr  r  r  r  r  r  r   r  c              3  h   #    U  H(  n[        U[        5      (       d  M  [        S U5      v   M*     g7fr  r  r  s     rx   r  :Runnable._atransform_stream_with_config.<locals>.<genexpr>l	  r  r  r  aclose)r0  rP   anextr,   r-   r  r   ry   r2   r  r;   r<   r4   r  r  r  tap_output_aiterr  r=   r   StopAsyncIterationr  r  r  rn   r  )rt   r  r  r   r  r   r  r  r  r  r  r  r  r  r  r  r  	iterator_r   r  r  rq  r  s                          rx   _atransform_stream_with_config'Runnable._atransform_stream_with_config5	  s    2 

?E: 26fa.*/0A4*H$H $&*!%v&@H,;;bMJ':4==?::h-' < 
 
<	)':O:O:QRLk**#/x ";//(3}%#L1W#KKSFS	%)!,!5!5 & >   .>>#**I H  )H&7h&Q Q#1+3/4!C3?%3GL
 ,1L Q %I
D !R (1 !C38L=B$:!C
 * $5 - -&,&.*0K>.9F.B#, >.48= 5> '- %6G 211f **<*LLL	  	,,Q{,CCC	 M$H)E)E&&((( *F$y$H)E)E&&((( *F$s8  0J0FA/J0"F#J0(A
H 2AG5
F #F
$F ;F F J0J0
F FF FF  
F-*G5,F--G52G+6F97G+;G5GG5G$ G5#G$$G5,	H 5
H?H I< HI< 
I)I<H?=III< 'J03I64J0<(J-$J'%J--J0z1This API is in beta and may change in the future.message)rh   r   	arg_typesc               "    SSK Jn  U" U UUUUS9$ )ae	  Create a `BaseTool` from a `Runnable`.

`as_tool` will instantiate a `BaseTool` with a name, description, and
`args_schema` from a `Runnable`. Where possible, schemas are inferred
from `runnable.get_input_schema`.

Alternatively (e.g., if the `Runnable` takes a dict as input and the specific
`dict` keys are not typed), the schema can be specified directly with
`args_schema`.

You can also pass `arg_types` to just specify the required arguments and their
types.

Args:
    args_schema: The schema for the tool.
    name: The name of the tool.
    description: The description of the tool.
    arg_types: A dictionary of argument names to types.

Returns:
    A `BaseTool` instance.

!!! example "`TypedDict` input"

    ```python
    from typing_extensions import TypedDict
    from langchain_core.runnables import RunnableLambda


    class Args(TypedDict):
        a: int
        b: list[int]


    def f(x: Args) -> str:
        return str(x["a"] * max(x["b"]))


    runnable = RunnableLambda(f)
    as_tool = runnable.as_tool()
    as_tool.invoke({"a": 3, "b": [1, 2]})
    ```

!!! example "`dict` input, specifying schema via `args_schema`"

    ```python
    from typing import Any
    from pydantic import BaseModel, Field
    from langchain_core.runnables import RunnableLambda

    def f(x: dict[str, Any]) -> str:
        return str(x["a"] * max(x["b"]))

    class FSchema(BaseModel):
        """Apply a function to an integer and list of integers."""

        a: int = Field(..., description="Integer")
        b: list[int] = Field(..., description="List of ints")

    runnable = RunnableLambda(f)
    as_tool = runnable.as_tool(FSchema)
    as_tool.invoke({"a": 3, "b": [1, 2]})
    ```

!!! example "`dict` input, specifying schema via `arg_types`"

    ```python
    from typing import Any
    from langchain_core.runnables import RunnableLambda


    def f(x: dict[str, Any]) -> str:
        return str(x["a"] * max(x["b"]))


    runnable = RunnableLambda(f)
    as_tool = runnable.as_tool(arg_types={"a": int, "b": list[int]})
    as_tool.invoke({"a": 3, "b": [1, 2]})
    ```

!!! example "`str` input"

    ```python
    from langchain_core.runnables import RunnableLambda


    def f(x: str) -> str:
        return x + "a"


    def g(x: str) -> str:
        return x + "z"


    runnable = RunnableLambda(f) | g
    as_tool = runnable.as_tool()
    as_tool.invoke("b")
    ```
r   )convert_runnable_to_tool)args_schemarh   r   r  )langchain_core.toolsr  )rt   r  rh   r   r  r  s         rx   as_toolRunnable.as_tool	  s%    Z 	B'##
 	
r{   r   r  ru   rg   rh   rg   r  r   r  r~   r  r   )r  type[BaseModel]r   RunnableConfig | Noner  r  )r   r  r  dict[str, Any]r  zlist[ConfigurableFieldSpec])r   Sequence[str] | Noner  r  )r   r  r  r  r   r  r  rZ   )r   r  r  zlist[BasePromptTemplate]r   zRunnable[Any, Other] | Callable[[Iterator[Any]], Iterator[Other]] | Callable[[AsyncIterator[Any]], AsyncIterator[Other]] | Callable[[Any], Other] | Mapping[str, Runnable[Any, Other] | Callable[[Any], Other] | Any]r  "RunnableSerializable[Input, Other]r   zRunnable[Other, Any] | Callable[[Iterator[Other]], Iterator[Any]] | Callable[[AsyncIterator[Other]], AsyncIterator[Any]] | Callable[[Other], Any] | Mapping[str, Runnable[Other, Any] | Callable[[Other], Any] | Any]r  z#RunnableSerializable[Other, Output])r   z-Runnable[Any, Other] | Callable[[Any], Other]rh   rg   r  r"  )r   zstr | list[str]r  RunnableSerializable[Any, Any])r   zRunnable[dict[str, Any], Any] | Callable[[dict[str, Any]], Any] | Mapping[str, Runnable[dict[str, Any], Any] | Callable[[dict[str, Any]], Any]]r  r$  r  r9   r   r  r   r   r  r:   
r  list[Input]r   ,RunnableConfig | list[RunnableConfig] | Noner  boolr   
Any | Noner  r  
r  Sequence[Input]r   0RunnableConfig | Sequence[RunnableConfig] | Noner  Literal[False]r   r   r  zIterator[tuple[int, Output]]
r  r,  r   r-  r  Literal[True]r   r   r  (Iterator[tuple[int, Output | Exception]]
r  r,  r   r-  r  r)  r   r*  r  r1  
r  r,  r   r-  r  r.  r   r*  r  z!AsyncIterator[tuple[int, Output]]
r  r,  r   r-  r  r0  r   r*  r  -AsyncIterator[tuple[int, Output | Exception]]
r  r,  r   r-  r  r)  r   r*  r  r5  r  r9   r   r  r   r*  r  Iterator[Output]r  r9   r   r  r   r*  r  AsyncIterator[Output])r  r   r   r  rT  r0  rU  r)  rV  r  rW  r  rX  r  rY  r  rZ  r  r[  r  r   r   r  zAsyncIterator[RunLogPatch])r  r   r   r  rT  r.  rU  r)  rV  r  rW  r  rX  r  rY  r  rZ  r  r[  r  r   r   r  zAsyncIterator[RunLog])r  r   r   r  rT  r)  rU  r)  rV  r  rW  r  rX  r  rY  r  rZ  r  r[  r  r   r   r  z2AsyncIterator[RunLogPatch] | AsyncIterator[RunLog])r  r   r   r  rg  zLiteral['v1', 'v2']rV  r  rW  r  rX  r  rY  r  rZ  r  r[  r  r   r   r  AsyncIterator[StreamEvent]r  Iterator[Input]r   r  r   r*  r  r8  r  AsyncIterator[Input]r   r  r   r*  r  r:  r   r   r  Runnable[Input, Output]r   r  r   r   r  rA  r  DCallable[[Run], None] | Callable[[Run, RunnableConfig], None] | Noner  rD  r  rD  r  rA  )r  AsyncListener | Noner  rE  r  rE  r  rA  )r  ztype[Input] | Noner  ztype[Output] | Noner  rA  )
r  tuple[type[BaseException], ...]r  r)  r  zExponentialJitterParams | Noner  r,  r  rA  )r  z#Runnable[list[Input], list[Output]])r  z!Sequence[Runnable[Input, Output]]r  rF  r  rg   r  z%RunnableWithFallbacksT[Input, Output]NN)r  zCallable[[Input], Output] | Callable[[Input, CallbackManagerForChainRun], Output] | Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]r  r9   r   r  r  rg   r  dict[str, Any] | Noner   r*  r  r:   )r  zCallable[[Input], Awaitable[Output]] | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]] | Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]r  r9   r   r  r  rg   r  rH  r   r*  r  r:   )r  zCallable[[list[Input]], list[Exception | Output]] | Callable[[list[Input], list[CallbackManagerForChainRun]], list[Exception | Output]] | Callable[[list[Input], list[CallbackManagerForChainRun], list[RunnableConfig]], list[Exception | Output]]r  r'  r   r(  r  r)  r  rg   r   r*  r  r  )r  a  Callable[[list[Input]], Awaitable[list[Exception | Output]]] | Callable[[list[Input], list[AsyncCallbackManagerForChainRun]], Awaitable[list[Exception | Output]]] | Callable[[list[Input], list[AsyncCallbackManagerForChainRun], list[RunnableConfig]], Awaitable[list[Exception | Output]]]r  r'  r   r(  r  r)  r  rg   r   r*  r  r  )r  r=  r  zCallable[[Iterator[Input]], Iterator[Output]] | Callable[[Iterator[Input], CallbackManagerForChainRun], Iterator[Output]] | Callable[[Iterator[Input], CallbackManagerForChainRun, RunnableConfig], Iterator[Output]]r   r  r  rg   r   r*  r  r8  )r  r?  r  zCallable[[AsyncIterator[Input]], AsyncIterator[Output]] | Callable[[AsyncIterator[Input], AsyncCallbackManagerForChainRun], AsyncIterator[Output]] | Callable[[AsyncIterator[Input], AsyncCallbackManagerForChainRun, RunnableConfig], AsyncIterator[Output]]r   r  r  rg   r   r*  r  r:  )
r  ztype[BaseModel] | Nonerh   rg   r   rg   r  zdict[str, type] | Noner  r]   );rp   r   __qualname____firstlineno____doc____annotations__ry   propertyr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r   r  r=  r@  rO  rR  r^  rm  rs  rw  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r#   betar  __static_attributes__r   r{   rx   re   re   |   s   CJ E$ $ $L    D  < ' ' )-&
%&
 
&
R /3A+A	A< ( ( )-&
%&
 
&
R /3B+B	B<   @D )VX 26G.G	G , /3
+
	!
ALA 
,A*ALA 
-A0  /:>/: /: 
,	/:b=)~-OX-O
 
(-O^  )- & 	
 
 2 )-SS &S 	S
 
S4 @D0U
 #(0U0U =0U
  0U 0U 
0Ud  DH+
 -2++ A+
 *+ + 
&+ +  DH77 A7
 )7 7 
27 7 DH?$
 #(?$?$ A?$
  ?$ ?$ 
2?$H @D.X
 #(.X.X =.X
  .X .X 
.X`  DH0
 -200 A0
 *0 0 
+0 0  DH<< A<
 )< < 
7< < DH:
 #(:: A:
  : : 
7:~ )-33 &3 	3
 
30 )-:: &: 	:
 
:*  )-)
 #*..2.2-1.2.2-1)) &)
 ) $() ,) ,) +) ,) ,) +) ) 
$) )   )-$ +/.2.2-1.2.2-1$$ &$
 $ $($ ,$ ,$ +$ ,$ ,$ +$ $ 
$ $& )-A
 *..2.2-1.2.2-1AA &A
 A $(A ,A ,A +A ,A ,A +A A 
<AL )-t
 (,.2.2-1.2.2-1tt &t
 %t ,t ,t +t ,t ,t +t t 
$tr )-+<+< &+< 	+<
 
+<` )-,#, &, 	,
 
,\ EH )-
%
 	

 
!
<   F
F
F
F
 
!F
V *.'+)-_
 '_
 %	_

 '_
 
!_
H *.+/	
 '
 )	

 
!
2 EN<(,DH"#>
 "A>
 "&	>

 $B>
  >
 
!>
@(6 BK$(L
4L
 >	L

 "L
 
/L
\ 2  $,0/P/
 / &/ / */ / 
/t  $,0)
) ) &) ) *) ) 
)l @DA" #(#A"
A" A" =A"  A" A" A"  
!A"^ @DI" #(#I"
I" I" =I"  I" I"  !I"" 
#I"j  $`G`G
`G &`G `G `G 
`G^  $i)$i)
i) &i) i) i) 
i)V !TU /3t
  "&,0t
+t
 	t

  t
 *t
 
t
 Vt
r{   re   c                     ^  \ rS rSr% SrSrS\S'   \" SS9r\	SU 4S jj5       r
    SS	 jrS
SS.         SS jjrSrU =r$ )RunnableSerializablei
  z(Runnable that can be serialized to JSON.Nrg   rh   r   )protected_namespacesc                   > [         TU ]  5       n[        R                  " [        5         U R                  5       US'   SSS5        U$ ! , (       d  f       U$ = f)zgSerialize the `Runnable` to JSON.

Returns:
    A JSON-serializable representation of the `Runnable`.

rh   N)superto_json
contextlibsuppressr  ry   )rt   dumpedro   s     rx   rU  RunnableSerializable.to_json#
  sF     "  +!]]_F6N , ,+s   A
Ac                    SSK Jn  [        U 5      R                  nU H,  nXC;  d  M
  SU SU  SUR	                  5        3n[        U5      e   U" XS9$ )a  Configure particular `Runnable` fields at runtime.

Args:
    **kwargs: A dictionary of `ConfigurableField` instances to configure.

Raises:
    ValueError: If a configuration key is not found in the `Runnable`.

Returns:
    A new `Runnable` with the fields configured.

!!! example

    ```python
    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,
    )
    ```
r   )RunnableConfigurableFieldszConfiguration key z not found in z: available keys are )r   fields)%langchain_core.runnables.configurabler[  typemodel_fieldsr   
ValueError)rt   r   r[  r_  keyr   s         rx   configurable_fields(RunnableSerializable.configurable_fields0
  so    V	
 Dz..C&(^D6 B**6*;*;*=)>@  !o%  *$FFr{   r   F)default_keyprefix_keysc               "    SSK Jn  U" UU UUUS9$ )a  Configure alternatives for `Runnable` objects that can be set at runtime.

Args:
    which: The `ConfigurableField` instance that will be used to select the
        alternative.
    default_key: The default key to use if no alternative is selected.
    prefix_keys: Whether to prefix the keys with the `ConfigurableField` id.
    **kwargs: A dictionary of keys to `Runnable` instances or callables that
        return `Runnable` instances.

Returns:
    A new `Runnable` with the alternatives configured.

!!! example

    ```python
    from langchain_anthropic import ChatAnthropic
    from langchain_core.runnables.utils import ConfigurableField
    from langchain_openai import ChatOpenAI

    model = ChatAnthropic(
        model_name="claude-sonnet-4-5-20250929"
    ).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
    )
    ```
r   ) RunnableConfigurableAlternatives)whichr   alternativesrd  re  )r]  rg  )rt   rh  rd  re  r   rg  s         rx   configurable_alternatives.RunnableSerializable.configurable_alternativesj
  s&    `	
 0##
 	
r{   )r  z0SerializedConstructor | SerializedNotImplemented)r   r6   r  #RunnableSerializable[Input, Output])
rh  r7   rd  r   re  r)  r   z?Runnable[Input, Output] | Callable[[], Runnable[Input, Output]]r  rl  )rp   r   rI  rJ  rK  rh   rL  r   model_configr"   rU  rb  rj  rO  __classcell__ro   s   @rx   rQ  rQ  
  s    2D*  L 
 
8G,8G	,8G| %!:
 :
 	:

 :
 R:
 
-:
 :
r{   rQ  c           
        SSK JnJn  U S   n[        U 5      S:X  a  UR	                  U5      $ [        XB5      (       a  [        U SS  U5      n[        U[        5      (       dh  [        SUR                  R                  5        VVs0 s H8  u  pgXdR                  R                  ;  d  M   XgR                  UR                  4_M:     snnS9$ O[        XC5      (       a  [        U SS  U5      $ UR	                  U5      $ s  snnf )Nr   r   r   r   RunnableSequenceInputr   )r   r   r   r   r   r   _seq_input_schemar   r!   rR   r_  r   mappersteps__r   r   )stepsr   r   r   firstnext_input_schemakvs           rx   rs  rs  
  s    
 !HE
5zQ%%f--%((-eABi@+Y77"' !2 > > D D F# F 4 44 1Aaii00 F#  8 
E	(	( qrF33!!&))#s   C;(C;c                >   SSK JnJn  U S   n[        U 5      S:X  a  UR	                  U5      $ [        XB5      (       a  UR                  R                  U5      n[        U S S U5      n[        U[        5      (       d  [        S0 UR                  R                  5        VVs0 s H  u  pxXxR                  UR                  4_M     snnEUR                  R                  5        VVs0 s H  u  pxXxR                  UR                  4_M     snnES9$ O[        XC5      (       a  [        U S S U5      n[        U[        5      (       d  [        UR                   ["        5      (       a^  [        SUR                  R                  5        VVs0 s H.  u  pxXtR                   ;   d  M  XxR                  UR                  4_M0     snnS9$ UR                  UR                      n	[        SU	R                  U	R                  4S9$ UR                  U5      $ s  snnf s  snnf s  snnf )Nr   rq  r   RunnableSequenceOutputr   )r   )r   r   r   r   r   r   rt  r   _seq_output_schemar   r!   rR   r_  r   r   r   r   r  )
rv  r   r   r   lastmapper_output_schemaprev_output_schemary  rz  fields
             rx   r~  r~  
  s    
 9D
5zQ$$V,,$''#{{<<VD/cr
FC,i88"(	# %7$C$C$I$I$K$KDA LL!))44$K	# %9$E$E$K$K$M$MDA LL!))44$M	#  9 
D	'	'/cr
FC,i88$))T**&, %7$C$C$I$I$K'$KDA		> 5LL!))44$K'  '33DII>E"(0@0@%--/P  !!&))9's   !$H&$HH!Hc                  l  ^  \ rS rSr% SrS\S'    \" \S9rS\S'    S\S	'    S
S
S
S
S.           S(U 4S jjjr	\
\S)S j5       5       r\S*S j5       r\
\S+S j5       5       r\" SS9r\\S,S j5       5       r\\S-S j5       5       r\S.S/S jj5       r\ S.   S/S jj5       r\\S0S j5       5       r\S.S1S jj5       r\S2S j5       r\    S3S j5       r\    S4S j5       r\ S.       S5S jj5       r\ S.       S6S jj5       r\ S.SS.         S7S jjj5       r\ S.SS.         S7S  jjj5       r          S8S! jr          S9S" jr \ S.       S:S# jj5       r!\ S.       S;S$ jj5       r"\ S.       S<S% jj5       r#\ S.       S=S& jj5       r$S'r%U =r&$ )>r   i
  a4  Sequence of `Runnable` objects, where the output of one is the input of the next.

**`RunnableSequence`** is the most important composition operator in LangChain
as it is used in virtually every chain.

A `RunnableSequence` can be instantiated directly or more commonly by using the
`|` operator where either the left or right operands (or both) must be a
`Runnable`.

Any `RunnableSequence` automatically supports sync, async, batch.

The default implementations of `batch` and `abatch` utilize threadpools and
asyncio gather and will be faster than naive invocation of `invoke` or `ainvoke`
for IO bound `Runnable`s.

Batching is implemented by invoking the batch method on each component of the
`RunnableSequence` in order.

A `RunnableSequence` preserves the streaming properties of its components, so if
all components of the sequence implement a `transform` method -- which
is the method that implements the logic to map a streaming input to a streaming
output -- then the sequence will be able to stream input to output!

If any component of the sequence does not implement transform then the
streaming will only begin after this component is run. If there are
multiple blocking components, streaming begins after the last one.

!!! note
    `RunnableLambdas` do not support `transform` by default! So if you need to
    use a `RunnableLambdas` be careful about where you place them in a
    `RunnableSequence` (if you need to use the `stream`/`astream` methods).

    If you need arbitrary logic and need streaming, you can subclass
    Runnable, and implement `transform` for whatever logic you need.

Here is a simple example that uses simple functions to illustrate the use of
`RunnableSequence`:

    ```python
    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 | runnable_2
    # Or equivalently:
    # sequence = RunnableSequence(first=runnable_1, last=runnable_2)
    sequence.invoke(1)
    await sequence.ainvoke(1)

    sequence.batch([1, 2, 3])
    await sequence.abatch([1, 2, 3])
    ```

Here's an example that uses streams JSON output generated by an LLM:

    ```python
    from langchain_core.output_parsers.json import SimpleJsonOutputParser
    from langchain_openai import ChatOpenAI

    prompt = PromptTemplate.from_template(
        "In JSON format, give me a list of {topic} and their "
        "corresponding names in French, Spanish and in a "
        "Cat Language."
    )

    model = ChatOpenAI()
    chain = prompt | model | SimpleJsonOutputParser()

    async for chunk in chain.astream({"topic": "colors"}):
        print("-")  # noqa: T201
        print(chunk, sep="", flush=True)  # noqa: T201
    ```
Runnable[Input, Any]rw  default_factorylist[Runnable[Any, Any]]middlezRunnable[Any, Output]r  N)rh   rw  r  r  c                 > / nU(       d  Ub  Ub  U/U=(       d    / -   U/-   nU HO  n[        U[        5      (       a  UR                  UR                  5        M5  UR	                  [        U5      5        MQ     [        U5      [        :  a   S[         S[        U5       3n[        U5      e[        T	U ])  US   [        USS 5      US   US9  g)aZ  Create a new `RunnableSequence`.

Args:
    steps: The steps to include in the sequence.
    name: The name of the `Runnable`.
    first: The first `Runnable` in the sequence.
    middle: The middle `Runnable` objects in the sequence.
    last: The last `Runnable` in the sequence.

Raises:
    ValueError: If the sequence has less than 2 steps.
Nz$RunnableSequence must have at least z steps, got r   r   r|  )rw  r  r  rh   )r   r   extendrv  r  r   r   _RUNNABLE_SEQUENCE_MIN_STEPSr`  rT  __init__r  )
rt   rh   rw  r  r  rv  
steps_flatstepr   ro   s
            rx   r  RunnableSequence.__init__Y  s    ( &(
*t/?FLb1TF:JD$ 011!!$**-!!"4T":;	 
 z?9967S6T U!*o.0  S/!Q-
1R()B	 	 	
r{   c                
    / SQ$ z_Get the namespace of the LangChain object.

Returns:
    `["langchain", "schema", "runnable"]`
)	langchainschemar  r   rw   s    rx   get_lc_namespace!RunnableSequence.get_lc_namespace  
     32r{   c                L    U R                   /U R                  QU R                  P$ )z]All the `Runnable`s that make up the sequence in order.

Returns:
    A list of `Runnable`s.
)rw  r  r  r   s    rx   rv  RunnableSequence.steps  s#     

4T[[4$))44r{   c                    gz,Return `True` as this class is serializable.Tr   r  s    rx   is_lc_serializable#RunnableSequence.is_lc_serializable       r{   Tarbitrary_types_allowedc                .    U R                   R                  $ z(The type of the input to the `Runnable`.)rw  r   r   s    rx   r   RunnableSequence.InputType  s     zz###r{   c                .    U R                   R                  $ )z)The type of the output of the `Runnable`.)r  r   r   s    rx   r   RunnableSequence.OutputType  s     yy###r{   c                .    [        U R                  U5      $ )Get the input schema of the `Runnable`.

Args:
    config: The config to use.

Returns:
    The input schema of the `Runnable`.

)rs  rv  r   s     rx   r   !RunnableSequence.get_input_schema  s     !V44r{   c                .    [        U R                  U5      $ )Get the output schema of the `Runnable`.

Args:
    config: The config to use.

Returns:
    The output schema of the `Runnable`.

)r~  rv  r   s     rx   r   "RunnableSequence.get_output_schema  s     "$**f55r{   c                    [        U R                   VVs/ s H  oR                    H  o"PM     M     snn5      $ s  snnf )[Get the config specs of the `Runnable`.

Returns:
    The config specs of the `Runnable`.

)rC   rv  r   )rt   r  r   s      rx   r   RunnableSequence.config_specs  s7     '"jjGjd5F5FTT5FTjG
 	
Gs   ;
c                   SSK Jn  U" 5       nU R                   H  nUR                  5       nUR	                  U5      nX@R
                  La  UR                  5         X@R                  La  UR                  5         UR                  U5      u  pxU(       d  SU S3n	[        U	5      eU(       d  M  UR                  XW5        M     U$ )Get the graph representation of the `Runnable`.

Args:
    config: The config to use.

Returns:
    The graph representation of the `Runnable`.

Raises:
    ValueError: If a `Runnable` has no first or last node.

r   rY   r    has no first node)r   rZ   rv  	last_noder   rw  trim_first_noder  trim_last_noder  r`  r   )
rt   r   rZ   r   r  current_last_node
step_graphstep_first_noderm   r   s
             rx   r   RunnableSequence.get_graph  s     	9JJD % 1/J::%**,99$))+!&j!9O"!$'9: o%  0B  r{   c                X    SR                  S [        U R                  5       5       5      $ )Nz
| c              3  r   #    U  H-  u  pUS :X  a  [        U5      O[        [        U5      S5      v   M/     g7f)r   z| N)reprrD   )r  r   ss      rx   r  ,RunnableSequence.__repr__.<locals>.<genexpr>  s4      
- AvDG#;DGT#JJ-s   57)joinr-  rv  r   s    rx   __repr__RunnableSequence.__repr__  s)    {{ 
!$**-
 
 	
r{   c                   [        U[        5      (       ap  [        U R                  /U R                  QU R                  PUR                  PUR                  QUR                  P7SU R
                  =(       d    UR
                  06$ [        U R                  /U R                  QU R                  P[        U5      P7SU R
                  06$ Nrh   r   r   rw  r  r  rh   r   r   s     rx   r   RunnableSequence.__or__  s     e-..#

 		 	
  

 YY,%**   JJ
[[
 II
 u%	

 
 	
r{   c                   [        U[        5      (       ap  [        UR                  /UR                  QUR                  PU R                  PU R                  QU R                  P7SUR
                  =(       d    U R
                  06$ [        [        U5      U R                  /U R                  QU R                  P7SU R
                  06$ r  r  r   s     rx   r   RunnableSequence.__ror__  s     e-..# 

 

	
  		 ZZ,499   u%JJ
 [[
 II	

 
 	
r{   c           	        [        U5      n[        U5      nUR                  S UUR                  S5      =(       d    U R	                  5       UR                  SS 5      S9nUn [        U R                  5       Hx  u  px[        X%R                  SUS-    35      S9n[        U5       n	US:X  a  U	R                  " UR                  Xb40 UD6nOU	R                  UR                  Xb5      nS S S 5        Mz     UR                  U5        [        SU5      $ ! , (       d  f       M  = f! [         a  n
UR!                  U
5        e S n
A
ff = f)	Nr  r  rh   r  	seq:step:r   r  r   r:   )r,   r.   r  r   ry   r0  r-  rv  r2   r  r4   r  r  r  r   r  r  )rt   r  r   r   r  r  r  r   r  r  r  s              rx   r  RunnableSequence.invoke4  s-   
 v&:6B&55J':4==?::h-	 6 
 	*$TZZ0%&;&;iAw<O&P (/7Av!(T[[&!SF!S!(T[[&!I	 0/ 1 $$V,&)) 0/  	&&q)	s2   "AD" %AD'D" 
D	D" "
E,D>>Ec           	       #    [        U5      n[        U5      nUR                  S UUR                  S5      =(       d    U R	                  5       UR                  SS 5      S9I S h  vN nUn [        U R                  5       H  u  px[        X%R                  SUS-    35      S9n[        U5       n	US:X  a#  [        R                  " UR                  Xb40 UD6n
O![        R                  " UR                  Xb5      n
[        U
" 5       U	SS	9I S h  vN nS S S 5        M     UR                  U5      I S h  vN   [!        S
U5      $  N N7! , (       d  f       M  = f N&! ["         a   nUR%                  U5      I S h  vN    e S nAff = f7f)Nr  r  r  r  r   r  r   Tcreate_taskr:   )r,   r-   r  r   ry   r0  r-  rv  r2   r  r4   	functoolspartialr  r=   r  r   r  r  )rt   r  r   r   r  r  r  r   r  r  partr  s               rx   r  RunnableSequence.ainvokeX  sj     v&@H,;;J':4==?::h-	 < 
 
 	*$TZZ0%&;&;iAw<O&P (/7Av(00vXQWX(00vN#4TVWRV#WWF 0/ 1  **6222&))7
( X 0/ 3	  	,,Q///	s   A"F$E%F,AE /AEEEE F2E3FE
E	E F
F%F 9E<:F  FFFr  c               h   U(       d  / $ [        U[        U5      5      nU Vs/ s HJ  n[        R                  " UR	                  S5      S SUR	                  S5      S UR	                  S5      S S9PML     nn[        XaUSS9 VVVs/ s HN  u  pxnUR                  S UUR	                  S5      =(       d    U R                  5       UR                  SS 5      S	9PMP     n	nnn U(       Ga  0 n
[        U R                  5       GHK  u  p[        [        U5      5       Vs/ s H  oU
;  d  M
  UPM     nnUR                  " [        XSS9 VVs/ s H  u  pX;  d  M  UPM     snn[        [        XSS95       VVVs/ s H/  u  nu  nnX;  d  M  [        UUR                  S
US-    35      S9PM1     snnn4SU0US:X  a  UO0 D6nU
R                  [        XSS9 VVs0 s H  u  p[!        U["        5      (       d  M  X_M      snn5        U Vs/ s H  n[!        U["        5      (       a  M  UPM     nn[        U
5      [        U5      :X  d  GML    O   UR%                  5       n/ n[        [        U5      5       HG  nX;   a  UR'                  [)        SX   5      5        M'  UR'                  UR                  S5      5        MI     Ow[        U R                  5       H^  u  pUR                  " U[        XSS9 VVs/ s H%  u  nn[        UUR                  S
US-    35      S9PM'     snn4SU0US:X  a  UO0 D6nM`     S n[        XSS9 HJ  u  nn[!        U["        5      (       a  U=(       d    UnUR+                  U5        M9  UR-                  U5        ML     U(       d  Uc  [)        SU5      $ Ues  snf s  snnnf s  snf s  snnf s  snnnf s  snnf s  snf s  snnf ! [.         aO  nU	 H  nUR+                  U5        M     U(       a(  [)        SU Vs/ s H  nUPM     Os  snf sn5      s S nA$ e S nAff = f)Nr  Ftagsr   inheritable_callbackslocal_callbacksverboseinheritable_tags
local_tagsinheritable_metadatalocal_metadatar'  r  r  r  r  r   r  r  r   r9   r  )r/   r   r%   	configurer   r.  r  ry   r0  r-  rv  ranger  r2   r  updater   r  copyr  r   r  r  r  )rt   r  r   r  r   r  r  cmr  r  failed_inputs_mapstepidxr  r   remaining_idxsinpr  inputs_copyr  r  r%  r  rm   s                          rx   r  RunnableSequence.batch  sD    I "&#f+6 "
 " %%&,jj&= $!'F!3%+ZZ
%;# " 	 
( '*!75'

'"F ZZ
+>t}}zz(D1	  ' 	 

V	"  ;=!%.tzz%:MG $)W#6&#6aCT:T#6 # & "ZZ +.nU*S*S 9  *S 4= #L% H4
4<B  !9L &*,,,7Q;-7P*Q4
" +<#$ &-\6r%F* &,, +.nU*S*S)#y9 #AF*S .4VVc:c9;UcVFV,-W=M &;R %kkms7|,A-d74E4H&IJkooa&89	 -  )4GA!ZZ /2,PU.V
 /W
F ) &",,1q5'?R2S /W +< &'!V6F  5, 15O$'U$K Sc9--&5&<O..s3,,S1 %L !O$;NF33!!a


,&


  W"  	"!!!$ # N,?1Q,?@@	s   AN)AN.;O 	N5'N5-O N:N:O 7O 
#O -,O O8O>O 
O'O-O 
B*O 4,O O 5#O 
P1"+P,PP,%P1+P,,P1c                 ^ ^#    U(       d  / $ [        U[        U5      5      nU Vs/ s HJ  n[        R                  " UR	                  S5      S SUR	                  S5      S UR	                  S5      S S9PML     nn[
        R                  " U 4S j[        XaUSS9 5       6 I S h  vN n U(       Ga  0 n[        T R                  5       GHR  u  p[        [        U5      5       Vs/ s H  oU;  d  M
  UPM     nnU
R                  " [        XSS9 VVs/ s H  u  pX;  d  M  UPM     snn[        [        XuSS95       VVVs/ s H.  u  nu  pX;  d  M  [        UUR                  SU	S	-    35      S
9PM0     snnn4SU0U	S:X  a  UO0 D6I S h  vN nUR                  [        XSS9 VVs0 s H  u  p[        U[         5      (       d  M  X_M      snn5        U Vs/ s H  n[        U[         5      (       a  M  UPM     nn[        U5      [        U5      :X  d  GMS    O   UR#                  5       n/ n[        [        U5      5       HG  nX;   a  UR%                  ['        SX   5      5        M'  UR%                  UR)                  S5      5        MI     O}[        T R                  5       Hd  u  pU
R                  " U[        XuSS9 VVs/ s H#  u  p[        X.R                  SUS	-    35      S
9PM%     snn4SU0US:X  a  UO0 D6I S h  vN nMf     S n/ n[        XqSS9 Hh  u  nn[        U[         5      (       a-  U=(       d    UnUR%                  UR+                  U5      5        MH  UR%                  UR-                  U5      5        Mj     [
        R                  " U6 I S h  vN   U(       d  Uc  ['        SU5      $ Ues  snf  GNs  snf s  snnf s  snnnf  GNHs  snnf s  snf s  snnf  N NL! [.         a[  m[
        R                  " U4S jU 5       6 I S h  vN    U(       a(  ['        SU Vs/ s H  nTPM     Os  snf sn5      s S m@$ e S m@ff = f7f)Nr  Fr  r   r  c           
   3     >#    U  HP  u  pnUR                  S UUR                  S5      =(       d    TR                  5       UR                  SS 5      S9v   MR     g 7f)Nr  r  r  r  )r  r  r  r   rt   s       rx   r  *RunnableSequence.abatch.<locals>.<genexpr>  s\      
+&B !!J/B4==?!::h5	 " +s   AAr'  r  r   r  r  r   r9   r  c              3  D   >#    U  H  oR                  T5      v   M     g 7fr  r  )r  r  r  s     rx   r  r  q  s     "O,B#4#4Q#7#7,r  )r/   r   r$   r  r   rI  r  r.  r-  rv  r  r=  r2   r  r  r   r  r  r  r   r0  r  r  r  )rt   r  r   r  r   r  r  r  r  r  r  r   r  r  r  r  r  r<  r  r%  rm   r  s   `                    @rx   r=  RunnableSequence.abatch   sD     I "&#f+6 "
 " !**&,jj&= $!'F!3%+ZZ
%;# " 	 
 ELNN
 +.%wu+
E
 ?
 V	"  ;=!%.tzz%:MG $)W#6&#6aCT:T#6 # & $(;; +.nU*S*S 9  *S 4= #L% H4
4<B  !9L &*,,,7Q;-7P*Q4
$" +<#$$ &-\6r%$ F* &,, +.nU*S*S)#y9 #AF*S .4VVc:c9;UcVFV,-W=M &;R %kkms7|,A-d74E4H&IJkooa&89	 -  )4GA#';; /2,PU.V
 /W
 ) &,,1q5'?R2S /W$ +<$ &'!V6$ F  5( 15O+-E$'U$K Sc9--&5&<OLL!;!;C!@ALL!9!9#!>? %L ..%((( O$;NF33!!g
?
2&


, W"6 )  	.."O,"OPPP N,?1Q,?@@		s  #QAN;8+Q#O $Q);O- $	O1O7O- O!O'O- O#O6O- OO- *O	OO- O8O>O- B*O- *O#/O- O)O- BQO+"QO- O- +Q-
Q7 QPQ.P;:QQQQQQc           	   +  B  #    U R                   /U R                  QU R                  Pn[        SU5      n[	        U5       HO  u  px[        X2R                  SUS-    35      S9nUS:X  a  UR                  " Xc40 UD6nM>  UR                  Xc5      nMQ     U S h  vN   g  N7f)Nr8  r  r   r  r   )rw  r  r  r   r-  r2   r  rs  )	rt   r  r  r   r   rv  final_pipelineidxr  s	            rx   
_transformRunnableSequence._transform  s      5dkk54995 0&9"5)IC!"7"7)C!G98M"NF ax!%!Q&!Q!%!G * "!!s   BBBBc           	    V  #    U R                   /U R                  QU R                  Pn[        SU5      n[	        U5       HP  u  px[        UUR                  SUS-    35      S9nUS:X  a  UR                  " Xc40 UD6nM?  UR                  Xc5      nMR     U  S h  vN n	U	7v   M   N
 g 7f)Nr:  r  r   r  r   )rw  r  r  r   r-  r2   r  rw  )
rt   r  r  r   r   rv  r  r  r  rv  s
             rx   _atransformRunnableSequence._atransform  s      5dkk54995
 5v>"5)IC!%//)C!G90EFF ax!%!R6!R!%!H * + 	&L	Ns*   BB)B'B%B'B)%B''B)c           
   +     #    U R                   " UU R                  [        X"=(       d    0 R                  S5      =(       d    U R                  S940 UD6 S h  vN   g  N7fNr  )r  )r  r  r2   r   rh   r   s       rx   rs  RunnableSequence.transform  sS      55OO<R*<*<Z*H*UDIIV
 	
 	
 	
s   AAAAc              +  \   #    U R                   " [        U/5      U40 UD6 S h  vN   g  N7fr  rs  iterr   s       rx   rO  RunnableSequence.stream  s&      >>$w-B6BBB   ",*,c           
       #    U R                   " UU R                  [        X"=(       d    0 R                  S5      =(       d    U R                  S940 UD6  S h  vN nU7v   M   N
 g 7fr  )r  r  r2   r   rh   rt   r  r   r   r  s        rx   rw  RunnableSequence.atransform  sc       >><R*<*<Z*H*UDIIV
 	
 	% K	 
s*   AA(A&A$A&A($A&&A(c               v   ^#    SU4S jjnU R                   " U" 5       U40 UD6  S h  vN nU7v   M   N
 g 7f)Nc                   >#    T 7v   g 7fr  r   r  s   rx   input_aiter-RunnableSequence.astream.<locals>.input_aiter       K   
r  r?  rw  rt   r  r   r   r  r  s    `    rx   rR  RunnableSequence.astream  6     	  ??;=&KFK 	%K	K   "9757979r   )rv  RunnableLikerh   rg   rw  Runnable[Any, Any] | Noner  zlist[Runnable[Any, Any]] | Noner  r  r  Noner  z	list[str])r  r  r  r)  r  r  r  r  r  r   r  r   r!  r#  r%  r  r9   r   r  r   r*  r  r:   r&  )
r  r=  r  rT   r   r)   r   r   r  r8  )
r  r?  r  rS   r   r)   r   r   r  r:  r<  r7  r>  r9  )'rp   r   rI  rJ  rK  rL  r    r  r  r  classmethodr"   r  rM  rv  r  r   rm  r   r   r   r   r   r   r  r   r   r  r  r  r=  r  r  rs  rO  rw  rR  rO  rn  ro  s   @rx   r   r   
  s   Ql  /',T'BF$B0
.
  +/26*.'
'
 '
 )	'

 0'
 ('
 
'
 '
R 3  3 5 5     $L $  $ $  $ 
5 
5 .26+6	6 6 

  

  B 
 
 
L
 
,
 
4 
L
 
-
 
4 <@!*!*$9!*LO!*	!* !*F  )-%*%* &%* 	%*
 
%* %*N  @D}"
 #(}"}" =}"
  }" }" 
}" }"~  @D@"
 #(@"@" =@"
  @" @" 
@" @"D"" 0" 	"
 " 
".$ 5 	
  
2  )-

 &
 	

 

 
  )-CC &C 	C
 
C C  )-# & 	
 
   )-

 &
 	

 

 
r{   r   c                    ^  \ rS rSr% SrS\S'    S     SU 4S jjjr\\SS j5       5       r	\\SS j5       5       r
\" S	S
9r\SSS.S U 4S jjjj5       r\\S!S j5       5       r\SS"U 4S jjj5       r\ S   S"S jj5       r\\S#S j5       5       r\SS$S jj5       r\S%S j5       r\ S       S&S jj5       r\ S       S'S jj5       r        S(S jr\ S       S)S jj5       r\ S       S*S jj5       r        S+S jr\ S       S,S jj5       r\ S       S-S jj5       rSrU =r$ ).r   i  a  Runnable that runs a mapping of `Runnable`s in parallel.

Returns a mapping of their outputs.

`RunnableParallel` is one of the two main composition primitives,
alongside `RunnableSequence`. It invokes `Runnable`s concurrently, providing the
same input to each.

A `RunnableParallel` can be instantiated directly or by using a dict literal
within a sequence.

Here is a simple example that uses functions to illustrate the use of
`RunnableParallel`:

    ```python
    from langchain_core.runnables import RunnableLambda


    def add_one(x: int) -> int:
        return x + 1


    def mul_two(x: int) -> int:
        return x * 2


    def mul_three(x: int) -> int:
        return x * 3


    runnable_1 = RunnableLambda(add_one)
    runnable_2 = RunnableLambda(mul_two)
    runnable_3 = RunnableLambda(mul_three)

    sequence = runnable_1 | {  # this dict is coerced to a RunnableParallel
        "mul_two": runnable_2,
        "mul_three": runnable_3,
    }
    # Or equivalently:
    # sequence = runnable_1 | RunnableParallel(
    #     {"mul_two": runnable_2, "mul_three": runnable_3}
    # )
    # Also equivalently:
    # sequence = runnable_1 | RunnableParallel(
    #     mul_two=runnable_2,
    #     mul_three=runnable_3,
    # )

    sequence.invoke(1)
    await sequence.ainvoke(1)

    sequence.batch([1, 2, 3])
    await sequence.abatch([1, 2, 3])
    ```

`RunnableParallel` makes it easy to run `Runnable`s in parallel. In the below
example, we simultaneously stream output from two different `Runnable` objects:

    ```python
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_core.runnables import RunnableParallel
    from langchain_openai import ChatOpenAI

    model = ChatOpenAI()
    joke_chain = (
        ChatPromptTemplate.from_template("tell me a joke about {topic}") | model
    )
    poem_chain = (
        ChatPromptTemplate.from_template("write a 2-line poem about {topic}")
        | model
    )

    runnable = RunnableParallel(joke=joke_chain, poem=poem_chain)

    # Display stream
    output = {key: "" for key, _ in runnable.output_schema()}
    for chunk in runnable.stream({"topic": "bear"}):
        for key in chunk:
            output[key] = output[key] + chunk[key].content
        print(output)  # noqa: T201
    ```
z"Mapping[str, Runnable[Input, Any]]ru  Nc           
        > Ub  0 UEO0 nUR                  U5        [        TU ]	  UR                  5        VVs0 s H  u  pEU[	        U5      _M     snnS9  gs  snnf )zsCreate a `RunnableParallel`.

Args:
    steps__: The steps to include.
    **kwargs: Additional steps to include.

N)ru  )r  rT  r  r   r   )rt   ru  r   mergedra  rro   s         rx   r  RunnableParallel.__init__=  s[    ( !( 3Gf>DllnMnFCS,Q//nM 	 	
Ms   A
c                    gr  r   r  s    rx   r  #RunnableParallel.is_lc_serializableW  r  r{   c                
    / SQ$ r  r   r  s    rx   r  !RunnableParallel.get_lc_namespace]  r  r{   Tr  ri   c                  > U=(       d@    U R                   =(       d-    SSR                  U R                  R                  5       5       S3n[        TU ]  XS9$ )zGet the name of the `Runnable`.

Args:
    suffix: The suffix to use.
    name: The name to use.

Returns:
    The name of the `Runnable`.

zRunnableParallel<,>ri   )rh   r  ru  r   rT  ry   rt   ru   rh   ro   s      rx   ry   RunnableParallel.get_namek  sM     XtyyX&7ARARAT8U7VVW$Xw22r{   c                    U R                   R                  5        H"  nUR                  (       d  M  UR                  s  $    [        $ r  )ru  r   r   r   )rt   r  s     rx   r   RunnableParallel.InputTypez  s5     LL'')D~~~~~% * 
r{   c                  >^ [        U4S jU R                  R                  5        5       5      (       Ga  U R                  R                  5        HY  nUR                  T5      R                  nUR                  S5      nUc  M4  UR                  [        :w  d  MJ  [        TU ]  T5      s  $    [        U R                  S5      U R                  R                  5        VVVs0 s HV  nUR                  T5      R                  R                  5         H%  u  pVUS:w  d  M  XVR                  UR                  4_M'     MX     snnnS9$ [        TU ]  T5      $ s  snnnf )r  c              3     >#    U  H7  nUR                  T5      R                  5       R                  S S5      S:H  v   M9     g7f)r^  objectN)r   r   r   )r  r  r   s     rx   r  4RunnableParallel.get_input_schema.<locals>.<genexpr>  sC      
 + v&88:>>vxP*s   ?Ar   r9   __root__r   )allru  r   r   r_  r   r   r   rT  rR   ry   r   r   )rt   r   r  r\  
root_fieldry  rz  ro   s    `     rx   r   !RunnableParallel.get_input_schema  s,     
 \\((*
 
 

 ++-..v6CC#ZZ/
)j.C.Cs.J 73F;;	 . #g& !% 3 3 5# 5 $ 5 5f = J J P P RJ 1Aaii00 R  5#  w'//#s    9E Ec                    U R                   R                  5        VVs0 s H  u  p#X#R                  S4_M     nnn[        U R	                  S5      US9$ s  snnf )r  .r:   r   )ru  r   r   rR   ry   )rt   r   ry  rz  r\  s        rx   r   "RunnableParallel.get_output_schema  sQ     6:\\5G5G5IJ5ITQ!llC((5IJt}}X6&QQ Ks   Ac                V    [        S U R                  R                  5        5       5      $ )r  c              3  J   #    U  H  oR                     H  o"v   M     M     g 7fr  r   )r  r  r   s      rx   r  0RunnableParallel.config_specs.<locals>.<genexpr>  s!      '
2T?P?PtD?PD2   !#)rC   ru  r   r   s    rx   r   RunnableParallel.config_specs  s+     ' '
!\\002'
 
 	
r{   c                @   SSK Jn  U" 5       nUR                  U R                  U5      5      nUR                  U R	                  U5      5      nU R
                  R                  5        H  nUR                  5       nUR                  5         UR                  5         U(       d  UR                  XE5        MM  UR                  U5      u  pU(       d  SU S3n
[        U
5      eU	(       d  SU S3n
[        U
5      eUR                  XH5        UR                  X5        M     U$ )r  r   rY   r   r   has no last node)r   rZ   r   r   r   ru  r   r   r  r  r   r  r`  )rt   r   rZ   r   r   r   r  r  r  step_last_noder   s              rx   r   RunnableParallel.get_graph  s     	9^^D$9$9&$AB
nnT%;%;F%CDLL'')D)J&&(%%'z727,,z2J/&%dV+=>C$S/)%%dV+<=C$S/)z;~; *" r{   c                r    SR                  S U R                  R                  5        5       5      nSU-   S-   $ )Nz,
  c              3  f   #    U  H'  u  pU S [        [        U5      SU-   S -   5       3v   M)     g7f)z: z  N)rD   r  )r  ry  rz  s      rx   r  ,RunnableParallel.__repr__.<locals>.<genexpr>  s9      $
, c,T!WdQhoFGH,   /1z{
  z
})r  ru  r   )rt   map_for_reprs     rx   r  RunnableParallel.__repr__  s<    || $
**,$
 
 %--r{   c                  ^ [        U5      n[        R                  " UR                  S5      S SUR                  S5      S UR                  S5      S S9nUR	                  S UUR                  S5      =(       d    U R                  5       UR                  SS 5      S9m          SU4S	 jjn [        U R                  5      n[        U5       nUR                  5        VV	s/ s H  u  pUR                  XYXU5      PM     n
nn	[        XjSS
9 VVs0 s H  u  pXR                  5       _M     nnnS S S 5        TR                  W5        U$ s  sn	nf s  snnf ! , (       d  f       N-= f! [         a  nTR!                  U5        e S nAff = f)Nr  Fr  r   r  r  r  r  c                   > [        UTR                  SU 35      S9n[        U5       nUR                  U R                  UU5      sS S S 5        $ ! , (       d  f       g = f)Nmap:key:r  )r2   r  r4   r  r  r  r  r   ra  r  r  r  s         rx   _invoke_step-RunnableParallel.invoke.<locals>._invoke_step
  sX     (%//(3%0@AL
 $L1W{{KK  211s   A
Ar'  
r  r  r  r9   r   r)   ra  r   r  r   )r,   r%   r  r   r  ry   r0  r   ru  r0   r   r/  r.  r1  r  r  r  )rt   r  r   r   r  rB  rv  r  ra  r  r3  r5  rv  r  r  s                 @rx   r  RunnableParallel.invoke  s   
 v&*44"(**["9 #ZZ/!'J!7
 '55J':4==?::h-	 6 
	&	05	?M	TW		 	&E(0H &+[[]%2	 OOLsK%2   (+5%'H'H ('H   1 $$V,M 10  	&&q)	sN   / E) E#EEE.E1E) E
E&"E) )
F
3FF
c           	     Z  ^^^	^
#    [        T5      m[        T5      nUR                  S TTR                  S5      =(       d    U R	                  5       TR                  SS 5      S9I S h  vN m
          SU
4S jjm	 [        U R                  5      n[        R                  " U	UU4S jUR                  5        5       6 I S h  vN n[        [        XVSS95      nT
R                  U5      I S h  vN   U$  N N4 N
! [         a   nT
R                  U5      I S h  vN    e S nAff = f7f)	Nr  r  r  c                   >#    [        UTR                  SU 35      S9n[        U5       n[        U R	                  X5      USS9I S h  vN sS S S 5        $  N! , (       d  f       g = f7f)Nr@  r  Tr  )r2   r  r4   r=   r  rA  s         rx   _ainvoke_step/RunnableParallel.ainvoke.<locals>._ainvoke_stepA  sh      (%//(3%0@AL $L1W.LL6T  21 21s.   (A*A	A
A
A*A
A'#A*c              3  >   >#    U  H  u  pT" UTTU5      v   M     g 7fr  r   )r  ra  r  rH  r   r  s      rx   r  +RunnableParallel.ainvoke.<locals>.<genexpr>R  s4      	 &3	 "  &3s   Fr'  rD  )r,   r-   r  r   ry   r0  r   ru  rI  r  r   r.  r  r  r  )rt   r  r   r   r  rv  resultsrv  r  rH  r  s    ``      @@rx   r  RunnableParallel.ainvoke/  s0     v&@H,;;J':4==?::h-	 < 
 

	&
	05
	?M
	TW
	
		&E#NN	 &+[[]	 G #eU;<F **6222MU
.$ 3	  	,,Q///	sg   A"D+(C8)D+ AC> C:C> D+1C<2D+:C> <D+>
D(D#DD##D((D+c              #    #    [        U R                  5      n[        [        U[	        U5      [
        R                  " 5       S95      n[        U5       nUR                  5        VVs/ s H@  u  pxUUR                  UR                  5       [        X2R                  SU 35      S95      4PMB     n	nnU	 V
Vs0 s H  u  pUR                  [        U5      X4_M     nn
nU(       an  [        U[         S9u  pU HO  nUR                  U5      u  p [#        XR%                  5       05      nUv   U
U4XR                  [        U5      '   MQ     U(       a  Mn  S S S 5        g s  snnf s  snn
f ! [&         a     M~  f = f! , (       d  f       g = f7f)Nlockr@  r  r)  )r   ru  r  rQ   r   	threadingLockr0   r   rs  r0  r2   r  r/  r  r   r   r5   r1  r  )rt   r  r  r   rv  input_copiesr  rh   r  named_generators	step_name	generatorr3  completed_futuresrm   r5  r  s                    rx   r  RunnableParallel._transformf  s~     T\\" GFCJY^^=MNO$V, #(++-  #0JD NN$((*$".C.ChtfDU.V #0    -=,<(I i092HH,<   '+G'Q$!/F-4[[-@*Y +Y,H I#%%Ei @A 0 '- -, $ ) C -,sa   AF	E8'AE.E86$E!2E88E'E8	F	E8'
E51E84E55E88
FF	c              +  \   #    U R                   " XR                  U40 UD6 S h  vN   g  N7fr  )r  r  r   s       rx   rs  RunnableParallel.transform  s0      55??F
.4
 	
 	
r  c              +  X   #    U R                  [        U/5      U5       S h  vN   g  N7fr  r  r   s       rx   rO  RunnableParallel.stream  s!      >>$w-888s    *(*c               4  #    [        U R                  5      n[        [        U[	        U5      [
        R                  " 5       S95      nUR                  5        VVs/ s H@  u  pgUUR                  UR                  5       [        X2R                  SU 35      S95      4PMB     nnnSS jn	U V
Vs0 s H#  u  p[
        R                  " U	" U5      5      X4_M%     nn
nU(       a  [
        R                  " U[
        R                  S9I S h  vN u  pU HX  nUR                  U5      u  p [        XR!                  5       05      nU7v   [
        R                  " U	" U5      5      nX4UU'   MZ     U(       a  M  g g s  snnf s  snn
f  N{! ["         a     M  f = f7f)NrO  r@  r  c                4   #    [        U 5      I S h  vN $  N7fr  )r  )rV  s    rx   get_next_chunk4RunnableParallel._atransform.<locals>.get_next_chunk  s     y))))s   r)  )rV  r   r  zOutput | None)r   ru  r  rP   r   rI  rR  r   rw  r0  r2   r  r  r   r   r5   r1  r
  )rt   r  r  r   rv  rS  rh   r  rT  r_  rU  rV  taskscompleted_tasksrm   taskr  new_tasks                     rx   r  RunnableParallel._atransform  s     T\\" DU',,.IJ $kkm
 ,
  $$& *?*?(4&@Q*R , 	 
	* )9
(8$	 y 9:Y<RR(8 	 
 '.||7#:#:( "O ().4&'KKM(BCEK&22>)3LMH'0&<E(O (	 e3
$
" * sV   AFAE9"F/*E?0F	F
F)AF*F7F
FFFFc               n   #    U R                   " XR                  U40 UD6  S h  vN nU7v   M   N
 g 7fr  )r  r  r  s        rx   rw  RunnableParallel.atransform  s@       >>##V
/5
 	% K	 
s   5313535c               r   ^#    SU4S jjnU R                  U" 5       U5        S h  vN nU7v   M   N
 g 7f)Nc                   >#    T 7v   g 7fr  r   r  s   rx   r  -RunnableParallel.astream.<locals>.input_aiter  r  r  r  r  r  s    `    rx   rR  RunnableParallel.astream  s1     	  ??;=&A 	%K	As    7535757r   r  )ru  zMapping[str, Runnable[Input, Any] | Callable[[Input], Any] | Mapping[str, Runnable[Input, Any] | Callable[[Input], Any]]] | Noner   zkRunnable[Input, Any] | Callable[[Input], Any] | Mapping[str, Runnable[Input, Any] | Callable[[Input], Any]]r  r  r  r  r  r  r   r  r  r   r  )r  r9   r   r  r   r   r  r  )r  r9   r   r  r   r*  r  r  )r  r=  r  rT   r   r)   r  zIterator[AddableDict])r  r=  r   r  r   r   r  Iterator[dict[str, Any]])r  r9   r   r  r   r*  r  rm  )r  r?  r  rS   r   r)   r  zAsyncIterator[AddableDict])r  r?  r   r  r   r   r  AsyncIterator[dict[str, Any]])r  r9   r   r  r   r*  r  rn  )rp   r   rI  rJ  rK  rL  r  r  r"   r  r  r   rm  ry   rM  r   r   r   r   r   r  r  r  r  rs  rO  r  rw  rR  rO  rn  ro  s   @rx   r   r     s   Qf 0/ 

F
 

 
4    3  3  $L 3 3 3 3     0  0  0D .2R+R	R R 	
  	
 $ $L . . <@99$99LO9	9 9v  )-44 &4 	4
 
4 4l-- 0- 	-
 
-^  )-

 &
 	

 
"
 
  )-99 &9 	9
 
"9 91$1 51 	1
 
$1f  )-	#	 &	 		
 
'	 	  )-

 &
 	

 
'
 
r{   r   c                     \ rS rSrSr SSS.       SS jjjr\\SS j5       5       r\SSS jj5       r	\\SS j5       5       r
\ S   SS	 jj5       r\SS
 j5       rSr\SS j5       r\ S       SS jj5       r\ S       SS jj5       r\ S       SS jj5       r\ S       SS jj5       r\ S       SS jj5       r\ S       SS jj5       rSrg)RunnableGeneratori  u,  `Runnable` that runs a generator function.

`RunnableGenerator`s can be instantiated directly or by using a generator within
a sequence.

`RunnableGenerator`s can be used to implement custom behavior, such as custom
output parsers, while preserving streaming capabilities. Given a generator function
with a signature `Iterator[A] -> Iterator[B]`, wrapping it in a
`RunnableGenerator` allows it to emit output chunks as soon as they are streamed
in from the previous step.

!!! note
    If a generator function has a `signature A -> Iterator[B]`, such that it
    requires its input from the previous step to be completed before emitting chunks
    (e.g., most LLMs need the entire prompt available to start generating), it can
    instead be wrapped in a `RunnableLambda`.

Here is an example to show the basic mechanics of a `RunnableGenerator`:

    ```python
    from typing import Any, AsyncIterator, Iterator

    from langchain_core.runnables import RunnableGenerator


    def gen(input: Iterator[Any]) -> Iterator[str]:
        for token in ["Have", " a", " nice", " day"]:
            yield token


    runnable = RunnableGenerator(gen)
    runnable.invoke(None)  # "Have a nice day"
    list(runnable.stream(None))  # ["Have", " a", " nice", " day"]
    runnable.batch([None, None])  # ["Have a nice day", "Have a nice day"]


    # Async version:
    async def agen(input: AsyncIterator[Any]) -> AsyncIterator[str]:
        for token in ["Have", " a", " nice", " day"]:
            yield token


    runnable = RunnableGenerator(agen)
    await runnable.ainvoke(None)  # "Have a nice day"
    [p async for p in runnable.astream(None)]  # ["Have", " a", " nice", " day"]
    ```

`RunnableGenerator` makes it easy to implement custom behavior within a streaming
context. Below we show an example:

    ```python
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_core.runnables import RunnableGenerator, RunnableLambda
    from langchain_openai import ChatOpenAI
    from langchain_core.output_parsers import StrOutputParser


    model = ChatOpenAI()
    chant_chain = (
        ChatPromptTemplate.from_template("Give me a 3 word chant about {topic}")
        | model
        | StrOutputParser()
    )


    def character_generator(input: Iterator[str]) -> Iterator[str]:
        for token in input:
            if "," in token or "." in token:
                yield "👏" + token
            else:
                yield token


    runnable = chant_chain | character_generator
    assert type(runnable.last) is RunnableGenerator
    "".join(runnable.stream({"topic": "waste"}))  # Reduce👏, Reuse👏, Recycle👏.


    # Note that RunnableLambda can be used to delay streaming of one step in a
    # sequence until the previous step is finished:
    def reverse_generator(input: str) -> Iterator[str]:
        # Yield characters of input in reverse order.
        for character in input[::-1]:
            yield character


    runnable = chant_chain | RunnableLambda(reverse_generator)
    "".join(runnable.stream({"topic": "waste"}))  # ".elcycer ,esuer ,ecudeR"
    ```
Nri   c               *   Ub  X l         Un[        U5      (       a	  Xl         UnO=[        R                  " U5      (       a	  Xl        UnOS[        U5       3n[        U5      e U=(       d    UR                  U l        g! [         a
    SU l         gf = f)zInitialize a `RunnableGenerator`.

Args:
    transform: The transform function.
    atransform: The async transform function.
    name: The name of the `Runnable`.

Raises:
    TypeError: If the transform is not a generator function.

NzTExpected a generator function type for `transform`.Instead got an unsupported type: rp  )
r  rF   r   isgeneratorfunctionr  r^  r   rp   rh   AttributeError)rt   rs  rw  rh   func_for_namer   s         rx   r  RunnableGenerator.__init__V  s    ( !)&0Mi(((%M((33'O%M448O3DF  C. 	,6 6 6DI 	,+DI	,s   #A> >BBc                   [        U SS 5      =(       d    U R                  n [        R                  " U5      R                  n[        [        UR                  5       5      S 5      nU(       aG  UR                  [        R                  R                  :w  a  [        UR                  S[        45      S   $ [        $ ! [         a     [        $ f = fNr  __args__r   )getattrr  r   	signature
parametersr  r  r   r   	Parameteremptyr   r`  rt   r  paramsfirst_params       rx   r   RunnableGenerator.InputType  s     t\40DD4D4D	&&t,77FtFMMO4d;K{559J9J9P9PP{55zC6J1MM 
  	
	s   BB9 9
C
Cc                6   U R                   n[        U SS 5      =(       d    U R                  n[        USS 5      n[        R                  " U5      (       a,  [        U[        5      (       d  [        U[        5      (       a  U$ [        U R                  S5      UUS9$ )Nr  r   r9   r   )r   ry  r  r   r   r   r   r   r   rR   ry   rt   r   r   r  modules        rx   r   "RunnableGenerator.get_input_schema  s    
 NN	t\40DD4D4D|T2 OOI&&y,779i00MM'" 
 	
r{   c                6   [        U SS 5      =(       d    U R                  n [        R                  " U5      nUR                  [        R
                  R                  :w  a  [        UR                  S[        45      S   $ [        $ ! [         a	    [        s $ f = frw  )	ry  r  r   rz  return_annotation	Signaturer}  r   r`  rt   r  sigs      rx   r   RunnableGenerator.OutputType  s     t\40DD4D4D	##D)C ((G,=,=,C,CC --zC6B1E 
  	J	s   AB ?B BBc                6   U R                   n[        U SS 5      =(       d    U R                  n[        USS 5      n[        R                  " U5      (       a,  [        U[        5      (       d  [        U[        5      (       a  U$ [        U R                  S5      UUS9$ )Nr  r   r:   r   )r   ry  r  r   r   r   r   r   r   rR   ry   r  s        rx   r   #RunnableGenerator.get_output_schema  s     OO	t\40DD4D4D|T2 OOI&&y,779i00MM(# 
 	
r{   c                   [        U[        5      (       aw  [        U S5      (       a*  [        US5      (       a  U R                  UR                  :H  $ [        U S5      (       a*  [        US5      (       a  U R                  UR                  :H  $ gg)Nr  r  F)r   rp  rn   r  r  r   s     rx   __eq__RunnableGenerator.__eq__  st    e.//t\**wul/K/K%*:*:::t]++}0M0M''5+<+<<<r{   c                "    SU R                    S3$ )NzRunnableGenerator()ri   r   s    rx   r  RunnableGenerator.__repr__  s    #DII;a00r{   c                    [        U S5      (       d  U < S3n[        U5      eU R                  " UU R                  U4SS0UD6$ )Nr  z only supports async methods.r  T)rn   rj  r  r  rt   r  r   r   r   s        rx   rs  RunnableGenerator.transform  s]     t\**H9:C%c**11OO
 	

 
 	
r{   c                >    U R                   " [        U/5      U40 UD6$ r  r  r   s       rx   rO  RunnableGenerator.stream        ~~dE7mV>v>>r{   c                d    S nU R                   " X40 UD6 H  nUc  UOXE-   nM     [        SU5      $ Nr:   )rO  r   rt   r  r   r   rr  rv  s         rx   r  RunnableGenerator.invoke  s;      $kk%:6:F#mFE ;He$$r{   c                    [        U S5      (       d  U < S3n[        U5      eU R                  " XR                  U4SS0UD6$ )Nr  z only supports sync methods.r  T)rn   rj  r  r  r  s        rx   rw  RunnableGenerator.atransform  sW     t]++H89C%c**22##V
;?
CI
 	
r{   c                F   ^ SU4S jjnU R                   " U" 5       U40 UD6$ )Nc                   >#    T 7v   g 7fr  r   r  s   rx   r  .RunnableGenerator.astream.<locals>.input_aiter  r  r  r  r  )rt   r  r   r   r  s    `   rx   rR  RunnableGenerator.astream  s"    	 {}f???r{   c                z   #    S nU R                   " X40 UD6  S h  vN nUc  UOXE-   nM   N
 [        SU5      $ 7fr  )rR  r   r  s         rx   r  RunnableGenerator.ainvoke  sH       $ LLA&A 	@&#mFE	@AHe$$s   ;.,.;.;)r  r  rh   r  )rs  zgCallable[[Iterator[Input]], Iterator[Output]] | Callable[[AsyncIterator[Input]], AsyncIterator[Output]]rw  z>Callable[[AsyncIterator[Input]], AsyncIterator[Output]] | Nonerh   rg   r  r  rl  r  r   r&  r  r)  r  r  r=  r   r  r   r   r  r8  )r  r9   r   r  r   r   r  r8  r%  r  r?  r   r  r   r   r  r:  )r  r9   r   r  r   r   r  r:  )rp   r   rI  rJ  rK  r  rM  r"   r   r   r   r   r  __hash__r  rs  rO  r  rw  rR  r  rO  r   r{   rx   rp  rp    sW   Y@ (,  (,B(,	(, (, 
(,T 	  	 
 
2 
  
 .2
+
	
 
4   H1 1  )-

 &
 	

 

 
"  )-?? &? 	?
 
? ? <@%%$9%LO%	% %  )-
#
 &
 	

 

 
  )-	@	@ &	@ 		@
 
	@ 	@ <@%%$9%LO%	% %r{   rp  c                    ^  \ rS rSrSr  S       SS jjr\\SS j5       5       r\SSU 4S jjj5       r	\\SS j5       5       r
\ S   SS jj5       r\R                  SS	 j5       r\\SS
 j5       5       r\SS U 4S jjj5       r\S!S j5       rSrS"S jr          S#S jr          S$S jr\ S       S%S jj5       r\ S       S%S jj5       r          S&S jr\ S       S'S jj5       r\ S       S(S jj5       r          S)S jr\ S       S*S jj5       r\ S       S+S jj5       rSrU =r$ ),RunnableLambdai)  a  `RunnableLambda` converts a python callable into a `Runnable`.

Wrapping a callable in a `RunnableLambda` makes the callable usable
within either a sync or async context.

`RunnableLambda` can be composed as any other `Runnable` and provides
seamless integration with LangChain tracing.

`RunnableLambda` is best suited for code that does not need to support
streaming. If you need to support streaming (i.e., be able to operate
on chunks of inputs and yield chunks of outputs), use `RunnableGenerator`
instead.

Note that if a `RunnableLambda` returns an instance of `Runnable`, that
instance is invoked (or streamed) during execution.

Examples:
    ```python
    # This is a RunnableLambda
    from langchain_core.runnables import RunnableLambda


    def add_one(x: int) -> int:
        return x + 1


    runnable = RunnableLambda(add_one)

    runnable.invoke(1)  # returns 2
    runnable.batch([1, 2, 3])  # returns [2, 3, 4]

    # Async is supported by default by delegating to the sync implementation
    await runnable.ainvoke(1)  # returns 2
    await runnable.abatch([1, 2, 3])  # returns [2, 3, 4]


    # Alternatively, can provide both synd and sync implementations
    async def add_one_async(x: int) -> int:
        return x + 1


    runnable = RunnableLambda(add_one, afunc=add_one_async)
    runnable.invoke(1)  # Uses add_one
    await runnable.ainvoke(1)  # Uses add_one_async
    ```
Nc                   Ub  X l         Un[        U5      (       d  [        U5      (       a  Ub  Sn[        U5      eXl         UnO=[	        U5      (       a  [        SU5      U l        UnOS[        U5       3n[        U5      e Ub  X0l        O!UR                  S:w  a  UR                  U l        SU l        g! [         a     Nf = f)a  Create a `RunnableLambda` from a callable, and async callable or both.

Accepts both sync and async variants to allow providing efficient
implementations for sync and async execution.

Args:
    func: Either sync or async callable
    afunc: An async callable that takes an input and returns an output.

    name: The name of the `Runnable`.

Raises:
    TypeError: If the `func` is not a callable type.
    TypeError: If both `func` and `afunc` are provided.

NzFunc was provided as a coroutine function, but afunc was also provided. If providing both, func should be a regular function to avoid ambiguity.Callable[[Input], Output]zEExpected a callable type for `func`.Instead got an unsupported type: z<lambda>)afuncrE   rF   r   callabler   r  r^  rh   rp   rs  _repr)rt   r  r  rh   rt  r   s         rx   r  RunnableLambda.__init__Y  s    R J&+MT""&8&>&> 3 
  n$J Md^^8$?DI M448J<A  C. 	 	'':5)22	 "&
  		s   	B6 !B6 6
CCc                v   [        U SS5      =(       d    U R                  n [        R                  " U5      R                  n[        [        UR                  5       5      S5      nU(       a4  UR                  [        R                  R                  :w  a  UR                  $ [        $ ! [         a     [        $ f = f)z)The type of the input to this `Runnable`.r  N)ry  r  r   rz  r{  r  r  r   r   r|  r}  r`  r   r~  s       rx   r   RunnableLambda.InputType  s     tVT*8djj	&&t,77FtFMMO4d;K{559J9J9P9PP"--- 
  	
	s   A=B& &
B87B8c                  > [        U SS5      =(       d    U R                  n[        U[        5      (       a  [	        U5      R                  SS5      SS R                  S5      n[        S U 5       5      (       a4  U Vs0 s H  oDSS [        S	4_M     nn[        U R                  S
5      US9$ [        USS5      n[        U R                  S
5      [        [           US9$ U R                  [        :w  a  [        TU ]9  U5      $ [        U5      =n(       a3  [        U R                  S
5      [         R#                  U[        S	45      S9$ [        TU ]9  U5      $ s  snf )zThe Pydantic schema for the input to this `Runnable`.

Args:
    config: The config to use.

Returns:
    The input schema for this `Runnable`.

r  Nzoperator.itemgetter(r  r|  z, c              3  f   #    U  H'  oS    S:H  =(       a    US   S:H  =(       a    US:g  v   M)     g7f)r   'r|  z''Nr   )r  re  s     rx   r  2RunnableLambda.get_input_schema.<locals>.<genexpr>  s3      PUQ3C48s?Ctt|CPUr;  r   .r9   r   r   r   )ry  r  r   r   r   replacesplitr)  r   rR   ry   r  r   rT  r   r@   r   fromkeys)	rt   r   r  r   re  r\  r  	dict_keysro   s	           rx   r   RunnableLambda.get_input_schema  sM    tVT*8djjdJ'' I%%&<bA#2FLLTRE PU   >CCUTq*sCj0UC&t}}W'=QWXXT<6F"g&#Y #  >>S 7+F338>>9>"g&"&--	C:"F 
 w'//- Ds   ?Ec                   [        U SS5      =(       d    U R                  n [        R                  " U5      nUR                  [        R
                  R                  :w  ax  [        UR                  SS5      [        R                  R                  [        R                  R                  1;   a  [        UR                  S[        45      S   $ UR                  $  [        $ ! [         a     [        $ f = f)zzThe type of the output of this `Runnable` as a type annotation.

Returns:
    The type of the output of this `Runnable`.

r  N
__origin__rx  r   )ry  r  r   rz  r  r  r}  collectionsabcr   r   r   r`  r  s      rx   r   RunnableLambda.OutputType  s     tVT*8djj	##D)C$$(9(9(?(??300,EOO,,OO11J  #3#8#8*sfMaPP,,, @ 
  	
	s   B)C C 
C10C1c                6   U R                   n[        U SS 5      =(       d    U R                  n[        USS 5      n[        R                  " U5      (       a,  [        U[        5      (       d  [        U[        5      (       a  U$ [        U R                  S5      UUS9$ )Nr  r   r:   r   )r   ry  r  r   r   r   r   r   r   rR   ry   r  s        rx   r    RunnableLambda.get_output_schema  s     OO	tVT*8djj|T2 OOI&&y,779i00MM(# 
 	
r{   c                   [        U S5      (       a  [        U R                  5      nO)[        U S5      (       a  [        U R                  5      nO/ n/ nU Hh  n[	        U[
        5      (       a  UR                  U5        M+  [	        [        USS5      [
        5      (       d  MM  UR                  UR                  5        Mj     U$ )zThe dependencies of this `Runnable`.

Returns:
    The dependencies of this `Runnable`. If the function has nonlocal
    variables that are `Runnable`s, they are considered dependencies.

r  r  __self__N)	rn   rA   r  r  r   re   r  ry  r  )rt   objectsdepsobjs       rx   r  RunnableLambda.deps  s     4  ,TYY7GT7##,TZZ8GG!C#x((C GCT:HEECLL)	 
 r{   c                :    [        S U R                   5       5      $ )Nc              3  J   #    U  H  oR                     H  o"v   M     M     g 7fr  r0  )r  depr   s      rx   r  .RunnableLambda.config_specs.<locals>.<genexpr>,  s       '
%S2B2B$D2BDIr2  )rC   r  r   s    rx   r   RunnableLambda.config_specs)  s"     ' '
 II'
 
 	
r{   c                \  > U R                   =n(       Ga  SSKJn  U" 5       nUR                  U R	                  U5      5      nUR                  U R                  U5      5      nU H  nUR                  5       nUR                  5         UR                  5         U(       d  UR                  XV5        MM  UR                  U5      u  pU	(       d  SU S3n[        U5      eU
(       d  SU S3n[        U5      eUR                  XY5        UR                  X5        M     U$ [        TU ]  U5      nU$ )Nr   rY   r   r  r5  )r  r   rZ   r   r   r   r   r  r  r   r  r`  rT  )rt   r   r  rZ   r   r   r   r  	dep_graphdep_first_nodedep_last_noder   ro   s               rx   r   RunnableLambda.get_graph0  s   994<GE(=(=f(EFJ..)?)?)GHKMMO	))+((* NN:;49LL4K1N) )#.@A(o-( )#.?@(o-NN:>NN=> &  G%f-Er{   c                   [        U[        5      (       aw  [        U S5      (       a*  [        US5      (       a  U R                  UR                  :H  $ [        U S5      (       a*  [        US5      (       a  U R                  UR                  :H  $ gg)Nr  r  F)r   r  rn   r  r  r   s     rx   r  RunnableLambda.__eq__N  sm    e^,,tV$$)?)?yyEJJ..tW%%'%*A*AzzU[[00r{   c                   U R                   c  [        U S5      (       aU  [        U R                  [        5      (       a6  S[        U R                  5      [        S5      S  S3U l         U R                   $ [        U S5      (       a3  S[        U R                  5      =(       d    S S3U l         U R                   $ [        U S5      (       a3  S[        U R                  5      =(       d    S S3U l         U R                   $ S	U l         U R                   $ )
z2Return a string representation of this `Runnable`.Nr  zRunnableLambda(z	operator.r  z...r  zRunnableLambda(afunc=zRunnableLambda(...))	r  rn   r   r  r   r   r   rB   r  r   s    rx   r  RunnableLambda.__repr__Z  s    ::tV$$DIIz)J)J.s499~c+>N>P/Q.RRST
 zz v&&./@/K/Tu.UUVW
 zz w''+,=djj,I,RU+SSTU 

 zz 3
zzr{   c           	        [         R                  " U R                  5      (       a9  S n[        [	        SU R                  5      UUU40 UD6 H  nUc  UnM
   XV-   nM     O[        U R                  XU40 UD6n[        U[        5      (       aK  US   nUS::  a  SU  SU S3n[        U5      eUR                  U[        UUR                  5       US-
  S95      n[	        S	U5      $ ! [
         a    Un M  f = f)
N#Callable[[Input], Iterator[Output]]recursion_limitr   &Recursion limit reached when invoking  with input .r   r  r  r:   )r   rr  r  r+   r   r   r   re   RecursionErrorr  r2   r  )	rt   r  r  r   r   rv  r  r  r   s	            rx   _invokeRunnableLambda._invokei  s"    &&tyy11$(F5:DIIF	
  >"F'!' 2		6;:@F fh''$%67O!#<TF,vhVWX  %S))]])335$3a$7F Hf%%- % '!&'s   C##C32C3c                  ^ ^^#    [        T S5      (       a  T R                  nOc[        R                  " T R                  5      (       a            SU 4S jjmO          SU 4S jjm[        T5      SUU4S jj5       nUn[        U5      (       aZ  S n[        [        S[        [        SU5      UTU40 UD65      5       IS h  vN n[        SU5        S h  vN n	Uc  U	nM   Xy-   nM  [        [        SU5      UTU40 UD6I S h  vN n[        U[        5      (       aS  TS	   n
U
S
::  a  ST  SU S3n[        U5      eUR                  U[        TUR!                  5       U
S-
  S95      I S h  vN n[        SU5      $  N N! [         a    U	n M  f = f
 S S S 5      IS h  vN    M  ! , IS h  vN  (       d  f       N= f N NW7f)Nr  r:   c                   > S n[        [        STR                  5      U UUR                  5       40 UD6 H  nUc  UnM
   XE-   nM     [        SU5      $ ! [         a    Un M.  f = f)Nr  r:   )r+   r   r  get_syncr   )r9  r  r   r   rv  r  rt   s         rx   r  %RunnableLambda._ainvoke.<locals>.func  s     -1F!=BDIIN#,,.	"
 !" ">%*F/)/"  &11 $- /)./s    AA$#A$c                P   > [        TR                  XUR                  5       40 UD6$ r  r+   r  r  )r9  r  r   r   rt   s       rx   r  r    s.     8		5+2F2F2HLR r{   c                 @   >#    [        TT/U Q70 UD6I S h  vN $  N7fr  r3   r}   r   r   r  s     rx   f"RunnableLambda._ainvoke.<locals>.f  #     ,VTKDKFKKKK   zAsyncGenerator[Any, Any]r	   r:  r  r   r  r  r  r   r  
r9  r9   r  rS   r   r)   r   r   r  r:   r}   r   r   r   r  r   )rn   r  r   rr  r  r   rF   rO   r   r*   r   r   re   r  r  r2   r  )rt   r9  r  r   r   r  r  rv  rO  r  r  r   r  s   `  `        @rx   _ainvokeRunnableLambda._ainvoke  sA     4!!JJE**499552 2!@2 +2 "	2
 2 22 !@ + "	
  4[L L Ee$$$(F.1Z/#	
 !	  #'+$ 
+% ~!&+%+^F 9Z'GM F fh''$%67O!#<TF,ugUVW  %S))!>>)335$3a$7 F Hf%%W
+  ) +%*F+$     0s   CG	F
GF1FFF"F1+F
/F11GGA'G5G6GF
FF1FF1G)F,*G1G7F:8GGGc                    [        U S5      (       a(  U R                  " U R                  U[        U5      40 UD6$ Sn[	        U5      e)a  Invoke this `Runnable` synchronously.

Args:
    input: The input to this `Runnable`.
    config: The config to use.
    **kwargs: Additional keyword arguments.

Returns:
    The output of this `Runnable`.

Raises:
    TypeError: If the `Runnable` is a coroutine function.

r  zGCannot invoke a coroutine function synchronously.Use `ainvoke` instead.)rn   r  r  r,   r   r  s        rx   r  RunnableLambda.invoke  sR    * 4  ))f% 	  Xnr{   c                n   #    U R                   " U R                  U[        U5      40 UD6I Sh  vN $  N7f)zInvoke this `Runnable` asynchronously.

Args:
    input: The input to this `Runnable`.
    config: The config to use.
    **kwargs: Additional keyword arguments.

Returns:
    The output of this `Runnable`.

N)r  r  r,   r   s       rx   r  RunnableLambda.ainvoke  s@     $ ,,MM&!
 	
 
 	
 
s   ,535c           	   +    #    SnU H  nU(       d  UnSnM   WU-   nM     [        R                  " U R                  5      (       a2  S n[	        U R                  WX240 UD6 H  n	U	v   Uc  U	nM   X-   nM     O[	        U R                  WX240 UD6n[        U[        5      (       aW  US   n
U
S::  a  SU  SU S3n[        U5      eUR                  U[        UUR                  5       U
S-
  S	95       H  n	U	v   M	     g [        R                  " U R                  5      (       d  [        S
U5      v   g g ! [          a    Un GM:  f = f! [          a    U	n M  f = f7f)NFTr  r   r  r  r  r   r  r:   )r   r   rr  r  r+   r   re   r  rO  r2   r  r   )rt   chunksr  r   r   rp  rq  rr  rv  r  r  r   s               rx   r  RunnableLambda._transform2  s     F
 ! $#!FNE  &&tyy11$(F5		5&9? >"F'!' 2		5&9?F
 fh''$%67O!#<TF,ugUVW  %S)))335$3a$7  ,,TYY77x(( 8M ! #"E# % '!&'sM   ED1AE/E3B>E1E=EEEEEEEc              +     #    [        U S5      (       a1  U R                  " UU R                  [        U5      40 UD6 S h  vN   g Sn[	        U5      e N7f)Nr  zGCannot stream a coroutine function synchronously.Use `astream` instead.)rn   r  r  r,   r   r  s        rx   rs  RunnableLambda.transformp  sc      4  99f% 	  )  C. s   =AA Ac                >    U R                   " [        U/5      U40 UD6$ r  r  r   s       rx   rO  RunnableLambda.stream  r  r{   c           	      ^ ^^#    SnU  S h  vN nU(       d  UnSnM   WU-   nM   N! [          a    Un M/  f = f
 [        T S5      (       a  T R                  nO][        R                  " T R
                  5      (       a  Sn	[        U	5      e          SU 4S jjm[        T5      SUU4S jj5       n
U
n[        U5      (       aW  S n[        S[        [        S	U5      WTU40 UD65        S h  vN  nU7v   Uc  UnM   X-   nM  ! [          a    Un M,  f = f
 O"[        [        S	U5      WTU40 UD6I S h  vN  n[        U[        5      (       a^  TS
   nUS::  a  ST  SU S3n	[        U	5      eUR                  U[        TUR                  5       US-
  S95        S h  vN  nU7v   M  
 g [        U5      (       d  [        SU5      7v   g g 7f)NFTr  zMCannot stream from a generator function asynchronously.Use .stream() instead.r:   c                P   > [        TR                  XUR                  5       40 UD6$ r  r  )r  r  r   r   rt   s       rx   r  (RunnableLambda._atransform.<locals>.func  s.     4IIv{/C/C/EIO r{   c                 @   >#    [        TT/U Q70 UD6I S h  vN $  N7fr  r  r  s     rx   r  %RunnableLambda._atransform.<locals>.f  r  r  r:  r	   r  r   r  r  r  r   r  )
r  r9   r  rS   r   r)   r   r   r  r:   r  )r   rn   r  r   rr  r  r   rF   r   r*   r   re   r  rR  r2   r  )rt   r  r  r   r   rp  rq  rr  r  r   r  rv  r  r  r  s   `  `          @rx   r  RunnableLambda._atransform  sL     " 	#&
 ! $#!FNE	# ! #"E# # 4!!JJE**49955-   n$< ' 	
  4[L L Ee$$$(F#'-U+	
 	  ' 'e >"F'!'$ '!&'!	 & 9Z'	
   F fh''$%67O!#<TF,ugUVW  %S))%~~)335$3a$7   e   $E**x(( +s   G=(=G*G=:G:B4G.D2C53D7GD	GDGD!G<D?=A%G"F3&F)'F3++Gc                  #    U R                   " UU R                  [        U5      40 UD6  S h  vN nU7v   M   N
 g 7fr  )r  r  r,   )rt   r  r   r   rv  s        rx   rw  RunnableLambda.atransform  sK      !??&!
 	
 	& L	 
s   )?=;=?=?c               v   ^#    SU4S jjnU R                   " U" 5       U40 UD6  S h  vN nU7v   M   N
 g 7f)Nc                   >#    T 7v   g 7fr  r   r  s   rx   r  +RunnableLambda.astream.<locals>.input_aiter  r  r  r  r  r  s    `    rx   rR  RunnableLambda.astream   r
  r  )r  r  r  rh   rG  )r  aA  Callable[[Input], Iterator[Output]] | Callable[[Input], Runnable[Input, Output]] | Callable[[Input], Output] | Callable[[Input, RunnableConfig], Output] | Callable[[Input, CallbackManagerForChainRun], Output] | Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output] | Callable[[Input], Awaitable[Output]] | Callable[[Input], AsyncIterator[Output]] | Callable[[Input, RunnableConfig], Awaitable[Output]] | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]] | Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]r  a-  Callable[[Input], Awaitable[Output]] | Callable[[Input], AsyncIterator[Output]] | Callable[[Input, RunnableConfig], Awaitable[Output]] | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]] | Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]] | Nonerh   rg   r  r  rl  r  r  )r  zlist[Runnable]r  r   r  r  )
r  r9   r  rT   r   r)   r   r   r  r:   r  r  )
r  r=  r  rT   r   r)   r   r   r  r8  r<  r7  )
r  r?  r  rS   r   r)   r   r   r  r:  r>  r9  ) rp   r   rI  rJ  rK  r  rM  r"   r   r   r   r   r  cached_propertyr  r   r   r  r  r  r  r  r  r  r  rs  rO  r  rw  rR  rO  rn  ro  s   @rx   r  r  )  s   -J /I&
I&I&. /I&0 
1I&V 
  
 )0 )0 )0V   , .2
+
	
 
4  . 
  

   :   H+&+& 0+& 	+&
 +& 
+&Zb&b& 5b& 	b&
 b& 
b&H  )- & 	
 
 <  )-

 &
 	

 

 
0<)<) 0<) 	<)
 <) 
<)|  )-!! &! 	!
 
! !(  )-?? &? 	?
 
? ?a)$a) 5a) 	a)
 a) 
a)F  )-# & 	
 
   )-

 &
 	

 

 
r{   r  c                     \ rS rSr% SrS\S'   \" SS9r\\	SS j5       5       r
\	SSS	 jj5       r\\	SS
 j5       5       r\	 S   SS jj5       r\\	SS j5       5       r\	SSS jj5       r\\	SS j5       5       r\\	SS j5       5       r          SS jr\	 S       SS jj5       r          S S jr\	 S       SS jj5       r\	 S       S!S jj5       rSrg)"RunnableEachBasei  zRunnableEachBase class.

`Runnable` that calls another `Runnable` for each element of the input sequence.

Use only if creating a new `RunnableEach` subclass with different `__init__`
args.

See documentation for `RunnableEach` for more details.

rA  rz  Tr  c                <    [         U R                  R                     $ r  )r  rz  r   r   s    rx   r   RunnableEachBase.InputType   s     DJJ(())r{   Nc                    [        U R                  S5      [        U R                  R	                  U5         S 4U R
                  R                  S9$ )Nr9   r   )rR   ry   r  rz  r   ro   r   r   s     rx   r   !RunnableEachBase.get_input_schema%  sI    MM'"TZZ0089 11
 	
r{   c                <    [         U R                  R                     $ r  )r  rz  r   r   s    rx   r   RunnableEachBase.OutputType7  s     DJJ))**r{   c                    U R                   R                  U5      n[        U R                  S5      [        U   U R
                  R                  S9$ )Nr:   r   )rz  r   rR   ry   r  ro   r   )rt   r   r  s      rx   r   "RunnableEachBase.get_output_schema<  sG     --f5MM(#f 11
 	
r{   c                .    U R                   R                  $ r  rz  r   r   s    rx   r   RunnableEachBase.config_specsN       zz&&&r{   c                8    U R                   R                  U5      $ r  )rz  r   r   s     rx   r   RunnableEachBase.get_graphS  s    zz##F++r{   c                    gr  r   r  s    rx   r  #RunnableEachBase.is_lc_serializableW  r  r{   c                
    / SQ$ r  r   r  s    rx   r  !RunnableEachBase.get_lc_namespace]  r  r{   c                    U Vs/ s H  n[        X2R                  5       S9PM     nnU R                  R                  " X40 UD6$ s  snf Nr  )r2   r  rz  r  rt   r  r  r   r   rm   r  s          rx   r  RunnableEachBase._invokeg  sQ     NT
MSL+@+@+BCV 	 
 zz:6::
s   !Ac                >    U R                   " U R                  X40 UD6$ r  )r  r  r   s       rx   r  RunnableEachBase.invokes  s      %%dllELVLLr{   c                   #    U Vs/ s H  n[        X2R                  5       S9PM     nnU R                  R                  " X40 UD6I S h  vN $ s  snf  N	7fr   )r2   r  rz  r=  r!  s          rx   r  RunnableEachBase._ainvokey  s]      NT
MSL+@+@+BCV 	 
 ZZ&&vA&AAA
 Bs   A!A"A
A
Ac                Z   #    U R                   " U R                  X40 UD6I S h  vN $  N7fr  )r  r  r   s       rx   r  RunnableEachBase.ainvoke  s)      ,,T]]ETVTTTTs   "+)+c               P   #    SS jn[        S5       H  nU" S5      7v   M     g 7f)Nc                    [        U 5      er  )rj  r  s    rx   _error_stream_event<RunnableEachBase.astream_events.<locals>._error_stream_event  s    %g..r{   r   z1RunnableEach does not support astream_events yet.)r  r   r  r\   )r  )rt   r  r   r   r+  rm   s         rx   rm  RunnableEachBase.astream_events  s*     	/ qA%C  s   $&r   rl  r  r  )r  ztype[list[Output]]r  r   r  r  )
r  r'  r  rT   r   r)   r   r   r  r  )r  r'  r   r  r   r   r  r  )
r  r'  r  rS   r   r)   r   r   r  r  r  r9   r   r  r   r*  r  r;  )rp   r   rI  rJ  rK  rL  r   rm  rM  r"   r   r   r   r   r   r   r  r  r  r  r  r  r  rm  rO  r   r{   rx   r  r    s    	 #" $L *  * 
 
" +  + .2
+
	
 
" '  ' , ,    3  3
;
; 0
; 	
;
 
; 

; BFM M*?MRUM	M M

B
B 5
B 	
B
 
B 

B BFU U*?URUU	U U
  )- & 	
 
$ r{   r  c                     ^  \ rS rSrSr\SSS.SU 4S jjjj5       r\SS j5       r\ S     SS jj5       r\SSSS.       SS	 jj5       r	SSSS.       SS
 jjr
SrU =r$ )r  i  a  RunnableEach class.

`Runnable` that calls another `Runnable` for each element of the input sequence.

It allows you to call multiple inputs with the bounded `Runnable`.

`RunnableEach` makes it easy to run multiple inputs for the `Runnable`.
In the below example, we associate and run three inputs
with a `Runnable`:

    ```python
    from langchain_core.runnables.base import RunnableEach
    from langchain_openai import ChatOpenAI
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_core.output_parsers import StrOutputParser
    prompt = ChatPromptTemplate.from_template("Tell me a short joke about
    {topic}")
    model = ChatOpenAI()
    output_parser = StrOutputParser()
    runnable = prompt | model | output_parser
    runnable_each = RunnableEach(bound=runnable)
    output = runnable_each.invoke([{'topic':'Computer Science'},
                                {'topic':'Art'},
                                {'topic':'Biology'}])
    print(output)  # noqa: T201

    ```
Nri   c                  > U=(       d1    U R                   =(       d    SU R                  R                  5        S3n[        TU ]	  XS9$ )NzRunnableEach<r  ri   )rh   rz  ry   rT  r   s      rx   ry   RunnableEach.get_name  s@    LtyyLmDJJ4G4G4I3J!$Lw22r{   c                H    [        U R                  R                  " S0 UD6S9$ )Nr  r   )r  rz  r~  r}  s     rx   r~  RunnableEach.bind  s    $**//";F";<<r{   c                J    [        U R                  R                  " U40 UD6S9$ )Nr  )r  rz  r  r  s      rx   r  RunnableEach.with_config  s#     $**"8"8"J6"JKKr{   r  c               D    [        U R                  R                  XUS9S9$ )aD  Bind lifecycle listeners to a `Runnable`, returning a new `Runnable`.

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.

Args:
    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.

Returns:
    A new `Runnable` with the listeners bound.

r  r  )r  rz  r  r  s       rx   r  RunnableEach.with_listeners  s.    @ **++!8 , 
 	
r{   c               D    [        U R                  R                  XUS9S9$ )av  Bind async lifecycle listeners to a `Runnable`.

Returns a new `Runnable`.

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.

Args:
    on_start: Called asynchronously before the `Runnable` starts running,
        with the `Run` object.
    on_end: Called asynchronously after the `Runnable` finishes running,
        with the `Run` object.
    on_error: Called asynchronously if the `Runnable` throws an error,
        with the `Run` object.

Returns:
    A new `Runnable` with the listeners bound.

r  r  )r  rz  r  r  s       rx   r  RunnableEach.with_alisteners  s-    6 **,,!8 - 
 	
r{   r   r  r  )r   r   r  RunnableEach[Input, Output])r   r  r   r   r  r:  )r  rD  r  rD  r  rD  r  r:  )r  rE  r  rE  r  rE  r  r:  )rp   r   rI  rJ  rK  r"   ry   r~  r  r  r  rO  rn  ro  s   @rx   r  r    s    : 3 3 3 3 = = .2L+L>AL	$L L
    #
#
#
#
 
%#
 #
P *.'+)-
 '
 %	

 '
 
%
 
r{   r  c                    ^  \ rS rSr% SrS\S'    \" \S9rS\S'    \" \	S9r
S\S	'    \" \S9rS
\S'    SrS\S'    SrS\S'    \" SS9rSSSSSS.               S1U 4S jjjr\S2SS.S3S jjj5       r\\S4S j5       5       r\\S5S j5       5       r\S2S6U 4S jjj5       r\ S2   S6U 4S jjj5       r\\S7S j5       5       r\S2S8S jj5       r\\S9S j5       5       r\\S:S j5       5       rS;S jr\ S2       S<S jj5       r\ S2       S<S  jj5       r \ S2S!S".         S=S# jjj5       r!\ S2S!S".         S=S$ jjj5       r"\# S2S!S".         S>S% jjj5       r$\# S2         S?S& jj5       r$\ S2S!S".         S@S' jjj5       r$\# S2S!S".         SAS( jjj5       r%\# S2         SBS) jj5       r%\ S2S!S".         SCS* jjj5       r%\ S2       SDS+ jj5       r&\ S2       SES, jj5       r'\ S2       SFS- jj5       r(\ S2       SGS. jj5       r)\ S2       SHS/ jj5       r*S0r+U =r,$ )IRunnableBindingBasei  z`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.

rA  rz  r  zMapping[str, Any]r   r)   r   z0list[Callable[[RunnableConfig], RunnableConfig]]r  Nr*  r  r  Tr  )r   r   r  r  r  c          
        > [         TU ]  " SUU=(       d    0 U=(       d    0 U=(       d    / UUS.UD6  U=(       d    0 U l        g)a<  Create a `RunnableBinding` from a `Runnable` and kwargs.

Args:
    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: optional config to bind to the underlying `Runnable`.

    config_factories: optional list of config factories to apply to the
        config before binding to the underlying `Runnable`.

    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.
rz  r   r   r  r  r  Nr   )rT  r  r   )	rt   rz  r   r   r  r  r  other_kwargsro   s	           rx   r  RunnableBindingBase.__init__?  sN    @ 	 	
<R<R-3/1	
 	
 lr{   ri   c               4    U R                   R                  XS9$ )Nri   )rz  ry   )rt   ru   rh   s      rx   ry   RunnableBindingBase.get_namem  s    zz""6"55r{   c                t    U R                   b  [        SU R                   5      $ U R                  R                  $ )Nr~   )r  r   rz  r   r   s    rx   r   RunnableBindingBase.InputTypeq  s;    
 %%1  6 67	
 %%	
r{   c                t    U R                   b  [        SU R                   5      $ U R                  R                  $ )Nr   )r  r   rz  r   r   s    rx   r   RunnableBindingBase.OutputTypez  s;    
 &&2 !8!89	
 &&	
r{   c                   > U R                   b  [        TU ]	  U5      $ U R                  R                  [	        U R
                  U5      5      $ r  )r  rT  r   rz  r1   r   rt   r   ro   s     rx   r   $RunnableBindingBase.get_input_schema  s?    !!-7+F33zz**=f+MNNr{   c                   > U R                   b  [        TU ]	  U5      $ U R                  R                  [	        U R
                  U5      5      $ r  )r  rT  r   rz  r1   r   rH  s     rx   r   %RunnableBindingBase.get_output_schema  sA     "".7,V44zz++M$++v,NOOr{   c                .    U R                   R                  $ r  r  r   s    rx   r    RunnableBindingBase.config_specs  r  r{   c                V    U R                   R                  U R                  U5      5      $ r  )rz  r   _merge_configsr   s     rx   r   RunnableBindingBase.get_graph  s"    zz##D$7$7$?@@r{   c                    gr  r   r  s    rx   r  &RunnableBindingBase.is_lc_serializable  r  r{   c                
    / SQ$ r  r   r  s    rx   r  $RunnableBindingBase.get_lc_namespace  r  r{   c                p   ^ [        U R                  /UQ76 m[        T/U4S jU R                   5       Q76 $ )Nc              3  2   >#    U  H  o" T5      v   M     g 7fr  r   )r  r  r   s     rx   r  5RunnableBindingBase._merge_configs.<locals>.<genexpr>  s     &P:OQqyy:Os   )r1   r   r  )rt   r  r   s     @rx   rO  "RunnableBindingBase._merge_configs  s2    t{{5W5VQ&P$:O:O&PQQr{   c                x    U R                   R                  " UU R                  U5      40 0 U R                  EUED6$ r  )rz  r  rO  r   r   s       rx   r  RunnableBindingBase.invoke  sD     zz  '
 (''
 	
r{   c                   #    U R                   R                  " UU R                  U5      40 0 U R                  EUED6I S h  vN $  N7fr  )rz  r  rO  r   r   s       rx   r  RunnableBindingBase.ainvoke  sQ      ZZ'''
 (''
 
 	
 
s   ?AAAFr  c          	     X   [        U[        5      (       a,  [        SU Vs/ s H  oPR                  U5      PM     sn5      nO2[	        [        U5      5       Vs/ s H  opR                  U5      PM     nnU R                  R                  " UU4SU00 U R                  EUED6$ s  snf s  snf Nzlist[RunnableConfig]r  )	r   r  r   rO  r  r   rz  r  r   rt   r  r   r  r   confr  rm   s           rx   r  RunnableBindingBase.batch  s     fd##&7=>vt$$T*v>G
 =B#f+<NO<Nq**62<NGOzz
 0
 (''	
 	
	 ? Ps   B"
B'c          	     t  #    [        U[        5      (       a,  [        SU Vs/ s H  oPR                  U5      PM     sn5      nO2[	        [        U5      5       Vs/ s H  opR                  U5      PM     nnU R                  R                  " UU4SU00 U R                  EUED6I S h  vN $ s  snf s  snf  N7fr^  )	r   r  r   rO  r  r   rz  r=  r   r_  s           rx   r=  RunnableBindingBase.abatch  s      fd##&7=>vt$$T*v>G
 =B#f+<NO<Nq**62<NGOZZ&&
 0
 (''	
 
 	
	 ? P
s'    B8B,
B8B143B8'B6(B8c                   g r  r   r  s        rx   r  &RunnableBindingBase.batch_as_completed  r  r{   c                   g r  r   r  s        rx   r  re     r!  r{   c          	   +    #    [        U[        5      (       a,  [        SU Vs/ s H  oPR                  U5      PM     sn5      nO2[	        [        U5      5       Vs/ s H  opR                  U5      PM     nnU(       a7  U R                  R                  " UU4SU00 U R                  EUED6 S h  vN   g U R                  R                  " UU4SU00 U R                  EUED6 S h  vN   g s  snf s  snf  NF N7fr^  )	r   r   r   rO  r  r   rz  r  r   r_  s           rx   r  re  
  s	     fh''&7=>vt$$T*v>G
 =B#f+<NO<Nq**62<NGOzz44 #4 ,T[[+F+	   zz44 #4 ,T[[+F+	   ? Ps9    C9C+
C9C04:C9.C5/6C9%C7&C97C9c                   g r  r   r  s        rx   r@  'RunnableBindingBase.abatch_as_completed*  rB  r{   c                   g r  r   r  s        rx   r@  ri  4  rD  r{   c          	      #    [        U[        5      (       a,  [        SU Vs/ s H  oPR                  U5      PM     sn5      nO2[	        [        U5      5       Vs/ s H  opR                  U5      PM     nnU(       a>  U R                  R                  " UU4SU00 U R                  EUED6  S h  vN nU7v   M  U R                  R                  " UU4SU00 U R                  EUED6  S h  vN nU7v   M  s  snf s  snf  NS
 g  N
 g 7fr^  )	r   r   r   rO  r  r   rz  r@  r   )	rt   r  r   r  r   r`  r  rm   re  s	            rx   r@  ri  >  s     fh''&7=>vt$$T*v>G
 =B#f+<NO<Nq**62<NGO"jj<< #4 ,T[[+F+	 d 
"jj<< #4 ,T[[+F+	 d 
' ? P  sc    DC9
DC>47D+D/D0D36D)D	-D.D	1DDDD		Dc              +     #    U R                   R                  " UU R                  U5      40 0 U R                  EUED6 S h  vN   g  N7fr  )rz  rO  rO  r   r   s       rx   rO  RunnableBindingBase.stream_  sL      ::$$'
 (''
 	
 	
   ?A	AA	c                  #    U R                   R                  " UU R                  U5      40 0 U R                  EUED6  S h  vN nU7v   M   N
 g 7fr  )rz  rR  rO  r   rt   r  r   r   re  s        rx   rR  RunnableBindingBase.astreaml  sZ      **,,'
 (''
 	$
 J	 
(   <AAAAAAAc                  #    U R                   R                  " XR                  U5      40 0 U R                  EUED6  S h  vN nU7v   M   N
 g 7fr  )rz  rm  rO  r   rp  s        rx   rm  "RunnableBindingBase.astream_eventsz  sU      **33&&v.
2KT[[2KF2K
 	$ J	 
s(   ;AAAAAAAc              +     #    U R                   R                  " UU R                  U5      40 0 U R                  EUED6 S h  vN   g  N7fr  )rz  rs  rO  r   r   s       rx   rs  RunnableBindingBase.transform  sL      ::'''
 (''
 	
 	
rn  c                  #    U R                   R                  " UU R                  U5      40 0 U R                  EUED6  S h  vN nU7v   M   N
 g 7fr  )rz  rw  rO  r   rp  s        rx   rw  RunnableBindingBase.atransform  sZ      **//'
 (''
 	$
 J	 
rr  r   )rz  rA  r   zMapping[str, Any] | Noner   r  r  z7list[Callable[[RunnableConfig], RunnableConfig]] | Noner  type[Input] | BaseModel | Noner  type[Output] | BaseModel | Noner?  r   r  r  r  r  r  r  r  r  r   r  r  )r  r  r  r)   r  r&  r+  r/  r2  r3  r4  r6  r7  r9  r.  r  r  )-rp   r   rI  rJ  rK  rL  r    r   r   r)   r   r  r  r  r  r   rm  r  r"   ry   rM  r   r   r   r   r   r   r  r  r  rO  r  r  r  r=  r   r  r@  rO  rR  rm  rs  rw  rO  rn  ro  s   @rx   r<  r<    sV    #"F %d ;F; #>BFNB:INJF  E %)z(
 &*
)
  $L ,0(,<@>B,# ',# )	,#
 &,#,# :,# <,# ,# 
,# ,#\ 6 6 6 
  
 
  
 O O O
 .2P+P	P P '  ' A A    3  3R  )-



 &

 	


 


 

  )-



 &

 	


 


 

  @D

 #(

 =

  
 
 

 
,  @D

 #(

 =

  
 
 

 
,  DH+
 -2++ A+
 *+ + 
&+ +  DH77 A7
 )7 7 
27 7  DH
 #( A
    
2 >  DH0
 -200 A0
 *0 0 
+0 0  DH<< A<
 )< < 
7< <  DH
 #( A
    
7 @  )-



 &

 	


 


 

  )- & 	
 
   )-		 &	 		
 
$	 	  )-



 &

 	


 


 

  )-# & 	
 
 r{   r<  c                      \ rS rSrSr\SS j5       r\ S     SS jj5       r\SSSS.       SS jj5       r\  S     SS jj5       r	\SS	 j5       r
\SS
 j5       rSrg)r|  i  a  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.

    ```python
    # Create a Runnable binding that invokes the chat model with the
    # additional kwarg `stop=['-']` when running it.
    from langchain_openai 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):

    ```python
    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`
    ```
c           	         U R                  U R                  U R                  U R                  0 U R                  EUEU R
                  U R                  S9$ )zBind additional kwargs to a `Runnable`, returning a new `Runnable`.

Args:
    **kwargs: 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.

)rz  r   r  r   r  r  )ro   rz  r   r  r   r  r  r}  s     rx   r~  RunnableBinding.bind  sT     ~~**;;!22,dkk,V,"44#66  
 	
r{   Nc           
         U R                  U R                  U R                  [        S0 U R                  EU=(       d    0 EUE5      U R
                  U R                  U R                  S9$ )Nr)   r>  )ro   rz  r   r   r   r  r  r  r  s      rx   r  RunnableBinding.with_config  sf     ~~**;;(*UT[[*UV\r*Uf*UV!22"44#66  
 	
r{   r  c          	        ^^^ SUUU4S jjnU R                  U R                  U R                  U R                  U/U R                  QU R
                  U R                  S9$ )aC  Bind lifecycle listeners to a `Runnable`, returning a new `Runnable`.

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.

Args:
    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.

Returns:
    A new `Runnable` with the listeners bound.
c                "   > S[        U TTTS9/0$ r  r  r  s    rx   listener_config_factory?RunnableBinding.with_listeners.<locals>.listener_config_factory  s)    '%!)%!)		 	r{   r>  )r   r)   r  r)   ro   rz  r   r   r  r  r  )rt   r  r  r  r  s    ``` rx   r  RunnableBinding.with_listeners  s^    @
	 
	 ~~**;;;;5N8M8MN"44#66  
 	
r{   c           	         U R                  U R                  U R                  U R                  U R                  Ub  UOU R
                  Ub  US9$ U R                  S9$ )Nr>  r  r  s      rx   r  RunnableBinding.with_types0  sm     ~~**;;;;!22(4
$:P:P  +6  
 	
 =A<S<S  
 	
r{   c                    U R                  U R                  R                  " S0 UD6U R                  U R                  U R
                  S9$ )N)rz  r   r   r  r   )ro   rz  r  r   r   r  r}  s     rx   r  RunnableBinding.with_retryC  sD    ~~**''1&1;;;;!22	  
 	
r{   c                :  ^ ^^ [        T R                  U5      m[        T5      (       a  [        R                  " T5      R
                  R                  S5      =n(       a  UR                  [        R                  R                  :X  a  [        T5      SUU 4S jj5       nU$ UR                  [        R                  R                  :X  aR  [        [        R                  " T5      R
                  5      R                  S5      m[        T5      SUUU 4S jj5       nU$ T$ )Nr   c                 `   > T" U S[        TR                  UR                  SS 5      5      0UD6$ )Nr   )r1   r   r0  )r}   r   attrrt   s     rx   wrapper,RunnableBinding.__getattr__.<locals>.wrapperU  s;    ,T[[&**Xt:TU ! r{   c                    > [        U 5      TS-   :  a/  [        U 5      n[        TR                  UT   5      UT'   T" U0 UD6$ T" U S[        TR                  UR	                  SS 5      5      0UD6$ )Nr   r   )r   r  r1   r   r0  )r}   r   argslr  r  rt   s      rx   r  r  a  s|    4yC!G+ $T
%24;;c
%Kc
#U5f55,T[[&**Xt:TU ! r{   r  )ry  rz  r  r   rz  r{  r   kindr|  KEYWORD_ONLYr   POSITIONAL_OR_KEYWORDr  index)rt   rh   config_paramr  r  r  s   `   @@rx   __getattr__RunnableBinding.__getattr__L  s    tzz4(D>>#--d3>>BB8LLLL  G$5$5$B$BBt    G$5$5$K$KK7,,T2==>DDXNt	 	 	 r{   r   r@  r  rB  rC  rG  )r  ry  r  rz  r  rA  )rh   r   r  r   )rp   r   rI  rJ  rK  r"   r~  r  r  r  r  r  rO  r   r{   rx   r|  r|    s    1f 
 
(  )-
%
 	

 
!
 
    2
2
2
2
 
!2
 2
h  6:7;
2
 5
 
!	
 
$ 
 
 " "r{   r|  c                      \ rS rSrSS jrSrg)_RunnableCallableSyncir  c                  g r  r   rt   _inr   s      rx   __call___RunnableCallableSync.__call__s  s    Cr{   r   N)r  r9   r   r)   r  r:   rp   r   rI  rJ  r  rO  r   r{   rx   r  r  r  s    Or{   r  c                  *    \ rS rSr      SS jrSrg)_RunnableCallableAsynciv  c                  g r  r   r  s      rx   r  _RunnableCallableAsync.__call__w  s    r{   r   N)r  r9   r   r)   r  zAwaitable[Output]r  r   r{   rx   r  r  v  s      (6 	 r{   r  c                  *    \ rS rSr      SS jrSrg)_RunnableCallableIteratori|  c                  g r  r   r  s      rx   r  "_RunnableCallableIterator.__call__}  s    r{   r   N)r  r=  r   r)   r  r8  r  r   r{   rx   r  r  |  s    "2@	r{   r  c                  *    \ rS rSr      SS jrSrg)_RunnableCallableAsyncIteratori  c                  g r  r   r  s      rx   r  '_RunnableCallableAsyncIterator.__call__  s     #r{   r   N)r  r?  r   r)   r  r:  r  r   r{   rx   r  r    s    $'$7E$	$r{   r  c                l   [        U [        5      (       a  U $ [        U 5      (       d  [        R                  " U 5      (       a  [        U 5      $ [        U 5      (       a  [        [        SU 5      5      $ [        U [        5      (       a  [        S[        U 5      5      $ S[        U 5       3n[        U5      e)zCoerce a `Runnable`-like object into a `Runnable`.

Args:
    thing: A `Runnable`-like object.

Returns:
    A `Runnable`.

Raises:
    TypeError: If the object is not `Runnable`-like.
r  rA  zGExpected a Runnable, callable or dict.Instead got an unsupported type: )r   re   rF   r   rr  rp  r  r  r   r   r   r^  r   )thingr   s     rx   r   r     s     %""%  G$?$?$F$F ''d#>FGG%-/?/FGG,,0K=	:  C.r{   c                    g r  r   r  s    rx   chainr         "r{   c                    g r  r   r  s    rx   r  r    r  r{   c                    g r  r   r  s    rx   r  r    r  r{   c                    g r  r   r  s    rx   r  r    r  r{   c                    [        U 5      $ )a|  Decorate a function to make it a `Runnable`.

Sets the name of the `Runnable` to the name of the function.
Any runnables called by the function will be traced as dependencies.

Args:
    func: A `Callable`.

Returns:
    A `Runnable`.

Example:
    ```python
    from langchain_core.runnables import chain
    from langchain_core.prompts import PromptTemplate
    from langchain_openai import OpenAI


    @chain
    def my_func(fields):
        prompt = PromptTemplate("Hello, {name}!")
        model = OpenAI()
        formatted = prompt.invoke(**fields)

        for chunk in model.stream(formatted):
            yield chunk
    ```
)r  r  s    rx   r  r    s    D $r{   )rv  r  r   r  r  r  )r  r  r  rA  )r  z.Callable[[Input], Coroutine[Any, Any, Output]]r  rA  )r  r  r  rA  )r  z(Callable[[Input], AsyncIterator[Output]]r  rA  )r  r  r  rA  )r  zCallable[[Input], Output] | Callable[[Input], Iterator[Output]] | Callable[[Input], Coroutine[Any, Any, Output]] | Callable[[Input], AsyncIterator[Output]]r  rA  )rK  
__future__r   rI  r  rV  r  r   rQ  r  r   r   collections.abcr   r   r   r	   r
   r   r   r   concurrent.futuresr   r   r   	itertoolsr   operatorr   typesr   typingr   r   r   r   r   r   r   r   r   r   pydanticr   r   r    r!   typing_extensionsr"   langchain_core._apir#    langchain_core.callbacks.managerr$   r%    langchain_core.load.serializabler&   r'   r(   langchain_core.runnables.configr)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   langchain_core.runnables.utilsr5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   !langchain_core.tracers._streamingrG   #langchain_core.tracers.event_streamrH   rI   !langchain_core.tracers.log_streamrK   rL   %langchain_core.tracers.root_listenersrM   rN   langchain_core.utils.aiterrO   rP   langchain_core.utils.iterrQ   langchain_core.utils.pydanticrR   rS   rT   r   rV   r  rX   RunnableWithFallbacksTr   rZ   r  r[   langchain_core.runnables.schemar\   r  r]   r^   r_   r`   langchain_core.tracers.schemasra   rb   r   re   rQ  rs  r~  r  r   r   r   r   RunnableMaprp  r  r  r  r  r<  r|  r  r  r  r  r  r   r  r   r{   rx   <module>r     s,   1 "       #	 	 	 5       = < & . R 
       ( H 6 - 9 ? 5F;-EC2 	 Y&
sGE6M* Y&
xLL
<%-)@ L
^*#*-B**<0*#0*-B0*0*f  ! i+E6M: iXL+E4S>,AB L` l%/ l%^	bXeVm, bJJ+DKf,EF JZr
#E6M2 r
jO.uf}= OdM)%-8 M`PHUF]3 P XeVm4   7 $XeVm%< $ UF]w w	&))*+  (6"2234 e$%}V'<<=	>
 E6M*+ UF]+,  v./ %UF]34 c3h	 6 
"
8"" 
"
 
"
-"" 
"
 
"
2"" 
"
 
"
#"" 
"
" /" 
 " r{   