a
    ”˜ëjJ6  ã                   @   sÜ   d Z ddlmZmZmZmZ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mZ er¤ddlmZmZ ed	eeƒZed
ƒZG dd„ dedd�Z G dd„ deeef ƒZ!dS )z-Runnable that retries a Runnable if it fails.é    )ÚTYPE_CHECKINGÚAnyÚOptionalÚTypeVarÚUnionÚcast)ÚAsyncRetryingÚRetryCallStateÚ
RetryErrorÚRetryingÚretry_if_exception_typeÚstop_after_attemptÚwait_exponential_jitter)Ú	TypedDictÚoverride)ÚRunnableBindingBase)ÚRunnableConfigÚpatch_config)ÚInputÚOutput)ÚAsyncCallbackManagerForChainRunÚCallbackManagerForChainRunÚTÚUc                   @   s2   e Zd ZU dZeed< eed< eed< eed< dS )ÚExponentialJitterParamsz4Parameters for ``tenacity.wait_exponential_jitter``.ÚinitialÚmaxZexp_baseÚjitterN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚfloatÚ__annotations__© r$   r$   ú]/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain_core/runnables/retry.pyr   %   s   
r   F)Útotalc                	       s  e Zd ZU dZefZeee df e	d< dZ
ee	d< dZee e	d< dZee	d	< eeeef d
œdd„ƒZeedœdd„Zeedœdd„Zeedeedœdd„ƒZee ed eee dœdd„Ze deee!dœ‡ fdd„Z"e#d0e ee ee!dœdd„ƒZ$e deee!dœ‡ fd d!„Z%e#d1e ee ee!dœd"d#„ƒZ&ee  ed ee eee'e!ef  d$œ‡ fd%d&„Z(e#d2d'd(œee  ee'eee f  eeee! d)œd*d+„ƒZ)ee  ed ee eee'e!ef  d$œ‡ fd,d-„Z*e#d3d'd(œee  ee'eee f  eeee! d)œd.d/„ƒZ+‡  Z,S )4ÚRunnableRetrya$	  Retry a Runnable if it fails.

    RunnableRetry can be used to add retry logic to any object
    that subclasses the base Runnable.

    Such retries are especially useful for network calls that may fail
    due to transient errors.

    The RunnableRetry is implemented as a RunnableBinding. The easiest
    way to use it is through the `.with_retry()` method on all Runnables.

    Example:
    Here's an example that uses a RunnableLambda to raise an exception

        .. code-block:: python

            import time


            def foo(input) -> None:
                '''Fake function that raises an exception.'''
                raise ValueError(f"Invoking foo failed. At time {time.time()}")


            runnable = RunnableLambda(foo)

            runnable_with_retries = runnable.with_retry(
                retry_if_exception_type=(ValueError,),  # Retry only on ValueError
                wait_exponential_jitter=True,  # Add jitter to the exponential backoff
                stop_after_attempt=2,  # Try twice
                exponential_jitter_params={
                    "initial": 2
                },  # if desired, customize backoff
            )

            # The method invocation above is equivalent to the longer form below:

            runnable_with_retries = RunnableRetry(
                bound=runnable,
                retry_exception_types=(ValueError,),
                max_attempt_number=2,
                wait_exponential_jitter=True,
                exponential_jitter_params={"initial": 2},
            )

    This logic can be used to retry any Runnable, including a chain of Runnables,
    but in general it's best practice to keep the scope of the retry as small as
    possible. For example, if you have a chain of Runnables, you should only retry
    the Runnable that is likely to fail, not the entire chain.

    Example:

        .. code-block:: python

            from langchain_core.chat_models import ChatOpenAI
            from langchain_core.prompts import PromptTemplate

            template = PromptTemplate.from_template("tell me a joke about {topic}.")
            model = ChatOpenAI(temperature=0.5)

            # Good
            chain = template | model.with_retry()

            # Bad
            chain = template | model
            retryable_chain = chain.with_retry()

    .Úretry_exception_typesTr   NÚexponential_jitter_paramsé   Úmax_attempt_number)Úreturnc                 C   sN   i }| j rt| j ƒ|d< | jr6tf i | jp,i ¤Ž|d< | jrJt| jƒ|d< |S )NÚstopÚwaitÚretry)r+   r   r   r)   r(   r   ©ÚselfÚkwargsr$   r$   r%   Ú_kwargs_retrying�   s    ÿ
zRunnableRetry._kwargs_retrying)r2   r,   c                 K   s   t f i | j¤|¤ŽS ©N)r   r3   r0   r$   r$   r%   Ú_sync_retryingž   s    zRunnableRetry._sync_retryingc                 K   s   t f i | j¤|¤ŽS r4   )r   r3   r0   r$   r$   r%   Ú_async_retrying¡   s    zRunnableRetry._async_retryingr   )ÚconfigÚrun_managerÚretry_stater,   c                 C   s.   |j }|dkrd|› �nd }t| | |¡d�S )Né   zretry:attempt:)Ú	callbacks)Úattempt_numberr   Z	get_child)r7   r8   r9   ÚattemptÚtagr$   r$   r%   Ú_patch_config¤   s    zRunnableRetry._patch_configc                    s   ‡ ‡fdd„t ||ƒD ƒS )Nc                    s   g | ]\}}ˆ  ||ˆ ¡‘qS r$   )r?   )Ú.0ÚcZrm©r9   r1   r$   r%   Ú
<listcomp>´   s   z4RunnableRetry._patch_config_list.<locals>.<listcomp>)Úzip)r1   r7   r8   r9   r$   rB   r%   Ú_patch_config_list®   s    ÿz RunnableRetry._patch_config_listr   )Úinput_r8   r7   r2   r,   c              	      sz   | j dd�D ]h}|�2 tƒ j||  |||j¡fi |¤Ž}W d   ƒ n1 sL0    Y  |jjr|jjjs|j |¡ q|S ©NT)Úreraise)r5   ÚsuperÚinvoker?   r9   ÚoutcomeÚfailedÚ
set_result©r1   rF   r8   r7   r2   r=   Úresult©Ú	__class__r$   r%   Ú_invoke¸   s    þý$zRunnableRetry._invoke)Úinputr7   r2   r,   c                 K   s   | j | j||fi |¤ŽS r4   )Z_call_with_configrR   ©r1   rS   r7   r2   r$   r$   r%   rJ   Ê   s    zRunnableRetry.invoker   c              	   ‹   sŠ   | j dd�2 zv3 d H W }|�8 tƒ j||  |||j¡fi |¤ŽI d H }W d   ƒ n1 sZ0    Y  |jjr|jjjs|j |¡ q6 |S rG   )r6   rI   Úainvoker?   r9   rK   rL   rM   rN   rP   r$   r%   Ú_ainvokeÐ   s    þý*zRunnableRetry._ainvokec                 Ë   s   | j | j||fi |¤ŽI d H S r4   )Z_acall_with_configrV   rT   r$   r$   r%   rU   â   s    zRunnableRetry.ainvoke)Úinputsr8   r7   r2   r,   c              
      sÀ  i ‰g }|}�z&|   ¡ D �]}|�Þ ‡fdd„ttˆƒƒD ƒ}|sTW d   ƒ  �q2‡fdd„|D ƒ}	‡ fdd„|D ƒ}
