
    WiC                    
   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
mZmZ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 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AsyncValidationErrorFailedAttemptValidationError)Hooks   )Mode)process_responseprocess_response_asynchandle_reask_kwargs)update_total_usage)ChatCompletion)CompletionUsageCompletionTokensDetailsPromptTokensDetails)	BaseModelr   )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   r   )stop)ConfigurationErrorzSmax_retries must be an int or a `tenacity.Retrying`/`tenacity.AsyncRetrying` object)
isinstanceintloggerdebugr   appendr   r   r   
exceptionsr'   )max_retriesis_asynctimeoutstop_conditionsstop_condition	conditionr'   s          a/home/sietch6/trending-topics-pipeline/venv/lib/python3.12/site-packages/instructor/core/retry.pyinitialize_retryingr5   0   s      +s#}[MWIFG .k:;""#3G#<= )+(, 	8I+i7N	8 '^<K  #7K  h%>?2 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)r8   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      r4   initialize_usagerK   [   sm     ""9Q#
 2qPQRK $$d&9&9::;$$%()	
 r6   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    r4   extract_messagesrR   z   sB     Vj!!Vj!!n%%Ir6   c	                &   |xs
 t               }t        |      }	|j                  d      }
t        |d|
      }|j                  dd      }g }	 d}|D ]  }|5  t        j                  d|j                  j                          	  |j                  |i |  | |i |}|j                  |       t        ||	      }t        ||||||      cddd       c S  y# t        t        t        f$ r}t        j                  d	|        |j                  |       |j!                  t#        |j                  j                  ||
             t%        |t&              rt)        |d      r|j                  j*                  du xs! |j                  j*                  j,                   }| xs7 |j                  j                  t/        |j0                  dt3        d            k\  }|r|j5                  |       t7        |||||      }|d}~wt8        $ r}t        j                  d|        |j;                  |       |j!                  t#        |j                  j                  ||
             t%        |t&              rt)        |d      r|j                  j*                  du xs! |j                  j*                  j,                   }| xs7 |j                  j                  t/        |j0                  dt3        d            k\  }|r|j5                  |       |d}~ww xY w# 1 sw Y   xY w# t<        $ ra}t        j                  d|        t?        |j@                  jB                  j                  j                  tE        |      ||	|      |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.
    r0   Fr/   r0   streamNRetrying, attempt: responserI   rX   response_modelvalidation_contextstrictrH   rU   Parse error: attempt_number	exception
completionr&   max_attempt_numberinfrQ   rH   rX   r`   failed_attemptsCompletion error: Retry error: last_completion
n_attemptsrM   create_kwargsrI   re   )#r   rK   getr5   r*   r+   retry_stater_   emit_completion_argumentsemit_completion_responser   r   r   r   InstructorValidationErroremit_parse_errorr,   r   r(   r   hasattroutcomefailedgetattrr&   floatemit_completion_last_attemptr   	Exceptionemit_completion_errorr   r	   last_attempt
_exceptionrR   funcrZ   argsrQ   contextr.   r\   rH   hooksrI   r0   rU   re   rX   attempte
will_retryis_last_attempts                     r4   
retry_syncr      s   > UWE"4(Kjj#G%kE7SK ZZ%(F ,.On" ^	G ]273F3F3U3U2VWX[3E33TDVD#T4V4H228<1!){ H ,!)'5+2%!%] ]^	( $#- +
 LL=!45**1- $**%+2+>+>+M+M&''/ "+x8W#V>
 $//774? F#*#6#6#>#>#E#EE #
 !+N &22AA& + 0 02Fe   ( +!>>qA0%!!)"#(7F G  LL#5aS!9://2 $**%+2+>+>+M+M&''/ "+x8W#V> $//774? F#*#6#6#>#>#E#EE #
 !+N &22AA& + 0 02Fe   ( +!>>qAG?}] ]|  }QC()&NN%%$**99% !#+
 	sd   	L& -LACL& L& L0DHLDLLLL#	L& &	N/ANNc	                p  K   |xs
 t               }t        |      }	|j                  d      }
t        |d|
      }|j                  dd      }g }	 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        t        f$ r}t        j                  d
|        |j!                  |       |j#                  t%        |j                  j                  ||             t'        |t(              rt+        |d      r|j                  j,                  du xs! |j                  j,                  j.                   }| xs7 |j                  j                  t1        |j2                  dt5        d            k\  }|r|j7                  |       t9        |||||      }|d}~wt:        $ r}t        j                  d|        |j=                  |       |j#                  t%        |j                  j                  ||             t'        |t(              rt+        |d      r|j                  j,                  du xs! |j                  j,                  j.                   }| xs7 |j                  j                  t1        |j2                  dt5        d            k\  }|r|j7                  |       |d}~ww xY w# 1 sw Y   xY w6 y# t>        $ ra}t        j                  d|        tA        |jB                  jD                  j                  j                  tG        |      ||	|      |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.
    r0   TrT   rU   FNrV   rW   rY   r]   r^   r&   rb   rc   rd   rf   rg   rh   )$r   rK   rl   r5   r*   r+   rm   r_   rn   ro   r   r   r   r   r
   rp   rq   r,   r   r(   r   rr   rs   rt   ru   r&   rv   rw   r   rx   ry   r   r	   rz   r{   rR   r|   s                     r4   retry_asyncr   +  s    > UWE"4(Kjj#G%kD'RK ZZ%(F ,.Oo( _	 _	'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- $**%+2+>+>+M+M&''/ "+}='#VC
 $//774? F#*#6#6#>#>#E#EE #
 !+N &22AA& + 0 02Fe   ( +!>>qA0%!!)"#(7F G  LL#5aS!9://2 $**%+2+>+>+M+M&''/ "+}='#VC $//774? F#*#6#6#>#>#E#EE #
 !+N &22AA& + 0 02Fe   ( +!>>qAG?}] ] )@  }QC()&NN%%$**99% !#+
 	s   AN6M	 MC1M/M	 L:C7*C3+6C7!C5"C7%M	 0N61M3C75C77L7DH##L70DL22L77L::M	?	M	 N6		N3AN..N33N6)N)r.   zint | Retrying | AsyncRetryingr/   boolr0   zfloat | None)rH   r   returnzCompletionUsage | Any)rQ   zdict[str, Any]r   r   )r}   Callable[T_ParamSpec, T_Retval]rZ   type[T_Model] | Noner~   r   rQ   r   r   dict[str, Any] | Noner.   zint | Retryingr\   bool | NonerH   r   r   Hooks | Noner   T_Model | None)r}   r   rZ   r   r~   r   rQ   r   r   r   r.   zint | AsyncRetryingr\   r   rH   r   r   r   r   r   )5
__future__r   loggingjsonr   typingr   r   r   r-   r	   r
   r   r   rp   r   r   rH   r   processing.responser   r   r   utilsr   openai.types.chatr   openai.types.completion_usager   r   r   pydanticr   tenacityr   r   r   r   r   typing_extensionsr   	getLoggerr*   r    r"   r#   r$   r5   rK   rR   TOOLSr   r   rP   r6   r4   <module>r      s   #    ) )    
 ' , 
 0  (			<	( )9
-:&CL !(/(( (V>4 &*"#Y
)Y(Y Y 	Y
 #Y  Y Y Y Y YB &*'(Z
)Z(Z Z 	Z
 #Z %Z Z Z Z Zr6   