
    {hS,                       d dl mZ d dlZd dlmZ d dlmZmZmZ d dl	m
Z
 d dlmZ d dl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 d dlmZmZmZ d dlmZm Z  d dl!m"Z"m#Z#m$Z$m%Z%m&Z& d dl'm(Z(  ejR                  d      Z* ede      Z+ ed      Z, e(d      Z- ed      Z.	 d	 	 	 	 	 ddZ/ddZ0d dZ1dddejd                  df	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d!dZ3dddejd                  df	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d"dZ4y)#    )annotationsN)JSONDecodeError)AnyCallableTypeVar)InstructorRetryException)Hooks)Mode)handle_reask_kwargs)process_responseprocess_response_async)update_total_usage)AsyncValidationError)ChatCompletion)CompletionUsageCompletionTokensDetailsPromptTokensDetails)	BaseModelValidationError)AsyncRetrying
RetryErrorRetryingstop_after_attemptstop_after_delay)	ParamSpec
instructorT_Model)boundT_RetvalT_ParamSpecTc                X   t        | t              rut        j                  d|  d|        t	        |       g}||j                  t        |             |d   }|dd D ]  }||z  }	 |rt        |      } | S t        |      } | S t        | t        t        f      sddl	m
}  |d      | S )	a  
    Initialize the retrying mechanism based on the type (synchronous or asynchronous).

    Args:
        max_retries (int | Retrying | AsyncRetrying): Maximum number of retries or a retrying object.
        is_async (bool): Flag indicating if the retrying is asynchronous.
        timeout (float | None): Optional timeout in seconds to limit total retry duration.

    Returns:
        Retrying | AsyncRetrying: Configured retrying object.
    zmax_retries: z, timeout: Nr      )stop)ConfigurationErrorzSmax_retries must be an int or a `tenacity.Retrying`/`tenacity.AsyncRetrying` object)
isinstanceintloggerdebugr   appendr   r   r   instructor.exceptionsr%   )max_retriesis_asynctimeoutstop_conditionsstop_condition	conditionr%   s          Q/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/instructor/retry.pyinitialize_retryingr3   ,   s      +s#}[MWIFG .k:;""#3G#<= )+(, 	8I+i7N	8 '^<K  #7K  h%>?< a
 	
     c           
         t        dddt        dd      t        dd            }| t        j                  t        j
                  hv rddlm}  |dddd      }|S )z
    Initialize the total usage based on the mode.

    Args:
        mode (Mode): The mode of operation.

    Returns:
        CompletionUsage | Any: Initialized usage object.
    r   )audio_tokensreasoning_tokens)r6   cached_tokens)completion_tokensprompt_tokenstotal_tokenscompletion_tokens_detailsprompt_tokens_details)Usage)input_tokensoutput_tokenscache_read_input_tokenscache_creation_input_tokens)r   r   r   r
   ANTHROPIC_TOOLSANTHROPIC_JSONanthropic.typesr>   )modetotal_usageAnthropicUsages      r2   initialize_usagerI   W   sm     ""9Q#
 2qPQRK $$d&9&9::;$$%()	
 r4   c                <    d| v r| d   S d| v r| d   S d| v r| d   S g S )z
    Extract messages from kwargs, helps handles the cohere and gemini chat history cases

    Args:
        kwargs (Dict[str, Any]): Keyword arguments containing message data.

    Returns:
        Any: Extracted messages.
    messagescontentschat_history )kwargss    r2   extract_messagesrP   v   sB     Vj!!Vj!!n%%Ir4   r#   c	           
     D   |xs
 t               }t        |      }	|j                  d      }
t        |d|
      }|j                  dd      }	 d}|D ]  }|5  t        j                  d|j                  j                          	  |j                  |i |  | |i |}|j                  |       t        ||	      }t        ||||||      cddd       c S  y# t        t        f$ r?}t        j                  d	|        |j                  |       t        ||||
      }|d}~ww xY w# 1 sw Y   xY w# t         $ r`}t        j                  d|        t#        |j$                  j&                  j                  j                  t)        |      ||	      |d}~ww xY w)a  
    Retry a synchronous function upon specified exceptions.

    Args:
        func (Callable[T_ParamSpec, T_Retval]): The function to retry.
        response_model (Optional[type[T_Model]]): The model to validate the response against.
        args (Any): Positional arguments for the function.
        kwargs (Any): Keyword arguments for the function.
        context (Optional[Dict[str, Any]], optional): Additional context for validation. Defaults to None.
        max_retries (int | Retrying, optional): Maximum number of retries or a retrying object. Defaults to 1.
        strict (Optional[bool], optional): Strict mode flag. Defaults to None.
        mode (Mode, optional): The mode of operation. Defaults to Mode.TOOLS.
        hooks (Optional[Hooks], optional): Hooks for emitting events. Defaults to None.

    Returns:
        T_Model | None: The processed response model or None.

    Raises:
        InstructorRetryException: If all retry attempts fail.
    r.   Fr-   r.   streamNRetrying, attempt: responserG   rV   response_modelvalidation_contextstrictrF   rS   Parse error: rO   rF   rV   	exceptionRetry error: last_completion
