
    gLB                        d dl Z d dlZd dlZd dlmZ d dlmZ d dlmZ d dlm	Z	m
Z
mZmZmZmZmZmZmZmZ d dlmZ ddlmZmZmZ  e            rd dlZd d	lmZ d d
lmZ ndZ e            rd dlmZ  e            rd dl m!Z! e"e#e$e%e	 e&d          dfZ' ej(        dej)                  Z* ej(        dej)                  Z+ ej(        dej)        ej,        z            Z- ej(        dej)                  Z. G d de/          Z0 G d de/          Z1de$dee$e$f         fdZ2de$defdZ3de
defdZ4de$deee$         ee         ee$         f         fdZ5de
defdZ6d  Z7ed!             Z8dS )"    N)contextmanager)datetime)	lru_cache)
AnyCallableDictListOptionalTupleUnionget_args
get_originget_type_hints)version   )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                       e Zd ZdZdS )TypeHintParsingExceptionzJException raised for errors in parsing type hints to generate JSON schemasN__name__
__module____qualname____doc__     b/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/utils/chat_template_utils.pyr   r   =           TTDr!   r   c                       e Zd ZdZdS )DocstringParsingExceptionzJException raised for errors in parsing docstrings to generate JSON schemasNr   r    r!   r"   r%   r%   C   r#   r!   r%   
param_typereturnc           
          t           ddit          ddit          ddit          ddit          i i}t                      rddi|t          <   t                      rddi|t          <   |	                    | ddi          S )	Ntypeintegernumberstringbooleanimageaudioobject)
intfloatstrboolr   r   r   r   r   get)r&   type_mappings     r"   _get_json_schema_typer7   I   s    fi !fhvy!RL  0%w/U 1 &0VJ(:;;;r!   hintc                 t   t          |           }t          |           }|.	 t          |           S # t          $ r t	          d|           w xY w|t
          u ryd |D             }t          |          dk    r	|d         }n9t          d |D                       rdt          d |D                       i}nd|i}t          d           |v rd	|d
<   |S |t          u r|sddiS dt          |d                   dS |t          u ro|sddiS t          |          dk    r4t	          dt          |                               dd           d          d|v rt	          d          dd |D             dS |t          u r1ddi}t          |          dk    rt          |d                   |d<   |S t	          d|           )NzGCouldn't parse this type hint, likely due to a custom class or object: c                 N    g | ]"}|t          d           ut          |          #S N)r)   _parse_type_hint.0ts     r"   
<listcomp>z$_parse_type_hint.<locals>.<listcomp>f   s1    MMMA$t**9L9L$Q''9L9L9Lr!   r   r   c              3   L   K   | ]}t          |d          t                    V   dS )r)   N)
isinstancer3   r>   subtypes     r"   	<genexpr>z#_parse_type_hint.<locals>.<genexpr>j   s0      JJgGFOS11JJJJJJr!   r)   c                     g | ]
}|d          S )r)   r    rC   s     r"   r@   z$_parse_type_hint.<locals>.<listcomp>l   s    *S*S*Sw76?*S*S*Sr!   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.c                 ,    g | ]}t          |          S r    )r<   r=   s     r"   r@   z$_parse_type_hint.<locals>.<listcomp>   s!    0S0S0S1A!1D1D0S0S0Sr!   )r)   prefixItemsr0      additionalProperties)r   r   r7   KeyErrorr   r   lenallsortedr)   listr<   tupler3   replacedict)r8   originargssubtypesreturn_dictouts         r"   r<   r<   X   sD   FD>>D~	(... 	 	 	*Y[_  	
 
5MMMMMx==A"1+KKJJJJJJJ 	.!6*S*S(*S*S*S#T#TUKK #H-K::&*K
#	4 	IG$$ $.>tAw.G.GHHH	5 	%G$$t99>>*-T!2!29b!A!A - - -   $;;*#  
  0S0Sd0S0S0STTT	4 x t99>>*:47*C*CC&'

"#lnr
s
sss	   1 Afuncc                    t          |           }t          j        |           }g }|j                                        D ]m\  }}|j        t          j        j        k    rt          d|j	         d| j
                   |j        t          j        j        k    r|                    |           ni }|                                D ]\  }}t          |          ||<   d|d}|r||d<   |S )Nz	Argument z$ is missing a type hint in function r0   )r)   
