a
    ”˜ëjq� ã                   @  sZ  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 ddlmZmZ ddlmZ ddlmZ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)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1m2Z2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z: ddl;m<Z<m=Z=m>Z> ddl?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZK ddlLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^ ddl_m`Z` ddlambZbmcZc ddldmeZemfZf ddlgmhZhmiZi ddljmkZkmlZlmmZm ddlnmoZo ddlpmqZq e �rÊddl8mrZrmsZs ddltmuZu ddlvmwZx ddlymzZz ddl{m|Z| dd l}m~Z~ dd!lm€Z€ dd"ldm�Z�m‚Z‚ dd#lgmƒZƒ dd$l„m…Z… e&d%ƒZ†G d&d'„ d'e
e#eQeRf ƒZ‡G d(d)„ d)e<e‡eQeRf ƒZˆd*d+d,d-œd.d/„Z‰d*d+d,d-œd0d1„ZŠG d2d3„ d3eˆeQeRf ƒZ‹G d4d5„ d5eˆeQeŒe�e!f f ƒZŽeŽZ�G d6d7„ d7e‡eQeRf ƒZ�G d8d9„ d9e‡eQeRf ƒZ‘G d:d;„ d;eˆe’eQ e’eR f ƒZ“G d<d=„ d=e“eQeRf ƒZ”G d>d?„ d?eˆeQeRf ƒZ•G d@dA„ dAe•eQeRf ƒZ–G dBdC„ dCe%eQeRf ƒZ—G dDdE„ dEe%eQeRf ƒZ˜G dFdG„ dGe%eQeRf ƒZ™G dHdI„ dIe%eQeRf ƒZše'e‡eQeRf e"eQgeRf e"eQgeeR f e"eeQ geeR f e"eeQ geeR f e—eQeRf e˜eQeRf e™eQeRf ešeQeRf ee�e!f f
 Z›dJdKdLœdMdN„Zœe*dOdKdPœdQdR„ƒZ�e*dSdKdPœdTdR„ƒZ�e*dUdKdPœdVdR„ƒZ�e*dWdKdPœdXdR„ƒZ�dYdKdPœdZdR„Z�dS )[z-Base classes and utilities for ``Runnable``s.é    )ÚannotationsN)ÚABCÚabstractmethod)ÚAsyncGeneratorÚAsyncIteratorÚ	AwaitableÚ	CoroutineÚIteratorÚMappingÚSequence)ÚFIRST_COMPLETEDÚwait)Úwraps)ÚgroupbyÚtee)Ú
itemgetter)ÚGenericAlias)ÚTYPE_CHECKINGÚAnyÚCallableÚGenericÚOptionalÚProtocolÚTypeVarÚUnionÚcastÚget_type_hintsÚoverload)Ú	BaseModelÚ
ConfigDictÚFieldÚ	RootModel)ÚLiteralÚget_argsÚoverride)Úbeta_decorator)Úwarn_deprecated)Ú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Úpy_anext)Úsafetee)Úcreate_model_v2)ÚAsyncCallbackManagerForChainRunÚCallbackManagerForChainRun©ÚBasePromptTemplate©ÚRunnableWithFallbacks©ÚGraph)ÚExponentialJitterParams)ÚStreamEvent)ÚBaseTool)ÚRunLogÚRunLogPatch)ÚAsyncListener)ÚRunÚOtherc                   @  s�  e Zd ZU dZded< dÎddœddddœdd	„Zed
dœdd„ƒZeddœdd„ƒZeddœdd„ƒZ	dÏdddœdd„Z
dÐdddœdd„Zeddœdd„ƒZdÑdddœdd„ZdÒdddœdd „Zed!dœd"d#„ƒZdd$œd%dd&œd'd(„Zdd$œd%dd&œd)d*„ZdÓdd+dœd,d-„ZdÔdd.dœd/d0„Zd1d2d3œd4d5„Zd6d7d3œd8d9„Zddœd:dd2d;œd<d=„Zd>d?d@œdAdB„ZdCd?dDœdEdF„ZedÕdGddHdIdJœdKdL„ƒZdÖdGddHdIdJœdMdN„Zd×dOdPœdQdRdSdTdUdVœdWdX„ZedØdOdPœdYdZd[dHd\dVœd]d^„ƒZedÙdYdZd_dHd`dVœdad^„ƒZdÚdOdPœdYdZdSdTd`dVœdbd^„ZdÛdOdPœdQdRdSdTdUdVœdcdd„ZedÜdOdPœdYdZd[dTdedVœdfdg„ƒZ edÝdYdZd_dTdhdVœdidg„ƒZ dÞdOdPœdYdZdSdTdhdVœdjdg„Z dßdGddTdkdJœdldm„Z!dàdGddTdndJœdodp„Z"edádqdqdddddddrœdHdd_dSd%d%d%d%d%d%dHdsdtœdudv„ƒZ#edâdqdddddddwœdHdd[dSd%d%d%d%d%d%dHdxdtœdydv„ƒZ#dãdqdqdddddddrœdHddSdSd%d%d%d%d%d%dHdzdtœd{dv„Z#däd|ddddddd}œdHdd~d%d%d%d%d%d%dHdd€œd�d‚„Z$dådƒddTdkdJœd„d…„Z%dæd†ddTdndJœd‡dˆ„Z&dHd‰dDœdŠd‹„Z'dçddHd‰dŒœd�dŽ„Z(dddd�œd�d�d�d‰d‘œd’d“„Z)dddd�œd”d”d”d‰d‘œd•d–„Z*ddd—œd˜d™d‰dšœd›dœ„Z+e,fdqdd�džœdŸdSd d¡d‰d¢œd£d¤„Z-d¥dœd¦d§„Z.e,fdd¨œd©dŸddªd«œd¬d­„Z/dèd®dGddd¯dTdId°œd±d²„Z0déd³dGddd¯dTdId°œd´dµ„Z1dêdOdd¶œd·dQdRdSddTdUd¸œd¹dº„Z2dëdOdd¶œd»dQdRdSddTdUd¸œd¼d½„Z3dìdƒd¾dddTdkd¿œdÀdÁ„Z4díd†dÂdddTdnd¿œdÃdÄ„Z5e6j7dÅdÆ�dîddddÇœdÈdddÉdÊdËœdÌdÍ„ƒZ8dS )ïÚRunnableai  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.

    LCEL and Composition
    ====================

    The LangChain Expression Language (LCEL) is a declarative way to compose
    ``Runnables``into chains.
    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,

    .. code-block:: 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,

    .. code-block:: 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:

        .. code-block:: python

            from langchain_core.globals import set_debug

            set_debug(True)

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

        .. code-block:: python

            from langchain_core.tracers import ConsoleCallbackHandler

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

    For a UI (and much more) checkout `LangSmith <https://docs.smith.langchain.com/>`__.

    úOptional[str]ÚnameN©rh   Ústr©Úsuffixrh   Úreturnc                C  sŽ   |r
|}nTt | dƒr"| jr"| j}n<| j}t |dƒrXd|jv rX|jd durX|jd j}n|j}|rŠ|d  ¡ rz|| ¡  S |d | ¡  S |S )a  Get the name of the ``Runnable``.

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

        Returns:
            The name of the ``Runnable``.
        rh   Ú__pydantic_generic_metadata__ÚoriginNr   Ú_)Úhasattrrh   Ú	__class__rn   Ú__name__ÚisupperÚtitleÚlower)Úselfrl   rh   Zname_Úcls© ry   ú\/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain_core/runnables/base.pyÚget_name  s*    þÿûúzRunnable.get_nameútype[Input]©rm   c                 C  s–   | j  ¡ D ]<}t|dƒr
|j}d|v r
t|d ƒdkr
|d d   S q
| j jD ](}t|ƒ}|rPt|ƒdkrP|d   S qPd|  ¡ › d�}t|ƒ‚dS )z·Input type.

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

        Raises:
            TypeError: If the input type cannot be inferred.
        rn   Úargsé   r   ú	Runnable z` doesn't have an inferable InputType. Override the InputType property to specify the input type.N©	rr   Úmrorq   rn   ÚlenÚ__orig_bases__r#   r{   Ú	TypeError©rw   ÚbaseÚmetadatarx   Z	type_argsÚmsgry   ry   rz   Ú	InputType,  s    
ÿzRunnable.InputTypeútype[Output]c                 C  s–   | j  ¡ D ]<}t|dƒr
|j}d|v r
t|d ƒdkr
|d d   S q
| j jD ](}t|ƒ}|rPt|ƒdkrP|d   S qPd|  ¡ › d�}t|ƒ‚dS )z»Output Type.

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

        Raises:
            TypeError: If the output type cannot be inferred.
        rn   r~   r   é   r€   zc doesn't have an inferable OutputType. Override the OutputType property to specify the output type.Nr�   r†   ry   ry   rz   Ú
OutputTypeL  s    
ÿzRunnable.OutputTypeútype[BaseModel]c                 C  s   |   ¡ S )zJThe type of input this ``Runnable`` accepts specified as a pydantic model.)Úget_input_schema©rw   ry   ry   rz   Úinput_schemah  s    zRunnable.input_schemaúOptional[RunnableConfig]©Úconfigrm   c                 C  s@   | j }t |¡r(t|tƒs(t|tƒr(|S t|  d¡|| j	j
d�S )a&  Get a pydantic model that can be used to validate input to the Runnable.

        ``Runnable``s 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.
        r<   ©ÚrootÚmodule_name)rŠ   ÚinspectÚisclassÚ
isinstancer   Ú
issubclassr   rU   r{   rr   Ú
__module__©rw   r”   Ú	root_typery   ry   rz   r�   m  s    ÿþýözRunnable.get_input_schemaúdict[str, Any]c                 C  s   |   |¡ ¡ S )aL  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:

            .. code-block:: 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())

        .. versionadded:: 0.3.0

        )r�   Úmodel_json_schema©rw   r”   ry   ry   rz   Úget_input_jsonschema•  s    zRunnable.get_input_jsonschemac                 C  s   |   ¡ S )zmOutput schema.

        The type of output this ``Runnable`` produces specified as a pydantic model.
        )Úget_output_schemar�   ry   ry   rz   Úoutput_schema´  s    zRunnable.output_schemac                 C  s@   | j }t |¡r(t|tƒs(t|tƒr(|S t|  d¡|| j	j
d�S )a.  Get a pydantic model that can be used to validate output to the ``Runnable``.

        ``Runnable``s 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   rU   r{   rr   rœ   r�   ry   ry   rz   r£   ¼  s    ÿþýözRunnable.get_output_schemac                 C  s   |   |¡ ¡ S )aO  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:

            .. code-block:: 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())

        .. versionadded:: 0.3.0

        )r£   r    r¡   ry   ry   rz   Úget_output_jsonschemaä  s    zRunnable.get_output_jsonschemaúlist[ConfigurableFieldSpec]c                 C  s   g S )z/List configurable fields for this ``Runnable``.ry   r�   ry   ry   rz   Úconfig_specs  s    zRunnable.config_specs©ÚincludezOptional[Sequence[str]])r©   rm   c                  sp   ˆ pg ‰ | j }|r(tddd„ |D ƒd�nd}i |r>d|dfini ¥‡ fdd„ttƒ ¡ D ƒ¥}t|  d¡|d�S )	a|  The type of config this ``Runnable`` accepts specified as a pydantic model.

        To mark a field as configurable, see the ``configurable_fields``
        and ``configurable_alternatives`` methods.

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

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

        ZConfigurablec              	   S  s*   i | ]"}|j |jt|j|j|jd �f“qS ))ru   Údescription)ÚidÚ
annotationr    Údefaultrh   rª   ©Ú.0Úspecry   ry   rz   Ú
<dictcomp>  s   úÿþz*Runnable.config_schema.<locals>.<dictcomp>©Zfield_definitionsNÚconfigurablec                   s,   i | ]$\}}|d d„ ˆ D ƒv r||df“qS )c                 S  s   g | ]}|d kr|‘qS )r³   ry   ©r¯   Úiry   ry   rz   Ú
<listcomp>0  ó    z5Runnable.config_schema.<locals>.<dictcomp>.<listcomp>Nry   )r¯   Ú
field_nameZ
field_typer¨   ry   rz   r±   -  s   þZConfig)r§   rU   r   r,   Úitemsr{   )rw   r©   r§   r³   Z
all_fieldsry   r¨   rz   Úconfig_schema  s&    ôùþòÿ

þþzRunnable.config_schemac                C  s   | j |d� ¡ S )a  Get a JSON schema that represents the config of the ``Runnable``.

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

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

        .. versionadded:: 0.3.0

        r¨   )rº   r    )rw   r©   ry   ry   rz   Úget_config_jsonschema5  s    zRunnable.get_config_jsonschemar]   c              	   C  sÂ   ddl m} |ƒ }z| |  |¡¡}W n& tyL   | t|  d¡ƒ¡}Y n0 |j| |rb| d¡ndd�}z| |  |¡¡}W n& ty¤   | t|  d¡ƒ¡}Y n0 | 	||¡ | 	||¡ |S )z3Return a graph representation of this ``Runnable``.r   r\   r<   rˆ   N)rˆ   r=   )
Úlangchain_core.runnables.graphr]   Úadd_noder�   r…   rU   r{   Úgetr£   Úadd_edge)rw   r”   r]   ÚgraphÚ
input_nodeZrunnable_nodeÚoutput_nodery   ry   rz   Ú	get_graphE  s     ÿzRunnable.get_graphzlist[BasePromptTemplate]c                   s,   ddl m‰  ‡ fdd„| j|d�j ¡ D ƒS )z3Return a list of prompts used by this ``Runnable``.r   rX   c                   s   g | ]}t |jˆ ƒr|j‘qS ry   )rš   Údata)r¯   ÚnoderX   ry   rz   r¶   a  s   þz(Runnable.get_prompts.<locals>.<listcomp>©r”   )Úlangchain_core.prompts.baserY   rÃ   ÚnodesÚvaluesr¡   ry   rX   rz   Úget_promptsZ  s    
þzRunnable.get_promptsúÝUnion[Runnable[Any, Other], Callable[[Iterator[Any]], Iterator[Other]], Callable[[AsyncIterator[Any]], AsyncIterator[Other]], Callable[[Any], Other], Mapping[str, Union[Runnable[Any, Other], Callable[[Any], Other], Any]]]ú"RunnableSerializable[Input, Other]©Úotherrm   c                 C  s   t | t|ƒƒS )a	  Runnable "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©rw   rÎ   ry   ry   rz   Ú__or__g  s    zRunnable.__or__úÝUnion[Runnable[Other, Any], Callable[[Iterator[Other]], Iterator[Any]], Callable[[AsyncIterator[Other]], AsyncIterator[Any]], Callable[[Other], Any], Mapping[str, Union[Runnable[Other, Any], Callable[[Other], Any], Any]]]ú#RunnableSerializable[Other, Output]c                 C  s   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Ò   ry   ry   rz   Ú__ror__~  s    zRunnable.__ror__z3Union[Runnable[Any, Other], Callable[[Any], Other]])Úothersrh   rm   c                G  s   t | g|¢R d|iŽS )aû  Pipe runnables.

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

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

        Example:

            .. code-block:: python

                from langchain_core.runnables import RunnableLambda


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


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


                runnable_1 = RunnableLambda(add_one)
                runnable_2 = RunnableLambda(mul_two)
                sequence = runnable_1.pipe(runnable_2)
                # Or equivalently:
                # sequence = runnable_1 | runnable_2
                # sequence = RunnableSequence(first=runnable_1, last=runnable_2)
                sequence.invoke(1)
                await sequence.ainvoke(1)
                # -> 4

                sequence.batch([1, 2, 3])
                await sequence.abatch([1, 2, 3])
                # -> [4, 6, 8]

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

        Returns:
            A new ``Runnable``.
        rh   )rÐ   )rw   rh   r×   ry   ry   rz   Úpipe•  s    0zRunnable.pipezUnion[str, list[str]]zRunnableSerializable[Any, Any])Úkeysrm   c                 C  s   ddl m} | ||ƒB S )a`  Pick keys from the output dict of this ``Runnable``.

        Pick single key:

            .. code-block:: 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]

        Pick list of keys:

            .. code-block:: 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Ú   )rw   rÙ   rÚ   ry   ry   rz   ÚpickÇ  s    ;zRunnable.pickzšUnion[Runnable[dict[str, Any], Any], Callable[[dict[str, Any]], Any], Mapping[str, Union[Runnable[dict[str, Any], Any], Callable[[dict[str, Any]], Any]]]]©Úkwargsrm   c                 K  s(   ddl m} | |ttttf  |ƒƒB S )aä  Assigns new fields to the dict output of this ``Runnable``.

        .. code-block:: python

            from langchain_community.llms.fake import FakeStreamingListLLM
            from langchain_core.output_parsers import StrOutputParser
            from langchain_core.prompts import SystemMessagePromptTemplate
            from langchain_core.runnables import Runnable
            from operator import itemgetter

            prompt = (
                SystemMessagePromptTemplate.from_template("You are a nice assistant.")
                + "{question}"
            )
            llm = FakeStreamingListLLM(responses=["foo-lish"])

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

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

            print(chain_with_assign.input_schema.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Údictrj   r   )rw   rÞ   rß   ry   ry   rz   Úassign  s    0zRunnable.assignr<   r   r=   ©Úinputr”   rÞ   rm   c                 K  s   dS ©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 the ``RunnableConfig``
                for more details. Defaults to None.

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

        Nry   ©rw   rä   r”   rÞ   ry   ry   rz   Úinvoke<  s    zRunnable.invokec                 Ë  s   t || j||fi |¤ŽI dH S rå   )r6   rç   ræ   ry   ry   rz   ÚainvokeR  s    zRunnable.ainvokeF©Úreturn_exceptionsúlist[Input]ú5Optional[Union[RunnableConfig, list[RunnableConfig]]]ÚboolúOptional[Any]úlist[Output]©Úinputsr”   rê   rÞ   rm   c             	     sž   |sg S t |t|ƒƒ}ddddœ‡ ‡‡fdd„}t|ƒdkrVtd||d	 |d	 ƒgƒS t|d	 ƒ�(}tdt| |||¡ƒƒW  d
  ƒ S 1 s�0    Y  d
