
    gh^                      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l6m7Z7m8Z8m9Z9 ddl:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZF ddlGmHZH ddlImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[ ddl\m]Z]m^Z^m_Z_ ddl`maZa ddlbmcZc e r:ddldmeZemfZf ddlgmhZh ddlimjZk ddllmmZm ddlnmoZo ddlpmqZq ddlrmsZsmtZt ddlumvZv ddlwmxZx  e&d          Zy G d  d!e#eNeOf         e
          Zz G d" d#e7ezeNeOf                   Z{dSd*Z|dSd+Z} G d, d-e{eNeOf                   Z~ G d. d/e{eNeee!f         f                   ZeZ G d0 d1ezeNeOf                   Z G d2 d3ezeNeOf                   Z G d4 d5e{eeN         eeO         f                   Z G d6 d7eeNeOf                   Z G d8 d9e{eNeOf                   Z G d: d;eeNeOf                   Z G d< d=e%eNeOf                   Z G d> d?e%eNeOf                   Z G d@ dAe%eNeOf                   Z G dB dCe%eNeOf                   Ze'ezeNeOf         e"eNgeOf         e"eNgeeO         f         e"eeN         geeO         f         e"eeN         geeO         f         eeNeOf         eeNeOf         eeNeOf         eeNeOf         eee!f         f
         ZdTdGZe*dUdJ            Ze*dVdL            Ze*dWdN            Ze*dXdP            ZdYdRZdS )Zz)Base classes and utilities for Runnables.    )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)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Graph)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)aclosingateepy_anext)safetee)create_model_v2)AsyncCallbackManagerForChainRunCallbackManagerForChainRunBasePromptTemplateRunnableWithFallbacks)ExponentialJitterParams)StreamEvent)BaseTool)RunLogRunLogPatch)AsyncListener)RunOtherc                     e Zd ZU dZded<   	 	 ddddd	Zedd            Zedd            Zedd            Z		 dddZ
	 dddZedd            Z	 dddZ	 dddZedd            ZddddZddddZddd Z	 ddd"Zdd&Zdd)Zdddd,Zdd0Zdd3Z	 e	 ddd8            Z	 ddd9Z	 dd:d;ddCZe	 dd:d;ddH            Ze	 dddK            Z	 dd:d;ddLZ	 dd:d;ddMZe	 dd:d;ddO            Z e	 dddQ            Z 	 dd:d;ddRZ 	 dddTZ!	 dddVZ"e	 ddWdWdddddddXddb            Z#e	 ddWdddddddcdde            Z#	 ddWdWdddddddXddgZ#	 ddhdddddddiddmZ$	 dddoZ%	 dddqZ&ddsZ'	 dddtZ(dddduddzZ)ddddudd|Z*ddd}ddZ+e,fdWdddddZ-ddZ.e,fddddZ/	 	 	 dddZ0	 	 dddZ1	 dd:ddddZ2	 dd:ddddZ3	 dddZ4	 dddZ5 e6j7        d          	 ddddddd            Z8dS )Runnablea  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 Runnables 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 Runnables. 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r`   suffixreturnstrc               v   |r|}nft          | d          r| j        r| j        }nG| j        }t          |d          r)d|j        v r |j        d         |j        d         j        }n|j        }|rK|d                                         r||                                z   S |dz   |                                z   S |S )zGet the name of the Runnable.r`   __pydantic_generic_metadata__originNr   _)hasattrr`   	__class__rf   __name__isuppertitlelower)selfrb   r`   name_clss        Z/var/www/FlaskApp/flask-venv/lib/python3.11/site-packages/langchain_core/runnables/base.pyget_namezRunnable.get_name   s      	%EET6"" 	%ty 	%IEE .C 3 
%
  AAA5h?K9(CL 	0Qx!! .v||~~--3;//    type[Input]c                   | j                                         D ]F}t          |d          r4|j        }d|v r)t	          |d                   dk    r|d         d         c S G| j         j        D ]0}t          |          }|rt	          |          dk    r
|d         c S 1d|                                  d}t          |          )zGThe type of input this Runnable accepts specified as a type annotation.rf   args   r   	Runnable z` doesn't have an inferable InputType. Override the InputType property to specify the input type.	rj   mrori   rf   len__orig_bases__r$   rs   	TypeErrorro   basemetadatarq   	type_argsmsgs         rr   	InputTypezRunnable.InputType  s     N&&(( 	/ 	/Dt<== /=X%%#hv.>*?*?1*D*D#F+A....
 >0 	$ 	$C I $S^^q00 |###I I I I 	 nnrt   type[Output]c                   | j                                         D ]F}t          |d          r4|j        }d|v r)t	          |d                   dk    r|d         d         c S G| j         j        D ]0}t          |          }|rt	          |          dk    r
|d         c S 1d|                                  d}t          |          )zIThe type of output this Runnable produces specified as a type annotation.rf   rw   rx      ry   zc doesn't have an inferable OutputType. Override the OutputType property to specify the output type.rz   r   s         rr   
OutputTypezRunnable.OutputType.  s    
 N&&(( 	/ 	/Dt<== /=X%%#hv.>*?*?1*D*D#F+A....>0 	$ 	$C I $S^^q00 |###K K K K 	 nnrt   type[BaseModel]c                *    |                                  S )zFThe type of input this Runnable accepts specified as a pydantic model.)get_input_schemaro   s    rr   input_schemazRunnable.input_schemaD  s     $$&&&rt   configOptional[RunnableConfig]c                    | j         }t          j        |          r,t          |t                    st          |t                    r|S t          |                     d          || j	        j
                  S )a  Get a pydantic model that can be used to validate input to the Runnable.

        Runnables that leverage the configurable_fields and configurable_alternatives
        methods will have a dynamic input schema that depends on which
        configuration the Runnable is invoked with.

        This method allows to get an input schema for a specific configuration.

        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   rN   rs   rj   
__module__ro   r   	root_types      rr   r   zRunnable.get_input_schemaI  s    $ N	 OI&&	y,77	 9i00	
 MM'"" 1
 
 
 	
rt   dict[str, Any]c                P    |                      |                                          S )aA  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ro   r   s     rr   get_input_jsonschemazRunnable.get_input_jsonschemaq  s$    4 $$V,,>>@@@rt   c                *    |                                  S )zHThe type of output this Runnable produces specified as a pydantic model.)get_output_schemar   s    rr   output_schemazRunnable.output_schema  s     %%'''rt   c                    | j         }t          j        |          r,t          |t                    st          |t                    r|S t          |                     d          || j	        j
                  S )a  Get a pydantic model that can be used to validate output to the Runnable.

        Runnables that leverage the configurable_fields and configurable_alternatives
        methods will have a dynamic output schema that depends on which
        configuration the Runnable is invoked with.

        This method allows to get an output schema for a specific configuration.

        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   rN   rs   rj   r   r   s      rr   r   zRunnable.get_output_schema  s    $ O	 OI&&	y,77	 9i00	
 MM(## 1
 
 
 	
rt   c                P    |                      |                                          S )aD  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   s     rr   get_output_jsonschemazRunnable.get_output_jsonschema  s$    4 %%f--??AAArt   list[ConfigurableFieldSpec]c                    g S )z+List configurable fields for this Runnable. r   s    rr   config_specszRunnable.config_specs  s	     	rt   includer   Optional[Sequence[str]]c                  pg | j         }|rt          dd |D                       nd}i |rd|dfini fdt          t                                                    D             }t          |                     d          |          S )as  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.
        Configurablec           	     j    i | ]0}|j         |j        t          |j        |j        |j                   f1S ))rm   description)id
annotationr!   defaultr`   r   .0specs     rr   
<dictcomp>z*Runnable.config_schema.<locals>.<dictcomp>  sV     # # #  G L	tGW  # # #rt   field_definitionsNconfigurablec                <    i | ]\  }}|d  D             v ||dfS )c                    g | ]
}|d k    |S )r   r   )r   is     rr   
<listcomp>z5Runnable.config_schema.<locals>.<dictcomp>.<listcomp>  s"    !L!L!L^8K8K!8K8K8Krt   Nr   )r   
field_name
field_typer   s      rr   r   z*Runnable.config_schema.<locals>.<dictcomp>  sH       *J
!L!LW!L!L!LLL Z.LLLrt   Config)r   rN   r   r*   itemsrs   )ro   r   r   r   
all_fieldss    `   rr   config_schemazRunnable.config_schema  s     -R( O# # !-# # #     	$
9EMt 4552
   .<^.L.L.R.R.T.T  

 t}}X66*UUUUrt   c               R    |                      |                                          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   )ro   r   s     rr   get_config_jsonschemazRunnable.get_config_jsonschema  s'     !!'!22DDFFFrt   r7   c                   t                      }	 |                    |                     |                    }nE# t          $ r8 |                    t	          |                     d                              }Y nw xY w|                    | |r|                    d          nd          }	 |                    |                     |                    }nE# t          $ r8 |                    t	          |                     d                              }Y nw xY w|                    ||           |                    ||           |S )z/Return a graph representation of this Runnable.r<   r   N)r   r=   )	r7   add_noder   r~   rN   rs   getr   add_edge)ro   r   graph
input_noderunnable_nodeoutput_nodes         rr   	get_graphzRunnable.get_graph  sI   	Q(=(=f(E(EFFJJ 	Q 	Q 	Qg8N8N(O(OPPJJJ	QVE6::j111 ' 
 
	S..)?)?)G)GHHKK 	S 	S 	S..x9P9P)Q)QRRKKK	Sz=111}k222s!   (9 ?A;:A;-(C ?DDlist[BasePromptTemplate]c                    ddl m fd|                     |          j                                        D             S )z/Return a list of prompts used by this Runnable.r   rQ   c                H    g | ]}t          |j                  |j        S r   )r   data)r   noderR   s     rr   r   z(Runnable.get_prompts.<locals>.<listcomp>.  s>     
 
 
$)%788
I
 
 
rt   )r   )langchain_core.prompts.baserR   r   nodesvalues)ro   r   rR   s     @rr   get_promptszRunnable.get_prompts(  s`     	CBBBBB
 
 
 
f55;BBDD
 
 
 	
rt   otherUnion[Runnable[Any, Other], Callable[[Any], Other], Callable[[Iterator[Any]], Iterator[Other]], Mapping[str, Union[Runnable[Any, Other], Callable[[Any], Other], Any]]]"RunnableSerializable[Input, Other]c                <    t          | t          |                    S zGCompose this Runnable with another object to create a RunnableSequence.RunnableSequencecoerce_to_runnablero   r   s     rr   __or__zRunnable.__or__4  s      &8&?&?@@@rt   Union[Runnable[Other, Any], Callable[[Other], Any], Callable[[Iterator[Other]], Iterator[Any]], Mapping[str, Union[Runnable[Other, Any], Callable[[Other], Any], Any]]]#RunnableSerializable[Other, Output]c                <    t          t          |          |           S r   r   r   s     rr   __ror__zRunnable.__ror__@  s       25 9 94@@@rt   others3Union[Runnable[Any, Other], Callable[[Any], Other]]c               "    t          | g|R d|iS )a  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]
        r`   )r   )ro   r`   r   s      rr   pipezRunnable.pipeL  s#    D  9v999D999rt   keysUnion[str, list[str]]RunnableSerializable[Any, Any]c                *    ddl m} |  ||          z  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]"}

        r   )RunnablePick)$langchain_core.runnables.passthroughr   )ro   r   r   s      rr   pickzRunnable.pickp  s-    b 	FEEEEEll4((((rt   kwargsUnion[Runnable[dict[str, Any], Any], Callable[[dict[str, Any]], Any], Mapping[str, Union[Runnable[dict[str, Any], Any], Callable[[dict[str, Any]], Any]]]]c                ~    ddl m} |  |t          t          t          t
          f                  |                    z  S )a  Assigns new fields to the dict output of this Runnable.

        Returns a new 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'}}}

        r   )RunnableAssign)r   r   RunnableParalleldictrd   r   )ro   r   r   s      rr   assignzRunnable.assign  sC    T 	HGGGGGnn%5d38n%Ef%M%MNNNNrt   inputr<   r   r=   c                    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.

        Returns:
            The output of the Runnable.
        Nr   ro   r   r   r   s       rr   invokezRunnable.invoke        rt   c                <   K   t          || j        ||fi | d{V S )a'  Default implementation of ainvoke, calls invoke from a thread.

        The default implementation allows usage of async code even if
        the Runnable did not implement a native async version of invoke.

        Subclasses should override this method if they can run asynchronously.
        N)r4   r   r   s       rr   ainvokezRunnable.ainvoke  s8       %VT[%RR6RRRRRRRRRrt   Freturn_exceptionsinputslist[Input]5Optional[Union[RunnableConfig, list[RunnableConfig]]]r  boolOptional[Any]list[Output]c                   |sg S t          |t          |                    }d fd}t          |          dk    r't          d	 ||d
         |d
                   g          S t          |d
                   5 }t          d	t	          |                    |||                              cddd           S # 1 swxY w Y   dS )aK  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.
        r   r<   r   r*   rc   Union[Output, Exception]c                x    r)	  j         | |fi S # t          $ r}|cY d }~S d }~ww xY w j         | |fi S Nr   	Exceptionr   r   er   r  ro   s      rr   r   zRunnable.batch.<locals>.invoke  sx      <&4;uf?????    HHHHHH #t{5&;;F;;;s    
*%**r   r  r   Nr   r<   r   r*   rc   r	  )r0   r|   r   r1   listmap)ro   r  r   r  r   configsr   executors   `  ``   rr   batchzRunnable.batch  s6     	I!&#f++66	< 	< 	< 	< 	< 	< 	< 	< v;;!q	71:)F)F(GHHH$WQZ00 	UHX\\&&'-R-R(S(STT	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	Us   <2B;;B?B?Sequence[Input]9Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]Literal[False]Iterator[tuple[int, Output]]c                   d S r  r   ro   r  r   r  r   s        rr   batch_as_completedzRunnable.batch_as_completed  	     (+srt   Literal[True].Iterator[tuple[int, Union[Output, Exception]]]c                   d S r  r   r  s        rr   r  zRunnable.batch_as_completed!  	     :=rt   c             +  |   	
K   |sdS t          |t          |                    }d fd

t          |          dk    r 
d|d         |d                   V  dS t          |d                   5 		
fdt          t	          ||                    D             }	 |rGt          |t                    \  }}|r*|                                                                V  |*|G|D ]}|	                                 n# |D ]}|	                                 w xY w	 ddd           dS # 1 swxY w Y   dS )z^Run invoke in parallel on a list of inputs.

        Yields results as they complete.
        Nr   intr   r<   r   r*   rc   $tuple[int, Union[Output, Exception]]c                    r*	  j         ||fi }n(# t          $ r}|}Y d }~nd }~ww xY w j         ||fi }| |fS r  r  r   r   r   outr  r   r  ro   s        rr   r   z+Runnable.batch_as_completed.<locals>.invoke<  s     ! ;4?DKv4X4XQW4X4XCC    CCCCCC "dk%::6::s8Os    
+&+r   r   c                L    h | ] \  }\  }}                     |||          !S r   submit)r   r   r   r   r  r   s       rr   	<setcomp>z.Runnable.batch_as_completed.<locals>.<setcomp>N  sC       &Av 5&99  rt   return_whenr   r#  r   r<   r   r*   rc   r$  )
r0   r|   r1   	enumeratezipr   r   popresultcancel)ro   r  r   r  r   r  futuresdonefuturer  r   s   `  ``    @@rr   r  zRunnable.batch_as_completed+  s       	F!&#f++66	 	 	 	 	 	 	 	 v;;!&F1Iwqz22222F$WQZ00 	$H    *3C4H4H*I*I  G
$ 2$(o$N$N$NMD' 2"hhjj//11111  2  2
 & $ $FMMOOOO$g $ $FMMOOOO$ $	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$s+   6+D1"A	D+D1D  D11D58D5c                   K   |sg S t          |t          |                    }d fd}t          |||          }t          |d                             d	          g|R   d
{V 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   r*   rc   r	  c                   K   r/	  j         | |fi  d {V S # t          $ r}|cY d }~S d }~ww xY w j         | |fi  d {V S r  r   r  r  s      rr   r   z Runnable.abatch.<locals>.ainvoke~  s       ! C!-eV!F!Fv!F!FFFFFFFF    HHHHHH *T\%BB6BBBBBBBBBs    
2-22r   max_concurrencyNr  )r0   r|   r  rB   r   )ro   r  r   r  r   r  r   coross   `  ``   rr   abatchzRunnable.abatch\  s      :  	I!&#f++66		C 		C 		C 		C 		C 		C 		C 		C GVW--,WQZ^^<M-N-NWQVWWWWWWWWWWrt   !AsyncIterator[tuple[int, Output]]c                   d S r  r   r  s        rr   abatch_as_completedzRunnable.abatch_as_completed  	     -0Crt   3AsyncIterator[tuple[int, Union[Output, Exception]]]c                   d S r  r   r  s        rr   r?  zRunnable.abatch_as_completed  
     ?Bcrt   c              l   	
K   |sdS t          |t          |                    }|r|d                             d          nd}|rt          j        |          nd
d fd		
fdt          t          ||                    D             }t          j        |          D ]}| d{V W V  dS )aC  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. 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   r*   rc   r$  c                   K   r0	  j         ||fi  d {V }n.# t          $ r}|}Y d }~nd }~ww xY w j         ||fi  d {V }| |fS r  r9  r&  s        rr   ainvoke_taskz2Runnable.abatch_as_completed.<locals>.ainvoke_task  s       ! B:F$,v; ;)/; ; 5 5 5 5 5 5CC !   CCCCCC )DLAA&AAAAAAAAs8Os    
3.3c           
     p    g | ]2\  }\  }}rt           |||                    n |||          3S r   )rA   )r   r   r   r   rF  	semaphores       rr   r   z0Runnable.abatch_as_completed.<locals>.<listcomp>  sf     
 
 
 #?E6 0Jy,,q%"@"@AAAa//
 
 
rt   r.  )r0   r|   r   asyncio	Semaphorer/  r0  as_completed)ro   r  r   r  r   r  r:  r;  cororF  rH  s   `  ``    @@rr   r?  zRunnable.abatch_as_completed  s     4  	F!&#f++66?FP'!*..):;;;D:ISG%o666t		 	 	 	 	 	 	 	
 
 
 
 
 '0FG0D0D&E&E	
 
 
 (// 	 	D******	 	rt   Iterator[Output]c              +  ,   K    | 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   s       rr   streamzRunnable.stream  s0      $ dk%2262222222rt   AsyncIterator[Output]c               :   K    | j         ||fi | d{V W 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   s       rr   astreamzRunnable.astream  sE      $ !DL99&99999999999999rt   T)diffwith_streamed_output_listinclude_namesinclude_typesinclude_tagsexclude_namesexclude_typesexclude_tagsrS  rT  rU  rV  rW  rX  rY  rZ  AsyncIterator[RunLogPatch]c                   d S r  r   ro   r   r   rS  rT  rU  rV  rW  rX  rY  rZ  r   s               rr   astream_logzRunnable.astream_log  s	     &)Srt   )rT  rU  rV  rW  rX  rY  rZ  AsyncIterator[RunLog]c                   d S r  r   r]  s               rr   r^  zRunnable.astream_log  s	     !$rt   8Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]c          
    z   K   ddl m}m}  |d|||||	|
d          } || ||f|||d|2 3 d{V }|W V  6 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.
        r   )LogStreamCallbackHandler_astream_log_implementationForiginal)
auto_closerU  rV  rW  rX  rY  rZ  _schema_format)rS  rO  rT  N)!langchain_core.tracers.log_streamrc  rd  )ro   r   r   rS  rT  rU  rV  rW  rX  rY  rZ  r   rc  rd  rO  items                   rr   r^  zRunnable.astream_log$  s      R	
 	
 	
 	
 	
 	
 	
 	

 *)''%''%%	
 	
 	
 65
 &?
 
 
 
 		 		 		 		 		 		 		$ JJJJJ
 
 
s   :v2)versionrU  rV  rW  rX  rY  rZ  rk  Literal['v1', 'v2']AsyncIterator[StreamEvent]c              6  K   ddl m}m} |dk    r || |f|||||||	d|
}n*|dk    r || |f|||||||	d|
}nd}t          |          t	          |          4 d{V  |2 3 d{V }|W V  6 	 ddd          d{V  dS # 1 d{V swxY w Y   dS )as5  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.

        **ATTENTION** 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   )!_astream_events_implementation_v1!_astream_events_implementation_v2rj  )r   rU  rV  rW  rX  rY  rZ  v1zAOnly versions "v1" and "v2" of the schema is currently supported.N)#langchain_core.tracers.event_streamro  rp  NotImplementedErrorrJ   )ro   r   r   rk  rU  rV  rW  rX  rY  rZ  r   ro  rp  event_streamr   events                   rr   astream_eventszRunnable.astream_eventsk  s     B	
 	
 	
 	
 	
 	
 	
 	

 d??<< ++)++)   LL __ =< ++)++)   LL VC%c***L)) 	 	 	 	 	 	 	 	+       e  ,|	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   #B&A3,B
BBIterator[Input]c              +     K   d}|D ]!}|s|}d}		 ||z   }# t           $ r |}Y w xY w|r | j        ||fi |E d{V  dS dS )a  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~   rO  )ro   r   r   r   got_first_valichunkfinals          rr   	transformzRunnable.transformu  s      (  	# 	#F ! # $#!FNEE  # # #"EEE#  	<"t{5&;;F;;;;;;;;;;;	< 	<s   &&AsyncIterator[Input]c                  K   d}|2 3 d{V }|s|}d}	 ||z   }# t           $ r |}Y #w xY w6 |r | j        ||fi |2 3 d{V }|W V  6 dS dS )a  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~   rR  )ro   r   r   r   ry  rz  r{  outputs           rr   
atransformzRunnable.atransform  s      ( ! 	# 	# 	# 	# 	# 	# 	#& ! # $#!FNEE  # # #"EEE# ""  	 ,UF E Ef E E       f !F E E	 	s   .++ ARunnable[Input, Output]c                &    t          | |i           S )aY  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_community.chat_models import ChatOllama
            from langchain_core.output_parsers import StrOutputParser

            llm = ChatOllama(model='llama2')

            # Without bind.
            chain = (
                llm
                | StrOutputParser()
            )

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

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

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

        )boundr   r   RunnableBindingro   r   s     rr   bindzRunnable.bind  s    P T&DDDDrt   c                N    t          | t          di |pi |          i           S )a  Bind config to a Runnable, returning a new Runnable.

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

        Returns:
            A new Runnable with the config bound.
        r*   )r  r   r   )r  r   ro   r   r   s      rr   with_configzRunnable.with_config  sD      ,FLb,V,  
 
 
 	
rt   on_starton_endon_errorr  MOptional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]]r  r  c               F    ddl m t          | fdg          S )a  Bind lifecycle listeners to a Runnable, returning a new Runnable.

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

        The Run object contains information about the run, including its id,
        type, input, output, error, start_time, end_time, and any tags or metadata
        added to the run.

        Args:
            on_start: Called before the Runnable starts running. Defaults to None.
            on_end: Called after the Runnable finishes running. Defaults to None.
            on_error: Called if the Runnable throws an error. 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)
        r   RootListenersTracerc                (    d |           giS N	callbacks)r   r  r  r  r   r   r  r  r  r  s    rr   <lambda>z)Runnable.with_listeners.<locals>.<lambda>H  s3    ++#)%-#)%-	  "	  rt   r  config_factories)%langchain_core.tracers.root_listenersr  r  )ro   r  r  r  r  s    ```@rr   with_listenerszRunnable.with_listeners  s^    n 	NMMMMM	 	 	 	 	 	 	
 
 
 	
rt   Optional[AsyncListener]c               F    ddl m t          | fdg          S )a  Bind async lifecycle listeners to a Runnable, returning a new Runnable.

        on_start: Asynchronously called before the Runnable starts running.
        on_end: Asynchronously called after the Runnable finishes running.
        on_error: Asynchronously called if the Runnable throws an error.

        The Run object contains information about the run, including its id,
        type, input, output, error, start_time, end_time, and any tags or metadata
        added to the run.

        Args:
            on_start: Asynchronously called before the Runnable starts running.
                Defaults to None.
            on_end: Asynchronously called after the Runnable finishes running.
                Defaults to None.
            on_error: Asynchronously called if the Runnable throws an error.
                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

        r   )AsyncRootListenersTracerc                (    d |           giS r  r   )r   r  r  r  r  s    rr   r  z*Runnable.with_alisteners.<locals>.<lambda>  s3    00#)%-#)%-	  "	  rt   r  )r  r  r  )ro   r  r  r  r  s    ```@rr   with_alistenerszRunnable.with_alistenersU  s^    \ 	SRRRRR	 	 	 	 	 	 	
 
 
 	
rt   )
input_typeoutput_typer  Optional[type[Input]]r  Optional[type[Output]]c               (    t          | ||i           S )aE  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.
        )r  custom_input_typecustom_output_typer   r  ro   r  r  s      rr   
with_typeszRunnable.with_types  s'     (*	
 
 
 	
rt      )retry_if_exception_typewait_exponential_jitterexponential_jitter_paramsstop_after_attemptr  tuple[type[BaseException], ...]r  r  !Optional[ExponentialJitterParams]r  r#  c          	     2    ddl m}  || i i ||||          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)r  r   r   retry_exception_typesr  max_attempt_numberr  )langchain_core.runnables.retryr  )ro   r  r  r  r  r  s         rr   
with_retryzRunnable.with_retry  sF    l 	A@@@@@}"9$;1&?
 
 
 	
rt   #Runnable[list[Input], list[Output]]c                "    t          |           S )a+  Return a new Runnable that maps a list of inputs to a list of outputs.

        Calls invoke() with each input.

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

        Example:

            .. 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]
        r  )RunnableEachr   s    rr   r  zRunnable.map  s    ( $''''rt   )exceptions_to_handleexception_key	fallbacks!Sequence[Runnable[Input, Output]]r  r  %RunnableWithFallbacksT[Input, Output]c               ,    ddl m}  || |||          S )a  Add fallbacks to a Runnable, returning a new Runnable.

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

        Args:
            fallbacks: A sequence of runnables to try if the original Runnable fails.
            exceptions_to_handle: A tuple of exception types to handle.
                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   rS   )runnabler  r  r  )"langchain_core.runnables.fallbacksrT   )ro   r  r  r  rT   s        rr   with_fallbackszRunnable.with_fallbacks#  s>    z 	MLLLLL$$!5'	
 
 
 	
