
    biw`                     $   d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlmZ d dl	m
Z
mZ d dlmZmZ d dlZd dlZd dlZd dlmZmZ d dlmZ d dlmZ 	 d dlZn# e$ r Y nw xY w ej                    dk    rd dlZ e            rd d	lmZ d d
lm Z  d dl!m"Z" dddZ# e$ej%        ej&        z             Z' e$ej%        ej(        z   ej&        z   dz             Z)ddiddiddiddiddiddiddidZ*dZ+dd,                    e*-                                           dZ. G d d          Z/ G d d           Z0d!e1dz  d"efd#Z2d$e3e1         dz  d"e4fd%Z5d0d&e1dz  d"e3e4         fd'Z6d(e1d)e3e4         d*e4d"e1fd+Z7d"e1fd,Z8e9d-k    r e0d./           dS dS )1    N)AsyncIterator)	AnnotatedAny)urljoinurlparse)AsyncInferenceClientChatCompletionStreamOutput)GenerationConfig)is_rich_availableWindows)Console)Live)Markdown	localhosti@  )hostnameportz .!\"#$%&'()*+,\-/:<=>?@[]^_`{|}~textz5There is a Llama in my lawn, how can I get rid of it?zyWrite a Python function that integrates any Python function f(x) numerically over an arbitrary interval [x_start, x_end].z4How many helicopters can a human eat in one sitting?z4Count to 10 but skip every number ending with an 'e'zWhy aren't birds real?z2Why is it important to eat socks after meditating?z$Which number is larger, 9.9 or 9.11?)llamacode
helicopternumbersbirdssocksnumbers2a  

**TRANSFORMERS CHAT INTERFACE**

Chat interface to try out a model. Besides chatting with the model, here are some basic commands:
- **!help**: shows all available commands (set generation settings, save chat, etc.)
- **!status**: shows the current status of the model and generation settings
- **!clear**: clears the current conversation and starts a new one
- **!exit**: closes the interface
am  

**TRANSFORMERS CHAT INTERFACE HELP**

Full command list:
- **!help**: shows this help message
- **!clear**: clears the current conversation and starts a new one
- **!status**: shows the current status of the model and generation settings
- **!example {NAME}**: loads example named `{NAME}` from the config and uses it as the user input.
Available example names: `z`, `a#  `
- **!set {ARG_1}={VALUE_1} {ARG_2}={VALUE_2}** ...: changes the system prompt or generation settings (multiple
settings are separated by a space). Accepts the same flags and format as the `generate_flags` CLI argument.
If you're a new user, check this basic flag guide: https://huggingface.co/docs/transformers/llm_tutorial#common-options
- **!save {SAVE_NAME} (optional)**: saves the current chat and settings to file by default to
`./chat_history/{MODEL_ID}/chat_{DATETIME}.yaml` or `{SAVE_NAME}` if provided
- **!exit**: closes the interface
c                       e Zd ZdedefdZdee         deeeez  dz  f         fdZ	defdZ
d	 Zd
efdZd
edefdZddededefdZddefdZdefdZdS )RichInterfacemodel_iduser_idc                 H    t                      | _        || _        || _        d S N)r   _consoler   r   )selfr   r   s      P/root/projects/butler/venv/lib/python3.11/site-packages/transformers/cli/chat.py__init__zRichInterface.__init__g   s    		     streamreturnNc                 (  K   | j                             d| j         d           t          | j         d          5 }d}d }| d {V 2 3 d {V }|j        d         j        j        }t          |j        d         d|          }|s=t          j	        dd	|          }||z  }g }|
                                D ]W}|                    |           |                    d
          r|                    d           B|                    d           Xt          d                    |                                          d          }	|                    |	d           6 	 d d d            n# 1 swxY w Y   | j                                          ||fS )Nz[bold blue]<z>:   )consolerefresh_per_second r   finish_reasonz<(/*)(\w*)>z\<\1\2\>z```
