
    *if                   
   S SK Jr  S SKrS SKrS SKrS SKrS SKrS SKrS SKrS SK	J	r	  S SK
Jr  S SKJrJrJrJrJrJrJrJrJrJr  S SKrS SKJr  S SKrS SKJr  S SKJr  S SK J!r!  S SK"J#r#  S SK$J%r%  SSK&J'r'  SS	K(J)r)J*r*  S
r+Sr,Sr-Sr.Sr/Sr0Sr1Sr2 " S S\5      r3 " S S\45      r5 " S S\*5      r6SS jr7SS jr8\Rr                   " S S5      5       r: " S S\5      r; " S S\;5      r<    SS jr=    SS  jr>    SS! jr? S     SS# jjr@      SS$ jrA    SS% jrB    SS& jrC    SS' jrD S     SS( jjrE S     SS) jjrFSS* jrG    SS+ jrH      SS, jrI          SS- jrJ        SS. jrK          SS/ jrL        SS0 jrM        SS1 jrN        SS2 jrO        SS3 jrPSSS4 jjrQ S     SS5 jjrR S   SS6 jjrSSS7 jrT\T" S85            SS9 j5       rU\T" S:5            SS; j5       rV\T" S<5            SS= j5       rW\T" S>5            SS? j5       rX\T" S@5            SSA j5       rY\T" SB5            SSC j5       rZ\T" SD5            SSE j5       r[\T" SF5            SSG j5       r\\T" SH5            SSI j5       r]\T" SJ5            SSK j5       r^\T" SL5            SSM j5       r_\T" SN5            SSO j5       r`\T" SP5            SSQ j5       ra\T" SR5            SSS j5       rb\T" ST5            SSU j5       rc\T" SV5            SSW j5       rd\T" SX5            SSY j5       re\T" SZ5            SS[ j5       rf\T" S\5            SS] j5       rg\T" S^5            SS_ j5       rh\T" S`5            SSa j5       ri\T" Sb5            SSc j5       rj\T" Sd5            SSe j5       rk\8" Sf5      SSSSSgShSiSjSkS"/ SSSlSlSmSkS SnSoSSS4                                                   SSp jj5       rl\8" Sq5      \8" Sr5      SSSSSgShSiSjSkS"/ SSSlSlSmSkS SnSoSSS4                                                   SSs jj5       5       rm " St Su5      rn " Sv Sw\n5      ro " Sx Sy\n5      rp " Sz S{\n5      rq " S| S}\n5      rr " S~ S\n5      rs\srt " S S\n5      ru " S S\n5      rv\8" S5      SSSSSgShSiSjSkS"/ SSSlSlSmSkS SnSoSSSSS4                                                       SS jj5       rwg)    )annotationsN)datetime)	ExitStack)
AnyDictIteratorListLiteralOptionalTupleUnionProtocolcast)ImmutableSandboxedEnvironment   )logger)suppress_stdout_stderr	Singletonz{% for message in messages %}{{'<|im_start|>' + message['role'] + '
' + message['content'] + '<|im_end|>' + '
'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
' }}{% endif %}<s>
<|im_end|>a  {{ bos_token }}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if message['role'] == 'user' %}{{ '[INST] ' + message['content'] + ' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ message['content'] + eos_token + ' ' }}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %}</s>a  {{ bos_token }}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if message['role'] == 'user' %}{{ '[INST] ' + message['content'] + ' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ message['content'] + eos_token}}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %}a  {% set loop_messages = messages %}{% for message in loop_messages %}{% set content = '<|start_header_id|>' + message['role'] + '<|end_header_id|>

'+ message['content'] | trim + '<|eot_id|>' %}{% if loop.index0 == 0 %}{% set content = bos_token + content %}{% endif %}{{ content }}{% endfor %}{% if add_generation_prompt %}{{ '<|start_header_id|>assistant<|end_header_id|>

' }}{% endif %}c                      \ rS rSrSrSSSSSSSS/ SSSSSS	SSS
SSSSSSSSSS.                                                           SS jjrSrg)LlamaChatCompletionHandler=   a  Base Protocol for a llama chat completion handler.

Very generic protocol that can be used to implement any chat format.
The only hard requirement is that it must return a ChatCompletion when
stream=False and an iterator of ChatCompletionChunks when stream=True.N皙?ffffff?(   F        皙?皙?      ?r         @皙?)	functionsfunction_calltoolstool_choicetemperaturetop_ptop_kstreamstopseedresponse_format
max_tokenspresence_penaltyfrequency_penaltyrepeat_penaltymodel
logit_biasmin_p	typical_ptfs_zmirostat_modemirostat_taumirostat_etalogits_processorgrammarlogprobstop_logprobsc                   g N )selfllamamessagesr$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   kwargss                                  Y/var/www/html/ai-backend/venv/lib/python3.13/site-packages/llama_cpp/llama_chat_format.py__call__#LlamaChatCompletionHandler.__call__D   s    R     rA   )<rC   llama.LlamarD   .List[llama_types.ChatCompletionRequestMessage]r$   2Optional[List[llama_types.ChatCompletionFunction]]r%   7Optional[llama_types.ChatCompletionRequestFunctionCall]r&   .Optional[List[llama_types.ChatCompletionTool]]r'   4Optional[llama_types.ChatCompletionToolChoiceOption]r(   floatr)   rP   r*   intr+   boolr,   Optional[Union[str, List[str]]]r-   Optional[int]r.   9Optional[llama_types.ChatCompletionRequestResponseFormat]r/   rT   r0   rP   r1   rP   r2   rP   r3   Optional[str]r4   Optional[Dict[str, float]]r5   rP   r6   rP   r7   rP   r8   rQ   r9   rP   r:   rP   r;   #Optional[llama.LogitsProcessorList]r<   Optional[llama.LlamaGrammar]r=   Optional[bool]r>   rT   returniUnion[llama_types.CreateChatCompletionResponse, Iterator[llama_types.CreateChatCompletionStreamResponse]]__name__
__module____qualname____firstlineno____doc__rG   __static_attributes__rA   rI   rF   r   r   =   s   N IMQU@DLP 02" $("%#& ##15!!@D04#'&*I) 	) A) F) O) >) J) ) ) ) ) .)  !)"
#)( "))*  +), !-). /)0 1)2 /3)6 7)8 9): ;)< =)> ?)@ A)B >C)D .E)F !G)H $I)L
M) )rI   r   c                      \ rS rSrSrg)+LlamaChatCompletionHandlerNotFoundExceptionp   rA   N)r^   r_   r`   ra   rc   rA   rI   rF   re   re   p   s    rI   re   c                  Z    \ rS rSr% 0 rS\S'    S	     S
S jjrSS jr    SS jrSr	g)"LlamaChatCompletionHandlerRegistryt   z%Dict[str, LlamaChatCompletionHandler]_chat_handlersc                j    U(       d  XR                   ;   a  [        SU S35      eX R                   U'   g )NzFormatter with name 'z>' is already registered. Use `overwrite=True` to overwrite it.rj   
ValueError)rB   namechat_handler	overwrites       rF    register_chat_completion_handlerCLlamaChatCompletionHandlerRegistry.register_chat_completion_handlerw   s<     T%8%88'v-kl  %1D!rI   c                Z    XR                   ;   a  U R                   U	 g [        SU S35      e)Nz(No formatter registered under the name 'z'.rl   )rB   rn   s     rF   unregister_chat_handler:LlamaChatCompletionHandlerRegistry.unregister_chat_handler   s1    &&&##D)GvRPQQrI   c           
          U R                   U   nU$ ! [         a4    [        SU S[        U R                   R	                  5       5       S35      ef = f)NzInvalid chat handler: z (valid formats: ))rj   KeyErrorre   listkeys)rB   rn   ro   s      rF   #get_chat_completion_handler_by_nameFLlamaChatCompletionHandlerRegistry.get_chat_completion_handler_by_name   sb    	..t4L 	=(.?TEXEXE]E]E_@`?aabc 	s	    >ArA   NF)rn   strro   r   rp   rR   rn   r~   rn   r~   r[   r   )
r^   r_   r`   ra   rj   __annotations__rq   rt   r{   rc   rA   rI   rF   rh   rh   t   sN    <>N9>  	
1
1 1
1 	
1R			#	rI   rh   c                4    [        5       R                  U 5      $ r@   )rh   r{   )rn   s    rF   get_chat_completion_handlerr      s    -/SS rI   c                   ^  SU 4S jjnU$ )Nc                <   > [        5       R                  TU 5        U $ r@   )rh   rq   )frn   s    rF   	decorator3register_chat_completion_handler.<locals>.decorator   s    *,MMdTUVrI   )r   r   rA   rn   r   s   ` rF   rq   rq      s     rI   c                  N    \ rS rSr% SrS\S'   SrS\S'   SrS\S	'   S
rS\S'   Sr	g)ChatFormatterResponse   a
  Dataclass that stores completion parameters for a given chat format and
create_chat_completion request.

prompt contains the formatted prompt generated from the chat format and messages.
stop contains the stop token or list of stop tokens to use for the chat format.r~   promptNrS   r,   z$Optional[llama.StoppingCriteriaList]stopping_criteriaFrR   added_specialrA   )
r^   r_   r`   ra   rb   r   r,   r   r   rc   rA   rI   rF   r   r      s0    W K,0D
)0>B;BM4rI   r   c                  .    \ rS rSrSr      SS jrSrg)ChatFormatter   a  Base Protocol for a chat formatter. A chat formatter is a function that
takes a list of messages and returns a chat format response which can be used
to generate a completion. The response can also include a stop token or list
of stop tokens to use for the completion.c                   g r@   rA   )rB   rD   rE   s      rF   rG   ChatFormatter.__call__   s    
 !$rI   rA   NrD   rK   rE   r   r[   r   r]   rA   rI   rF   r   r      s+    1
$ A$ 	$
 
$rI   r   c                      \ rS rSr  S	         S
S jjr\SS j5       rSSSSS.             SS jjrSS jrSr	g)Jinja2ChatFormatter   Nc                    Xl         X l        X0l        X@l        Ub  [	        U5      OSU l        [        [        R                  " 5       SSS9R                  U R                   5      U l
        g)zAA chat formatter that uses jinja2 templates to format the prompt.NT)loadertrim_blockslstrip_blocks)template	eos_token	bos_tokenadd_generation_promptsetstop_token_idsr   jinja2
BaseLoaderfrom_string_environment)rB   r   r   r   r   r   s         rF   __init__Jinja2ChatFormatter.__init__   sd     !""%:"#1#=C4 	 :$$&
 +dmm
$	 	rI   c                J    [         R                  " 5       R                  U 5      $ r@   )r   nowstrftime)r   s    rF   strftime_now Jinja2ChatFormatter.strftime_now   s    ||~&&q))rI   )r$   r%   r&   r'   c               8  ^  SS jnT R                   R                  UT R                  T R                  UT R                  UUUUT R
                  S9
nS n	T R                  b%        SU 4S jjn
[        R                  " U
/5      n	[        UT R                  /U	SS9$ )Nc                    [        U 5      er@   )rm   )messages    rF   raise_exception5Jinja2ChatFormatter.__call__.<locals>.raise_exception   s    W%%rI   )
rD   r   r   r   r   r$   r%   r&   r'   r   c                (   > U S   TR                   ;   $ )N)r   )tokenslogitsrB   s     rF   stop_on_last_token8Jinja2ChatFormatter.__call__.<locals>.stop_on_last_token   s     bzT%8%888rI   T)r   r,   r   r   )r   r~   )r   znpt.NDArray[np.intc]r   znpt.NDArray[np.single]r[   rR   )
r   renderr   r   r   r   r   rC   StoppingCriteriaListr   )rB   rD   r$   r%   r&   r'   rE   r   r   r   r   s   `          rF   rG   Jinja2ChatFormatter.__call__   s    	& ""))nnnn+"&"<"<'#** * 
 !*9,96L99
 !& : :<N;O P$..!/	
 	