rt   funcUnion[Callable[[Input], Output], Callable[[Input, CallbackManagerForChainRun], Output], Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]]run_type
serializedOptional[dict[str, Any]]c                F   t          |          }t          |          }|                    ||||                    d          p|                                 |                    dd                    }	 t          ||                                          }	t          |	          5 }
t          d |
j
        t          ||||fi |          }ddd           n# 1 swxY w Y   |                    |           |S # t          $ r}|                    |            d}~ww xY w)zHelper method to transform an Input value to an Output value, with callbacks.

        Use this method to implement invoke() in subclasses.
        run_namerun_idNr  r`   r  r  r=   )r-   r/   on_chain_startr   rs   r1  r3   	get_childr5   r   runr,   on_chain_endBaseExceptionon_chain_error)ro   r  r   r   r  r  r   callback_managerrun_managerchild_configcontextr  r  s                rr   _call_with_configzRunnable._call_with_configk  s   " v&&:6BB&55J'':4==??::h-- 6 
 
	'+:O:O:Q:QRRRL#L11 WGK4#  ! 
 
                $$V,,,M  	 	 	&&q)))	s<   52C; '&CC; CC;  C!C; ;
D DD Union[Callable[[Input], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]c           
     p  K   t          |          }t          |          }|                    ||||                    d          p|                                 |                    dd                     d{V }	 t          ||                                          }	t          |	          5 }
t          ||||fi |}t          ||
           d{V }ddd           n# 1 swxY w Y   |                    |           d{V  |S # t          $ r!}|                    |           d{V   d}~ww xY w)zHelper method to transform an Input value to an Output value, with callbacks.

        Use this method to implement ainvoke() in subclasses.
        r  r  Nr  r  )r-   r.   r  r   rs   r1  r3   r  r5   r+   r@   r  r  r  )ro   r  r   r   r  r  r   r  r  r  r  rL  r  r  s                 rr   _acall_with_configzRunnable._acall_with_config  s     ( v&&@HH,;;J'':4==??::h-- < 
 
 
 
 
 
 
 
	'+:O:O:Q:QRRRL#L11 HW4% 8>  (9w'G'G!G!G!G!G!G!G	H H H H H H H H H H H H H H H **6222222222M  	 	 	,,Q/////////	s<   =2D
 /'C"D
 "C&&D
 )C&*D
 

D5D00D5)r  r  
  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]]]]c                   |sg S t          |t          |                    }d |D             } fdt          |||          D             }		 t          |          rd t          ||	          D             |d<   t	          |          r|	|d<    ||fi |}
d}t          |	|
          D ]I\  }}t          |t                    r|p|}|                    |           4|                    |           J|s|t          d|
          S |# t          $ rC|	D ]}|                               |r!t          dfd|D                       cY dS  dww xY w)	zTransform a list of inputs to a list of outputs, with callbacks.

        Helper method to transform an Input value to an Output value,
        with callbacks. Use this method to implement invoke() in subclasses.
        c                ,    g | ]}t          |          S r   )r/   r   cs     rr   r   z/Runnable._batch_with_config.<locals>.<listcomp>  s!    QQQA<Q??QQQrt   c                    g | ][\  }}}|                     d ||                    d          p                                |                    dd                     \S Nr  r  r  r  r   rs   r1  r   r  r   r   r  ro   s       rr   r   z/Runnable._batch_with_config.<locals>.<listcomp>  s}     
 
 
 0 % ++!ZZ
++>t}}zz(D11 ,  
 
 
rt   c                Z    g | ](\  }}t          ||                                           )S r  r3   r  r   r  rms      rr   r   z/Runnable._batch_with_config.<locals>.<listcomp>  A     $ $ $2 !bllnn===$ $ $rt   r   r  Nr  c                    g | ]}S r   r   r   rh   r  s     rr   r   z/Runnable._batch_with_config.<locals>.<listcomp>      ,>,>,>1Q,>,>,>rt   )r0   r|   r0  r>   r?   r   r  r  r  r   r  )ro   r  r   r   r  r  r   r  callback_managersrun_managersr  first_exceptionr  r'  r  s   `    `        @rr   _batch_with_configzRunnable._batch_with_config  s   2  	I!&#e**55QQQQQ
 
 
 
 
 47!5'4 4
 
 
	"d## $ $!$Wl!;!;$ $ $x  #4(( 5(4}%T%**6**F 48O$'f$=$= 2 2 Sc9-- 2&5&<O..s3333,,S1111  4O$;NF333!!!  	 	 	+ . .**1----  @N,>,>,>,>,>,>,>????????	s%   A	D 
E7EEEE5  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               n   K   |sg S t          |t          |                    }d |D             }t          j         fdt	          |||          D               d{V }		 t          |          rd t	          ||	          D             |d<   t          |          r|	|d<    ||fi | d{V }
d}g }t	          |	|
          D ]o\  }}t          |t                    r-|p|}|	                    |
                    |                     G|	                    |                    |                     pt          j        |  d{V  |s|t          d|
          S |# t          $ rIt          j        fd|	D               d{V  |r!t          dfd	|D                       cY dS  dww xY w)
zTransform a list of inputs to a list of outputs, with callbacks.

        Helper method to transform an Input value to an Output value,
        with callbacks.
        Use this method to implement invoke() in subclasses.
        c                ,    g | ]}t          |          S r   )r.   r  s     rr   r   z0Runnable._abatch_with_config.<locals>.<listcomp>,  s!    WWW!B1EEWWWrt   c              3     K   | ]]\  }}}|                     d ||                    d          p                                |                    dd                     V  ^d S r  r  r  s       rr   	<genexpr>z/Runnable._abatch_with_config.<locals>.<genexpr>.  s         4$eV !//%J//B4==??!::h55 0       rt   Nc                Z    g | ](\  }}t          ||                                           )S r  r  r  s      rr   r   z0Runnable._abatch_with_config.<locals>.<listcomp>=  r  rt   r   r  r  c              3  B   K   | ]}|                               V  d S r  r  )r   r  r  s     rr   r  z/Runnable._abatch_with_config.<locals>.<genexpr>F  s1      PPK+,,Q//PPPPPPrt   c                    g | ]}S r   r   r  s     rr   r   z0Runnable._abatch_with_config.<locals>.<listcomp>I  r  rt   )r0   r|   rI  gatherr0  r>   r?   r   r  appendr  r  r   r  )ro   r  r   r   r  r  r   r  r  r  r  r  r;  r  r'  r  s   `    `         @rr   _abatch_with_configzRunnable._abatch_with_config
  s     <  	I!&#e**55WWwWWWDKN     8;%ug8 8  E
 ?
 ?
 ?
 ?
 ?
 ?
	"d## $ $!$Wl!;!;$ $ $x  #4(( 5(4}%40000000000F 48O+-E$'f$=$= @ @ Sc9-- @&5&<OLL!;!;C!@!@AAAALL!9!9#!>!>????.%((((((((  4O$;NF333!!'  	 	 	.PPPP<PPP        ! @N,>,>,>,>,>,>,>????????	s%   $AE! !
F4+=F/(F4.F//F4transformerUnion[Callable[[Iterator[Input]], Iterator[Output]], Callable[[Iterator[Input], CallbackManagerForChainRun], Iterator[Output]], Callable[[Iterator[Input], CallbackManagerForChainRun, RunnableConfig], Iterator[Output]]]c           
   +  d  K   ddl m t          |d          \  }}t          |d          }d}	d}
d}t	          |          }t          |          }|                    dddi||                    d          p|                                 |	                    d	d          
          }	 t          ||                                          }t          |          r||d<   t          |          r||d<   t          |          5 } |j        ||fi |}t          fd|j        D             d          x}r|                    |j        |          }	 	 |                    t          |          }|V  |r |
|}
n	 |
|z   }
n# t&          $ r |}
d}Y nw xY w|}
D# t(          t*          f$ r Y nw xY w|D ]&}|	r ||}		 ||z   }# t&          $ r |}d}	Y  w xY w|}'	 ddd           n# 1 swxY w Y   |                    |
|           dS # t.          $ r}|                    ||            d}~ww xY w)zTransform a stream with config.

        Helper method to transform an Iterator of Input values into an Iterator of
        Output values, with callbacks.
        Use this to implement `stream()` or `transform()` in Runnable subclasses.
        r   _StreamingCallbackHandlerrx   NTr    r  r  r  r  r   r  c              3  X   K   | ]$}t          |          t          d |          V  %dS r  Nr   r   r   hr  s     rr   r  z9Runnable._transform_stream_with_config.<locals>.<genexpr>  S        %a)BCC	8!<<     rt   Fr  )!langchain_core.tracers._streamingr  r   nextr-   r/   r  r   rs   r1  r3   r  r>   r?   r5   r  handlerstap_output_iterr  r~   StopIterationGeneratorExitr  r  r  )ro   r   r  r   r  r   input_for_tracinginput_for_transformfinal_inputfinal_input_supportedfinal_outputfinal_output_supportedr  r  r  r  iteratorstream_handlerchunkrz  r  r  s                        @rr   _transform_stream_with_configz&Runnable._transform_stream_with_configY  s{     4 	POOOOO 25UA..'+,=t'D'D $)-!%v&&:6BB&55bMJ'':4==??::h-- 6 
 
6	G'+:O:O:Q:QRRRLk** 0#/x ";// 4(3}%#L11 +-W&7;{4GRR6RR%)   !,!5   & & >   .==#*H   H1(/D((C(C#1 
1+3/4!C3?%3GLL'0 !C !C !C38L=B$:$:$:!C ,1L1 &}5   D/ - -F, 
-&.*0KK>.9F.B#, > > >.48= 5 5 5> '--A+- +- +- +- +- +- +- +- +- +- +- +- +- +- +-` $$\+$FFFFF	  	 	 	&&q&===	s   )AH AG$'F:F ?F FFFFF+(G$*F++G$:G ?G$ GG$GG$H $G((H +G(,H 
H/H**H/  Union[Callable[[AsyncIterator[Input]], AsyncIterator[Output]], Callable[[AsyncIterator[Input], AsyncCallbackManagerForChainRun], AsyncIterator[Output]], Callable[[AsyncIterator[Input], AsyncCallbackManagerForChainRun, RunnableConfig], AsyncIterator[Output]]]c           
    t  K   ddl m t          |d          \  }}t          |d           d{V }d}	d}