z  
zgithub-dark)
code_themeT)refresh)r!   printr   r   choicesdeltacontentgetattrresub
splitlinesappend
startswithr   joinstripupdate)
r"   r&   liver   r-   tokenoutputslineslinemarkdowns
             r#   stream_outputzRichInterface.stream_outputl   s     <4=<<<===$-A>>> (	4$D(,M%+|||||| %4 %4 %4 %4 %4 %4 %4e-*08 'a(8/= Y Y  &gFF  OO-- - -DLL&&&u-- - T****V,,,,#BGGENN$8$8$:$:}UUU Hd3333K  ,|(	4 (	4 (	4 (	4 (	4 (	4 (	4 (	4 (	4 (	4 (	4 (	4 (	4 (	4 (	4T 	]""s   E,	EDE,,E03E0c                 ~    | j                             d| j         d          }| j                                          |S )z!Gets user input from the console.[bold red]<z>:
)r!   inputr   r1   )r"   rG   s     r#   rG   zRichInterface.input   s>    ##$D$,$D$D$DEEr%   c                 8    | j                                          dS )zClears the console.N)r!   clear)r"   s    r#   rI   zRichInterface.clear   s    r%   r   c                     | j                             d| j         d|            | j                                          dS )z%Prints a user message to the console.rF   z>:[/ bold red]
N)r!   r1   r   )r"   r   s     r#   print_user_messagez RichInterface.print_user_message   sE    N$,NNNNOOOr%   colorc                 x    | j                             d| d|            | j                                          dS )z,Prints text in a given color to the console.z[bold ]N)r!   r1   )r"   r   rL   s      r#   print_colorzRichInterface.print_color   sC    3U33T33444r%   Fmessagedefaultc                     |rdnd}| j                             d| d| d          }| j                                          |                                                                }|s|S |dv S )zFDisplays a yes/no prompt to the user, returning True for confirmation.zY/nzy/Nz[bold yellow]z (z): >   yyes)r!   rG   r1   r<   lower)r"   rP   rQ   default_hintresponses        r#   confirmzRichInterface.confirm   s     '2uuU=&&'Sw'S'S,'S'S'STT>>##))++ 	N<''r%   minimalc                     | j                             t          |rt          nt                               | j                                          dS )z'Prints the help message to the console.N)r!   r1   r   HELP_STRING_MINIMALHELP_STRING)r"   rY   s     r#   
print_helpzRichInterface.print_help   sE    HG%T%8%8UUVVVr%   configc                     | j                             d| j         d           | j                             d|            | j                                          dS )zFPrints the status of the model and generation settings to the console.z[bold blue]Model: r.   z[bold blue]N)r!   r1   r   )r"   r^   s     r#   print_statuszRichInterface.print_status   s_    BBBBCCC2&22333r%   )F)__name__
__module____qualname__strr$   r   r	   tupler   rD   rG   rI   rK   rO   boolrX   r]   r
   r`    r%   r#   r   r   f   sI        s    
.#-8R*S .#X]^acfilcloscs^sXt .# .# .# .#`s      s    
 C    

( 
(s 
(T 
(d 
( 
( 
( 
( $    
#3      r%   r   c                      e Zd ZdZded          ded          ddddddfdee ej        d	
          f         deedz   ej        d
          f         dee	e         dz   ej        d
          f         deedz   ej
        d
          f         deedz   ej
        d
          f         dee ej
        d
          f         deedz   ej
        d
          f         deedz   ej
        d
          f         ddfdZed             Zdededeeeeef         f         ded e	e         dee	e         ef         fd!Zd" ZdS )#Chat(Chat with a model from the command line.zhttp://r   :r   Nz./chat_history/r   z9ID of the model to use (e.g. 'HuggingFaceTB/SmolLM3-3B').)helpbase_urlz7Base url to connect to (e.g. http://localhost:8000/v1).generate_flagsa  Flags to pass to `generate`, using a space as a separator between flags. Accepts booleans, numbers, and lists of integers, more advanced parameterization should be set through --generation-config. Example: `transformers chat <base_url> <model_id> max_new_tokens=100 do_sample=False eos_token_id=[1,2]`. If you're a new user, check this basic flag guide: https://huggingface.co/docs/transformers/llm_tutorial#common-optionsuserzKUsername to display in chat interface. Defaults to the current user's name.system_promptzSystem prompt.save_folderzFolder to save chat history.examples_pathz"Path to a yaml file with examples.generation_configzPath to a local generation config file or to a HuggingFace repo containing a `generation_config.json` file. Other generation settings passed as CLI arguments will be applied on top of this generation config.r'   c	                    || _         t          | j                   }	|	j        t          d         k    r0|	j        t          d         k    r|                     | j                    || _        || _        || _        t          |          }
|

                    dd            |
j
        d	i t          |           |
| _        ||| j                                        d| _        ||nt                      | _        |rAt#          |          5 }t%          j        |          | _        ddd           n# 1 swxY w Y   nt*          | _        t-                      st/          d          t1          j        |                                            dS )
rj   r   r   T   )	do_samplemax_new_tokens)rm   r   r^   NzHYou need to install rich to use the chat interface. (`pip install rich`)rg   )rm   r   r   DEFAULT_HTTP_ENDPOINTr   check_healthr   rp   rq   load_generation_configr=   parse_generate_flagsr^   to_dictsettingsget_usernamero   openyaml	safe_loadexamplesDEFAULT_EXAMPLESr   ImportErrorasynciorun
_inner_run)r"   r   rm   rn   ro   rp   rq   rr   rs   parsedr^   fs               r#   r$   zChat.__init__   s   F !$-((?3J???FKShioSpDpDpdm,,, *& ((9::S999==,^<<===%-8t{ObObOdOdee !,DD,..	  	-m$$ 2 $q 1 12 2 2 2 2 2 2 2 2 2 2 2 2 2 2 -DM !"" 	jhiii 	DOO%%&&&&&s   D..D25D2c                     t          | dz   d          }	 t          j        |          }|j        dk    rt	          d|  d|j         d          n&# t          j        $ r t	          d|  d          w xY wd	S )
N/health   zThe server running on z returned status code z on health check (/health).zNo server currently running on z. To run a local server, please run `transformers serve` in aseparate shell. Find more information here: https://huggingface.co/docs/transformers/servingT)r   httpxgetstatus_code
ValueErrorConnectError)url
health_urloutputs      r#   ry   zChat.check_health  s    S3Y11

	Yz**F!S(( wSwwHZwww   ) ! 	 	 	p# p p p  	 ts   :A #A3
user_input	interfacer   r^   chatc                    d}|dk    r*t          | j                  }|                                 n|dk    r|                                 n|                    d          rt          |                                          dk     r|                                }t          |          dk    r|d         n@t          j        	                    | j
        | j        dt          j        d           d	          }t          ||| j        
           |                    d| dd           n|                    d          rr|dd                                         }	|	                                }	|	D ]#}
