
    g3fir5                         d 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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y)z-Runnable that retries a Runnable if it fails.    )TYPE_CHECKINGAnyTypeVar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                   @    e Zd ZU dZeed<   	 eed<   	 eed<   	 eed<   y)ExponentialJitterParamsz2Parameters for `tenacity.wait_exponential_jitter`.initialmaxexp_basejitterN)__name__
__module____qualname____doc__float__annotations__     \/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_core/runnables/retry.pyr   r   #   s%    <N	JO'M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dz  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dz  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dz  ded
e fd       Z%dee   ded   dee   ded
ee ez     f
 fdZ&e"	 d%dd dee   deee   z  dz  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z     f
 fd#Z(e"	 d%dd dee   deee   z  dz  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

        ```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:
        ```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                  xs i |d<   | j                  rt        | j                        |d<   |S )Nstopwaitretryr%   )r.   r   r   r,   r+   r   selfkwargss     r'   _kwargs_retryingzRunnableRetry._kwargs_retrying   sr    !#""/0G0GHF6N''4 117RF6N %%5d6P6PQF7Or&   r6   c                 0    t        di | j                  |S Nr%   )r
   r7   r4   s     r'   _sync_retryingzRunnableRetry._sync_retrying   s    :$//:6::r&   c                 0    t        di | j                  |S r9   )r   r7   r4   s     r'   _async_retryingzRunnableRetry._async_retrying   s    ?t44???r&   configrun_managerr   retry_statec                 j    |j                   }|dkD  rd| nd }t        | |j                  |            S )N   zretry:attempt:)	callbacks)attempt_numberr   	get_child)r=   r>   r?   attempttags        r'   _patch_configzRunnableRetry._patch_config   s;     ,,,3aKwi(TFk.C.CC.HIIr&   c           	      r    t        ||d      D cg c]  \  }}| j                  |||       c}}S c c}}w )NF)strict)ziprG   )r5   r=   r>   r?   crms         r'   _patch_config_listz RunnableRetry._patch_config_list   s@     V[?
2 q"k2
 	
 
s   3input_r   c           
      b   | j                  d      D ]  }|5  t        |   || j                  |||j                        fi |}d d d        |j                  j
                  sQ|j                  j
                  j                  rr|j                  j                          S # 1 sw Y   `xY wNT)reraise)r:   superinvokerG   r?   outcomefailed
set_resultr5   rN   r>   r=   r6   rE   result	__class__s          r'   _invokezRunnableRetry._invoke   s     **4*8 	7G &&v{G<O<OP  ""**73F3F3N3N3U3U##..v6	7  s   -B%%B.	inputc                 @     | j                   | j                  ||fi |S N)_call_with_configrZ   r5   r[   r=   r6   s       r'   rS   zRunnableRetry.invoke   s$     &t%%dllE6LVLLr&   r   c           
        K   | j                  d      2 3 d {   }|5  t        |   || j                  |||j                        fi | d {   }d d d        |j                  j
                  s_|j                  j
                  j                  r|j                  j                         7 7 b# 1 sw Y   axY w6 S wrP   )r<   rR   ainvokerG   r?   rT   rU   rV   rW   s          r'   _ainvokezRunnableRetry._ainvoke   s      "11$1? 	7 	7' $w&&v{G<O<OP     ""**73F3F3N3N3U3U##..v6	7  @ sT   CCB2CC0B6B4B6C5 CC2C4B66B?	;
