
    g3ficR             	         d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	m
Z
mZ ddlmZmZmZmZmZmZmZmZ ddlmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+m,Z,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7m8Z8m9Z9 ddl:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZF ddlGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZY ddlZm[Z[ ddl\m]Z]m^Z^ ddl_m`Z`maZa ddlbmcZcmdZd ddlemfZfmgZg ddlhmiZi ddljmkZk e r@ddl3mlZlmmZm ddlnmoZo ddlpmqZr ddlsmtZt ddlumvZv ddlwmxZx dd lymzZz dd!l_m{Z{m|Z| dd"lbm}Z} dd#l~mZ  e%d$      Zd%Z G d& d'e
e"eLeMf         Z G d( d)e7eeLeMf         Z	 	 	 	 	 	 dJd*Z	 	 	 	 	 	 dJd+Zd%Z G d, d-eeLeMf         Z G d. d/eeLeee!f   f         ZeZ G d0 d1eeLeMf         Z G d2 d3eeLeMf         Z G d4 d5eeeL   eeM   f         Z G d6 d7eeLeMf         Z G d8 d9eeLeMf         Z G d: d;eeLeMf         Z G d< d=e$eLeMf         Z G d> d?e$eLeMf         Z G d@ dAe$eLeMf         Z G dB dCe$eLeMf         ZeeLeMf   eeLgeMf   z  eeLgeeM   f   z  eeeL   geeM   f   z  eeeL   geeM   f   z  eeLeMf   z  eeLeMf   z  eeLeMf   z  eeLeMf   z  eee!f   z  ZdKdDZe)	 	 	 	 dLdE       Ze)	 	 	 	 dMdF       Ze)	 	 	 	 dNdG       Ze)	 	 	 	 dOdH       Z	 	 	 	 dPdIZy)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                     e Zd ZU dZded<   	 dKdddLdZedMd       ZedNd       ZedOd	       Z		 dK	 	 	 dPd
Z
	 dK	 	 	 dQdZedOd       Z	 dK	 	 	 dPdZ	 dK	 	 	 dQdZedRd       ZdddSdZdd	 	 	 dTdZdKdUdZ	 dK	 	 	 dVdZ	 	 	 	 dWdZ	 	 	 	 dXdZdd	 	 	 	 	 dYdZdZdZ	 	 	 	 d[dZ	 e	 dK	 	 	 	 	 	 	 d\d       Z	 dK	 	 	 	 	 	 	 d\dZ	 dKdd	 	 	 	 	 	 	 	 	 d]dZe	 dKdd	 	 	 	 	 	 	 	 	 d^d       Ze	 dK	 	 	 	 	 	 	 	 	 d_d        Z	 dKdd	 	 	 	 	 	 	 	 	 d`d!Z	 dKdd	 	 	 	 	 	 	 	 	 d]d"Ze	 dKdd	 	 	 	 	 	 	 	 	 dad#       Z e	 dK	 	 	 	 	 	 	 	 	 dbd$       Z 	 dKdd	 	 	 	 	 	 	 	 	 dcd%Z 	 dK	 	 	 	 	 	 	 ddd&Z!	 dK	 	 	 	 	 	 	 ded'Z"e	 dKd(d(ddddddd)	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dfd*       Z#e	 dKd(ddddddd+	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dgd,       Z#	 dKd(d(ddddddd)	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dhd-Z#	 dKd.ddddddd/	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 did0Z$	 dK	 	 	 	 	 	 	 djd1Z%	 dK	 	 	 	 	 	 	 dkd2Z&dld3Z'	 dK	 	 	 	 	 dmd4Z(dddd5	 	 	 	 	 	 	 dnd6Z)dddd5	 	 	 	 	 	 	 dod7Z*ddd8	 	 	 	 	 dpd9Z+e,fd(dd:d;	 	 	 	 	 	 	 	 	 dqd<Z-drd=Z.e,fdd>	 	 	 	 	 	 	 dsd?Z/	 	 	 dt	 	 	 	 	 	 	 	 	 	 	 	 	 dud@Z0	 	 dt	 	 	 	 	 	 	 	 	 	 	 	 	 dvdAZ1	 dKdddB	 	 	 	 	 	 	 	 	 	 	 	 	 dwdCZ2	 dKdddB	 	 	 	 	 	 	 	 	 	 	 	 	 dxdDZ3	 dK	 	 	 	 	 	 	 	 	 	 	 dydEZ4	 dK	 	 	 	 	 	 	 	 	 	 	 dzdFZ5 e6jn                  dGH      	 dKddddI	 	 	 	 	 	 	 	 	 d{dJ       Z8y)|RunnableaW  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rg   c                  |r|}nt        | d      r| j                  r| j                  }n[| j                  }t        |d      r7d|j                  v r)|j                  d   |j                  d   j                  }n|j                  }|r<|d   j                         r||j                         z   S |dz   |j                         z   S |S )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`.
        rg   __pydantic_generic_metadata__originr   _)hasattrrg   	__class__rj   __name__isuppertitlelower)selfsuffixrg   name_clss        [/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_core/runnables/base.pyget_namezRunnable.get_name  s     ET6"tyyIIE ..C 3  A AA55h?K99(CLLQx!v||~--3;//    c                   | j                   j                         D ]I  }t        |d      s|j                  }d|v s!t	        |d         t
        k(  s7t        d|d   d         c S  | j                   j                  D ]3  }t        |      }|st	        |      t
        k(  s$t        d|d         c S  d| j                          d}t        |      )zInput type.

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

        Raises:
            TypeError: If the input type cannot be inferred.
        rj   argstype[Input]r   	Runnable z` doesn't have an inferable InputType. Override the InputType property to specify the input type.rn   mrorm   rj   len_RUNNABLE_GENERIC_NUM_ARGSr   __orig_bases__r   rx   	TypeErrorrs   basemetadatarv   	type_argsmsgs         rw   	InputTypezRunnable.InputType+  s     NN&&( 	DDt<===h&HV,-1KKx/?/BCC	D >>00 	9C IS^/IIM9Q<88	9 ( )I I 	 nry   c                   | j                   j                         D ]I  }t        |d      s|j                  }d|v s!t	        |d         t
        k(  s7t        d|d   d         c S  | j                   j                  D ]3  }t        |      }|st	        |      t
        k(  s$t        d|d         c S  d| j                          d}t        |      )zOutput Type.

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

        Raises:
            TypeError: If the output type cannot be inferred.
        rj   r{   type[Output]   r}   zc doesn't have an inferable OutputType. Override the OutputType property to specify the output type.r~   r   s         rw   
OutputTypezRunnable.OutputTypeN  s     NN&&( 	EDt<===h&HV,-1KK0@0CDD	E >>00 	:C IS^/IINIaL99	: ( )K K 	 nry   c                "    | j                         S )zHThe type of input this `Runnable` accepts specified as a Pydantic model.)get_input_schemars   s    rw   input_schemazRunnable.input_schemam  s     $$&&ry   c                    | j                   }t        j                  |      r"t        |t              st        |t              r|S t        | j                  d      || j                  j                        S )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   rx   rn   
__module__rs   config	root_types      rw   r   zRunnable.get_input_schemar  s`    $ NN	 OOI&y,79i0MM'" 11
 	
ry   c                @    | j                  |      j                         S )aQ  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rs   r   s     rw   get_input_jsonschemazRunnable.get_input_jsonschema  s    8 $$V,>>@@ry   c                "    | j                         S )zkOutput schema.

        The type of output this `Runnable` produces specified as a Pydantic model.
        )get_output_schemar   s    rw   output_schemazRunnable.output_schema  s     %%''ry   c                    | j                   }t        j                  |      r"t        |t              st        |t              r|S t        | j                  d      || j                  j                        S )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   rx   rn   r   r   s      rw   r   zRunnable.get_output_schema  s`    $ OO	 OOI&y,79i0MM(# 11
 	
ry   c                @    | j                  |      j                         S )aT  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     rw   get_output_jsonschemazRunnable.get_output_jsonschema  s    8 %%f-??AAry   c                    g S )z-List configurable fields for this `Runnable`. r   s    rw   config_specszRunnable.config_specs  s	     	ry   includec                  |xs g }| j                   }|r\t        d|D ci c]E  }|j                  |j                  t	        |j
                  |j                  |j                        fG c}      nd}i |rd|dfini t        t              j                         D ci c]"  \  }}||D cg c]
  }|dk7  s	| c}v r||df$ c}}}}t        | j                  d      |      S c c}w c c}w c c}}}w )av  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)rq   descriptionfield_definitionsNconfigurableConfig)r   rR   id
annotationr    defaultrg   r   r   r)   itemsrx   )	rs   r   r   specr   
field_name
field_typei
all_fieldss	            rw   config_schemazRunnable.config_schema  s    -R((   !-#  GG LL		tGWGW #  	$
9Et 452
 /=^.L.R.R.T *J
W!L^8K!!LL Z..

 t}}X6*UU/#( "Ms$   A
C(
C2
,
C-7C-;C2
-C2
c               B    | j                  |      j                         S )a6  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   )rs   r   s     rw   get_config_jsonschemazRunnable.get_config_jsonschema6  s!     !!'!2DDFFry   c                   ddl m}  |       }	 |j                  | j                  |            }|j                  | |r|j                  d      nd      }	 |j                  | j                  |            }|j                  ||       |j                  ||       |S # t        $ r, |j                  t        | j                  d                  }Y w xY w# t        $ r, |j                  t        | j                  d                  }Y w xY w)z1Return a graph representation of this `Runnable`.r   rY   r9   r   N)r   r:   )
langchain_core.runnables.graphrZ   add_noder   r   rR   rx   getr   add_edge)rs   r   rZ   graph
input_noderunnable_nodeoutput_nodes          rw   	get_graphzRunnable.get_graphF  s     	9	Q(=(=f(EFJ V6::j1 ' 
	S..)?)?)GHK 	z=1}k2  	Qg8N(OPJ	Q  	S..x9P)QRK	Ss#    B  C 2CC2D	D	c                    ddl m} | j                  |      j                  j	                         D cg c]$  }t        |j                  |      r|j                  & c}S c c}w )z1Return a list of prompts used by this `Runnable`.r   rU   )r   )langchain_core.prompts.baserV   r   nodesvaluesr   data)rs   r   rV   nodes       rw   get_promptszRunnable.get_prompts[  sW    
 	C f5;;BBD
