a
    ”˜ëjÒ?  ã                   @   sÐ   d Z ddlmZmZmZmZmZ ddl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mZmZmZ ddlmZmZmZmZmZ dd	l m!Z!m"Z"m#Z#m$Z$ G d
d„ dee"e#f ƒZ%dS )z?Runnable that selects which branch to run based on a condition.é    )ÚAsyncIteratorÚ	AwaitableÚIteratorÚMappingÚSequence)ÚAnyÚCallableÚOptionalÚUnionÚcast)Ú	BaseModelÚ
ConfigDict)Úoverride)ÚCONTEXT_CONFIG_PREFIXÚCONTEXT_CONFIG_SUFFIX_SET)ÚRunnableÚRunnableLikeÚRunnableSerializableÚcoerce_to_runnable)ÚRunnableConfigÚensure_configÚ%get_async_callback_manager_for_configÚget_callback_manager_for_configÚpatch_config)ÚConfigurableFieldSpecÚInputÚOutputÚget_unique_config_specsc                	       s’  e Zd ZU dZeeeeef eee	f f  e
d< eee	f e
d< eeeeeef eegef eegee f f ef ef ddœ‡ fdd„Zedd	�Zeed
œdd„ƒZeeee d
œdd„ƒƒZedee ee dœ‡ fdd„ƒZeeee d
œdd„ƒƒZedeee e e	dœdd„ƒZ!edeee e e	dœdd„ƒZ"ed eee ee  e#e	 dœdd„ƒZ$ed!eee ee  e%e	 dœdd„ƒZ&‡  Z'S )"ÚRunnableBranchaz  Runnable that selects which branch to run based on a condition.

    The Runnable is initialized with a list of (condition, Runnable) pairs and
    a default branch.

    When operating on an input, the first condition that evaluates to True is
    selected, and the corresponding Runnable is run on the input.

    If no condition evaluates to True, the default branch is run on the input.

    Examples:

        .. code-block:: python

            from langchain_core.runnables import RunnableBranch

            branch = RunnableBranch(
                (lambda x: isinstance(x, str), lambda x: x.upper()),
                (lambda x: isinstance(x, int), lambda x: x + 1),
                (lambda x: isinstance(x, float), lambda x: x * 2),
                lambda x: "goodbye",
            )

            branch.invoke("hello")  # "HELLO"
            branch.invoke(None)  # "goodbye"

    ÚbranchesÚdefaultN)r   Úreturnc           	         sì   t |ƒdk rd}t|ƒ‚|d }t|tttfƒs<d}t|ƒ‚tdttd|ƒƒƒ}g }|dd… D ]v}t|t	t