S )a&  Default implementation runs invoke in parallel using a thread pool executor.

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

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

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

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

        r<   r,   úUnion[Output, Exception])Úinput_r”   rm   c              
     s^   ˆrFzˆj | |fi ˆ ¤ŽW S  tyB } z|W  Y d }~S d }~0 0 nˆj | |fi ˆ ¤ŽS d S ©N©rç   Ú	Exception)ró   r”   Úe©rÞ   rê   rw   ry   rz   rç   ‹  s    zRunnable.batch.<locals>.invokerŒ   rï   r   N)r2   rƒ   r   r3   ÚlistÚmap)rw   rñ   r”   rê   rÞ   Úconfigsrç   Úexecutorry   rø   rz   Úbatchh  s    
zRunnable.batchúSequence[Input]ú9Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]úLiteral[False]úIterator[tuple[int, Output]]c                K  s   d S rô   ry   ©rw   rñ   r”   rê   rÞ   ry   ry   rz   Úbatch_as_completed›  s    zRunnable.batch_as_completedúLiteral[True]ú.Iterator[tuple[int, Union[Output, Exception]]]c                K  s   d S rô   ry   r  ry   ry   rz   r  ¥  s    c          	   
   +  sü   |sdS t |t|ƒƒ}dddddœ‡‡‡fdd„‰t|ƒd	krXˆd
|d
 |d
 ƒV  dS t|d
 ƒ�„‰ ‡ ‡fdd„tt||ƒƒD ƒ}z@|r°t|td�\}}|r†| ¡  ¡ V  qšq†W |D ]}| 	¡  q¶n|D ]}| 	¡  qÊ0 W d  ƒ n1 sî0    Y  dS )aV  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 the ``RunnableConfig``
                for more details. Defaults to None.
            return_exceptions: Whether to return exceptions instead of raising them.
                Defaults to False.
            **kwargs: Additional keyword arguments to pass to the ``Runnable``.

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

        NÚintr<   r,   ú$tuple[int, Union[Output, Exception]]©rµ   ró   r”   rm   c              
     sd   ˆrHzˆj ||fi ˆ ¤Ž}W q\ tyD } z|}W Y d }~q\d }~0 0 nˆj ||fi ˆ ¤Ž}| |fS rô   rõ   ©rµ   ró   r”   Úoutr÷   rø   ry   rz   rç   Ï  s    ÿÿ
z+Runnable.batch_as_completed.<locals>.invokerŒ   r   c                   s$   h | ]\}\}}ˆ   ˆ|||¡’qS ry   ©Úsubmit©r¯   rµ   ró   r”   )rü   rç   ry   rz   Ú	<setcomp>ã  s   
ÿz.Runnable.batch_as_completed.<locals>.<setcomp>©Zreturn_when)
r2   rƒ   r3   Ú	enumerateÚzipr   r   ÚpopÚresultÚcancel)	rw   rñ   r”   rê   rÞ   rû   ÚfuturesÚdoneÚfuturery   )rü   rç   rÞ   rê   rw   rz   r  ¯  s(    þÿc                ‹  s\   |sg S t |t|ƒƒ}ddddœ‡ ‡‡fdd„}t|||ƒ}t|d  d¡g|¢R Ž I d	H S )
a+  Default implementation runs ``ainvoke`` in parallel using ``asyncio.gather``.

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

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

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

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

        r<   r,   rò   )Úvaluer”   rm   c              
   “  sj   ˆrLzˆj | |fi ˆ ¤ŽI d H W S  tyH } z|W  Y d }~S d }~0 0 nˆj | |fi ˆ ¤ŽI d H S d S rô   ©rè   rö   )r  r”   r÷   rø   ry   rz   rè     s    z Runnable.abatch.<locals>.ainvoker   Úmax_concurrencyN)r2   rƒ   rú   rB   r¾   )rw   rñ   r”   rê   rÞ   rû   rè   Úcorosry   rø   rz   Úabatchñ  s    zRunnable.abatchú!AsyncIterator[tuple[int, Output]]c                K  s   d S rô   ry   r  ry   ry   rz   Úabatch_as_completed"  s    zRunnable.abatch_as_completedú3AsyncIterator[tuple[int, Union[Output, Exception]]]c                K  s   d S rô   ry   r  ry   ry   rz   r  ,  s    c          	       s˜   |sdS t |t|ƒƒ}|r(|d  d¡nd}|r:t |¡nd‰dddddœ‡‡‡fd	d
„‰ ‡ ‡fdd„tt||ƒƒD ƒ}t |¡D ]}|I dH V  q‚dS )aV  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 the ``RunnableConfig``
                for more details. Defaults to None.
            return_exceptions: Whether to return exceptions instead of raising them.
                Defaults to False.
            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  r  r<   r,   r  r  c              
   “  sp   ˆrNzˆj ||fi ˆ ¤ŽI d H }W qh tyJ } z|}W Y d }~qhd }~0 0 nˆj ||fi ˆ ¤ŽI d H }| |fS rô   r  r	  rø   ry   rz   Úainvoke_taskY  s    ÿÿz2Runnable.abatch_as_completed.<locals>.ainvoke_taskc                   s6   g | ].\}\}}ˆr&t ˆˆ |||ƒƒn
ˆ |||ƒ‘qS ry   )rA   r  )r   Ú	semaphorery   rz   r¶   g  s   
þÿz0Runnable.abatch_as_completed.<locals>.<listcomp>)r2   rƒ   r¾   ÚasyncioÚ	Semaphorer  r  Zas_completed)	rw   rñ   r”   rê   rÞ   rû   r  r  Úcorory   )r   rÞ   rê   rw   r!  rz   r  6  s    üúIterator[Output]c                 k  s   | j ||fi |¤ŽV  dS )a³  Default implementation of ``stream``, which calls ``invoke``.

        Subclasses should override this method if they support streaming output.

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

        Yields:
            The output of the ``Runnable``.

        N)rç   ræ   ry   ry   rz   Ústreamq  s    zRunnable.streamúAsyncIterator[Output]c                 K s    | j ||fi |¤ŽI dH V  dS )aµ  Default implementation of ``astream``, which calls ``ainvoke``.

        Subclasses should override this method if they support streaming output.

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

        Yields:
            The output of the ``Runnable``.

        N)rè   ræ   ry   ry   rz   Úastream†  s    zRunnable.astreamT)ÚdiffÚwith_streamed_output_listÚinclude_namesÚinclude_typesÚinclude_tagsÚexclude_namesÚexclude_typesÚexclude_tagszAsyncIterator[RunLogPatch])rä   r”   r)  r*  r+  r,  r-  r.  r/  r0  rÞ   rm   c                K  s   d S rô   ry   ©rw   rä   r”   r)  r*  r+  r,  r-  r.  r/  r0  rÞ   ry   ry   rz   Úastream_log›  s    zRunnable.astream_log)r*  r+  r,  r-  r.  r/  r0  zAsyncIterator[RunLog]c                K  s   d S rô   ry   r1  ry   ry   rz   r2  ¬  s    z8Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]c             
   K s\   t dddd� td|||||	|
dd�}t| ||f|||dœ|¤Ž2 z3 d	H W }|V  qB6 d	S )
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.

        ú0.3.85z/astream_log is deprecated. Use astream instead.T©ZsinceÚmessageÚpendingFÚoriginal)Ú
auto_closer+  r,  r-  r.  r/  r0  Z_schema_format)r)  r&  r*  N)r&   rM   rN   )rw   rä   r”   r)  r*  r+  r,  r-  r.  r/  r0  rÞ   r&  Úitemry   ry   rz   r2  ½  s6    *ýøýúù	Úv2)Úversionr+  r,  r-  r.  r/  r0  zLiteral['v1', 'v2']úAsyncIterator[StreamEvent])rä   r”   r;  r+  r,  r-  r.  r/  r0  rÞ   rm   c             
   K sÌ   |dkr,t | |f|||||||	dœ|
¤Ž}nF|dkrftdddd� t| |f|||||||	dœ|
¤Ž}nd}t|ƒ‚t|ƒ4 I d	H š0 |2 z3 d	H W }|V  qˆ6 W d	  ƒI d	H  qÈ1 I d	H s¾0    Y  d	S )
a/8  Generate a stream of events.

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

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

        - ``event``: **str** - Event names are of the format:
          ``on_[runnable_type]_(start|stream|end)``.
        - ``name``: **str** - The name of the ``Runnable`` that generated the event.
        - ``run_id``: **str** - randomly generated ID associated with the given
          execution 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``: **list[str]** - 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``: **Optional[list[str]]** - The tags of the ``Runnable`` that generated
          the event.
        - ``metadata``: **Optional[dict[str, Any]]** - The metadata of the ``Runnable`` that
          generated the event.
        - ``data``: **dict[str, Any]**

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

        .. code-block:: 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``:

        .. code-block:: python

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

        ``prompt``:

        .. code-block:: python

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


        Example:

        .. code-block:: 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": [],
                },
            ]


        Example: Dispatch Custom Event

        .. code-block:: python

            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 ``Runnables`` with matching names.
            include_types: Only include events from ``Runnables`` with matching types.
            include_tags: Only include events from ``Runnables`` with matching tags.
            exclude_names: Exclude events from ``Runnables`` with matching names.
            exclude_types: Exclude events from ``Runnables`` with matching types.
            exclude_tags: Exclude events from ``Runnables`` 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 ``StreamEvents``.

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

        r:  )r”   r+  r,  r-  r.  r/  r0  Zv1r3  zOastream_events version='v1' is deprecated. Use version='v2' or astream instead.Tr4  zAOnly versions "v1" and "v2" of the schema is currently supported.N)rL   r&   rK   ÚNotImplementedErrorrQ   )rw   rä   r”   r;  r+  r,  r-  r.  r/  r0  rÞ   Zevent_streamr‰   Úeventry   ry   rz   Úastream_events  sR     hþ÷
öú
þ÷
özRunnable.astream_eventsúIterator[Input]c              	   k  sb   d}|D ]6}|s|}d}qz|| }W q t y<   |}Y q0 q|r^| j||fi |¤ŽE dH  dS )a&  Transform inputs to outputs.

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

        Subclasses should 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``. Defaults to None.
            kwargs: Additional keyword arguments to pass to the ``Runnable``.

        Yields:
            The output of the ``Runnable``.

        FTN)r…   r&  )rw   rä   r”   rÞ   Úgot_first_valÚichunkÚfinalry   ry   rz   Ú	transform  s    zRunnable.transformúAsyncIterator[Input]c              	   K s|   d}|2 z>3 dH W }|s"|}d}qz|| }W q t yD   |}Y q0 q6 |rx| j||fi |¤Ž2 z3 dH W }|V  qb6 dS )a-  Transform inputs to outputs.

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

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

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

        Yields:
            The output of the ``Runnable``.

        FNT)r…   r(  )rw   rä   r”   rÞ   rA  rB  rC  Úoutputry   ry   rz   Ú
atransformE  s     zRunnable.atransformúRunnable[Input, Output]c                 K  s   t | |i d�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:

        .. code-block:: python

            from langchain_ollama import ChatOllama
            from langchain_core.output_parsers import StrOutputParser

            llm = ChatOllama(model="llama2")

            # Without bind.
            chain = llm | StrOutputParser()

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

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

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

        )ÚboundrÞ   r”   ©ÚRunnableBinding©rw   rÞ   ry   ry   rz   Úbinds  s    "zRunnable.bind©r”   rÞ   rm   c                 K  s    t | tdi |pi ¥|¥ƒi d�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,   )rI  r”   rÞ   )rK  r   ©rw   r”   rÞ   ry   ry   rz   Úwith_config—  s    þúzRunnable.with_config©Úon_startÚon_endÚon_errorúMOptional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]]©rR  rS  rT  rm   c                  s   t | ‡ ‡‡fdd„gd�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. Defaults to None.
            on_end: Called after the ``Runnable`` finishes running, with the ``Run``
                object. Defaults to None.
            on_error: Called if the ``Runnable`` throws an error, with the ``Run``
                object. Defaults to None.

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

        Example:

        .. code-block:: python

            from langchain_core.runnables import RunnableLambda
            from langchain_core.tracers.schemas import Run

            import time


            def test_runnable(time_to_sleep: int):
                time.sleep(time_to_sleep)


            def fn_start(run_obj: Run):
                print("start_time:", run_obj.start_time)


            def fn_end(run_obj: Run):
                print("end_time:", run_obj.end_time)


            chain = RunnableLambda(test_runnable).with_listeners(
                on_start=fn_start, on_end=fn_end
            )
            chain.invoke(2)

        c                   s   dt | ˆˆ ˆd�giS ©NÚ	callbacks)r”   rR  rS  rT  ©rP   rÆ   ©rS  rT  rR  ry   rz   Ú<lambda>í  s    üÿÿz)Runnable.with_listeners.<locals>.<lambda>©rI  Úconfig_factoriesrJ  ©rw   rR  rS  rT  ry   rZ  rz   Úwith_listeners°  s
    :ÿþzRunnable.with_listenersúOptional[AsyncListener]c                  s   t | ‡ ‡‡fdd„gd�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. Defaults to None.
            on_end: Called asynchronously after the ``Runnable`` finishes running,
                with the ``Run`` object. Defaults to None.
            on_error: Called asynchronously if the ``Runnable`` throws an error,
                with the ``Run`` object. Defaults to None.

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

        Example:

        .. code-block:: python

            from langchain_core.runnables import RunnableLambda, Runnable
            from datetime import datetime, timezone
            import time
            import asyncio

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

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

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

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

            runnable = RunnableLambda(test_runnable).with_alisteners(
                on_start=fn_start,
                on_end=fn_end
            )
            async def concurrent_runs():
                await asyncio.gather(runnable.ainvoke(2), runnable.ainvoke(3))

            asyncio.run(concurrent_runs())
            Result:
            on start callback starts at 2025-03-01T07:05:22.875378+00:00
            on start callback starts at 2025-03-01T07:05:22.875495+00:00
            on start callback ends at 2025-03-01T07:05:25.878862+00:00
            on start callback ends at 2025-03-01T07:05:25.878947+00:00
            Runnable[2s]: starts at 2025-03-01T07:05:25.879392+00:00
            Runnable[3s]: starts at 2025-03-01T07:05:25.879804+00:00
            Runnable[2s]: ends at 2025-03-01T07:05:27.881998+00:00
            on end callback starts at 2025-03-01T07:05:27.882360+00:00
            Runnable[3s]: ends at 2025-03-01T07:05:28.881737+00:00
            on end callback starts at 2025-03-01T07:05:28.882428+00:00
            on end callback ends at 2025-03-01T07:05:29.883893+00:00
            on end callback ends at 2025-03-01T07:05:30.884831+00:00

        c                   s   dt | ˆˆ ˆd�giS rW  )rO   rÆ   rZ  ry   rz   r[  I  s    üÿÿz*Runnable.with_alisteners.<locals>.<lambda>r\  rJ  r^  ry   rZ  rz   Úwith_alistenersú  s
    LÿþzRunnable.with_alisteners)Ú
input_typeÚoutput_typezOptional[type[Input]]zOptional[type[Output]]©rb  rc  rm   c                C  s   t | ||i d�S )aU  Bind input and output types to a ``Runnable``, returning a new ``Runnable``.

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

        Returns:
            A new Runnable with the types bound.
        )rI  Úcustom_input_typeÚcustom_output_typerÞ   rJ  ©rw   rb  rc  ry   ry   rz   Ú
with_typesV  s    üzRunnable.with_typesé   )Úretry_if_exception_typeÚwait_exponential_jitterÚexponential_jitter_paramsÚstop_after_attemptztuple[type[BaseException], ...]z!Optional[ExponentialJitterParams]r  )rj  rk  rl  rm  rm   c             	   C  s"   ddl m} || i i ||||d�S )a   Create a new Runnable that retries the original Runnable on exceptions.

        Args:
            retry_if_exception_type: A tuple of exception types to retry on.
                Defaults to (Exception,).
            wait_exponential_jitter: Whether to add jitter to the wait
                time between retries. Defaults to True.
            stop_after_attempt: The maximum number of attempts to make before
                giving up. Defaults to 3.
            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:

        .. code-block:: 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)rI  rÞ   r”   Zretry_exception_typesrk  Zmax_attempt_numberrl  )Úlangchain_core.runnables.retryrn  )rw   rj  rk  rl  rm  rn  ry   ry   rz   Ú