$))%78 II
 	
 
s   )Ac                ,    t        | t        |            S )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rs   others     rw   __or__zRunnable.__or__h  s    &  &8&?@@ry   c                ,    t        t        |      |       S )a  Runnable "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     rw   __ror__zRunnable.__ror__}  s    &   25 94@@ry   c                    t        | g|d|iS )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`.
        rg   )r   )rs   rg   otherss      rw   pipezRunnable.pipe  s    ^  9v9D99ry   c                $    ddl m} |  ||      z  S )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   )rs   keysr   s      rw   pickzRunnable.pick  s    v 	Fl4(((ry   c                ^    ddl m} |  |t        t        t        t
        f      |            z  S )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   )rs   kwargsr   s      rw   assignzRunnable.assign  s,    V 	Hn%5d38n%Ef%MNNNry   c                     y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   rs   inputr   r   s       rw   invokezRunnable.invoke3      ry   c                P   K   t        || j                  ||fi | d{   S 7 wr   )r3   r   r   s       rw   ainvokezRunnable.ainvokeJ  s(     * %VT[[%R6RRRRs   &$&Freturn_exceptionsc               .    |sg S t        |t        |            }d fd}t        |      dk(  rt        d ||d   |d         g      S t        |d         5 }t        dt	        |j                  |||                  cddd       S # 1 sw Y   yxY w)a  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                    r	  j                   | |fi S  j                   | |fi S # t        $ r}|cY d }~S d }~ww xY wNr   	Exception)input_r   er   r   rs   s      rw   r   zRunnable.batch.<locals>.invoke  sT     &4;;vv@@@ #t{{66<V<< ! Hs   - 	A=AAr   list[Output]r   N)r   r9   r   r)   returnOutput | Exception)r/   r   r   r0   listmap)rs   inputsr   r   r   configsr   executors   `  ``   rw   batchzRunnable.batcha  s    : I!&#f+6	= v;!q	71:)F(GHH$WQZ0 	UHX\\&&'-R(ST	U 	U 	Us   &BBc                    y r   r   rs   r   r   r   r   s        rw   batch_as_completedzRunnable.batch_as_completed       (+ry   c                    y r   r   r  s        rw   r  zRunnable.batch_as_completed       47ry   c             +  ^   K   |syt        |t        |            }	 	 	 	 	 	 	 	 d fd}t        |      dk(  r |d|d   |d          yt        |d         5 }t        t	        ||d            D 	ch c]  \  }\  }	}|j                  |||	|       }
}	}}	 |
r<t        |
t              \  }}
|r#|j                         j                          |r#|
r<|
D ]  }|j                           	 ddd       yc c}}	}w # |
D ]  }|j                           w xY w# 1 sw Y   yxY ww)	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                    r	  j                   ||fi }| |fS  j                   ||fi }| |fS # t        $ r}|}Y d }~| |fS d }~ww xY wr   r   r   r   r   outr   r   r   rs   s        rw   r   z+Runnable.batch_as_completed.<locals>.invoke  ss     !.9dkk&&.SF.SC s8O "dkk&&;F;s8O ! C s8Os   5 	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)rs   r   r   r   r   r   r   r  r   r   futuresdonefutures   `  ``        rw   r  zRunnable.batch_as_completed  sS    8 !&#f+6		!	+9	+	 v;!F1Iwqz22$WQZ0 	$H ,5SQV5W+X 'A' 66:G 
$$(o$NMD'"hhj//11  
 & $FMMO$	$ 	$ & $FMMO$	$ 	$sN   AD-D!9!C>
D!:DDD!5	D->D!DD!!D*&D-c                   K   |sg S t        |t        |            }d fd}t        |||      }t        |d   j	                  d      g|  d{   S 7 w)a  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                   K   r	  j                   | |fi  d {   S  j                   | |fi  d {   S 7  # t        $ r}|cY d }~S d }~ww xY w7 wr   r   r   )valuer   r   r   r   rs   s      rw   r   z Runnable.abatch.<locals>.ainvoke  sh      !-eV!Fv!FFF *T\\%B6BBB	 G  H CsK   AA ?A AAAA 	A
AAAAAr   max_concurrencyN)r  r9   r   r)   r   r   )r/   r   r   r?   r   )rs   r   r   r   r   r   r   coross   `  ``   rw   abatchzRunnable.abatch  s\     > I!&#f+6	C GVW-,WQZ^^<M-NWQVWWWWs   AAAAc                    y r   r   r  s        rw   abatch_as_completedzRunnable.abatch_as_completed       -0ry   c                    y r   r   r  s        rw   r$  zRunnable.abatch_as_completed"       9<ry   c                 K   |syt        |t        |            }|r|d   j                  d      nd}|rt        j                  |      nd}	 	 	 	 	 	 	 	 d fd}t        t        ||d            D 	
cg c](  \  }	\  }
}|rt        | ||	|
|            n	 ||	|
|      * }}
}	}t        j                  |      D ]  }| d{     yc c}}
}	w 7 w)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                   K   r!	  j                   ||fi  d {   }| |fS  j                   ||fi  d {   }| |fS 7 (# t        $ r}|}Y d }~| |fS d }~ww xY w7 %wr   r  r  s        rw   ainvoke_taskz2Runnable.abatch_as_completed.<locals>.ainvoke_taskP  s      !4@DLL5*05 /C s8O )DLLB6BBs8O/ ! C s8O	 CsG   A&A	 AA	 A&A$A&A	 		A!AA&A!!A&Fr  r  )	r/   r   r   asyncio	Semaphorer  r  r>   as_completed)rs   r   r   r   r   r   r   	semaphorer*  r   r   r!  coros   `  ``        rw   r$  zRunnable.abatch_as_completed,  s     8 !&#f+6?F'!*..):;D:IG%%o6t			!	+9	+	$ (1VWU1S'T	
 
 $#FF  y,q&&"ABa01
 
 ((/ 	D*	
 s   A5C:-C'!CC	Cc              +  8   K    | j                   ||fi | yw)a  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       rw   streamzRunnable.streamh  s      & dkk%2622s   c               N   K    | j                   ||fi | d{    y7 w)a  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       rw   astreamzRunnable.astream}  s&     & !DLL9&9999s   %#	%T)diffwith_streamed_output_listinclude_namesinclude_typesinclude_tagsexclude_namesexclude_typesexclude_tagsc                    y r   r   rs   r   r   r4  r5  r6  r7  r8  r9  r:  r;  r   s               rw   astream_logzRunnable.astream_log  s     &)ry   )r5  r6  r7  r8  r9  r:  r;  c                    y r   r   r=  s               rw   r>  zRunnable.astream_log  s     !$ry   c          
    z   K   t        d|||||	|
d      }t        | ||f|||d|2 3 d{   }| 7 
6 yw)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_closer6  r7  r8  r9  r:  r;  _schema_format)r4  r1  r5  NrJ   )rs   r   r   r4  r5  r6  r7  r8  r9  r:  r;  r   r1  items                 rw   r>  zRunnable.astream_log  sv     T *''%''%%	
 6
 &?
 
 		 		$ J		 
s   &;979;9;v2)versionr6  r7  r8  r9  r:  r;  c              2  K   |dk(  rt        | |f|||||||	d|
}n(|dk(  rt        | |f|||||||	d|
}nd}t        |      t        |      4 d{    |2 3 d{   }| 7 7 6 ddd      d{  7   y# 1 d{  7  sw Y   yxY ww)ag)  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'`.

        rE  )r   r6  r7  r8  r9  r:  r;  v1zAOnly versions "v1" and "v2" of the schema is currently supported.N)rI   rH   NotImplementedErrorrO   )rs   r   r   rF  r6  r7  r8  r9  r:  r;  r   event_streamr   events                 rw   astream_eventszRunnable.astream_events  s     d d?< ++)++) L _ = ++)++) L VC%c**L) 	 	+  e	|	 	 	 	 	sl   ABA+BBA/ A-!A/$B+B-A//B0B;A><BBB	BBc              +     K   d}|D ]  }|s|}d}
	 |z   } |r | j                  |fi |E d{    yy# t         $ r |}Y ?w xY w7 w)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   r1  )rs   r   r   r   got_first_valichunkfinals          rw   	transformzRunnable.transform  sy     .  	#F ! $#!FNE	#" "t{{5&;F;;;  ! #"E# <s/   A9AA
AAAAAc                  K   d}|2 3 d{   }|s|}d}	 |z   }7 # t         $ r |}Y &w xY w6 |r& | j                  |fi |2 3 d{  7  }| 6 yyw)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   r3  )rs   r   r   r   rN  rO  rP  outputs           rw   
atransformzRunnable.atransform  s     . ! 	# 	#& ! $#!FNE	# ! #"E# ""  ,UF Ef E  f !F sM   A11A A1.A.AAAA
Ac                    t        | |i       S )a  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rs   r   s     rw   bindzRunnable.bindH  s    @ T&DDry   c           	     B    t        | t        di |xs i |      i       S )a  Bind 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)   )rV  r   r   )rX  r   rs   r   r   s      rw   with_configzRunnable.with_configj  s5       ,FLb,V, 
 	
ry   on_starton_endon_errorc               .    t        | fdg      S )a3  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                (    dt        |       giS N	callbacks)r   r_  r`  ra  rN   r   r`  ra  r_  s    rw   <lambda>z)Runnable.with_listeners.<locals>.<lambda>  s&    +#)%-#)%-	"	  ry   rV  config_factoriesrW  rs   r_  r`  ra  s    ```rw   with_listenerszRunnable.with_listeners  s     p 	
 	
ry   c               .    t        | fdg      S )a  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                (    dt        |       giS rd  )rM   rg  s    rw   rh  z*Runnable.with_alisteners.<locals>.<lambda>  s&    0#)%-#)%-	"	  ry   ri  rW  rk  s    ```rw   with_alistenerszRunnable.with_alisteners  s     b 	
 	
ry   )
input_typeoutput_typec                    t        | ||i       S )a+  Bind 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.
        )rV  custom_input_typecustom_output_typer   rW  rs   rp  rq  s      rw   
with_typeszRunnable.with_types,  s     (*	
 	
ry      )retry_if_exception_typewait_exponential_jitterexponential_jitter_paramsstop_after_attemptc          	     ,    ddl m}  || i i ||||      S )aY  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)rV  r   r   retry_exception_typesry  max_attempt_numberrz  )langchain_core.runnables.retryr}  )rs   rx  ry  rz  r{  r}  s         rw   
with_retryzRunnable.with_retryB  s+    h 	A"9$;1&?
 	
ry   c                    t        |       S )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]
            ```
        rV  )RunnableEachr   s    rw   r   zRunnable.map  s    * $''ry   )exceptions_to_handleexception_keyc               &    ddl m}  || |||      S )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   )rs   r  r  r  rX   s        rw   with_fallbackszRunnable.with_fallbacks  s#    F	
 %!5'	
 	
ry   c                   t        |      }t        |      }|j                  ||||j                  d      xs | j	                         |j                  dd            }	 t        ||j                               }	t        |	      5 }
t        d |
j                  t        ||||fi |      }ddd       |j                         |S # 1 sw Y   xY w# t        $ r}|j                  |        d}~ww xY w)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_typerg   r  re  r:   )r,   r.   on_chain_startr   rx   r  r2   	get_childr4   r   runr+   on_chain_endBaseExceptionon_chain_error)rs   funcr   r   r  
serializedr   callback_managerrun_managerchild_configcontextrS  r   s                rw   _call_with_configzRunnable._call_with_config  s    & v&:6B&55J':4==?::h- 6 
	'+:O:O:QRL#L1 WGKK4# !
  $$V,M#   	&&q)	s0   &C &C+C CC 	C2C--C2c           
     ,  K   t        |      }t        |      }|j                  ||||j                  d      xs | j	                         |j                  dd             d{   }	 t        ||j                               }	t        |	      5 }
t        ||||fi |}t        ||
       d{   }ddd       |j                         d{    |S 7 r7 )# 1 sw Y   (xY w7 # t        $ r }|j                  |       d{  7    d}~ww xY ww)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   rx   r  r2   r  r4   r*   r=   r  r  r  )rs   r  r   r   r  r  r   r  r  r  r  r/  rS  r   s                 rw   _acall_with_configzRunnable._acall_with_config  s#    ( v&@H,;;J':4==?::h- < 
 
	'+:O:O:QRL#L1 HW4&&+9? (9w'G!G	H **6222M'
 "H	H H 3	  	,,Q///	s~   A!D#C$D)&C( C.C/C3C( ;DC&DCC#C( &D(	D1DDDDD)r   r  c                  |sg S t        |t        |            }|D cg c]  }t        |       }	}t        |	||d      D 
cg c]M  \  }
}}|
j	                  d|||j                  d      xs | j                         |j                  dd            O }}}
}	 t        |      r=t        ||d      D cg c]   \  }}t        ||j                               " c}}|d<   t        |      r||d	<    ||fi |}d}t        ||d      D ]>  \  }}t        |t              r|xs |}|j                  |       .|j                  |       @ |s|t!        d
|      S |c c}w c c}}}
w c c}}w # t"        $ rE}|D ]  }|j                  |        |r%t!        d
|D cg c]  }| nc c}w c}      cY d}~S  d}~ww xY w)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   rx   r  r;   r2   r  r<   r   r   r  r  r   r  )rs   r  r   r   r   r  r   r   ccallback_managersr  r   run_managersrmrS  first_exceptionr  r  r   rl   s                       rw   _batch_with_configzRunnable._batch_with_configE  s   . I!&#f+6IPQA<Q?QQ 58!6755
 
 1 && ++!ZZ
+>t}}zz(D1 , 
 
	"d# "%Wl5!I$2 !blln=$x  #4((4}%&+F+F 15O$'fU$K 2 Sc9-&5&<O..s3,,S12 !O$;NF33!!M R
$  	+ .**1-. N,?1Q,?,?@@	sN   E AE%E2 8%E, E2 ,E2 2	G ;$F;	F)(F;4G :F;;G c          	        K   |sg S t        |t        |            }|D cg c]  }t        |       }	}t        j                   fdt        |	||d      D          d{   }
	 t        |      r=t        ||
d      D cg c]   \  }}t        ||j                               " c}}|d<   t        |      r|
|d<    ||fi | d{   }d}g }t        |
|d      D ]\  \  }}t        |t              r'|xs |}|j                  |j                  |             =|j                  |j                  |             ^ t        j                  |  d{    |s|t        d|      S |c c}w 7 c c}}w 7 7 &# t         $ rQt        j                  fd	|
D          d{  7   |r%t        d|D cg c]  } nc c}w c}      cY dS  dww xY ww)
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     K   | ]O  \  }}}|j                  d ||j                  d      xs j                         |j                  dd              Q y w)Nr  r  r  r  r   rx   r  ).0r  r   r   r  rs   s       rw   	<genexpr>z/Runnable._abatch_with_config.<locals>.<genexpr>  s`       5$ff !//%J/B4==?!::h5 0 s   AAFr  Nr  r   r  r   c              3  @   K   | ]  }|j                          y wr   r  )r  r  r   s     rw   r  z/Runnable._abatch_with_config.<locals>.<genexpr>  s     PK+,,Q/P   )r/   r   r-   r+  gatherr  r;   r2   r  r<   r   r   appendr  r  r   r  )rs   r  r   r   r   r  r   r   r  r  r  r  rS  r  r!  r  r  rl   r   s   `    `            @rw   _abatch_with_configzRunnable._abatch_with_config  s    4 I!&#f+6OVW!B1EWWDKNN 9<%vwu9E
 ?
	"d# "%Wl5!I$2 !blln=$x  #4((4}%1&11F 15O+-E$'fU$K @ Sc9-&5&<OLL!;!;C!@ALL!9!9#!>?@ ..%((( O$;NF33!!W X?
 $ 2" )!  	..P<P   !N,?1Q,?,?@@	s   GE/.G#E4$G)F %E7*#F E=F BGE?G7F ?G	G
G(F+)G:	GGGGGGGc           
   +    K   |j                  dd      }t        |d      \  }}t        |d      }	d}
d}d}t        |      }t	        |      }|j                  dddi||j                  d      xs | j                         |j                  d	d      |
      }	 t        ||j                               }t        |      r||d<   t        |      r||d<   t        |      5 } |j                  ||fi |}t        d |j                  D        d      x}r|j                  |j                   |      }	 	 |j                  t        |      }| |r||}n		 ||z   }n|}+# t"        $ r |}d}Y w xY w# t$        t&        f$ r Y nw xY w|D ]%  }|
r|	|}	
	 |	|z   }	# t"        $ r |}	d}
Y  w xY w|}	' 	 ddd       n# 1 sw Y   nxY w|j)                  ||	       y# t*        $ r}|j-                  ||	        d}~ww xY ww)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  rg   r  r  r  r   r  c              3  T   K   | ]   }t        |t              rt        d |       " ywrG   Nr   rG   r   r  hs     rw   r  z9Runnable._transform_stream_with_config.<locals>.<genexpr>	  +      %a)BC 8!<   &(r   )r  r   nextr,   r.   r  r   rx   r2   r  r;   r<   r4   r  handlerstap_output_iterr  r   StopIterationGeneratorExitr  r  r  )rs   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chunkrO  r   s                         rw   _transform_stream_with_configz&Runnable._transform_stream_with_config  sp    , 