d|
vr|                    d|
 dd            n$ |j        d"i t'          |	           nB|                    d          rt          |                                          dk    r|                                d         }||v r\|                                 g }|                    ||         d                    |                    d||         d         d           nd| dt-          |                                           d}|                    |d           nN|dk    r|                    |           n1d}|                    d | d!d           |                                 |||fS )#z
        Handles all user commands except for `!exit`. May update the chat history (e.g. reset it) or the
        generation config (e.g. set a new flag).
        T!clear!help!save      chat_%Y-%m-%d_%H-%M-%S.jsonfilenamer   r}   Chat saved to !greenr   rL   !setr)   N=(Invalid flag format, missing `=` after `;`. Please use the format `arg_1=value_1 arg_2=value_2 ...`.red!exampler   ro   roler4   Example * not found in list of available examples: .!statusr^   F'/' is not a valid command. Showing help message.rg   )new_chat_historyrp   rI   r]   r:   lensplitospathr;   rq   r   timestrftime	save_chatr}   rO   r<   r=   r{   rK   r9   listkeysr`   )r"   r   r   r   r^   r   valid_commandsplit_inputr   new_generate_flagsflagexample_nameexample_errors                r#   handle_non_exit_user_commandsz"Chat.handle_non_exit_user_commands$  sp    !!#D$677DOO7""  """"""7++ 1	#J4D4D4F4F0G0G!0K0K$**,,K {##q(( AW\\$"2DMCt4=YlKmKmCtCtCtuu 
 xdT]KKKK!!'C'C'C'C7!SSSS""6** '	# ",ABB!5!5!7!7!3!9!9!;!;* J Jd??))At A A A $ *    E # II 45G H HIII"":.. 	#3z7G7G7I7I3J3Ja3O3O%++--a0Lx''!!!,,Xl-CF-KLLLV8Nv8VWWXXXX p|ooW[\d\i\i\k\kWlWlooo  %%=%FFFF9$$""&"1111 "M!!'f:'f'f'fns!ttt  """]F**r%   c           	      	  K   t          | j        | j                  }|                                 t	          | j                  }|                    d           | j        }t          | j	                  4 d {V }d }	 	 ||}d }|
                    |           n|                                }|dk    rn|dk    r)t	          | j                  }|                                 i|dk    r|                                 |                    d          rt          |                                          d	k     r|                                }t          |          d	k    r|d
         n@t          j                            | j        | j        dt'          j        d           d          }t+          ||| j                   |                    d| dd           b|                    d          rr|dd                                          }	|	                                }	|	D ]#}
d|
vr|                    d|
 dd            n$ |j        d,i t5          |	           |                    d          rt          |                                          d	k    r|                                d
         }|| j        v rf|                                 g }|
                    | j        |         d                    |                    d| j        |         d         d           nd| dt;          | j                                                   d}|                    |d           n||d k    r|                    |!           |                    d          r1|                    d"| d#d           |                                 U|                    d|d           |                     |d| j        |!                                | j        d$%          }|"                    |           d {V \  }}|                    d&|d           |d'k    r/|                    d(d)           |#                    d*          rd+}n# tH          $ r Y nw xY w"	 d d d           d {V  d S # 1 d {V swxY w Y   d S )-N)r   r   T)rY   )rm   z!exitr   r   r   r   r   r   r   r   r   r   r   r   r   r   r)   r   r   r   r   r   r   ro   r   r   r   r   r   r   r   r   )rs   model)r&   r   
extra_body	assistantlengthz2Generation stopped after reaching the token limit.yellowzContinue generating?u'   Please continue. Do not repeat text.”rg   )%r   r   ro   rI   r   rp   r]   r^   r   rm   rK   rG   r:   r   r   r   r   r;   rq   r   r   r   r}   rO   r<   r=   r{   r   r9   r   r   r`   chat_completionto_json_stringrD   rX   KeyboardInterrupt)r"   r   r   r^   clientpending_user_inputr   r   r   r   r   r   r   r&   model_outputr-   s                   r#   r   zChat._inner_runn  sw     !4=$)LLL	 233 	T***'??? g	 g	 g	 g	 g	 g	 g	6-1ed)5%7
-1*!44Z@@@@%.__%6%6
 "W,,#x///0BCC!))) #w..!,,... #..w77 9MC