with_retryl  s    7ùzRunnable.with_retryz#Runnable[list[Input], list[Output]]c                 C  s
   t | d�S )a9  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:

            .. code-block:: 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]

        ©rI  )ÚRunnableEachr�   ry   ry   rz   rú   ¯  s    zRunnable.map)Úexceptions_to_handleÚexception_keyz!Sequence[Runnable[Input, Output]]z%RunnableWithFallbacksT[Input, Output])Ú	fallbacksrs  rt  rm   c                C  s   ddl m} || |||d�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.
                Defaults to ``(Exception,)``.
            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. Defaults to None.

        Returns:
            A new ``Runnable`` that will try the original ``Runnable``, and then each
            fallback in order, upon failures.

        Example:

            .. code-block:: 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   rZ   )Úrunnableru  rs  rt  )Ú"langchain_core.runnables.fallbacksr[   )rw   ru  rs  rt  r[   ry   ry   rz   Úwith_fallbacksÈ  s    BüzRunnable.with_fallbackszžUnion[Callable[[Input], Output], Callable[[Input, CallbackManagerForChainRun], Output], Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]]zOptional[dict[str, Any]])Úfuncró   r”   Úrun_typeÚ
serializedrÞ   rm   c              
   K  sÚ   t |ƒ}t|ƒ}|j|||| d¡p*|  ¡ | dd¡d�}z\t|| ¡ d�}	t|	ƒ�0}
t	d|
j
t||||fi |¤Žƒ}W d  ƒ n1 sŠ0    Y  W n0 tyÆ } z| |¡ ‚ W Y d}~nd}~0 0 | |¡ |S dS )zÂCall 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©rz  rh   r}  ©rX  r=   )r/   r1   Úon_chain_startr¾   r{   r  r5   Ú	get_childr7   r   Úrunr.   ÚBaseExceptionÚon_chain_errorÚon_chain_end)rw   ry  ró   r”   rz  r{  rÞ   Úcallback_managerÚrun_managerÚchild_configÚcontextrF  r÷   ry   ry   rz   Ú_call_with_config  s:    
û
ûúþ&

zRunnable._call_with_configzÉUnion[Callable[[Input], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]c              
   Ë  sò   t |ƒ}t|ƒ}|j|||| d¡p*|  ¡ | dd¡d�I dH }zbt|| ¡ d�}	t|	ƒ�6}
t	||||fi |¤Ž}t
||
ƒI dH }W d  ƒ n1 s–0    Y  W n6 tyØ } z| |¡I dH  ‚ W Y d}~nd}~0 0 | |¡I dH  |S dS )zÈAsync 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/   r0   r€  r¾   r{   r  r5   r�  r7   r-   r@   rƒ  r„  r…  )rw   ry  ró   r”   rz  r{  rÞ   r†  r‡  rˆ  r‰  r$  rF  r÷   ry   ry   rz   Ú_acall_with_configJ  s.    
û
ÿÿ2zRunnable._acall_with_config)rê   rz  a
  Union[Callable[[list[Input]], list[Union[Exception, Output]]], Callable[[list[Input], list[CallbackManagerForChainRun]], list[Union[Exception, Output]]], Callable[[list[Input], list[CallbackManagerForChainRun], list[RunnableConfig]], list[Union[Exception, Output]]]])ry  rñ   r”   rê   rz  rÞ   rm   c             
     sN  |sg S t |t|ƒƒ}dd„ |D ƒ}‡‡fdd„t|||ƒD ƒ}	zDt|ƒrbdd„ t||	ƒD ƒ|d< t|ƒrr|	|d< ||fi |¤Ž}
W nb tyæ ‰  zJ|	D ]}| ˆ ¡ q˜|rÐtd‡ fdd„|D ƒƒW  Y d	‰ Š S ‚ W Y d	‰ Š nld	‰ Š 0 0 d	}t|	|
ƒD ]4\}}t|t	ƒ�r |�p|}| |¡ qö| 
|¡ qö|�s<|d	u �rFtd|
ƒS |‚d	S )
zèTransform 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                 S  s   g | ]}t |ƒ‘qS ry   )r1   ©r¯   Úcry   ry   rz   r¶   –  r·   z/Runnable._batch_with_config.<locals>.<listcomp>c                   s<   g | ]4\}}}|j d |ˆ | d¡p(ˆ ¡ | dd ¡d�‘qS ©Nr|  r}  r~  ©r€  r¾   r{   r  ©r¯   r†  ró   r”   ©rz  rw   ry   rz   r¶   —  s   ù
ûc                 S  s    g | ]\}}t || ¡ d �‘qS ©r  ©r5   r�  ©r¯   r�  Úrmry   ry   rz   r¶   ¥  s   ÿr”   r‡  rï   c                   s   g | ]}ˆ ‘qS ry   ry   ©r¯   rp   ©r÷   ry   rz   r¶   °  r·   N)r2   rƒ   r  r>   r?   rƒ  r„  r   rš   rö   r…  )rw   ry  rñ   r”   rê   rz  rÞ   rû   Úcallback_managersÚrun_managersrF  r‡  Úfirst_exceptionr
  ry   ©r÷   rz  rw   rz   Ú_batch_with_configx  s@    ÿøþ
$

zRunnable._batch_with_configa5  Union[Callable[[list[Input]], Awaitable[list[Union[Exception, Output]]]], Callable[[list[Input], list[AsyncCallbackManagerForChainRun]], Awaitable[list[Union[Exception, Output]]]], Callable[[list[Input], list[AsyncCallbackManagerForChainRun], list[RunnableConfig]], Awaitable[list[Union[Exception, Output]]]]]c             
   ‹  sŽ  |sg S t |t|ƒƒ}dd„ |D ƒ}tj‡‡fdd„t|||ƒD ƒŽ I dH }	zJt|ƒrndd„ t||	ƒD ƒ|d< t|ƒr~|	|d< ||fi |¤ŽI dH }
W nn t�y ‰  zTtj‡ fd	d„|	D ƒŽ I dH  |rîtd
‡ fdd„|D ƒƒW  Y d‰ Š S ‚ W Y d‰ Š nŽd‰ Š 0 0 d}g }t|	|
ƒD ]B\}}t	|t
ƒ�rH|�p4|}| | |¡¡ n| | |¡¡ �qtj|Ž I dH  |�s||du �r†td
|
ƒS |‚dS )zñTransform 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                 S  s   g | ]}t |ƒ‘qS ry   )r0   rŒ  ry   ry   rz   r¶   â  r·   z0Runnable._abatch_with_config.<locals>.<listcomp>c              
   3  s>   | ]6\}}}|j d |ˆ | d¡p&ˆ ¡ | dd ¡d�V  qd S rŽ  r�  r�  r‘  ry   rz   Ú	<genexpr>ä  s   ù
ûz/Runnable._abatch_with_config.<locals>.<genexpr>Nc                 S  s    g | ]\}}t || ¡ d �‘qS r’  r“  r”  ry   ry   rz   r¶   ó  s   ÿr”   r‡  c                 3  s   | ]}|  ˆ ¡V  qd S rô   ©r„  )r¯   r‡  r—  ry   rz   r�  ü  r·   rï   c                   s   g | ]}ˆ ‘qS ry   ry   r–  r—  ry   rz   r¶   ÿ  r·   )r2   rƒ   r"  Úgatherr  r>   r?   rƒ  r   rš   rö   Úappendr„  r…  )rw   ry  rñ   r”   rê   rz  rÞ   rû   r˜  r™  rF  rš  r  r‡  r
  ry   r›  rz   Ú_abatch_with_config¾  sJ     ÿøÿ
þ
ÿ
$

zRunnable._abatch_with_configzÚUnion[Callable[[Iterator[Input]], Iterator[Output]], Callable[[Iterator[Input], CallbackManagerForChainRun], Iterator[Output]], Callable[[Iterator[Input], CallbackManagerForChainRun, RunnableConfig], Iterator[Output]]])rñ   Útransformerr”   rz  rÞ   rm   c              
   k  s"  |  dd¡}t|dƒ\}}t|dƒ}	d}
d}d}t|ƒ}t|ƒ}|jdddi|| d¡p^|  ¡ |  d	d¡|d
�}�zft|| 	¡ d�}t
|ƒr”||d< t|ƒr¤||d< t|ƒ��}|j||fi |¤Ž}tdd„ |jD ƒdƒ }rì| |j|¡}z^| t|¡}|V  |�rB|du �r|}n*z|| }W n t�y>   |}d}Y n0 qî|}qîW n ttf�yb   Y n0 |D ]L}|
�r®|	du �r‚|}	n*z|	| }	W n t�yª   |}	d}
Y n0 n|}	�qhW d  ƒ n1 �sÌ0    Y  W n6 t�y } z|j||	d� ‚ W Y d}~nd}~0 0 |j||	d� dS )a  Transform 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_inputsFr   NTrä   Ú r|  r}  ©rz  rh   r}  r£  r  r”   r‡  c                 s  s"   | ]}t |tƒrtd |ƒV  qdS ©rJ   N©rš   rJ   r   ©r¯   Úhry   ry   rz   r�  H	  s   
ýz9Runnable._transform_stream_with_config.<locals>.<genexpr>©rñ   )r  r   Únextr/   r1   r€  r¾   r{   r5   r�  r>   r?   r7   r‚  ÚhandlersZtap_output_iterr}  r…   ÚStopIterationÚGeneratorExitrƒ  r„  r…  )rw   rñ   r¢  r”   rz  rÞ   r£  Úinput_for_tracingÚinput_for_transformÚfinal_inputÚfinal_input_supportedÚfinal_outputÚfinal_output_supportedr†  r‡  rˆ  r‰  ÚiteratorÚstream_handlerÚchunkrB  r÷   ry   ry   rz   Ú_transform_stream_with_config	  sz    

úþù
ÿ


,z&Runnable._transform_stream_with_configa  Union[Callable[[AsyncIterator[Input]], AsyncIterator[Output]], Callable[[AsyncIterator[Input], AsyncCallbackManagerForChainRun], AsyncIterator[Output]], Callable[[AsyncIterator[Input], AsyncCallbackManagerForChainRun, RunnableConfig], AsyncIterator[Output]]]c              
   K s¢  |  dd¡}t|dƒ\}}t|dƒI dH }	d}
d}d}t|ƒ}t|ƒ}|jdddi|| d¡pd|  ¡ |  d	d¡|d
�I dH }�zø�z|t|| 	¡ d�}t
|ƒr¤||d< t|ƒr´||d< t|ƒ��,}|j||fi |¤Ž}tdd„ |jD ƒdƒ }rþ| |j|¡}n|}zhtt|ƒ|ƒI dH }|V  |�r`|du �r4|}n*z|| }W n t�y\   |}d}Y n0 n|}�qW n t�y~   Y n0 |2 zT3 dH W }|
�rÒ|	du �r¦|}	n*z|	| }	W n t�yÎ   |}	d}
Y n0 n|}	�q„6 W d  ƒ n1 �sò0    Y  W n< t�y: } z"|j||	d�I dH  ‚ W Y d}~nd}~0 0 |j||	d�I dH  W |du�ržt|dƒ�rž| ¡ I dH  n&|du�rœt|dƒ�rœ| ¡ I dH  0 dS )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£  Fr   NTrä   r¤  r|  r}  r¥  r  r”   r‡  c                 s  s"   | ]}t |tƒrtd |ƒV  qdS r¦  r§  r¨  ry   ry   rz   r�  ´	  s   
ýz:Runnable._atransform_stream_with_config.<locals>.<genexpr>rª  Úaclose)r  rR   rS   r/   r0   r€  r¾   r{   r5   r�  r>   r?   r7   r‚  r«  r¬  Ztap_output_aiterr}  r@   r…   ÚStopAsyncIterationrƒ  r„  r…  rq   r¹  )rw   rñ   r¢  r”   rz  rÞ   r£  r¯  r°  r±  r²  r³  r´  r†  r‡  rˆ  r‰  Z	iterator_r¶  rµ  r·  rB  r÷   ry   ry   rz   Ú_atransform_stream_with_configw	  s„    
úþù
ÿ

.ÿz'Runnable._atransform_stream_with_configz1This API is in beta and may change in the future.©r5  )rh   rª   Ú	arg_typeszOptional[type[BaseModel]]zOptional[dict[str, type]]r`   )Úargs_schemarh   rª   r½  rm   c                C  s   ddl m} || ||||d�S )a–  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. Defaults to None.
            name: The name of the tool. Defaults to None.
            description: The description of the tool. Defaults to None.
            arg_types: A dictionary of argument names to types. Defaults to None.

        Returns:
            A ``BaseTool`` instance.

        Typed dict input:

        .. code-block:: 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]})

        ``dict`` input, specifying schema via ``args_schema``:

        .. code-block:: 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]})

        ``dict`` input, specifying schema via ``arg_types``:

        .. code-block:: 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]})

        String input:

        .. code-block:: 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")

        .. versionadded:: 0.2.14

        r   )Úconvert_runnable_to_tool)r¾  rh   rª   r½  )Úlangchain_core.toolsr¿  )rw   r¾  rh   rª   r½  r¿  ry   ry   rz   Úas_toolè	  s    lûzRunnable.as_tool)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)NN)NN)N)N)N)N)N)9rs   rœ   Ú__qualname__Ú__doc__Ú__annotations__r{   Ú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  r&  r(  r2  r?  rD  rG  rM  rP  r_  ra  rh  rö   rp  rú   rx  rŠ  r‹  rœ  r¡  r¸  r»  r%   ÚbetarÁ  ry   ry   ry   rz   rf   {   sf  
  ÿÿ( þ) ÿ	 þ) ÿÿ.ÿ ÿý2?6 ý ý ýû3 ýû	 ý ýûE ýû1 ýû	 ý ýû> ý ý ýô* ýô* ýô(K ýõ&   ý0 ý.& þõMû_üúCûX  ö?  ó< òïX îëa ð{ íq
 þúrf   c                      sp   e Zd ZU dZdZded< edd�Zeddœ‡ fd	d
„ƒZ	dddœdd„Z
dddœddddddœdd„Z‡  ZS )ÚRunnableSerializablez(Runnable that can be serialized to JSON.Nrg   rh   ry   )Zprotected_namespacesz6Union[SerializedConstructor, SerializedNotImplemented]r}   c                   sD   t ƒ  ¡ }t t¡� |  ¡ |d< W d  ƒ n1 s60    Y  |S )zƒSerialize the ``Runnable`` to JSON.

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

        rh   N)ÚsuperÚto_jsonÚ
contextlibÚsuppressrö   r{   )rw   Zdumped©rr   ry   rz   rÉ  j
  s    
*zRunnableSerializable.to_jsonr9   z#RunnableSerializable[Input, Output]rÝ   c                 K  sV   ddl m} t| ƒj}|D ].}||vrd|› d| › d| ¡ › �}t|ƒ‚q|| |d�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.

        .. code-block:: 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)rw   rÞ   rÍ  rÑ  Úkeyr‰   ry   ry   rz   Úconfigurable_fieldsw
  s    *
ÿÿ
z(RunnableSerializable.configurable_fieldsr­   F)Údefault_keyÚprefix_keysr:   rj   rí   zEUnion[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]])ÚwhichrÕ  rÖ  rÞ   rm   c                K  s   ddl m} ||| |||d�S )aØ  Configure alternatives for ``Runnables`` 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.
                Defaults to ``'default'``.
            prefix_keys: Whether to prefix the keys with the ``ConfigurableField`` id.
                Defaults to False.
            **kwargs: A dictionary of keys to ``Runnable`` instances or callables that
                return ``Runnable`` instances.

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

        .. code-block:: python

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

            model = ChatAnthropic(
                model_name="claude-3-7-sonnet-20250219"
            ).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)r×  r­   ZalternativesrÕ  rÖ  )rÏ  rØ  )rw   r×  rÕ  rÖ  rÞ   rØ  ry   ry   rz   Úconfigurable_alternatives°
  s    1ûz.RunnableSerializable.configurable_alternatives)rs   rœ   rÂ  rÃ  rh   rÄ  r   Úmodel_configr$   rÉ  rÔ  rÙ  Ú__classcell__ry   ry   rÌ  rz   rÇ  _
  s   