?E: 25VQ..$():D$A $&*!%v&:6B&55bMJ':4==?::h-' 6 
6	G'+:O:O:QRLk*#/x ";/(3}%#L1 +-W&7;;{4G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> '--A+- +- +-` $$\+$F	  	&&q&=	s   BG;AG AF6."E-EE-E*'E-)E**E--E?<F6>E??F6FF6F%"F6$F%%F6-	G 6F?;G G;	G8G33G88G;c           
      K   |j                  dd      }t        |d      \  }}t        |d       d{   }	d}
d}d}t        |      }t	        |      }|j                  dddi||j                  d      xs | j                         |j                  d	d      |
       d{   }	 t        ||j                               }t        |      r||d<   t        |      r||d<   t        |      5 } |j                  ||fi |}t        d |j                  D        d      x}r|j!                  |j"                  |      }n|}	 	 t%        t        |      |       d{   }| |r||}n		 ||z   }n|}37 B7 7 # t&        $ r |}d}Y w xY w# t(        $ r Y nw xY w|2 3 d{  7  }|
r|	|}		 |	|z   }	# t&        $ r |}	d}
Y 'w xY w|}	.6 	 ddd       n# 1 sw Y   nxY w|j+                  ||	       d{  7   n.# t,        $ r"}|j/                  ||	       d{  7    d}~ww xY w	 't1        |d      r|j3                          d{  7   yyy# 't1        |d      r|j3                          d{  7   w w w xY ww)a  Transform 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  T   K   | ]   }t        |t              rt        d |       " ywr  r  r  s     rw   r  z:Runnable._atransform_stream_with_config.<locals>.<genexpr>l	  r  r  r  aclose)r  rP   anextr,   r-   r  r   rx   r2   r  r;   r<   r4   r  r  r  tap_output_aiterr  r=   r   StopAsyncIterationr  r  r  rm   r  )rs   r   r  r   r  r   r  r  r  r  r  r  r  r  r  r  r  	iterator_r  r  r  rO  r   s                          rw   _atransform_stream_with_configz'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1 .-W'GKK5H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.- .- .-f **<*LLL	  	,,Q{,CCC	 M$H)E&&((( *F$y$H)E&&((( *F$s8  1J	E5A-J	!E8"J	'AH -AGFE:F,E<1F5J	8J	:F<F	FFF	FGFG G$F'%G)G2F87G8GGGG	H G"H %I ;G><I 	H-H(!H$"H((H--I 1!J	IJ	"J=J >JJ	z1This API is in beta and may change in the future.message)rg   r   	arg_typesc               (    ddl m}  || ||||      S )am  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_schemarg   r   r  )langchain_core.toolsr  )rs   r  rg   r   r  r  s         rw   as_toolzRunnable.as_tool	  s%    Z 	B'##
 	
ry   r   rt   rf   rg   rf   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]rg   rf   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   r  
r   r  r   r  r   r  r   r  r   z!AsyncIterator[tuple[int, Output]]
r   r  r   r  r   r  r   r  r   -AsyncIterator[tuple[int, Output | Exception]]
r   r  r   r  r   r  r   r  r   r  r   r9   r   r  r   r  r   Iterator[Output]r   r9   r   r  r   r  r   AsyncIterator[Output])r   r   r   r  r4  r  r5  r  r6  r  r7  r  r8  r  r9  r  r:  r  r;  r  r   r   r   zAsyncIterator[RunLogPatch])r   r   r   r  r4  r  r5  r  r6  r  r7  r  r8  r  r9  r  r:  r  r;  r  r   r   r   zAsyncIterator[RunLog])r   r   r   r  r4  r  r5  r  r6  r  r7  r  r8  r  r9  r  r:  r  r;  r  r   r   r   z2AsyncIterator[RunLogPatch] | AsyncIterator[RunLog])r   r   r   r  rF  zLiteral['v1', 'v2']r6  r  r7  r  r8  r  r9  r  r:  r  r;  r  r   r   r   AsyncIterator[StreamEvent]r   Iterator[Input]r   r  r   r  r   r   r   AsyncIterator[Input]r   r  r   r  r   r  r   r   r   Runnable[Input, Output]r   r  r   r   r   r	  r_  DCallable[[Run], None] | Callable[[Run, RunnableConfig], None] | Noner`  r  ra  r  r   r	  )r_  AsyncListener | Noner`  r  ra  r  r   r	  )rp  ztype[Input] | Nonerq  ztype[Output] | Noner   r	  )
rx  tuple[type[BaseException], ...]ry  r  rz  zExponentialJitterParams | Noner{  r  r   r	  )r   z#Runnable[list[Input], list[Output]])r  z!Sequence[Runnable[Input, Output]]r  r  r  rf   r   z%RunnableWithFallbacksT[Input, Output]NN)r  zCallable[[Input], Output] | Callable[[Input, CallbackManagerForChainRun], Output] | Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]r   r9   r   r  r  rf   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  rf   r  r  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  rf   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  rf   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  rf   r   r  r   r   )r   r  r  zCallable[[AsyncIterator[Input]], AsyncIterator[Output]] | Callable[[AsyncIterator[Input], AsyncCallbackManagerForChainRun], AsyncIterator[Output]] | Callable[[AsyncIterator[Input], AsyncCallbackManagerForChainRun, RunnableConfig], AsyncIterator[Output]]r   r  r  rf   r   r  r   r  )
r  ztype[BaseModel] | Nonerg   rf   r   rf   r  zdict[str, type] | Noner   r]   )9ro   r   __qualname____doc____annotations__rx   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$  r1  r3  r>  rL  rQ  rT  rZ  r]  rl  ro  rv  r   r  r   r  r  r  r  r  r  r  r#   betar  r   ry   rw   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
ry   re   c                       e Zd ZU dZdZded<    ed      Zed fd       Z		 	 	 	 ddZ
d	d
d	 	 	 	 	 	 	 	 	 ddZ xZS )RunnableSerializablez(Runnable that can be serialized to JSON.Nrf   rg   r   )protected_namespacesc                    t         |          }t        j                  t              5  | j                         |d<   ddd       |S # 1 sw Y   |S xY w)zSerialize the `Runnable` to JSON.

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

        rg   N)superto_json
contextlibsuppressr   rx   )rs   dumpedrn   s     rw   r  zRunnableSerializable.to_json#
  sH     "  + 	-!]]_F6N	-	-s   AAc                    ddl m} t        |       j                  }|D ]*  }||vsd| d|  d|j	                          }t        |        || |      S )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)rs   r   r   r$  keyr   s         rw   configurable_fieldsz(RunnableSerializable.configurable_fields0
  sx    V	
 Dz.. 	&C,&(^D6 B**6*;*;*=)>@  !o%	& *$vFFry   r   F)default_keyprefix_keysc               (    ddl m}  ||| |||      S )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   alternativesr(  r)  )r"  r+  )rs   r,  r(  r)  r   r+  s         rw   configurable_alternativesz.RunnableSerializable.configurable_alternativesj
  s&    `	
 0##
 	
ry   )r   z0SerializedConstructor | SerializedNotImplemented)r   r6   r   #RunnableSerializable[Input, Output])
r,  r7   r(  r   r)  r  r   z?Runnable[Input, Output] | Callable[[], Runnable[Input, Output]]r   r/  )ro   r   r  r  rg   r  r   model_configr"   r  r'  r.  __classcell__rn   s   @rw   r  r  
  s    2D*  L 
 
8G,8G	,8G| %!:
 :
 	:

 :
 R:
 
-:
ry   r  c           
        ddl m}m} | d   }t        |       dk(  r|j	                  |      S t        ||      rt        | dd  |      }t        |t              st        d|j                  j                         D ci c]6  \  }}||j                  j                  vr||j                  |j                  f8 c}}      S t        ||      rt        | dd  |      S |j	                  |      S c c}}w )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           rw   r6  r6  
  s    
 !HE
5zQ%%f--%(-eABi@+Y7"' !2 > > D D F#1 4 44 aii00#  
E<	( qrF33!!&))#s   ;;C+c                   ddl m}m} | d   }t        |       dk(  r|j	                  |      S t        ||      r|j                  j                  |      }t        | d d |      }t        |t              sst        di |j                  j                         D ci c]  \  }}||j                  |j                  f  c}}|j                  j                         D ci c]  \  }}||j                  |j                  f  c}}      S t        ||      rt        | d d |      }t        |t              st        |j                   t"              r]t        d|j                  j                         D ci c],  \  }}||j                   v r||j                  |j                  f. c}}      S |j                  |j                      }	t        d|	j                  |	j                  f      S |j                  |      S c c}}w c c}}w c c}}w )Nr   r4  r   RunnableSequenceOutputr   )r   )r   r   r   r   r   r   r7  r   _seq_output_schemar   r!   rR   r$  r   r   r   r   r   )
r9  r   r   r   lastmapper_output_schemaprev_output_schemar<  r=  fields
             rw   rA  rA  
  s   
 9D
5zQ$$V,,$'#{{<<VD/cr
FC,i8"(	# %7$C$C$I$I$K Aq ALL!))44	# %9$E$E$K$K$M Aq ALL!))44	#  
D,	'/cr
FC,i8$))T*&, %7$C$C$I$I$K' Aq		> ALL!))44'  '33DII>E"(0@0@%--/P  !!&))9's   #G8#G>11Hc                  $    e Zd ZU dZded<   	  ee      Zded<   	 ded<   	 d	d	d	d	d
	 	 	 	 	 	 	 	 	 	 	 d& fdZe	e
d'd              Zed(d       Ze	e
d)d              Z ed      Zee
d*d              Zee
d+d              Ze
d,d-d       Ze
	 d,	 	 	 d-d       Zee
d.d              Ze
d,d/d       Ze
d0d       Ze
	 	 	 	 d1d       Ze
	 	 	 	 d2d       Ze
	 d,	 	 	 	 	 	 	 d3d       Ze
	 d,	 	 	 	 	 	 	 d4d       Ze
	 d,dd	 	 	 	 	 	 	 	 	 d5d       Ze
	 d,dd	 	 	 	 	 	 	 	 	 d5d       Z	 	 	 	 	 	 	 	 	 	 d6d Z	 	 	 	 	 	 	 	 	 	 d7d!Ze
	 d,	 	 	 	 	 	 	 d8d"       Z e
	 d,	 	 	 	 	 	 	 d9d#       Z!e
	 d,	 	 	 	 	 	 	 d:d$       Z"e
	 d,	 	 	 	 	 	 	 d;d%       Z# xZ$S )<r   a  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]r:  default_factorylist[Runnable[Any, Any]]middlezRunnable[Any, Output]rB  N)rg   r:  rK  rB  c               z   g }|s|||g|xs g z   |gz   }|D ]H  }t        |t              r|j                  |j                         /|j	                  t        |             J t        |      t        k  r dt         dt        |       }t        |      t        	| )  |d   t        |dd       |d   |       y)a  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?  )r:  rK  rB  rg   )r   r   extendr9  r  r   r   _RUNNABLE_SEQUENCE_MIN_STEPSr%  r  __init__r   )
rs   rg   r:  rK  rB  r9  
steps_flatstepr   rn   s
            rw   rO  zRunnableSequence.__init__Y  s    ( &(
*t/?FLb1TF:J 	<D$ 01!!$**-!!"4T":;		<
 z?9967S6T U!*o.0  S/!Q-
1R()B	 	 	
ry   c                
    g dS zwGet the namespace of the LangChain object.

        Returns:
            `["langchain", "schema", "runnable"]`
        )	langchainschemar  r   rv   s    rw   get_lc_namespacez!RunnableSequence.get_lc_namespace  
     32ry   c                L    | j                   g| j                  | j                  S )zuAll the `Runnable`s that make up the sequence in order.

        Returns:
            A list of `Runnable`s.
        )r:  rK  rB  r   s    rw   r9  zRunnableSequence.steps  s#     

4T[[4$))44ry   c                     yz,Return `True` as this class is serializable.Tr   rV  s    rw   is_lc_serializablez#RunnableSequence.is_lc_serializable       ry   Tarbitrary_types_allowedc                .    | j                   j                  S z(The type of the input to the `Runnable`.)r:  r   r   s    rw   r   zRunnableSequence.InputType  s     zz###ry   c                .    | j                   j                  S )z)The type of the output of the `Runnable`.)rB  r   r   s    rw   r   zRunnableSequence.OutputType  s     yy###ry   c                .    t        | j                  |      S )Get the input schema of the `Runnable`.

        Args:
            config: The config to use.

        Returns:
            The input schema of the `Runnable`.

        )r6  r9  r   s     rw   r   z!RunnableSequence.get_input_schema  s     !V44ry   c                .    t        | j                  |      S )Get the output schema of the `Runnable`.

        Args:
            config: The config to use.

        Returns:
            The output schema of the `Runnable`.

        )rA  r9  r   s     rw   r   z"RunnableSequence.get_output_schema  s     "$**f55ry   c                z    t        | j                  D cg c]  }|j                  D ]  }|  c}}      S c c}}w )sGet the config specs of the `Runnable`.

        Returns:
            The config specs of the `Runnable`.

        )rC   r9  r   )rs   rQ  r   s      rw   r   zRunnableSequence.config_specs  s8     '"jjGdT5F5FGTTGTG
 	