d}t	          |          }t          |          }|                    dddi||                    d          p|                                 |	                    d	d          
           d{V }	 t          ||                                          }t          |          r||d<   t          |          r||d<   t          |          5 } |j        ||fi |}t!          fd|j        D             d          x}r|                    |j        |          }n|}	 	 t)          t          |          |           d{V }|W V  |r |
|}
n	 |
|z   }
n# t*          $ r |}
d}Y nw xY w|}
M# t,          $ r Y nw xY w|2 3 d{V }|	r ||}	 ||z   }# t*          $ r |}d}	Y %w xY w|},6 	 ddd           n# 1 swxY w Y   |                    |
|           d{V  n0# t0          $ r#}|                    ||           d{V   d}~ww xY w	 |,t5          |d          r|                                 d{V  dS dS dS # |+t5          |d          r|                                 d{V  w w w xY w)a  Transform a stream with config.

        Helper method to transform an Async Iterator of Input values into an Async
        Iterator of Output values, with callbacks.
        Use this to implement `astream()` or `atransform()` in Runnable subclasses.
        r   r  rx   NTr   r  r  r  r  r  r   r  c              3  X   K   | ]$}t          |          t          d |          V  %dS r  r  r  s     rr   r  z:Runnable._atransform_stream_with_config.<locals>.<genexpr>  r	  rt   Fr
  aclose)r  r  rK   rL   r-   r.   r  r   rs   r1  r3   r  r>   r?   r5   r  r  r  tap_output_aiterr  r@   r~   StopAsyncIterationr  r  r  ri   r  )ro   r   r  r   r  r   r  r  r  r  r  r  r  r  r  r  	iterator_r  r  r  rz  r  r  s                         @rr   _atransform_stream_with_configz'Runnable._atransform_stream_with_config  s     : 	POOOOO 26eQ..-56G-N-N'N'N'N'N'N'N $)-!%v&&@HH,;;bMJ'':4==??::h-- < 
 
 
 
 
 
 
 
<	)'+:O:O:Q:QRRRLk** 0#/x ";// 4(3}%#L11 .-W'GK5HSSFSS	%)   !,!5   & & > )  .>>#*I   HH  )H1&78J8JG&T&T T T T T T T#1 
1+3/4!C3?%3GLL'0 !C !C !C38L=B$:$:$:!C ,1L1 *   D$5 - - - - - - -&, 
-&.*0KK>.9F.B#, > > >.48= 5 5 5> '- %6$5G.- .- .- .- .- .- .- .- .- .- .- .- .- .- .-f **<*LLLLLLLLLL	  	 	 	,,Q{,CCCCCCCCC	 M$H)E)E$&&((((((((((( %$$$y$H)E)E$&&(((((((((( %$s   5AH$ AG;!0F/FF/F)&F/(F))F//
F<9G;;F<<G;G-G;GG;G'$G;&G''G;/H$ ;G??H$ G?H$ J $
I.IIJ 0J7z1This API is in beta and may change in the future.)message)r`   r   	arg_typesargs_schemaOptional[type[BaseModel]]r   r$  Optional[dict[str, type]]rW   c               .    ddl m}  || ||||          S )au  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%  r`   r   r$  )langchain_core.toolsr)  )ro   r%  r`   r   r$  r)  s         rr   as_toolzRunnable.as_tool,	  sA    F 	BAAAAA''##
 
 
 	
rt   r  rb   r_   r`   r_   rc   rd   rc   ru   rc   r   )rc   r   r   r   rc   r   )r   r   rc   r   rc   r   )r   r   rc   r   )r   r   rc   r   r   r   rc   r7   )r   r   rc   r   r   r   rc   r   r   r   rc   r   )r   r   r`   r_   rc   r   )r   r   rc   r   )r   r   rc   r   r   r<   r   r   r   r   rc   r=   
r  r  r   r  r  r  r   r  rc   r  
r  r  r   r  r  r  r   r   rc   r  
r  r  r   r  r  r  r   r   rc   r  
r  r  r   r  r  r  r   r  rc   r  
r  r  r   r  r  r  r   r  rc   r=  
r  r  r   r  r  r  r   r  rc   rA  
r  r  r   r  r  r  r   r  rc   rA  r   r<   r   r   r   r  rc   rM  r   r<   r   r   r   r  rc   rP  )r   r   r   r   rS  r  rT  r  rU  r   rV  r   rW  r   rX  r   rY  r   rZ  r   r   r   rc   r[  )r   r   r   r   rS  r  rT  r  rU  r   rV  r   rW  r   rX  r   rY  r   rZ  r   r   r   rc   r_  )r   r   r   r   rS  r  rT  r  rU  r   rV  r   rW  r   rX  r   rY  r   rZ  r   r   r   rc   ra  )r   r   r   r   rk  rl  rU  r   rV  r   rW  r   rX  r   rY  r   rZ  r   r   r   rc   rm  r   rw  r   r   r   r  rc   rM  r   r}  r   r   r   r  rc   rP  r   r   rc   r  r   r   r   r   rc   r  r  r  r  r  r  r  rc   r  )r  r  r  r  r  r  rc   r  )r  r  r  r  rc   r  )
r  r  r  r  r  r  r  r#  rc   r  )rc   r  )r  r  r  r  r  r_   rc   r  NN)r  r  r   r<   r   r   r  r_   r  r  r   r  rc   r=   )r  r  r   r<   r   r   r  r_   r  r  r   r  rc   r=   )r  r  r   r  r   r  r  r  r  r_   r   r  rc   r  )r  r  r   r  r   r  r  r  r  r_   r   r  rc   r  )r   rw  r  r  r   r   r  r_   r   r  rc   rM  )r   r}  r  r  r   r   r  r_   r   r  rc   rP  )
r%  r&  r`   r_   r   r_   r$  r'  rc   rW   )9rk   r   __qualname____doc____annotations__rs   propertyr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r  r<  r?  rO  rR  r^  rv  r|  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r"  r&   betar+  r   rt   rr   r^   r^   o   s         B C '+EI     @    X2    X* ' ' ' X' ,0&
 &
 &
 &
 &
R 26A A A A A8 ( ( ( X( ,0&
 &
 &
 &
 &
R 26B B B B B8    X
 59*V *V *V *V *V *VZ 59G G G G G G    & 26

 

 

 

 


A 
A 
A 
A
A 
A 
A 
A #": ": ": ": ": ":H3) 3) 3) 3)j,O ,O ,O ,O\ ?C    ^$ @D
S 
S 
S 
S 
S IM"U
 #("U "U "U "U "U "UH  MQ+
 -2+ + + + + X+  MQ= = = = X= MQ/$
 #(/$ /$ /$ /$ /$ /$h IM.X
 #(.X .X .X .X .X .X`  MQ0
 -20 0 0 0 0 X0  MQB B B B XB MQ8
 #(8 8 8 8 8 8z ,03 3 3 3 3. ,0: : : : :(  ,0)
 #*.151504151504) ) ) ) ) X)   ,0$ +/151504151504$ $ $ $ $ X$& ,0E
 *.151504151504E E E E E ET ,0H
 (,151504151504H H H H H HZ ,0(< (< (< (< (<Z ,0) ) ) ) )V(E (E (E (EX ,0
 
 
 
 
:   G
 G
 G
 G
 G
 G
X -1*.,0^
 ^
 ^
 ^
 ^
 ^
F -1.2	
 
 
 
 
 
2 EN<(,GK"#@
 @
 @
 @
 @
 @
D( ( ( (4 BK'+D
 D
 D
 D
 D
 D
L 2 #'/3- - - - -v #'/3) ) ) ) )r IMC"  #("&#C" C" C" C" C" C"n IM%M"( #("&+M" M" M" M" M" M"~ #'!cG cG cG cG cGp #''l) l) l) l) l)\ ^!TUUU 26j
 #%)/3j
 j
 j
 j
 j
 VUj
 j
 j
rt   r^   c                  t     e Zd ZU dZdZded<    ed          Zed fd	            Z	ddZ
dddddZ xZS )RunnableSerializablez(Runnable that can be serialized to JSON.Nr_   r`   r   )protected_namespacesrc   6Union[SerializedConstructor, SerializedNotImplemented]c                    t                                                      }t          j        t                    5  |                                 |d<   ddd           n# 1 swxY w Y   |S )zzSerialize the Runnable to JSON.

        Returns:
            A JSON-serializable representation of the Runnable.
        r`   N)superto_json
contextlibsuppressr  rs   )ro   dumpedrj   s     rr   rO  zRunnableSerializable.to_json	  s     "" ++ 	- 	-!]]__F6N	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	-s   AA#&A#r   r9   #RunnableSerializable[Input, Output]c                    ddl m} t          |           j        }|D ]2}||vr,d| d|  d|                                 }t          |          3 || |          S )aH  Configure particular Runnable fields at runtime.

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

        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.configurablerU  typemodel_fieldsr   
ValueError)ro   r   rU  rY  keyr   s         rr   configurable_fieldsz(RunnableSerializable.configurable_fields	  s    H 	UTTTTTDzz. 	& 	&C,&&@ @ @D @ @*6*;*;*=*=@ @  !oo% ' *)$vFFFFrt   r   F)default_keyprefix_keyswhichr:   r]  rd   r^  r  EUnion[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]c               .    ddl m}  ||| |||          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-sonnet-20240229"
            ).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   alternativesr]  r^  )rW  rb  )ro   r_  r]  r^  r   rb  s         rr   configurable_alternativesz.RunnableSerializable.configurable_alternatives	  sL    ^	
 	
 	
 	
 	
 	
 0/##
 
 
 	
rt   )rc   rL  )r   r9   rc   rS  )
r_  r:   r]  rd   r^  r  r   r`  rc   rS  )rk   r   rD  rE  r`   rF  r    model_configr%   rO  r\  rd  __classcell__rj   s   @rr   rJ  rJ  	  s         22D:    L 	 	 	 	 	 X	/G /G /G /Gj %!9
 9
 9
 9
 9
 9
 9
 9
 9
 9
rt   rJ  stepslist[Runnable[Any, Any]]r   r   rc   r   c                   ddl m}m} | d         t          |           dk    r                    |          S t          |          rbt          | dd          |          }t          |t                    s4t          dfd|j
                                        D                       S n(t          |          rt          | dd          |          S                     |          S )Nr   r   r   r   RunnableSequenceInputc                P    i | ]"\  }}|j         j        v||j        |j        f#S r   )mappersteps__r   r   )r   kvfirsts      rr   r   z%_seq_input_schema.<locals>.<dictcomp>,
  sB     # # #1 444 ai0444rt   r   )r   r   r   r|   r   r   _seq_input_schemar   r"   rN   rY  r   )rh  r   r   r   next_input_schemarr  s        @rr   rs  rs  
  s    RQQQQQQQ!HE
5zzQ%%f---%(( 4-eABBi@@+Y77 		"'# # # # 1 > D D F F# # #   		 
E<	(	( 4 qrrF333!!&)))rt   c                p   ddl m}m} | d         t          |           dk    r                    |          S t          |          rj                            |          }t          | d d         |          }t          |t                    sWt          di d |j                                        D             d |j                                        D                       S nt          |          rt          | d d         |          }t          |t                    s}t          j        t                    r4t          dfd	|j                                        D                       S |j        j                 }t          d|j        |j        f
          S                     |          S )Nr   rk  r   RunnableSequenceOutputc                2    i | ]\  }}||j         |j        fS r   r   r   r   rp  rq  s      rr   r   z&_seq_output_schema.<locals>.<dictcomp>H
  7        Aq AL!)4  rt   c                2    i | ]\  }}||j         |j        fS r   ry  rz  s      rr   r   z&_seq_output_schema.<locals>.<dictcomp>L
  r{  rt   r   c                F    i | ]\  }}|j         v ||j        |j        fS r   )r   r   r   )r   rp  rq  lasts      rr   r   z&_seq_output_schema.<locals>.<dictcomp>Y
  s;     ' ' ' Aq	>> AL!)4)>>rt   )r   )r   r   r   r|   r   r   rn  r   _seq_output_schemar   r"   rN   rY  r   r   r  r   r   )rh  r   r   r   mapper_output_schemaprev_output_schemafieldr~  s          @rr   r  r  8
  s    RQQQQQQQ9D
5zzQ$$V,,,$'' "#{<<VDD/crc
FCC,i88 	"(	# $6$C$I$I$K$K  	#
 $8$E$K$K$M$M  	#   	 
D,	'	' /crc
FCC,i88 	$)T** &,' ' ' '$6$C$I$I$K$K' ' '    '3DI>E"(0@%-/P    !!&)))rt   c                      e Zd ZU dZded<   	  ee          Zded<   	 ded<   	 d	d	d	d	d
dP fdZe	e
dQd                        ZedRd            Ze	e
dSd                        Z ed          Zee
dTd                        Zee
dUd                        Ze
	 dVdWd"            Ze
	 dVdWd#            Zee
dXd%                        Ze
dVdYd'            Ze
dZd)            Ze
d[d-            Ze
d\d0            Ze
	 dVd]d6            Ze
	 dVd^d8            Ze
	 dVd9d:d_d@            Ze
	 dVd9d:d_dA            Zd`dGZdadKZe
	 dVdbdL            Z e
	 dVdcdM            Z!e
	 dVdddN            Z"e
	 dVdedO            Z# xZ$S )fr   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 Runnables.

    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.

    Please 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]rr  default_factoryri  middlezRunnable[Any, Output]r~  N)r`   rr  r  r~  rh  RunnableLiker`   r_   Optional[Runnable[Any, Any]]"Optional[list[Runnable[Any, Any]]]rc   Nonec                  g }|s|||g|pg z   |gz   }|D ]T}t          |t                    r|                    |j                   2|                    t          |                     Ut          |          dk     r!dt          |           }t          |          t                      	                    |d         t          |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.
        Nrx   z1RunnableSequence must have at least 2 steps, got r   r   rv  )rr  r  r~  r`   )r   r   extendrh  r  r   r|   rZ  rN  __init__r  )