ý=ûrÇ  úlist[Runnable[Any, Any]]r’   rŽ   )Ústepsr”   rm   c                   sœ   ddl m}m} | d ‰ t| ƒdkr.ˆ  |¡S tˆ |ƒrvt| dd … |ƒ}t|tƒs’t	d‡ fdd„|j
 ¡ D ƒd�S ntˆ |ƒr’t| dd … |ƒS ˆ  |¡S )Nr   ©rß   rÚ   rŒ   ZRunnableSequenceInputc                   s*   i | ]"\}}|ˆ j jvr||j|jf“qS ry   )ÚmapperÚsteps__r¬   r­   ©r¯   ÚkÚv©Úfirstry   rz   r±      s   þz%_seq_input_schema.<locals>.<dictcomp>r²   )rÛ   rß   rÚ   rƒ   r�   rš   Ú_seq_input_schemar›   r!   rU   rÑ  r¹   )rÝ  r”   rß   rÚ   Znext_input_schemary   rä  rz   ræ  î
  s     



þþ
ræ  c                   s  ddl m}m} | d ‰ t| ƒdkr.ˆ  |¡S tˆ |ƒr–ˆ j |¡}t| d d… |ƒ}t	|t
ƒs”tdi dd„ |j ¡ D ƒ¥dd„ |j ¡ D ƒ¥d	�S nvtˆ |ƒ�rt| d d… |ƒ}t	|t
ƒ�stˆ jtƒrìtd‡ fd
d„|j ¡ D ƒd	�S |jˆ j }td|j|jfd�S ˆ  |¡S )Nr   rÞ  éÿÿÿÿrŒ   ZRunnableSequenceOutputc                 S  s   i | ]\}}||j |jf“qS ry   ©r¬   r­   rá  ry   ry   rz   r±      s   ÿz&_seq_output_schema.<locals>.<dictcomp>c                 S  s   i | ]\}}||j |jf“qS ry   rè  rá  ry   ry   rz   r±   $  s   ÿr²   c                   s(   i | ] \}}|ˆ j v r||j|jf“qS ry   )rÙ   r¬   r­   rá  ©Úlastry   rz   r±   1  s   
þ)r–   )rÛ   rß   rÚ   rƒ   r�   rš   rß  r£   Ú_seq_output_schemar›   r!   rU   rÑ  r¹   rÙ   rù   r¬   r­   )rÝ  r”   rß   rÚ   Zmapper_output_schemaZprev_output_schemaÚfieldry   ré  rz   rë    sF    


þÿþûþ
þþÿrë  c                	      sr  e Zd ZU dZded< eed�Zded< ded< d	d	d	d	d
œdddddddœ‡ fdd„Ze	e
ddœdd„ƒƒZeddœdd„ƒZe	e
ddœdd„ƒƒZedd�Zee
ddœdd „ƒƒZee
d!dœd"d#„ƒƒZe
ddd$d%d&œd'd(„ƒZe
ded$d%d&œd)d*„ƒZee
d+dœd,d-„ƒƒZe
dfd$d.d&œd/d0„ƒZe
d1dœd2d3„ƒZe
d4d5d6œd7d8„ƒZe
d9d:d6œd;d<„ƒZe
dgd=d$d>d?d@œdAdB„ƒZe
dhd=d$dCd?d@œdDdE„ƒZe
didFdGœdHdIddCdJdKœdLdM„ƒZe
djdFdGœdHdIddCdJdKœdNdO„ƒZdPdQdRd>dSdTœdUdV„ZdWdXdRd>dYdTœdZd[„Ze
dkdPd$dCdSd@œd\d]„ƒZ e
dld=d$dCdSd@œd^d_„ƒZ!e
dmdWd$dCdYd@œd`da„ƒZ"e
dnd=d$dCdYd@œdbdc„ƒZ#‡  Z$S )orÐ   a°  Sequence of ``Runnables``, where the output of each 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``:

        .. code-block:: 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:

        .. code-block:: 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_factoryrÜ  ÚmiddlezRunnable[Any, Output]rê  N)rh   rå  rð  rê  ÚRunnableLikerg   zOptional[Runnable[Any, Any]]z"Optional[list[Runnable[Any, Any]]]ÚNone)rÝ  rh   rå  rð  rê  rm   c          	        sª   g }|s,|dur,|dur,|g|p"g  |g }|D ]*}t |tƒrL| |j¡ q0| t|ƒ¡ q0t|ƒdk r~dt|ƒ› �}t|ƒ‚tƒ j	|d t
|dd… ƒ|d |d� dS )aé  Create a new ``RunnableSequence``.

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

        Raises:
            ValueError: If the sequence has less than 2 steps.
        Nr   z1RunnableSequence must have at least 2 steps, got r   rŒ   rç  )rå  rð  rê  rh   )rš   rÐ   ÚextendrÝ  r   rÑ   rƒ   rÒ  rÈ  Ú__init__rù   )	rw   rh   rå  rð  rê  rÝ  Z
steps_flatÚstepr‰   rÌ  ry   rz   rô  ž  s     
üzRunnableSequence.__init__ú	list[str]r}   c                 C  s   g d¢S ©zyGet the namespace of the langchain object.

        Returns:
            ``["langchain", "schema", "runnable"]``
        )Z	langchainÚschemarv  ry   ©rx   ry   ry   rz   Úget_lc_namespaceÄ  s    z!RunnableSequence.get_lc_namespacec                 C  s   | j g| j¢| j‘S )zyAll the ``Runnable``s that make up the sequence in order.

        Returns:
            A list of ``Runnable``s.
        )rå  rð  rê  r�   ry   ry   rz   rÝ  Î  s    zRunnableSequence.stepsrí   c                 C  s   dS ©z*Return True as this class is serializable.Try   rù  ry   ry   rz   Úis_lc_serializable×  s    z#RunnableSequence.is_lc_serializableT©Zarbitrary_types_allowedr|   c                 C  s   | j jS ©z*The type of the input to the ``Runnable``.)rå  rŠ   r�   ry   ry   rz   rŠ   á  s    zRunnableSequence.InputTyper‹   c                 C  s   | j jS )z+The type of the output of the ``Runnable``.)rê  r�   r�   ry   ry   rz   r�   ç  s    zRunnableSequence.OutputTyper’   rŽ   r“   c                 C  s   t | j|ƒS )ú¿Get the input schema of the ``Runnable``.

        Args:
            config: The config to use. Defaults to None.

        Returns:
            The input schema of the ``Runnable``.

        )ræ  rÝ  r¡   ry   ry   rz   r�   í  s    z!RunnableSequence.get_input_schemac                 C  s   t | j|ƒS )úÁGet the output schema of the ``Runnable``.

        Args:
            config: The config to use. Defaults to None.

        Returns:
            The output schema of the ``Runnable``.

        )rë  rÝ  r¡   ry   ry   rz   r£   ü  s    z"RunnableSequence.get_output_schemar¦   c                   sî   ddl m‰ m‰ dd„ t| jƒD ƒ}t‡ fdd„|D ƒtdƒƒ}tƒ }i }|D ]"\}}|||< |dd„ |D ƒB }qNt|ƒD ]`\}\‰}ˆj 	ˆ ¡rzt
ˆjˆjˆjˆjˆjˆj‡‡fd	d„|| D ƒˆjpÊg  d
�|f||< qztdd„ |D ƒƒS )úwGet the config specs of the ``Runnable``.

        Returns:
            The config specs of the ``Runnable``.

        r   )ÚCONTEXT_CONFIG_PREFIXÚ_key_from_idc                 S  s$   g | ]\}}|j D ]}||f‘qqS ry   ©r§   )r¯   Úidxrõ  r°   ry   ry   rz   r¶     s   
þz1RunnableSequence.config_specs.<locals>.<listcomp>c                   s    g | ]}|d  j  ˆ ¡r|‘qS ©r   )r«   Ú
startswith)r¯   Útup)r  ry   rz   r¶   "  r·   rŒ   c                 S  s   h | ]}|d  j ’qS r  ©r«   r®   ry   ry   rz   r  )  r·   z0RunnableSequence.config_specs.<locals>.<setcomp>c                   s"   g | ]}ˆ |ƒˆ ˆj ƒkr|‘qS ry   r	  )r¯   Úd)r  r°   ry   rz   r¶   5  s   þ)r«   r¬   rh   r­   rª   Ú	is_sharedÚdependenciesc                 s  s   | ]\}}|V  qd S rô   ry   )r¯   r°   rp   ry   ry   rz   r�  ?  r·   z0RunnableSequence.config_specs.<locals>.<genexpr>)Ú%langchain_core.beta.runnables.contextr  r  r  rÝ  r   r   Úsetr«   r  r;   r¬   rh   r­   rª   r  r  rF   )rw   Z	all_specsZspecs_by_posZ	next_depsZdeps_by_posÚposÚspecsr  ry   )r  r  r°   rz   r§     s>    
þþþûùñ
zRunnableSequence.config_specsr]   c           
      C  sŽ   ddl m} |ƒ }| jD ]p}| ¡ }| |¡}|| jur@| ¡  || jurR| ¡  | 	|¡\}}|sxd|› d�}	t
|	ƒ‚|r| ||¡ q|S )á%  Get the graph representation of the ``Runnable``.

        Args:
            config: The config to use. Defaults to None.

        Returns:
            The graph representation of the ``Runnable``.

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

        r   r\   r€   ú has no first node)r¼   r]   rÝ  Z	last_noderÃ   rå  Útrim_first_noderê  Útrim_last_noderó  rÒ  r¿   )
rw   r”   r]   rÀ   rõ  Zcurrent_last_nodeÚ
step_graphÚstep_first_noderp   r‰   ry   ry   rz   rÃ   A  s     



zRunnableSequence.get_graphrj   c                 C  s   d  dd„ t| jƒD ƒ¡S )Nz
| c                 s  s0   | ](\}}|d krt |ƒntt |ƒdƒV  qdS )r   z| N)ÚreprrG   )r¯   rµ   Úsry   ry   rz   r�  e  s   ÿz,RunnableSequence.__repr__.<locals>.<genexpr>)Újoinr  rÝ  r�   ry   ry   rz   Ú__repr__c  s    
þzRunnableSequence.__repr__rË   rÌ   rÍ   c                 C  sn   t |tƒrDt| jg| j¢| j‘|j‘|j¢|j‘R d| jp>|jiŽS t| jg| j¢| j‘t|ƒ‘R d| jiŽS ©Nrh   ©rš   rÐ   rå  rð  rê  rh   rÑ   rÒ   ry   ry   rz   rÓ   j  s6    
ÿþýüûú
ù	ÿþýüûzRunnableSequence.__or__rÔ   rÕ   c                 C  sl   t |tƒrDt|jg|j¢|j‘| j‘| j¢| j‘R d|jp>| jiŽS tt|ƒ| jg| j¢| j‘R d| jiŽS r  r  rÒ   ry   ry   rz   rÖ   ‡  s4    
ÿþýüûú
ù	þýüûzRunnableSequence.__ror__r<   r   r=   rã   c              
   K  s*  ddl m} |t|ƒ| jƒ}t|ƒ}|jd || d¡p<|  ¡ | dd ¡d�}|}zŽt	| jƒD ]~\}}	t
|| d|d › �¡d�}t|ƒ�B}
|dkr¬|
j|	j||fi |¤Ž}n|
 |	j||¡}W d   ƒ q\1 sÐ0    Y  q\W n2 t�y } z| |¡ ‚ W Y d }~nd }~0 0 | |¡ td	|ƒS d S )
Nr   ©Úconfig_with_contextr|  r}  ©rh   r}  ú	seq:step:rŒ   r  r=   )r  r  r/   rÝ  r1   r€  r¾   r{   r  r  r5   r�  r7   r‚  rç   rƒ  r„  r…  r   )rw   rä   r”   rÞ   r  r†  r‡  ró   rµ   rõ  r‰  r÷   ry   ry   rz   rç   ¤  s0    
üÿ
4

zRunnableSequence.invokerî   c              
   Ë  sR  ddl m} |t|ƒ| jƒ}t|ƒ}|jd || d¡p<|  ¡ | dd ¡d�I d H }|}z¤t	| jƒD ]”\}}	t
|| d|d › �¡d�}t|ƒ�X}
|dkr²tj|	j||fi |¤Ž}nt |	j||¡}t|ƒ |
d	d
�I d H }W d   ƒ qb1 sì0    Y  qbW n8 t�y2 } z| |¡I d H  ‚ W Y d }~n$d }~0 0 | |¡I d H  td|ƒS d S )Nr   ©Úaconfig_with_contextr|  r}  r  r   rŒ   r  T©Úcreate_taskr=   )r  r"  r/   rÝ  r0   r€  r¾   r{   r  r  r5   r�  r7   Ú	functoolsÚpartialrè   r@   rƒ  r„  r…  r   )rw   rä   r”   rÞ   r"  r†  r‡  ró   rµ   rõ  r‰  Úpartr÷   ry   ry   rz   rè   Í  s2    
üÿ
:zRunnableSequence.ainvokeFré   rë   rì   rï   rð   c             
     sœ  ddl m‰  |sg S ‡ ‡fdd„t|t|ƒƒD ƒ}dd„ |D ƒ}‡fdd„t|||ƒD ƒ}�zn|�rxi ‰tˆjƒD ]²\‰}‡fdd„tt|ƒƒD ƒ}	|j‡fdd„t|	|ƒD ƒ‡‡fd	d„tt||ƒƒD ƒfd
|iˆdkrÞ|ni ¤Ž}ˆ 	dd„ t|	|ƒD ƒ¡ dd„ |D ƒ}tˆƒt|ƒkrr �q&qr| 
¡ }
g }tt|ƒƒD ]6‰ˆˆv �rb| tdˆˆ ƒ¡ n| |
 d¡¡ �q>nPtˆjƒD ]D\‰}|j|‡fdd„t||ƒD ƒfd
|iˆdk�r¼|ni ¤Ž}�q‚W nh t�y2 ‰ zN|D ]}| ˆ¡ �qà|�rtd‡fdd„|D ƒƒW  Y d ‰ŠS ‚ W Y d ‰Šnnd ‰Š0 0 d }t||ƒD ]6\}}t|tƒ�rl|�p^|}| |¡ n
| |¡ �qB|�sŠ|d u �r”td|ƒS |‚d S )Nr   r  c                   s   g | ]}ˆ |ˆj ƒ‘qS ry   ©rÝ  rŒ  )r  rw   ry   rz   r¶     s   ÿz*RunnableSequence.batch.<locals>.<listcomp>c                 S  s6   g | ].}t j| d ¡dd| d¡d| d¡dd�‘qS ©rX  NFÚtagsrˆ   ©Zinheritable_callbacksZlocal_callbacksÚverboseZinheritable_tagsZ
local_tagsZinheritable_metadataZlocal_metadata)r(   Ú	configurer¾   ©r¯   r”   ry   ry   rz   r¶     s   
÷ùc              
     s:   g | ]2\}}}|j d || d¡p&ˆ  ¡ | dd ¡d�‘qS ©Nr|  r}  r  r�  ©r¯   Úcmró   r”   r�   ry   rz   r¶     s   ú