Gs   7
c                t   ddl m}  |       }| j                  D ]  }|j                         }|j	                  |      }|| j
                  ur|j                          || j                  ur|j                          |j                  |      \  }}|sd| d}	t        |	      |s|j                  ||        |S )  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   r9  	last_noder   r:  trim_first_noderB  trim_last_noderM  r%  r   )
rs   r   rZ   r   rQ  current_last_node
step_graphstep_first_noderl   r   s
             rw   r   zRunnableSequence.get_graph  s     	9JJ 	CD % 1/J4::%**,499$))+!&j!9OQ"!$'9: o% 0/B	C ry   c                X    dj                  d t        | j                        D              S )Nz
| c              3  l   K   | ],  \  }}|d k(  rt        |      nt        t        |      d       . yw)r   z| N)reprrD   )r  r   ss      rw   r  z,RunnableSequence.__repr__.<locals>.<genexpr>  s7      
1 AvDG#;DGT#JJ
s   24)joinr  r9  r   s    rw   __repr__zRunnableSequence.__repr__  s)    {{ 
!$**-
 
 	
ry   c                   t        |t              rkt        | j                  g| j                  | j                  |j                  |j                  |j                  d| j
                  xs |j
                  iS t        | j                  g| j                  | j                  t        |      d| j
                  iS Nrg   r   r   r:  rK  rB  rg   r   r   s     rw   r   zRunnableSequence.__or__  s     e-.#

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

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

 
 	
ry   c                ~   t        |t              rkt        |j                  g|j                  |j                  | j                  | j                  | j                  d|j
                  xs | j
                  iS t        t        |      | j                  g| j                  | j                  d| j
                  iS ry  rz  r   s     rw   r   zRunnableSequence.__ror__  s     e-.# 

 

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

 
 	
ry   c           	        t        |      }t        |      }|j                  d ||j                  d      xs | j	                         |j                  dd             }|}	 t        | j                        D ]}  \  }}t        ||j                  d|dz                }t        |      5 }	|dk(  r  |	j                  |j                  ||fi |}n|	j                  |j                  ||      }d d d         	 |j                  |       t        d|      S # 1 sw Y   xY w# t        $ r}
|j!                  |
        d }
~
ww xY w)	Nr  r  rg   r  	seq:step:r   r  r   r:   )r,   r.   r  r   rx   r  r  r9  r2   r  r4   r  r   r  r   r  r  )rs   r   r   r   r  r  r   r   rQ  r  r   s              rw   r   zRunnableSequence.invoke4  sL   
 v&:6B&55J':4==?::h-	 6 
 	*$TZZ0 	J4%k&;&;iAw<O&P (/ J7Av!,T[[&&!SF!S!(T[[&&!I	J J	J $$V,&))J J  	&&q)	s2    AD (AD+
D D	D 	D?(D::D?c           	       K   t        |      }t        |      }|j                  d ||j                  d      xs | j	                         |j                  dd              d {   }|}	 t        | j                        D ]  \  }}t        ||j                  d|dz                }t        |      5 }	|dk(  r#t        j                  |j                  ||fi |}
n!t        j                  |j                  ||      }
t         |
       |	d	       d {   }d d d         	 |j                  |       d {    t!        d
|      S 7 7 6# 1 sw Y   xY w7  # t"        $ r }|j%                  |       d {  7    d }~ww xY ww)Nr  r  r}  r~  r   r  r   Tcreate_taskr:   )r,   r-   r  r   rx   r  r  r9  r2   r  r4   	functoolspartialr   r=   r  r   r  r  )rs   r   r   r   r  r  r   r   rQ  r  partr   s               rw   r   zRunnableSequence.ainvokeX  s     v&@H,;;J':4==?::h-	 < 
 
 	*$TZZ0 
X4%k&;&;iAw<O&P (/ X7Av(00vvXQWX(00vvN#4TVWRV#WWFX X
X  **6222&))7
( XX X 3	  	,,Q///	s   A F"E#F*AE 2A EE	E
E "F6E7F	EE	E F	F"E=6E97E==FFFr   c                  |sg S t        |t        |            }|D cg c]K  }t        j                  |j	                  d      d d|j	                  d      d |j	                  d      d       M }}t        |||d      D cg c]L  \  }}}|j                  d ||j	                  d      xs | j                         |j                  dd       	      N }	}}}	 |ri }
t        | j                        D ]7  \  }}t        t        |            D cg c]	  }||
vs| }} |j                  t        ||d      D cg c]  \  }}||
vr| c}}t        t        |	|d            D cg c].  \  }\  }}||
vr"t        ||j                  d
|dz                0 c}}}fd|i|dk(  r|ni }|
j                  t        ||d      D ci c]  \  }}t!        |t"              r|| c}}       |D cg c]  }t!        |t"              r| }}t        |
      t        |      k(  s8 n |j%                         }g }t        t        |            D ]E  }||
v r|j'                  t)        d|
|                &|j'                  |j                  d             G nyt        | j                        D ]a  \  }} |j                  |t        |	|d      D cg c]'  \  }}t        ||j                  d
|dz                ) c}}fd|i|dk(  r|ni }c d }t        |	|d      D ]>  \  }}t!        |t"              r|xs |}|j+                  |       .|j-                  |       @ |s|t)        d|      S |c c}w c c}}}w c c}w c c}}w c c}}}w c c}}w c c}w c c}}w # t.        $ rE}|	D ]  }|j+                  |        |r%t)        d|D cg c]  }| nc c}w c}      cY d }~S  d }~ww xY w)Nre  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  rx   r  r  r9  ranger  r2   r  updater   r   copyr  r   r  r  r  )rs   r   r   r   r   r   r  cmr   r  failed_inputs_mapstepidxrQ  r   remaining_idxsinpr  inputs_copyr  r  r  r   rl   s                          rw   r  zRunnableSequence.batch  s_    I "&#f+6 "
  %%&,jj&= $!'F!3%+ZZ
%;#
 
( '*!675'

 

 #FF ZZ
+>t}}zz(D1	  

 

V	"  ;=!%.tzz%: &MGT $)W#6&!CT:T&N & (TZZ +.nfU*S &3 (99   4= #L'% H4
 
 !0<B  !(99 ) &*,,,7Q;-7P*Q
" +<#$ &-\6r%F* &,, +.nfU*S &3)#y9 sF .4Vc:c9;UcVFV,-W=M&R %kkms7|, :A--d74Ea4H&IJkooa&89	:  )4 GAt'TZZ /2,PU.V
 !+F ) &",,1q5'?R2S +< &'!V6F, 15O$'fU$K 2 Sc9-&5&<O..s3,,S12 !O$;NF33!!a


,&


  W"  	" %!!!$% N,?1Q,?,?@@	s   AM9AM>7N( 	NNN( =N
N( +3N/N( N*N( 6NNN( +B+N( ,N"N( #N( (	O61$O1	OO1*O60O11O6c               @   K   |sg S t        |t        |            }|D cg c]K  }t        j                  |j	                  d      d d|j	                  d      d |j	                  d      d       M }}t        j                   fdt        |||d      D          d {   }	 |ri }t         j                        D ]?  \  }	}
t        t        |            D cg c]	  }||vs| }} |
j                  t        ||d      D cg c]  \  }}||vr| c}}t        t        ||d            D cg c].  \  }\  }}||vr"t        ||j                  d|	d	z          
      0 c}}}fd|i|	dk(  r|ni  d {   }|j                  t        ||d      D ci c]  \  }}t        |t               r|| c}}       |D cg c]  }t        |t               r| }}t        |      t        |      k(  s@ n |j#                         }g }t        t        |            D ]E  }||v r|j%                  t'        d||                &|j%                  |j)                  d             G nt         j                        D ]i  \  }}
 |
j                  |t        ||d      D cg c]'  \  }}t        ||j                  d|d	z          
      ) c}}fd|i|dk(  r|ni  d {   }k d }g }t        ||d      D ]\  \  }}t        |t               r'|xs |}|j%                  |j+                  |             =|j%                  |j-                  |             ^ t        j                  |  d {    |s|t'        d|      S |c c}w 7 c c}w c c}}w c c}}}w 7 )c c}}w c c}w c c}}w 7 7 F# t.        $ rQt        j                  fd|D          d {  7   |r%t'        d|D cg c]  } nc c}w c}      cY d S  d ww xY ww)Nre  Fr  r   r  c           
   3     K   | ]N  \  }}}|j                  d ||j                  d      xs j                         |j                  dd              P y w)Nr  r  r}  r  )r  r  r   r   rs   s       rw   r  z*RunnableSequence.abatch.<locals>.<genexpr>  s\      
 'B !!J/B4==?!::h5	 " 
s   AAr  r~  r   r  r   r   r9   r   c              3  @   K   | ]  }|j                          y wr   r  )r  r  r   s     rw   r  z*RunnableSequence.abatch.<locals>.<genexpr>q  s     "OB2#4#4Q#7"Or  )r/   r   r$   r  r   r+  r  r  r  r9  r  r"  r2   r  r  r   r   r  r  r   r  r  r  r  )rs   r   r   r   r   r   r  r  r  r  rQ  r   r  r  r  r  r  r!  r  r  rl   r   s   `                    @rw   r"  zRunnableSequence.abatch   sc     I "&#f+6 "
  !**&,jj&= $!'F!3%+ZZ
%;#
 
 ELNN
 +.%vwu+
E
 ?
 V	"  ;=!%.tzz%: &MGT $)W#6&!CT:T&N & $/4;; +.nfU*S &3 (99   4= #L'% H4
 
 !0<B  !(99 ) &*,,,7Q;-7P*Q
$" +<#$$ &-\6r%$ F* &,, +.nfU*S &3)#y9 sF .4Vc:c9;UcVFV,-W=M&R %kkms7|, :A--d74Ea4H&IJkooa&89	:  )4 GAt#.4;; /2,PU.V
 !+F ) &",,1q5'?R2S$ +<$ &'!V6$ F( 15O+-E$'fU$K @ Sc9-&5&<OLL!;!;C!@ALL!9!9#!>?@ ..%((( O$;NF33!!g
?
2&


, W"6 )  	.."O,"OPPP N,?1Q,?,?@@		s   PAN2-PN P%7O 	N&N*O 	NO 73N"*O  N) O !N,>O 
N2 N2$O ?B+O *,N7O +N=,O 2BP8N?9PO ,O ?P	P
P(O+)P:	PPPPPPPc           	   +  H  K   | j                   g| j                  | j                  }t        d|      }t	        |      D ]S  \  }}t        ||j                  d|dz                }|dk(  r |j                  ||fi |}B|j                  ||      }U |E d {    y 7 w)Nr   r~  r   r  r   )r:  rK  rB  r   r  r2   r  rQ  )	rs   r   r  r   r   r9  final_pipelineidxrQ  s	            rw   
_transformzRunnableSequence._transform  s      5dkk54995 0&9"5) 	HIC!+"7"7)C!G98M"NF ax!/!Q&!Q!%!G	H "!!s   BB"B B"c           	    X  K   | j                   g| j                  | j                  }t        d|      }t	        |      D ]S  \  }}t        ||j                  d|dz                }|dk(  r |j                  ||fi |}B|j                  ||      }U |2 3 d {   }	|	 7 
6 y w)Nr  r~  r   r  r   )r:  rK  rB  r   r  r2   r  rT  )
rs   r   r  r   r   r9  r  r  rQ  rS  s
             rw   _atransformzRunnableSequence._atransform  s      5dkk54995
 5v>"5) 	IIC!%//)C!G90EFF ax!0!R6!R!%!H	I + 	 	&L	Ns*   BB*B(B&B(B*&B((B*c           
   +     K    | j                   || j                  t        ||xs i j                  d      xs | j                        fi |E d {    y 7 wNr  )r  )r  r  r2   r   rg   r   s       rw   rQ  zRunnableSequence.transform  sX      6455OO6<R*<*<Z*H*UDIIV
 	
 	
 	
s   AAAAc              +  \   K    | j                   t        |g      |fi |E d {    y 7 wr   rQ  iterr   s       rw   r1  zRunnableSequence.stream  s)      "4>>$w-B6BBBs   ",*,c           
       K    | j                   || j                  t        ||xs i j                  d      xs | j                        fi |2 3 d {   }| 7 
6 y wr  )r  r  r2   r   rg   rs   r   r   r   r  s        rw   rT  zRunnableSequence.atransform  sn      ?4>>6<R*<*<Z*H*UDIIV
 	
 	 	% K	 