ro   r`   rr  r  r~  rh  
steps_flatstepr   rj   s
            rr   r  zRunnableSequence.__init__
  s   ( &(
 	;*t/?FLb1TF:J 	< 	<D$ 011 <!!$*----!!"4T":":;;;;z??QWc*ooWWCS//!Q-
1R4())B	 	 	
 	
 	
 	
 	
rt   	list[str]c                
    g dS N	langchainschemar  r   rq   s    rr   get_lc_namespacez!RunnableSequence.get_lc_namespace
       3222rt   c                4    | j         g| j        z   | j        gz   S )zqAll the Runnables that make up the sequence in order.

        Returns:
            A list of Runnables.
        )rr  r  r~  r   s    rr   rh  zRunnableSequence.steps
  s     
|dk)TYK77rt   r  c                    dS )zCheck if the object is serializable.

        Returns:
            True if the object is serializable, False otherwise.
                Defaults to True.
        Tr   r  s    rr   is_lc_serializablez#RunnableSequence.is_lc_serializable
  s	     trt   Tarbitrary_types_allowedru   c                    | j         j        S z&The type of the input to the Runnable.)rr  r   r   s    rr   r   zRunnableSequence.InputType  s     z##rt   r   c                    | j         j        S )z'The type of the output of the Runnable.)r~  r   r   s    rr   r   zRunnableSequence.OutputType	  s     y##rt   r   r   r   c                ,    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.
        )rs  rh  r   s     rr   r   z!RunnableSequence.get_input_schema  s     !V444rt   c                ,    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  rh  r   s     rr   r   z"RunnableSequence.get_output_schema  s     "$*f555rt   r   c                @  	
 ddl mm	 d t          | j                  D             }t          fd|D             t          d                    }t                      }i }|D ]\  }}|||<   |d |D             z  }t          |          D ]x\  }\  
}
j        	                              rVt          
j        
j        
j        
j        
j        
j        	
fd||         D             
j        pg z             |f||<   yt#          d	 |D                       S )
nGet the config specs of the Runnable.

        Returns:
            The config specs of the Runnable.
        r   )CONTEXT_CONFIG_PREFIX_key_from_idc                0    g | ]\  }}|j         D ]}||fS r   r   )r   idxr  r   s       rr   r   z1RunnableSequence.config_specs.<locals>.<listcomp>9  sJ     
 
 
T)
 
  3K
 
 
 
rt   c                T    g | ]$}|d          j                                       "|%S r   )r   
startswith)r   tupr  s     rr   r   z1RunnableSequence.config_specs.<locals>.<listcomp>@  s3    UUUSQ)=)=>S)T)TUSUUUrt   r   c                (    h | ]}|d          j         S r  r   r   s     rr   r+  z0RunnableSequence.config_specs.<locals>.<setcomp>G  s    $B$B$BDT!WZ$B$B$Brt   c                N    g | ]!} |           j                   k    |"S r   r  )r   dr  r   s     rr   r   z1RunnableSequence.config_specs.<locals>.<listcomp>S  sB     & & & !+|A,,tw2G2GGG GGGrt   )r   r   r`   r   r   	is_shareddependenciesc              3      K   | ]	\  }}|V  
d S r  r   )r   r   rh   s      rr   r  z0RunnableSequence.config_specs.<locals>.<genexpr>]  s&      &E&Eat&E&E&E&E&E&Ert   )%langchain_core.beta.runnables.contextr  r  r/  rh  r   r   setr   r  r;   r   r`   r   r   r  r  rF   )ro   	all_specsspecs_by_pos	next_depsdeps_by_posposspecsr  r  r  r   s           @@@rr   r   zRunnableSequence.config_specs+  s   	
 	
 	
 	
 	
 	
 	
 	

 
&tz22
 
 
	 UUUUIUUUqMM
 
 "ee	+-& 	C 	CJC(K!$B$BE$B$B$BBII )) 4 4 	 	C$w!!"788 )7#'?!Y $$($4"&.& & & & &%0%5& & &
  ,2&4   "	#$ '&E&E9&E&E&EEEErt   r7   c                   ddl m}  |            }| j        D ]}|                                }|                    |          }|| j        ur|                                 || j        ur|                                 |	                    |          \  }}|sd| d}	t          |	          |r|                    ||           |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   r6   ry    has no first node)langchain_core.runnables.graphr7   rh  	last_noder   rr  trim_first_noder~  trim_last_noder  rZ  r   )
ro   r   r7   r   r  current_last_node
step_graphstep_first_noderh   r   s
             rr   r   zRunnableSequence.get_graph_  s     	988888J 	C 	CD % 1 1//J4:%%**,,,49$$))+++!&j!9!9OQ" &:$::: oo%  C0/BBBrt   rd   c                d    d                     d t          | j                  D                       S )Nz
| c              3     K   | ]9\  }}|d k    rt          |          nt          t          |          d          V  :dS )r   z| N)reprrG   )r   r   ss      rr   r  z,RunnableSequence.__repr__.<locals>.<genexpr>  s]       
 
1 AvvDGGG#;DGGT#J#J
 
 
 
 
 
rt   )joinr/  rh  r   s    rr   __repr__zRunnableSequence.__repr__  s>    {{ 
 
!$*--
 
 
 
 
 	
rt   r   r   r   c                   t          |t                    rBt          | 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 Nr`   r   r   rr  r  r~  r`   r   r   s     rr   r   zRunnableSequence.__or__  s     e-.. 		#
 	 	
  
   Y,%*    J
[
 I
 u%%	
 
 

 
 
 	
rt   r   r   c                   t          |t                    rBt          |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   s     rr   r   zRunnableSequence.__ror__  s     e-.. 		# 
 
	
  	   Z,49    u%%J
 [
 I	
 
 

 
 
 	
rt   r   r<   r   r   r=   c           	        ddl m}  |t          |          | j                  }t	          |          }|                    d ||                    d          p|                                 |                    dd                     }	 t          | j                  D ]\  }}t          ||                    d|dz                        }t          |          5 }	|dk    r |	j        |j        ||fi |}n|	                    |j        ||          }d d d            n# 1 swxY w Y   	 |                    |           t!          d	|          S # t"          $ r}
|                    |
            d }
~
ww xY w)
Nr   config_with_contextr  r  r`   r  	seq:step:r   r  r=   )r  r  r-   rh  r/   r  r   rs   r1  r/  r3   r  r5   r  r   r  r   r  r  )ro   r   r   r   r  r  r  r   r  r  r  s              rr   r   zRunnableSequence.invoke  s     	NMMMMM %$]6%:%:DJGG:6BB&55J'':4==??::h--	 6 
 
	)$TZ00 	H 	H4%k&;&;<OA<O<O&P&P   (// H7Avv +DK Q Q& Q Q 'DK G G	H H H H H H H H H H H H H H H	H $$U+++%(((  	 	 	&&q)))	s=   	AE 9D E  D$	$E 'D$	(E 
E7E22E7r  c           	     b  K   ddl m}  |t          |          | j                  }t	          |          }|                    d ||                    d          p|                                 |                    dd                      d {V }	 t          | j                  D ]\  }}t          ||                    d|dz                        }t          |          5 }	|dk    rt          j        |j        ||fi |}
nt          j        |j        ||          }
t!           |
            |	d	
           d {V }d d d            n# 1 swxY w Y   	 |                    |           d {V  t%          d|          S # t&          $ r!}|                    |           d {V   d }~ww xY w)Nr   aconfig_with_contextr  r  r  r  r   r  Tcreate_taskr=   )r  r  r-   rh  r.   r  r   rs   r1  r/  r3   r  r5   	functoolspartialr   r@   r  r   r  r  )ro   r   r   r   r  r  r  r   r  r  partr  s               rr   r   zRunnableSequence.ainvoke  sr      	ONNNNN &%mF&;&;TZHH@HH,;;J'':4==??::h--	 < 
 
 
 
 
 
 
 
	)$TZ00 
W 
W4%k&;&;<OA<O<O&P&P   (// W7Avv(0ufWWPVWW(0ufMM"3DDFFGQU"V"V"VVVVVVVEW W W W W W W W W W W W W W W
W  **5111111111%(((  	 	 	,,Q/////////	s>   AF #AE?F E	F E	F 
F.F))F.Fr   r  r  r  r  r  c                   ddl m ddlm |sg S  fdt	          |t          |                    D             }fd|D             } fdt          |||          D             }	 |ri t           j                  D ]\  }fdt          t          |                    D             }	 |j
        fdt          |	|          D             fd	t          t          ||                    D             fd
|idk    r|ni }                    d t          |	|          D                        d |D             }t                    t          |          k    r n|                                }
g }t          t          |                    D ]Xv r*|                    t          d                              0|                    |
                    d                     YnMt           j                  D ]8\  } |j
        |fdt          ||          D             fd
|idk    r|ni }9d }t          ||          D ]I\  }}t!          |t"                    r|p|}|                    |           4|                    |           J|s|t          d|          S |# t(          $ rC|D ]}|                               |r!t          dfd|D                       cY d S  d ww xY w)Nr   r  CallbackManagerc                2    g | ]} |j                   S r   rh  )r   r  r  ro   s     rr   r   z*RunnableSequence.batch.<locals>.<listcomp>  s8     
 
 
  4:..
 
 
rt   c                    g | ]W}                     |                    d           dd|                    d          d|                    d          d          XS r  NFtagsr   inheritable_callbackslocal_callbacksverboseinheritable_tags
local_tagsinheritable_metadatalocal_metadata	configurer   )r   r   r  s     rr   r   z*RunnableSequence.batch.<locals>.<listcomp>   sy     
 
 
  %%&,jj&=&= $!'F!3!3%+ZZ
%;%;# &  
 
 
rt   c                    g | ]Z\  }}}|                     d ||                    d          p                                |                    dd                     [S Nr  r  r  r  r   cmr   r   ro   s       rr   r   z*RunnableSequence.batch.<locals>.<listcomp>-  sy     
 
 
 "E6 ZZ
++>t}}zz(D11	   
 
 
rt   c                    g | ]}|v|	S r   r   r   r   failed_inputs_maps     rr   r   z*RunnableSequence.batch.<locals>.<listcomp>A  +     & & &!CT:T:T:T:T:Trt   c                "    g | ]\  }}|v	|S r   r   r   r   inpr  s      rr   r   z*RunnableSequence.batch.<locals>.<listcomp>F  3        &3 (999  999rt   c           
     x    g | ]6\  }\  }}|vt          ||                    d dz                        7S r  r   r  r  r   r   r  r   r  stepidxs       rr   r   z*RunnableSequence.batch.<locals>.<listcomp>K  i        !0<B (999 ) &*,,,7P7Q;7P7P*Q*Q  
  :99rt   r  c                D    i | ]\  }}t          |t                    ||S r   r   r  r   r   r  s      rr   r   z*RunnableSequence.batch.<locals>.<dictcomp>Y  >        &3)#y99s  rt   c                <    g | ]}t          |t                    |S r   r  r   r  s     rr   r   z*RunnableSequence.batch.<locals>.<listcomp>_  '    VVVc:c9;U;UVcVVVrt   r<   c           
     j    g | ]/\  }}t          ||                    d dz                        0S r   r  r   r  r   r   s      rr   r   z*RunnableSequence.batch.<locals>.<listcomp>p  \       
 !+F ) &",,?R1q5?R?R2S2S    rt   r  c                    g | ]}S r   r   r  s     rr   r   z*RunnableSequence.batch.<locals>.<listcomp>      ,?,?,?1Q,?,?,?rt   )r  r   langchain_core.callbacks.managerr  r0   r|   r0  r/  rh  ranger  updatecopyr  r   r1  r   r  r  r  r  )ro   r  r   r  r   r  r  r  r  remaining_idxsinputs_copyr  r  r'  r  r  r  r  r  r   r  s   `              @@@@@@rr   r  zRunnableSequence.batch  s    	NMMMMMDDDDDD 	I
 
 
 
 
$VS[[99
 
 

 
 
 
 "
 
 

 
 
 
 &)):FG%L%L
 
 
T	"  @ ;=!%.tz%:%: $ $MGT& & & &#(W#6#6& & &N (TZ   *-nf*E*E  
     4=Sw=W=W3X3X    +<  &-\\66r! F& &,, *-nf*E*E     WVVVVVF,--W== > %kkmms7||,, : :A---d74Ea4H&I&IJJJJkooa&8&89999	:  )44  GAt'TZ   
 /2,.H.H    +< &'!VV66 FF* 48O$'f$=$= 2 2 Sc9-- 2&5&<O..s3333,,S1111  4O$;NF333!!!  	 	 	" % %!!!$$$$  AN,?,?,?,?,?,?,?@@@@@@@@	s%   .GJ6 6
L 7K>7L=K>>Lc                  K   ddl m ddlm |sg S  fdt	          |t          |                    D             }fd|D             }t          j         fdt          |||          D               d {V }	 |ri t           j
                  D ]\  }fdt          t          |                    D             }	 |j        fdt          |	|          D             fd	t          t          ||                    D             fd
|idk    r|ni  d {V }                    d t          |	|          D                        d |D             }t                    t          |          k    r n|                                }
g }t          t          |                    D ]Xv r*|                    t!          d                              0|                    |
                    d                     YnSt           j
                  D ]>\  } |j        |fdt          ||          D             fd
|idk    r|ni  d {V }?d }g }t          ||          D ]o\  }}t%          |t&                    r-|p|}|                    |                    |                     G|                    |                    |                     pt          j        |  d {V  |s|t!          d|          S |# t,          $ rIt          j        fd|D               d {V  |r!t!          dfd|D                       cY d S  d ww xY w)Nr   r  )AsyncCallbackManagerc                2    g | ]} |j                   S r   r  )r   r  r  ro   s     rr   r   z+RunnableSequence.abatch.<locals>.<listcomp>  s8     
 
 
 ! DJ//
 
 
rt   c                    g | ]W}                     |                    d           dd|                    d          d|                    d          d          XS r  r  )r   r   r  s     rr   r   z+RunnableSequence.abatch.<locals>.<listcomp>  sy     
 
 
  !**&,jj&=&= $!'F!3!3%+ZZ
%;%;# +  
 
 
rt   c           
   3     K   | ]\\  }}}|                     d ||                    d          p                                |                    dd                     V  ]d S r  r  r  s       rr   r  z*RunnableSequence.abatch.<locals>.<genexpr>  s         &Bv !!J//B4==??!::h55	 "       rt   c                    g | ]}|v|	S r   r   r  s     rr   r   z+RunnableSequence.abatch.<locals>.<listcomp>  r  rt   c                "    g | ]\  }}|v	|S r   r   r  s      rr   r   z+RunnableSequence.abatch.<locals>.<listcomp>  r  rt   c           
     x    g | ]6\  }\  }}|vt          ||                    d dz                        7S r   r  r  s       rr   r   z+RunnableSequence.abatch.<locals>.<listcomp>  r  rt   r  c                D    i | ]\  }}t          |t                    ||S r   r  r  s      rr   r   z+RunnableSequence.abatch.<locals>.<dictcomp>  r  rt   c                <    g | ]}t          |t                    |S r   r  r	  s     rr   r   z+RunnableSequence.abatch.<locals>.<listcomp>  r
  rt   r<   c           
     j    g | ]/\  }}t          ||                    d dz                        0S r   r  r  s      rr   r   z+RunnableSequence.abatch.<locals>.<listcomp>  r  rt   r  c              3  B   K   | ]}|                               V  d S r  r  )r   r  r  s     rr   r  z*RunnableSequence.abatch.<locals>.<genexpr>  s1      "O"OB2#4#4Q#7#7"O"O"O"O"O"Ort   c                    g | ]}S r   r   r  s     rr   r   z+RunnableSequence.abatch.<locals>.<listcomp>  r  rt   )r  r  r  r  r0   r|   rI  r  r0  r/  rh  r  r<  r  r  r  r   r1  r   r  r  r  r  )ro   r  r   r  r   r  r  r  r  r  r  r  r;  r  r'  r  r  r  r  r   r  s   `              @@@@@@rr   r<  zRunnableSequence.abatch  sR      	ONNNNNIIIIII 	I
 
 
 
 
$VS[[99
 
 

 
 
 
 "
 
 
 ELN    *-->)P)P  
E
 
?
 
?
 
?
 
?
 
?
 
?
T	"  @ ;=!%.tz%:%: $ $MGT& & & &#(W#6#6& & &N $/4;   *-nf*E*E  
     4=Sw=W=W3X3X  $ $ +<$  &-\\66r!$ $      F& &,, *-nf*E*E     WVVVVVF,--W== > %kkmms7||,, : :A---d74Ea4H&I&IJJJJkooa&8&89999	:  )44  GAt#.4;   
 /2,.H.H  $ $ +<$ &'!VV66$ $      FF& 48O+-E$'f$=$= @ @ Sc9-- @&5&<OLL!;!;C!@!@AAAALL!9!9#!>!>????.%((((((((  4O$;NF333!!#  	 	 	."O"O"O"O,"O"O"OPPPPPPPP  AN,?,?,?,?,?,?,?@@@@@@@@		s%   G"L 
M%=M M%M  M%rw  r  rP   r*   rM  c           	   +  p  K   ddl m} | j        g| j        z   | j        gz   } ||| j                  }t          d|          }t          |          D ][\  }}	t          ||	                    d|dz                        }|dk    r |	j
        ||fi |}E|	
                    ||          }\|E d {V  d S )Nr   r  rM  r  r   r  )r  r  rr  r  r~  rh  r   r/  r3   r  r|  )
ro   r   r  r   r   r  rh  final_pipeliner  r  s
             rr   
_transformzRunnableSequence._transform  s      	NMMMMMt{*di[8$$VTZ88
 0%88"5)) 	H 	HIC!+"7"78MC!G8M8M"N"N  F axx!/!Q!Q&!Q!Q!%!G!G!!!!!!!!!!rt   r}  rO   rP  c           	      K   ddl m} | j        g| j        z   | j        gz   } ||| j                  }t          d|          }t          |          D ][\  }}	t          ||	                    d|dz                        }|dk    r |	j
        ||fi |}E|	
                    ||          }\|2 3 d {V }