Cc                 \   K    | j                   | j                  ||fi | d {   S 7 wr]   )_acall_with_configrb   r_   s       r'   ra   zRunnableRetry.ainvoke   s.      -T,,T]]E6TVTTTTs   #,*,inputsc           
         i }g }|}	 | j                         D ]2  }|5  t        t        |            D 	cg c]	  }	|	|vs|	 }
}	|
s	 d d d         n|
D 	cg c]  }	||	   	 }}	|
D 	cg c]  }	||	   	 }}	|
D 	cg c]  }	||	   	 }}	t        |   || j                  |||j                        fddi|}d }t        |      D ]$  \  }}t        |t              r|s|}|
|   }|||<   & |r|	 d d d        |j                  j                  s|j                  j                  j                  r|j                  j                  |       5 g }t        t        |            D ];  }||v r|j                  ||          |j                  |j!                  d             = |S c c}	w c c}	w c c}	w c c}	w # 1 sw Y   xY w# t        $ r'}||u rt        d|gt        |      z        }Y d }~d }~ww xY wNreturn_exceptionsTzlist[Output]r   )r:   rangelenrR   batchrM   r?   	enumerate
isinstance	ExceptionrT   rU   rV   r	   r   appendpopr5   re   r>   r=   r6   results_mapnot_setrX   rE   iremaining_indicespending_inputspending_configspending_run_managersfirst_exceptionoffsetrorig_idxeoutputsidxrY   s                        r'   _batchzRunnableRetry._batch   sA    *, "*	A..0 &;  . $)V#5)+9M)% ) - .  . :K%KAfQi%KN%K:K&LQvay&LO&LDU+VqKN+V(+V"W]&//+-A7CVCV
 +/ !F '+O%.v%6 2	%a3#223$#4V#<01H-2 '-- '? .D ''//#//77>>''226:M&;V -/V% 	.Ck!{3/0vzz!}-		.
 [)
 &L&L+V .  .L  	A nqcCK.?@	As   G F9	F% F%F9	
G F9F*#F9)F/5F9;F4A(F90G  G 1G %F99G	>G 	G5G00G5F)rh   rh   c                D     | j                   | j                  ||fd|i|S Nrh   )_batch_with_configr   r5   re   r=   rh   r6   s        r'   rk   zRunnableRetry.batch"  s4     't&&KK
;L
PV
 	
r&   c           
      $  K   i }g }|}	 | j                         2 3 d {   }|5  t        t        |            D 	cg c]	  }	|	|vs|	 }
}	|
s	 d d d         n|
D 	cg c]  }	||	   	 }}	|
D 	cg c]  }	||	   	 }}	|
D 	cg c]  }	||	   	 }}	t        |   || j                  |||j                        fddi| d {   }d }t        |      D ]$  \  }}t        |t              r|s|}|
|   }|||<   & |r|	 d d d        |j                  j                  s|j                  j                  j                  r'|j                  j                  |       Dg }t        t        |            D ];  }||v r|j                  ||          |j                  |j!                  d             = |S 7 c c}	w c c}	w c c}	w c c}	w 7 
# 1 sw Y   xY w6 ~# t        $ r'}||u rt        d|gt        |      z        }Y d }~d }~ww xY wwrg   )r<   ri   rj   rR   abatchrM   r?   rl   rm   rn   rT   rU   rV   r	   r   ro   rp   rq   s                        r'   _abatchzRunnableRetry._abatch/  sX     *, ")	A!%!5!5!7 %; %;g . $)V#5)+9M)% ) -. . :K%KAfQi%KN%K:K&LQvay&LO&LDU+VqKN+V(+V#(7>&//+-A7CVCV$
 +/$ !$ F '+O%.v%6 2	%a3#223$#4V#<01H-2 '-- '=.B ''//#//77>>''226:
 -/V% 	.Ck!{3/0vzz!}-		.
 a%;)
 &L&L+V. . "8L  	A nqcCK.?@	As   HG GF5GG G	F8F8GG GF=+G1G=GG3GG<G G   G G AH5G8GG	G 	H&HHHHc                `   K    | j                   | j                  ||fd|i| d {   S 7 wr   )_abatch_with_configr   r   s        r'   r   zRunnableRetry.abatchm  sB      .T--LL&&
<M
QW
 
 	
 
s   %.,.r]   )+r   r    r!   r"   rn   r+   tupletypeBaseExceptionr$   r   boolr,   r   r.   intpropertydictstrr   r7   r
   r:   r   r<   staticmethodr   r   rG   listrM   r   r   rZ   r   rS   rb   ra   r   rk   r   r   __classcell__)rY   s   @r'   r*   r*   0   s   ?B ?H\5m!4c!9:I %)T(;@D6=D  ?$sCx.   ;s ;x ;@ @ @ JJJ $J 
	J J	
^$	
 #Y	
 $		

 
n		
 2 	
  
$ <@MM$2T$9MLOM	M M
 7 	
  
$ <@UU$2T$9ULOU	U U
=U= 67= ^$	=
 = 
fy 	!=~  @D


 #(

U

 n!55<


  

 

 
f

 

<U< ;<< ^$	<
 < 
fy 	!<|  @D


 #(

U

 n!55<


  

 

 
f

 

r&   r*   N) r"   typingr   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      sz    3    2 = H 8
 	/1PQACL
Iiu 
IH
'v6 H
r&   