s*   AA!AAAA!AA!c               p   K   dfd} | j                    |       |fi |2 3 d {   }| 7 
6 y w)Nc                   K     y wr   r   r   s   rw   input_aiterz-RunnableSequence.astream.<locals>.input_aiter       K   
r   r  rT  rs   r   r   r   r  r  s    `    rw   r3  zRunnableSequence.astream  ?     	 +4??;=&KFK 	 	%K	K    6424646)r9  RunnableLikerg   rf   r:  Runnable[Any, Any] | NonerK  zlist[Runnable[Any, Any]] | NonerB  r  r   Noner   z	list[str])r   rJ  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   r   )
r   r  r  rS   r   r)   r   r   r   r  r  r  r  r  )%ro   r   r  r  r  r    r   rK  rO  classmethodr"   rW  r  r9  r\  r   r0  r   r   r   r   r   r   rw  r   r   r   r   r  r"  r  r  rQ  r1  rT  r3  r1  r2  s   @rw   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  )-# & 	
 
   )-

 &
 	

 

 
ry   r   c                  @    e Zd ZU dZded<   	 d	 	 	 	 	 d fdZeedd              Zeedd              Z	 e
d	      Zeddd
d fd       Zeedd              Zedd  fd       Ze	 d	 	 	 d d       Zeed!d              Zedd"d       Zed#d       Ze	 d	 	 	 	 	 	 	 d$d       Ze	 d	 	 	 	 	 	 	 d%d       Z	 	 	 	 	 	 	 	 d&dZe	 d	 	 	 	 	 	 	 d'd       Ze	 d	 	 	 	 	 	 	 d(d       Z	 	 	 	 	 	 	 	 d)dZe	 d	 	 	 	 	 	 	 d*d       Ze	 d	 	 	 	 	 	 	 d+d       Z xZS ),r   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]]r8  Nc           
         |i |ni }|j                  |       t        | 	  |j                         D ci c]  \  }}|t	        |       c}}       yc c}}w )zCreate a `RunnableParallel`.

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

        N)r8  )r  r  rO  r   r   )rs   r8  r   mergedr&  rrn   s         rw   rO  zRunnableParallel.__init__=  sY    ( !( 3Gf>DllnMFCS,Q//M 	 	
Ms   A
c                     yr[  r   rV  s    rw   r\  z#RunnableParallel.is_lc_serializableW  r]  ry   c                
    g dS rS  r   rV  s    rw   rW  z!RunnableParallel.get_lc_namespace]  rX  ry   Tr^  rh   c                   |xs; | j                   xs- ddj                  | j                  j                                d}t        |   ||      S )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<,>rh   )rg   rv  r8  r   r  rx   rs   rt   rg   rn   s      rw   rx   zRunnableParallel.get_namek  sO     XtyyX&7ARARAT8U7VVW$XwT22ry   c                    | j                   j                         D ]  }|j                  s|j                  c S  t        S ra  )r8  r   r   r   )rs   rQ  s     rw   r   zRunnableParallel.InputTypez  s8     LL'') 	&D~~~~%	& 
ry   c                   t        fd| j                  j                         D              r| j                  j                         D ]U  }|j                        j                  }|j                  d      }|2|j                  t        k7  sFt        |         c S  t        | j                  d      | j                  j                         D ci c]Q  }|j                        j                  j                         D ]#  \  }}|dk7  r||j                  |j                  f% S c}}}      S t        |         S c c}}}w )rd  c              3     K   | ]6  }|j                        j                         j                  d d      dk(   8 yw)r#  objectN)r   r   r   )r  ru  r   s     rw   r  z4RunnableParallel.get_input_schema.<locals>.<genexpr>  sD      
  v&88:>>vxP
s   <?r   r9   __root__r   )allr8  r   r   r$  r   r   r   r  rR   rx   r   r   )rs   r   rQ  r!  
root_fieldr<  r=  rn   s    `     rw   r   z!RunnableParallel.get_input_schema  s6     
 \\((*
 

 ++- <..v6CC#ZZ/
)j.C.Cs.J 73F;;	< #g& !% 3 3 5# # $ 5 5f = J J P P R# 1J aii00##  w'//#s   AEc                    | j                   j                         D ci c]  \  }}||j                  df }}}t        | j	                  d      |      S c c}}w )rf  .r:   r   )r8  r   r   rR   rx   )rs   r   r<  r=  r!  s        rw   r   z"RunnableParallel.get_output_schema  sR     6:\\5G5G5IJTQ!allC((JJt}}X6&QQ Ks   Ac                V    t        d | j                  j                         D              S )rh  c              3  B   K   | ]  }|j                   D ]  }|   y wr   r   )r  rQ  r   s      rw   r  z0RunnableParallel.config_specs.<locals>.<genexpr>  s-      '
t?P?P'
7;D'
'
   )rC   r8  r   r   s    rw   r   zRunnableParallel.config_specs  s+     ' '
!\\002'
 
 	
ry   c                $   ddl m}  |       }|j                  | j                  |            }|j                  | j	                  |            }| j
                  j                         D ]  }|j                         }|j                          |j                          |s|j                  ||       H|j                  |      \  }}	|sd| d}
t        |
      |	sd| d}
t        |
      |j                  ||       |j                  |	|        |S )rj  r   rY   r}   rk   has no last node)r   rZ   r   r   r   r8  r   r   rm  rn  r   rM  r%  )rs   r   rZ   r   r   r   rQ  rp  rq  step_last_noder   s              rw   r   z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?;~{;	<" ry   c                r    dj                  d | j                  j                         D              }d|z   dz   S )Nz,
  c              3  b   K   | ]'  \  }}| d t        t        |      d|z   d z           ) yw)z: z  N)rD   rt  )r  r<  r=  s      rw   r  z,RunnableParallel.__repr__.<locals>.<genexpr>  s<      $
1 c,T!WdQhoFGH$
s   -/z{
  z
})rv  r8  r   )rs   map_for_reprs     rw   rw  zRunnableParallel.__repr__  s<    || $
**,$
 
 %--ry   c                   t        |      }t        j                  |j                  d      d d|j                  d      d |j                  d      d       }|j	                  d ||j                  d      xs | j                         |j                  dd             	 	 	 	 	 	 	 	 	 	 dfd	}	 t        | j                        }t        |      5 }|j                         D 	cg c]  \  }}	|j                  ||	|||       }
}}	t        ||
d
      D ci c]  \  }}||j                          }}}d d d        j                         |S c c}	}w c c}}w # 1 sw Y   (xY w# t        $ r}j!                  |        d }~ww xY w)Nre  Fr  r   r  r  r  r}  c                    t        |j                  d|             }t        |      5 }|j                  | j                  ||      cd d d        S # 1 sw Y   y xY w)Nmap:key:r  )r2   r  r4   r  r   rQ  r   r   r&  r  r  r  s         rw   _invoke_stepz-RunnableParallel.invoke.<locals>._invoke_step
  sa     (%//(3%0@AL
 $L1 W{{KK   s   AAr  
rQ  rG  r   r9   r   r)   r&  r   r   r   )r,   r%   r  r   r  rx   r  r   r8  r0   r   r  r  r  r  r  r  )rs   r   r   r   r  r  r9  r  r&  rQ  r  r  rS  r   r  s                 @rw   r   zRunnableParallel.invoke  s   
 v&*44"(**["9 #ZZ/!'J!7
 '55J':4==?::h-	 6 
	&	05	?M	TW		 	&E(0 H &+[[]!T OOL$vsK  (+5'%'H#V (  $$V,M   	&&q)	sN   - E% E!E EE/E2E% EE"E% %	F.F  Fc           	     T  	
K   t              t              }|j                  d j                  d      xs | j	                         j                  dd              d {   
	 	 	 	 	 	 	 	 	 	 d
fd		 t        | j                        }t        j                  	fd|j                         D          d {   }t        t        ||d            }
j                  |       d {    |S 7 7 87 
# t        $ r }
j                  |       d {  7    d }~ww xY ww)	Nr  r  r}  c                   K   t        |j                  d|             }t        |      5 }t        | j	                  ||      |d       d {   cd d d        S 7 # 1 sw Y   y xY ww)Nr  r  Tr  )r2   r  r4   r=   r   r  s         rw   _ainvoke_stepz/RunnableParallel.ainvoke.<locals>._ainvoke_stepA  su      (%//(3%0@AL $L1 W.LL6T   s.   +A,"A AA 
A,A  A)%A,c              3  :   K   | ]  \  }} ||        y wr   r   )r  r&  rQ  r  r   r   s      rw   r  z+RunnableParallel.ainvoke.<locals>.<genexpr>R  s0      	 "T "	s   Fr  r  )r,   r-   r  r   rx   r  r   r8  r+  r  r   r  r  r  r  )rs   r   r   r   r  r9  resultsrS  r   r  r  s    ``      @@rw   r   zRunnableParallel.ainvoke/  s5     v&@H,;;J':4==?::h-	 < 
 

	&
	05
	?M
	TW
	
		&E#NN	 &+[[]	 G #eWU;<F **6222MU
.$ 3	  	,,Q///	sg   A D(&C6'D(<AC< ?C8 C< D(/C:0D(8C< :D(<	D%D DD  D%%D(c              #    K   t        | j                        }t        t        |t	        |      t        j                                     }t        |      5 }|j                         D cg c]D  \  }}||j                  |j                         t        ||j                  d|                   fF }	}}|	D 
ci c]  \  }
}|j                  t        |      |
|f  }}
}|rmt        |t               \  }}|D ]Q  }|j                  |      \  }
}	 t#        |
|j%                         i      }| |
|f||j                  t        |      <   S |rmd d d        y c c}}w c c}}
w # t&        $ r Y ww xY w# 1 sw Y   y xY ww)Nlockr  r  r  )r   r8  r   rQ   r   	threadingLockr0   r   rQ  r  r2   r  r  r  r   r   r5   r  r  )rs   r   r  r   r9  input_copiesr  rg   rQ  named_generators	step_name	generatorr  completed_futuresrl   r  r  s                    rw   r  zRunnableParallel._transformf  s     T\\" GFCJY^^=MNO$V, "	 #(++-  D$ NN$((*$"k.C.ChtfDU.V    -=(Iy i09i2HHG  '+G'Q$!1/ 
F-4[[-@*Y	 +Y,H I#%%Ei @A
 -"	 "	 $ ) C"	 "	sa   AE?E3)A	E2E3:#E2E3:E$
E3	E?E3$	E0-E3/E00E33E<8E?c              +  ^   K    | j                   || j                  |fi |E d {    y 7 wr   )r  r  r   s       rw   rQ  zRunnableParallel.transform  s5      64554??F
.4
 	
 	
s   #-+-c              +  X   K   | j                  t        |g      |      E d {    y 7 wr   r  r   s       rw   r1  zRunnableParallel.stream  s"      >>$w-888s    *(*c               "  K   t        | j                        }t        t        |t	        |      t        j                                     }|j                         D cg c]D  \  }}||j                  |j                         t        ||j                  d|                   fF }}}dd}	|D 
ci c]#  \  }
}t        j                   |	|            |
|f% }}
}|rt        j                  |t
        j                         d {   \  }}|D ]Y  }|j                  |      \  }
}	 t        |
|j!                         i      }| t        j                   |	|            }|
|f||<   [ |ry y c c}}w c c}}
w 7 v# t"        $ r Y zw xY ww)Nr  r  r  c                4   K   t        |        d {   S 7 wr   )r  )r  s    rw   get_next_chunkz4RunnableParallel._atransform.<locals>.get_next_chunk  s     y))))s   r  )r  r   r   zOutput | None)r   r8  r   rP   r   r+  r  r   rT  r  r2   r  r  r   r   r5   r  r  )rs   r   r  r   r9  r  rg   rQ  r  r  r  r  taskscompleted_tasksrl   taskr  new_tasks                     rw   r  zRunnableParallel._atransform  s     T\\" DU',,.IJ $kkm
 d  $$& +*?*?(4&@Q*R
 
	* )9
$	9 y 9:Y	<RR
 
 '.||7#:#:( "OQ ( ).4&I'DKKM(BCEK&22>)3LMH'0)&<E(O	 3
$
" * sV   AFA	E2&F2(E8-FE> F)AF +F0F 	F	FFFc               n   K    | j                   || j                  |fi |2 3 d {   }| 7 
6 y wr   )r  r  r  s        rw   rT  zRunnableParallel.atransform  sK      ?4>>4##V
/5
 	 	% K	 
