
    fThT                        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  S SK J	r	  S SK
JrJrJrJrJrJrJr  S SKJr  SS	KJr  SS
KJrJrJr  \R4                  " \5      r\" 5       (       a  S SKrS SKJr  S SK J!r!  OSr\" 5       (       a  S SK"J#r#  \" 5       (       a  S SK$J%r%  \&\'\(\)\\*" S5      S4r+\RX                  " S\RZ                  5      r.\RX                  " S\RZ                  5      r/\RX                  " S\RZ                  \R`                  -  5      r1\RX                  " S\RZ                  5      r2 " S S\35      r4 " S S\35      r5S\(S\6\(\(4   4S jr7S\(S\64S jr8S\S\64S jr9S\(S\:\\(   \\6   \\(   4   4S  jr;S\S\64S! jr<S" r=\S# 5       r>      S,S$\?\?\6\(\(4         S%\\?\\6\4         S&\\?\6\(\(4         S'\\(   S(\\)   S)\\)   S*\\)   S\(4S+ jjr@g)-    N)contextmanager)datetime)	lru_cache)
isfunction)AnyCallableOptionalUnionget_args
get_originget_type_hints)version   )logging)is_jinja_availableis_torch_availableis_vision_available)	Extension)ImmutableSandboxedEnvironment)Image)Tensor.z(^(.*?)[\n\s]*(Args:|Returns:|Raises:|\Z)z0\n\s*Args:\n\s*(.*?)[\n\s]*(Returns:|Raises:|\Z)a1  
(?:^|\n)  # Match the start of the args block, or a newline
\s*(\w+):\s*  # Capture the argument name and strip spacing
(.*?)\s*  # Capture the argument description, which can span multiple lines, and strip trailing spacing
(?=\n\s*\w+:|\Z)  # Stop when you hit the next argument or the end of the block
z*\n\s*Returns:\n\s*(.*?)[\n\s]*(Raises:|\Z)c                       \ rS rSrSrSrg)TypeHintParsingExceptionB   zJException raised for errors in parsing type hints to generate JSON schemas N__name__
__module____qualname____firstlineno____doc____static_attributes__r       ^/var/www/auris/envauris/lib/python3.13/site-packages/transformers/utils/chat_template_utils.pyr   r   B       Tr#   r   c                       \ rS rSrSrSrg)DocstringParsingExceptionH   zJException raised for errors in parsing docstrings to generate JSON schemasr   Nr   r   r#   r$   r'   r'   H   r%   r#   r'   
param_typereturnc                     [         SS0[        SS0[        SS0[        SS0[	        S 5      SS0[
        0 0n[        5       (       a  SS0U[        '   [        5       (       a  SS0U[        '   UR                  U SS	05      $ )
Ntypeintegernumberstringbooleannullimageaudioobject)intfloatstrboolr,   r   r   r   r   r   get)r)   type_mappings     r$   _get_json_schema_typer;   N   s    fi !fhvy!T
VV$RL %w/U &0VJ(:;;r#   hintc                    [        U 5      n[        U 5      nUc   [        U 5      $ U[
        L d(  [        [        S5      (       a  U[        R                  L a  U Vs/ s H  o3[        S 5      Ld  M  [        U5      PM     nn[        U5      S:X  a  US   nO<[        S U 5       5      (       a!  S[        U Vs/ s H  ofS   PM	     sn5      0nOSU0n[        S 5      U;   a  SUS	'   U$ U[        L a  U(       d  SS
0$ S
[        US   5      S.$ U[        L ar  U(       d  SS
0$ [        U5      S:X  a(  [	        S[!        U 5      R#                  SS5       S35      eSU;   a  [	        S5      eS
U Vs/ s H  n[        U5      PM     snS.$ U[$        L a&  SS0n[        U5      S:X  a  [        US   5      US'   U$ [	        SU 5      e! [         a    [	        SU 5      ef = fs  snf s  snf s  snf )NzGCouldn't parse this type hint, likely due to a custom class or object: 	UnionTyper   r   c              3   H   #    U  H  n[        US    [        5      v   M     g7f)r,   N)
isinstancer7   ).0subtypes     r$   	<genexpr>#_parse_type_hint.<locals>.<genexpr>p   s     JgGFOS11s    "r,   anyOfTnullablearray)r,   itemszThe type hint ztyping. a1   is a Tuple with a single element, which we do not automatically convert to JSON schema as it is rarely necessary. If this input can contain more than one element, we recommend using a List[] type instead, or if it really is a single element, remove the Tuple[] wrapper and just pass the element directly..znConversion of '...' is not supported in Tuple type hints. Use List[] types for variable-length inputs instead.)r,   prefixItemsr4      additionalProperties)r   r   r;   KeyErrorr   r
   hasattrtypesr>   r,   _parse_type_hintlenallsortedlisttupler7   replacedict)r<   originargstsubtypesreturn_dictrB   outs           r$   rP   rP   ^   s   FD>D~	(.. 
5WUK88Vu=V15MA$t*9L'$Q'Mx=A"1+KJJJJ!6(*S(w6?(*S#TUK #H-K:&*K
#	4G$$ $.>tAw.GHH	5G$$t9>* T!2!29b!A B C- -  $;*# 
  d0Sd1A!1Dd0STT	4 x t9>*:47*CC&'

"#lnr
sso  	*Y[_ 	 N +T@ 1Ts#   
G G0G7G"
.G'Gfuncc                    [        U 5      n[        R                  " U 5      n/ nUR                  R	                  5        H  u  pEUR
                  [        R                  R                  :X  a%  [        SUR                   SU R                   35      eUR                  [        R                  R                  :X  d  M|  UR                  U5        M     0 nUR	                  5        H  u  pG[        U5      Xd'   M     SUS.nU(       a  X8S'   U$ )Nz	Argument z$ is missing a type hint in function r4   )r,   
propertiesrequired)r   inspect	signature
parametersrH   
annotation	Parameteremptyr   namer   defaultappendrP   )	r^   
type_hintsrc   ra   
param_nameparamr`   r)   schemas	            r$   "_convert_type_hints_to_json_schemaro      s    %J!!$'IH&11779
w00666*YuzzlBfgkgtgtfu+vww==G--333OOJ'	 : J","2"2"4
!1*!=
 #5 j9F%zMr#   	docstringc           
         [         R                  U 5      n[        R                  U 5      n[        R                  U 5      nU(       a  UR	                  S5      R                  5       OSnU(       a  UR	                  S5      R                  5       OSnU(       a  UR	                  S5      R                  5       OSnUb  SR                  UR                  S5       Vs/ s H  owR                  5       (       d  M  UPM     sn5      n[        R                  U5      nU V	s0 s H/  oS   [        R                  " SSU	S   R                  5       5      _M1     n
n	O0 n
XJU4$ s  snf s  sn	f )z
Parses a Google-style docstring to extract the function description,
argument descriptions, and return description.

Args:
    docstring (str): The docstring to parse.

Returns:
    The function description, arguments, and return description.
r   N
r   z	\s*\n+\s* )description_researchargs_re
returns_regroupstripjoinsplitargs_split_refindallresub)rp   description_match
args_matchreturns_matchdescriptiondocstring_argsreturnslinematchesmatch	args_dicts              r$   parse_google_format_docstringr      s)    '--i8	*J%%i0M 9J#))!,224tK4>Z%%a(..0DN0=m!!!$**,4G !^5I5I$5O#`5OTS]S]S_D5O#`a''7X_`X_u1XrvvlCq9IJJX_	`		7** $a`s   E5E6Ec                     [         R                  " U 5      nU(       d  [        SU R                   S35      eUR	                  5       n[        U5      u  p#n[        U 5      nUS   R                  SS5      =nb  Ub  XFS'   US   R                  5        H  u  pxXs;  a  [        SU R                   SU S35      eX7   n	[        R                  " S	U	[        R                  S
9n
U
(       aq  [        R                  " U
R                  S5      5       Vs/ s H  oR	                  5       PM     snUS'   U
R                  SU
R!                  5        R	                  5       n	XS'   M     U R                  X%S.nUb  XlS'   SUS.$ s  snf )ax  
This function generates a JSON schema for a given function, based on its docstring and type hints. This is
mostly used for passing lists of tools to a chat template. The JSON schema contains the name and description of
the function, as well as the names, types and descriptions for each of its arguments. `get_json_schema()` requires
that the function has a docstring, and that each argument has a description in the docstring, in the standard
Google docstring format shown below. It also requires that all the function arguments have a valid Python type hint.

Although it is not required, a `Returns` block can also be added, which will be included in the schema. This is
optional because most chat templates ignore the return value of the function.

Args:
    func: The function to generate a JSON schema for.

Returns:
    A dictionary containing the JSON schema for the function.

Examples:
```python
>>> def multiply(x: float, y: float):
>>>    '''
>>>    A function that multiplies two numbers
>>>
>>>    Args:
>>>        x: The first number to multiply
>>>        y: The second number to multiply
>>>    '''
>>>    return x * y
>>>
>>> print(get_json_schema(multiply))
{
    "name": "multiply",
    "description": "A function that multiplies two numbers",
    "parameters": {
        "type": "object",
        "properties": {
            "x": {"type": "number", "description": "The first number to multiply"},
            "y": {"type": "number", "description": "The second number to multiply"}
        },
        "required": ["x", "y"]
    }
}
```

The general use for these schemas is that they are used to generate tool descriptions for chat templates that
support them, like so:

```python
>>> from transformers import AutoTokenizer
>>> from transformers.utils import get_json_schema
>>>
>>> def multiply(x: float, y: float):
>>>    '''
>>>    A function that multiplies two numbers
>>>
>>>    Args:
>>>        x: The first number to multiply
>>>        y: The second number to multiply
>>>    return x * y
>>>    '''
>>>
>>> multiply_schema = get_json_schema(multiply)
>>> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
>>> messages = [{"role": "user", "content": "What is 179 x 4571?"}]
>>> formatted_chat = tokenizer.apply_chat_template(
>>>     messages,
>>>     tools=[multiply_schema],
>>>     chat_template="tool_use",
>>>     return_dict=True,
>>>     return_tensors="pt",
>>>     add_generation_prompt=True
>>> )
>>> # The formatted chat can now be passed to model.generate()
```

Each argument description can also have an optional `(choices: ...)` block at the end, such as
`(choices: ["tea", "coffee"])`, which will be parsed into an `enum` field in the schema. Note that this will
only be parsed correctly if it is at the end of the line:

```python
>>> def drink_beverage(beverage: str):
>>>    '''
>>>    A function that drinks a beverage
>>>
>>>    Args:
>>>        beverage: The beverage to drink (choices: ["tea", "coffee"])
>>>    '''
>>>    pass
>>>
>>> print(get_json_schema(drink_beverage))
```
{
    'name': 'drink_beverage',
    'description': 'A function that drinks a beverage',
    'parameters': {
        'type': 'object',
        'properties': {
            'beverage': {
                'type': 'string',
                'enum': ['tea', 'coffee'],
                'description': 'The beverage to drink'
                }
            },
        'required': ['beverage']
    }
}
z Cannot generate JSON schema for z because it has no docstring!r`   r*   Nr   z< because the docstring has no description for the argument ''z\(choices:\s*(.*?)\)\s*$)flagsr   enum)rh   r   rd   function)r,   r   )rb   getdocr'   r   ry   r   ro   poprH   r~   ru   
IGNORECASEjsonloadsrx   r/   start)r^   docmain_docparam_descriptions
return_docjson_schemar\   argrn   descenum_choicescoutputs                r$   get_json_schemar      s   V ..
C'.t}}o=Z[
 	
 ))+C/LS/Q,H*4T:K"<044XtDDQ!)3&"<0668(+24==/A}  B  ~C  CD  E  "&yy!<d"--X15L<N<Nq<Q1RS1RAggi1RSF6N&&'=););)=>DDFD $} 9 mmHXF&xF33 Ts   E;c           	          / n/ nU R                   R                  Xg5         U R                  " SUUUUS.UD6 H  nUR                  U5        M     SR	                  U5      n	S S S 5        X4$ ! , (       d  f       W	U4$ = f)Nmessagestools	documentsadd_generation_promptrI   r   )environmentactivate_trackergeneraterj   rz   )
compiled_templater   r   r   r   template_kwargsrendered_blocksgeneration_indicesblockrendered_chats
             r$   _render_with_assistant_indicesr   ^  s     O		&	&	7	7	\&// 
"7	

 
E ""5)
 0 
] ,, 
]	\ ,,,s   AA,,
A=c                    [        5       (       d  [        S5      e " S S[        5      n[        R                  " [
        R                  5      [        R                  " S5      :  a  [        S[
        R                   S35      eS nSS jnS	 n[        S
S
U[
        R                  R                  /S9nX5R                  S'   X%R                  S'   XER                  S'   UR                  U 5      $ )Nzbapply_chat_template requires jinja2 to be installed. Please install it using `pip install jinja2`.c                   R  ^  \ rS rSrS1rS\4U 4S jjrS\R                  R                  S\R                  R                  4S jr\R                  S\R                  R                  S	\R                  R                   S\4S
 j5       rS\4S jr\S\\   S\\   4S j5       rSrU =r$ )1_compile_jinja_template.<locals>.AssistantTrackeriw  
generationr   c                 r   > [         TU ]  U5        UR                  U R                  S9  S U l        S U l        g )N)r   )super__init__extendr   _rendered_blocks_generation_indices)selfr   	__class__s     r$   r   :_compile_jinja_template.<locals>.AssistantTracker.__init__{  s7    G[)0E0EF$(D!'+D$r#   parserr*   c                     [        UR                  5      R                  nUR                  S/SS9n[        R
                  R                  U R                  S5      / / U5      R                  U5      $ )Nzname:endgenerationT)drop_needle_generation_support)	nextstreamlinenoparse_statementsjinja2nodes	CallBlockcall_method
set_lineno)r   r   r   bodys       r$   parse7_compile_jinja_template.<locals>.AssistantTracker.parse  se    &--(//F**,@+At*TD<<))$*:*:;P*QSUWY[_`kklrssr#   contextcallerc                     U" 5       nU R                  5       (       aN  [        SR                  U R                  5      5      nU[        U5      -   nU R                  R                  XE45        U$ )NrI   )	is_activerQ   rz   r   r   rj   )r   r   r   rvstart_index	end_indexs         r$   r   E_compile_jinja_template.<locals>.AssistantTracker._generation_support  sY    B~~!"''$*?*?"@A'#b'1	((//0HIIr#   c                 @    U R                   =(       d    U R                  $ N)r   r   )r   s    r$   r   ;_compile_jinja_template.<locals>.AssistantTracker.is_active  s    ((DD,D,DDr#   r   r   c              3      #     U R                  5       (       a  [        S5      eXl        X l        S v   S U l        S U l        g ! S U l        S U l        f = f7f)Nz3AssistantTracker should not be reused before closed)r   
ValueErrorr   r   )r   r   r   s      r$   r   B_compile_jinja_template.<locals>.AssistantTracker.activate_tracker  sU     	0>>##$%Z[[(7%+=((,%+/( )-%+/(s   A0A AAA)r   r   )r   r   r   r    tagsr   r   r   r   Parserr   r   r   pass_eval_contextEvalContextruntimeMacror7   r   r8   r   r   rT   r5   r   r"   __classcell__)r   s   @r$   AssistantTrackerr   w  s    ~	,(E 	,	t 4 4 	t9O9O 	t
 
	!	!	v||/G/G 	QWQ_Q_QeQe 	jm 	 
"		Et 	E 

	0DI 
	0SWX[S\ 
	0 

	0r#   r   z3.1.0zLapply_chat_template requires jinja2>=3.1.0 to be installed. Your version is .c                 @    [         R                  R                  U 5      er   )r   
exceptionsTemplateError)messages    r$   raise_exception0_compile_jinja_template.<locals>.raise_exception  s    --g66r#   c                 .    [         R                  " XX#US9$ )N)ensure_asciiindent
separators	sort_keys)r   dumps)xr   r   r   r   s        r$   tojson'_compile_jinja_template.<locals>.tojson  s     zz!vhqrrr#   c                 J    [         R                  " 5       R                  U 5      $ r   )r   nowstrftime)formats    r$   strftime_now-_compile_jinja_template.<locals>.strftime_now  s    ||~&&v..r#   T)trim_blockslstrip_blocks
extensionsr   r   r   )FNNF)r   ImportErrorr   r   r   r   __version__r   extloopcontrolsfiltersglobalsfrom_string)chat_templater   r   r   r   	jinja_envs         r$   _compile_jinja_templater  p  s    p
 	
(09 (0T }}V''(7==+AAZ[a[m[mZnnop
 	
7s
/ .:JFJJLcLc9dI #)h+:'((4n%  //r#   conversationsr   r   r  return_assistant_tokens_maskcontinue_final_messager   c           
         U(       a1  [         R                  " SU5      (       d  [        R                  S5        [	        U5      nUbi  / n	U H`  n
[        U
[        5      (       a  U	R                  U
5        M+  [        U
5      (       a  U	R                  [        U
5      5        MW  [        S5      e   OS n	Ub)  U H#  n[        U[        5      (       a  M  [        S5      e   / n/ nU  GHj  n[        US5      (       a  UR                  nU(       a&  [        SUUU	UUS.UD6u  nnUR                  U5        OUR                  " SUU	UUS.UD6nU(       a  US   S	   n[        U[         ["        45      (       a*  [%        U5       H  nS
U;   d  M  US
   n  O   [        S5      eUR'                  5       U;  a  [        S5      eUR)                  UR'                  5       5      nUUU[+        UR-                  5       5      -    U:X  a   US U[+        UR-                  5       5      -    nOUS U[+        UR'                  5       5      -    nUR                  U5        GMm     X4$ )Nz\{\%-?\s*generation\s*-?\%\}zareturn_assistant_tokens_mask==True but chat template does not contain `{% generation %}` keyword.zTools should either be a JSON schema, or a callable function with type hints and a docstring suitable for auto-conversion to a schema.zADocuments should be a list of dicts with 'title' and 'text' keys!r   )r   r   r   r   r   r   contenttextz]continue_final_message is set but we could not find any text to continuein the final message!a  continue_final_message is set but the final message does not appear in the chat after applying the chat template! This can happen if the chat template deletes portions of the final message. Please verify the chat template and final message in your chat to ensure they are compatible.r   )r~   ru   loggerwarning_oncer  r@   rW   rj   r   r   r   	TypeErrorrN   r   r   renderrT   rU   reversedry   rindexrQ   lstrip)r  r   r   r  r  r	  r   kwargsr   tool_schemastooldocumentrenderedall_generation_indiceschatr   r   final_messagecontent_blockfinal_msg_locs                       r$   render_jinja_templater    s|    $BII6UWd,e,eo	

 0> D$%%##D)D!!##OD$9: P   !Hh-- cdd " H4$$==D'0N 1"3"#&;1 1-M- #))*<=-44 "#&;	
 M " HY/M-$77%-m%<M.(5f(=	 &= %w  ""$M9 2  *001D1D1FGM]]SAUAUAW=X-XY]jj -.[MDXDXDZ@[0[ \ !..ZMDWDWDY@Z0Z [&a d ++r#   )NNNFFF)Arb   r   r~   rO   
contextlibr   r   	functoolsr   r   typingr   r   r	   r
   r   r   r   	packagingr   rI   r   import_utilsr   r   r   
get_loggerr   r  r   
jinja2.extr   jinja2.sandboxr   	PIL.Imager   torchr   r5   r6   r7   r8   r,   BASIC_TYPEScompileDOTALLrt   rv   VERBOSEr|   rw   	Exceptionr   r'   rW   r;   rP   ro   rU   r   r   r   r  rT   r  r   r#   r$   <module>r/     sj     	  %    W W W   U U 
		H	%$<F E3c4:s;GS
**H"))
T

 II

 ZZEryyQ
	y 			 	<c <d38n < >t3 >t4 >tBX $ *+S +U8C=(SW.ZbcfZg;g5h +BF4( F4t F4R-$ F0 F0V 4804#'38-2,1[,T#s(^,-[,DtX~./0[, T#s(^,-[, C=	[,
 #+4.[, %TN[, $D>[, 	[,r#   