üc                   s   g | ]}|ˆ vr|‘qS ry   ry   r´   ©Úfailed_inputs_mapry   rz   r¶   1  s   c                   s   g | ]\}}|ˆ vr|‘qS ry   ry   ©r¯   rµ   Úinpr2  ry   rz   r¶   6  s   þc              	     s8   g | ]0\}\}}|ˆ vrt || d ˆd › �¡d�‘qS ©r   rŒ   r  r“  ©r¯   rµ   r•  r”   ©r3  Ústepidxry   rz   r¶   ;  s   
ûþrê   c                 S  s    i | ]\}}t |tƒr||“qS ry   ©rš   rö   r4  ry   ry   rz   r±   I  s   
þz*RunnableSequence.batch.<locals>.<dictcomp>c                 S  s   g | ]}t |tƒs|‘qS ry   r:  ©r¯   r5  ry   ry   rz   r¶   O  r·   r<   c              	     s,   g | ]$\}}t || d ˆ d › �¡d�‘qS r6  r“  ©r¯   r•  r”   ©rµ   ry   rz   r¶   `  s   ýÿrï   c                   s   g | ]}ˆ ‘qS ry   ry   r–  r—  ry   rz   r¶   p  r·   )r  r  r2   rƒ   r  r  rÝ  Úrangerý   ÚupdateÚcopyr   r   r  rƒ  r„  rš   rö   r…  )rw   rñ   r”   rê   rÞ   rû   r˜  r™  rõ  Úremaining_idxsÚinputs_copyr•  rš  r‡  r
  ry   )r  r÷   r3  rµ   rw   r9  rz   rý   ú  sŽ    
þ
ö

ù

ÿ
þúúñðþÿ

ûþ	÷
ö$

zRunnableSequence.batchc             
   ‹  sÜ  ddl m‰  |sg S ‡ ‡fdd„t|t|ƒƒD ƒ}dd„ |D ƒ}tj‡fdd„t|||ƒD ƒŽ I d H }�zz|�rŠi ‰tˆjƒD ]¸\‰}‡fdd„t	t|ƒƒD ƒ}	|j
‡fd	d„t|	|ƒD ƒ‡‡fd
d„tt||ƒƒD ƒfd|iˆdkrê|ni ¤ŽI d H }ˆ dd„ t|	|ƒD ƒ¡ dd„ |D ƒ}tˆƒt|ƒkr~ �q8q~| ¡ }
g }t	t|ƒƒD ]6‰ˆˆv �rt| tdˆˆ ƒ¡ n| |
 d¡¡ �qPnVtˆjƒD ]J\‰}|j
|‡fdd„t||ƒD ƒfd|iˆdk�rÎ|ni ¤ŽI d H }�q”W np t�yR ‰ zVtj‡fdd„|D ƒŽ I d H  |�r<td‡fdd„|D ƒƒW  Y d ‰ŠS ‚ W Y d ‰ŠnŽd ‰Š0 0 d }g }t||ƒD ]B\}}t|tƒ�r–|�p‚|}| | |¡¡ n| | |¡¡ �qftj|Ž I d H  |�sÊ|d u �rÔtd|ƒS |‚d S )Nr   r!  c                   s   g | ]}ˆ |ˆj ƒ‘qS ry   r(  rŒ  )r"  rw   ry   rz   r¶   �  s   ÿz+RunnableSequence.abatch.<locals>.<listcomp>c                 S  s6   g | ].}t j| d ¡dd| d¡d| d¡dd�‘qS r)  )r'   r-  r¾   r.  ry   ry   rz   r¶   ”  s   
÷ùc              	   3  s<   | ]4\}}}|j d || d¡p$ˆ  ¡ | dd ¡d�V  qd S r/  r�  r0  r�   ry   rz   r�  ¢  s   ú
üz*RunnableSequence.abatch.<locals>.<genexpr>c                   s   g | ]}|ˆ vr|‘qS ry   ry   r´   r2  ry   rz   r¶   ¸  s   c                   s   g | ]\}}|ˆ vr|‘qS ry   ry   r4  r2  ry   rz   r¶   ½  s   þc              	     s8   g | ]0\}\}}|ˆ vrt || d ˆd › �¡d�‘qS r6  r“  r7  r8  ry   rz   r¶   Â  s   
ûþrê   c                 S  s    i | ]\}}t |tƒr||“qS ry   r:  r4  ry   ry   rz   r±   Ð  s   
þz+RunnableSequence.abatch.<locals>.<dictcomp>c                 S  s   g | ]}t |tƒs|‘qS ry   r:  r;  ry   ry   rz   r¶   Ö  r·   r<   c              	     s,   g | ]$\}}t || d ˆ d › �¡d�‘qS r6  r“  r<  r=  ry   rz   r¶   ç  s   ýÿc                 3  s   | ]}|  ˆ ¡V  qd S rô   rž  )r¯   r•  r—  ry   rz   r�  ó  r·   rï   c                   s   g | ]}ˆ ‘qS ry   ry   r–  r—  ry   rz   r¶   õ  r·   )r  r"  r2   rƒ   r"  rŸ  r  r  rÝ  r>  r  r?  r@  r   r   r  rƒ  rš   rö   r„  r…  )rw   rñ   r”   rê   rÞ   rû   r˜  r™  rõ  rA  rB  rš  r  r‡  r
  ry   )r"  r÷   r3  rµ   rw   r9  rz   r  ~  s”    
þ
ö

ùÿ


ÿ
þúúñðþÿ

ûþ	÷
ö$

zRunnableSequence.abatchr@  rW   r,   r%  ©rñ   r‡  r”   rÞ   rm   c           
      k  sœ   ddl m} | jg| j¢| j‘}||| jƒ}td|ƒ}t|ƒD ]N\}}	t|| 	d|d › �¡d�}|dkr€|	j
||fi |¤Ž}q>|	 
||¡}q>|E d H  d S )Nr   r  r%  r   rŒ   r  )r  r  rå  rð  rê  rÝ  r   r  r5   r�  rD  )
rw   rñ   r‡  r”   rÞ   r  rÝ  Úfinal_pipeliner  rõ  ry   ry   rz   Ú
_transform  s    
ÿzRunnableSequence._transformrE  rV   r'  c                 K s¬   ddl m} | jg| j¢| j‘}||| jƒ}td|ƒ}t|ƒD ]N\}}	t|| 	d|d › �¡d�}|dkr€|	j
||fi |¤Ž}q>|	 
||¡}q>|2 z3 d H W }
|
V  q’6 d S )Nr   r!  r'  r   rŒ   r  )r  r"  rå  rð  rê  rÝ  r   r  r5   r�  rG  )rw   rñ   r‡  r”   rÞ   r"  rÝ  rD  r  rõ  rF  ry   ry   rz   Ú_atransform#  s    
þzRunnableSequence._atransformc                 k  s:   | j || jt||pi  d¡p | jd�fi |¤ŽE d H  d S ©Nr|  )r|  )r¸  rE  r5   r¾   rh   ræ   ry   ry   rz   rD  C  s    ýüzRunnableSequence.transformc                 k  s$   | j t|gƒ|fi |¤ŽE d H  d S rô   ©rD  Úiterræ   ry   ry   rz   r&  Q  s    zRunnableSequence.streamc                 K sJ   | j || jt||pi  d¡p | jd�fi |¤Ž2 z3 d H W }|V  q06 d S rG  )r»  rF  r5   r¾   rh   ©rw   rä   r”   rÞ   r·  ry   ry   rz   rG  Z  s    ýüzRunnableSequence.atransformc                  sB   ddœ‡ fdd„}| j |ƒ |fi |¤Ž2 z3 d H W }|V  q(6 d S )NrE  r}   c                    s
   ˆ V  d S rô   ry   ry   ©rä   ry   rz   Úinput_aiterp  s    z-RunnableSequence.astream.<locals>.input_aiter©rG  ©rw   rä   r”   rÞ   rL  r·  ry   rK  rz   r(  i  s    "zRunnableSequence.astream)N)N)N)N)N)N)N)N)N)N)N)%rs   rœ   rÂ  rÃ  rÄ  r    rù   rð  rô  Úclassmethodr$   rú  rÅ  rÝ  rü  r   rÚ  rŠ   r�   r�   r£   r§   rÃ   r  rÓ   rÖ   rç   rè   rý   r  rE  rF  rD  r&  rG  r(  rÛ  ry   ry   rÌ  rz   rÐ   ?  s–   
Wú &ÿ ÿ ÿ4! ÿ( ý, ýû  ýû   ý ý ý ýrÐ   c                      sÖ  e Zd ZU dZded< dJddddœ‡ fd	d
„Zeeddœdd„ƒƒZeeddœdd„ƒƒZ	e
dd�ZedKddœddddœ‡ fdd„ƒZeeddœdd„ƒƒZedLdddœ‡ fd d!„ƒZedMdddœd"d#„ƒZeed$dœd%d&„ƒƒZedNdd'dœd(d)„ƒZeddœd*d+„ƒZedOd,ddd-d.œd/d0„ƒZedPd,dd1d-d.œd2d3„ƒZd4d5d6d7d8œd9d:„ZedQd4ddd;d.œd<d=„ƒZedRd,dd1d;d.œd>d?„ƒZd@dAd6dBd8œdCdD„ZedSd@dddEd.œdFdG„ƒZedTd,dd1dEd.œdHdI„ƒZ‡  ZS )Urà   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 for the LCEL,
    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``:

        .. code-block:: 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 ``Runnables``:

        .. code-block:: 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]]rà  NzŽOptional[Mapping[str, Union[Runnable[Input, Any], Callable[[Input], Any], Mapping[str, Union[Runnable[Input, Any], Callable[[Input], Any]]]]]]zvUnion[Runnable[Input, Any], Callable[[Input], Any], Mapping[str, Union[Runnable[Input, Any], Callable[[Input], Any]]]]rò  )rà  rÞ   rm   c                   s>   |duri |¥ni }|  |¡ tƒ jdd„ | ¡ D ƒd� dS )z§Create a ``RunnableParallel``.

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

        Nc                 S  s   i | ]\}}|t |ƒ“qS ry   )rÑ   )r¯   rÓ  Úrry   ry   rz   r±   ê  r·   z-RunnableParallel.__init__.<locals>.<dictcomp>)rà  )r?  rÈ  rô  r¹   )rw   rà  rÞ   ÚmergedrÌ  ry   rz   rô  Î  s
    
ÿzRunnableParallel.__init__rí   r}   c                 C  s   dS rû  ry   rù  ry   ry   rz   rü  í  s    z#RunnableParallel.is_lc_serializablerö  c                 C  s   g d¢S r÷  ry   rù  ry   ry   rz   rú  ó  s    z!RunnableParallel.get_lc_namespaceTrý  ri   rg   rj   rk   c                  s2   |p | j p dd | j ¡ ¡› d�}tƒ j||d�S )zäGet the name of the ``Runnable``.

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

        Returns:
            The name of the ``Runnable``.

        zRunnableParallel<ú,ú>ri   )rh   r  rà  rÙ   rÈ  r{   ©rw   rl   rh   rÌ  ry   rz   r{     s    "zRunnableParallel.get_namer   c                 C  s$   | j  ¡ D ]}|jr
|j  S q
tS rþ  )rà  rÉ   rŠ   r   )rw   rõ  ry   ry   rz   rŠ     s    zRunnableParallel.InputTyper’   rŽ   r“   c                   sN   t ‡ fdd„| j ¡ D ƒƒrBt|  d¡‡ fdd„| j ¡ D ƒd�S tƒ  ˆ ¡S )rÿ  c                 3  s(   | ] }|  ˆ ¡ ¡  d d¡dkV  qdS )rÐ  ÚobjectN)r�   r    r¾   )r¯   r  rÆ   ry   rz   r�  )  s   þÿz4RunnableParallel.get_input_schema.<locals>.<genexpr>r<   c                   s<   i | ]4}|  ˆ ¡j ¡ D ]\}}|d kr||j|jf“qqS )Z__root__)r�   rÑ  r¹   r¬   r­   )r¯   rõ  râ  rã  rÆ   ry   rz   r±   1  s   ýz5RunnableParallel.get_input_schema.<locals>.<dictcomp>r²   )Úallrà  rÉ   rU   r{   rÈ  r�   r¡   rÌ  rÆ   rz   r�     s    ý
þþ
z!RunnableParallel.get_input_schemac                 C  s&   dd„ | j  ¡ D ƒ}t|  d¡|d�S )r   c                 S  s   i | ]\}}||j d f“qS ).)r�   rá  ry   ry   rz   r±   H  r·   z6RunnableParallel.get_output_schema.<locals>.<dictcomp>r=   r²   )rà  r¹   rU   r{   )rw   r”   rÎ  ry   ry   rz   r£   ;  s    z"RunnableParallel.get_output_schemar¦   c                 C  s   t dd„ | j ¡ D ƒƒS )r  c                 s  s   | ]}|j D ]
}|V  qqd S rô   r  )r¯   rõ  r°   ry   ry   rz   r�  T  s   z0RunnableParallel.config_specs.<locals>.<genexpr>)rF   rà  rÉ   r�   ry   ry   rz   r§   K  s    	ÿzRunnableParallel.config_specsr]   c                 C  sÆ   ddl m} |ƒ }| |  |¡¡}| |  |¡¡}| j ¡ D ]„}| ¡ }| ¡  | 	¡  |sj| 
||¡ q<| |¡\}}	|s�d|› d�}
t|
ƒ‚|	s¨d|› d�}
t|
ƒ‚| 
||¡ | 
|	|¡ q<|S )r  r   r\   r€   r  ú has no last node)r¼   r]   r½   r�   r£   rà  rÉ   rÃ   r  r  r¿   ró  rÒ  )rw   r”   r]   rÀ   rÁ   rÂ   rõ  r  r  Zstep_last_noder‰   ry   ry   rz   rÃ   X  s(    zRunnableParallel.get_graphc                 C  s&   d  dd„ | j ¡ D ƒ¡}d| d S )Nz,
  c                 s  s2   | ]*\}}|› d t t|ƒd| d  ƒ› �V  qdS )z: z  N)rG   r  rá  ry   ry   rz   r�  �  s   ÿz,RunnableParallel.__repr__.<locals>.<genexpr>z{
  z
})r  rà  r¹   )rw   Zmap_for_reprry   ry   rz   r    s    
þzRunnableParallel.__repr__r<   rŸ   rã   c           	   
     s   t ˆƒ‰tjˆ d¡d dˆ d¡d ˆ d¡d d�}|jd ˆˆ d¡pJ|  ¡ ˆ dd ¡d�‰d	d
ddddœ‡fdd„‰ zft| jƒ}t	ˆƒ�@‰‡ ‡‡‡fdd„| 
¡ D ƒ}dd„ t||ƒD ƒ}W d   ƒ n1 sÎ0    Y  W n2 t�y } zˆ |¡ ‚ W Y d }~nd }~0 0 ˆ |¡ |S d S )NrX  Fr*  rˆ   r+  r|  r}  r  rí  r<   r,   rj   r   ©rõ  ró   r”   rÓ  rm   c                   sT   t |ˆ  d|› �¡d�}t|ƒ� }| | j||¡W  d   ƒ S 1 sF0    Y  d S )Númap:key:r  )r5   r�  r7   r‚  rç   ©rõ  ró   r”   rÓ  rˆ  r‰  ©r‡  ry   rz   Ú_invoke_stepž  s    ý
ýz-RunnableParallel.invoke.<locals>._invoke_stepc              	     s"   g | ]\}}ˆ  ˆ |ˆˆ|¡‘qS ry   r  ©r¯   rÓ  rõ  )r\  r”   rü   rä   ry   rz   r¶   ³  s   ÿz+RunnableParallel.invoke.<locals>.<listcomp>c                 S  s   i | ]\}}||  ¡ “qS ry   )r  )r¯   rÓ  r  ry   ry   rz   r±   ·  r·   z+RunnableParallel.invoke.<locals>.<dictcomp>)r/   r(   r-  r¾   r€  r{   r  rá   rà  r3   r¹   r  rƒ  r„  r…  )	rw   rä   r”   rÞ   r†  rÝ  r  rF  r÷   ry   )r\  r”   rü   rä   r‡  rz   rç   ‡  s:    ù

ü

þ6

zRunnableParallel.invokerî   c           	   
   ‹  sê   t ˆƒ‰tˆƒ}|jd ˆˆ d¡p(|  ¡ ˆ dd ¡d�I d H ‰dddddd	œ‡fd
d„‰ zBt| jƒ}tj	‡ ‡‡fdd„| 
¡ D ƒŽ I d H }tt||ƒƒ}W n6 tyÐ } zˆ |¡I d H  ‚ W Y d }~nd }~0 0 ˆ |¡I d H  |S d S )Nr|  r}  r  rí  r<   r,   rj   r   rX  c                 “  s`   t |ˆ  d|› �¡d�}t|ƒ�,}t|  ||¡|dd�I d H W  d   ƒ S 1 sR0    Y  d S )NrY  r  Tr#  )r5   r�  r7   r@   rè   rZ  r[  ry   rz   Ú_ainvoke_stepÒ  s    þ
ÿz/RunnableParallel.ainvoke.<locals>._ainvoke_stepc                 3  s    | ]\}}ˆ |ˆˆ|ƒV  qd S rô   ry   r]  )r^  r”   rä   ry   rz   r�  ã  s   ùûz+RunnableParallel.ainvoke.<locals>.<genexpr>)r/   r0   r€  r¾   r{   r  rá   rà  r"  rŸ  r¹   r  rƒ  r„  r…  )	rw   rä   r”   rÞ   r†  rÝ  ÚresultsrF  r÷   ry   )r^  r”   rä   r‡  rz   rè   À  s,    
ü
øÿ
zRunnableParallel.ainvoker@  rW   r,   zIterator[AddableDict])rñ   r‡  r”   rm   c              
   #  sì   t | jƒ}tt|t|ƒt ¡ d�ƒ‰tˆ ƒ�¬‰‡ ‡‡fdd„| ¡ D ƒ}‡fdd„|D ƒ}|rÊt	|t
d�\}}|D ]T}	| |	¡\}
}z.t|
|	 ¡ iƒ}|V  |
|f|ˆ t|¡< W qr tyÄ   Y qr0 qrqZW d   ƒ n1 sÞ0    Y  d S )N©Úlockc                   s8   g | ]0\}}||  ˆ ¡ tˆ ˆ d |› �¡d�¡f‘qS ©rY  r  )rD  r  r5   r�  ©r¯   rh   rõ  ©r”   Úinput_copiesr‡  ry   rz   r¶     s   
øÿþþz/RunnableParallel._transform.<locals>.<listcomp>c                   s"   i | ]\}}ˆ   t|¡||f“qS ry   )r  r«  ©r¯   Ú	step_nameÚ	generator)rü   ry   rz   r±     s   ÿz/RunnableParallel._transform.<locals>.<dictcomp>r  )rá   rà  rù   rT   rƒ   Ú	threadingÚLockr3   r¹   r   r   r  r8   r  r  r«  r­  )rw   rñ   r‡  r”   rÝ  Únamed_generatorsr  Zcompleted_futuresrp   r  rg  rh  r·  ry   )r”   rü   re  r‡  rz   rE  ÷  s*    