s    5313535c               l   K   dfd}| j                   |       |      2 3 d {   }| 7 
6 y w)Nc                   K     y wr   r   r  s   rw   r  z-RunnableParallel.astream.<locals>.input_aiter  r  r  r  r  r  s    `    rw   r3  zRunnableParallel.astream  s8     	  ??;=&A 	 	%K	As   4202424r   )r8  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   r  )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   r  )ro   r   r  r  r  rO  r  r"   r\  rW  r   r0  rx   r  r   r   r   r   r   rw  r   r   r  rQ  r1  r  rT  r3  r1  r2  s   @rw   r   r     s
   Qf 0/ 

F
 

4    3  3  $L 3 3 3     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  )-	#	 &	 		
 
'	 	  )-

 &
 	

 
'
 
ry   r   c                     e Zd ZdZ	 ddd	 	 	 	 	 	 	 ddZeedd              Zeddd       Zeedd              Z	e	 d	 	 	 dd       Z
edd	       ZdZedd
       Ze	 d	 	 	 	 	 	 	 dd       Ze	 d	 	 	 	 	 	 	 dd       Ze	 d	 	 	 	 	 	 	 dd       Ze	 d	 	 	 	 	 	 	 dd       Ze	 d	 	 	 	 	 	 	 dd       Ze	 d	 	 	 	 	 	 	 dd       Zy)RunnableGeneratoru(  `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"
        ```
    Nrh   c                  |	|| _         |}t        |      r
|| _         |}n8t        j                  |      r
|| _        |}ndt        |       }t        |      	 |xs |j                  | _        y# t        $ r
 d| _        Y yw xY w)a#  Initialize 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: r  )
r  rF   r   isgeneratorfunctionr  r#  r   ro   rg   AttributeError)rs   rQ  rT  rg   func_for_namer   s         rw   rO  zRunnableGenerator.__init__V  s    ( !)D&0Mi((D%M((3'DO%M448O3DF  C. 	,6 6 6DI 	,+DI	,s   A0 0BBc                   t        | dd       xs | j                  }	 t        j                  |      j                  }t        t        |j                               d       }|rF|j                  t        j                  j                  k7  rt        |j                  dt        f      d   S t        S # t        $ r Y t        S w xY wNr  __args__r   )getattrr  r   	signature
parametersr  r  r   r   	Parameteremptyr   r%  rs   r  paramsfirst_params       rw   r   zRunnableGenerator.InputType  s     t\40DD4D4D	&&t,77FtFMMO4d;K{559J9J9P9PP{55zC6J1MM 
  	
	s   B	B- -	B>=B>c                   | j                   }t        | dd       xs | j                  }t        |dd       }t        j                  |      r"t        |t              st        |t              r|S t        | j                  d      ||      S )Nr  r   r9   r   )r   r  r  r   r   r   r   r   r   rR   rx   rs   r   r   r  modules        rw   r   z"RunnableGenerator.get_input_schema  s}    
 NN	t\40DD4D4D|T2 OOI&y,79i0MM'" 
 	
ry   c                &   t        | dd       xs | j                  }	 t        j                  |      }|j                  t        j
                  j                  k7  rt        |j                  dt        f      d   S t        S # t        $ r	 t        cY S w xY wr  )	r  r  r   r  return_annotation	Signaturer	  r   r%  rs   r  sigs      rw   r   zRunnableGenerator.OutputType  s     t\40DD4D4D	##D)C ((G,=,=,C,CC --zC6B1E 
  	J	s   AA> 8A> >BBc                   | j                   }t        | dd       xs | j                  }t        |dd       }t        j                  |      r"t        |t              st        |t              r|S t        | j                  d      ||      S )Nr  r   r:   r   )r   r  r  r   r   r   r   r   r   rR   rx   r  s        rw   r   z#RunnableGenerator.get_output_schema  s}     OO	t\40DD4D4D|T2 OOI&y,79i0MM(# 
 	
ry   c                    t        |t              rct        | d      r%t        |d      r| j                  |j                  k(  S t        | d      r%t        |d      r| j                  |j                  k(  S yy)Nr  r  F)r   r  rm   r  r  r   s     rw   __eq__zRunnableGenerator.__eq__  se    e./t\*wul/K%*:*:::t]+}0M''5+<+<<<ry   c                "    d| j                    dS )NzRunnableGenerator()rh   r   s    rw   rw  zRunnableGenerator.__repr__  s    #DII;a00ry   c                |    t        | d      s| d}t        |       | j                  || j                  |fddi|S )Nr  z only supports async methods.r  T)rm   rI  r  r  rs   r   r   r   r   s        rw   rQ  zRunnableGenerator.transform  s\     t\*H9:C%c**1t11OO
 	

 
 	
ry   c                >     | j                   t        |g      |fi |S r   r  r   s       rw   r1  zRunnableGenerator.stream  "     t~~dE7mV>v>>ry   c                b    d } | j                   ||fi |D ]  }||n||z   } t        d|      S Nr:   )r1  r   rs   r   r   r   rP  rS  s         rw   r   zRunnableGenerator.invoke  sH      $!dkk%:6: 	@F#mFE	@He$$ry   c                |    t        | d      s| d}t        |       | j                  || j                  |fddi|S )Nr  z only supports sync methods.r  T)rm   rI  r  r  r  s        rw   rT  zRunnableGenerator.atransform  sX     t]+H89C%c**2t224##V
;?
CI
 	
ry   c                B    dfd} | j                    |       |fi |S )Nc                   K     y wr   r   r  s   rw   r  z.RunnableGenerator.astream.<locals>.input_aiter  r  r  r  r  )rs   r   r   r   r  s    `   rw   r3  zRunnableGenerator.astream  s$    	 t{}f???ry   c                z   K   d } | j                   ||fi |2 3 d {   }||n||z   }7 6 t        d|      S wr  )r3  r   r   s         rw   r   zRunnableGenerator.ainvoke  sV       $(DLLA&A 	@ 	@&#mFE	@AHe$$s   ;.,.;.;r   )rQ  zgCallable[[Iterator[Input]], Iterator[Output]] | Callable[[AsyncIterator[Input]], AsyncIterator[Output]]rT  z>Callable[[AsyncIterator[Input]], AsyncIterator[Output]] | Nonerg   rf   r   r  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   r  r   r   r   r  )r   r9   r   r  r   r   r   r  )ro   r   r  r  rO  r  r"   r   r   r   r   r  __hash__rw  rQ  r1  r   rT  r3  r   r   ry   rw   r  r    sW   Y@ (,  (,B(,	(, (, 
(,T 	  	 
 
2 
  
 .2
+
	
 
4   H1 1  )-

 &
 	

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

 

 
  )-	@	@ &	@ 		@
 
	@ 	@ <@%%$9%LO%	% %ry   r  c                  `    e Zd ZdZ	 	 d	 	 	 	 	 	 	 ddZeedd              Zedd fd       Zeedd              Z	e	 d	 	 	 dd       Z
ej                  dd       Zeedd	              Zedd fd
       Zedd       ZdZd dZ	 	 	 	 	 	 	 	 	 	 d!dZ	 	 	 	 	 	 	 	 	 	 d"dZe	 d	 	 	 	 	 	 	 d#d       Ze	 d	 	 	 	 	 	 	 d#d       Z	 	 	 	 	 	 	 	 	 	 d$dZe	 d	 	 	 	 	 	 	 d%d       Ze	 d	 	 	 	 	 	 	 d&d       Z	 	 	 	 	 	 	 	 	 	 d'dZe	 d	 	 	 	 	 	 	 d(d       Ze	 d	 	 	 	 	 	 	 d)d       Z xZS )*RunnableLambdaa  `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                x   |	|| _         |}t        |      st        |      r|d}t        |      || _         |}n8t	        |      rt        d|      | _        |}ndt        |       }t        |      	 ||| _        n |j                  dk7  r|j                  | _        d| _        y# t        $ r
 Y d| _        yw xY w)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#  rg   ro   r   _repr)rs   r  r-  rg   r  r   s         rw   rO  zRunnableLambda.__init__Y  s    R DJ&+MT"&8&> 3 
  n$DJ Md^8$?DI M448J<A  C. 	 	'':5)22	 "&
  	!%
	s   4*B& &	B98B9c                \   t        | dd      xs | j                  }	 t        j                  |      j                  }t        t        |j                               d      }|r3|j                  t        j                  j                  k7  r|j                  S t        S # t        $ r Y t        S w xY w)z)The type of the input to this `Runnable`.r  N)r  r-  r   r  r  r  r  r   r   r  r	  r%  r   r
  s       rw   r   zRunnableLambda.InputType  s     tVT*8djj	&&t,77FtFMMO4d;K{559J9J9P9PP"--- 
  	
	s   A6B 	B+*B+c                   t        | dd      xs | j                  }t        |t              rt	        |      j                  dd      dd j                  d      }t        d |D              r5|D ci c]  }|dd t        d	f }}t        | j                  d
      |      S t        |dd      }t        | j                  d
      t        t           |      S | j                  t        k7  rt        | 9  |      S t        |      x}r6t        | j                  d
      t         j#                  |t        d	f            S t        | 9  |      S c c}w )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  N   K   | ]  }|d    dk(  xr |d   dk(  xr |dk7    yw)r   'r?  z''Nr   )r  rD  s     rw   r  z2RunnableLambda.get_input_schema.<locals>.<genexpr>  s6      HLQ3C48s?Ctt|Cs   #%r   .r9   r   r   r   )r  r-  r   r   r   replacesplitr  r   rR   rx   r   r   r  r   r@   r   fromkeys)	rs   r   r  r   rD  r!  r  	dict_keysrn   s	           rw   r   zRunnableLambda.get_input_schema  sF    tVT*8djjdJ' I%%&<bA#2FLLTRE PU  >CCT$q*sCj0CC&t}}W'=QWXXT<6F"g&#Y #  >>S 7+F338>>9>"g&"&--	C:"F 
 w'//- Ds   0E
c                   t        | dd      xs | j                  }	 t        j                  |      }|j                  t        j
                  j                  k7  rvt        |j                  dd      t        j                  j                  t        j                  j                  hv rt        |j                  dt        f      d   S |j                  S 	 t        S # t        $ r Y t        S w xY w)zThe type of the output of this `Runnable` as a type annotation.

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

        r  N
__origin__r  r   )r  r-  r   r  r  r  r	  collectionsabcr   r   r   r%  r  s      rw   r   z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 	C'&C'c                   | j                   }t        | dd       xs | j                  }t        |dd       }t        j                  |      r"t        |t              st        |t              r|S t        | j                  d      ||      S )Nr  r   r:   r   )r   r  r-  r   r   r   r   r   r   rR   rx   r  s        rw   r   z RunnableLambda.get_output_schema  s{     OO	tVT*8djj|T2 OOI&y,79i0MM(# 
 	
ry   c                V   t        | d      rt        | j                        }n$t        | d      rt        | j                        }ng }g }|D ][  }t	        |t
              r|j                  |       %t	        t        |dd      t
              sA|j                  |j                         ] |S )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)	rm   rA   r  r-  r   re   r  r  r>  )rs   objectsdepsobjs       rw   r@  zRunnableLambda.deps  s     4 ,TYY7GT7#,TZZ8GG! 	*C#x(C GCT:HECLL)		*
 ry   c                :    t        d | j                  D              S )Nc              3  B   K   | ]  }|j                   D ]  }|   y wr   r  )r  depr   s      rw   r  z.RunnableLambda.config_specs.<locals>.<genexpr>,  s-      '
#2B2B'
*.D'
'
r  )rC   r@  r   s    rw   r   zRunnableLambda.config_specs)  s"     ' '
 II'
 
 	
ry   c                4   | j                   x}rddlm}  |       }|j                  | j	                  |            }|j                  | j                  |            }|D ]  }|j                         }|j                          |j                          |s|j                  ||       H|j                  |      \  }	}
|	sd| d}t        |      |
sd| d}t        |      |j                  ||	       |j                  |
|        |S t        |   |      }|S )Nr   rY   r}   rk  r  )r@  r   rZ   r   r   r   r   rm  rn  r   rM  r%  r  )rs   r   r@  rZ   r   r   r   rD  	dep_graphdep_first_nodedep_last_noder   rn   s               rw   r   zRunnableLambda.get_graph0  s   994<GE(=(=f(EFJ..)?)?)GHK ?MMO	))+((* NN:{;49LL4K1NM) )#.@A(o-( )#.?@(o-NN:~>NN=+>?&  G%f-Ery   c                    t        |t              rct        | d      r%t        |d      r| j                  |j                  k(  S t        | d      r%t        |d      r| j                  |j                  k(  S yy)Nr  r-  F)r   r*  rm   r  r-  r   s     rw   r  zRunnableLambda.__eq__N  s^    e^,tV$)?yyEJJ..tW%'%*AzzU[[00ry   c                   | j                   t        | d      rPt        | j                  t              r6dt        | j                        t        d      d  d| _         | j                   S t        | d      r.dt        | j                        xs d d| _         | j                   S t        | d      r.dt        | j                        xs d d| _         | j                   S d	| _         | j                   S )
z2Return a string representation of this `Runnable`.Nr  zRunnableLambda(z	operator.r  z...r-  zRunnableLambda(afunc=zRunnableLambda(...))	r/  rm   r   r  r   r   r   rB   r-  r   s    rw   rw  zRunnableLambda.__repr__Z  s    ::tV$DIIz)J.s499~c+>N>P/Q.RRST
 zz v&./@/K/Tu.UUVW
 zz w'+,=djj,I,RU+SSTU 

 zz 3
zzry   c           	        t        j                  | j                        r6d }t        t	        d| j                        |||fi |D ]  }||}	 ||z   } nt        | j                  |||fi |}t        |t              rM|d   }|dk  rd|  d| d}t        |      |j                  |t        ||j                         |dz
              }t	        d	|      S # t
        $ r |}Y w xY w)
N#Callable[[Input], Iterator[Output]]recursion_limitr   &Recursion limit reached when invoking  with input .r   re  rM  r:   )r   r  r  r+   r   r   r   re   RecursionErrorr   r2   r  )	rs   r   r  r   r   rS  r  rM  r   s	            rw   _invokezRunnableLambda._invokei  s%    &&tyy1$(F5:DIIF	
  ' >"F'!'%' 2		66;:@F fh'$%67O!#<TF,vhVWX  %S))]])335$3a$7F Hf%%- % '!&'s   CC&%C&c                \   K   t         d      r j                  }nWt        j                   j                        r	 	 	 	 	 	 	 	 	 	 d fdn	 	 	 	 	 	 	 	 	 	 d fdt              dfd       }|}t        |      rXd }t        t        dt        t        d|      ||fi |            4 d {   }t        d|      2 3 d {   }	||	}	 ||	z   }t        t        d|      ||fi | d {   }t        |t              rUd	   }
|
d
k  rd  d| d}t        |      |j                  |t        |j!                         |
dz
               d {   }t        d|      S 7 7 # t        $ r |	}Y w xY w6 d d d       d {  7   # 1 d {  7  sw Y   xY w7 7 Ow)Nr-  r:   c                    d }t        t        dj                        | ||j                         fi |D ]  }||}	 ||z   } t        d|      S # t        $ r |}Y )w xY w)NrL  r:   )r+   r   r  get_syncr   )r  r  r   r   rS  r  rs   s         rw   r  z%RunnableLambda._ainvoke.<locals>.func  s     -1F!=BDIIN#,,.	"
 !" / ">%*F/)/%/  &11 $- /)./s   AAAc                R    t        j                  | ||j                         fi |S r   r+   r  rV  )r  r  r   r   rs   s       rw   r  z%RunnableLambda._ainvoke.<locals>.func  s0     8		5&+2F2F2HLR ry   c                 @   K   t        g| i | d {   S 7 wr   r3   r{   r   r   r  s     rw   fz"RunnableLambda._ainvoke.<locals>.f  $     ,VTKDKFKKKK   zAsyncGenerator[Any, Any]r	   r  rM  r   rN  rO  rP  r   rQ  
r  r9   r  rS   r   r)   r   r   r   r:   r{   r   r   r   r   r   )rm   r-  r   r  r  r   rF   rO   r   r*   r   r   re   rR  r   r2   r  )rs   r  r  r   r   r-  r\  rS  r1  r  rM  r   r  s   `  `        @rw   _ainvokezRunnableLambda._ainvoke  s:     4!JJE**49952 2!@2 +2 "	2
 22 !@ + "	
  4[L L Ee$$(F.1Z/#	
 !	 + + #'+$ 
+ 
+% ~!&+%+e^F 9Z'GM F fh'$%67O!#<TF,ugUVW  %S))!>>)335$3a$7 F Hf%%W+
+  ) +%*F+$+ + + + +0s   B.F,3E+4F,7FF E-	F FE/FF,5F(6A$F,F*F,-F /E=:F<E==FF,FF,F%FF%!F,*F,c                    t        | d      r( | j                  | j                  |t        |      fi |S d}t	        |      )aZ  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.)rm   r  rS  r,   r   r  s        rw   r   zRunnableLambda.invoke  sQ    * 4 )4))f% 	  Xnry   c                n   K    | j                   | j                  |t        |      fi | d{   S 7 w)a  Invoke 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  ra  r,   r   s       rw   r   zRunnableLambda.ainvoke  sC     $ -T,,MM&!
 	
 
 	
 
s   ,535c           	   +  x  K   d}|D ]  }|s|}d}
	 |z   } t        j                  | j                        r0d }t	        | j                  ||fi |D ]  }	|	 ||	}	 ||	z   } nt	        | j                  ||fi |}t        |t              rW|d   }
