
    h6                         d dl Z d dlmZ d dlmZmZmZmZ d dlZd dl	Z	d dl
mZ d dlmZ d dlmZmZ d dlmZmZ d dlmZ d d	lmZmZ  G d
 de      ZdedededededefdZ G d d      Z y)    N)partial)CallableListOptionalUnion)Logging)track_llm_api_timing)custom_promptprompt_factory)AsyncHTTPHandlerget_async_httpx_client)TextChoices)CustomStreamWrapperTextCompletionResponsec                   b     e Zd Z	 	 ddeej
                     deej                     f fdZ xZS )TextCompletionCodestralErrorrequestresponsec                     || _         || _        ||| _        nt        j                  dd      | _        ||| _        n&t        j                  || j                        | _        t        | !  | j                         y )NPOSTz8https://docs.codestral.com/user-guide/inference/rest_api)methodurl)status_coder   )	r   messager   httpxRequestr   Responsesuper__init__)selfr   r   r   r   	__class__s        e/var/www/Befach/backend/env/lib/python3.12/site-packages/litellm/llms/codestral/completion/handler.pyr   z%TextCompletionCodestralError.__init__   su     '"DL ==NDL $DM!NN'DM 	LL	
    )NN)	__name__
__module____qualname__r   r   r   r   r   __classcell__r!   s   @r"   r   r      s;    
 ,0-1
 %--(	

 5>>*
 
r#   r   clientapi_baseheadersdatamodelmessagesc                    K   | j                  |||d       d {   }|j                  dk7  r!t        |j                  |j                        |j	                         }|j                  |d|d|i       |S 7 ]w)NTr+   r,   stream   r   r    complete_input_dictinputapi_keyoriginal_responseadditional_args)postr   r   textaiter_lines	post_call)	r)   r*   r+   r,   r-   r.   logging_objr   completion_streams	            r"   	make_callrA   5   s      [[7d[SSHs"* ,,hmm
 	
 !,,.+.5	   ! Ts   A;A9AA;c                       e Zd Zd fdZdee   dedefdZdefdZd	ed
e	j                  dedededededeeef   dedefdZdddi fd	ededededededededeee	j&                  f   dedeeef   fdZ e       ddi fd	edededededededeee	j&                  f   defd       Z e       dddi fd	ededededededeee	j&                  f   defd       Zd Z xZS )CodestralTextCompletionreturnNc                 "    t         |           y N)r   r   )r    r!   s    r"   r   z CodestralTextCompletion.__init__R   s    r#   r8   user_headersc                 x    |t        d      ddj                  |      d}|t        |t              ri ||}|S )NzVMissing CODESTRAL_API_Key - Please add CODESTRAL_API_Key to your environment variableszapplication/jsonz	Bearer {})zcontent-typeAuthorization)
ValueErrorformat
isinstancedict)r    r8   rG   r+   s       r"   _validate_environmentz-CodestralTextCompletion._validate_environmentU   sX    
 ?h  /(//8
 #
<(F11L1Gr#   generated_textc                     g d}|D ]k  }|j                         j                  |      r|j                  |dd      }|j                  |      sG|ddd   j                  |ddd   dd      ddd   }m |S )z
        Parse the output text to remove any special characters. In our current approach we just check for ChatML tokens.

        Initial issue that prompted this - https://github.com/BerriAI/litellm/issues/763
        )z<|assistant|>z
<|system|>z<|user|>z<s>z</s>r4      N)strip
startswithreplaceendswith)r    rO   chat_template_tokenstokens       r"   output_parserz%CodestralTextCompletion.output_parserf   s     
 *E##%007!/!7!7r1!E&&u-!/"!5!=!=eDbDk2q!QRVTVRV!W	 *
 r#   r-   r   model_responser1   r?   optional_paramsr,   r.   c                 f   |j                  |	||j                  d|i        |
d|j                          |j                  dk7  r*t        t	        |j                        |j                        	 |j                         }|j                  dg       }g }|D ]  }d }d}d }d }|j                  d	i       }t        j                  j                  |j                  d
      |j                  d      |j                  d      |j                  d            }|j                  |        t        j                  |j                  d      ||j                  d      |j                  d      |j                  d      d|j                  d            }|S # t        $ r t        |j                  d      w xY w)Nr5   r6   z#codestral api: raw model_response: r2   )r   r   i  choicesr   r   finish_reasonindexcontentlogprobs)r^   r_   r<   ra   idcreatedr-   usageFobject)rb   r]   rc   r-   rd   r1   re   )r>   r<   r   r   strjson	Exceptiongetlitellmutilsr   appendr   )r    r-   r   rZ   r1   r?   r[   r8   r,   r.   print_verboseencodingcompletion_response_original_choices_choiceschoice_finish_reason_index_text	_logprobs_choice_message_choice	_responses                          r"    process_text_completion_responsez8CodestralTextCompletion.process_text_completion_responsez   s    	&mm2D9	 	 	
 	;HMM?KL3&.HMM*$00 	W"*--/ 033IrB&('F "NFEI$jjB7Omm//$jj9jj)$((3J/	 0 G OOG$3 (6 22"&&t,'++I6%))'2%))'2&**84
	 S  	W.x}}RUVV	Ws   1F !F0r*   custom_prompt_dictrm   timeoutr+   c                    | j                  ||      }|