‡fdd„|D ƒ}tƒ j|	|  |
||j¡fddi|¤Ž}d }t|ƒD ],\}}t|t	ƒrØ|s¼|}q¼|| }|ˆ|< q¼|rò|‚W d   ƒ n1 �s0    Y  |jj
r|jj
js|j |¡ qW nD t�yx } z*||u �rdtd|gtˆƒ ƒ}W Y d }~n
d }~0 0 g }ttˆƒƒD ]0}|ˆv �r¨| ˆ| ¡ n| | d	¡¡ �qŠ|S )
Nc                    s   g | ]}|ˆ vr|‘qS r$   r$   ©r@   Úi©Úresults_mapr$   r%   rC   ø   s   z(RunnableRetry._batch.<locals>.<listcomp>c                    s   g | ]}ˆ | ‘qS r$   r$   rX   ©rW   r$   r%   rC   ý   ó    c                    s   g | ]}ˆ | ‘qS r$   r$   rX   ©r7   r$   r%   rC   þ   r]   c                    s   g | ]}ˆ | ‘qS r$   r$   rX   ©r8   r$   r%   rC   ÿ   r]   Úreturn_exceptionsTúlist[Output]r   )r5   ÚrangeÚlenrI   ÚbatchrE   r9   Ú	enumerateÚ
isinstanceÚ	ExceptionrK   rL   rM   r
   r   ÚappendÚpop©r1   rW   r8   r7   r2   Znot_setrO   r=   Zremaining_indicesZpending_inputsZpending_configsZpending_run_managersZfirst_exceptionÚoffsetÚrZorig_idxÚeÚoutputsÚidxrP   ©r7   rW   r[   r8   r%   Ú_batchè   s`    

ÿÿþûú


$ÿþ
*
zRunnableRetry._batchF)r`   )rW   r7   r`   r2   r,   c                K   s   | j | j||fd|i|¤ŽS ©Nr`   )Z_batch_with_configrq   ©r1   rW   r7   r`   r2   r$   r$   r%   rd   '  s    	ÿÿÿzRunnableRetry.batchc              
   ‹   sÒ  i ‰g }|}�z8|   ¡ 2 �z&3 d H W }|�æ ‡fdd„ttˆƒƒD ƒ}|s\W d   ƒ  �qD‡fdd„|D ƒ}	‡ fdd„|D ƒ}
‡fdd„|D ƒ}tƒ j|	|  |
||j¡fddi|¤ŽI d H }d }t|ƒD ],\}}t|t	ƒræ|sÊ|}qÊ|| }|ˆ|< qÊ|�r|‚W d   ƒ n1 �s0    Y  |jj
r|jj
js|j |¡ q6 W nD t�yŠ } z*||u �rvtd|gtˆƒ ƒ}W Y d }~n
d }~0 0 g }ttˆƒƒD ]0}|ˆv �rº| ˆ| ¡ n| | d	¡¡ �qœ|S )
Nc                    s   g | ]}|ˆ vr|‘qS r$   r$   rX   rZ   r$   r%   rC   D  s   z)RunnableRetry._abatch.<locals>.<listcomp>c                    s   g | ]}ˆ | ‘qS r$   r$   rX   r\   r$   r%   rC   I  r]   c                    s   g | ]}ˆ | ‘qS r$   r$   rX   r^   r$   r%   rC   J  r]   c                    s   g | ]}ˆ | ‘qS r$   r$   rX   r_   r$   r%   rC   K  r]   r`   Tra   r   )r6   rb   rc   rI   ÚabatchrE   r9   re   rf   rg   rK   rL   rM   r
   r   rh   ri   rj   rP   rp   r%   Ú_abatch4  s`    

ÿÿþûú


$ÿþ
*
zRunnableRetry._abatchc                Ë   s"   | j | j||fd|i|¤ŽI d H S rr   )Z_abatch_with_configru   rs   r$   r$   r%   rt   r  s    	ÿÿÿzRunnableRetry.abatch)N)N)N)N)-r   r   r    r!   rg   r(   ÚtupleÚtypeÚBaseExceptionr#   r   Úboolr)   r   r   r+   ÚintÚpropertyÚdictÚstrr   r3   r   r5   r   r6   Ústaticmethodr   r	   r?   ÚlistrE   r   r   rR   r   rJ   rV   rU   r   rq   rd   ru   rt   Ú__classcell__r$   r$   rP   r%   r'   2   sœ   
E
üûú ÿ
þú ÿ
þú? ýûùú> ýûùr'   N)"r!   Útypingr   r   r   r   r   r   Ztenacityr   r	   r
   r   r   r   r   Ztyping_extensionsr   r   Zlangchain_core.runnables.baser   Zlangchain_core.runnables.configr   r   Zlangchain_core.runnables.utilsr   r   Z langchain_core.callbacks.managerr   r   r   r   r   r'   r$   r$   r$   r%   Ú<module>   s    	$	