n_attemptsrK   create_kwargsrG   )r	   rI   getr3   r(   r)   retry_stateattempt_numberemit_completion_argumentsemit_completion_responser   r   r   r   emit_parse_errorr   r   r   last_attempt
_exceptionrP   funcrX   argsrO   contextr,   rZ   rF   hooksrG   r.   rS   rV   attemptes                  r2   
retry_syncrr      s   > UWE"4(Kjj#G%kE7SK ZZ%(F+" 	G 273F3F3U3U2VWX3E33TDVD#T4V4H228<1!){ H ,!)'5+2%!% 	& (9 	LL=!45**1-0%!!)"#	F G	% 8  }QC()&NN%%$**99% !#

 
	sV   	D6 -D*ACD6 D6 D'(:D""D''D**D3	/D6 6	F?AFFc	           
       K   |xs
 t               }t        |      }	|j                  d      }
t        |d|
      }|j                  dd      }	 d}|2 3 d{   }t        j                  d|j                  j                          |5  	  |j                  |i |  | |i | d{   }|j                  |       t        ||	      }t        ||||||	       d{   cddd       c S 7 7 H7 # t        t        t        f$ r?}t        j                  d
|        |j                  |       t!        ||||      }|d}~ww xY w# 1 sw Y   xY w6 y# t"        $ r`}t        j                  d|        t%        |j&                  j(                  j                  j                  t+        |      ||	      |d}~ww xY ww)a  
    Retry an asynchronous function upon specified exceptions.

    Args:
        func (Callable[T_ParamSpec, T_Retval]): The asynchronous function to retry.
        response_model (Optional[type[T_Model]]): The model to validate the response against.
        context (Optional[Dict[str, Any]]): Additional context for validation.
        args (Any): Positional arguments for the function.
        kwargs (Any): Keyword arguments for the function.
        max_retries (int | AsyncRetrying, optional): Maximum number of retries or an async retrying object. Defaults to 1.
        strict (Optional[bool], optional): Strict mode flag. Defaults to None.
        mode (Mode, optional): The mode of operation. Defaults to Mode.TOOLS.
        hooks (Optional[Hooks], optional): Hooks for emitting events. Defaults to None.

    Returns:
        T_Model | None: The processed response model or None.

    Raises:
        InstructorRetryException: If all retry attempts fail.
    r.   TrR   rS   FNrT   rU   rW   r[   r\   r^   r_   )r	   rI   rc   r3   r(   r)   rd   re   rf   rg   r   r   r   r   r   rh   r   r   r   ri   rj   rP   rk   s                  r2   retry_asyncrt      s    > UWE"4(Kjj#G%kD'RK ZZ%(F/(  	  	'LL.w/B/B/Q/Q.RST 3E33TDVD5945J65J/JH228<1!){ H "8!)'5+2%!%"   	
 0K $#( 
 LL=!45**1-0%!!)"#	F G#  )B  }QC()&NN%%$**99% !#

 
	s   AGE EC/E/E 	EC5(C1)6C5C3 C5#E .G/E1C53C55E	:EEEE		E G	G#AF>>GG)N)r,   zint | Retrying | AsyncRetryingr-   boolr.   zfloat | None)rF   r
   returnzCompletionUsage | Any)rO   zdict[str, Any]rv   r   )rl   Callable[T_ParamSpec, T_Retval]rX   type[T_Model] | Nonerm   r   rO   r   rn   dict[str, Any] | Noner,   zint | RetryingrZ   bool | NonerF   r
   ro   Hooks | Nonerv   T_Model | None)rl   rw   rX   rx   rm   r   rO   r   rn   ry   r,   zint | AsyncRetryingrZ   rz   rF   r
   ro   r{   rv   r|   )5
__future__r   loggingjsonr   typingr   r   r   r+   r   instructor.hooksr	   instructor.moder
   instructor.reaskr   instructor.process_responser   r   instructor.utilsr   instructor.validatorsr   openai.types.chatr   openai.types.completion_usager   r   r   pydanticr   r   tenacityr   r   r   r   r   typing_extensionsr   	getLoggerr(   r   r   r    r!   r3   rI   rP   TOOLSrr   rt   rN   r4   r2   <module>r      s   #    ) ) : "   0 0 6 , 
 0  (			<	( )9
-:&CL !(/(( (V>4 &*"#S
)S(S S 	S
 #S  S S S S Sv &*'(W
)W(W W 	W
 #W %W W W W Wr4   