ö
þþzRunnableParallel._transformzIterator[dict[str, Any]]c                 k  s"   | j || j|fi |¤ŽE d H  d S rô   )r¸  rE  ræ   ry   ry   rz   rD  &  s
    ÿÿzRunnableParallel.transformc                 k  s   |   t|gƒ|¡E d H  d S rô   rH  ræ   ry   ry   rz   r&  1  s    zRunnableParallel.streamrE  rV   zAsyncIterator[AddableDict]c              	    sä   t | jƒ}tt|t|ƒt ¡ d�ƒ‰‡ ‡‡fdd„| ¡ D ƒ}dddœdd„‰‡fd	d
„|D ƒ}|ràtj|tj	d�I d H \}}|D ]Z}	| 
|	¡\}
}z4t|
|	 ¡ iƒ}|V  t ˆ|ƒ¡}|
|f||< W q‚ tyÚ   Y q‚0 q‚q`d S )Nr`  c                   s8   g | ]0\}}||  ˆ ¡ tˆ ˆ d |› �¡d�¡f‘qS rb  )rG  r  r5   r�  rc  rd  ry   rz   r¶   F  s   
øÿþþz0RunnableParallel._atransform.<locals>.<listcomp>r   zOptional[Output])rh  rm   c                 Ó  s   t | ƒI d H S rô   )rS   )rh  ry   ry   rz   Úget_next_chunkT  s    z4RunnableParallel._atransform.<locals>.get_next_chunkc                   s$   i | ]\}}t  ˆ |ƒ¡||f“qS ry   )r"  r$  rf  )rl  ry   rz   r±   X  s   ÿz0RunnableParallel._atransform.<locals>.<dictcomp>r  )rá   rà  rù   rR   rƒ   r"  rj  r¹   r   r   r  r8   r  r$  rº  )rw   rñ   r‡  r”   rÝ  rk  ZtasksZcompleted_tasksrp   Ztaskrg  rh  r·  Znew_taskry   )r”   rl  re  r‡  rz   rF  :  s,    

ö
þÿzRunnableParallel._atransformzAsyncIterator[dict[str, Any]]c                 K s2   | j || j|fi |¤Ž2 z3 d H W }|V  q6 d S rô   )r»  rF  rJ  ry   ry   rz   rG  m  s    ÿÿzRunnableParallel.atransformc                  s:   ddœ‡ fdd„}|   |ƒ |¡2 z3 d H W }|V  q 6 d S )NrE  r}   c                    s
   ˆ V  d S rô   ry   ry   rK  ry   rz   rL  €  s    z-RunnableParallel.astream.<locals>.input_aiterrM  rN  ry   rK  rz   r(  y  s    zRunnableParallel.astream)N)N)N)N)N)N)N)N)N)N)N)rs   rœ   rÂ  rÃ  rÄ  rô  rO  r$   rü  rú  r   rÚ  r{   rÅ  rŠ   r�   r£   r§   rÃ   r  rç   rè   rE  rD  r&  rF  rG  r(  rÛ  ry   ry   rÌ  rz   rà   w  sl   
T õÿ ÿÿ ÿ ÿ& ÿ8 ý6/ ý
 ý3 ý ýrà   c                   @  sJ  e Zd ZdZd3ddœdddddœd	d
„Zeeddœdd„ƒƒZed4dddœdd„ƒZeeddœdd„ƒƒZ	ed5dddœdd„ƒZ
edddœdd„ƒZdZeddœdd„ƒZed6d ddd!d"œd#d$„ƒZed7d%ddd!d"œd&d'„ƒZed8d%ddd(d"œd)d*„ƒZed9d+ddd,d"œd-d.„ƒZed:d%ddd,d"œd/d0„ƒZed;d%ddd(d"œd1d2„ƒZdS )<Ú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``:

        .. code-block:: 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:

        .. code-block:: python

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


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


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


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


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


            runnable = chant_chain | RunnableLambda(reverse_generator)
            "".join(runnable.stream({"topic": "waste"}))  # ".elcycer ,esuer ,ecudeR"

    Nri   zmUnion[Callable[[Iterator[Input]], Iterator[Output]], Callable[[AsyncIterator[Input]], AsyncIterator[Output]]]zAOptional[Callable[[AsyncIterator[Input]], AsyncIterator[Output]]]rg   rò  )rD  rG  rh   rm   c                C  s€   |dur|| _ |}t|ƒr&|| _ |}n,t |¡r<|| _|}ndt|ƒ› �}t|ƒ‚z|p\|j| _W n t	yz   d| _Y n0 dS )aK  Initialize a ``RunnableGenerator``.

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

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

        NzTExpected a generator function type for `transform`.Instead got an unsupported type: rm  )
rF  rI   r˜   ÚisgeneratorfunctionrE  rÐ  r…   rs   rh   ÚAttributeError)rw   rD  rG  rh   Úfunc_for_namer‰   ry   ry   rz   rô  ê  s$    
ÿÿzRunnableGenerator.__init__r   r}   c                 C  st   t | dd ƒp| j}zJt |¡j}tt| ¡ ƒd ƒ}|rZ|jtj	j
krZt |jdtfƒd W S W n tyn   Y n0 tS ©NrE  Ú__args__r   )ÚgetattrrF  r˜   Ú	signatureÚ
parametersr«  rI  rÉ   r¬   Ú	ParameterÚemptyr   rÒ  ©rw   ry  ÚparamsZfirst_paramry   ry   rz   rŠ     s    zRunnableGenerator.InputTyper’   rŽ   r“   c                 C  sZ   | j }t| dd ƒp| j}t|dd ƒ}t |¡rFt|tƒsFt|tƒrF|S t	|  
d¡||d�S )NrE  rœ   r<   r•   )rŠ   rs  rF  r˜   r™   rš   r   r›   r   rU   r{   ©rw   r”   rž   ry  Úmodulery   ry   rz   r�   $  s    ÿþýúz"RunnableGenerator.get_input_schemac                 C  s`   t | dd ƒp| j}z2t |¡}|jtjjkr@t |jdtfƒd ntW S  tyZ   t Y S 0 d S rq  )	rs  rF  r˜   rt  Úreturn_annotationÚ	Signaturerw  r   rÒ  ©rw   ry  Úsigry   ry   rz   r�   @  s    
ÿýzRunnableGenerator.OutputTypec                 C  sZ   | j }t| dd ƒp| j}t|dd ƒ}t |¡rFt|tƒsFt|tƒrF|S t	|  
d¡||d�S )NrE  rœ   r=   r•   )r�   rs  rF  r˜   r™   rš   r   r›   r   rU   r{   rz  ry   ry   rz   r£   N  s    ÿþýúz#RunnableGenerator.get_output_schemarU  rí   rÍ   c                 C  sR   t |tƒrNt| dƒr*t|dƒr*| j|jkS t| dƒrJt|dƒrJ| j|jkS dS dS )NrE  rF  F)rš   rm  rq   rE  rF  rÒ   ry   ry   rz   Ú__eq__i  s    
zRunnableGenerator.__eq__rj   c                 C  s   d| j › d�S )NzRunnableGenerator(ú)ri   r�   ry   ry   rz   r  u  s    zRunnableGenerator.__repr__r@  r%  rã   c                 K  s8   t | dƒs| ›d�}t|ƒ‚| j|| j|fddi|¤ŽS )NrE  z only supports async methods.r£  T)rq   r=  r¸  rE  ©rw   rä   r”   rÞ   r‰   ry   ry   rz   rD  y  s    

ýüûzRunnableGenerator.transformr<   c                 K  s   | j t|gƒ|fi |¤ŽS rô   rH  ræ   ry   ry   rz   r&  ‹  s    zRunnableGenerator.streamr=   c                 K  s<   d }| j ||fi |¤ŽD ]}|d u r(|n|| }qtd|ƒS ©Nr=   )r&  r   ©rw   rä   r”   rÞ   rC  rF  ry   ry   rz   rç   ”  s    zRunnableGenerator.invokerE  r'  c                 K  s8   t | dƒs| ›d�}t|ƒ‚| j|| j|fddi|¤ŽS )NrF  z only supports sync methods.r£  T)rq   r=  r»  rF  r‚  ry   ry   rz   rG  �  s    

ÿÿÿzRunnableGenerator.atransformc                   s(   ddœ‡ fdd„}| j |ƒ |fi |¤ŽS )NrE  r}   c                    s
   ˆ V  d S rô   ry   ry   rK  ry   rz   rL  ³  s    z.RunnableGenerator.astream.<locals>.input_aiterrM  )rw   rä   r”   rÞ   rL  ry   rK  rz   r(  ¬  s    zRunnableGenerator.astreamc                 Ë  sF   d }| j ||fi |¤Ž2 z 3 d H W }|d u r0|n|| }q6 td|ƒS rƒ  )r(  r   r„  ry   ry   rz   rè   ¸  s     zRunnableGenerator.ainvoke)N)N)N)N)N)N)N)N)N)rs   rœ   rÂ  rÃ  rô  rÅ  r$   rŠ   r�   r�   r£   r€  Ú__hash__r  rD  r&  rç   rG  r(  rè   ry   ry   ry   rz   rm  ‹  sP   f ø
ö- ÿ ÿ	 ý ý ÿ ý ý ÿrm  c                      sä  e Zd ZdZdKdddddœdd	„Zeed
dœdd„ƒƒZedLdddœ‡ fdd„ƒZeed
dœdd„ƒƒZ	edMdddœdd„ƒZ
ejddœdd„ƒZeeddœdd„ƒƒZedNdddœ‡ fdd „ƒZed!d"d#œd$d%„ƒZdZd&dœd'd(„Zd)d*d+d
d,d-œd.d/„Zd)d0d+d
d,d1œd2d3„ZedOd)dd4d,d5œd6d7„ƒZedPd)dd4d,d5œd8d9„ƒZd:d*d+d
d;d<œd=d>„ZedQd:dd4d;d5œd?d@„ƒZedRd)dd4d;d5œdAdB„ƒZdCd0d+d
dDd<œdEdF„ZedSdCdd4dDd5œdGdH„ƒZedTd)dd4dDd5œdIdJ„ƒZ‡  ZS )UÚRunnableLambdaaN  ``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:

        .. code-block:: 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

    NaL  Union[Union[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]], Union[Callable[[Input], Awaitable[Output]], Callable[[Input], AsyncIterator[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]]a3  Optional[Union[Callable[[Input], Awaitable[Output]], Callable[[Input], AsyncIterator[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]]rg   rò  )ry  Úafuncrh   rm   c                 C  s¶   |dur|| _ |}t|ƒs"t|ƒrB|dur6d}t|ƒ‚|| _ |}n0t|ƒr\td|ƒ| _|}ndt|ƒ› �}t|ƒ‚z&|dur„|| _n|j	dkr–|j	| _W n t
yª   Y n0 d| _dS )aZ  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.
                Defaults to None.
            name: The name of the ``Runnable``. Defaults to None.

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

        Nz�Func 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>)r‡  rH   rI   r…   Úcallabler   ry  rÐ  rh   rs   ro  Ú_repr)rw   ry  r‡  rh   rp  r‰   ry   ry   rz   rô  ô  s4    4ÿÿÿ
zRunnableLambda.__init__r   r}   c                 C  sf   t | ddƒp| j}z<t |¡j}tt| ¡ ƒdƒ}|rL|jtj	j
krL|jW S W n ty`   Y n0 tS )z+The type of the input to this ``Runnable``.ry  N)rs  r‡  r˜   rt  ru  r«  rI  rÉ   r¬   rv  rw  rÒ  r   rx  ry   ry   rz   rŠ   J  s    zRunnableLambda.InputTyper’   rŽ   r“   c                   sÜ   t | ddƒp| j}t|tƒr�t|ƒ dd¡dd…  d¡}tdd„ |D ƒƒrld	d
„ |D ƒ}t|  	d¡|d�S t |ddƒ}t|  	d¡t
t |d�S | jtkr¦tƒ  |¡S t|ƒ }rÐt|  	d¡t |tdf¡d�S tƒ  |¡S )zÏThe pydantic schema for the input to this ``Runnable``.

        Args:
            config: The config to use. Defaults to None.

        Returns:
            The input schema for this ``Runnable``.

        ry  Nzoperator.itemgetter(r¤  rç  z, c                 s  s2   | ]*}|d  dko(|d dko(t |ƒdkV  qdS )r   ú'rç  r   N)rƒ   ©r¯   r9  ry   ry   rz   r�  k  s   z2RunnableLambda.get_input_schema.<locals>.<genexpr>c                 S  s   i | ]}|d d… t df“qS )rŒ   rç  .)r   rŒ  ry   ry   rz   r±   n  r·   z3RunnableLambda.get_input_schema.<locals>.<dictcomp>r<   r²   rœ   r•   .)rs  r‡  rš   r   rj   ÚreplaceÚsplitrV  rU   r{   rù   r   rŠ   rÈ  r�   rC   rá   Úfromkeys)rw   r”   ry  r¹   rÎ  r{  Ú	dict_keysrÌ  ry   rz   r�   X  s,    
ÿú	
þzRunnableLambda.get_input_schemac                 C  s‚   t | ddƒp| j}zXt |¡}|jtjjkrht |jddƒtjj	tjj
hv r`t |jdtfƒd W S |jW S W n ty|   Y n0 tS )z–The type of the output of this ``Runnable`` as a type annotation.

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

        ry  NÚ
__origin__rr  r   )rs  r‡  r˜   rt  r|  r}  rw  ÚcollectionsÚabcr	   r   r   rÒ  r~  ry   ry   rz   r�   †  s    	
þzRunnableLambda.OutputTypec                 C  sZ   | j }t| dd ƒp| j}t|dd ƒ}t |¡rFt|tƒsFt|tƒrF|S t	|  
d¡||d�S )Nry  rœ   r=   r•   )r�   rs  r‡  r˜   r™   rš   r   r›   r   rU   r{   rz  ry   ry   rz   r£   ž  s    ÿþýúz RunnableLambda.get_output_schemazlist[Runnable]c                 C  sv   t | dƒrt| jƒ}nt | dƒr,t| jƒ}ng }g }|D ]8}t|tƒrR| |¡ q8tt|ddƒtƒr8| |j¡ q8|S )zâThe dependencies of this ``Runnable``.

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

        ry  r‡  Ú__self__N)	rq   rD   ry  r‡  rš   rf   r   rs  r”  )rw   ZobjectsÚdepsÚobjry   ry   rz   r•  ¹  s    	


zRunnableLambda.depsr¦   c                 C  s   t dd„ | jD ƒƒS )Nc                 s  s   | ]}|j D ]
}|V  qqd S rô   r  )r¯   Údepr°   ry   ry   rz   r�  Ô  s   z.RunnableLambda.config_specs.<locals>.<genexpr>)rF   r•  r�   ry   ry   rz   r§   Ñ  s    ÿzRunnableLambda.config_specszRunnableConfig | Noner]   c                   sØ   | j  }rÈddlm} |ƒ }| |  |¡¡}| |  |¡¡}|D ]„}| ¡ }| ¡  | ¡  |sn| 	||¡ q@| 
|¡\}	}
|	s”d|› d�}t|ƒ‚|
s¬d|› d�}t|ƒ‚| 	||	¡ | 	|
|¡ q@ntƒ  |¡}|S )Nr   r\   r€   r  rW  )r•  r¼   r]   r½   r�   r£   rÃ   r  r  r¿   ró  rÒ  rÈ  )rw   r”   r•  r]   rÀ   rÁ   rÂ   r—  Z	dep_graphZdep_first_nodeZdep_last_noder‰   rÌ  ry   rz   rÃ   Ø  s,    
zRunnableLambda.get_graphrU  rí   rÍ   c                 C  sR   t |tƒrNt| dƒr*t|dƒr*| j|jkS t| dƒrJt|dƒrJ| j|jkS dS dS )Nry  r‡  F)rš   r†  rq   ry  r‡  rÒ   ry   ry   rz   r€  ö  s    
zRunnableLambda.__eq__rj   c                 C  s–   | j du r�t| dƒrBt| jtƒrBdt| jƒtdƒd… › d�| _ nNt| dƒrfdt| jƒpZd› d�| _ n*t| dƒrŠdt| jƒp~d› d�| _ nd	| _ | j S )
z4Return a string representation of this ``Runnable``.Nry  zRunnableLambda(z	operator.r�  z...r‡  zRunnableLambda(afunc=zRunnableLambda(...))	rŠ  rq   rš   ry  r   rj   rƒ   rE   r‡  r�   ry   ry   rz   r    s    
"

ÿzRunnableLambda.__repr__r<   rW   r,   r=   ©ró   r‡  r”   rÞ   rm   c           	   	   K  sÜ   t  | j¡rhd }ttd| jƒ|||fi |¤ŽD ]6}|d u r@|}q.z|| }W q. tyb   |}Y q.0 q.nt| j|||fi |¤Ž}t|tƒrÒ|d }|dkr´d| › d|› d�}t|ƒ‚| 	|t
|| ¡ |d d�¡}td	|ƒS )
Nú#Callable[[Input], Iterator[Output]]Úrecursion_limitr   ú&Recursion limit reached when invoking ú with input Ú.rŒ   ©rX  rš  r=   )r˜   rn  ry  r.   r   r…   rš   rf   ÚRecursionErrorrç   r5   r�  )	rw   ró   r‡  r”   rÞ   rF  r·  rš  r‰   ry   ry   rz   Ú_invoke  sH    
üû