|
W V  6 d S )Nr   r  rP  r  r   r  )r  r  rr  r  r~  rh  r   r/  r3   r  r  )ro   r   r  r   r   r  rh  r$  r  r  r  s              rr   _atransformzRunnableSequence._atransform.  s'      	ONNNNNt{*di[8%%fdj99 5u=="5)) 	I 	IIC!%//0EC!G0E0EFF  F axx!0!R!R6!R!R!%!H!H* 	 	 	 	 	 	 	&LLLLL +NNs   0B=c           
   +     K    | j         || j        t          ||pi                     d          p| j                  fi |E d {V  d S Nr  )r  )r  r%  r3   r   r`   r   s       rr   r|  zRunnableSequence.transformK  s       645O6<R*<*<Z*H*H*UDIVVV
 
 	
 
 	
 	
 	
 	
 	
 	
 	
 	
 	
rt   c              +  P   K    | j         t          |g          |fi |E d {V  d S r  r|  iterr   s       rr   rO  zRunnableSequence.streamY  sD       "4>$w--BB6BBBBBBBBBBBrt   c           
       K    | j         || j        t          ||pi                     d          p| j                  fi |2 3 d {V }|W V  6 d S r)  )r"  r'  r3   r   r`   ro   r   r   r   r  s        rr   r  zRunnableSequence.atransformb  s       ?4>6<R*<*<Z*H*H*UDIVVV
 
 	
 
 	 	 	 	 	 	 	% KKKKK
 
 
s   Ac               b   K   dfd} | j          |            |fi |2 3 d {V }|W V  6 d S )Nrc   r}  c                   K    W V  d S r  r   r   s   rr   input_aiterz-RunnableSequence.astream.<locals>.input_aiterx        KKKKKKrt   rc   r}  r  ro   r   r   r   r2  r  s    `    rr   rR  zRunnableSequence.astreamq        	 	 	 	 	 	 +4?;;==&KKFKK 	 	 	 	 	 	 	%KKKKK LKK   .)rh  r  r`   r_   rr  r  r  r  r~  r  rc   r  rc   r  )rc   ri  rc   r  r-  r.  r  r/  r0  r1  rc   rd   r2  r3  r4  r   r<   r   r   r   r  rc   r=   r5  
r   rw  r  rP   r   r*   r   r   rc   rM  
r   r}  r  rO   r   r*   r   r   rc   rP  r>  r<  r?  r=  )%rk   r   rD  rE  rF  r!   r  r  r  classmethodr%   r  rG  rh  r  r    re  r   r   r   r   r   r   r  r   r   r   r   r  r<  r%  r'  r|  rO  r  rR  rf  rg  s   @rr   r   r   g
  s<        L Lb  -',uT'B'B'BFBBBB/,
 #.259-1$
 $
 $
 $
 $
 $
 $
 $
L 3 3 3 X [3 8 8 8 X8    X [ : $  L $ $ $ X X$ $ $ $ X X$ 155 5 5 5 X5 156 6 6 6 X6 0F 0F 0F X X0Fd     X> 
 
 
 X
 
 
 
 X
6 
 
 
 X
6 ?C") ") ") ") X")H  ,0&) &) &) &) X&)P  IM"
 #(" " " " " X"B  IMB"
 #(B" B" B" B" B" XB"H" " " "6   :  ,0
 
 
 
 X
  ,0C C C C XC  ,0    X  ,0
 
 
 
 X
 
 
 
 
rt   r   c                  8    e Zd ZU dZded<   	 d9d: fd
Zeed;d                        Zeed<d                        Z	 e
d          Ze	 d9ddd= fd            Zeed>d                        Ze	 d9d? fd            Ze	 d9d?d            Zeed@d                        Zed9dAd!            ZedBd"            Ze	 d9dCd&            Ze	 d9dDd(            ZdEd.Ze	 d9dFd0            Ze	 d9dGd1            ZdHd5Ze	 d9dId7            Ze	 d9dJd8            Z xZS )Kr   a
  Runnable that runs a mapping of Runnables in parallel.

    Returns a mapping of their outputs.

    RunnableParallel is one of the two main composition primitives for the LCEL,
    alongside RunnableSequence. It invokes Runnables 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 Runnables 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]]ro  NOptional[Mapping[str, Union[Runnable[Input, Any], Callable[[Input], Any], Mapping[str, Union[Runnable[Input, Any], Callable[[Input], Any]]]]]]r   vUnion[Runnable[Input, Any], Callable[[Input], Any], Mapping[str, Union[Runnable[Input, Any], Callable[[Input], Any]]]]rc   r  c                    |i |ni }|                     |           t                                          d |                                D                        dS )zCreate a RunnableParallel.

        Args:
            steps__: The steps to include. Defaults to None.
            **kwargs: Additional steps to include.
        Nc                4    i | ]\  }}|t          |          S r   )r   )r   r[  rs      rr   r   z-RunnableParallel.__init__.<locals>.<dictcomp>  s'    MMMFCS,Q//MMMrt   )ro  )r  rN  r  r   )ro   ro  r   mergedrj   s       rr   r  zRunnableParallel.__init__  sm    0 !( 3GfMMfllnnMMM 	 	
 	
 	
 	
 	
rt   r  c                    dS NTr   r  s    rr   r  z#RunnableParallel.is_lc_serializable  	     trt   r  c                
    g dS r  r   r  s    rr   r  z!RunnableParallel.get_lc_namespace  r  rt   Tr  ra   rb   r_   r`   rd   c                   |p6| j         p/dd                    | j                                                   d}t	                                          ||          S )zGet 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<,>ra   )r`   r  ro  r   rN  rs   ro   rb   r`   rj   s      rr   rs   zRunnableParallel.get_name  sY     XtyX$XARARATAT8U8U$X$X$XwwT222rt   r   c                h    | j                                         D ]}|j        r	|j        c S t          S r  )ro  r   r   r   )ro   r  s     rr   r   zRunnableParallel.InputType  sE     L'')) 	& 	&D~ &~%%%& 
rt   r   r   r   c                :   t          fd| j                                        D                       rGt          |                     d          fd| j                                        D                       S t                                                    S )r  c              3     K   | ]C}|                                                                                   d d          dk    V  DdS )rX  objectN)r   r   r   )r   r  r   s     rr   r  z4RunnableParallel.get_input_schema.<locals>.<genexpr>$  sk       
 
  v&&88::>>vxPP
 
 
 
 
 
rt   r<   c                    i | ]I}|                               j                                        D ]\  }}|d k    ||j        |j        fJS )__root__)r   rY  r   r   r   )r   r  rp  rq  r   s       rr   r   z5RunnableParallel.get_input_schema.<locals>.<dictcomp>,  sl     # # # $ 5 5f = = J P P R R# # 1J ai0 'rt   r   )allro  r   rN   rs   rN  r   ro   r   rj   s    `rr   r   z!RunnableParallel.get_input_schema  s      
 
 
 
 \((**
 
 
 
 
 	 #g&&# # # # $ 3 3 5 5# # #    ww''///rt   c                    d | j                                         D             }t          |                     d          |          S )r  c                (    i | ]\  }}||j         d fS ).)r   rz  s      rr   r   z6RunnableParallel.get_output_schema.<locals>.<dictcomp>B  s%    JJJTQ!alC(JJJrt   r=   r   )ro  r   rN   rs   )ro   r   rV  s      rr   r   z"RunnableParallel.get_output_schema6  sE     KJT\5G5G5I5IJJJt}}X66&QQQQrt   r   c                b    t          d | j                                        D                       S )r  c              3  .   K   | ]}|j         D ]}|V  d S r  r  )r   r  r   s      rr   r  z0RunnableParallel.config_specs.<locals>.<genexpr>M  sJ       '
 '
t?P'
 '
7;D'
 '
 '
 '
 '
 '
 '
rt   )rF   ro  r   r   s    rr   r   zRunnableParallel.config_specsE  s@     ' '
 '
!\0022'
 '
 '
 
 
 	
rt   r7   c                   ddl m}  |            }|                    |                     |                    }|                    |                     |                    }| j                                        D ]}|                                }|                                 |	                                 |s|
                    ||           W|                    |          \  }}	|sd| d}
t          |
          |	sd| d}
t          |
          |
                    ||           |
                    |	|           |S )r  r   r6   ry   r   has no last node)r  r7   r   r   r   ro  r   r   r  r  r   r  rZ  )ro   r   r7   r   r   r   r  r  r  step_last_noder   s              rr   r   zRunnableParallel.get_graphQ  s\    	988888^^D$9$9&$A$ABB