@P@P@R@R<S<SVW<W<W&0&6&6&8&8  #;//144 (NN!# $ 0$-ArWjIkIkArArAr" " ! "8$WWWW!--3OH3O3O3OW^-___ #..v66 ,M .8^-A-A-C-C*-?-E-E-G-G*$6 V VD"$ ) 5 5)MSW )M )M )M +0 !6 !" !" !" !&  / *FMUU,@AS,T,TUUU #..z:: Ms:CSCSCUCU?V?VZ[?[?['1'7'7'9'9!'<'4=88%OO---#%D%88|9TU[9\]]] KKDMR^D_`fDg(h(hiiii -M|  -M  -Mostx  uB  uG  uG  uI  uI  pJ  pJ  -M  -M  -MM%11}E1RRRR#y00!..f.=== #..s33 M!--!`Z!`!`!`hm .    ",,...  V
$K$KLLL#33#"m171F1F1H1H%)]$ $	 4  F 9B8O8OPV8W8W2W2W2W2W2W2W/L-KK N NOOO$00!--.bdlmmm$,,-CDD %1Z.$(   EIe eg	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	 g	s   >R86R9R8;.R)R8*RR8CR!R8#BR(R8*D$RR8ARR8B9RR8
RR8RR88
SS)ra   rb   rc   __doc__rx   r   rd   typerArgumentr   Optionr$   staticmethodry   r   dictr
   re   r   r   rg   r%   r#   ri   ri      s       22 Z+J7YY:OPV:WYY 
 TXYjhl AD' D'C5p!q!q!qqrD' $J,effff
D' "IEN[  	
D'& $JELkllln
'D'. !t\U\?O-P-P-P!PQ/D'0 sLEL6T$U$U$UUV1D'2 !t\U\?c-d-d-d!de3D'6 %$JEL g  
7D'B 
CD' D' D' D'L   \ H+H+ !H+ sDcN*+	H+
 !H+ 4jH+ 
tDz++	,H+ H+ H+ H+Tq q q q qr%   ri   rs   r'   c                     | t                      S d| v rSt          j                            |           }t          j                            |           }t          j        ||          S t          j        |           S )Nr   )r
   r   r   dirnamebasenamefrom_pretrained)rs   r   r   s      r#   rz   rz     so     !!!###'//"3447##$566/BBB/0ABBBr%   rn   c                    | t          |           dk    ri S d | D             }d |                                D             }d |                                D             }dt          dt          fdfd	|                                D             }d
                    d |                                D                       }d|z   dz   }|                    dd          }|                    dd          }|                    dd          }|                    dd          }|                    dd          }|                    dd          }	 t          j        |          }n"# t          j        $ r t          d          w xY w|S )zUParses the generate flags from the user input into a dictionary of `generate` kwargs.Nr   c                     i | ]=}d |                     d          d         z   d z   |                     d          d         >S )"r   r   r   )r   ).0r   s     r#   