|
dk  rd|  d| d}t        |      |j                  |t        ||j                         |
dz
  	            D ]  }	|	  y t        j                  | j                        st        d
|       y y # t         $ r |}Y w xY w# t         $ r |	}Y w xY ww)NFTrM  r   rN  rO  rP  r   rQ  r:   )r   r   r  r  r+   r   re   rR  r1  r2   r  r   )rs   chunksr  r   r   rN  rO  rP  rS  r  rM  r   s               rw   r  zRunnableLambda._transform2  s      	#F
 ! $#!FNE	# &&tyy1$(F5		5&+9? 
' >"F'!'%
' 2		5&+9?F
 fh'$%67O!#<TF,ugUVW  %S)))335$3a$7   ,,TYY7x(( 8M ! #"E# % '!&'sM   D:DAD: D)%B2D:D&"D:%D&&D:)D74D:6D77D:c              +     K   t        | d      r1 | j                  || j                  t        |      fi |E d {    y d}t	        |      7 w)Nr  zGCannot stream a coroutine function synchronously.Use `astream` instead.)rm   r  r  r,   r   r  s        rw   rQ  zRunnableLambda.transformp  sc      4 9t99f% 	  )  C. s   8AAAc                >     | j                   t        |g      |fi |S r   r  r   s       rw   r1  zRunnableLambda.stream  r  ry   c           	    \   K   d}|2 3 d {   }|s|}d}	 |z   }7 # t         $ r |}Y &w xY w6 t         d      r j                  }nSt        j                   j
                        rd}	t        |	      	 	 	 	 	 	 	 	 	 	 d fdt              dfd       }
|
}t        |      rSd }t        dt        t        d	|      |fi |      2 3 d {  7  }| ||}	 ||z   }# t         $ r |}Y (w xY w6 n"t        t        d	|      |fi | d {  7  }t        |t              r_d
   }|dk  rd  d| d}	t        |	      |j                  |t        |j                         |dz
              2 3 d {  7  }| 6 y t        |      st        d|       y y w)NFTr-  zMCannot stream from a generator function asynchronously.Use .stream() instead.r:   c                R    t        j                  | ||j                         fi |S r   rX  )r   r  r   r   rs   s       rw   r  z(RunnableLambda._atransform.<locals>.func  s0     4IIvv{/C/C/EIO ry   c                 @   K   t        g| i | d {   S 7 wr   rZ  r[  s     rw   r\  z%RunnableLambda._atransform.<locals>.f  r]  r^  r  r	   rM  r   rN  rO  rP  r   rQ  )
r   r9   r  rS   r   r)   r   r   r   r:   r`  )r   rm   r-  r   r  r  r   rF   r   r*   r   re   rR  r3  r2   r  )rs   re  r  r   r   rN  rO  rP  r-  r   r\  rS  r  rM  r  s   `  `          @rw   r  zRunnableLambda._atransform  sE     " 	# 	#&
 ! $#!FNE	# ! #"E# # 4!JJE**499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   F,4!4F,#F,41F,1B F,C=CC=F,&C,+F,,C:7F,9C::!F,DA"F,>FFF%F,c                  K    | j                   || j                  t        |      fi |2 3 d {   }| 7 
6 y wr   )r  r  r,   )rs   r   r   r   rS  s        rw   rT  zRunnableLambda.atransform  sU      @D??&!
 	
 	 	& L	 
s   )><:<><>c               p   K   dfd} | j                    |       |fi |2 3 d {   }| 7 
6 y w)Nc                   K     y wr   r   r  s   rw   r  z+RunnableLambda.astream.<locals>.input_aiter  r  r  r  r  r  s    `    rw   r3  zRunnableLambda.astream   r  r  r  )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]] | Nonerg   rf   r   r  r  r   r  )r   zlist[Runnable]r  r  r%  r  )
r   r9   r  rT   r   r)   r   r   r   r:   r_  r  )
re  r  r  rT   r   r)   r   r   r   r   r  r  )
re  r  r  rS   r   r)   r   r   r   r  r  r  )ro   r   r  r  rO  r  r"   r   r   r   r   r  cached_propertyr@  r   r   r  r(  rw  rS  ra  r   r   r  rQ  r1  r  rT  r3  r1  r2  s   @rw   r*  r*  )  s   -J /I&
I&I&. /I&0 
1I&V 
  
 )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  )-# & 	
 
   )-

 &
 	

 

 
ry   r*  c                     e Zd ZU dZded<    ed      Zeedd              Z	eddd       Z
eedd	              Ze	 d	 	 	 dd
       Zeedd              Zeddd       Zeedd              Zeedd              Z	 	 	 	 	 	 	 	 	 	 ddZe	 d	 	 	 	 	 	 	 dd       Z	 	 	 	 	 	 	 	 	 	 ddZe	 d	 	 	 	 	 	 	 dd       Ze	 d	 	 	 	 	 	 	 dd       Zy) RunnableEachBasea  RunnableEachBase 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.

    r	  rV  Tr^  c                <    t         | j                  j                     S r   )r   rV  r   r   s    rw   r   zRunnableEachBase.InputType   s     DJJ(())ry   Nc                    t        | j                  d      t        | j                  j	                  |         d f| j
                  j                        S )Nr9   r   )rR   rx   r   rV  r   rn   r   r   s     rw   r   z!RunnableEachBase.get_input_schema%  sI    MM'"TZZ0089 11
 	
ry   c                <    t         | j                  j                     S r   )r   rV  r   r   s    rw   r   zRunnableEachBase.OutputType7  s     DJJ))**ry   c                    | j                   j                  |      }t        | j                  d      t        |   | j
                  j                        S )Nr:   r   )rV  r   rR   rx   r   rn   r   )rs   r   rU  s      rw   r   z"RunnableEachBase.get_output_schema<  sG     --f5MM(#f 11
 	
ry   c                .    | j                   j                  S r   rV  r   r   s    rw   r   zRunnableEachBase.config_specsN       zz&&&ry   c                8    | j                   j                  |      S r   )rV  r   r   s     rw   r   zRunnableEachBase.get_graphS  s    zz##F++ry   c                     yr[  r   rV  s    rw   r\  z#RunnableEachBase.is_lc_serializableW  r]  ry   c                
    g dS rS  r   rV  s    rw   rW  z!RunnableEachBase.get_lc_namespace]  rX  ry   c                    |D cg c]  }t        ||j                                }} | j                  j                  ||fi |S c c}w Nr  )r2   r  rV  r  rs   r   r  r   r   rl   r   s          rw   rS  zRunnableEachBase._invokeg  sU     NT
HIL;+@+@+BC
 
  tzz:6::
s   "Ac                @     | j                   | j                  ||fi |S r   )r  rS  r   s       rw   r   zRunnableEachBase.invokes  s$     &t%%dllE6LVLLry   c                   K   |D cg c]  }t        ||j                                }} | j                  j                  ||fi | d {   S c c}w 7 	wr|  )r2   r  rV  r"  r}  s          rw   ra  zRunnableEachBase._ainvokey  sb      NT
HIL;+@+@+BC
 
 'TZZ&&vwA&AAA
 Bs   A"A#AA
Ac                \   K    | j                   | j                  ||fi | d {   S 7 wr   )r  ra  r   s       rw   r   zRunnableEachBase.ainvoke  s.      -T,,T]]E6TVTTTTs   #,*,c               J   K   dd}t        d      D ]  } |d        y w)Nc                    t        |       r   )rI  r  s    rw   _error_stream_eventz<RunnableEachBase.astream_events.<locals>._error_stream_event  s    %g..ry   r   z1RunnableEach does not support astream_events yet.)r  r   r   r\   )r  )rs   r   r   r   r  rl   s         rw   rL  zRunnableEachBase.astream_events  s0     	/ q 	A%C 	s   !#r  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  )ro   r   r  r  r  r   r0  r  r"   r   r   r   r   r   r   r  r\  rW  rS  r   ra  r   rL  r   ry   rw   rp  rp    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
  )- & 	
 
$ ry   rp  c                       e Zd ZdZed
ddd fd       Zedd       Ze	 d
	 	 	 	 	 dd       Zedddd	 	 	 	 	 	 	 dd       Zdddd	 	 	 	 	 	 	 dd	Z	 xZ