ÿÿ
ÿýþzRunnableLambda._invokerV   ©r  r‡  r”   rÞ   rm   c              
   ‹  sº  t ˆdƒrˆj}nft ˆj¡r:ddddddœ‡fdd	„‰nddddddœ‡fd
d	„‰tˆƒddddœ‡ ‡fdd„ƒ}|}t|ƒ�r2d }ttdt	td|ƒ|ˆ |fi |¤Žƒƒ4 I d H šd}td|ƒ2 z>3 d H W }	|d u rÚ|	}qÀz||	 }W qÀ t
yü   |	}Y qÀ0 qÀ6 W d   ƒI d H  �qT1 I d H �s&0    Y  n"t	td|ƒ|ˆ |fi |¤ŽI d H }t|tƒ�r°ˆ d }
|
dk�rŒdˆ› d|› d�}t|ƒ‚| |tˆ | ¡ |
d d�¡I d H }td|ƒS )Nr‡  r<   rV   r,   r   r=   r¡  c              	     sh   d }t tdˆ jƒ| || ¡ fi |¤ŽD ]6}|d u r8|}q&z|| }W q& tyZ   |}Y q&0 q&td|ƒS )Nr™  r=   )r.   r   ry  Úget_syncr…   )r  r‡  r”   rÞ   rF  r·  r�   ry   rz   ry  J  s     
üû
z%RunnableLambda._ainvoke.<locals>.funcc                   s   t ˆ j| || ¡ fi |¤ŽS rô   ©r.   ry  r¢  )r  r‡  r”   rÞ   r�   ry   rz   ry  c  s
    ÿÿ©r~   rÞ   rm   c                  Ÿ  s   t ˆ ˆg| ¢R i |¤ŽI d H S rô   ©r6   ©r~   rÞ   ©r”   ry  ry   rz   Úfm  s    z"RunnableLambda._ainvoke.<locals>.fzAsyncGenerator[Any, Any]r   r'  rš  r   r›  rœ  r�  rŒ   rž  )rq   r‡  r˜   rn  ry  r   rI   rQ   r   r-   r…   rš   rf   rŸ  rè   r5   r�  )rw   r  r‡  r”   rÞ   r‡  r¨  rF  r&  r·  rš  r‰   ry   ©r”   ry  rw   rz   Ú_ainvoke>  sl    


üûþÿþ>ÿÿ
ÿýþ
zRunnableLambda._ainvokerî   rã   c                 K  s6   t | dƒr&| j| j|t|ƒfi |¤ŽS d}t|ƒ‚dS )ar  Invoke this ``Runnable`` synchronously.

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

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

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

        ry  zGCannot invoke a coroutine function synchronously.Use `ainvoke` instead.N)rq   rŠ  r   r/   r…   r‚  ry   ry   rz   rç   ¢  s    
ýüzRunnableLambda.invokec                 Ë  s"   | j | j|t|ƒfi |¤ŽI dH S )a  Invoke this ``Runnable`` asynchronously.

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

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

        N)r‹  rª  r/   ræ   ry   ry   rz   rè   Á  s    ýüzRunnableLambda.ainvoker@  r%  )Úchunksr‡  r”   rÞ   rm   c              	   k  sB  d}|D ]6}|s|}d}qz|| }W q t y<   |}Y q0 qt | j¡r¨d }t| j|||fi |¤ŽD ]<}	|	V  |d u r€|	}qhz||	 }W qh t y¢   |	}Y qh0 qhnt| j|||fi |¤Ž}t|tƒ�r$|d }
|
dkröd| › d|› d�}t|ƒ‚| |t	|| 
¡ |
d d	�¡D ]}	|	V  �qnt | j¡�s>td
|ƒV  d S )NFTrš  r   r›  rœ  r�  rŒ   rž  r=   )r…   r˜   rn  ry  r.   rš   rf   rŸ  r&  r5   r�  r   )rw   r«  r‡  r”   rÞ   rA  rB  rC  rF  r·  rš  r‰   ry   ry   rz   rE  Ú  sZ    
ÿÿ

ÿÿÿýþzRunnableLambda._transformc                 k  s>   t | dƒr.| j|| jt|ƒfi |¤ŽE d H  nd}t|ƒ‚d S )Nry  zGCannot stream a coroutine function synchronously.Use `astream` instead.)rq   r¸  rE  r/   r…   r‚  ry   ry   rz   rD    s    
ýüÿzRunnableLambda.transformc                 K  s   | j t|gƒ|fi |¤ŽS rô   rH  ræ   ry   ry   rz   r&  -  s    zRunnableLambda.streamrE  r'  c              	    sÜ  d}|2 z>3 d H W }|s"|}d}qz|| }W q t yD   |}Y q0 q6 tˆdƒr\ˆj}nVt ˆj¡rtd}	t |	ƒ‚ddddd	d
œ‡fdd„‰tˆƒddddœ‡ ‡fdd„ƒ}
|
}t|ƒ�r0d }tdt	td|ƒ|ˆ |fi |¤Žƒ2 zH3 d H W }|V  |d u �r|}qâz|| }W qâ t �y(   |}Y qâ0 qâ6 n"t	td|ƒ|ˆ |fi |¤ŽI d H }t
|tƒ�rÂˆ d }|dk�rŠdˆ› d|› d�}	t|	ƒ‚| |tˆ | ¡ |d d�¡2 z3 d H W }|V  �q¨6 nt|ƒ�sØtd	|ƒV  d S )NFTr‡  zMCannot stream from a generator function asynchronously.Use .stream() instead.r<   rV   r,   r   r=   r˜  c                   s   t ˆ j| || ¡ fi |¤ŽS rô   r£  )ró   r‡  r”   rÞ   r�   ry   rz   ry  W  s
    ÿÿz(RunnableLambda._atransform.<locals>.funcr¤  c                  Ÿ  s   t ˆ ˆg| ¢R i |¤ŽI d H S rô   r¥  r¦  r§  ry   rz   r¨  a  s    z%RunnableLambda._atransform.<locals>.fr'  r   rš  r   r›  rœ  r�  rŒ   rž  )r…   rq   r‡  r˜   rn  ry  r   rI   r   r-   rš   rf   rŸ  r(  r5   r�  )rw   r«  r‡  r”   rÞ   rA  rB  rC  r‡  r‰   r¨  rF  r·  rš  ry   r©  rz   rF  6  s€    
ÿ

üûþ

üû	
ÿýþ
zRunnableLambda._atransformc                 K s6   | j || jt|ƒfi |¤Ž2 z3 d H W }|V  q6 d S rô   )r»  rF  r/   )rw   rä   r”   rÞ   rF  ry   ry   rz   rG  ™  s    ýüzRunnableLambda.atransformc                  sB   ddœ‡ fdd„}| j |ƒ |fi |¤Ž2 z3 d H W }|V  q(6 d S )NrE  r}   c                    s
   ˆ V  d S rô   ry   ry   rK  ry   rz   rL  ¯  s    z+RunnableLambda.astream.<locals>.input_aiterrM  rN  ry   rK  rz   r(  ¨  s    "zRunnableLambda.astream)NN)N)N)N)N)N)N)N)N)N)rs   rœ   rÂ  rÃ  rô  rÅ  r$   rŠ   r�   r�   r£   r%  Úcached_propertyr•  r§   rÃ   r€  r…  r  r   rª  rç   rè   rE  rD  r&  rF  rG  r(  rÛ  ry   ry   rÌ  rz   r†  Â  sb   R  ÞV ÿ- ÿ	-d ý ý> ý ýc ý ýr†  c                   @  sN  e Zd ZU dZded< edd�Zeeddœdd	„ƒƒZ	ed5dddœdd„ƒZ
eeddœdd„ƒƒZed6dddœdd„ƒZeeddœdd„ƒƒZed7dddœdd„ƒZeeddœdd„ƒƒZeeddœdd „ƒƒZd!d"d#dd$d%œd&d'„Zed8d!ddd$d(œd)d*„ƒZd!d+d#dd$d%œd,d-„Zed9d!ddd$d(œd.d/„ƒZed:d0dd1d2d(œd3d4„ƒZd
S );Ú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.

    rH  rI  Trý  r   r}   c                 C  s   t | jj S rô   )rù   rI  rŠ   r�   ry   ry   rz   rŠ   È  s    zRunnableEachBase.InputTypeNr’   rŽ   r“   c                 C  s(   t |  d¡t| j |¡ d f| jjd�S )Nr<   r•   )rU   r{   rù   rI  r�   rr   rœ   r¡   ry   ry   rz   r�   Í  s    þóz!RunnableEachBase.get_input_schemaztype[list[Output]]c                 C  s   t | jj S rô   )rù   rI  r�   r�   ry   ry   rz   r�   á  s    zRunnableEachBase.OutputTypec                 C  s(   | j  |¡}t|  d¡t| | jjd�S )Nr=   r•   )rI  r£   rU   r{   rù   rr   rœ   )rw   r”   rø  ry   ry   rz   r£   æ  s    öz"RunnableEachBase.get_output_schemar¦   c                 C  s   | j jS rô   ©rI  r§   r�   ry   ry   rz   r§   ø  s    zRunnableEachBase.config_specsr]   c                 C  s   | j  |¡S rô   )rI  rÃ   r¡   ry   ry   rz   rÃ   ý  s    zRunnableEachBase.get_graphrí   c                 C  s   dS rû  ry   rù  ry   ry   rz   rü    s    z#RunnableEachBase.is_lc_serializablerö  c                 C  s   g d¢S r÷  ry   rù  ry   ry   rz   rú    s    z!RunnableEachBase.get_lc_namespacerë   rW   r,   rï   rC  c                   s*   ‡ ‡fdd„|D ƒ}| j j||fi |¤ŽS )Nc                   s   g | ]}t ˆ ˆ ¡ d �‘qS r’  r“  r–  ©r”   r‡  ry   rz   r¶     s   z,RunnableEachBase._invoke.<locals>.<listcomp>)rI  rý   ©rw   rñ   r‡  r”   rÞ   rû   ry   r¯  rz   r     s    ÿzRunnableEachBase._invokerã   c                 K  s   | j | j||fi |¤ŽS rô   )rŠ  r   ræ   ry   ry   rz   rç     s    zRunnableEachBase.invokerV   c                 ‹  s0   ‡ ‡fdd„|D ƒ}| j j||fi |¤ŽI d H S )Nc                   s   g | ]}t ˆ ˆ ¡ d �‘qS r’  r“  r–  r¯  ry   rz   r¶   *  s   z-RunnableEachBase._ainvoke.<locals>.<listcomp>)rI  r  r°  ry   r¯  rz   rª  #  s    ÿzRunnableEachBase._ainvokec                 Ë  s   | j | j||fi |¤ŽI d H S rô   )r‹  rª  ræ   ry   ry   rz   rè   /  s    zRunnableEachBase.ainvoker<   rî   r<  c                 K s,   dddœdd„}t dƒD ]}|dƒV  qd S )Nrj   r_   )r5  rm   c                 S  s   t | ƒ‚d S rô   )r=  r¼  ry   ry   rz   Ú_error_stream_event<  s    z<RunnableEachBase.astream_events.<locals>._error_stream_eventrŒ   z1RunnableEach does not support astream_events yet.)r>  )rw   rä   r”   rÞ   r±  rp   ry   ry   rz   r?  5  s
    ÿzRunnableEachBase.astream_events)N)N)N)N)N)N)rs   rœ   rÂ  rÃ  rÄ  r   rÚ  rÅ  r$   rŠ   r�   r�   r£   r§   rÃ   rO  rü  rú  r   rç   rª  rè   r?  ry   ry   ry   rz   r­  ¶  sN   
ÿ ÿ ÿ ÿ ÿ ýr­  c                      s¢   e Zd ZdZedddœddddœ‡ fdd„ƒZed	d
dœdd„ƒZeddd	d
dœdd„ƒZeddddœdddd
dœdd„ƒZddddœdddd
dœdd„Z	‡  Z
S )rr  a‘  RunnableEach class.

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

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

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

        .. code-block:: python

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

    Nri   rg   rj   rk   c                  s,   |p| j pd| j ¡ › d�}tƒ j||d�S )NzRunnableEach<rS  ri   )rh   rI  r{   rÈ  rT  rÌ  ry   rz   r{   c  s    zRunnableEach.get_namer   zRunnableEach[Input, Output]rÝ   c                 K  s   t | jjf i |¤Žd�S ©Nrq  )rr  rI  rM  rL  ry   ry   rz   rM  j  s    zRunnableEach.bindr’   rN  c                 K  s   t | jj|fi |¤Žd�S r²  )rr  rI  rP  rO  ry   ry   rz   rP  n  s    zRunnableEach.with_configrQ  rU  rV  c                C  s   t | jj|||d�d�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. Defaults to None.
            on_end: Called after the ``Runnable`` finishes running, with the ``Run``
                object. Defaults to None.
            on_error: Called if the ``Runnable`` throws an error, with the ``Run``
                object. Defaults to None.

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

        rQ  rq  )rr  rI  r_  r^  ry   ry   rz   r_  t  s
     ÿÿzRunnableEach.with_listenersr`  c                C  s   t | jj|||d�d�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. Defaults to None.
            on_end: Called asynchronously after the ``Runnable`` finishes running,
                with the ``Run`` object. Defaults to None.
            on_error: Called asynchronously if the ``Runnable`` throws an error,
                with the ``Run`` object. Defaults to None.

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

        rQ  rq  )rr  rI  ra  r^  ry   ry   rz   ra  š  s
    ÿÿzRunnableEach.with_alisteners)N)N)rs   rœ   rÂ  rÃ  r$   r{   rM  rP  r_  ra  rÛ  ry   ry   rÌ  rz   rr  E  s(    ÿÿ ÿõ(ûrr  c                
      sD  e Zd ZU dZded< eed�Zded< eed�Z	ded< ee
d�Zd	ed
< dZded< dZded< edd�Zddddddœdddddddddœ‡ fdd„Zednddœddddœd d!„ƒZeed"d#œd$d%„ƒƒZeed&d#œd'd(„ƒƒZedodd)d*œ‡ fd+d,„ƒZedpdd)d*œ‡ fd-d.„ƒZeed/d#œd0d1„ƒƒZedqdd2d*œd3d4„ƒZeed5d#œd6d7„ƒƒZeed8d#œd9d:„ƒƒZddd;œd<d=„Zedrd>ddd?d@œdAdB„ƒZedsd>ddd?d@œdCdD„ƒZedtdEdFœdGdHd5ddIdJœdKdL„ƒZ edudEdFœdGdHd5ddIdJœdMdN„ƒZ!e"dvdEdFœdOdPdQddRdJœdSdT„ƒZ#e"dwdOdPdUddVdJœdWdT„ƒZ#edxdEdFœdOdPd5ddVdJœdXdT„ƒZ#e"dydEdFœdOdPdQddYdJœdZd[„ƒZ$e"dzdOdPdUdd\dJœd]d[„ƒZ$ed{dEdFœdOdPd5dd\dJœd^d[„ƒZ$ed|d>ddd_d@œd`da„ƒZ%ed}d>dddbd@œdcdd„ƒZ&ed~d>ddded@œdfdg„ƒZ'eddhddd_d@œdidj„ƒZ(ed€dkdddbd@œdldm„ƒZ)‡  Z*S )�Ú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.

    rH  rI  rî  zMapping[str, Any]rÞ   r,   r”   z0list[Callable[[RunnableConfig], RunnableConfig]]r]  Nrî   re  rf  Trý  )rÞ   r”   r]  re  rf  zOptional[Mapping[str, Any]]r’   z:Optional[list[Callable[[RunnableConfig], RunnableConfig]]]ú'Optional[Union[type[Input], BaseModel]]ú(Optional[Union[type[Output], BaseModel]]r   rò  )rI  rÞ   r”   r]  re  rf  Úother_kwargsrm   c             	     s:   t ƒ jf ||pi |pi |pg ||dœ|¤Ž |p2i | _dS )aW  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)
                Defaults to None.
            config: optional config to bind to the underlying ``Runnable``.
                Defaults to None.
            config_factories: optional list of config factories to apply to the
                config before binding to the underlying ``Runnable``.
                Defaults to None.
            custom_input_type: Specify to override the input type of the underlying
                ``Runnable`` with a custom type. Defaults to None.
            custom_output_type: Specify to override the output type of the underlying
                ``Runnable`` with a custom type. Defaults to None.
            **other_kwargs: Unpacked into the base class.
        ©rI  rÞ   r”   r]  re  rf  N)rÈ  rô  r”   )rw   rI  rÞ   r”   r]  re  rf  r¶  rÌ  ry   rz   rô  ë  s    !úùzRunnableBindingBase.__init__ri   rg   rj   rk   c                C  s   | j j||d�S )Nri   )rI  r{   rT  ry   ry   rz   r{     s    zRunnableBindingBase.get_namer|   r}   c                 C  s   | j d urtd| j ƒS | jjS )Nr|   )re  r   rI  rŠ   r�   ry   ry   rz   rŠ      s    ÿýzRunnableBindingBase.InputTyper‹   c                 C  s   | j d urtd| j ƒS | jjS )Nr‹   )rf  r   rI  r�   r�   ry   ry   rz   r�   )  s    ÿýzRunnableBindingBase.OutputTyperŽ   r“   c                   s*   | j d urtƒ  |¡S | j t| j|ƒ¡S rô   )re  rÈ  r�   rI  r4   r”   r¡   rÌ  ry   rz   r�   2  s    