fƒsˆdt|ƒ› �}t|ƒ‚t |ƒdkrªd	t |ƒ› �}t|ƒ‚|\}}td
t|ƒƒ}t|ƒ}| ||f¡ q`tƒ j||d� dS )að  A Runnable that runs one of two branches based on a condition.

        Args:
            *branches: A list of (condition, Runnable) pairs.
                Defaults a Runnable to run if no condition is met.

        Raises:
            ValueError: If the number of branches is less than 2.
            TypeError: If the default branch is not Runnable, Callable or Mapping.
            TypeError: If a branch is not a tuple or list.
            ValueError: If a branch is not of length 2.
        é   z-RunnableBranch requires at least two brancheséÿÿÿÿz=RunnableBranch default must be Runnable, callable or mapping.zRunnable[Input, Output]r   Nz5RunnableBranch branches must be tuples or lists, not zARunnableBranch branches must be tuples or lists of length 2, not zRunnable[Input, bool])r   r    )ÚlenÚ
ValueErrorÚ
isinstancer   r   r   Ú	TypeErrorr   r   ÚtupleÚlistÚtypeÚappendÚsuperÚ__init__)	Úselfr   Úmsgr    Zdefault_Z	branches_ÚbranchÚ	conditionÚrunnable©Ú	__class__© ú^/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain_core/runnables/branch.pyr-   J   sF    þÿÿÿÿÿþzRunnableBranch.__init__T)Zarbitrary_types_allowed)r!   c                 C   s   dS )z*Return True as this class is serializable.Tr5   ©Úclsr5   r5   r6   Úis_lc_serializable“   s    z!RunnableBranch.is_lc_serializablec                 C   s   g d¢S )zyGet the namespace of the langchain object.

        Returns:
            ``["langchain", "schema", "runnable"]``
        )Z	langchainZschemar2   r5   r7   r5   r5   r6   Úget_lc_namespace˜   s    zRunnableBranch.get_lc_namespace)Úconfigr!   c                    sd   | j gdd„ | jD ƒ dd„ | jD ƒ }|D ]*}| |¡ ¡  d¡d ur,| |¡  S q,tƒ  |¡S )Nc                 S   s   g | ]\}}|‘qS r5   r5   ©Ú.0Ú_Úrr5   r5   r6   Ú
<listcomp>¨   ó    z3RunnableBranch.get_input_schema.<locals>.<listcomp>c                 S   s   g | ]\}}|‘qS r5   r5   ©r=   r?   r>   r5   r5   r6   r@   ©   rA   r*   )r    r   Úget_input_schemaZmodel_json_schemaÚgetr,   )r.   r;   Z	runnablesr2   r3   r5   r6   rC   ¢   s    ÿþÿÿÿzRunnableBranch.get_input_schemac                 C   sX   t dd„ | jgdd„ | jD ƒ dd„ | jD ƒ D ƒƒ}tdd„ |D ƒƒrTd}t|ƒ‚|S )Nc                 s   s   | ]}|j D ]
}|V  qqd S ©N)Úconfig_specs)r=   ÚstepÚspecr5   r5   r6   Ú	<genexpr>¸   s   
úz.RunnableBranch.config_specs.<locals>.<genexpr>c                 S   s   g | ]\}}|‘qS r5   r5   r<   r5   r5   r6   r@   ¼   rA   z/RunnableBranch.config_specs.<locals>.<listcomp>c                 S   s   g | ]\}}|‘qS r5   r5   rB   r5   r5   r6   r@   ½   rA   c                 s   s&   | ]}|j  t¡o|j  t¡V  qd S rE   )ÚidÚ
startswithr   Úendswithr   )r=   Úsr5   r5   r6   rI   Á   s   þz.RunnableBranch cannot contain context setters.)r   r    r   Úanyr%   )r.   Úspecsr/   r5   r5   r6   rF   µ   s    ÿþý	ýzRunnableBranch.config_specs)Úinputr;   Úkwargsr!   c              
   K   s"  t |ƒ}t|ƒ}|jd|| d¡p(|  ¡ | dd¡d�}z¨t| jƒD ]p\}}|\}}	|j|t	||j
d|d › �d�d�d	�}
|
rD|	j|fd
t	||j
d|d › �d�d�i|¤Ž} qÞqD| jj|fd
t	||j
dd�d�i|¤Ž}W n2 t�y } z| |¡ ‚ W Y d}~n
d}~0 0 | |¡ |S )ad  First evaluates the condition, then delegate to true or false branch.

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

        Returns:
            The output of the branch that was run.
        NÚrun_nameÚrun_id©ÚnamerS   ú
condition:é   ©Útag©Ú	callbacks©r;   r;   úbranch:úbranch:default)r   r   Úon_chain_startrD   Úget_nameÚpopÚ	enumerater   Úinvoker   Ú	get_childr    ÚBaseExceptionÚon_chain_errorÚon_chain_end©r.   rP   r;   rQ   Úcallback_managerÚrun_managerÚidxr0   r1   r2   Úexpression_valueÚoutputÚer5   r5   r6   rc   Ê   sX    
üþþÿþþúÿÿþû


zRunnableBranch.invokec              
   Ë   sF  t |ƒ}t|ƒ}|jd || d¡p(|  ¡ | dd ¡d�I d H }zºt| jƒD ]|\}}|\}}	|j|t	||j
d|d › �d�d�d�I d H }
|
rJ|	j|fd	t	||j
d
|d › �d�d�i|¤ŽI d H } qöqJ| jj|fd	t	||j
dd�d�i|¤ŽI d H }W n8 t�y0 } z| |¡I d H  ‚ W Y d }~n
d }~0 0 | |¡I d H  |S )NrR   rS   rT   rV   rW   rX   rZ   r\   r;   r]   r^   )r   r   r_   rD   r`   ra   rb   r   Úainvoker   rd   r    re   rf   rg   rh   r5   r5   r6   ro     sX    
üþþÿþþúÿÿþûzRunnableBranch.ainvokec              
   k   sÄ  t |ƒ}t|ƒ}|jd|| d¡p(|  ¡ | dd¡d�}d}d}�z@t| jƒD ]º\}}	|	\}
}|
j|t	||j
d|d › �d�d	�d
�}|rN|j|fdt	||j
d|d › �d�d	�i|¤ŽD ]F}|V  |rº|du rÖ|}qºz|| }W qº t� yþ   d}d}Y qº0 qº �q€qN| jj|fdt	||j
dd�d	�i|¤ŽD ]L}|V  |�r2|du �rR|}n*z|| }W n t�yz   d}d}Y n0 �q2W n2 t�y´ } z| |¡ ‚ W Y d}~n
d}~0 0 | |¡ dS ©ac  First evaluates the condition, then delegate to true or false branch.

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

        Yields:
            The output of the branch that was run.
        NrR   rS   rT   TrV   rW   rX   rZ   r\   r;   r]   Fr^   )r   r   r_   rD   r`   ra   rb   r   rc   r   rd   Ústreamr'   r    re   rf   rg   ©r.   rP   r;   rQ   ri   rj   Zfinal_outputZfinal_output_supportedrk   r0   r1   r2   rl   Úchunkrn   r5   r5   r6   rq   5  s€    
üþþÿþþú
ÿ
þþú


zRunnableBranch.streamc              
   K  sð  t |ƒ}t|ƒ}|jd|| d¡p(|  ¡ | dd¡d�I dH }d}d}�zZt| jƒD ]Ê\}}	|	\}
}|
j|t	||j
d|d › �d�d	�d
�I dH }|rT|j|fdt	||j
d|d › �d�d	�i|¤Ž2 zN3 dH W }|V  |rÆ|du rê|}qÆz|| }W qÆ t�y   d}d}Y qÆ0 qÆ6  �q qT| jj|fdt	||j
dd�d	�i|¤Ž2 zT3 dH W }|V  |�rH|du �rp|}n*z|| }W n t�y˜   d}d}Y n0 �qH6 W n8 t�yÚ } z| |¡I dH  ‚ W Y d}~n
d}~0 0 | |¡I dH  dS rp   )r   r   r_   rD   r`   ra   rb   r   ro   r   rd   Úastreamr'   r    re   rf   rg   rr   r5   r5   r6   rt   ‰  s€    
üþþÿþþúÿ
þþú
zRunnableBranch.astream)N)N)N)N)N)(Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r(   r   r   Úboolr   Ú__annotations__r
   r   r   r   r-   r   Zmodel_configÚclassmethodr9   r   r)   Ústrr:   r	   r   r*   r   rC   Úpropertyr   rF   r   rc   ro   r   rq   r   rt   Ú__classcell__r5   r5   r3   r6   r   (   s€   
$
þÿûÿøÿóEÿ ÿþ ÿ
þ: ÿ
þ/ ýûS ýûr   N)&rx   Úcollections.abcr   r   r   r   r   Útypingr   r   r	   r
   r   Zpydanticr   r   Ztyping_extensionsr   Z%langchain_core.beta.runnables.contextr   r   Zlangchain_core.runnables.baser   r   r   r   Zlangchain_core.runnables.configr   r   r   r   r   Zlangchain_core.runnables.utilsr   r   r   r   r   r5   r5   r5   r6   Ú<module>   s   