rI   c                    [        U 5      $ r@   ))chat_formatter_to_chat_completion_handlerrB   s    rF   to_chat_handler#Jinja2ChatFormatter.to_chat_handler	  s    8>>rI   )r   r   r   r   r   r   )TN)
r   r~   r   r~   r   r~   r   rR   r   zOptional[List[int]])r   r~   r[   r~   )rD   rK   r$   rL   r%   rM   r&   rN   r'   rO   rE   r   r[   r   )r[   r   )
r^   r_   r`   ra   r   staticmethodr   rG   r   rc   rA   rI   rF   r   r      s     '+.2%% % 	%
  $% ,%. * * IMQU@DLP)
 A)
 F	)

 O)
 >)
 J)
 )
 
)
V?rI   r   c                    U c  g [        U S   U S   U S   5       VVVVVs/ s H4  u  pnUS UUR                  5        VVs/ s H  u  pEUUS S.PM     snnS.PM6     snnnnnS S.$ s  snnf s  snnnnnf )Nr   token_logprobsr>   )tokenlogprobbytes)r   r   r   r>   )contentrefusal)zipitems)r=   r   r   r>   	top_tokentop_logprobs         rF   )_convert_text_completion_logprobs_to_chatr     s       588JHUeLfhpq  iA  5B
 5B05< " 3?2D2D2F! 3G.		 "+#.!%
 3G!	 5B
 ! !
s   A, A&
A,&A,c           
         SU ;   d   eSU S   -   SU S   U S   SSU S	   S   S
   S.[        U S	   S   S   5      U S	   S   S   S./U S   S.$ )Nusagechatidchat.completioncreatedr3   r   	assistantchoicestextroler   r=   finish_reasonindexr   r=   r   r   objectr   r3   r   r   r   )
completions    rF    _convert_text_completion_to_chatr   &  s     j   z$''#i(G$ '))4Q7? FjQZF[\]F^_iFjk!+I!6q!9/!J

 G$! rI   c              #    #    [        U 5       Hy  u  pUS:X  a  SUS   -   US   US   SSSS0S S S	./S
.v   SUS   -   US   US   SSUS   S   S   c  SUS   S   S   0O0 [        US   S   S   5      US   S   S   S	./S
.v   M{     g 7f)Nr   r   r   r3   r   chat.completion.chunkr   r   r   deltar=   r   r   r3   r   r   r   r   r   r   r   r=   )	enumerater   )chunksichunks      rF   '_convert_text_completion_chunks_to_chatr   >  s     f%6uT{*w +1 "#"K" %))-	 " 5;&7^Y'- 
 !+A.?G &uY'7':6'B   I%PYJZ[\J]^hJi j%*9%5a%8%I
 	
% &s   B
BFc                D    U(       a  U n[        U5      $ U n[        U5      $ r@   )r   r   )completion_or_chunksr+   r   r   s       rF   _convert_completion_to_chatr   i  s'     G[6v>>-A
/
;;rI   c                  ^  U(       dl  UnSU;   d   eST -   S-   US   -   nSUS   -   SUS   US   S	S
S T US   S	   S   S.UST US   S	   S   S.S./S.[        US   S	   S   5      SS./US   S.nU$ Un    SU 4S jjnU" U5      $ )Nr   call__0__r   r   r   r   r3   r   r   r   r   rn   	argumentsfunctionr   typer   r   r   r%   
tool_callsr=   r   r   r   c              3  D  >#    SnS nS nS nS nU  H  nU(       a  SUS   -   nUS   nUS   nST-   S-   US   -   nUSUUS	S S S
S S S S.S./S.v   SUS   -   SUS   US   S	S [        US   S	   S   5      S S TUS   S	   S   S.S	USTUS   S	   S   S.S./S.S./S.v   SnM  Uc   eSUS   -   SUS   US   S	S [        US   S	   S   5      S S TUS   S	   S   S.S	USTUS   S	   S   S.S./S.S./S.v   M     Ub  Ub  Ub  USUUS	SS S S S S S.S./S.v   g g g g 7f)NTr   r   r   r3   r   r   r   r   r   r   r   r   r=   r   r   r   r   r3   r   r   r=   r   r   r   r   r   r   r   Fr   r   )r   firstid_r   r3   tool_idr   	tool_names          rF   #_stream_response_to_function_streamQ_convert_completion_to_chat_function.<locals>._stream_response_to_function_stream  sk     ECGEG 5;.C#I.G!'NE-	9C?%+MG!"9#*!& *+15,0,7/35926	*"	
$ ( %uT{2"9#(#3!&w *+15,UV[\eVfghVijtVu,v,0/3095:95Ea5H5P6& 67294>8A=B9=Ma=P4:>29.	
)*3&*"	$! !D "E*** 5;.5$Y/"7^ &'-1(QRWXaRbcdRefpRq(r(,+/,516y1A!1DV1L2" 23.50:4=9>y9I!9LV9T5*	%&
/"&	  }  ~ 7#65;L5&" &'-9(,(,+/15.2	&	
   <M#6s   DD )r   4Iterator[llama_types.CreateCompletionStreamResponse]r[   z8Iterator[llama_types.CreateChatCompletionStreamResponse]r   )r   r   r+   r   r   chat_completionr   r   s   `       rF   $_convert_completion_to_chat_functionr  z  s    ;O
*$$$!I-3j6FF :d++'!),(  +#'$-)3I)>q)A&)I* '.(2,51;I1Fq1I&1Q-"	' $ !J*U^J_`aJbcmJn o%1+2  (=E
@ G[{	H{	E{	z 36::rI   c                   ^  S S S S SSSSSS/ S S S SSSSS	S
SS S S S S S S.                                                           SU 4S jjjnU$ )Nr   r   r   r    r!   Fr   r   r   r"   r#   r$   r%   r&   r'   r(   r)   r*   r5   r6   r+   r,   r-   r.   r/   r0   r1   r2   r7   r8   r9   r:   r3   r;   r<   r4   r=   r>   c                  >^( T)" UUUUUS9nU R                   " UR                  R                  S5      UR                  (       + SS9nUR                  b\  Uc  / O[        U[        5      (       a  U/OUn[        UR                  [        5      (       a  UR                  OUR                  /n UU -   nS n!UR                  b  UR                  n!Ub  US   S:X  a  [        XR                  S9nUb  U V"s/ s H  n"SU"S	.PM
     nn"UbH  [        U[        5      (       a  US
:X  d  US:X  a  Un[        U[        5      (       a  SU;   a
  SSUS   0S	.nS n#Ub  [        U[        5      (       ax  Ubu  US   S   m([        U(4S jU 5       S 5      n#U#c  [        ST( S35      eU#S   S   n$ [        R                  R!                  ["        R$                  " U$5      U R                  S9nU R2                  " S*0 SU_SU_SU_SU_SU	_SU
_SU(       a  UOS _SU_SU_SU_SU_SU_SU_SU_S U_S!U_S"U_S#U_S$U_S%U_S&U!_S'U_S(U_6n&U#b  U#S   S   n'[5        U'U&U5      $ [7        U&US)9$ s  sn"f ! [&         ar  n%U R                  (       a!  [)        [        U%5      [*        R,                  S9  [        R                  R/                  [        R0                  U R                  S9n S n%A%NS n%A%ff = f)+N)rD   r$   r%   r&   r'   utf-8T)add_bosspecialr   json_objectverboser   r   r   noneautorn   c              3  B   >#    U  H  oS    S   T:X  d  M  Uv   M     g7fr   rn   NrA   .0trn   s     rF   	<genexpr>]chat_formatter_to_chat_completion_handler.<locals>.chat_completion_handler.<locals>.<genexpr>  !     KEqz]6-Bd-JE   	Tool choice '' not found in tools.
parametersfiler   r(   r)   r*   r5   r6   r=   r+   r,   r-   r/   r0   r1   r2   r7   r8   r9   r:   r3   r;   r   r<   r4   r+   rA   )tokenizer   encoder   r,   
isinstancer~   ry   r   _grammar_for_response_formatr  dictnextrm   llama_grammarLlamaGrammarfrom_json_schemajsondumps	Exceptionprintsysstderrr   	JSON_GBNFcreate_completionr  r   )*rC   rD   r$   r%   r&   r'   r(   r)   r*   r5   r6   r+   r,   r-   r.   r/   r0   r1   r2   r7   r8   r9   r:   r3   r;   r<   r4   r=   r>   rE   resultr   rstopr   r   toolschemaer   r   rn   chat_formatters*                                           @rF   chat_completion_handlerJchat_formatter_to_chat_completion_handler.<locals>.chat_completion_handler.  s   L  '#
 MM  ),,,

 ;;"2Zc5J5JD6PTD#-fkk4#@#@FKKv{{mE%<D ##/ & 8 8&?6+Bm+S2G
   !*
 !*H ' ( !*   $---'=F+B+-..6]3J&f 5! #;--!z*62DKEKTRD| =6K!LMM*%l3F
'44EEJJv& F   %66  
 
# 
  
 	 

  
   
 &.\4 
  
  
  
 " 
 . 
 0 
 * 
  
  (! 
" &# 
$ &% 
& ' 
( .) 
* 0+ 
, - 
. "/ 
2 Z(0I7/  ++?OOWL  ==#a&szz2'44@@!++U]] A s   1I#<I$ $
K .A(KK <rC   rJ   rD   rK   r$   rL   r%   rM   r&   rN   r'   rO   r(   rP   r)   rP   r*   rQ   r5   rP   r6   rP   r+   rR   r,   rS   r-   rT   r.   rU   r/   rT   r0   rP   r1   rP   r2   rP   r7   rP   r8   rQ   r9   rP   r:   rP   r3   rV   r;   rX   r<   rY   r4   rW   r=   rZ   r>   rT   r[   r\   rA   )r6  r7  s   ` rF   r   r   +  s    IMQU@DLP 02" $("%#& #!!#@D0415#'&*AMPMP AMP F	MP
 OMP >MP JMP MP MP MP MP MP MP .MP MP 
!MP& "'MP(  )MP* !+MP, -MP. /MP0 1MP2 3MP4 5MP6 7MP8 >9MP: .;MP< /=MP> !?MP@ $AMPD
EMP MP^ #"rI   c                R   ^ SSK Jn  UR                  U 5      m      SU4S jjnU$ )Nr   AutoTokenizerc                   > STl         TR                  U SS9n[        U[        5      (       d   e[	        UTR
                  SS9$ )NFr   Tr   r,   r   )use_default_system_promptapply_chat_templater"  r~   r   r   )rD   rE   r   	tokenizers      rF   format_autotokenizer@hf_autotokenizer_to_chat_formatter.<locals>.format_autotokenizer  sO     /4	+33Hu3M&#&&&&$	 3 34
 	
rI   r   )transformersr<  from_pretrained)pretrained_model_name_or_pathr<  rC  rB  s      @rF   "hf_autotokenizer_to_chat_formatterrH    s@     +--.KLI