propertiesrequired)r   inspect	signature
parametersrJ   
annotation	Parameteremptyr   namer   defaultappendr<   )	r]   
type_hintsrb   r`   
param_nameparamr_   r&   schemas	            r"   "_convert_type_hints_to_json_schemarn      s   %%J!$''IH&17799 ( (
Ew0666*+vuz+v+vgkgt+v+vwww=G-333OOJ'''J","2"2"4"4 > >
J!1*!=!=
:j99F &%zMr!   	docstringc                 d   t                               |           }t                              |           }t                              |           }|r'|                    d                                          nd}|r'|                    d                                          nd}|r'|                    d                                          nd}|Yd                    d |                    d          D                       }t          	                    |          }d |D             }ni }|||fS )a  
    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
c                 :    g | ]}|                                 |S r    strip)r>   lines     r"   r@   z1parse_google_format_docstring.<locals>.<listcomp>   s*    #`#`#`TSWS]S]S_S_#`D#`#`#`r!   c           	      x    i | ]7}|d          t          j        dd|d                                                   8S )r   z	\s*\n+\s* r   )resubrt   )r>   matchs     r"   
<dictcomp>z1parse_google_format_docstring.<locals>.<dictcomp>   s:    ```uU1XrvlCq9I9IJJ```r!   )
description_researchargs_re
returns_regrouprt   joinsplitargs_split_refindall)	ro   description_match
args_matchreturns_matchdescriptiondocstring_argsreturnsmatches	args_dicts	            r"   parse_google_format_docstringr      s,    '--i88	**J%%i00M 9JS#))!,,22444tK4>HZ%%a((..000DN0=Gm!!!$$**,,,4G !#`#`^5I5I$5O5O#`#`#`aa''77``X_```				7**r!   c                    t          j        |           }|st          d| j         d          |                                }t          |          \  }}}t          |           }|d                             dd          x}|||d<   |d                                         D ]\  }}||vrt          d| j         d| d          ||         }	t          j
        d	|	t          j        
          }
|
rgd t          j        |
                    d                    D             |d<   |
j        d|
                                                                         }	|	|d<   | j        ||d}|||d<   d|dS )a  
    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*$)flagsc                 6    g | ]}|                                 S r    rs   )r>   cs     r"   r@   z#get_json_schema.<locals>.<listcomp>N  s     SSSAaggiiSSSr!   r   enum)rg   r   rc   function)r)   r   )ra   getdocr%   r   rt   r   rn   poprJ   rx   r}   
IGNORECASEjsonloadsr   r,   start)r]   docmain_docparam_descriptions
return_docjson_schemar[   argrm   descenum_choicesoutputs               r"   get_json_schemar      s   V .

C 
'[t}[[[
 
 	
 ))++C/LS/Q/Q,H *4T::K"<044XtDDDQ!)3K&"<06688 
% 
%V(((+ E4=  E  E  B  E  E  E   "#&y!<d"-XXX 	GSSL<N<Nq<Q<Q1R1RSSSF6N&'=););)=)='=>DDFFD $}mHKXXF&xF333r!   c           	          g }g }| j                             ||          5   | j        d||||d|D ]}|                    |           d                    |          }	d d d            n# 1 swxY w Y   |	|fS )N)messagestools	documentsadd_generation_promptrK   r    )environmentactivate_trackergenerateri   r   )
compiled_templater   r   r   r   template_kwargsrendered_blocksgeneration_indicesblockrendered_chats
             r"   _render_with_assistant_indicesr   X  s     O		&	7	7I[	\	\ 	1 	1/&/ 
"7	
 

 
 
 	* 	*E ""5))))00	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 ,,,s   A A,,A03A0c                     G d dt                     }t          j        t          j                  t          j        d          k     rt          dt          j         d          d }dd}d	 }t          d
d
|t          j        j        g          }||j	        d<   ||j
        d<   ||j
        d<   |                    |           S )Nc                        e Zd ZdhZdef fdZdej        j        dej	        j
        fdZej        dej	        j        dej        j        defd	            Zdefd