z$RunnableBindingBase.get_input_schemac                   s*   | j d urtƒ  |¡S | j t| j|ƒ¡S rô   )rf  rÈ  r£   rI  r4   r”   r¡   rÌ  ry   rz   r£   :  s    
z%RunnableBindingBase.get_output_schemar¦   c                 C  s   | j jS rô   r®  r�   ry   ry   rz   r§   B  s    z RunnableBindingBase.config_specsr]   c                 C  s   | j  |  |¡¡S rô   )rI  rÃ   Ú_merge_configsr¡   ry   ry   rz   rÃ   G  s    zRunnableBindingBase.get_graphrí   c                 C  s   dS rû  ry   rù  ry   ry   rz   rü  K  s    z&RunnableBindingBase.is_lc_serializablerö  c                 C  s   g d¢S r÷  ry   rù  ry   ry   rz   rú  Q  s    z$RunnableBindingBase.get_lc_namespace)rû   rm   c                   s2   t | jg|¢R Ž ‰ t ˆ g‡ fdd„| jD ƒ¢R Ž S )Nc                 3  s   | ]}|ˆ ƒV  qd S rô   ry   )r¯   r¨  rÆ   ry   rz   r�  ]  r·   z5RunnableBindingBase._merge_configs.<locals>.<genexpr>)r4   r”   r]  )rw   rû   ry   rÆ   rz   r¸  [  s    z"RunnableBindingBase._merge_configsr<   r=   rã   c                 K  s&   | j j||  |¡fi i | j¥|¥¤ŽS rô   )rI  rç   r¸  rÞ   ræ   ry   ry   rz   rç   _  s    þýzRunnableBindingBase.invokec                 Ë  s,   | j j||  |¡fi i | j¥|¥¤ŽI d H S rô   )rI  rè   r¸  rÞ   ræ   ry   ry   rz   rè   l  s    þýzRunnableBindingBase.ainvokeFré   rë   rì   rï   rð   c                  sd   t ˆ tƒr$td‡fdd„ˆ D ƒƒ}n‡ ‡fdd„tt|ƒƒD ƒ}ˆjj||fd|ii ˆj¥|¥¤ŽS )Núlist[RunnableConfig]c                   s   g | ]}ˆ   |¡‘qS ry   ©r¸  ©r¯   Úconfr�   ry   rz   r¶   …  r·   z-RunnableBindingBase.batch.<locals>.<listcomp>c                   s   g | ]}ˆ  ˆ ¡‘qS ry   rº  r–  ©r”   rw   ry   rz   r¶   ˆ  r·   rê   )rš   rù   r   r>  rƒ   rI  rý   rÞ   ©rw   rñ   r”   rê   rÞ   rû   ry   r½  rz   rý   y  s    	
þþýüzRunnableBindingBase.batchc                ‹  sj   t ˆ tƒr$td‡fdd„ˆ D ƒƒ}n‡ ‡fdd„tt|ƒƒD ƒ}ˆjj||fd|ii ˆj¥|¥¤ŽI d H S )Nr¹  c                   s   g | ]}ˆ   |¡‘qS ry   rº  r»  r�   ry   rz   r¶   œ  r·   z.RunnableBindingBase.abatch.<locals>.<listcomp>c                   s   g | ]}ˆ  ˆ ¡‘qS ry   rº  r–  r½  ry   rz   r¶   Ÿ  r·   rê   )rš   rù   r   r>  rƒ   rI  r  rÞ   r¾  ry   r½  rz   r  �  s    	
þþýüzRunnableBindingBase.abatchrþ   rÿ   r   r  c                K  s   d S rô   ry   r  ry   ry   rz   r  §  s    z&RunnableBindingBase.batch_as_completedr  r  c                K  s   d S rô   ry   r  ry   ry   rz   r  ±  s    c                +  sž   t ˆ tƒr$td‡fdd„ˆ D ƒƒ}n‡ ‡fdd„tt|ƒƒD ƒ}|rpˆjj||fd|ii ˆj¥|¥¤ŽE d H  n*ˆjj||fd|ii ˆj¥|¥¤ŽE d H  d S )Nr¹  c                   s   g | ]}ˆ   |¡‘qS ry   rº  r»  r�   ry   rz   r¶   Ç  r·   z:RunnableBindingBase.batch_as_completed.<locals>.<listcomp>c                   s   g | ]}ˆ  ˆ ¡‘qS ry   rº  r–  r½  ry   rz   r¶   Ê  r·   rê   )rš   r   r   r>  rƒ   rI  r  rÞ   r¾  ry   r½  rz   r  »  s.    	
þþýüþýür  c                K  s   d S rô   ry   r  ry   ry   rz   r  Û  s    z'RunnableBindingBase.abatch_as_completedr  c                K  s   d S rô   ry   r  ry   ry   rz   r  å  s    c                 s¾   t ˆ tƒr$td‡fdd„ˆ D ƒƒ}n‡ ‡fdd„tt|ƒƒD ƒ}|r€ˆjj||fd|ii ˆj¥|¥¤Ž2 z3 d H W }|V  qh6 n:ˆjj||fd|ii ˆj¥|¥¤Ž2 z3 d H W }|V  q¤6 d S )Nr¹  c                   s   g | ]}ˆ   |¡‘qS ry   rº  r»  r�   ry   rz   r¶   û  r·   z;RunnableBindingBase.abatch_as_completed.<locals>.<listcomp>c                   s   g | ]}ˆ  ˆ ¡‘qS ry   rº  r–  r½  ry   rz   r¶   þ  r·   rê   )rš   r   r   r>  rƒ   rI  r  rÞ   )rw   rñ   r”   rê   rÞ   rû   r9  ry   r½  rz   r  ï  s2    	
þþýüþýür%  c                 k  s0   | j j||  |¡fi i | j¥|¥¤ŽE d H  d S rô   )rI  r&  r¸  rÞ   ræ   ry   ry   rz   r&    s    þýzRunnableBindingBase.streamr'  c                 K s@   | j j||  |¡fi i | j¥|¥¤Ž2 z3 d H W }|V  q&6 d S rô   )rI  r(  r¸  rÞ   ©rw   rä   r”   rÞ   r9  ry   ry   rz   r(    s    þýzRunnableBindingBase.astreamr<  c                 K s@   | j j||  |¡fi i | j¥|¥¤Ž2 z3 d H W }|V  q&6 d S rô   )rI  r?  r¸  rÞ   r¿  ry   ry   rz   r?  +  s    
ÿÿz"RunnableBindingBase.astream_eventsr@  c                 k  s0   | j j||  |¡fi i | j¥|¥¤ŽE d H  d S rô   )rI  rD  r¸  rÞ   ræ   ry   ry   rz   rD  7  s    þýzRunnableBindingBase.transformrE  c                 K s@   | j j||  |¡fi i | j¥|¥¤Ž2 z3 d H W }|V  q&6 d S rô   )rI  rG  r¸  rÞ   r¿  ry   ry   rz   rG  D  s    þýzRunnableBindingBase.atransform)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)+rs   rœ   rÂ  rÃ  rÄ  r    rá   rÞ   r,   r”   rù   r]  re  rf  r   rÚ  rô  r$   r{   rÅ  rŠ   r�   r�   r£   r§   rÃ   rO  rü  rú  r¸  rç   rè   rý   r  r   r  r  r&  r(  r?  rD  rG  rÛ  ry   ry   rÌ  rz   r³  ¼  sÐ   
		ÿÿö$/ ÿÿ ÿ ÿ ý ý ýû ýû ýû	 ý	 ýû ýû	 ý	 ýû  ý ý ý ý ýr³  c                   @  sž   e Zd ZdZedddœdd„ƒZeddddd	œd
d„ƒZeddddœdddddœdd„ƒZedddddœdd„ƒZedddœdd„ƒZ	edddœdd„ƒZ
dS )rK  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.

        .. code-block:: python

            # Create a Runnable binding that invokes the ChatModel with the
            # additional kwarg `stop=['-']` when running it.
            from langchain_community.chat_models import ChatOpenAI

            model = ChatOpenAI()
            model.invoke('Say "Parrot-MAGIC"', stop=["-"])  # Should return `Parrot`
            # Using it the easy way via `bind` method which returns a new
            # RunnableBinding
            runnable_binding = model.bind(stop=["-"])
            runnable_binding.invoke('Say "Parrot-MAGIC"')  # Should return `Parrot`

        Can also be done by instantiating a ``RunnableBinding`` directly (not
        recommended):

        .. code-block:: 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`

    r   rH  rÝ   c                 K  s*   | j | j| j| ji | j¥|¥| j| jd�S )a0  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.

        )rI  r”   r]  rÞ   re  rf  )rr   rI  r”   r]  rÞ   re  rf  rL  ry   ry   rz   rM  ‰  s    úzRunnableBinding.bindNr’   rN  c                 K  s8   | j | j| jtdi | j¥|pi ¥|¥ƒ| j| j| jd�S )Nr,   r·  )rr   rI  rÞ   r   r”   r]  re  rf  rO  ry   ry   rz   rP  ž  s    úzRunnableBinding.with_configrQ  rU  rV  c                  s@   dddœ‡ ‡‡fdd„}| j | j| j| j|g| j¢| j| jd�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. Defaults to None.
            on_end: Called after the ``Runnable`` finishes running, with the ``Run``
                object. Defaults to None.
            on_error: Called if the ``Runnable`` throws an error, with the ``Run``
                object. Defaults to None.

        Returns:
            A new ``Runnable`` with the listeners bound.
        r,   r“   c                   s   dt | ˆˆ ˆd�giS rW  rY  rÆ   rZ  ry   rz   Úlistener_config_factoryÎ  s    üÿÿz?RunnableBinding.with_listeners.<locals>.listener_config_factoryr·  ©rr   rI  rÞ   r”   r]  re  rf  )rw   rR  rS  rT  rÀ  ry   rZ  rz   r_  ®  s     
úzRunnableBinding.with_listenersr´  rµ  rd  c                 C  s:   | j | j| j| j| j|d ur |n| j|d ur0|n| jd�S )Nr·  rÁ  rg  ry   ry   rz   rh  ã  s    ÷zRunnableBinding.with_typesc                 K  s&   | j | jjf i |¤Ž| j| j| jd�S )N)rI  rÞ   r”   r]  )rr   rI  rp  rÞ   r”   r]  rL  ry   ry   rz   rp  ö  s    üzRunnableBinding.with_retryrj   )rh   rm   c                   sª   t ˆj|ƒ‰ tˆ ƒr¦t ˆ ¡j d¡ }r¦|jtjj	kr\t
ˆ ƒddddœ‡ ‡fdd„ƒ}|S |jtjjkr¦tt ˆ ¡jƒ d¡‰t
ˆ ƒddddœ‡ ‡‡fdd„ƒ}|S ˆ S )Nr”   r   r¤  c               	     s"   ˆ | dt ˆj| dd ¡ƒi|¤ŽS )Nr”   )r4   r”   r  r¦  )Úattrrw   ry   rz   Úwrapper  s    ÿþýz,RunnableBinding.__getattr__.<locals>.wrapperc               	     s\   t | ƒˆd kr:t| ƒ}tˆj|ˆ ƒ|ˆ< ˆ |i |¤ŽS ˆ | dtˆj| dd ¡ƒi|¤ŽS )NrŒ   r”   )rƒ   rù   r4   r”   r  )r~   rÞ   Zargsl©rÂ  r  rw   ry   rz   rÃ    s    ÿþý)rs  rI  r‰  r˜   rt  ru  r¾   Úkindrv  ÚKEYWORD_ONLYr   ÚPOSITIONAL_OR_KEYWORDrù   Úindex)rw   rh   Zconfig_paramrÃ  ry   rÄ  rz   Ú__getattr__ÿ  s    ÿzRunnableBinding.__getattr__)N)NN)rs   rœ   rÂ  rÃ  r$   rM  rP  r_  rh  rp  rÉ  ry   ry   ry   rz   rK  S  s&   5 þõ4  ýrK  c                   @  s   e Zd Zddddœdd„ZdS )Ú_RunnableCallableSyncr<   r,   r=   ©Ú_inr”   rm   c               C  s   d S rô   ry   ©rw   rÌ  r”   ry   ry   rz   Ú__call__&  r·   z_RunnableCallableSync.__call__N©rs   rœ   rÂ  rÎ  ry   ry   ry   rz   rÊ  %  s   rÊ  c                   @  s   e Zd Zddddœdd„ZdS )Ú_RunnableCallableAsyncr<   r,   zAwaitable[Output]rË  c               C  s   d S rô   ry   rÍ  ry   ry   rz   rÎ  *  s    z_RunnableCallableAsync.__call__NrÏ  ry   ry   ry   rz   rÐ  )  s   rÐ  c                   @  s   e Zd Zddddœdd„ZdS )Ú_RunnableCallableIteratorr@  r,   r%  rË  c               C  s   d S rô   ry   rÍ  ry   ry   rz   rÎ  0  s    z"_RunnableCallableIterator.__call__NrÏ  ry   ry   ry   rz   rÑ  /  s   rÑ  c                   @  s   e Zd Zddddœdd„ZdS )Ú_RunnableCallableAsyncIteratorrE  r,   r'  rË  c               C  s   d S rô   ry   rÍ  ry   ry   rz   rÎ  6  s    z'_RunnableCallableAsyncIterator.__call__NrÏ  ry   ry   ry   rz   rÒ  5  s   rÒ  rñ  rH  )Úthingrm   c                 C  sp   t | tƒr| S t| ƒs t | ¡r(t| ƒS t| ƒr>ttd| ƒƒS t | t	ƒrVtdt
| ƒƒS dt| ƒ› �}t|ƒ‚dS )zßCoerce 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ˆ  rH  zGExpected a Runnable, callable or dict.Instead got an unsupported type: N)rš   rf   rI   r˜   rn  rm  r‰  r†  r   rá   rà   rÐ  r…   )rÓ  r‰   ry   ry   rz   rÑ   I  s    

ÿÿrÑ   z.Callable[[Input], Coroutine[Any, Any, Output]])ry  rm   c                 C  s   d S rô   ry   ©ry  ry   ry   rz   Úchaind  s    rÕ  r™  c                 C  s   d S rô   ry   rÔ  ry   ry   rz   rÕ  j  s    z(Callable[[Input], AsyncIterator[Output]]c                 C  s   d S rô   ry   rÔ  ry   ry   rz   rÕ  p  s    rˆ  c                 C  s   d S rô   ry   rÔ  ry   ry   rz   rÕ  v  s    zŸUnion[Callable[[Input], Output], Callable[[Input], Iterator[Output]], Callable[[Input], Coroutine[Any, Any, Output]], Callable[[Input], AsyncIterator[Output]]]c                 C  s   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:

    .. code-block:: 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}!")
            llm = OpenAI()
            formatted = prompt.invoke(**fields)

            for chunk in llm.stream(formatted):
                yield chunk

    )r†  rÔ  ry   ry   rz   rÕ  |  s    &)žrÃ  Ú
__future__r   r"  r’  rÊ  r%  r˜   ri  r“  r   r   Úcollections.abcr   r   r   r   r	   r
   r   Úconcurrent.futuresr   r   r   Ú	itertoolsr   r   Úoperatorr   Útypesr   Útypingr   r   r   r   r   r   r   r   r   r   r   Zpydanticr   r   r    r!   Ztyping_extensionsr"   r#   r$   Zlangchain_core._apir%   Zlangchain_core._api.deprecationr&   Z langchain_core.callbacks.managerr'   r(   Z langchain_core.load.serializabler)   r*   r+   Zlangchain_core.runnables.configr,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   Zlangchain_core.runnables.utilsr8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   Z!langchain_core.tracers._streamingrJ   Z#langchain_core.tracers.event_streamrK   rL   Z!langchain_core.tracers.log_streamrM   rN   Z%langchain_core.tracers.root_listenersrO   rP   Zlangchain_core.utils.aiterrQ   rR   rS   Zlangchain_core.utils.iterrT   Zlangchain_core.utils.pydanticrU   rV   rW   rÇ   rY   rw  r[   ZRunnableWithFallbacksTr¼   r]   ro  r^   Zlangchain_core.runnables.schemar_   rÀ  r`   ra   rb   rc   Zlangchain_core.tracers.schemasrd   re   rf   rÇ  ræ  rë  rÐ   rá   rj   rà   ZRunnableMaprm  r†  rù   r­  rr  r³  rK  rÊ  rÐ  rÑ  rÒ  rñ  rÑ   rÕ  ry   ry   ry   rz   Ú<module>   sø   $	48P                   w 3      >       9     y  w    S





÷ÿ