
    gh1                        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ed          Z  G 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                   B    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maxexp_basejitterN)__name__
__module____qualname____doc__float__annotations__     [/var/www/FlaskApp/flask-venv/lib/python3.11/site-packages/langchain_core/runnables/retry.pyr   r   %   sE         >>NNN	JJJOOO'MMMHHr(   r   F)totalc                       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d
eeef         fd            Zded
efdZded
efdZededdded
efd            Zdee         ded         ded
ee         fdZde dddeded
e!f
 fdZ"e#	 d$de dee         ded
e!fd            Z$de dddeded
e!f
 fdZ%e#	 d$de dee         ded
e!fd            Z&dee          ded         dee         ded
ee'e!ef                  f
 fdZ(e#	 d$dddee          dee'eee         f                  d eded
ee!         f
d!            Z)dee          ded         dee         ded
ee'e!ef                  f
 fd"Z*e#	 d$dddee          dee'eee         f                  d eded
ee!         f
d#            Z+ xZ,S )%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                     i }| j         rt          | j                   |d<   | j        rt          di | j        pi |d<   | j        rt          | j                  |d<   |S )Nstopwaitretryr'   )r0   r   r   r.   r-   r   selfkwargss     r)   _kwargs_retryingzRunnableRetry._kwargs_retrying   s    !#" 	I/0GHHF6N' 	4  17R F6N % 	R5d6PQQF7Or(   r8   c                 (    t          di | j        |S Nr'   )r   r9   r6   s     r)   _sync_retryingzRunnableRetry._sync_retrying   s    ::$/:6:::r(   c                 (    t          di | j        |S r;   )r	   r9   r6   s     r)   _async_retryingzRunnableRetry._async_retrying   s    ??t4????r(   configrun_managerr   retry_statec                 r    |j         }|dk    rd| nd }t          | |                    |                    S )N   zretry:attempt:)	callbacks)attempt_numberr   	get_child)r?   r@   rA   attempttags        r)   _patch_configzRunnableRetry._patch_config   sH     ,,3aKK(w(((TFk.C.CC.H.HIIIIr(   c                 @      fdt          ||          D             S )Nc                 D    g | ]\  }}                     ||          S r'   )rI   ).0crmrA   r7   s      r)   
<listcomp>z4RunnableRetry._patch_config_list.<locals>.<listcomp>   s<     
 
 
7<q"Dq"k22
 
 
r(   )zip)r7   r?   r@   rA   s   `  `r)   _patch_config_listz RunnableRetry._patch_config_list   s>    
 
 
 
 
@CFK@X@X
 
 
 	
r(   inputr   c           
      F   |                      d          D ]}|5   t                      j        ||                     |||j                  fi |}d d d            n# 1 swxY w Y   |j        j        r+|j        j        j        s|j                            |           |S NT)reraise)r<   superinvokerI   rA   outcomefailed
set_resultr7   rR   r@   r?   r8   rG   result	__class__s          r)   _invokezRunnableRetry._invoke   s     **4*88 	7 	7G  '&&v{G<OPP                  "* 773F3N3U 7#..v666s   6AA"	%A"	c                 ,     | j         | j        ||fi |S N)_call_with_configr^   r7   rR   r?   r8   s       r)   rW   zRunnableRetry.invoke   s%     &t%dlE6LLVLLLr(   r   c           
      b  K   |                      d          2 3 d {V }|5   t                      j        ||                     |||j                  fi | d {V }d d d            n# 1 swxY w Y   |j        j        r+|j        j        j        s|j                            |           6 |S rT   )r>   rV   ainvokerI   rA   rX   rY   rZ   r[   s          r)   _ainvokezRunnableRetry._ainvoke   sA      "11$1?? 	7 	7 	7 	7 	7 	7 	7'  .uww&&v{G<OPP                            "* 773F3N3U 7#..v666 @ s   B.<A++A/	2A/	c                 <   K    | j         | j        ||fi | d {V S r`   )_acall_with_configre   rb   s       r)   rd   zRunnableRetry.ainvoke   s;       -T,T]E6TTVTTTTTTTTTr(   inputsc                    i dt           t                   dt           t                   ffd}g }|}	 |                                 D ]}|5   t                      j         ||          |                      ||           ||          |j                  fddi|}d }	t          |          D ]$\  }
}t          |t                    r|	s|}	||
<   %|	r|		 d d d            n# 1 swxY w Y   |j        j
        r+|j        j
        j        s|j                            |           n<# t          $ r/}||u r!t          d|gt          |          z            }Y d }~nd }~ww xY wg }t!          t          |                    D ]J}|v r|                    |                    "|                    |                    d                     K|S )Niterabler1   c                 :    fdt          |           D             S )Nc                 "    g | ]\  }}|v	|S r'   r'   rL   idxitemresults_maps      r)   rO   z9RunnableRetry._batch.<locals>.pending.<locals>.<listcomp>   '    XXXYS$KAWAWDAWAWAWr(   	enumeraterj   rp   s    r)   pendingz%RunnableRetry._batch.<locals>.pending   %    XXXX)H*=*=XXXXr(   return_exceptionsTlist[Output]r   )listr   r<   rV   batchrQ   rA   rs   