nnT%;%;F%C%CDDL'')) 	< 	<D))J&&(((%%''' <z;777727,,z2J2J/& *>d>>>C$S//)% *=d===C$S//)z?;;;~{;;;;rt   c                ~    d                     d | j                                        D                       }d|z   dz   S )Nz,
  c              3  l   K   | ]/\  }}| d t          t          |          d|z   d z              V  0dS )z: z  N)rG   r  rz  s      rr   r  z,RunnableParallel.__repr__.<locals>.<genexpr>x  sa       $
 $
1 HH,T!WWdQhoFFHH$
 $
 $
 $
 $
 $
rt   z{
  z
})r  ro  r   )ro   map_for_reprs     rr   r  zRunnableParallel.__repr__v  sQ    || $
 $
**,,$
 $
 $
 
 
 %--rt   r   r<   r   c           
       
 ddl m} t                    |                                        d          d d                    d          d                     d          d           }|                    d                     d          p|                                                     d	d           
          dfd
	 t          | j	                  }t                    5 
fd|                                D             }d t          ||          D             }d d d            n# 1 swxY w Y                       |           |S # t          $ r}	                    |	            d }	~	ww xY w)Nr   r  r  Fr  r   r  r  r  r  r  r  r   r<   r   r*   r[  rd   rc   r   c                    t          |                    d|                     }t          |          5 }|                    | j        ||          cd d d            S # 1 swxY w Y   d S )Nmap:key:r  )r3   r  r5   r  r   r  r   r   r[  r  r  r  s         rr   _invoke_stepz-RunnableParallel.invoke.<locals>._invoke_step  s     (%//0@30@0@AA  L
 $L11 W{{K                   s   A!!A%(A%c           	     H    g | ]\  }}                     ||          S r   r)  )r   r[  r  re  r   r  r   s      rr   r   z+RunnableParallel.invoke.<locals>.<listcomp>  sA       !T OOL$vsKK  rt   c                >    i | ]\  }}||                                 S r   )r2  )r   r[  r6  s      rr   r   z+RunnableParallel.invoke.<locals>.<dictcomp>  s&    VVV;3#v}}VVVrt   
r  r  r   r<   r   r*   r[  rd   rc   r   )r  r  r-   r  r   r  rs   r1  r   ro  r1   r   r0  r  r  r  )ro   r   r   r   r  r  rh  r4  r  r  re  r  r  s    ``       @@@rr   r   zRunnableParallel.invoke~  s"    	EDDDDD v&&*44"(**["9"9 #ZZ//!'J!7!7 5 
 
 '55J'':4==??::h--	 6 
 
	 	 	 	 	 	 	&&E(00 WH      %*[[]]   WV#eWBUBUVVVW W W W W W W W W W W W W W W $$V,,,M  	 	 	&&q)))	s<   #E .>D8,E 8D<<E ?D< E 
E?$E::E?r  c           	     l  	
K   t                    t                    }|                    d                     d          p|                                                     dd                      d {V 
d
fd		 t          | j                  }t          j	        	fd|
                                D               d {V }t          t          ||                    }
                    |           d {V  |S # t          $ r!}
                    |           d {V   d }~ww xY w)Nr  r  r  r  r  r   r<   r   r*   r[  rd   rc   r   c                   K   t          |                    d|                     }t          |          5 }t          |                     ||          |d           d {V cd d d            S # 1 swxY w Y   d S )Nrc  r  Tr  )r3   r  r5   r@   r   rd  s         rr   _ainvoke_stepz/RunnableParallel.ainvoke.<locals>._ainvoke_step  s       (%//0@30@0@AA  L $L11 W.LL55wD                         s   ,A33A7:A7c              3  :   K   | ]\  }} ||          V  d S r  r   )r   r[  r  rk  r   r   s      rr   r  z+RunnableParallel.ainvoke.<locals>.<genexpr>  sU       	 	 "T "M 	 	 	 	 	 	rt   rh  )r-   r.   r  r   rs   r1  r   ro  rI  r  r   r0  r  r  r  )ro   r   r   r   r  rh  resultsr  r  rk  r  s    ``      @@rr   r   zRunnableParallel.ainvoke  s      v&&@HH,;;J'':4==??::h--	 < 
 
 
 
 
 
 
 

	 
	 
	 
	 
	 
		&&E#N	 	 	 	 	 	 &+[[]]	 	 	      G #eW--..F **6222222222M  	 	 	,,Q/////////	s   A%D 
D3D..D3rw  r  rP   r*   Iterator[AddableDict]c              #    K   t          | j                  }t          t          |t	          |          t          j                                        t                    5 fd|                                D             }fd|D             }|rt          |t                    \  }}|D ]r}	|                    |	          \  }
}	 t          |
|	                                i          }|V  |
|f|                    t          |          <   c# t           $ r Y ow xY w|d d d            d S # 1 swxY w Y   d S )Nlockc                    g | ]T\  }}||                                                     t                              d |                               fUS rc  r  )r|  r1  r3   r  r   r`   r  r   input_copiesr  s      rr   r   z/RunnableParallel._transform.<locals>.<listcomp>  s           D$ NN$((**$"k.C.CDUtDUDU.V.V        rt   c                R    i | ]#\  }}                     t          |          ||f$S r   )r*  r  )r   	step_name	generatorr  s      rr   r   z/RunnableParallel._transform.<locals>.<dictcomp>
  sB       (Iy i009i2H  rt   r,  )r   ro  r  rM   r|   	threadingLockr1   r   r   r   r1  r8   r2  r*  r  r  )ro   r   r  r   rh  named_generatorsr4  completed_futuresrh   r6  rw  rx  r  r  ru  s     ``         @@rr   r%  zRunnableParallel._transform  s      T\"" GE3u::IN<L<LMMMNN$V,, "	            #(++--        ,<  G  '+G'Q'Q'Q$!1/ 
 
F-4[[-@-@*Y	 +Y,H I I#%%Ei @ @AA )     -"	 "	 "	 "	 "	 "	 "	 "	 "	 "	 "	 "	 "	 "	 "	 "	 "	 "	s8   'A(D7ADD7
D%"D7$D%%D77D;>D;Iterator[dict[str, Any]]c              +  @   K    | j         || j        |fi |E d {V  d S r  )r  r%  r   s       rr   r|  zRunnableParallel.transform  s]       6454?F
 
.4
 
 	
 	
 	
 	
 	
 	
 	
 	
 	
rt   c              +  ^   K   |                      t          |g          |          E d {V  d S r  r+  r   s       rr   rO  zRunnableParallel.stream*  s<       >>$w--88888888888rt   r}  rO   AsyncIterator[AddableDict]c               n  K   t          | j                  }t          t          |t	          |          t          j                                        fd|                                D             }d
dfd|D             }|rt          j        |t
          j	        	           d {V \  }}|D ]w}	|
                    |	          \  }
}	 t          |
|	                                i          }|W V  t          j         |                    }|
|f||<   h# t          $ r Y tw xY w|d S d S )Nrp  c                    g | ]T\  }}||                                                     t                              d |                               fUS rs  )r  r1  r3   r  rt  s      rr   r   z0RunnableParallel._atransform.<locals>.<listcomp>?  s     
 
 
 d  $$&& +*?*?@Q4@Q@Q*R*R   
 
 
rt   rx  r   rc   Optional[Output]c                0   K   t          |            d {V S r  )rL   )rx  s    rr   get_next_chunkz4RunnableParallel._atransform.<locals>.get_next_chunkM  s&      !),,,,,,,,,rt   c                V    i | ]%\  }}t          j         |                    ||f&S r   )rI  r  )r   rw  rx  r  s      rr   r   z0RunnableParallel._atransform.<locals>.<dictcomp>Q  sI     
 
 
$	9 y 9 9::Y	<R
 
 
rt   r,  )rx  r   rc   r  )r   ro  r  rK   r|   rI  rz  r   r   r   r1  r8   r2  r  r   )ro   r   r  r   rh  r{  taskscompleted_tasksrh   taskrw  rx  r  new_taskr  ru  s     ``          @@rr   r'  zRunnableParallel._atransform3  s      T\"" DE

HHHII
 
 
 
 
 
 $kkmm
 
 
	- 	- 	- 	-
 
 
 
(8
 
 
  	'.|7#:( ( ( " " " " " "OQ (  ).4&I'DKKMM(BCCEKKKK&2>>)3L3LMMH'0)&<E(OO)   D  	 	 	 	 	s   AD!!
D.-D.AsyncIterator[dict[str, Any]]c               P   K    | j         || j        |fi |2 3 d {V }|W V  6 d S r  )r"  r'  r.  s        rr   r  zRunnableParallel.atransformf  st       ?4>4#V
 
/5
 
 	 	 	 	 	 	 	% KKKKK
 
 
s   %c               p   K   dfd}|                       |            |          2 3 d {V }|W V  6 d S )Nrc   r}  c                   K    W V  d S r  r   r1  s   rr   r2  z-RunnableParallel.astream.<locals>.input_aitery  r3  rt   r4  r5  r6  s    `    rr   rR  zRunnableParallel.astreamr  s|      	 	 	 	 	 	  ??;;==&AA 	 	 	 	 	 	 	%KKKKK BAAs   5r  )ro  rA  r   rB  rc   r  r:  r9  r,  rc   r   r/  r0  r1  r;  )r   r<   r   r   r   r   rc   r   )r   r<   r   r   r   r  rc   r   )r   rw  r  rP   r   r*   rc   rn  )r   rw  r   r   r   r   rc   r}  )r   r<   r   r   r   r  rc   r}  )r   r}  r  rO   r   r*   rc   r  )r   r}  r   r   r   r   rc   r  )r   r<   r   r   r   r  rc   r  )rk   r   rD  rE  rF  r  r?  r%   r  r  r    re  rs   rG  r   r   r   r   r   r  r   r   r%  r|  rO  r'  r  rR  rf  rg  s   @rr   r   r     s1        N N` 0/// 
 
 
 
 
 
 
<    X [ 3 3 3 X [3 : $  L &*3EI3 3 3 3 3 3 3 X3    X X 150 0 0 0 0 0 X0: 15R R R R XR 
 
 
 X X
 " " " " X"H . . . X. ?C8 8 8 8 X8t  ,04 4 4 4 X4l- - - -^  ,0
 
 
 
 X
  ,09 9 9 9 X91 1 1 1f  ,0	 	 	 	 X	  ,0
 
 
 
 X
 
 
 
 
rt   r   c                     e Zd ZdZ	 d)ddd*dZeed+d                        Ze	 d)d,d            Zeed+d                        Z	e	 d)d,d            Z
ed-d            Zed.d            Ze	 d)d/d            Ze	 d)d0d!            Ze	 d)d1d#            Ze	 d)d2d&            Ze	 d)d3d'            Ze	 d)d1d(            ZdS )4RunnableGeneratoru  Runnable that runs a generator function.

    RunnableGenerators can be instantiated directly or by using a generator within
    a sequence.

    RunnableGenerators 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 that 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"
    Nra   r|  mUnion[Callable[[Iterator[Input]], Iterator[Output]], Callable[[AsyncIterator[Input]], AsyncIterator[Output]]]r  AOptional[Callable[[AsyncIterator[Input]], AsyncIterator[Output]]]r`   r_   rc   r  c                  |	|| _         |}t          |          r
|| _         |}n?t          j        |          r
|| _        |}n!dt          |           }t          |          	 |p|j        | _        dS # t          $ r d| _        Y dS w xY w)aB  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: r  )
r'  rI   r   isgeneratorfunctionr%  rX  r~   rk   r`   AttributeError)ro   r|  r  r`   func_for_namer   s         rr   r  zRunnableGenerator.__init__  s    , !)D&0Mi(( 	!(D%MM(33 	!'DO%MMF48OOF F  C.. 	,6 6DIII 	, 	, 	,+DIIII	,s   %A5 5B
	B
r   c                p   t          | dd           p| j        }	 t          j        |          j        }t          t          |                                          d           }|r<|j        t          j	        j
        k    r"t          |j        dt          f          d         S n# t          $ r Y nw xY wt          S Nr%  __args__r   )getattrr'  r   	signature
parametersr  r,  r   r   	Parameteremptyr   rZ  ro   r  paramsfirst_params       rr   r   zRunnableGenerator.InputType  s     t\400DD4D	&t,,7FtFMMOO44d;;K N{59J9PPP{5zC6JJ1MM 	 	 	D	
s   BB! !
B.-B.r   r   r   c                ,   | j         }t          | dd           p| j        }t          |dd           }t          j        |          r,t          |t                    st          |t                    r|S t          | 
                    d          ||          S )Nr%  r   r<   r   )r   r  r'  r   r   r   r   r   r   rN   rs   ro   r   r   r  modules        rr   r   z"RunnableGenerator.get_input_schema  s     N	t\400DD4D|T22 OI&&	y,77	 9i00	
 MM'"" 
 
 
 	
rt   c                   t          | dd           p| j        }	 t          j        |          }|j        t          j        j        k    r"t          |j        dt          f          d         nt          S # t          $ r
 t          cY S w xY wr  )	r  r'  r   r  return_annotation	Signaturer  r   rZ  ro   r  sigs      rr   r   zRunnableGenerator.OutputType/  s     t\400DD4D	#D))C (G,=,CCC -zC6BB1EE
  	 	 	JJJ	s   AA1 1BBc                ,   | j         }t          | dd           p| j        }t          |dd           }t          j        |          r,t          |t                    st          |t                    r|S t          | 
                    d          ||          S )Nr%  r   r=   r   )r   r  r'  r   r   r   r   r   r   rN   rs   r  s        rr   r   z#RunnableGenerator.get_output_schema=  s     O	t\400DD4D|T22 OI&&	y,77	 9i00	
 MM(## 
 
 
 	
rt   r   rR  r  c                    t          |t                    rbt          | d          r t          |d          r| j        |j        k    S t          | d          r t          |d          r| j        |j        k    S dS dS )Nr%  r'  F)r   r  ri   r%  r'  r   s     rr   __eq__zRunnableGenerator.__eq__X  s    e.// 	t\** ;wul/K/K ;%*:::t]++ =}0M0M ='5+<<<5urt   rd   c                    d| j          dS )NzRunnableGenerator()ra   r   s    rr   r  zRunnableGenerator.__repr__b  s    0DI0000rt   r   rw  r   rM  c                    t          | d          s!t          |            d}t          |           | j        || j        |fi |S )Nr%  z only supports async methods.)ri   r  rs  r  r%  ro   r   r   r   r   s        rr   r|  zRunnableGenerator.transformf  si     t\** 	+$ZZ>>>C%c***1t1O
 
 	
 
 	
rt   r<   c                <     | j         t          |g          |fi |S r  r+  r   s       rr   rO  zRunnableGenerator.streamw  (     t~dE7mmV>>v>>>rt   r=   c                \    d } | j         ||fi |D ]}||n||z   }t          d|          S Nr=   )rO  r   ro   r   r   r   r{  r  s         rr   r   zRunnableGenerator.invoke  sS     #'!dk%::6:: 	@ 	@F#mFFEEHe$$$rt   r}  rP  c                    t          | d          s!t          |            d}t          |           | j        || j        |fi |S )Nr'  z only supports sync methods.)ri   r  rs  r"  r'  r  s        rr   r  zRunnableGenerator.atransform  sf     t]++ 	+$ZZ===C%c***2t24#V
 
/5
 
 	
rt   c                >    dfd} | j          |            |fi |S )Nrc   r}  c                   K    W V  d S r  r   r1  s   rr   r2  z.RunnableGenerator.astream.<locals>.input_aiter  r3  rt   r4  r5  )ro   r   r   r   r2  s    `   rr   rR  zRunnableGenerator.astream  sE    	 	 	 	 	 	 t{{}}f?????rt   c                l   K   d } | j         ||fi |2 3 d {V }||n||z   }6 t          d|          S r  )rR  r   r  s         rr   r   zRunnableGenerator.ainvoke  s{       #'(DLAA&AA 	@ 	@ 	@ 	@ 	@ 	@ 	@&#mFFEE BHe$$$s   %r  )r|  r  r  r  r`   r_   rc   r  r  r/  r   rR  rc   r  r;  r   rw  r   r   r   r   rc   rM  )r   r<   r   r   r   r   rc   rM  r4  r   r}  r   r   r   r   rc   rP  )r   r<   r   r   r   r   rc   rP  )rk   r   rD  rE  r  rG  r%   r   r   r   r   r  r  r|  rO  r   r  rR  r   r   rt   rr   r  r    s0       S Sz *, #*, *, *, *, *, *,X 	 	 	 X X	 15
 
 
 
 X
6 
 
 
 X X
 15
 
 
 
 X
4    X 1 1 1 X1  ,0
 
 
 
 X
   ,0? ? ? ? X? ?C% % % % X%  ,0
 
 
 
 X
  ,0	@ 	@ 	@ 	@ X	@ ?C% % % % X% % %rt   r  c                      e Zd ZdZ	 	 d8d9dZeed:d                        Ze	 d;d< fd            Zeed:d                        Z	e	 d;d<d            Z
ej        d=d            Zeed>d                        Zed;d? fd            Zed@d            ZdAd ZdBd(ZdCd*Ze	 d;dDd,            Ze	 d;dDd-            ZdEd0Ze	 d;dFd1            Ze	 d;dGd2            ZdHd5Ze	 d;dId6            Ze	 d;dJd7            Z xZS )KRunnableLambdaa0  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
    Nr     Union[Union[Callable[[Input], Output], Callable[[Input], Iterator[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]]]]afunc3  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]]]]r`   r_   rc   r  c                   |	|| _         |}t          |          st          |          r|d}t          |          || _         |}nHt	          |          rt          d|          | _        |}n!dt          |           }t          |          	 ||| _        n|j	        dk    r|j	        | _        n# t          $ r Y nw xY wd| _        dS )aE  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.
        NzFunc was provided as a coroutine function, but afunc was also provided. If providing both, func should be a regular function to avoid ambiguity.Callable[[Input], Output]zEExpected a callable type for `func`.Instead got an unsupported type: z<lambda>)r  rH   rI   r~   callabler   r  rX  r`   rk   r  _repr)ro   r  r  r`   r  r   s         rr   r  zRunnableLambda.__init__  s   d DJ&+MT"" 	!&8&>&> 	! 3 
  nn$DJ MMd^^ 	!8$??DI MMA48JJA A  C.. 	 		':55)2	 	 	 	D	 %)


s   !B2 2
B?>B?r   c                :   t          | dd          p| j        }	 t          j        |          j        }t          t          |                                          d          }|r!|j        t          j	        j
        k    r|j        S n# t          $ r Y nw xY wt          S )z'The type of the input to this Runnable.r  N)r  r  r   r  r  r  r,  r   r   r  r  rZ  r   r  s       rr   r   zRunnableLambda.InputType0  s     tVT**8dj	&t,,7FtFMMOO44d;;K .{59J9PPP"-- 	 	 	D	
s   A*B 
BBr   r   r   c                F   t          | dd          p| j        }t          |t                    rt	          |                              dd          dd                             d          }t          d |D                       r0d |D             }t          | 	                    d	          |
          S t          |dd          }t          | 	                    d	          t          t                   |          S | j        t          k    r!t                                          |          S t          |          x}rDt          | 	                    d	          t                               |t          df          
          S t                                          |          S )zThe pydantic schema for the input to this Runnable.

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

        Returns:
            The input schema for this Runnable.
        r  Nzoperator.itemgetter(r  rv  z, c              3  l   K   | ]/}|d          dk    o|d         dk    ot          |          dk    V  0dS )r   'rv  rx   N)r|   r   ri  s     rr   r  z2RunnableLambda.get_input_schema.<locals>.<genexpr>P  sW        IMQ3D48s?Ds4yy1}     rt   c                2    i | ]}|d d         t           dfS )r   rv  .)r   r  s     rr   r   z3RunnableLambda.get_input_schema.<locals>.<dictcomp>S  s&    CCCT$qt*sCjCCCrt   r<   r   r   r   .)r  r  r   r   rd   replacesplitrU  rN   rs   r  r   r   rN  r   rC   r   fromkeys)ro   r   r  r   rV  r  	dict_keysrj   s          rr   r   zRunnableLambda.get_input_schema>  s    tVT**8djdJ'' 	 II%%&<bAA#2#FLLTRRE  QV     Y DCUCCC&t}}W'='=QWXXXXT<66F"g&&#Y #    >S  77++F3338>>>9 	"g&&"&--	C:"F"F   
 ww''///rt   c                   t          | dd          p| j        }	 t          j        |          }|j        t          j        j        k    rat          |j        dd          t          j        j	        t          j        j
        fv r"t          |j        dt          f          d         S |j        S n# t          $ r Y nw xY wt          S )zThe type of the output of this Runnable as a type annotation.

        Returns:
            The type of the output of this Runnable.
        r  N
__origin__r  r   )r  r  r   r  r  r  r  collectionsabcr
   r   r   rZ  r  s      rr   r   zRunnableLambda.OutputTypek  s     tVT**8dj	#D))C$(9(???30,EEO,O1J   #3#8*sfMMaPP,, @  	 	 	D	
s   BB* "B* *
B76B7c                ,   | j         }t          | dd           p| j        }t          |dd           }t          j        |          r,t          |t                    st          |t                    r|S t          | 
                    d          ||          S )Nr  r   r=   r   )r   r  r  r   r   r   r   r   r   rN   rs   r  s        rr   r   z RunnableLambda.get_output_schema  s     O	tVT**8dj|T22 OI&&	y,77	 9i00	
 MM(## 
 
 
 	
rt   list[Runnable]c                ~   t          | d          rt          | j                  }n't          | d          rt          | j                  }ng }g }|D ]k}t	          |t
                    r|                    |           -t	          t          |dd          t
                    r|                    |j                   l|S )zThe dependencies of this Runnable.

        Returns:
            The dependencies of this Runnable. If the function has nonlocal
            variables that are Runnables, they are considered dependencies.
        r  r  __self__N)	ri   rD   r  r  r   r^   r  r  r  )ro   objectsdepsobjs       rr   r  zRunnableLambda.deps  s     4   	,TY77GGT7## 	,TZ88GGG! 	* 	*C#x(( *C    GCT::HEE *CL)))rt   r   c                >    t          d | j        D                       S )Nc              3  .   K   | ]}|j         D ]}|V  d S r  r  )r   depr   s      rr   r  z.RunnableLambda.config_specs.<locals>.<genexpr>  sJ       '
 '
#2B'
 '
*.D'
 '
 '
 '
 '
 '
 '
rt   )rF   r  r   s    rr   r   zRunnableLambda.config_specs  s4     ' '
 '
 I'
 '
 '
 
 
 	
rt   RunnableConfig | Noner7   c                   | j         x}r+t                      }|                    |                     |                    }|                    |                     |                    }|D ]}|                                }|                                 |                                 |s|                    ||           W|	                    |          \  }}	|sd| d}
t          |
          |	sd| d}
t          |
          |                    ||           |                    |	|           n!t                                          |          }|S )Nry   r  r\  )r  r7   r   r   r   r   r  r  r   r  rZ  rN  )ro   r   r  r   r   r   r  	dep_graphdep_first_nodedep_last_noder   rj   s              rr   r   zRunnableLambda.get_graph  sd   94 	.GGE(=(=f(E(EFFJ..)?)?)G)GHHK ? ?MMOO	))+++((***  ?NN:{;;;;49LL4K4K1NM) .A#AAA(oo-( .@#@@@(oo-NN:~>>>NN=+>>>>?" GG%%f--Ert   r   rR  r  c                    t          |t                    rbt          | d          r t          |d          r| j        |j        k    S t          | d          r t          |d          r| j        |j        k    S dS dS )Nr  r  F)r   r  ri   r  r  r   s     rr   r  zRunnableLambda.__eq__  s    e^,, 	tV$$ /)?)? /yEJ..tW%% 1'%*A*A 1zU[005urt   rd   c                   | j         t          | d          rMt          | j        t                    r3dt          | j                  t          d          d          d| _         ngt          | d          r dt          | j                  pd d| _         n7t          | d          r dt          | j                  pd d| _         nd	| _         | j         S )
z)A string representation of this Runnable.Nr  zRunnableLambda(z	operator.r  z...r  zRunnableLambda(afunc=zRunnableLambda(...))	r  ri   r   r  r   rd   r|   rE   r  r   s    rr   r  zRunnableLambda.__repr__  s    :tV$$ 	3DIz)J)J 	3Ts49~~c+>N>N>P>P/QTTT

v&& 3W/@/K/K/TuWWW

w'' 3U,=dj,I,I,RUUUU 

 3
zrt   r   r<   r  rP   r*   r   r=   c           	        t          j        | j                  rFd }t          t	          d| j                  |||fi |D ]}||}	 ||z   }# t
          $ r |}Y w xY wnt          | j        |||fi |}t          |t                    ra|d         }|dk    rd|  d| d}t          |          |	                    |t          ||                                |dz
                      }t	          d	|          S )
N#Callable[[Input], Iterator[Output]]recursion_limitr   &Recursion limit reached when invoking  with input .r   r  r  r=   )r   r  r  r,   r   r~   r   r^   RecursionErrorr   r3   r  )	ro   r   r  r   r   r  r  r  r   s	            rr   _invokezRunnableLambda._invoke  sx    &ty11 	'+F5:DIFF	 
   ' ' >"FF'!'%$ ' ' '!&'' 2	5&+ 9? F fh'' 	$%67O!##WTWWuWWW  %S)))]])3355$3a$7   F Hf%%%s   AAArO   c                ~   K   t           d          r j        }nDt          j         j                  rd fdnd fdt                    dfd            }|}t          |          rd }t          t          dt          t          d|          ||fi |                    4 d {V 	 }t          d|          2 3 d {V }	||	}	 ||	z   }# t          $ r |	}Y !w xY w6 	 d d d           d {V  n# 1 d {V swxY w Y   n$t          t          d|          ||fi | d {V }t          |t                    rgd         }
|
dk    rd  d| d}t          |          |                    |t          |                                |
dz
                       d {V }t          d|          S )Nr  r   r<   r  rO   r   r*   r   r   rc   r=   c                    d }t          t          dj                  | ||                                fi |D ]}||}	 ||z   }# t          $ r |}Y w xY wt          d|          S )Nr  r=   )r,   r   r  get_syncr~   )r   r  r   r   r  r  ro   s         rr   r  z%RunnableLambda._ainvoke.<locals>.func(  s     04F!=BDINN#,,..	" "
 !" " / / ">%*FF/)/%#, / / /)./&111s   AAAc                R    t          j        | ||                                fi |S r  r,   r  r  r   r  r   r   ro   s       rr   r  z%RunnableLambda._ainvoke.<locals>.funcA  s;     8	5&+2F2F2H2H LR  rt   rw   c                 6   K   t          g| R i | d {V S r  r4   rw   r   r   r  s     rr   fz"RunnableLambda._ainvoke.<locals>.fK  9      ,VTKDKKKFKKKKKKKKKrt   zAsyncGenerator[Any, Any]r   rP  r  r   r  r  r  r   r  
r   r<   r  rO   r   r*   r   r   rc   r=   rw   r   r   r   rc   r   )ri   r  r   r  r  r   rI   rJ   r   r+   r~   r   r^   r  r   r3   r  )ro   r   r  r   r   r  r  r  rO  r  r  r   r  s   `  `        @rr   _ainvokezRunnableLambda._ainvoke  su      4!! ,	JEE*4955 #2 2 2 2 2 2 22      4[[L L L L L L [L Ee$$ 	'+F.1Z//#	 
 ! 	 	  + + + + + + + + #'+$ $ 
+ 
+ 
+ 
+ 
+ 
+ 
+% ~!&+%+e^FF( + + +%*FFF+$ $+ + + + + + + + + + + + + + + + + + + + + + + + + + +0 9Z'' GM       F fh'' 	$%67O!##WTWWuWWW  %S)))!>>)3355$3a$7         F Hf%%%sB   3C=C)
C=CC=C&#C=%C&&C==
D
Dr  c                    t          | d          r" | j        | j        |t          |          fi |S d}t	          |          )aa  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.
        r  zGCannot invoke a coroutine function synchronously.Use `ainvoke` instead.)ri   r  r  r-   r~   r  s        rr   r   zRunnableLambda.invoke  sc    ( 4   	)4)f%%  	   Xnnrt   c                V   K    | j         | j        |t          |          fi | d{V 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   s       rr   r   zRunnableLambda.ainvoke  s_      " -T,M&!!
 
 	
 
 
 
 
 
 
 
 	
rt   rw  rM  c           	   +    K   d}|D ]!}|s|}d}		 ||z   }# t           $ r |}Y w xY wt          j        | j                  r<d }t	          | j        |||fi |D ]#}	|	V  ||	}	 ||	z   }# t           $ r |	}Y  w xY wnt	          | j        |||fi |}t          |t                    rj|d         }
|
dk    rd|  d| d}t          |          |                    |t          ||
                                |
dz
  	                    D ]}	|	V  d S t          j        | j                  st          d
|          V  d S d S )NFTr  r   r  r  r  r   r  r=   )r~   r   r  r  r,   r   r^   r  rO  r3   r  r   )ro   r   r  r   r   ry  rz  r{  r  r  r  r   s               rr   r%  zRunnableLambda._transform  s!       	# 	#F
 ! # $#!FNEE  # # #"EEE# &ty11 	'+F5	5&+ 9?  
' 
' >"FF'!'%$ ' ' '!&'
' 2	5&+ 9? F
 fh'' 	)$%67O!##WTWWuWWW  %S))))3355$3a$7        ,TY77 	)x(((((((	) 	)s   &&%A++A:9A:c              +     K   t          | d          r* | j        || j        t          |          fi |E d {V  d S d}t	          |          )Nr  zGCannot stream a coroutine function synchronously.Use `astream` instead.)ri   r  r%  r-   r~   r  s        rr   r|  zRunnableLambda.transform  s       4   	!9t9f%%  	          )  C.. rt   c                <     | j         t          |g          |fi |S r  r+  r   s       rr   rO  zRunnableLambda.stream	  r  rt   r}  rP  c           	       K   d}|2 3 d {V }|s|}d}	 ||z   }# t           $ r |}Y #w xY w6 t           d          r j        }nNt          j         j                  rd}	t          |	          d fdt                    dfd            }
|
}t          |          rZd }t          dt          t          d|          ||fi |          2 3 d {V }|W V  ||}	 ||z   }# t           $ r |}Y &w xY w6 n$t          t          d|          ||fi | d {V }t          |t                    rqd         }|dk    rd  d| d}	t          |	          |                    |t          |                                |dz
                      2 3 d {V }|W V  6 d S t          |          st          d|          W V  d S d S )NFTr  zMCannot stream from a generator function asynchronously.Use .stream() instead.r   r<   r  rO   r   r*   r   r   rc   r=   c                R    t          j        | ||                                fi |S r  r  r  s       rr   r  z(RunnableLambda._atransform.<locals>.func3  s;     4Iufk.B.B.D.D HN  rt   rw   c                 6   K   t          g| R i | d {V S r  r  r  s     rr   r  z%RunnableLambda._atransform.<locals>.f=  r  rt   rP  r   r  r   r  r  r  r   r  r  r  )r~   ri   r  r   r  r  r   rI   r   r+   r   r^   r  rR  r3   r  )ro   r   r  r   r   ry  rz  r{  r  r   r  r  r  r  r  s   `  `          @rr   r'  zRunnableLambda._atransform  sl      ! 	# 	# 	# 	# 	# 	# 	#&
 ! # $#!FNEE  # # #"EEE# " 4!! 	JEE*4955 %-   nn$      4[[L L L L L L [L Ee$$ 	'+F#'-U++	 
  	  	  ' ' ' ' ' ' 'e >"FF'!'%$ ' ' '!&'!	  	 & 9Z''	 
        F fh'' 	)$%67O!##WTWWuWWW  %S)))%~~)3355$3a$7            e       $E** 	)x((((((((	) 	)s.   1..C?'C--C<;C<F(c               j   K    | j         || j        t          |          fi |2 3 d {V }|W V  6 d S r  )r"  r'  r-   )ro   r   r   r   r  s        rr   r  zRunnableLambda.atransformu  s       @D?&!!
 
 	
 
 	 	 	 	 	 	 	& LLLLL
 
 
s   2c               b   K   dfd} | j          |            |fi |2 3 d {V }|W V  6 d S )Nrc   r}  c                   K    W V  d S r  r   r1  s   rr   r2  z+RunnableLambda.astream.<locals>.input_aiter  r3  rt   r4  r5  r6  s    `    rr   rR  zRunnableLambda.astream  r7  r8  rC  )r  r  r  r  r`   r_   rc   r  r  r  r/  )rc   r  r0  )r   r  rc   r7   r  r;  )
r   r<   r  rP   r   r*   r   r   rc   r=   r  r<  r=  r>  r<  r>  r?  r=  )rk   r   rD  rE  r  rG  r%   r   r   r   r   r  cached_propertyr  r   r   r  r  r  r  r   r   r%  r|  rO  r'  r  rR  rf  rg  s   @rr   r  r    s
       + +Z "CR) R) R) R) R)h 
 
 
 X X
 15*0 *0 *0 *0 *0 *0 X*0X    X X* 15
 
 
 
 X
4    , 
 
 
 X X

       X4    X   +& +& +& +&Zb& b& b& b&H  ,0    X:  ,0
 
 
 
 X
.<) <) <) <)|  ,0! ! ! ! X!(  ,0? ? ? ? X?a) a) a) a)F  ,0    X  ,0
 
 
 
 X
 
 
 
 
rt   r  c                     e Zd ZU dZded<    ed          Zeed*d                        Z	e	 d+d,d            Z
eed-d                        Ze	 d+d,d            Zeed.d                        Zed+d/d            Zeed0d                        Zeed1d                        Zd2d Ze	 d+d3d"            Zd4d$Ze	 d+d3d%            Ze	 d+d5d)            Zd	S )6RunnableEachBasezRunnable that calls another Runnable for each element of the input sequence.

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

    See documentation for RunnableEach for more details.
    r  r  Tr  rc   r   c                0    t           | j        j                 S r  )r  r  r   r   s    rr   r   zRunnableEachBase.InputType  s     DJ())rt   Nr   r   r   c                    t          |                     d          t          | j                            |                   d f| j        j                  S )Nr<   r   )rN   rs   r  r  r   rj   r   r   s     rr   r   z!RunnableEachBase.get_input_schema  sT     MM'""TZ00889 1
 
 
 	
rt   type[list[Output]]c                0    t           | j        j                 S r  )r  r  r   r   s    rr   r   zRunnableEachBase.OutputType  s     DJ)**rt   c                    | j                             |          }t          |                     d          t          |         | j        j                  S )Nr=   r   )r  r   rN   rs   r  rj   r   )ro   r   r  s      rr   r   z"RunnableEachBase.get_output_schema  sP     --f55MM(##f 1
 
 
 	
rt   r   c                    | j         j        S r  r  r   r   s    rr   r   zRunnableEachBase.config_specs       z&&rt   r7   c                6    | j                             |          S r  )r  r   r   s     rr   r   zRunnableEachBase.get_graph  s    z##F+++rt   r  c                    dS rH  r   r  s    rr   r  z#RunnableEachBase.is_lc_serializable  rI  rt   r  c                
    g dS r  r   r  s    rr   r  z!RunnableEachBase.get_lc_namespace  r  rt   r  r  r  rP   r*   r   r  c                L    fd|D             } | j         j        ||fi |S )Nc                V    g | ]%}t                                                     &S r  r  r   rh   r   r  s     rr   r   z,RunnableEachBase._invoke.<locals>.<listcomp>  ?     
 
 
HIL;+@+@+B+BCCC
 
 
rt   )r  r  ro   r  r  r   r   r  s     ``  rr   r  zRunnableEachBase._invoke  sR    
 
 
 
 
MS
 
 
  tz::6:::rt   r   c                ,     | j         | j        ||fi |S r  )r  r  r   s       rr   r   zRunnableEachBase.invoke  s%     &t%dlE6LLVLLLrt   rO   c                \   K   fd|D             } | j         j        ||fi | d {V S )Nc                V    g | ]%}t                                                     &S r  r  r  s     rr   r   z-RunnableEachBase._ainvoke.<locals>.<listcomp>  r  rt   )r  r<  r  s     ``  rr   r  zRunnableEachBase._ainvoke  sh      
 
 
 
 
MS
 
 
 'TZ&vwAA&AAAAAAAAArt   c                <   K    | j         | j        ||fi | d {V S r  )r  r  r   s       rr   r   zRunnableEachBase.ainvoke  s;       -T,T]E6TTVTTTTTTTTTrt   r<   r  rm  c               N   K   t          d          D ]}d}t          |          d S )Nr   z1RunnableEach does not support astream_events yet.)r  rs  )ro   r   r   r   rh   r   s         rr   rv  zRunnableEachBase.astream_events  s:       q 	 	AEC%c***	 	rt   r  r  r/  )rc   r  r0  r1  r:  r9  )
r  r  r  rP   r   r*   r   r   rc   r  )r   r  r   r   r   r   rc   r  )
r  r  r  rO   r   r*   r   r   rc   r  r   r<   r   r   r   r  rc   rm  )rk   r   rD  rE  rF  r    re  rG  r%   r   r   r   r   r   r   r?  r  r  r  r   r  r   rv  r   rt   rr   r
  r
    s>          #""": $  L * * * X X* 15
 
 
 
 X
& + + + X X+ 15
 
 
 
 X
" ' ' ' X X' , , , , X,    X [ 3 3 3 X [3
; 
; 
; 
; EIM M M M XM

B 
B 
B 
B EIU U U U XU
  ,0	 	 	 	 X	 	 	rt   r
  c                       e Zd ZdZe	 dddd fd	            Zedd            Ze	 ddd            Zedddddd            ZddddddZ	 xZ
S )r  a_  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
    Nra   rb   r_   r`   rc   rd   c                   |p#| j         pd| j                                         d}t                                          ||          S )NzRunnableEach<rM  ra   )r`   r  rs   rN  rN  s      rr   rs   zRunnableEach.get_name/  sM     LtyL$LDJ4G4G4I4I$L$L$LwwT222rt   r   r   RunnableEach[Input, Output]c                B    t           | j        j        di |          S )Nr  r   )r  r  r  r  s     rr   r  zRunnableEach.bind6  s'    /$*/";";F";";<<<<rt   r   r   c                D    t           | j        j        |fi |          S )Nr  )r  r  r  r  s      rr   r  zRunnableEach.with_config:  s-     "8$*"8"J"J6"J"JKKKKrt   r  r  r  r  r  c               X    t          | j                            |||                    S )a  Bind lifecycle listeners to a Runnable, returning a new Runnable.

        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.

        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.
        r  r  )r  r  r  ro   r  r  r  s       rr   r  zRunnableEach.with_listeners@  s<    > *++!&8 ,  
 
 
 	
rt   r  c               X    t          | j                            |||                    S )a   Bind async lifecycle listeners to a Runnable, returning a new Runnable.

        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.

        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.
        r  r  )r  r  r  r'  s       rr   r  zRunnableEach.with_alistenerse  s<    0 *,,!&8 -  
 
 
 	
rt   r  r,  )r   r   rc   r#  )r   r   r   r   rc   r#  )r  r  r  r  r  r  rc   r#  )r  r  r  r  r  r  rc   r#  )rk   r   rD  rE  r%   rs   r  r  r  r  rf  rg  s   @rr   r  r    s        4 &*3EI3 3 3 3 3 3 3 X3 = = = X= 15L L L L XL
    "
 "
 "
 "
 "
 X"
N -1*.,0
 
 
 
 
 
 
 
 
 
rt   r  c                      e Zd ZU dZded<   	  ee          Zded<   	  ee          Z	ded<   	  ee
          Zd	ed
<   	 dZded<   	 dZded<   	  ed          ZdddddddY fdZe	 dZddd[d!            Zeed\d#                        Zeed]d%                        Ze	 dZd^ fd'            Ze	 dZd^ fd(            Zeed_d*                        ZedZd`d,            Zeedad.                        Zeedbd0                        Zdcd2Ze	 dZddd6            Ze	 dZddd7            Ze	 dZd8d9ded?            Z e	 dZd8d9ded@            Z!e"	 dZd8d9dfdE            Z#e"	 dZdgdH            Z#e	 dZd8d9dhdI            Z#e"	 dZd8d9didK            Z$e"	 dZdjdM            Z$e	 dZd8d9dkdN            Z$e	 dZdldP            Z%e	 dZdmdR            Z&e	 dZdndT            Z'e	 dZdodV            Z(e	 dZdpdX            Z) xZ*S )qRunnableBindingBasezRunnable that delegates calls to another Runnable with a set of kwargs.

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

    See documentation for RunnableBinding for more details.
    r  r  r  zMapping[str, Any]r   r*   r   z0list[Callable[[RunnableConfig], RunnableConfig]]r  Nr  r  r  Tr  )r   r   r  r  r  Optional[Mapping[str, Any]]r   :Optional[list[Callable[[RunnableConfig], RunnableConfig]]]'Optional[Union[type[Input], BaseModel]](Optional[Union[type[Output], BaseModel]]other_kwargsr   rc   r  c          
     f     t                      j        d||pi |pi |pg ||d| |pi | _        dS )a>  Create a RunnableBinding from a Runnable and kwargs.

        Args:
            bound: The underlying Runnable that this Runnable delegates calls to.
            kwargs: optional kwargs to pass to the underlying Runnable, when running
                    the underlying Runnable (e.g., via `invoke`, `batch`,
                    `transform`, or `stream` or async variants)
                    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.
        r  r   r   r  r  r  Nr   )rN  r  r   )	ro   r  r   r   r  r  r  r/  rj   s	           rr   r  zRunnableBindingBase.__init__  se    @ 	 	
<R<R-3/1	
 	
 	
 	
 	
 lrt   ra   rb   r_   r`   rd   c               :    | j                             ||          S )Nra   )r  rs   )ro   rb   r`   s      rr   rs   zRunnableBindingBase.get_name  s     z""6"555rt   ru   c                R    | j         t          d| j                   n| j        j        S )Nru   )r  r   r  r   r   s    rr   r   zRunnableBindingBase.InputType  s/    
 %1  6777%	
rt   r   c                R    | j         t          d| j                   n| j        j        S )Nr   )r  r   r  r   r   s    rr   r   zRunnableBindingBase.OutputType  s/    
 &2 !8999&	
rt   r   c                    | j         !t                                          |          S | j                            t	          | j        |                    S r  )r  rN  r   r  r2   r   rV  s     rr   r   z$RunnableBindingBase.get_input_schema  sH     !-77++F333z**=f+M+MNNNrt   c                    | j         !t                                          |          S | j                            t	          | j        |                    S r  )r  rN  r   r  r2   r   rV  s     rr   r   z%RunnableBindingBase.get_output_schema  sH     ".77,,V444z++M$+v,N,NOOOrt   r   c                    | j         j        S r  r  r   s    rr   r   z RunnableBindingBase.config_specs  r  rt   r7   c                \    | j                             |                     |                    S r  )r  r   _merge_configsr   s     rr   r   zRunnableBindingBase.get_graph  s&    z##D$7$7$?$?@@@rt   r  c                    dS rH  r   r  s    rr   r  z&RunnableBindingBase.is_lc_serializable  rI  rt   r  c                
    g dS )zmGet the namespace of the langchain object.

        Defaults to ["langchain", "schema", "runnable"].
        r  r   r  s    rr   r  z$RunnableBindingBase.get_lc_namespace  s     3222rt   r  c                d    t          | j        g|R  t          gfd| j        D             R  S )Nc              3  .   K   | ]} |          V  d S r  r   )r   r  r   s     rr   r  z5RunnableBindingBase._merge_configs.<locals>.<genexpr>  s+      &P&PQqqyy&P&P&P&P&P&Prt   )r2   r   r  )ro   r  r   s     @rr   r9  z"RunnableBindingBase._merge_configs  sH    t{5W555VQ&P&P&P&P$:O&P&P&PQQQQrt   r   r<   r=   c                b     | j         j        ||                     |          fi i | j        |S r  )r  r   r9  r   r   s       rr   r   zRunnableBindingBase.invoke!  sL     !tz ''
 
 (''
 
 	
rt   c                r   K    | j         j        ||                     |          fi i | j        | d {V S r  )r  r   r9  r   r   s       rr   r   zRunnableBindingBase.ainvoke.  sn       (TZ'''
 
 (''
 
 
 
 
 
 
 
 	
rt   Fr   r  r  r  r  r  c                    t          t                    rt          d fdD                       }n) fdt          t	          |                    D             }  j        j        ||fd|ii  j        |S )Nlist[RunnableConfig]c                :    g | ]}                     |          S r   r9  r   confro   s     rr   r   z-RunnableBindingBase.batch.<locals>.<listcomp>G  '    >>>t$$T**>>>rt   c                :    g | ]}                               S r   rC  r   rh   r   ro   s     rr   r   z-RunnableBindingBase.batch.<locals>.<listcomp>J  '    OOOqt**622OOOrt   r  )r   r  r   r  r|   r  r  r   ro   r  r   r  r   r  s   ` `   rr   r  zRunnableBindingBase.batch;  s     fd## 	P&>>>>v>>> GG
 POOOOE#f++<N<NOOOGtz
 
 0
 (''	
 
 	
rt   c               
   K   t          t                    rt          d fdD                       }n) fdt          t	          |                    D             }  j        j        ||fd|ii  j        | d {V S )NrA  c                :    g | ]}                     |          S r   rC  rD  s     rr   r   z.RunnableBindingBase.abatch.<locals>.<listcomp>^  rF  rt   c                :    g | ]}                               S r   rC  rH  s     rr   r   z.RunnableBindingBase.abatch.<locals>.<listcomp>a  rI  rt   r  )r   r  r   r  r|   r  r<  r   rJ  s   ` `   rr   r<  zRunnableBindingBase.abatchR  s       fd## 	P&>>>>v>>> GG
 POOOOE#f++<N<NOOOG&TZ&
 
 0
 (''	
 
 
 
 
 
 
 
 	
rt   r  r  r  r  c                   d S r  r   r  s        rr   r  z&RunnableBindingBase.batch_as_completedi  r  rt   r  r  c                   d S r  r   r  s        rr   r  z&RunnableBindingBase.batch_as_completeds  r!  rt   c             +  `   K   t          t                    rt          d fdD                       }n) fdt          t	          |                    D             }|r'  j        j        ||fd|ii  j        |E d {V  d S   j        j        ||fd|ii  j        |E d {V  d S )NrA  c                :    g | ]}                     |          S r   rC  rD  s     rr   r   z:RunnableBindingBase.batch_as_completed.<locals>.<listcomp>  rF  rt   c                :    g | ]}                               S r   rC  rH  s     rr   r   z:RunnableBindingBase.batch_as_completed.<locals>.<listcomp>  rI  rt   r  )r   r   r   r  r|   r  r  r   rJ  s   ` `   rr   r  z&RunnableBindingBase.batch_as_completed}  sW      fh'' 	P&>>>>v>>> GG
 POOOOE#f++<N<NOOOG 	4tz4  #4 ,T[+F+	           5tz4  #4 ,T[+F+	          rt   r=  c                   d S r  r   r  s        rr   r?  z'RunnableBindingBase.abatch_as_completed  r@  rt   rA  c                   d S r  r   r  s        rr   r?  z'RunnableBindingBase.abatch_as_completed  rC  rt   c                 K   t          t                    rt          d fdD                       }n) fdt          t	          |                    D             }|r/  j        j        ||fd|ii  j        |2 3 d {V }|W V  6 d S   j        j        ||fd|ii  j        |2 3 d {V }|W V  6 d S )NrA  c                :    g | ]}                     |          S r   rC  rD  s     rr   r   z;RunnableBindingBase.abatch_as_completed.<locals>.<listcomp>  rF  rt   c                :    g | ]}                               S r   rC  rH  s     rr   r   z;RunnableBindingBase.abatch_as_completed.<locals>.<listcomp>  rI  rt   r  )r   r   r   r  r|   r  r?  r   )ro   r  r   r  r   r  ri  s   ` `    rr   r?  z'RunnableBindingBase.abatch_as_completed  s      fh'' 	P&>>>>v>>> GG
 POOOOE#f++<N<NOOOG 	<dj<  #4 ,T[+F+	        d 




   =dj<  #4 ,T[+F+	        d 




  s   B0B=rM  c              +  v   K    | j         j        ||                     |          fi i | j        |E d {V  d S r  )r  rO  r9  r   r   s       rr   rO  zRunnableBindingBase.stream  sx       %4:$''
 
 (''
 
 	
 	
 	
 	
 	
 	
 	
 	
 	
rt   rP  c                  K    | j         j        ||                     |          fi i | j        |2 3 d {V }|W V  6 d S r  )r  rR  r9  r   ro   r   r   r   ri  s        rr   rR  zRunnableBindingBase.astream  s       -$*,''
 
 (''
 
 	 	 	 	 	 	 	$
 JJJJJ
 
 
   A rm  c                  K    | j         j        ||                     |          fi i | j        |2 3 d {V }|W V  6 d S r  )r  rv  r9  r   rZ  s        rr   rv  z"RunnableBindingBase.astream_events  s       4$*34&&v..
 
2KT[2KF2K
 
 	 	 	 	 	 	 	$ JJJJJ
 
 
r[  rw  c              +  v   K    | j         j        ||                     |          fi i | j        |E d {V  d S r  )r  r|  r9  r   r   s       rr   r|  zRunnableBindingBase.transform  sx       (4:'''
 
 (''
 
 	
 	
 	
 	
 	
 	
 	
 	
 	
rt   r}  c                  K    | j         j        ||                     |          fi i | j        |2 3 d {V }|W V  6 d S r  )r  r  r9  r   rZ  s        rr   r  zRunnableBindingBase.atransform  s       0$*/''
 
 (''
 
 	 	 	 	 	 	 	$
 JJJJJ
 
 
r[  )r  r  r   r+  r   r   r  r,  r  r-  r  r.  r/  r   rc   r  r  r,  r-  r.  r/  r0  r1  r:  r9  )r  r   rc   r*   r<  r5  r6  r7  r8  r9  r:  r;  r<  r=  r   r  r  )+rk   r   rD  rE  rF  r!   r   r   r*   r   r  r  r  r  r    re  r  r%   rs   rG  r   r   r   r   r   r   r?  r  r  r9  r   r   r  r<  r   r  r?  rO  rR  rv  r|  r  rf  rg  s   @rr   r*  r*    s          #"""B %d ; ; ;F;;;; #U>BBBFBBBB8INJ J J     C (,++++
 )-,,,,
 : $  L /3+/ EIGK,# ,# ,# ,# ,# ,# ,# ,#\ &*6EI6 6 6 6 6 X6
 
 
 
 X X
 
 
 
 X X
 15O O O O O O XO 15P P P P P P XP ' ' ' X X' A A A A XA    X [ 3 3 3 X [3R R R R  ,0

 

 

 

 X

  ,0

 

 

 

 X

  IM

 #(
 
 
 
 
 X
,  IM

 #(
 
 
 
 
 X
,  MQ+
 -2+ + + + + X+  MQ= = = = X=  MQ
 #(     X>  MQ0
 -20 0 0 0 0 X0  MQB B B B XB  MQ
 #(     X@  ,0

 

 

 

 X

  ,0    X  ,0	 	 	 	 X	  ,0

 

 

 

 X

  ,0    X    rt   r*  c                      e Zd ZdZedd            Ze	 ddd
            Zedddddd            Ze	 	 ddd            Zedd            Z	ed d            Z
dS )!r  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   r   rc   r  c                |    |                      | j        | j        | j        i | j        || j        | j                  S )a  Bind additional kwargs to a Runnable, returning a new Runnable.

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

        Returns:
            A new Runnable with the same type and config as the original,
            but with the additional kwargs bound.
        )r  r   r  r   r  r  )rj   r  r   r  r   r  r  r  s     rr   r  zRunnableBinding.bindE  sJ     ~~*;!2,dk,V,"4#6  
 
 	
rt   Nr   r   c           	         |                      | j        | j        t          di | j        |pi |          | j        | j        | j                  S )Nr*   r1  )rj   r  r   r   r   r  r  r  r  s      rr   r  zRunnableBinding.with_configY  s_     ~~*;(*UT[*UV\r*Uf*UVV!2"4#6  
 
 	
rt   r  r  r  r  r  c                   ddl m dfd}|                     | j        | j        | j        |g| j        z   | j        | j                  S )	a  Bind lifecycle listeners to a Runnable, returning a new Runnable.

        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:
            The Runnable 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.
        r   r  r   r*   rc   c                (    d |           giS r  r   r  s    rr   listener_config_factoryz?RunnableBinding.with_listeners.<locals>.listener_config_factory  s6    ''%!)%!)	  	 	rt   r1  )r   r*   rc   r*   )	r  r  rj   r  r   r   r  r  r  )ro   r  r  r  rd  r  s    ``` @rr   r  zRunnableBinding.with_listenersi  s    : 	NMMMMM
	 
	 
	 
	 
	 
	 
	 
	 
	 ~~*;;569NN"4#6  
 
 	
rt   r  r-  r  r.  c                    |                      | j        | j        | j        | j        ||n| j        ||n| j                  S )Nr1  )rj   r  r   r   r  r  r  r  s      rr   r  zRunnableBinding.with_types  sT     ~~*;;!2(4

$:P  +6D<S  
 
 	
rt   c                r    |                       | j        j        di || j        | j        | j                  S )N)r  r   r   r  r   )rj   r  r  r   r   r  r  s     rr   r  zRunnableBinding.with_retry  sE    ~~'$*'11&11;;!2	  
 
 	
rt   r`   rd   c                    t           j        |          t                    rt          j                  j                            d          x}r|j        t          j        j	        k    rt                    d fd            }|S |j        t          j        j        k    rXt          t          j                  j                                      d          t                    d fd            }|S S )	Nr   rw   r   r   rc   c                 f     | dt          j        |                    dd                     i|S )Nr   )r2   r   r1  )rw   r   attrro   s     rr   wrapperz,RunnableBinding.__getattr__.<locals>.wrapper  sF    4,T[&**Xt:T:TUU !  rt   c                     t          |           dz   k    r5t          |           }t          j        |                   |<    |i |S  | dt          j        |                    dd                     i|S )Nr   r   )r|   r  r2   r   r1  )rw   r   argslri  r  ro   s      rr   rj  z,RunnableBinding.__getattr__.<locals>.wrapper  s    4yyC!G++ $T

%24;c
%K%Kc
#tU5f5554,T[&**Xt:T:TUU !  rt   r  )r  r  r  r   r  r  r   kindr  KEYWORD_ONLYr   POSITIONAL_OR_KEYWORDr  index)ro   r`   config_paramrj  ri  r  s   `   @@rr   __getattr__zRunnableBinding.__getattr__  s   tz4((D>> 	#-d33>BB8LLLL	  G$5$BBBt        G$5$KKK7,T22=>>DDXNNt	 	 	 	 	 	 	 	 rt   r@  r  rA  rB  rC  )r  r-  r  r.  rc   r  )r`   rd   rc   r   )rk   r   rD  rE  r%   r  r  r  r  r  rr  r   rt   rr   r  r    s       - -^ 
 
 
 X