<dictcomp>z(parse_generate_flags.<locals>.<dictcomp>  sC    lllUYcDJJsOOA$66<djjooa>Plllr%   c                 n    i | ]2\  }}||                                 d v r|                                 n|3S ))truefalse)rU   r   kvs      r#   r   z(parse_generate_flags.<locals>.<dictcomp>  sJ       BF!Q		%666177999A  r%   c                 *    i | ]\  }}||d k    rdn|S )Nonenullrg   r   s      r#   r   z(parse_generate_flags.<locals>.<dictcomp>  s*    iii$!Qa1;;Aiiir%   sr'   c                 ~    |                      d          } |                     ddd                                          S )N-r   r,   r   )removeprefixreplaceisdigit)r   s    r#   	is_numberz'parse_generate_flags.<locals>.is_number   s5    NN3yyb!$$,,...r%   c                 >    i | ]\  }}| |          sd | d n|S )r   rg   )r   r   r   r   s      r#   r   z(parse_generate_flags.<locals>.<dictcomp>  s8    pppAa1!DQ1pppr%   z, c                 "    g | ]\  }}| d | S )z: rg   r   s      r#   
<listcomp>z(parse_generate_flags.<locals>.<listcomp>
  s&    &^&^&^tq!!{{q{{&^&^&^r%   {}z"null"r   z"true"r   z"false"r   z"[[z]"rN   r   rk   zFailed to convert `generate_flags` into a valid JSON object.
`generate_flags` = {generate_flags}
Converted JSON string = {generate_flags_string})
r   itemsrd   rf   r;   r   jsonloadsJSONDecodeErrorr   )rn   generate_flags_as_dictgenerate_flags_stringprocessed_generate_flagsr   s       @r#   r{   r{     s   ^!4!4!9!9	
 ml]klll J`JfJfJhJh   jiJ`JfJfJhJhiii/S /T / / / /
 qpppQgQmQmQoQoppp
 !II&^&^?U?[?[?]?]&^&^&^__  "77#= 299(FKK199(FKK199)WMM199$DD199$DD 299#sCC
#':.C#D#D   
 
 
@
 
 	

 $#s   E& &Frp   c                     | rd| dgng S )z Returns a new chat conversation.systemr   rg   )rp   s    r#   r   r   $  s    =JRX-8899PRRr%   r   r   r}   c                 *   t          j        t           j                            |           d           t	          | d          5 }t          j        ||d|d           ddd           n# 1 swxY w Y   t           j                            |           S )z!Saves the chat history to a file.T)exist_okw)r}   chat_historyr)   )indentN)r   makedirsr   r   r   r   dumpabspath)r   r   r}   r   s       r#   r   r   )  s    K))D9999	h		 M	x>>!LLLLM M M M M M M M M M M M M M M7??8$$$s   A++A/2A/c                      t          j                    dk    rt          j                    S t	          j        t          j                              j        S )z)Returns the username of the current user.r   )platformr  r   getloginpwdgetpwuidgetuidpw_namerg   r%   r#   r~   r~   1  s:    I%%{}}|BIKK((00r%   __main__z meta-llama/Llama-3.2-3b-Instruct)r   r    ):r   r   r   r  r6   stringr   collections.abcr   typingr   r   urllib.parser   r   r   r   r   huggingface_hubr   r	   transformersr
   transformers.utilsr   readliner   r  r  rich.consoler   	rich.liver   rich.markdownr   rx   setascii_letters
whitespaceALLOWED_KEY_CHARSdigitsALLOWED_VALUE_CHARSr   r[   r;   r   r\   r   ri   rd   rz   r   r   r{   r   r   r~   ra   rg   r%   r#   <module>r#     s     				  				   ) ) ) ) ) ) ! ! ! ! ! ! ! ! * * * * * * * *    L L L L L L L L ) ) ) ) ) ) 0 0 0 0 0 0	OOOO 	 	 	D	 8?	!!JJJ '$$$$$$&&&&&&%0$?? C,v/@@AA c
6=(6+<<?bb  
 MN) QRNO./JK?@   	  ";;'7'<'<'>'>??  &_ _ _ _ _ _ _ _DW W W W W W W Wt	CcDj 	C=M 	C 	C 	C 	C3$cT)9 3$d 3$ 3$ 3$ 3$lS SC$J S$t* S S S S
% %4: % %# % % % %1c 1 1 1 1 zD4555555 s   A A! A!