
    ge6                         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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)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        ^/var/www/openai/venv/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_callr@   4   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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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__Q   s    r"   r7   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   r7   rF   r*   s       r!   _validate_environmentz-CodestralTextCompletion._validate_environmentT   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>r3      N)strip
startswithreplaceendswith)r   rN   chat_template_tokenstokens       r!   output_parserz%CodestralTextCompletion.output_parsere   s     
 *E##%007!/!7!7r1!E&&u-!/"!5!=!=eDbDk2q!QRVTVRV!W	 *
 r"   r,   r   model_responser0   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)Nr4   r5   z#codestral api: raw model_response: r1   )r   r   i  choicesr   r   finish_reasonindexcontentlogprobs)r]   r^   r;   r`   idcreatedr,   usageFobject)ra   r\   rb   r,   rc   r0   rd   )r=   r;   r   r   strjson	Exceptiongetlitellmutilsr   appendr   )r   r,   r   rY   r0   r>   rZ   r7   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_responsey   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_dictrl   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-   r0   F)r,   prompt)r4   r*   r)   acompletion)r6   r7   r9   )r,   r-   r+   r)   rY   rl   rm   r7   r>   rZ   litellm_params	logger_fnr*   r{   )r,   r-   r+   r)   rY   rl   rm   r7   r>   rZ   r0   r   r   r*   r{   r/   	codestral)custom_llm_providerr>   )r   r*   r+   )r,   r   rY   r0   r>   rZ   r7   r+   r-   rl   rm   )rM   popr	   r
   ri   CodestralTextCompletionConfig
get_configitemspre_callasync_streamingasync_completionmodule_level_clientr:   rf   dumpsr   
iter_linesry   rh   )r   r,   r-   r)   rz   rY   rl   rm   r7   r>   rZ   r{   r   r   r   r*   completion_urlmodel_prompt_detailsr   configkvr0   r+   
input_textr   rx   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 - {}r2   i  z{})r,   r   rY   r0   r>   r7   r+   r-   rl   rZ   rm   )r   ri   LlmProvidersTEXT_COMPLETION_CODESTRALr:   rf   r   r   HTTPStatusErrorr   r   r   rJ   r;   rg   re   ry   )r   r,   r-   r)   rY   rl   rm   r7   r>   r0   r+   rZ   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)NTr0   )r)   r*   r+   r,   r-   r>   ztext-completion-codestral)r?   r@   r,   r   r>   )r   r   r@   rf   r   )r   r,   r-   r)   rY   rl   rm   r7   r>   r+   r{   rZ   r   r   r*   streamwrappers                   r!   r   z'CodestralTextCompletion.async_streaming  sW     " X+"!ZZ%!'  ;#
 s   ?Ac                      y rE    )r   argskwargss      r!   	embeddingz!CodestralTextCompletion.embedding  s    r"   )rC   N)r#   r$   r%   r   r   re   rL   rM   rX   r   r   r   boolLiteLLMLoggingr   listry   r   floatTimeoutr   r   r   r   r   r&   r'   s   @r!   rB   rB   P   sK   #  
	"C (GG ..G /	G
 G $G G G D#IG G 
 Gl !M
M
 M
 	M

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

 /1
  1
 1
 1
 uemm+,1
" 
 #1
~ "" " 	"
 /"  " " uemm+,"  
!"Hr"   rB   )rf   	functoolsr   typingr   r   r   r   r   ri   *litellm.litellm_core_utils.litellm_loggingr   r   3litellm.litellm_core_utils.prompt_templates.factoryr	   r
   &litellm.llms.custom_httpx.http_handlerr   r   litellm.types.utilsr   litellm.utilsr   r   rg   r   re   rL   r   r@   rB   r   r"   r!   <module>r      s      2 2   P , E
9 
8  	
  8Y Yr"   