isinstance	ExceptionrX   rY   rZ   r   r   lenrangeappendpopr7   rh   r@   r?   r8   ru   not_setr\   rG   first_exceptionireoutputsrn   rp   r]   s                  @r)   _batchzRunnableRetry._batch   s    *,	Yd1g 	Y$q' 	Y 	Y 	Y 	Y 	Y 	Y !#	A..00 ; ; . .*UWW]//#GFOOWW[-A-A7CV  
 +/ ! F '+O )& 1 1 + +1%a33 %#2 423$)*A& .--.'. . . . . . . . . . . . . . ., '/;#/7>; '226:::5;6  	A 	A 	A  nqcCKK.?@@	A 35V%% 	. 	.Ck!!{3/0000vzz!}}----s<   D* BC&D* &C*	*D* -C*	.;D* *
E#4%EE#F)rw   rw   c                0     | j         | j        ||fd|i|S Nrw   )_batch_with_configr   r7   rh   r?   rw   r8   s        r)   rz   zRunnableRetry.batch  s9     't&K
 
;L
PV
 
 	
r(   c                   K   i dt           t                   dt           t                   ffd}g }|}	 |                                 2 3 d {V }|5   t                      j         ||          |                      ||           ||          |j                  fddi| d {V }d }	t          |          D ]$\  }
}t          |t                    r|	s|}	||
<   %|	r|		 d d d            n# 1 swxY w Y   |j        j
        r+|j        j
        j        s|j                            |           6 n<# t          $ r/}||u r!t          d|gt          |          z            }Y d }~nd }~ww xY wg }t!          t          |                    D ]J}|v r|                    |                    "|                    |                    d                     K|S )Nrj   r1   c                 :    fdt          |           D             S )Nc                 "    g | ]\  }}|v	|S r'   r'   rm   s      r)   rO   z:RunnableRetry._abatch.<locals>.pending.<locals>.<listcomp>0  rq   r(   rr   rt   s    r)   ru   z&RunnableRetry._abatch.<locals>.pending/  rv   r(   rw   Trx   r   )ry   r   r>   rV   abatchrQ   rA   rs   r{   r|   rX   rY   rZ   r   r   r}   r~   r   r   r   s                  @r)   _abatchzRunnableRetry._abatch&  s      *,	Yd1g 	Y$q' 	Y 	Y 	Y 	Y 	Y 	Y !#	A!%!5!5!7!7 ; ; ; ; ; ; ;g . .#1577>//#GFOOWW[-A-A7CV $ $
 +/$ !$ $      F '+O )& 1 1 + +1%a33 %#2 423$)*A& .--.'. . . . . . . . . . . . . . ., '/;#/7>; '226:::5 "8!76  	A 	A 	A  nqcCKK.?@@	A 35V%% 	. 	.Ck!!{3/0000vzz!}}----sH   D8 
D6D8 BC3'D8 3C7	7D8 :C7	;<D8 8
E1%E,,E1c                @   K    | j         | j        ||fd|i| d {V S r   )_abatch_with_configr   r   s        r)   r   zRunnableRetry.abatch\  s[       .T-L&&
 
<M
QW
 
 
 
 
 
 
 
 	
r(   r`   )-r!   r"   r#   r$   r|   r-   tupletypeBaseExceptionr&   r   boolr.   r   r   r0   intpropertydictstrr   r9   r   r<   r	   r>   staticmethodr   r
   rI   ry   rQ   r   r   r^   r   rW   re   rd   r   r   rz   r   r   __classcell__)r]   s   @r)   r,   r,   2   s        > >@ ?H\5m!4c!9:III %)T(((;CGx(?@GGG  ?$sCx.    X ;s ;x ; ; ; ;@ @ @ @ @ @ JJJ $J 
	J J J \J
^$
 #Y
 $	

 
n	
 
 
 
 2 	
  
     $ ?CM MM$,^$<MORM	M M M XM
 7 	
  
     $ ?CU UU$,^$<UORU	U U U XU
4U4 674 ^$	4
 4 
eFI%&	'4 4 4 4 4 4l  IM


 #(

 

 

U

 ~tN/CCDE


  

 

 
f

 

 

 X

4U4 ;<4 ^$	4
 4 
eFI%&	'4 4 4 4 4 4l  IM


 #(

 

 

U

 ~tN/CCDE


  

 

 
f

 

 

 X

 

 

 

 

r(   r,   N)"r$   typingr   r   r   r   r   r   tenacityr	   r
   r   r   r   r   r   typing_extensionsr   r   langchain_core.runnables.baser   langchain_core.runnables.configr   r   langchain_core.runnables.utilsr   r    langchain_core.callbacks.managerr   r   r   r   r   r,   r'   r(   r)   <module>r      s   3 3                                 2 1 1 1 1 1 1 1 = = = = = = H H H H H H H H 8 8 8 8 8 8 8 8 R       
 	/1PQQAGCLL
I 
I 
I 
I 
Iiu 
I 
I 
I 
Iu
 u
 u
 u
 u
'v6 u
 u
 u
 u
 u
r(   