S )r  aK  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

        ```
    Nrh   c                   |xs, | j                   xs d| j                  j                          d}t        | 	  ||      S )NzRunnableEach<r  rh   )rg   rV  rx   r  r  s      rw   rx   zRunnableEach.get_name  sB    LtyyLmDJJ4G4G4I3J!$LwT22ry   c                N    t         | j                  j                  di |      S )Nr  r   )r  rV  rZ  rY  s     rw   rZ  zRunnableEach.bind  s    /$**//";F";<<ry   c                P    t         | j                  j                  |fi |      S )Nr  )r  rV  r]  r\  s      rw   r]  zRunnableEach.with_config  s&     "8$**"8"8"J6"JKKry   r^  c               R    t        | j                  j                  |||            S )a  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  rV  rl  rk  s       rw   rl  zRunnableEach.with_listeners  s0    @ **++!&8 , 
 	
ry   c               R    t        | j                  j                  |||            S )a  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  rV  ro  rk  s       rw   ro  zRunnableEach.with_alisteners  s/    6 **,,!&8 - 
 	
ry   r   r  )r   r   r   RunnableEach[Input, Output])r   r  r   r   r   r  )r_  r  r`  r  ra  r  r   r  )r_  r  r`  r  ra  r  r   r  )ro   r   r  r  r"   rx   rZ  r]  rl  ro  r1  r2  s   @rw   r  r    s    : 3 3 3 = = .2L+L>AL	$L L
    #
#
#
#
 
%#
 #
P *.'+)-
 '
 %	

 '
 
%
ry   r  c                  D    e Zd ZU dZded<   	  ee      Zded<   	  ee      Z	ded<   	  ee
      Zd	ed
<   	 dZded<   	 dZded<   	  ed      Zdddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d/ fdZed0ddd1d       Zeed2d              Zeed3d              Zed0d4 fd       Ze	 d0	 	 	 d4 fd       Zeed5d              Zed0d6d       Zeed7d              Zeed8d              Zd9dZe	 d0	 	 	 	 	 	 	 d:d       Ze	 d0	 	 	 	 	 	 	 d:d       Ze	 d0d d!	 	 	 	 	 	 	 	 	 d;d"       Z e	 d0d d!	 	 	 	 	 	 	 	 	 d;d#       Z!e"	 d0d d!	 	 	 	 	 	 	 	 	 d<d$       Z#e"	 d0	 	 	 	 	 	 	 	 	 d=d%       Z#e	 d0d d!	 	 	 	 	 	 	 	 	 d>d&       Z#e"	 d0d d!	 	 	 	 	 	 	 	 	 d?d'       Z$e"	 d0	 	 	 	 	 	 	 	 	 d@d(       Z$e	 d0d d!	 	 	 	 	 	 	 	 	 dAd)       Z$e	 d0	 	 	 	 	 	 	 dBd*       Z%e	 d0	 	 	 	 	 	 	 dCd+       Z&e	 d0	 	 	 	 	 	 	 dDd,       Z'e	 d0	 	 	 	 	 	 	 dEd-       Z(e	 d0	 	 	 	 	 	 	 dFd.       Z) xZ*S )GRunnableBindingBasez`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.

    r	  rV  rH  zMapping[str, Any]r   r)   r   z0list[Callable[[RunnableConfig], RunnableConfig]]rj  Nr  rs  rt  Tr^  )r   r   rj  rs  rt  c          
     `    t        |   d||xs i |xs i |xs g ||d| |xs i | _        y)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.
        rV  r   r   rj  rs  rt  Nr   )r  rO  r   )	rs   rV  r   r   rj  rs  rt  other_kwargsrn   s	           rw   rO  zRunnableBindingBase.__init__?  sN    @ 	 	
<R<R-3/1	
 	
 lry   rh   c               <    | j                   j                  ||      S )Nrh   )rV  rx   )rs   rt   rg   s      rw   rx   zRunnableBindingBase.get_namem  s    zz""6"55ry   c                r    | j                   t        d| j                         S | j                  j                  S )Nr|   )rs  r   rV  r   r   s    rw   r   zRunnableBindingBase.InputTypeq  s;    
 %%1  6 67	
 %%	
ry   c                r    | j                   t        d| j                         S | j                  j                  S )Nr   )rt  r   rV  r   r   s    rw   r   zRunnableBindingBase.OutputTypez  s;    
 &&2 !8!89	
 &&	
ry   c                    | j                   t        | 	  |      S | j                  j                  t	        | j
                  |            S r   )rs  r  r   rV  r1   r   rs   r   rn   s     rw   r   z$RunnableBindingBase.get_input_schema  s?    !!-7+F33zz**=f+MNNry   c                    | j                   t        | 	  |      S | j                  j                  t	        | j
                  |            S r   )rt  r  r   rV  r1   r   r  s     rw   r   z%RunnableBindingBase.get_output_schema  sA     "".7,V44zz++M$++v,NOOry   c                .    | j                   j                  S r   rv  r   s    rw   r   z RunnableBindingBase.config_specs  rw  ry   c                V    | j                   j                  | j                  |            S r   )rV  r   _merge_configsr   s     rw   r   zRunnableBindingBase.get_graph  s"    zz##D$7$7$?@@ry   c                     yr[  r   rV  s    rw   r\  z&RunnableBindingBase.is_lc_serializable  r]  ry   c                
    g dS rS  r   rV  s    rw   rW  z$RunnableBindingBase.get_lc_namespace  rX  ry   c                n    t        | j                  g| t        gfd| j                  D         S )Nc              3  .   K   | ]  } |        y wr   r   )r  r\  r   s     rw   r  z5RunnableBindingBase._merge_configs.<locals>.<genexpr>  s     &PQqy&Ps   )r1   r   rj  )rs   r   r   s     @rw   r  z"RunnableBindingBase._merge_configs  s2    t{{5W5VQ&P$:O:O&PQQry   c                x     | j                   j                  || j                  |      fi i | j                  |S r   )rV  r   r  r   r   s       rw   r   zRunnableBindingBase.invoke  sF     !tzz  '
 (''
 	
ry   c                   K    | j                   j                  || j                  |      fi i | j                  | d {   S 7 wr   )rV  r   r  r   r   s       rw   r   zRunnableBindingBase.ainvoke  sT      (TZZ'''
 (''
 
 	
 
s   ?AAAFr   c          	     F   t        |t              r*t        d|D cg c]  }| j                  |       c}      }n0t	        t        |            D cg c]  }| j                  |       }} | j                  j                  ||fd|ii | j                  |S c c}w c c}w Nzlist[RunnableConfig]r   )	r   r   r   r  r  r   rV  r  r   rs   r   r   r   r   confr   rl   s           rw   r  zRunnableBindingBase.batch  s     fd#&7=>t$$T*>G
 =B#f+<NOqt**62OGOtzz
 0
 (''	
 	
	 ? Ps   B
Bc          	     b  K   t        |t              r*t        d|D cg c]  }| j                  |       c}      }n0t	        t        |            D cg c]  }| j                  |       }} | j                  j                  ||fd|ii | j                  | d {   S c c}w c c}w 7 wr  )	r   r   r   r  r  r   rV  r"  r   r  s           rw   r"  zRunnableBindingBase.abatch  s      fd#&7=>t$$T*>G
 =B#f+<NOqt**62OGO&TZZ&&
 0
 (''	
 
 	
	 ? P
s'   B/B#
B/B(+3B/B-B/c                    y r   r   r  s        rw   r  z&RunnableBindingBase.batch_as_completed  r  ry   c                    y r   r   r  s        rw   r  z&RunnableBindingBase.batch_as_completed   r  ry   c          	   +    K   t        |t              r*t        d|D cg c]  }| j                  |       c}      }n0t	        t        |            D cg c]  }| j                  |       }}|r7 | j                  j                  ||fd|ii | j                  |E d {    y  | j                  j                  ||fd|ii | j                  |E d {    y c c}w c c}w 7 F7 wr  )	r   r   r   r  r  r   rV  r  r   r  s           rw   r  z&RunnableBindingBase.batch_as_completed
  s	     fh'&7=>t$$T*>G
 =B#f+<NOqt**62OGO4tzz44 #4 ,T[[+F+	   5tzz44 #4 ,T[[+F+	   ? Ps9   C+C
C+C"+5C+ C'!6C+C)C+)C+c                    y r   r   r  s        rw   r$  z'RunnableBindingBase.abatch_as_completed*  r%  ry   c                    y r   r   r  s        rw   r$  z'RunnableBindingBase.abatch_as_completed4  r'  ry   c          	      K   t        |t              r*t        d|D cg c]  }| j                  |       c}      }n0t	        t        |            D cg c]  }| j                  |       }}|r= | j                  j                  ||fd|ii | j                  |2 3 d {   }|  | j                  j                  ||fd|ii | j                  |2 3 d {   }| c c}w c c}w 7 Q6 y 7 6 y wr  )	r   r   r   r  r  r   rV  r$  r   )	rs   r   r   r   r   r  r   rl   rD  s	            rw   r$  z'RunnableBindingBase.abatch_as_completed>  s$     fh'&7=>t$$T*>G
 =B#f+<NOqt**62OGO<djj<< #4 ,T[[+F+	  d 
<djj<< #4 ,T[[+F+	  d 
' ? P  sc   C;C)
C;C.+2C;C5!C3"C5%5C;C9C7C9"C;3C55C;7C99C;c              +     K    | j                   j                  || j                  |      fi i | j                  |E d {    y 7 wr   )rV  r1  r  r   r   s       rw   r1  zRunnableBindingBase.stream_  sO      %4::$$'
 (''
 	
 	
   ?A	AA	c                  K    | j                   j                  || j                  |      fi i | j                  |2 3 d {   }| 7 
6 y wr   )rV  r3  r  r   rs   r   r   r   rD  s        rw   r3  zRunnableBindingBase.astreaml  sc      -$**,,'
 (''
 	 	$
 J	 
(   <AAAAAAAc                  K    | j                   j                  || j                  |      fi i | j                  |2 3 d {   }| 7 
6 y wr   )rV  rL  r  r   r  s        rw   rL  z"RunnableBindingBase.astream_eventsz  s`      4$**334&&v.
2KT[[2KF2K
 	 	$ J	 
r  c              +     K    | j                   j                  || j                  |      fi i | j                  |E d {    y 7 wr   )rV  rQ  r  r   r   s       rw   rQ  zRunnableBindingBase.transform  sO      (4::'''
 (''
 	
 	
r  c                  K    | j                   j                  || j                  |      fi i | j                  |2 3 d {   }| 7 
6 y wr   )rV  rT  r  r   r  s        rw   rT  zRunnableBindingBase.atransform  sc      0$**//'
 (''
 	 	$
 J	 
r  )rV  r	  r   zMapping[str, Any] | Noner   r  rj  z7list[Callable[[RunnableConfig], RunnableConfig]] | Noners  type[Input] | BaseModel | Nonert  type[Output] | BaseModel | Noner  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  r  r  r&  r'  )+ro   r   r  r  r  r    r   r   r)   r   r   rj  rs  rt  r   r0  rO  r"   rx   r  r   r   r   r   r   r   r  r\  rW  r  r   r   r  r"  r   r  r$  r1  r3  rL  rQ  rT  r1  r2  s   @rw   r  r    sK    #"F %d ;F; #>BFNB:INJF  E %)z(
 &*
)
  $L ,0(,<@>B,# ',# )	,#
 &,#,# :,# <,# ,# 
,#\ 6 6 6 
  
 
  
 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 @  )-



 &

 	


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

 


 

  )-# & 	
 
 ry   r  c                      e Zd ZdZed
d       Ze	 d	 	 	 	 	 dd       Zedddd	 	 	 	 	 	 	 dd       Ze	 	 d	 	 	 	 	 dd       Zed
d       Z	edd	       Z
y)rX  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                    | j                  | j                  | j                  | j                  i | j                  || j
                  | j                        S )a(  Bind 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.

        )rV  r   rj  r   rs  rt  )rn   rV  r   rj  r   rs  rt  rY  s     rw   rZ  zRunnableBinding.bind  sT     ~~**;;!22,dkk,V,"44#66  
 	
ry   Nc           
         | j                  | j                  | j                  t        di | j                  |xs i |      | j
                  | j                  | j                        S )Nr)   r  )rn   rV  r   r   r   rj  rs  rt  r\  s      rw   r]  zRunnableBinding.with_config  sf     ~~**;;(*UT[[*UV\r*Uf*UV!22"44#66  
 	
ry   r^  c                   dfd}| j                  | j                  | j                  | j                  |g| j                  | j
                  | j                        S )a  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                (    dt        |       giS rd  rf  rg  s    rw   listener_config_factoryz?RunnableBinding.with_listeners.<locals>.listener_config_factory  s)    '%!)%!)		 	ry   r  )r   r)   r   r)   rn   rV  r   r   rj  rs  rt  )rs   r_  r`  ra  r  s    ``` rw   rl  zRunnableBinding.with_listeners  sY    @
	 ~~**;;;;5N8M8MN"44#66  
 	
ry   c                    | j                  | j                  | j                  | j                  | j                  ||n| j
                  ||      S | j                        S )Nr  r  ru  s      rw   rv  zRunnableBinding.with_types0  sm     ~~**;;;;!22(4
$:P:P  +6  
 	
 =A<S<S  
 	
ry   c                    | j                   | j                  j                  di || j                  | j                  | j
                        S )N)rV  r   r   rj  r   )rn   rV  r  r   r   rj  rY  s     rw   r  zRunnableBinding.with_retryC  sF    ~~'$**''1&1;;;;!22	  
 	
ry   c                    t         j                  |      t              rt        j                        j
                  j                  d      x}r|j                  t        j                  j                  k(  rt              d fd       }|S |j                  t        j                  j                  k(  rOt        t        j                        j
                        j                  d      t              d fd       }|S S )Nr   c                 `     | dt        j                  |j                  dd             i|S )Nr   )r1   r   r  )r{   r   attrrs   s     rw   wrapperz,RunnableBinding.__getattr__.<locals>.wrapperU  s;    ,T[[&**Xt:TU ! ry   c                     t        |       dz   k\  r/t        |       }t        j                  |         |<    |i |S  | dt        j                  |j	                  dd             i|S )Nr   r   )r   r   r1   r   r  )r{   r   argslr  r  rs   s      rw   r  z,RunnableBinding.__getattr__.<locals>.wrappera  s|    4yC!G+ $T
%24;;c
%Kc
#U5f55,T[[&**Xt:TU ! ry   r`  )r  rV  r.  r   r  r  r   kindr  KEYWORD_ONLYr   POSITIONAL_OR_KEYWORDr   index)rs   rg   config_paramr  r  r  s   `   @@rw   __getattr__z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	 	 ry   r  r   r
  r  r  )rp  r  rq  r  r   r	  )rg   r   r   r   )ro   r   r  r  r"   rZ  r]  rl  rv  r  r  r   ry   rw   rX  rX    s    1f 
 
(  )-
%
 	

 
!
 
    2
2
2
2
 
!2
 2
h  6:7;
2
 5
 
!	
 
$ 
 
 " "ry   rX  c                      e Zd ZddZy)_RunnableCallableSyncc                   y r   r   rs   _inr   s      rw   __call__z_RunnableCallableSync.__call__s  r   ry   N)r  r9   r   r)   r   r:   ro   r   r  r  r   ry   rw   r  r  r  s    Ory   r  c                       e Zd Z	 	 	 	 	 	 ddZy)_RunnableCallableAsyncc                   y r   r   r  s      rw   r  z_RunnableCallableAsync.__call__w  s    ry   N)r  r9   r   r)   r   zAwaitable[Output]r  r   ry   rw   r  r  v  s      (6 	 ry   r  c                       e Zd Z	 	 	 	 	 	 ddZy)_RunnableCallableIteratorc                   y r   r   r  s      rw   r  z"_RunnableCallableIterator.__call__}  s    ry   N)r  r  r   r)   r   r   r  r   ry   rw   r  r  |  s    "2@	ry   r  c                       e Zd Z	 	 	 	 	 	 ddZy)_RunnableCallableAsyncIteratorc                   y r   r   r  s      rw   r  z'_RunnableCallableAsyncIterator.__call__  s     #ry   N)r  r  r   r)   r   r  r  r   ry   rw   r  r    s    $'$7E$	$ry   r  c                8   t        | t              r| S t        |       st        j                  |       rt        |       S t        |       rt        t        d|             S t        | t              rt        dt        |             S dt        |        }t        |      )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,  r	  zGExpected a Runnable, callable or dict.Instead got an unsupported type: )r   re   rF   r   r  r  r.  r*  r   r   r   r#  r   )thingr   s     rw   r   r     s     %"% G$?$?$F ''d#>FGG%-/?/FGG,,0K=	:  C.ry   c                     y r   r   r  s    rw   chainr         "ry   c                     y r   r   r  s    rw   r  r    r  ry   c                     y r   r   r  s    rw   r  r    r  ry   c                     y r   r   r  s    rw   r  r    r  ry   c                    t        |       S )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    rw   r  r    s    D $ry   )r9  rJ  r   r  r   r  )r  r  r   r	  )r  z.Callable[[Input], Coroutine[Any, Any, Output]]r   r	  )r  rL  r   r	  )r  z(Callable[[Input], AsyncIterator[Output]]r   r	  )r  r,  r   r	  )r  zCallable[[Input], Output] | Callable[[Input], Iterator[Output]] | Callable[[Input], Coroutine[Any, Any, Output]] | Callable[[Input], AsyncIterator[Output]]r   r	  )r  
__future__r   r+  r:  r  r  r   r  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   r  r6  rA  rN  r   r   r   r   RunnableMapr  r*  r   rp  r  r  rX  r  r  r  r  r  r   r  r   ry   rw   <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"" 
"
 
"
#"" 
"
" /" 
 " ry   