j                  dd       du r|}n|xs d}||v r||   }t        |d   |d   |d   |      }nt        ||      }t        j
                  j                         }|j                         D ]  \  }}||
vs||
|<    |
j                  d	d
      }||d|
}|}|	j                  ||||||d       |du rC|du r| j                  |||||||||	|
||||      S | j                  |||||||||	|
d
||||      S |du rUt        j                  j                  ||t        j                  |      |      }t        |j!                         |d|	      }|S t        j                  j                  ||t        j                  |            }| j#                  ||||
j%                  d	d
      |	|
|||||      S )Ncustom_endpointTz/https://codestral.mistral.ai/v1/fim/completionsrolesinitial_prompt_valuefinal_prompt_value)	role_dictr   r   r.   )r-   r.   r1   F)r-   prompt)r5   r+   r*   acompletion)r7   r8   r:   )r-   r.   r,   r*   rZ   rm   rn   r8   r?   r[   litellm_params	logger_fnr+   r|   )r-   r.   r,   r*   rZ   rm   rn   r8   r?   r[   r1   r   r   r+   r|   r0   	codestral)custom_llm_providerr?   )r   r+   r,   )r-   r   rZ   r1   r?   r[   r8   r,   r.   rm   rn   )rN   popr
   r   rj   CodestralTextCompletionConfig
get_configitemspre_callasync_streamingasync_completionmodule_level_clientr;   rg   dumpsr   
iter_linesrz   ri   )r    r-   r.   r*   r{   rZ   rm   rn   r8   r?   r[   r|   r   r   r   r+   completion_urlmodel_prompt_detailsr   configkvr1   r,   
input_textr   ry   s                              r"   
completionz"CodestralTextCompletion.completion   s   $ ,,Wg>0$74?%N MM  &&#5e#< ".w7%9:P%Q#78L#M!	F $%(CF 66AACLLNDAq(%&"	 # !$$Xu5 
 

 
'+"**	 	 		
 $~++%+#1"/%# +$3#1'## ,  $ ,,%+#1"/%# +$3 #1'## -  & T>2277ZZ%	 8 H ,##%$/'	I  2277"ZZ% 8 H
 44)"&&x7#+' 5 
 	
r#   c                   K   t        t        j                  j                  d|i      }	 |j	                  ||t        j                  |
             d {   }| j!                  ||||	|||
||||      S 7  # t        j                  $ rI}t        |j                  j                  dj                  |j                  j                              d }~wt        $ r*}t        ddj                  t        |                  d }~ww xY ww)	Nr|   )llm_providerparams)r+   r,   zHTTPStatusError - {}r3   i  z{})r-   r   rZ   r1   r?   r8   r,   r.   rm   r[   rn   )r   rj   LlmProvidersTEXT_COMPLETION_CODESTRALr;   rg   r   r   HTTPStatusErrorr   r   r   rK   r<   rh   rf   rz   )r    r-   r.   r*   rZ   rm   rn   r8   r?   r1   r,   r[   r|   r   r   r+   async_handlerr   es                      r"   r   z(CodestralTextCompletion.async_completionQ  s	    & / --GGw'
	*//'

40@ 0  H 44)#'+ 5 
 	
 $$ 	.JJ22.55ajjooF   	.SV)< 	sG   (D*A8 A6A8 D6A8 8DACD%D  DDc                    K   d|	d<   t        d t        t        ||t        j                  |	      |||      |d|      }|S w)NTr1   )r*   r+   r,   r-   r.   r?   ztext-completion-codestral)r@   rA   r-   r   r?   )r   r   rA   rg   r   )r    r-   r.   r*   rZ   rm   rn   r8   r?   r,   r|   r[   r   r   r+   streamwrappers                   r"   r   z'CodestralTextCompletion.async_streaming  sW     $ X+"!ZZ%!'  ;#
 s   ?Ac                      y rF    )r    argskwargss      r"   	embeddingz!CodestralTextCompletion.embedding  s    r#   )rD   N)r$   r%   r&   r   r   rf   rM   rN   rY   r   r   r   boolLiteLLMLoggingr   listrz   r   floatTimeoutr   r   r	   r   r   r   r'   r(   s   @r"   rC   rC   Q   so   #  
	"C (GG ..G /	G
 G $G G G D#IG G 
 Gl !L
L
 L
 	L

 !L
 /L
  L
 L
 L
 uemm+,L
  !L
" 
%'::	;#L
\  !/
/
 /
 	/

 //
  /
 /
 /
 uemm+,/
" 
 #/
 /
b  "" " 	"
 /"  " " uemm+,"  
!" "Hr#   rC   )!rg   	functoolsr   typingr   r   r   r   r   rj   *litellm.litellm_core_utils.litellm_loggingr   r   (litellm.litellm_core_utils.logging_utilsr	   3litellm.litellm_core_utils.prompt_templates.factoryr
   r   &litellm.llms.custom_httpx.http_handlerr   r   litellm.types.utilsr   litellm.utilsr   r   rh   r   rf   rM   r   rA   rC   r   r#   r"   <module>r      s      2 2   P I , E
9 
8  	
  8X Xr#   