Zedee         dee         fd            Z xZS )1_compile_jinja_template.<locals>.AssistantTracker
generationr   c                     t                                          |           |                    | j                   d | _        d | _        d S )N)r   )super__init__extendr   _rendered_blocks_generation_indices)selfr   	__class__s     r"   r   z:_compile_jinja_template.<locals>.AssistantTracker.__init__p  sK    GG[)))0EFFF$(D!'+D$$$r!   parserr'   c                     t          |j                  j        }|                    dgd          }t          j                            |                     d          g g |                              |          S )Nzname:endgenerationT)drop_needle_generation_support)	nextstreamlinenoparse_statementsjinja2nodes	CallBlockcall_method
set_lineno)r   r   r   bodys       r"   parsez7_compile_jinja_template.<locals>.AssistantTracker.parsew  sm    &-((/F**,@+At*TTD<))$*:*:;P*Q*QSUWY[_``kklrsssr!   contextcallerc                      |            }|                                  rUt          d                    | j                            }|t          |          z   }| j                            ||f           |S )NrK   )	is_activerQ   r   r   r   ri   )r   r   r   rvstart_index	end_indexs         r"   r   zE_compile_jinja_template.<locals>.AssistantTracker._generation_support|  sm    B~~ J!"''$*?"@"@AA'#b''1	(//i0HIIIIr!   c                     | j         p| j        S r;   )r   r   )r   s    r"   r   z;_compile_jinja_template.<locals>.AssistantTracker.is_active  s    (DD,DDr!   r   r   c              3      K   	 |                                  rt          d          || _        || _        d V  d | _        d | _        d S # d | _        d | _        w xY w)Nz3AssistantTracker should not be reused before closed)r   
ValueErrorr   r   )r   r   r   s      r"   r   zB_compile_jinja_template.<locals>.AssistantTracker.activate_tracker  s{      	0>>## \$%Z[[[(7%+=((,%+/((( )-%+/(////s   5A	 	A)r   r   r   tagsr   r   r   r   Parserr   r   r   pass_eval_contextEvalContextruntimeMacror3   r   r4   r   r   r	   r1   r   __classcell__)r   s   @r"   AssistantTrackerr   l  s       ~	,(E 	, 	, 	, 	, 	, 	,	t 4 	t9O 	t 	t 	t 	t
 
	!	v|/G 	QWQ_Qe 	jm 	 	 	 
"	!		Et 	E 	E 	E 	E 

	0DI 
	0SWX[S\ 
	0 
	0 
	0 

	0 
	0 
	0 
	0 
	0r!   r   z3.1.0zLapply_chat_template requires jinja2>=3.1.0 to be installed. Your version is .c                 @    t           j                            |           r;   )r   
exceptionsTemplateError)messages    r"   raise_exceptionz0_compile_jinja_template.<locals>.raise_exception  s    --g666r!   Fc                 4    t          j        | ||||          S )N)ensure_asciiindent
separators	sort_keys)r   dumps)xr   r   r   r   s        r"   tojsonz'_compile_jinja_template.<locals>.tojson  s!     z!,vR\hqrrrrr!   c                 N    t          j                                        |           S r;   )r   nowstrftime)formats    r"   strftime_nowz-_compile_jinja_template.<locals>.strftime_now  s    |~~&&v...r!   T)trim_blockslstrip_blocks
extensionsr   r   r   )FNNF)r   r   r   r   __version__ImportErrorr   extloopcontrolsfiltersglobalsfrom_string)chat_templater   r   r   r   	jinja_envs         r"   _compile_jinja_templater   j  s   (0 (0 (0 (0 (09 (0 (0 (0T }V'((7=+A+AAAs^d^psss
 
 	
7 7 7s s s s
/ / / .:JFJLc9d  I #)Ih+:I'((4In%  ///r!   )9ra   r   rx   
contextlibr   r   	functoolsr   typingr   r   r   r	   r
   r   r   r   r   r   	packagingr   import_utilsr   r   r   r   
jinja2.extr   jinja2.sandboxr   	PIL.Imager   torchr   r1   r2   r3   r4   r)   BASIC_TYPEScompileDOTALLr|   r~   VERBOSEr   r   	Exceptionr   r%   r7   r<   rn   r   r   r   r   r    r!   r"   <module>r     sP     				 % % % % % %             j j j j j j j j j j j j j j j j j j j j j j j j       U U U U U U U U U U  MMM$$$$$$<<<<<<<F    E3c44::s;GSS
"*H")
T
T
 I
  RZEryQQ
	 	 	 	 	y 	 	 		 	 	 	 		 	 	 	<c <d38n < < < <>t3 >t4 >t >t >t >tBX $    *+S +U8C=(SW.ZbcfZg;g5h + + + +BF4( F4t F4 F4 F4 F4R- - -$ A0 A0 A0 A0 A0r!   