&  ,0
 
 
 
 X
    1
 1
 1
 1
 1
 X1
f  ?C@D
 
 
 
 X
$ 
 
 
 X
 " " " X" " "rt   r  c                      e Zd Zd	dZdS )
_RunnableCallableSync_inr<   r   r*   rc   r=   c                  d S r  r   ro   ru  r   s      rr   __call__z_RunnableCallableSync.__call__  r   rt   N)ru  r<   r   r*   rc   r=   rk   r   rD  rx  r   rt   rr   rt  rt    s        OOOOOOrt   rt  c                      e Zd Zd	dZdS )
_RunnableCallableAsyncru  r<   r   r*   rc   Awaitable[Output]c                  d S r  r   rw  s      rr   rx  z_RunnableCallableAsync.__call__  s    Crt   N)ru  r<   r   r*   rc   r|  ry  r   rt   rr   r{  r{    s(                   rt   r{  c                      e Zd Zd	dZdS )
_RunnableCallableIteratorru  rw  r   r*   rc   rM  c                  d S r  r   rw  s      rr   rx  z"_RunnableCallableIterator.__call__  s    3rt   N)ru  rw  r   r*   rc   rM  ry  r   rt   rr   r  r    s(             rt   r  c                      e Zd Zd	dZdS )
_RunnableCallableAsyncIteratorru  r}  r   r*   rc   rP  c                  d S r  r   rw  s      rr   rx  z'_RunnableCallableAsyncIterator.__call__  s     #rt   N)ru  r}  r   r*   rc   rP  ry  r   rt   rr   r  r    s(        $ $ $ $ $ $rt   r  thingr  r  c                   t          | t                    r| S t          |           st          j        |           rt          |           S t          |           rt          t          d|                     S t          | t                    rt          dt          |                     S dt          |            }t          |          )zCoerce a Runnable-like object into a Runnable.

    Args:
        thing: A Runnable-like object.

    Returns:
        A Runnable.

    Raises:
        TypeError: If the object is not Runnable-like.
    r  r  zGExpected a Runnable, callable or dict.Instead got an unsupported type: )r   r^   rI   r   r  r  r  r  r   r   r   rX  r~   )r  r   s     rr   r   r     s     %"" %   (G$?$F$F ( ''' Hd#>FFGGG% H-/?/F/FGGG	:,0KK	: 	:  C..rt   r  .Callable[[Input], Coroutine[Any, Any, Output]]c                    d S r  r   r  s    rr   chainr    	     "crt   r  c                    d S r  r   r  s    rr   r  r  $  r  rt   (Callable[[Input], AsyncIterator[Output]]c                    d S r  r   r  s    rr   r  r  *  r  rt   r  c                    d S r  r   r  s    rr   r  r  0  r  rt   Union[Callable[[Input], Output], Callable[[Input], Iterator[Output]], Callable[[Input], Coroutine[Any, Any, Output]], Callable[[Input], AsyncIterator[Output]]]c                     t          |           S )a  Decorate a function to make it a Runnable.

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

    Args:
        func: A callable.

    Returns:
        A Runnable.

    Example:

    .. 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  s    rr   r  r  6  s    H $rt   )rh  ri  r   r   rc   r   )r  r  rc   r  )r  r  rc   r  )r  r  rc   r  )r  r  rc   r  )r  r  rc   r  )r  r  rc   r  )rE  
__future__r   rI  r  rP  r  r   ry  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   pydanticr   r    r!   r"   typing_extensionsr#   r$   r%   langchain_core._apir&    langchain_core.load.serializabler'   r(   r)   langchain_core.runnables.configr*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r  r7   langchain_core.runnables.utilsr8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   langchain_core.utils.aiterrJ   rK   rL   langchain_core.utils.iterrM   langchain_core.utils.pydanticrN   r  rO   rP   r   rR   r  rT   RunnableWithFallbacksTr  rU   langchain_core.runnables.schemarV   r*  rW   rh  rX   rY   r  rZ   langchain_core.tracers.schemasr[   r\   r^   rJ  rs  r  r   r   rd   r   RunnableMapr  r  r  r
  r  r*  r  rt  r{  r  r  r  r   r  r   rt   rr   <module>r     s	   / / " " " " " "                   # # # # # # # #                  5 4 4 4 4 4 4 4       " " " " " " " "                                      = < < < < < < < < < < < 9 9 9 9 9 9 9 9 9 9 . . . . . .         
                            1 0 0 0 0 0                                       ( @ ? ? ? ? ? ? ? ? ? - - - - - - 9 9 9 9 9 9 3        ?>>>>>      GFFFFF;;;;;;------        DCCCCC222222 	h$
 h$
 h$
 h$
 h$
wuf}%s h$
 h$
 h$
VIA
 A
 A
 A
 A
<%-)@ A
 A
 A
H* * * *4,* ,* ,* ,*^U U U U U+E6M: U U Up~ ~ ~ ~ ~+E4S>,AB ~ ~ ~D g% g% g% g% g%/ g% g% g%T	a a a a aXeVm, a a aH    +DKf,EF   Dm
 m
 m
 m
 m
#E6M2 m
 m
 m
`N N N N N.uf}= N N NbG G G G G)%-8 G G GTP P P P PHUF]3 P P P         XeVm4           7   $ $ $ $ $XeVm%< $ $ $ UF]eWf_eWi''(huo 001mE"#]6%::;%-(5&=)eVm,"5&=1CH	   6 
" " " 
"
 
" " " 
"
 
" " " 
"
 
" " " 
"
$  $  $  $  $  $ rt   