@



 


  rI   c                .    [        U 5      n[        U5      $ r@   )rH  r   )rG  r6  s     rF   +hf_autotokenizer_to_chat_completion_handlerrJ    s     88UVN4^DDrI   c                z  ^^^^ [        U [        5      (       d   eSU ;   d   e[        U S   [        5      (       d   eU S   nSU ;   d   e[        U S   [        5      (       d   eU S   mSU ;   d   e[        U S   [        5      (       d   eU S   m[        SSS9R	                  U5      m      SUUUU4S jjnU$ )Nchat_templater   r   Tr   r   c                   > T(       a  / U Q[         R                  " SSS9Pn TR                  U TTS9n[        UTT/SS9$ )Nr    r   )rD   r   r   Tr?  )llama_types%ChatCompletionRequestAssistantMessager   r   )rD   rE   r   r   r   envr   s      rF   format_tokenizer_configFhf_tokenizer_config_to_chat_formatter.<locals>.format_tokenizer_config  sh     !AA$bH   

 %I 6d
 	
rI   r   )r"  r$  r~   r   r   )tokenizer_configr   rL  rS  r   rR  r   s    `  @@@rF   %hf_tokenizer_config_to_chat_formatterrV    s     &----....&7====$_5M****&{3S9999 -I****&{3S9999 -I
' k-  

@

 

 
, #"rI   c                *    [        XS9n[        U5      $ )N)r   )rV  r   )rU  r   r6  s      rF   .hf_tokenizer_config_to_chat_completion_handlerrX    s     ;N 5^DDrI   c                    SU ;  a  g U S   [         :X  a  gU S   [        :X  d  U S   [        :X  a  gU S   [        :X  a  gg )Nztokenizer.chat_templatechatmlmistral-instructllama-3)CHATML_CHAT_TEMPLATEMISTRAL_INSTRUCT_CHAT_TEMPLATEMIXTRAL_INSTRUCT_CHAT_TEMPLATELLAMA3_INSTRUCT_CHAT_TEMPLATE)metadatas    rF   $guess_chat_format_from_gguf_metadatarb    sW     0)*.BB 	*+/MM-.2PP!)*.KKrI   c                H    U  H  nUS   S:X  d  M  US   =(       d    Ss  $    g)zGet the first system message.r   systemr   rO  rA   )rD   r   s     rF   _get_system_messagere  1  s/     6?h&9%++  rI   c                    / nU  HC  nUS   nXA;   d  M  [        US   [        5      (       a  US   OSnUR                  X   U45        ME     U$ )zMap the message roles.r   r   N)r"  r~   append)rD   role_mapoutputr   r   r   s         rF   
_map_rolesrj  ;  s^    
 /1Fv&01CS&I&I	"t  MM8>734  MrI   c                    X#/nX-   n[        U5       HP  u  nu  pxU (       a  US:X  a  U=(       d    Sn	XYXFS-     -   -  nM.  U(       a  XWU-   S-   XFS-     -   -  nMI  XWS-   -  nMR     U$ )z(Format the prompt with the llama2 style.r   rO      r   )
system_messagerD   sepsep2sepsretr   r   r   ms
             rF   _format_llama2ru  K  s     ;D

C'1?Da1f2AtE{?"C'>C'$1u+55C#:C 2 JrI   c                ^    X-   nU H"  u  pEU(       a  X4S-   U-   U-   -  nM  X4S-   -  nM$     U$ )z2Format the prompt with the add-colon-single style.: :rA   ro  rD   rp  rs  r   r   s         rF   _format_add_colon_singlerz  \  sD     
C!$;(3..C#:C	 "
 JrI   c                    X#/nXS   -   n[        U5       H*  u  nu  pxU(       a  XWS-   U-   XFS-     -   -  nM#  XWS-   -  nM,     U$ )z/Format the prompt with the add-colon-two style.r   rw  rl  rx  rn  )	ro  rD   rp  rq  rr  rs  r   r   r   s	            rF   _format_add_colon_twor|  i  s_     ;D
7
"C'1?D$;(4A;66C#:C	 2
 JrI   c                N    U nU H  u  pEU(       a  X4U-   U-   -  nM  X4-  nM     U$ )z1Format the prompt with the no-colon-single style.rA   ry  s         rF   _format_no_colon_singler~  w  s7     C!'>C''CKC	 "
 JrI   c                ^    X-   nU H"  u  pEU(       a  X4S-   U-   U-   -  nM  X4S-   -  nM$     U$ )z8Format the prompt with the add-colon-space-single style.rw  rA   ry  s         rF   _format_add_colon_space_singler    sD     
C!$;(3..C$;C	 "
 JrI   c                z    U S:X  a  SOX-   S-   nU H%  u  pEU(       a  X4S-   U-   U-   S-   -  nM  X4S-   -  nM'     U$ )z(Format the prompt with the chatml style.rO  
rA   ry  s         rF   _format_chatmlr    sW     "$".*>*EC!$;(3.55C$;C	 "
 JrI   c                j    SnU (       a  X0-  nU H  u  pEU(       a  X4S-   S-   U-   -  nM  X4-  nM!     U$ )z*Format the prompt with the chatglm3 style.rO  r  rm  rA   ry  s         rF   _format_chatglm3r    sG     C!$;$w..CKC	 "
 JrI   c                Z    [         R                  R                  [         R                  U S9$ Nr  )r&  r'  r   r/  r  s    rF   _grammar_for_jsonr    s+    %%11 2  rI   c                     [         R                  R                  XS9$ ! [         a  nU(       a  [	        US9s S nA$ UeS nAff = fr  )r&  r'  r(  r+  r  )r4  r  fallback_to_jsonr5  s       rF   _grammar_for_json_schemar    sD    ))::6:SS $W55G	s    
AA AA  Ac                v    U S   S:w  a  g SU ;   a!  [        [        R                  " U S   5      US9$ [        US9$ )Nr   r  r4  r  )r  r)  r*  r  )r.   r  s     rF   r#  r#    sI     v-/?"'JJx017
 	
 !11rI   c                   ^  SU 4S jjnU$ )Nc                R   > [        U 5      n[        5       R                  TU5        U $ r@   )r   rh   rq   )r   r7  rn   s     rF   r   'register_chat_format.<locals>.decorator  s,    "KA"N*,MM)	
 rI   )r   r   rA   r   s   ` rF   register_chat_formatr    s     rI   zllama-2c                    Sn[        SSS9n[        X5      n[        U 5      nU(       a  UR                  US9n[	        XTSS5      S-   n[        US9$ )	Nz([INST] <<SYS>>
{system_message}
<</SYS>>z	<s>[INST]z[/INST]userr   ro  rm  r   r   )r$  rj  re  formatru  r   )rD   rE   _system_template_roles	_messagesro  _prompts          rF   format_llama2r    s_    
 D{i8F8,I(2N)000O^VDyPG 00rI   r\  c                    [        SSSS9nSn[        X5      nUR                  US   S 45        [        SXC5      n[	        XSS9$ )	Nz,<|start_header_id|>system<|end_header_id|>

z*<|start_header_id|>user<|end_header_id|>

z/<|start_header_id|>assistant<|end_header_id|>

)rd  r  r   z
<|eot_id|>r   rO  r   r,   )r$  rj  rg  r~  r   )rD   rE   r  _sepr  r  s         rF   format_llama3r    sW    
 ?;EF
 D8,If[)401%b):G ;;rI   alpacac                t    [        SSS9nSnSn[        U 5      n[        X5      n[        XVX45      n[	        US9$ )Nz### Instruction### Responser  

r   r  )r$  re  rj  r|  r   )rD   rE   r  r  _sep2ro  r  r  s           rF   format_alpacar     sF    
 (NCFDE(2N8,I#NtKG 00rI   qwenc                    [        SSS9n[        U 5      =(       d    SnSnUR                  US9n[        X5      nUR	                  US   S 45        Sn[        X5U5      nS	n[        XxS
9$ )N<|im_start|>user<|im_start|>assistantr  You are a helpful assistant.#<|im_start|>system
{system_message}r  r   r   z<|endoftext|>r  )r$  re  r  rj  rg  r  r   )	rD   rE   r  ro  system_templater  r  r  r  s	            rF   format_qwenr    s}    
 )5LMF(2T6TN<O$++>+JN8,If[)401D^=GE <<rI   vicunac                    Sn[        SSS9nSnSnUn[        X5      nUR                  US   S 45        [        XgXE5      n[	        US9$ )	NzA chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.USER	ASSISTANTr  rm  r   r   r  )r$  rj  rg  r|  r   )	rD   rE   _system_messager  r  r  ro  r  r  s	            rF   r  r    s^    
 sOv5FDE$N8,If[)401#NtKG 00rI   oasst_llamac                    Sn[        SSS9nSn[        U 5      nUR                  US9n[        X5      nUR	                  US   S 45        [        XVU5      n[        US9$ )	Nz*[INST] <<SYS>>
{system_message}
<</SYS>>

<|prompter|><|assistant|>r  r   r  r   r  r$  re  r  rj  rg  r~  r   rD   rE   r  r  r  ro  r  r  s           rF   format_oasst_llamar  /  sr    
 H~AFD(2N%,,N,KN8,If[)401%nFG 00rI   z
baichuan-2c                    Sn[        SSS9nSn[        U 5      nUR                  US9n[        X5      nUR	                  US   S 45        [        XVU5      n[        US9$ )	N{system_message}z<reserved_106>z<reserved_107>r  rO  r  r   r  r  r  s           rF   format_baichuan2r  ?  s    
 *'3CDFD(2N%,,N,KN8,If[)401%nFG 00rI   baichuanc                    Sn[        SSS9nSn[        U 5      nUR                  US9n[        X5      nUR	                  US   S 45        [        XVU5      n[        US9$ )	Nr  z<reserved_102>z<reserved_103>r  rO  r  r   r  r  r  s           rF   format_baichuanr  O  r  rI   	openbuddyc                    Sn[        SSS9nSnUn[        X5      nUR                  US   S 45        [        XVU5      n[	        US9$ )Na  You are a helpful, respectful and honest INTP-T AI Assistant named Buddy. You are talking to a human User.
Always answer as helpfully and logically as possible, while being safe. Your answers should not include any harmful, political, religious, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.
You can speak fluently in many languages, for example: English, Chinese.
You cannot access the internet, but you have vast knowledge, cutoff: 2021-09.
You are trained by OpenBuddy team, (https://openbuddy.ai, https://github.com/OpenBuddy/OpenBuddy), you are based on LLaMA and Falcon transformers model, not related to GPT or OpenAI.

User	Assistantr  r  r   r  r$  rj  rg  rz  r   )rD   rE   r  r  r  ro  r  r  s           rF   format_openbuddyr  _  sZ    
O v5FD$N8,If[)401&~$GG 00rI   zredpajama-incitec                    [        U 5      n[        SSS9nSnSnUn[        X5      nUR                  US   S 45        [	        XgU5      n[        XS9$ )Nz<human>z<bot>r  r  r   r  )re  r$  rj  rg  rz  r   )	rD   rE   r  r  r  _stopro  r  r  s	            rF   format_redpajama_inciter  u  sb    
 *(3OyG4FDE$N8,If[)401&~$GG <<rI   snoozyc                    SnSn[        U 5      nUS:w  a  UOUnUR                  US9n[        SSS9nSnS	nUn[        X5      n	U	R	                  US
   S 45        [        XYU5      n
[        XS9$ )Nz!### Instruction:
{system_message}zThe prompt below is a question to answer, a task to complete, or a conversation to respond to; decide which and write an appropriate response.rO  r  z
### Promptr  r  r  z###r   r  )re  r  r$  rj  rg  rz  r   )rD   rE   r  default_system_messager  ro  r  r  r  r  r  s              rF   format_snoozyr    s    
 ;O n)(3O*b06L  %++?+KN|~>FDE$N8,If[)401&~$GG <<rI   phindc                    [        SSS9nSnSn[        X5      nUR                  US   S 45        [        XEU5      n[	        US9$ )Nz### User Messagez### Assistantr  r  z?### System Prompt
You are an intelligent programming assistant.r   r  r  rD   rE   r  r  r  r  r  s          rF   format_phindr    sT    
 )_EFDXO8,If[)401&4HG 00rI   intelc                    [        SSS9nSnSn[        X5      nUR                  US   S 45        [        XEU5      n[	        US9$ )Nz	### User:z### Assistant:r  r  z### System:
{system_message}r   r  r  r  s          rF   format_intelr    sT    
 {.>?FD5O8,If[)401&4HG 00rI   z	open-orcac           	         SnSnSnSnSnUR                  US9n[        U [        [        XD5      5      5      nUR	                  US   S 45        [        X7U5      n[        XS9$ )	Nr  a  You are a helpful assistant. Please answer truthfully and write out your thinking step by step to be sure you get the right answer. If you make a mistake or encounter an error in your thinking, say so out loud and attempt to correct it. If you don't know or aren't sure about something, say so clearly. You will act as a professional logician, mathematician, and physicist. You will also act as the most appropriate type of expert to answer any particular question or solve the relevant problem; state which expert type your are, if so. Also think of any particular named expert that would be ideal to answer the relevant question or solve the relevant problem; name and act as them, if appropriate.)r  r  z<|end_of_turn|>
r  r  r   r  )r  rj  r$  r   rg  r  r   )	rD   rE   r  ro  rolesrp  stop_strr  r  s	            rF   format_open_orcar    s|    
 )O	B  "E
CH$++>+JN8T#e*;%<=IeAh%&,^LG ??rI   mistrallitec                    [        SSS9nSnSn[        U 5      nUR                  US9n[        X5      nUR	                  US   S 45        [        XVU5      n[        US9$ )	Nr  z</s>
<|assistant|>r  rm  z<|system|>{system_message}</s>r  r   r  r  )rD   rE   r  r  r  ro  r  r  s           rF   format_mistralliter    sq    
 ~1FGFD:O(2N$++>+JN8,If[)401%nFG 00rI   zephyrc                    Sn[        U 5      nUR                  US9n[        SSS9nSn[        X5      nUR	                  US   S 45        [        X6U5      n[        XuS9$ )	N<|system|>
{system_message}r  z	<|user|>
z<|assistant|>
r  r   r   r  re  r  r$  rj  rg  r  r   rD   rE   r  ro  r  r  r  r  s           rF   format_zephyrr    sq    
O(2N$++>+JN|/@AFD8,If[)401^=G ;;rI   	pygmalionc                    Sn[        U 5      nUR                  US9n[        SSS9nSn[        X5      nUR	                  US   S 45        [        X6U5      n[        XuS9$ )	Nz<|system|>{system_message}r  <|user|>z	<|model|>r  r  r   r  r  r  s           rF   format_pygmalionr    sp    
 7O(2N$++>+JNz[9FD8,If[)401^=G ;;rI   rZ  c                    Sn[        U 5      nUR                  US9n[        SSS9nSn[        X5      nUR	                  US   S 45        [        X6U5      n[        XuS9$ )	Nr  r  r  r  r  r   r   r  r  r  s           rF   format_chatmlr    sr    
O(2N$++>+JN)5LMFD8,If[)401^=G ;;rI   r[  c                    SnUnSnU  HX  nUS   S:X  a+  US   b%  [        US   [        5      (       a  USUS   -   -  nM7  US   S:X  d  MB  US   c  MJ  USUS   -   U-   -  nMZ     US-  n[        XCS	9$ )
Nr   rO  r   r  r   z[INST] r   z [/INST]r  )r"  r~   r   )rD   rE   eosr,   r   r   s         rF   format_mistral_instructr    s    
 CDFFOv%	".79-s33i')"444FV_+	0B0Nj79#55;;F  jF ::rI   chatglm3c                    Sn[        U 5      nUR                  US9n[        SSS9nSn[        X5      nUR	                  US   S 45        [        X6U5      n[        XuS9$ )	Nr  r  r  r  r  r   r   r  )re  r  r$  rj  rg  r  r   r  s           rF   format_chatglm3r  )  sp    
O(2N$++>+JNz_=FD8,If[)401~$?G ;;rI   openchatc                    Sn[        U 5      nUR                  US9n[        SSS9nSn[        X5      nUR	                  US   S 45        [        X6U5      n[        XuS9$ )	Nz{system_message}<|end_of_turn|>r  zGPT4 Correct User: z'<|end_of_turn|>GPT4 Correct Assistant: r  z<|end_of_turn|>r   r  r  r  s           rF   format_openchatr  :  sv    
 8O(2N$++>+JN".WF D8,If[)401^=G ;;rI   saigac                    Sn[        SSSS9n[        X5      nSnU H(  u  pgU(       a  XRR                  XgS9-  nM  USU S	3-  nM*     US
-  n[        UR	                  5       S9$ )Nz<s>{role}
{content}</s>r  botrd  )r  r  rd  rO  r   r   r  z<s>botr  )r$  rj  r  r   strip)rD   rE   _message_templater  r  r  r   r   s           rF   format_saigar  N  s{    
 3v5:F8,IG"//T/KKGTF"~%G	 # xG 88rI   gemmac                    [        U 5      nUS:w  a  [        R                  " S5        [        SSS9nSn[	        X5      nUR                  US   S 45        [        SXTS9n[        XdS	9$ )
NrO  zB`role='system'` messages are not allowed on Google's Gemma models.z<start_of_turn>user
z<start_of_turn>model
r  z<end_of_turn>
r   )ro  rD   rp  r  )re  r   debugr$  rj  rg  r~  r   )rD   rE   ro  r  r  r  r  s          rF   format_gemmar  d  ss    
 )2NP	
 .:RSFD8,If[)401%R)VG ;;rI   functionaryr   r   r   r    r!   r   r   r"   r#   c                ~	  ^%^&^'^( Sm%      S<U(4S jjm(S=U(4S jjm'S>S?U'U(4S jjjm&  S@     SAU%U&4S jjjnUb   U Vs/ s H  nUS   S:X  d  M  US   PM     nnUb  [        U[        5      (       a  UOUS   nU" XU5      nUcj  Ub  [        U5      S:X  aX  U R                  " SB0 S	US
-   _SU_SU_SU_SU	_SU
_SU_SSS/_SU_SU_SU_SU_SU_SU_SU_SU_SU_SU_SU_6n[	        UUS9$ Ub  [        U[        5      (       aE  US :X  a?  S!nU R                  " UUS"S#9nUS$   S   S%   nUR                  S&5      S'   S S' nUU-   U-   n OM[        U[        5      (       a  US(:w  a  US
-   n O,[        U[        5      (       a  US)US*    S
3-   n US*   nOUS
-   n S n!U=(       d    /  H  n"U"S*   U:X  d  M  U"S+   n!  O   U=(       d    /  H$  nUS   S:X  d  M  US   S*   U:X  d  M  US   S+   n!  O   U!b   [        U R                  S,9   [        R                  " [        R                  " U!5      5      n#[        R                  R                  [        R                  " [        R                  " U!5      5      U R                  S-9n[        U#5        S S S 5        OR[        U R                  S,9   [        R                  R                  [        R"                  U R                  S-9nS S S 5        U R                  " SB0 S	U _SSS/_SS"_SU_SU_SU_SU_SU_SU	_SU
_SU_SU_SU_SU_SU_SU_SU_SU_SU_6nS/U;   d   e[        U[        5      (       d   eUS"L d   eU R                  (       a  [        U 5        [        US$   S   S%   5        [$        R&                  " S0US1   -   S2US3   US   SS4S UUS$   S   S%   S5.USUUS$   S   S%   S5.S6./S7.[)        US$   S   S8   5      S9S:./US/   S;9$ s  snf ! , (       d  f       GN= f! [          a  n$U R                  (       a  [        S.5        [        U$5        [        U R                  S,9   [        R                  R                  [        R"                  U R                  S-9nS S S 5         S n$A$GM  ! , (       d  f        S n$A$GN= fS n$A$ff = f! , (       d  f       GN= f)CNA chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. The assistant calls functions with appropriate input when necessaryc                  > SU-  nSU ;   a  U S   R                  S5      S   nU$ U R                  S5      S:X  a$  U R                  S0 5      nT" XQS-   U5      nS	U S
3$ U R                  S5      S:X  aP  U R                  S0 5      nSnUR                  5        H  u  pT" XS-   U5      nUU SU	 SU S3-  nM!     XS-   -  nU$ SU ;   a)  SR                  U S    Vs/ s H	  nSU S3PM     sn5      $ U R                  SS5      $ s  snf N  z$ref/r   r   arrayr   r   zArray<>r   
propertiesz{
rw  ,
}enum | "anysplitgetr   joinparamindent_levelshared_defsindentref_namer   	item_typer  nested_schemanested_param_namenested_paramnested_param_type
enum_valuegenerate_type_definitions                rF   r  :functionary_chat_handler.<locals>.generate_type_definition  R    $U?V}**3/H OYYv')IIgr*E0q8H+VII;a((YYv(*<4J!M3=3C3C3E/!$< "2K%! hb!2 326G5HL	 4F c\)M  u_::5=Q=Z:,a0=QRR 99VU++ R   Dc           
       > SU-  nSnU R                  5        Hh  u  pEX2 SU S3-  nUR                  S5      S:X  a  UT" XQU 5      -  nO2SU;   a,  USR                  US    Vs/ s H	  nS	U S	3PM     sn5      -  nUS
-  nMj     U$ s  snf Nr   rO  type z = r   r   r  r  r	  z;
r   r  r  r  r  r  shared_definitionsdef_namedef_propertiesr  r  s          rF   generate_shared_definitions=functionary_chat_handler.<locals>.generate_shared_definitions      $(3(9(9(;$HHE(3"??!!&)X5"&>"+' " >)"ejj9G9OP9O:qA&9OP' " %' )< "! Q   #Bc           	     Z  > SnUSU S3-  n0 nU  H6  nUR                  S0 5      nUR                  UR                  S0 5      5        M8     UT" US5      -  nU  H  nUS   nUR                  SS	5      nUR                  S0 5      nUR                  S
/ 5      nUSU S3-  nUSU S3-  nUR                  S0 5      R                  5        HA  u  pU
R                  SS	5      nT" U
SU5      nX;   a  S	OSnUSU S3-  nUSU	 U SU S3-  nMC     US-  nM     USR                  U5      -  nU$ )NH// Supported function definitions that should be called when necessary.

namespace  {

r  $defsr   rn   descriptionrO  requiredz  // r  z  type 	 = (_: {
r  rl  ?z    // z    rw  r  z  }) => any;

z}} // namespace {}
r  updater   r  r$   	namespacer4  r$  r   r  function_namer0  required_params
param_namer  param_description
param_typeoptional_indicatorr'  r  s                 rF   generate_schema_from_functions@functionary_chat_handler.<locals>.generate_schema_from_functions  s   W 	 	Jyk11  !H!lB7J%%jnnWb&AB " 	-.@!DD!H$V,M",,}b9K!lB7J(nnZ<Ok]"--Fk::F%/^^L"%E%K%K%M!
$)IImR$@!5eQ@RS
+5+HRc"G$5#6b99D-?,@:,cRR &N ((F "" 	(//	::rI   c                  > / nUb*  UR                  [        R                  " ST	" U5      S95        UbI  UR                  [        R                  " ST	" U Vs/ s H  nUS   S:X  d  M  US   PM     sn5      S95        UR                  [        R                  " STS95        U  HE  nUS   S:X  a  SU;   a  SUS    3US'   SU;   a  SUS   S    3US   S'   UR                  U5        MG     UR                  [        R                  " S	S S95        SS
 jnSR	                  U Vs/ s H
  ov" U5      PM     sn5      $ s  snf s  snf )Nrd  r   r   r   r   rn   
functions.r%   r   c                p   U S   S:X  a	  SU S    S3$ U S   S:X  a  SU ;   a  SU S    S	U S    S3$ U S   S:X  a  S
U ;   a  SU S
   S    S	U S
   S    S3$ U S   S:X  a  U S   b  SU S    S	U S    S3$ SU S    S3$ U S   S:X  a  U S   c  gSU S    S3$ U S   S:X  a  U S   b!  S
U ;   a  SU S    SU S
   S    S	U S
   S    S3$ S
U ;   a  SU S
   S    S	U S
   S    S3$ SU ;   a1  [        U S   5      S:  a  U S    H  nSUS    S	US   S    S3s  $    g U S   c  gSU S    S3$ [        SU S    35      e)Nr   rd  zsystem:
r   r  r   rn   zfunction name=:
r%   r   r3  tool_call_idr  zuser:
</s></s>
z
user:
</s>z</s>
r   assistant:
z
assistant to=zassistant to=r   r   r   zUnsupported role: )lenrm   )msg	tool_calls     rF   message_to_strXfunctionary_chat_handler.<locals>.prepare_messages_for_inference.<locals>.message_to_str  s>   6{h&"3y>"2"55V
*v}'F}CI7GrJJV
*#/E'O(<V(D'ES_I]^iIjHkkmnnV&y>-+C,?+@C	NCSSUVV+C,?+@CCV&y>).(Y(8??V+y>-/S2H)#i.)9_I]^dIeHffijmn}j~  @K  kL  jM  MS  T  T$+*3+?+G*HCP_L`alLmKnntuu!S(S\1B-Ca-G%($&	 "/y.?s9ZCXYdCeBfflmm& ^+&)#i.)9<< #5c&k]!CDDrI   rO  )rG  z(llama_types.ChatCompletionRequestMessage)rg  rP  "ChatCompletionRequestSystemMessagerQ  r  )
rD   r$   r&   all_messagesr3  r   rI  rG  SYSTEM_MESSAGEr>  s
           rF   prepare_messages_for_inference@functionary_chat_handler.<locals>.prepare_messages_for_inference  s   
 HJ >>!+I)+T >>!: ).(-#F|z9 -D,(-	 	::~	
  Gv*,71B$.wv.?"@') !!9&!A BC ( (   	== $	
!	EF ww|D|s+|DEEGF Es   D<'	D<$Er   r   r   r   rC  r(   r)   r*   r5   r6   r+   r,   zuser:r   r/   r0   r1   r2   r7   r8   r9   r:   r3   r;   r<   r  r  r  F)r   r,   r+   r   r   .r   r  z to=functions.rn   r  disabler  MFailed to parse function body as JSON schema, falling back to default grammarr   r   r   r   r   r   r   r   r   r=   r   r   r   r  zDict[str, llama_types.JsonType]r  rQ   r[   r~   r  rQ   r[   r~   r$   r[   r~   NN)rD   rK   r$   3Optional[List[llama_types.ChatCompletionFunctions]]r&   rN   rA   )r"  r~   rF  r0  r   r  r$  r   r  r&  json_schema_to_gbnfr)  r*  r'  r   r,  r+  r/  rP  CreateChatCompletionResponser   ))rC   rD   r$   r%   r&   r'   r(   r)   r*   r5   r6   r+   r,   r.   r/   r0   r1   r2   r7   r8   r9   r:   r3   r;   r<   rE   rN  r3  r   completion_or_completion_chunksr   completion_text
new_promptfunction_bodyr   grammar_textr5  rM  r>  r'  r  s)                                        @@@@rF   functionary_chat_handlerra  y  s<   : zN,.,>A,	,B""   H JN@DUF@UFFUF >UF UFn 27V%$4<:;U%T*%%	V%k377K[=T 	 ,HGF)"3s9~7J*/*A*A +
E>+
#+
 +
 	+

 +
  +
 +
 6"+
 "+
 .+
 0+
 *+
 +
 (+
 &+
  &!+
" #+
$ .%+
& '+
'* ++JSYZZ=#&&=F+B-2-D-DU.

 %Y/26:'--c226s;o-4
	M3	'	'MV,Ce^
	M4	(	(}V/D.ESII
%f-e^
MOOF},$\2M $ <:%$z*:6*Bm*S ,\:M 
  	'>,@@JJ}-  (44@@!55djj6OP!MM A  l# ?>* $EMM:#00<<'' = G ;
 */)@)@ **v* * 	*
 *  * * * * * ** ,* &* * $*  "!*" "#*$ %*& *'*J, j   mS))))U??}}jj#A&v./ 33Jt$$ 9%! '# -%/	%:1%=f%E& #0$.(5-7	-B1-Ef-M)	#$ FjQZF[\]F^_iFjk!-+
2 != s W@ ?>  
	}}c a'>'44@@!++!MM A  ?>>>>
	 ;:sm   O.	O.7P 
BO3P ,7R-3
P=P P 
R*:R%	7R R%
R"	R%"R%%R*-
R<zfunctionary-v1zfunctionary-v2c                  ^ ^^^^^^	^
^^^^^^^^^^^^4^5^6^7^8^9^:^;^<^=^> Sm8T R                   n[        US5      (       d   S5       eSSKJn  SUR                  R
                  ;   a  Sm>SnS	nS
nSnSn Sn!O
Sm>Sm6Sm5Sm7Sm4      SVU<4S jjm<SWU<4S jjm;SXSYU;U<4S jjjm:   SZ           S[U8U:4S jjjn"Tb!  T V#s/ s H  n#U#S   S:X  d  M  U#S   PM     sn#mUb  [        U[        5      (       a  UOUS   nOUb  OSnU"" UUT>TTU5      n$US:X  d  Tb  [        T5      S:X  a  T>S:X  a  WnOT7nU$S-  n$T R                  " S\0 SU$_ST_ST_ST_ST	_S T
_S!T_S"U_S#T_S$T_S%T_S&T_S'T_S(T_S)T_S*T_S+T_S,T_S-U_6n%TS.L a"  U%S/   S   S0   R                  5       U%S/   S   S0'   [        U%TS19$ UU U4S2 jm=UU UUU	UUUUUUUUUUUU
4S3 jm9S4n&/ / n(n'Sn)U4U5U6U7U9U=U>4S5 jn*TS.La	  U*" TTUU$S69$ T>S:X  Gai  [        U[        5      (       a  US:X  a  S7W/n+OI[        U[        5      (       a.  U$W  US8    S93-  n$W!n+US8   nU'R                  U5        T=" U5      nOU$n$S7W/n+T9" U$U+US:9n,U,S/   S   S0   n-U)U,S;   S<   -  n)W U$;  a  U U-;  a  U)U,S;   S<'   [        U,TS19$ U U$;  a  U U-;   a  U$U-R                  U  S=3U 5      S7-   -  n$U'R                  U-R                  U 5      S>   S S> R!                  5       5        T=" U'S>   5      nT9" U$W!US:9n,U)U,S;   S<   -  n)U(R                  U,S/   S   S0   R!                  5       5        GOU(R                  U-R!                  5       5        GO[        U[        5      (       an  U$US8    S7T4 3-  n$US8   nU'R                  U5        T=" U5      nT7T5/n+T9" U$U+US:9n,U,S/   S   S0   n-U)U,S;   S<   -  n)U(R                  U-R!                  5       5        GO[        U[        5      (       Ga  US:X  Ga   S nT4n+T9" U$U+US:9n,U,S/   S   S0   n-U)U,S;   S<   -  n)U-R!                  5       n.U.S?:X  a  U$S-  n$O1U-R!                  5       nU$U S@3-  n$U'R                  U5        T=" U5      nT6T7/n+T9" U$U+US:9n,U,S/   S   S0   n-U)U,S;   S<   -  n)U.S?:X  a  U-R#                  SA5      (       a  U&U-S [        SA5      *  -  n&U-R#                  SB5      (       a  U&U-[        SB5      *    -  n&OU&U--  n&U&R                  5       n&SCU-;   d  SDU-;   a  U-R#                  SA5      (       a  U-S [        SA5      *  R!                  5       n/ODU-R#                  SB5      (       a  U-[        SB5      *    R!                  5       n/OU-R!                  5       n/U$U/ SE3-  n$OmOoU(R                  U-R!                  5       5        U$U-R!                  5       -  n$S nT9" U$U+US:9n,U)U,S;   S<   -  n)SCU,S/   S   S0   ;   d  SDU,S/   S   S0   ;   a  U$SE-  n$OOGM  S;W,;   d   e[        U'5      [        U(5      :X  d   e/ n0[%        U'U(5       H}  u  nn1U0R                  SFS4R'                  [)        SG5       V2s/ s H8  n2[*        R,                  " [.        R0                  [.        R2                  -   5      PM:     sn25      -   SUU1SH.SI.5        M     0 n3[        U05      S:  a#  Tb  U0U3SJ'   OU0S   S   S8   U0S   S   SK   SH.U3SL'   U)U,S;   S<'   [4        R6                  " SMU,SN   -   SOU,SP   U,S+   S[9        U,S/   S   SQ   5      SRU&S4:X  a  S OU&SS.U3E[        U05      S:  a  SJOS"ST./U,S;   SU9$ s  sn#f s  sn2f )]Nr  hf_tokenizerznPlease provide a valid hf_tokenizer_path from https://huggingface.co/meetkai when initializing the Llama classr   r;  z<|START_OF_FUNCTION_CALL|>v1z<|END_OF_SYSTEM|>z<|END_OF_USER|>z<|END_OF_ASSISTANT|>z<|END_OF_FUNCTION_RESULT|>z<|END_OF_FUNCTION_CALL|>v2z<|recipient|>z<|from|>z<|stop|>z<|content|>c                  > SU-  nSU ;   a  U S   R                  S5      S   nU$ U R                  S5      S:X  a$  U R                  S0 5      nT" XQS-   U5      nS	U S
3$ U R                  S5      S:X  aP  U R                  S0 5      nSnUR                  5        H  u  pT" XS-   U5      nUU SU	 SU S3-  nM!     XS-   -  nU$ SU ;   a)  SR                  U S    Vs/ s H	  nSU S3PM     sn5      $ U R                  SS5      $ s  snf r  r  r  s                rF   r  @functionary_v1_v2_chat_handler.<locals>.generate_type_definition  r  r  c           
       > SU-  nSnU R                  5        Hh  u  pEX2 SU S3-  nUR                  S5      S:X  a  UT" XQU 5      -  nO2SU;   a,  USR                  US    Vs/ s H	  nS	U S	3PM     sn5      -  nUS
-  nMj     U$ s  snf r   r"  r#  s          rF   r'  Cfunctionary_v1_v2_chat_handler.<locals>.generate_shared_definitions5  r)  r*  c                V  > SnUSU S3-  n0 nU  H6  nUR                  S0 5      nUR                  UR                  S0 5      5        M8     UT" US5      -  nU  H  nUS   nUR                  SS	5      nUR                  S0 5      nUR                  S
/ 5      nUSU S3-  nUSU S3-  nUR                  S0 5      R                  5        H?  u  pU
R                  SS	5      nT" U
SU5      nX;   a  S	OSnUSU S3-  nX) U SU S3-  nMA     US-  nM     USR                  U5      -  nU$ )Nr,  r-  r.  r  r/  r   rn   r0  rO  r1  z// r  r!  r2  r  rl  r3  rw  r  z}) => any;

z}} // namespace {}r4  r6  s                 rF   r>  Ffunctionary_v1_v2_chat_handler.<locals>.generate_schema_from_functionsF  s   W 	 	Jyk11  !H!lB7J%%jnnWb&AB " 	-.@!DD!H$V,M",,}b9K!lB7J(nnZ<OK=++Fm_K88F%/^^L"%E%K%K%M!
$)IImR$@!5eQ@RS
+5+HRc"C 12"55L);(<Bzl#NN &N &&F "" 	&--i88rI   r  c                  > / nUS:X  a+  UR                  [        R                  " ST" / 5      S95        OUb+  UR                  [        R                  " ST" U5      S95        ORUbO  US:w  aI  UR                  [        R                  " ST" U Vs/ s H  nUS   S:X  d  M  US   PM     sn5      S95        UR                  [        R                  " ST
S95        U  HE  nUS   S:X  a  SU;   a  SUS    3US'   S	U;   a  SUS	   S    3US	   S'   UR                  U5        MG     US
:X  a  Sn	OSn	UR                  R	                  USS9U	-   $ s  snf )Nr  rd  r   r   r   r   rn   rA  r%   rd  rE  z<|from|>assistant
<|recipient|>Fr>  )rg  rP  rK  rc  rA  )rD   rB  versionr$   r&   r'   rL  r3  r   suffixrM  r>  s             rF   rN  Ffunctionary_v1_v2_chat_handler.<locals>.prepare_messages_for_inferenceh  s    HJ& >>!+I"+M $##BB%/Mi/X
 "{f'<##BB% > -2,1D#'<:#= !1Z 0,1!	 	::~	
  Gv*,71B$.wv.?"@') !!9&!A BC ( (   d?#F7F ""66|e6T	
?s   E	Er   r   r  all
<|content|>r   r(   r)   r*   r5   r6   r+   r,   r/   r0   r1   r2   r7   r8   r9   r:   r3   r;   r<   Fr   r   r  c                Z  > S nT=(       d    /  H  nUS   U :X  d  M  US   n  O   T	=(       d    /  H$  nUS   S:X  d  M  US   S   U :X  d  M  US   S   n  O    [        TR                  S9   [        R                  " [        R
                  " U5      5      n[        R                  R                  [        R                  " [        R
                  " U5      5      5      n[        U5        S S S 5        U$ ! , (       d  f       W$ = f! [         a  nTR                  (       a  [        S5        [        U5        [        TR                  S9   [        R                  R                  [        R                  TR                  S9nS S S 5         S nAU$ ! , (       d  f        S nAW$ = fS nAff = f)Nrn   r  r   r   rQ  rS  r  )r   r  r&  rZ  r)  r*  r'  r   r,  r+  r/  )
r%   r_  r   r3  r`  r<   r5  r$   rC   r&   s
          rF   get_grammar3functionary_v1_v2_chat_handler.<locals>.get_grammar  sy   !RH=0 ( 6 ( KRKDF|z)d:.>v.F-.W $Z 0 >  
	'>,@@JJ}-  (44@@!55djj6OP l# ?& ' ?>&   		}}c a'>'44@@!++U]] A  ?>
  ?>>
 		sU   D -A=C4*D 4
D>D D 
F*:F%
7FF%
F"	F%"F%%F*c           	        > [        [        R                  TR                  " S0 SU _ST_ST_ST_ST_ST_ST_SU_S	T_S
T_ST_ST_ST_ST
_ST_ST	_ST_ST_SU_65      nU$ )Nr   r(   r)   r*   r5   r6   r+   r,   r/   r0   r1   r2   r7   r8   r9   r:   r3   r;   r<   rA   )r   rP  
Completionr0  )r   r,   r<   r   r1   rC   r;   r/   r5   r:   r8   r9   r3   r0   r2   r+   r(   r7   r*   r)   r6   s       rF   r0  9functionary_v1_v2_chat_handler.<locals>.create_completion  s    ""## '  	
  $   & "2 #4  .  , *  *!" #$ "2%&  '

2 rI   rO  c              3    >#    TS:X  d   S5       eSu  pE[        U[        5      (       Ga  X2S    ST 3-  nT" US   5      nTT/nSR                  [        S5       Vs/ s H8  n[        R
                  " [        R                  [        R                  -   5      PM:     sn5      n	T" X7US9n
SnS	nU
 GH  nU(       aS  U b  S
SSU	-   SUS   SS.S./0nO
SUS   SS.0n[        R                  " SUS   -   SUS   US   SS S S S.UES./S9v   SnU b(  S
SSU	-   SS US   S   S   R                  5       S.S./0nOSS US   S   S   R                  5       S.0n[        US   S   S   R                  5       5      S:  d  M  [        R                  " SUS   -   SUS   US   S[        US   S   S   5      S S S.UES./S9v   GM     [        R                  " SWS   -   SUS   US   SU b  S
OSS S S S S S.S./S9v   g [        U[        5      (       Ga5  US:X  Ga-  Sn S nTnT" X7US9n
SnU
 H  nXS   S   S   -  nM     Uc  WS   nUc  WS   nUR                  5       nUS :X  a/  US!-  n[        R                  " SU-   WS   USSS"SS.S S S#./S$9v   OUU S%3-  nT" U5      nSR                  [        S5       Vs/ s H8  n[        R
                  " [        R                  [        R                  -   5      PM:     sn5      n	U b  S
USU	-   SUSS.S./0nOSUSS.0n[        R                  " SU-   SUWS   S[        US   S   S   5      S"S S.UES./S9v   TT/nT" X7US9n
US :X  Ga  SnS&/ Snnn[!        U
5       GH  u  nnXS   S   S   -  nU(       a  UR#                  US   S   S   R                  S'5      5        UR%                  SR                  U5      5      (       a  Mk  UR'                  5         [        U5      S:  aZ  [        R                  " SU-   SUUS   S[        US   S   S   5      S"UR'                  S5      S.S./S9v   [        U5      S:  a  MZ  SnO=US   S   S   S:X  a.  S	nUR#                  US   S   S   R                  S'5      5        GM$  [        U5      S:X  d  GM6  [        US   S   S   5      S:  d  GMQ  [        R                  " SU-   SUUS   S[        US   S   S   5      S"US:  a  US   S   S   OUS   S   S   R)                  5       S.S./S9v   GM     S(U;   d  S)U;   a  UR+                  S*5      (       a  US [        S*5      *  R                  5       nODUR+                  S+5      (       a  US [        S+5      *  R                  5       nOUR                  5       nUU S&3-  nGO[        R                  " SU-   US   USS0 S S,S#./S$9v   g SnU
 H  nXS   S   S   -  n[        US   S   S   R                  5       5      S:  d  M8  U b(  S
USW	-   SS US   S   S   R                  5       S.S./0nOSS US   S   S   R                  5       S.0n[        R                  " SU-   SUUS   S[        US   S   S   5      S S S.UES./S9v   M     X;R                  5       -  nS nT" X7US9n
USR                  U
 Vs/ s H  oS   S   S   PM     sn5      -  nS(U;   d  S)U;   a  U b  US&-  nUS--  nO1[        R                  " SU-   SUWS   SU b  S
OSS S S S S S.S./S9v   g GM*  g g s  snf s  snf s  snf 7f).Nre  z!Streaming for v1 is not supportedrX  rn   r  rO     r   r,   r<   Tr   r   call_r   r   r   r%   r   r   r   r   r3   r   )r   r=   r   r   Fr   r   r=   r   r   r  allrp  r   r   r   
<|content|> 
<|from|>assistant
<|recipient|>rm  <|from|> assistant<|from|>assistant
<|from|>assistant

<|from|> assistant
r,   r   )r"  r$  r  rangerandomchoicestringascii_lettersdigitsrP  "CreateChatCompletionStreamResponserstriprF  r   r~   r  r   rg  
startswithpoplstripendswith)r&   r$   r%   r   chunk_idchunk_createdr<   stopsr   r   r   r]  r   r   func_call_dict
tool_indexr8  stop_sequencebufferis_endr   cleaned_completion_textCONTENT_TOKEN
FROM_TOKENRECIPIENT_TOKEN
STOP_TOKENr0  rr  rm  s                         rF   generate_streaming:functionary_v1_v2_chat_handler.<locals>.generate_streaming  sV
    $C CC", mT**v./r-AAF!-"78G,EggNSTViXiv33fmmCDiXG +&gVJ OE#((-.*1G*;,60=f0E571&	!"
+* ,(5f(=-/.* &HH!E$K/6 %i 0#Gn *+,0,0/3*" '5*"
! " "E$$)*&-&7(2,016y1A!1DV1L1S1S1U-"	
'&N ($().y)9!)<V)D)K)K)M*&N uY'*6299;<q@%HH!E$K/6 %i 0#Gn *+,UV[\eVfghVijtVu,v,0/3*" '5*"
! A $d @@E$K'.i(Gn "#,1,=L?$($('+-1*.	" , s++0GJ%.!w
 #%'E#Y'7':6'BBO (#$T{H ($))$4M / 5 5 7 E)00F%HH!H,#Gn -6 *+2=")M,015	!  }==F)-8G gg &+2Y%. #MM&*>*>*NO%.G ((-7*1G*;,60=571&	!"
+* ,mRT-U* &HH!H,6 -#Gn *+,UV[\eVfghVijtVu,v,7/3*" '5*"
! $ )*5.!w
 !E)&(O< ,26M
 %.j$95'+;A+>v+FF!"MM%	*:1*=f*E*K*KC*PQ,77HH ( &

&)&kAo*5*X*X+1H+</F0=.3Gn :;<efklufvwxfy  {E  gF  =G<G?Ezz!}:2-.	1*+& %& '*&kAo" */"9-a08D@%)F"MM%	*:1*=f*E*K*KC*PQ$v;!+E)4DQ4G4O0PST0T"-"P"P#)H#4'>(5&+Gn 234]^cdm^nop^qr|^}4~4? 45q5 16i0@0CF0K5:95Ea5H4:6228&(	2*%&)"# A %:p -?./A*334KLL6E ?3'>#?"?7#eg 4 -556NOO6E @3'?#@"@7#eg 4 7F6K6K6M3%<$==_"`` *LL%0"'.$1#: ./-/045;	!"%   ')O!+'+;A+>v+FFuY/26:AACDqH$0$05?29G2C4>8<=B9=Ma=P4:>228&(	9.	
)*3&2"" %4045:95Ea5H,26**0&(	6&2" #."P"P#)H#4'>(5&+Gn 234]^cdm^nop^qr|^}4~487;2* /=2*%&
)"# 9 ",Z 3355F"G!2%7"J $rwwBLM*y)!,V4*M( O -?./A+"FF"a
 *LL%0#:$1"'. ./ ,1+< )5-<0404379=6:	.&!"% . O  1H+[ YfD NsO   A]?]
C] D>]>?]=E%]$A]6]E])B4]]
1A(])r&   r$   r%   r   r  rn   rC  ry  r   completion_tokensrm  r   r{  r|  r  r  r~  r  r}  rz  rx  r   r   r   r   r%   r   r   r   r   r=   r   r   )r   r=   r   r   r   rT  rU  rV  rW  )NNr  )rD   rK   rB  r<  rm  zLiteral['v1', 'v2']r$   rY  r&   rN   r'   zUnion[Dict, str]rA   )
tokenizer_hasattrrE  r<  rc  additional_special_tokensr"  r~   rF  r0  r  r   r$  rg  replacer  r  r  r   r  r  r  r  r  r  r  rP  r[  r   )?rC   rD   r$   r%   r&   r'   r(   r)   r*   r5   r6   r+   r,   r.   r/   r0   r1   r2   r7   r8   r9   r:   r3   r;   r<   rE   rB  r<  END_SYSTEM_TOKENEND_USER_TOKENEND_ASSISTANT_TOKENEND_FUNCTION_RESULT_TOKENSTART_FUNCTION_CALL_TOKENEND_FUNCTION_CALL_TOKENrN  r3  r   r\  r   function_callsfunction_bodiesr  r  r  r   r]  r8  r  r   r_  r   function_call_dictr  r  r  r  rM  r0  r>  r'  r  rr  rm  s?   ` ` ` ``````  ``````````                            @@@@@@@@@@@rF   functionary_v1_v2_chat_handlerr    s/
   < zN  I>  xwx  +#y'='='W'WW.*4$@!$@!"<)

%,.,>A,	,B""   L JN@D(.=
@=
 =
 %=
 G	=

 >=
 &=
 =
~ 27V%$4<:;U%T*%%V	%k377K[=T 	 
	"+)WiF
 )"3s9~7Jd?&DD((F*/*A*A +
+
#+
 +
 	+

 +
  +
 +
 +
 "+
 .+
 0+
 *+
 +
 (+
 &+
  &!+
" #+
$ .%+
& '+
'* U?/	:1=fELLN ,I6q9&A ++JSYZZB  8 G&("ONA AF U!9MRX
 	
 d?----62I23M40067f8M7NcRR/ -f 5%%m4%m423*&ugVJ(3A6v>OG!45H!II *7-_D;L
7#$782:fMM *7-@#++45Q79R  %%#))*CDRH"MSSU &nR&89.!(?
 "Z%89L%MM!&&z)'<Q'?'G'M'M'OP  &&'<'<'>? -..]6232m_EE -f 5%%m4%m4#Z0.!w
 #-Y"7":6"B!Z%89L%MM!&&'<'<'>?M3//MV4K"G)E!2%E7"J '1&;A&>v&FO%G)<=P)QQ%$3$9$9$;M$-"44(7(=(=(?]O="AA&--m<"-m"<,j9E!2%E7"J '1&;A&>v&FO%G)<=P)QQ%$-*334KLL#7V#>U:V9V'WWG*334LMM#<T8U7U'VVG#6G").."2 1OC2oE.778OPP:I$Cs+B'C&C;""'%' !8 "1!9!9:R!S!S:I%()A%B$B;""'%' !8 ;J:O:O:Q 7")@(AAc&ddF!'../D/D/FG/"7"7"99"&%6#)w&
 *Z-@AT-UU)0Jy4I!4LV4TT2j6KA6Nv6VV"&JJF!C F *$$$>"c/&::::FH
,/,P(M=!gg &+2Y%. #MM&*>*>*NO%. ' -%2! -Q2  	 z?Q 3="<0 'qM*5f=!+Az!:;!G7"?3 4E
7/077
4(($y)W%  I*U^J_`aJbcmJn o ++2b=4g  - 
 69_q5H\f	 W%#
 	
M WPs   ?]	]?]c                     \ rS rSr% SrS\S'   SrSSS jjrSS jrS S jr	S!S	 jr
S
S
S
S
SSSSSS/ S
S
S
SSSSSSSS
S
S
S
S
S
S.                                                           S"S jjr\S S j5       r\S#S j5       r\S$S j5       r\   S%             S&S jj5       rSrg
)'Llava15ChatHandleric
  zA chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.rV   DEFAULT_SYSTEM_MESSAGEa%  {% for message in messages %}{% if message.role == 'system' %}{{ message.content }}{% endif %}{% if message.role == 'user' %}{% if message.content is string %}
USER: {{ message.content }}{% endif %}{% if message.content is iterable %}
USER: {% for content in message.content %}{% if content.type == 'image_url' and content.image_url is string %}{{ content.image_url }}{% endif %}{% if content.type == 'image_url' and content.image_url is mapping %}{{ content.image_url.url }}{% endif %}{% endfor %}{% for content in message.content %}{% if content.type == 'text' %}{{ content.text }}{% endif %}{% endfor %}{% endif %}{% endif %}{% if message.role == 'assistant' and message.content is not none %}
ASSISTANT: {{ message.content }}{% endif %}{% endfor %}{% if add_generation_prompt %}
ASSISTANT: {% endif %}c                    SS K Jn  Xl        X l        X0l        [        5       U l        S U l        [        R                  R                  U5      (       d  [        SU 35      eg )Nr   z Clip model path does not exist: )llama_cpp.mtmd_cppmtmd_cppclip_model_pathr  	_mtmd_cppr   _exit_stackmtmd_ctxospathexistsrm   )rB   r  r  r  s       rF   r   Llava15ChatHandler.__init__
  sR    -.!$;;?ww~~o..??PQRR /rI   c                  ^  T R                   b  g[        T R                  S9   T R                  R	                  5       nSUl        T R                  Ul        UR                  Ul        T R                  (       a  SOSUl        T R                  R                  T R                  R                  5       UR                  U5      T l         T R                   c  [        ST R                   35      eT R                  R                  T R                   5      (       d  [        S5      eU 4S jnT R                  R!                  U5        SSS5        g! , (       d  f       g= f)	z-Initialize mtmd context with the llama model.NrQ  Trl  r   z"Failed to load mtmd context from: z%Vision is not supported by this modelc                    > [        T R                  S9   T R                  b,  T R                  R	                  T R                  5        S T l        S S S 5        g ! , (       d  f       g = f)NrQ  )r   r  r  r  	mtmd_freer   s   rF   r  8Llava15ChatHandler._init_mtmd_context.<locals>.mtmd_free
  sC    +DLLA}}000?(, BAAs   :A
A&)r  r   r  r  mtmd_context_params_defaultuse_gpuprint_timings	n_threads	verbositymtmd_init_from_filer  r!  r3   rm   mtmd_support_visionr  callback)rB   llama_model
ctx_paramsr  s   `   rF   _init_mtmd_context%Llava15ChatHandler._init_mtmd_context
  s
   ==$#DLL9CCEJ!%J'+||J$#.#8#8J (,1!J  !NN>>$$++-!!DM }}$ #EdFZFZE[!\]] >>55dmmDD !HII- %%i09 :99s   DE		
Ec                $    U R                  U5      $ r@   )_load_image)rB   	image_urls     rF   
load_imageLlava15ChatHandler.load_image
  s    	**rI   c           	     r   U R                   c  [        S5      e[        U R                  S9   U R                  R                  U R                   [        R                  [        U5      -  R                  [        U5      5      [        U5      5      nUc  [        S5      eUsSSS5        $ ! , (       d  f       g= f)z$Create mtmd_bitmap from image bytes.Nzmtmd context not initializedrQ  z(Failed to create bitmap from image bytes)r  rm   r   r  r   mtmd_helper_bitmap_init_from_bufctypesc_uint8rF  from_buffer	bytearray)rB   image_bytesbitmaps      rF   _create_bitmap_from_bytes,Llava15ChatHandler._create_bitmap_from_bytes
  s    == ;<<#DLL9^^DD#k"22??	+@VWK F ~ !KLL :99s   A2B((
B6Nr   r   r   r    r!   Fr   r   r   r"   r#   r  c                  ^? U R                  U5        U R                  c   e[        U5      nUS:X  a0  U R                  b#  [        R
                  " SU R                  S9/U-   nU R                  U5      n [        SSS9R                  U R                  5      n!U R                  R                  5       R                  S5      n"U!R                  USUR                  " UR                  " 5       /5      UR                  " UR                   " 5       /5      S9n#U  H  n$U#R#                  U$U"5      n#M     U R$                  (       a  ['        U#[(        R*                  S9  / n%/ n& U  HG  n$U R-                  U$5      n'U R/                  U'5      n(U%R1                  U(5        U&R1                  U(5        MI     U R                  R3                  5       n)U#R5                  S5      U)l        SU)l        SU)l        U R                  R=                  5       n*U*c  [?        S	5      e U R                  R@                  [C        U%5      -  " U%6 n+U R                  RE                  U R                  U*[F        RH                  " U)5      U+[C        U%5      5      n,U,S
:w  a  [?        SU, 35      eURJ                  " 5         URL                  RO                  5         [P        RR                  " S
5      n-U R                  RU                  U*5      n.[W        U.5       GH  n/U R                  RY                  U*U/5      n0U0c  M%  U R                  R[                  U05      n1U1U R                  R\                  :X  Ga   [F        R^                  " 5       n2U R                  Ra                  U0[F        RH                  " U25      5      n3U3(       a  U2Rb                  S
:  a  [W        U2Rb                  5       V4s/ s H  n4U3U4   PM
     n5n4URd                  [C        U55      -   URf                  " 5       :  a6  [?        SURd                  [C        U55      -    SURf                  " 5        35      eURh                  " U55        GMU  GMX  GM[  U1U R                  Rj                  U R                  Rl                  4;   d  GM  U R                  Ro                  U05      n6URd                  U6-   URf                  " 5       :  a-  [?        SURd                  U6-    SURf                  " 5        35      e[P        RR                  " S
5      n7U R                  Rq                  U R                  URL                  Rr                  U0[P        RR                  " URd                  5      [P        Rt                  " S
5      URv                  S[F        RH                  " U75      5      n,U,S
:w  a  [?        SU, 35      eU7Rb                  Ul2        GM     URx                  S URd                   R{                  5       n8U R                  R}                  U*5         U& H  n(U R                  R                  U(5        M      Ub  US   S:X  a  [        U5      nUb  U V9s/ s H  n9SU9S.PM
     nn9UbH  [        U[        5      (       a  US:X  d  US:X  a  Un[        U[        5      (       a  SU;   a
  SSUS   0S.nS n:Ub  [        U[        5      (       ax  Ubu  US   S   m?[        U?4S jU 5       S 5      n:U:c  [?        ST? S35      eU:S   S   n; [        R                  R                  [        R                  " U;5      UR$                  S9nUR                  " S30 SU8_SU_SU_SU	_S U
_S!U_S"U(       a  UOS _S#U_S$U_S%U_S&U_S'U_S(U_S)U_S*U_S+U_S,U_S-U_S.U_S/U_S0U_S1U_6n=U:b  U:S   S   n>[        U>U=U5      $ [        U=US29$ s  sn4f ! U R                  R}                  U*5        f = f! U& H  n(U R                  R                  U(5        M      f = fs  sn9f ! [         as  n<UR$                  (       a!  ['        [        U<5      [(        R*                  S9  [        R                  R                  [        R                  UR$                  S9n S n<A<GNHS n<A<ff = f)4NrO  rd  r   TrM  r  )rD   r   r   r   r  zFailed to create input chunksr   z%Failed to tokenize input: error code zPrompt exceeds n_ctx: z > Fz%Failed to evaluate chunk: error code r   r  r   r  r  r  rn   c              3  B   >#    U  H  oS    S   T:X  d  M  Uv   M     g7fr  rA   r  s     rF   r  .Llava15ChatHandler.__call__.<locals>.<genexpr>  r  r  r  r  r  r  r   r(   r)   r*   r5   r6   r=   r+   r,   r-   r/   r0   r1   r2   r7   r8   r9   r:   r3   r;   r<   r4   r  rA   )Or  r  re  r  rP  rK  get_image_urlsr   r   CHAT_FORMATr  mtmd_default_markerdecoder   
detokenize	token_eos	token_bosr  r  r,  r-  r.  r  r  rg  mtmd_input_textr!  r   add_specialparse_specialmtmd_input_chunks_initrm   mtmd_bitmap_p_ctypesrF  mtmd_tokenizer  byrefreset_ctxkv_cache_clear	llama_cpp	llama_posmtmd_input_chunks_sizer  mtmd_input_chunks_getmtmd_input_chunk_get_typeMTMD_INPUT_CHUNK_TYPE_TEXTc_size_t mtmd_input_chunk_get_tokens_textvaluen_tokensn_ctxevalMTMD_INPUT_CHUNK_TYPE_IMAGEMTMD_INPUT_CHUNK_TYPE_AUDIOmtmd_input_chunk_get_n_tokensmtmd_helper_eval_chunk_singlectxllama_seq_idn_batch	input_idstolistmtmd_input_chunks_freemtmd_bitmap_freer#  r"  r~   r$  r%  r&  r'  r(  r)  r*  r+  r/  r0  r  r   )@rB   rC   rD   r$   r%   r&   r'   r(   r)   r*   r5   r6   r+   r,   r-   r.   r/   r0   r1   r2   r7   r8   r9   r:   r3   r;   r<   r4   r=   r>   rE   system_prompt
image_urlsr   media_markerr   r  bitmapsbitmap_cleanupr  r  
input_textr   bitmap_arrayr1  n_pastn_chunksr   r   
chunk_typen_tokens_out
tokens_ptrjr   chunk_n_tokens
new_n_pastr   r   r3  r4  r5  r   r   rn   s@                                                                  @rF   rG   Llava15ChatHandler.__call__
  sC   P 	&}}(((+H5B4#>#>#J>>!4+F+F 	H ((2
0
 +d&&
' 	 ~~99;BB7K "&&&(9':;&&(9':;	  
 $I<<	<8D $ <<$SZZ( d	8'	"ooi877Dv&%%f-	 ( 779J"kk'2JO%)J"'+J$ ^^::<F~ !@AAM> $ C Cc'l RU\]55MMLL, L Q;$'LVH%UVV 

))+ #,,Q/>>@@HxA NN@@KE} !%!I!I%!PJ!T^^%N%NN'-'8%)^^%T%T!6<<#=&
 &,*<*<q*@=B<CUCU=V%W=Vjm=VF%W$~~F;ekkmK&0&<U^^cRXk=Y<ZZ]^c^i^i^k]l$m'" !" "JJv. +A: $(R(RTXTbTbT~T~')-)U)UV[)\ >>N:U[[]J","8.9X8YY\]b]h]h]j\k l#  &/%8%8%;
!%!M!M MM!JJNN!%//?%2215!MM!"LL4	" "Q;",/TU[T\-]"^^ *4)9)9c )h )95>>:AAC 55f= )//7 ) &?6+Bm+S2?CG   !*
 !*H ' ( !*   $---'=F+B+-..6]3J&f 5! #;--!z*62DKEKTRD| =6K!LMM*%l3F
'44EEJJv& F   %66  
 
# 
  
 	 

  
   
 &.\4 
  
  
  
 " 
 . 
 0 
 * 
  
  (! 
" &# 
$ &% 
& ' 
( .) 
* + 
, "- 
2 Z(0I7/  ++?OO &XN 55f= )//7 )L  ==#a&szz2'44@@!++U]] A s_   B3_ F4^2 ^-B,^2 E!^2 $_ _;4<`  -^2 2__ &_8 
a=
A(a88a=c                   U R                  S5      (       a)  SS KnUR                  U R                  S5      S   5      nU$ SS KnUR
                  R                  U 5       nUR                  5       nUsS S S 5        $ ! , (       d  f       g = f)Nzdata:r   ,r   )r  base64	b64decoder  urllib.requestrequesturlopenread)r  r  r  urllibr   s        rF   r  Llava15ChatHandler._load_image  sm     (( **9??3+?+BCK!''	2affh" 322s   A;;
B	c                J   / nU  H  nUS   S:X  d  M  US   c  M  US    H{  n[        U[        5      (       d  M  SU;   d  M"  US   S:X  d  M-  [        US   [        5      (       a"  SUS   ;   a  UR                  US   S   5        Mg  UR                  US   5        M}     M     U$ )Nr   r  r   r   r  url)r"  r$  rg  )rD   r  r   r   s       rF   r  !Llava15ChatHandler.get_image_urls  s     "
Gv&(9%-&y1G!'400Vw5F"6?k9 *7;+? F F$)W[-A$A * 1 1'+2Fu2M N * 1 1'+2F G  2	   rI   c                
   SS jn/ nU nU(       ar  U" XA5      u  pVUbG  UbD  US:  a  UR                  SUSU 45        UR                  SX   45        XE[        X   5      -   S nOUR                  SU45        SnU(       a  Mr  U$ )z8This method is no longer used in the new implementation.c                d    [        U5       H!  u  p#U R                  U5      nUS:w  d  M  XB4s  $    g)Nr   rX  )r   find)ssubstrsr   substrposs        rF   
find_first?Llava15ChatHandler.split_text_on_image_urls.<locals>.find_first  s3    &w/	ffVn"96M 0 rI   Nr   r   r  rO  )r$  r~   r%  	List[str])rg  rF  )r   r  r(  
split_text	remainingr'  r   s          rF   split_text_on_image_urls+Llava15ChatHandler.split_text_on_image_urls  s    	 FH
		6FC1=7%%vy#&?@!!;
">?%C
,>&>&@A	!!69"56	 i rI   c                .   SS K nSSKJn   SSKJn	Jn
  SSKJn  U" U5        U
" 5       nUR                  U5       Vs/ s H  n[        U[        5      (       a  US   OUPM!     nn/ nU H4  nU" U5      R                  U5      nUR                  [        U5      5        M6     U Vs/ s H  oR                  X5      (       d  M  UPM     nn[        U5      S:X  a(  [!        SU SU S	["        R$                  " U5       35      e[        U5      S
:  a(  [!        SU SU S	["        R$                  " U5       35      eUu  n[        U" U5      R&                  5      nU" U5      R(                  nU	" UUU[+        [,        [        US 4   U5      U[+        [,        [        US 4   U5      S9  Uc%  U	" UUUUU[+        [,        [        US 4   U5      SS9nO[.        R0                  R3                  X25      nU " SSU0UD6$ ! [         a    [        S5      ef = fs  snf s  snf )Nr   )Path)hf_hub_downloadHfFileSystem)validate_repo_idzrLlama.from_pretrained requires the huggingface-hub package. You can install it with `pip install huggingface-hub`.rn   zNo file found in z that match z

Available Files:
r   zMultiple files found in z
 matching )repo_idfilename	subfolder	local_dirlocal_dir_use_symlinks	cache_dirT)r4  r5  r6  r7  r8  r9  local_files_onlyr  rA   )fnmatchpathlibr0  huggingface_hubr1  r2  huggingface_hub.utilsr3  ImportErrorlsr"  r$  relative_torg  r~   rF  rm   r)  r*  parentrn   r   r   r  r  r  )clsr4  r5  r7  r8  r9  rE   r;  r0  r1  r2  r3  hffsr  files	file_listrel_pathmatching_filesmatching_filer6  
model_paths                        rF   rF  "Llava15ChatHandler.from_pretrained  sH    	 	E> 	!~ (
( 'tT22DL<( 	 
  "	DDz--g6HS]+  ,5X948W$9X~!##G9L
 C%%)ZZ	%:$;= 
 ~"*7):hZ H%%)ZZ%6$79 
 *]+223	&++ 	5dD19=#95dD19=	
 (!##'=uS$_5yA!%J i:J 
&

 	
  	I 	
 Ys   G4 &H$HH4H
)r  r  r  r  r  T)r  r~   r  rR   )r  rJ   )r  r~   r[   r   )r  r   r9  )rD   rK   )r   r~   r  r*  )Nr  N)r4  r~   r5  rV   r7  &Optional[Union[str, os.PathLike[str]]]r8  zUnion[bool, Literal['auto']]r9  rM  rE   r   r[   z'Llava15ChatHandler')r^   r_   r`   ra   r  r   r  r   r  r  r  rG   r   r  r  r-  classmethodrF  rc   rA   rI   rF   r  r  c
  s    	g M 
	 F
S!1F+. IMQU@DLP 02" $("%#& #!!#@D0415#'&*CEP EP A	EP
 FEP OEP >EP JEP EP EP EP EP EP EP .EP  !EP"
#EP( ")EP*  +EP, !-EP. /EP0 1EP2 3EP4 5EP6 7EP8 9EP: >;EP< .=EP> /?EP@ !AEPB $CEPF
GEPN 
# 
#  $  0 
 =A?E<@Q
Q
  Q
 :	Q

 !=Q
 :Q
 Q
 
Q
 Q
rI   r  c                      \ rS rSrSrSrg)ObsidianChatHandlerid  a<  {% for message in messages %}{% if message.role == 'system' %}<|im_start|>system
{{ message.content }}
###
{% endif %}{% if message.role == 'user' %}<|im_start|>user
{% if message.content is string %}{{ message.content }}{% endif %}{% if message.content is iterable %}{% for content in message.content %}{% if content.type == 'image_url' and content.image_url is string %}{{ content.image_url }}{% endif %}{% if content.type == 'image_url' and content.image_url is mapping %}{{ content.image_url.url }}{% endif %}{% endfor %}{% for content in message.content %}{% if content.type == 'text' %}{{ content.text }}{% endif %}{% endfor %}{% endif %}###
{% endif %}{% if message.role == 'assistant' %}<|im_start|>assistant
{{ message.content }}###
{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant
{% endif %}rA   Nr^   r_   r`   ra   r  rc   rA   rI   rF   rP  rP  d  s    (	 rI   rP  c                      \ rS rSrSrSrg)MoondreamChatHandleri  a  {% for message in messages %}{% if message.role == 'user' %}{% if message.content is iterable %}{% for content in message.content %}{% if content.type == 'image_url' %}{% if content.image_url is string %}{{ content.image_url }}

{% endif %}{% if content.image_url is mapping %}{{ content.image_url.url }}

{% endif %}{% endif %}{% endfor %}{% for content in message.content %}{% if content.type == 'text' %}Question: {{ content.text }}

{% endif %}{% endfor %}{% endif %}{% if message.content is string %}Question: {{ message.content }}

{% endif %}{% endif %}{% if message.role == 'assistant' %}Answer:{{ message.content }}

{% endif %}{% endfor %}{% if add_generation_prompt %}Answer:{% endif %}rA   NrQ  rA   rI   rF   rS  rS    s    "	 rI   rS  c                      \ rS rSrSrSrSrg)Llava16ChatHandleri  zA chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions. a  {% for message in messages %}{% if message.role == 'system' %}{{ message.content }}{% endif %}{% if message.role == 'user' %}{% if message.content is iterable %}{% for content in message.content %}{% if content.type == 'image_url' %}{% if content.image_url is string %}{{ content.image_url }}
{% endif %}{% if content.image_url is mapping %}{{ content.image_url.url }}
{% endif %}{% endif %}{% endfor %}{% for content in message.content %}{% if content.type == 'text' %}{{ content.text }}{% endif %}{% endfor %}{% endif %}{% if message.content is string %}{{ message.content }}{% endif %}{% endif %}{% if message.role == 'assistant' %}{{ message.content }}{% endif %}{% endfor %}{% if add_generation_prompt %}Answer:{% endif %}rA   Nr^   r_   r`   ra   r  r  rc   rA   rI   rF   rU  rU    s     }%	 rI   rU  c                      \ rS rSrSrSrSrg)NanoLlavaChatHandleri  zAnswer the questionaM  {% for message in messages %}{% if message.role == 'system' %}<|im_start|>system
{{ message.content }}<|im_end|>{% endif %}{% if message.role == 'user' %}<|im_start|>user
{% if message.content is string %}{{ message.content }}{% endif %}{% if message.content is iterable %}{% for content in message.content %}{% if content.type == 'image_url' and content.image_url is string %}{{ content.image_url }}{% endif %}{% if content.type == 'image_url' and content.image_url is mapping %}{{ content.image_url.url }}{% endif %}{% endfor %}{% for content in message.content %}{% if content.type == 'text' %}{{ content.text }}{% endif %}{% endfor %}{% endif %}<|im_end|>{% endif %}{% if message.role == 'assistant' %}<|im_start|>assistant
{{ message.content }}<|im_end|>{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant
{% endif %}rA   NrV  rA   rI   rF   rX  rX    s     3(	 rI   rX  c                      \ rS rSrSrSrSrg)Llama3VisionAlphaChatHandleri-  Na  {% for message in messages %}<|start_header_id|>{% if message.role == 'user' %}user<|end_header_id|>

{% if message.content is iterable %}{% for content in message.content %}{% if content.type == 'image_url' %}{% if content.image_url is string %}{{ content.image_url }}{% endif %}{% if content.image_url is mapping %}{{ content.image_url.url }}{% endif %}{% endif %}{% endfor %}{% for content in message.content %}{% if content.type == 'text' %}{{ content.text }}{% endif %}{% endfor %}{% endif %}{% if message.content is string %}{{ message.content }}{% endif %}{% endif %}{% if message.role == 'assistant' %}assistant<|end_header_id|>

{{ message.content }}{% endif %}<|eot_id|>{% endfor %}{% if add_generation_prompt %}<|start_header_id|>assistant<|end_header_id|>

{% endif %}rA   rV  rA   rI   rF   rZ  rZ  -  s     "&	 rI   rZ  c                      \ rS rSrSrSrSrg)MiniCPMv26ChatHandlerib  r  a  {% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}<|im_start|>system
You are a helpful assistant.<|im_end|>
{% endif %}<|im_start|>{{ message['role'] }}
{% if message['content'] is iterable %}{% for content in message['content'] %}{% if content.type == 'image_url' %}{% if content.image_url is string %}{{ content.image_url }}{% endif %}{% if content.image_url is mapping %}{{ content.image_url.url }}{% endif %}{% endif %}{% endfor %}{% for content in message['content'] %}{% if content.type == 'text' %}{{ content.text }}{% endif %}{% endfor %}{% endif %}{% if message['content'] is string %}{{ message['content'] }}{% endif %}<|im_end|>
{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant
{% endif %}rA   NrV  rA   rI   rF   r\  r\  b  s    ;	 rI   r\  c                  0   ^  \ rS rSrSrSrU 4S jrSrU =r$ )Qwen25VLChatHandleri  r  aO  {% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system
{{ self.DEFAULT_SYSTEM_MESSAGE }}<|im_end|>
{% endif %}<|im_start|>{{ message['role'] }}
{% if message['content'] is string %}{{ message['content'] }}<|im_end|>
{% else %}{% for content in message['content'] %}{% if content['type'] == 'image_url' %}{% if content.image_url is string %}{{ content.image_url }}{% else %}{{ content.image_url.url }}{% endif %}{% elif content['type'] == 'text' %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>
{% endif %}{% endfor %}<|im_start|>assistant
c                  > US   nUR                   " 5         UR                  R                  5         SUl        [	        US5      (       a  UR
                  R                  S5        [	        U S5      (       a  S U l        S U l        U R                  (       aH  UR                  S/ 5      n[        U R                  U5      5      n[        SU S3[        R                  S9  [         TU ]D  " S	0 UD6$ )
NrC   r   r   _last_image_embedrD   z$Minimal - Cleared state, processing z imagesr  rA   )r  r  r  r  r  r   fillr`  _last_image_hashr  r  rF  r  r,  r-  r.  superrG   )rB   rE   rC   rD   image_count	__class__s        rF   rG   Qwen25VLChatHandler.__call__  s    w 	

!!#5+&&OO  # 4,--%)D"$(D!<<zz*b1Hd11(;<K8WMTWT^T^_ w)&))rI   )r`  rb  )	r^   r_   r`   ra   r  r  rG   rc   __classcell__)re  s   @rF   r^  r^    s    ;
	" <* *rI   r^  zchatml-function-callingc                F  ^- Sn[        [        R                  " SS/5      [        R                  S9R	                  U5      nUb  U Vs/ s H  nSUS.PM
     nnUbH  [        U[        5      (       a  US:X  d  US:X  a  Un[        U[        5      (       a  S	U;   a
  SS	US	   0S.n[        U[        5      (       a  US
/OU(       a  US
/-   OS
/nUb-  [        U[        5      (       a  US:X  d  Ub  [        U5      S:X  a  UR                  U/ S SS9nUb  US   S:X  a  [        U5      n[        U R                  " SO0 SU_SU_SU_SU_SU	_SU
_SU_SU_SU_SU_SU_SU_SU_SU_SU_SU_S U_S!U_S"U_S#U(       a  UOS _6US$9$ [        U[        5      (       a  US   S	   m-[        U-4S% jU 5       S 5      n U c  [        S&T- S'35      eUR                  UUSSS9nUS(T- S)3-  n [        R                   R#                  [$        R&                  " U S   S*   5      U R(                  S+9nU R                  " SO0 SU_SU_SU_SU_SU	_SU
_SU_SU_SU_SU_SU_SU_SU_SU_SU_SU_S U_S!U_S"U_6n"[1        T-U"U5      $ [        U[        5      (       a  US:X  d   eS-R3                  U V s/ s H  n S.U S   S	    S/3PM     sn 5      n#S0U# S13n$S2U# S13n%UR                  UUSSS9nU R                  " SO0 SU_SS_SU_SU_SU	_SU
_SS3_SS4/_SS _SU_SU_SU_SU_SU_SU_SU_S U_S!U_S"[        R                   R	                  U$U R(                  S+9_6n"U"n&U&S5   S   S6   n'S7U';   a  [        U R                  " SO0 SUS8-   _SU_SU_SU_SU	_SU
_SU_SS
/_S#U(       a  UOS _SS _SU_SU_SU_SU_SU_SU_SU_S U_S!U_S"[        R                   R	                  U%U R(                  S+9_6US$9$ U'[        S(5      S  m-[        U-4S9 jU 5       S 5      n U(       Gd  / n(/ n)U Gb  US(T- S)3-  n [        R                   R#                  [$        R&                  " U S   S*   5      U R(                  S+9nU R                  " SO0 SU_SU_SU_SU_SU	_SU
_SS3_SU_SS _SU_SU_SU_SU_SU_SU_SU_S U_S!U_S"U_6n"[5        [6        R8                  U"5      n"U(R;                  U"5        U)R;                  T-5        UU"S5   S   S6   -  nUS1-  nU R                  " SO0 SU_SU_SU_SU_SU	_SU
_SS3_SU_SS _SU_SU_SU_SU_SU_SU_SU_S U_S!U_S"[        R                   R	                  U%U R(                  S+9_6n*[5        [6        R8                  U*5      n*U*S5   S   S6   [        S(5      S  m-[        U-4S: jU 5       S 5      n U b  GM  [        U(5      S;:X  a  S<T-U(S   S5   S   S6   S=.0O0 n+S>U&S?   -   S@U&SA   U&S    SBS[=        U&S5   S   S#   5      SCS [?        [A        U)U(5      5       V,V-V&s/ s H.  u  n,u  n-n&SDSEU, SE3-   U--   SE-   U&S?   -   SU-U&S5   S   S6   S=.SF.PM0     sn&n-n,SG.U+ESH./[C        SI U( 5       5      [C        SJ U( 5       5      [C        SK U( 5       5      SL.SM.$ [        SN5      es  snf ! [*         ah  n![        R                   R	                  [        R,                  U R(                  S+9nU R(                  (       a  [/        S,5        [/        U!5         S n!A!GNS n!A!ff = fs  sn f ! [*         ah  n![        R                   R	                  [        R,                  U R(                  S+9nU R(                  (       a  [/        S,5        [/        U!5         S n!A!GN'S n!A!ff = fs  sn&n-n,f )PNa  {% for message in messages %}<|im_start|>{{ message.role }}
{% if message.role == 'system' %}{{ message.content }}{% if tool_calls %}

You have access to the following functions:
{% for tool in tools %}
functions.{{ tool.function.name }}:
{{ tool.function.parameters | tojson }}
{% endfor %}

You can respond to users messages with either a single message or one or more function calls.

To respond with a message begin the message with 'message:', use the following format:

message:
<message>

To respond with one or more function calls begin the message with 'functions.<function_name>:', use the following format:

functions.<function_name>:
{ "arg1": "value1", "arg2": "value2" }
functions.<function_name>:
{ "arg1": "value1", "arg2": "value2" }{% endif %}<|im_end|>
{% endif %}{% if message.role == 'user' %}{{ message.content }}<|im_end|>
{% endif %}{% if message.role == 'assistant' %}{% if message.content and message.content | length > 0 %}{% if tool_calls %}message:
{% endif %}{{ message.content }}<|im_end|>
{% endif %}{% if 'tool_calls' in message %}{% for tool_call in message.tool_calls %}functions.{{ tool_call.function.name }}:
{{ tool_call.function.arguments }}{% endfor %}<|im_end|>
{% endif %}{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant
{% endif %}htmlxml)
autoescape	undefinedr   r  r  r  rn   r   r   T)rD   r&   r   r   r   r  r   r(   r)   r*   r5   r6   r+   r,   r/   r0   r1   r2   r7   r8   r9   r:   r3   r;   r<   r=   r  c              3  B   >#    U  H  oS    S   T:X  d  M  Uv   M     g7fr  rA   r  r3  r   s     rF   r  *chatml_function_calling.<locals>.<genexpr>i  s"     MedJ'7'?9'LTTer  zTool with name 'z' not found in toolsrA  rC  r  r  rS  r  z"functions.z:"z0root   ::= functions | "message:"
functions ::= r  z2root   ::= functions | "<|im_end|>"
functions ::= Frx  r   r   r   z	message:
c              3  B   >#    U  H  oS    S   T:X  d  M  Uv   M     g7fr  rA   rn  s     rF   r  ro    "     Q%$
+;F+Cy+P%r  c              3  B   >#    U  H  oS    S   T:X  d  M  Uv   M     g7fr  rA   rn  s     rF   r  ro  0  rq  r  r   r%   r   r   r   r   r   r   r   rz  r   r   )r   r   r   )r   r   r=   r   c              3  B   #    U  H  nS U;   a  US    S   OSv   M     g7f)r   r  r   NrA   r  r   s     rF   r  ro  g  s8      ) '2
 #j0 #7+,?@ '2   c              3  B   #    U  H  nS U;   a  US    S   OSv   M     g7f)r   prompt_tokensr   NrA   rt  s     rF   r  ro  o  s/      %&1
 =Dz<QJw'8WXX&1ru  c              3  B   #    U  H  nS U;   a  US    S   OSv   M     g7f)r   total_tokensr   NrA   rt  s     rF   r  ro  s  s/      $&1
 <Cj;PJw'7VWW&1ru  )r  rw  ry  r   z0Automatic streaming tool choice is not supportedrA   )"r   r   select_autoescapeStrictUndefinedr   r"  r~   r$  rF  r   r#  r   r0  r%  rm   r&  r'  r(  r)  r*  r  r+  r/  r,  r  r  r   rP  CreateCompletionResponserg  r   r   r   sum).rC   rD   r$   r%   r&   r'   r(   r)   r*   r5   r6   r+   r,   r.   r/   r0   r1   r2   r7   r8   r9   r:   r3   r;   r<   r=   r>   rE   function_calling_templatetemplate_rendererr   r   r3  r5  r   function_namesinitial_gbnf_tool_grammarfollow_up_gbnf_tool_grammarr   r   completionscompletions_tool_nameresponser  r   r   s.                                                `rF   chatml_function_callingr    s   F0	K f 6++VUO<(( k+,   &

 & #$ & 	 
  mS))V#}'>'KmT**v/F"M&1K dC   
|&*T\N" 	 	{C(([F-B=u:?"))"&	 * 
 &?6+Bm+S2?CG*## '  	
  $   & "2 #4  .  , *  *!" #$ "2%&  '( *2t), /
 	
6 +t$$
+F3	MeMt
 </	{:NOPP"))"&	 * 
 	Jyk--	#00AA

4
+L9:EMM B G  %66  
 
# 
  
 	 

  
   
  
  
 " 
 . 
 0 
 * 
  
 ( 
 & 
  &! 
" # 
$ .% 
& ' 
* 4+V
 	

 k3''K6,AAAZZDIJED[j)&12"	7EJN	)*"	0 
	)*"	0   %%"	 & F !22   	
    U  * , &  $ "  "!" #$ *%& **66%u}} 7 
'. 8LJi #F+DD*## ,'  	
  $  #^ *2t   "2 #4  .  ,  *!" *#$ %& "2'( &22>>/ ? )0 3
 	
: S&()IQ%QSWXDBD+-
9+S11F'44EEJJtJ/=> F  $)#:#: $$'$ $ 	$
 $ $$ $ $  $ "2$ #4$  .$ $ ,$ *$  *!$" #$$ "2%$&  '$ * $(446J$  34!((3*95a8@@FdNF.. '  	
  $     "2 #4  .  , *  *!" #$ "2%& &22>>/ ? 'H. K@@(KH +A.v6s<7H7JKIQ%QSWDM p ;1$  %!,Q	!:1!=f!E"  	" :d++'!),( &2 I*U^J_`aJbcmJn o +#' ?H #$9; G?'? :#:Iz '.$%aS('+"+', #&'& #-T"2	'3
 )3,51;I1Fq1I&1Q-"?' ( -) 	< &) ) '2) & "% %&1% " !$ $&1$ !E4
 4	
l G
HHy

t  	#00<<'' = G }}c a	J 	Kd  '44@@!++U]] A  ==g !HD'sF   Z($AZ- (\"+A\' %5^-
\7A\\'
^1A^^r   r   )r=   z(Optional[llama_types.CompletionLogprobs]r[   z"llama_types.ChatCompletionLogprobs)r   zllama_types.Completionr[   zllama_types.ChatCompletion)r   r  r[   z)Iterator[llama_types.ChatCompletionChunk]r}   )r   aUnion[llama_types.CreateCompletionResponse, Iterator[llama_types.CreateCompletionStreamResponse]]r+   rR   r[   zZUnion[llama_types.CreateChatCompletionResponse, Iterator[llama_types.ChatCompletionChunk]])r   r~   r   r  r+   rR   )r6  r   r[   r   )rG  Union[str, os.PathLike[str]]r[   r   )rG  r  r[   r   rL  )rU  Dict[str, Any]r   rR   r[   r   )rU  r  r   rR   r[   r   )ra  Dict[str, str]r[   rV   )rD   rK   r[   r~   )rD   rK   rh  r  r[   List[Tuple[str, Optional[str]]])
ro  r~   rD   r  rp  r~   rq  r~   r[   r~   )ro  r~   rD   r  rp  r~   r[   r~   )r  rR   )FT)r4  r~   r  rR   r  rR   )r.   z/llama_types.ChatCompletionRequestResponseFormatr  rR   r   )rD   z.list[llama_types.ChatCompletionRequestMessage]rE   r   r[   r   )4rC   rJ   rD   rK   r$   rL   r%   rM   r&   rN   r'   rO   r(   rP   r)   rP   r*   rQ   r5   rP   r6   rP   r+   rR   r,   rS   r.   rU   r/   rT   r0   rP   r1   rP   r2   rP   r7   rP   r8   rQ   r9   rP   r:   rP   r3   rV   r;   rX   r<   rY   r[   zLUnion[llama_types.ChatCompletion, Iterator[llama_types.ChatCompletionChunk]])8rC   rJ   rD   rK   r$   rL   r%   rM   r&   rN   r'   rO   r(   rP   r)   rP   r*   rQ   r5   rP   r6   rP   r+   rR   r,   rS   r.   rU   r/   rT   r0   rP   r1   rP   r2   rP   r7   rP   r8   rQ   r9   rP   r:   rP   r3   rV   r;   rX   r<   rY   r=   rZ   r>   rT   r[   r\   )x
__future__r   r  r-  r)  r  dataclassesr  r  r   
contextlibr   typingr   r   r   r	   r
   r   r   r   r   r   r   jinja2.sandboxr   numpynpnumpy.typingnptllama_cpp.llama_cppr  llama_cpp.llamarC   llama_cpp.llama_typesrP  llama_cpp.llama_grammarr&  _loggerr   _utilsr   r   r]  CHATML_BOS_TOKENCHATML_EOS_TOKENr^  MISTRAL_INSTRUCT_BOS_TOKENMISTRAL_INSTRUCT_EOS_TOKENr_  r`  r   r+  re   rh   r   rq   	dataclassr   r   r   r   r   r   r   r  r   rH  rJ  rV  rX  rb  re  rj  ru  rz  r|  r~  r  r  r  r  r  r#  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  ra  r  r  rP  rS  rU  rX  rZ  Llama3VisionAlphar\  r^  r  rA   rI   rF   <module>r     s   " 	 
            8   '  + /  5
 a    "A " #  "z  !l 
0 0f	) 	 B 
  
  
 $H $H?- H?V6'2&0(
@(
.(
` <<
 <<"n;n;n; n;bR#!R#R#j #?  2E#?EE #'-#$-#-# -#d #'E$EE  E.<< % #BILTW"

#B
IL

#BILTW

#B
IL



#B
IL



#B
IL

#BIL BF			:>	 2D22$ i 1<11 1 !1  i <<<< < !<  h
1<
1
1 
1  
1 f=<== = =  h1<11 1  1 m$1<11 1 %1 l#1<11 1 $1 j!1<11 1 "1 k"1<11 1 #1* ()=<== = *= h=<== =  =* g
1<
1
1 
1 
1 g
1<
1
1 
1 
1 k"@<@@ @ #@4 m$1<11 1 %1 h<<<< <  <  k"<<<< < #< h<<<< <  <  ();<;; ; *;( j!<<<< < "<  j!<<<< < "<& g9<99 9 9* g<<<< < <( "-0 EIMQ<@HL,.QU $!"<@,03bb<b Bb K	b
 :b Fb b b b b b b *b Ob b  !b" #b$ %b& 'b( )b* +b, -b. /b0 :1b2 *3b6 R7b 1bJ ""23!"23 EIMQ<@HL,.QU $!"<@,03

<
 B
 K	

 :
 F
 
 
 
 
 
 
 *
 O
 
  !
" #
$ %
& '
( )
* +
, -
. /
0 :1
2 *3
6 R7
 4 4
D~
 ~
B5, 5p'- 'T-+ -`4- 4n.#5 .d 1 #. #L7*, 7*t "";< EIMQ<@HL,.QU $!"<@,0#"&7wIwI<wI BwI K	wI
 :wI FwI wI wI wI wI wI wI *wI OwI wI  !wI" #wI$ %wI& 'wI( )wI* +wI, -wI. /wI0 :1wI2 *3wI4 5wI6  7wI:;wI =wIrI   