Ë
    S^(h%  ã                   óZ  — d dl mZ d dlmZ d dlmZmZmZ d dlm	Z	 d dl
mZ ddlmZ ddlmZ dd	lmZ  ej$                  e«      Z G d
„ dee«      Zi fdeeeef      deeef   fd„Zej0                  ej2                  iZ G d„ d«      Z G d„ de«      Z G d„ de«      ZdddœZdddœZy)é    )Údeepcopy)ÚEnum)ÚDictÚListÚOptional)ÚInferenceClient)Ú_deprecate_methodé   )ÚAutoTokenizer)ÚPipeline)Úloggingc                   ó0   — e Zd ZdZdZdZdZdZed„ «       Z	y)ÚMessageRoleÚuserÚ	assistantÚsystemz	tool-callztool-responsec                 ó@   — | D �cg c]  }|j                   ‘Œ c}S c c}w ©N)Úvalue)ÚclsÚrs     ú\/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/agents/llm_engine.pyÚroleszMessageRole.roles'   s   € à!$Ö%˜A�—“Ò%Ð%ùÒ%s   …N)
Ú__name__Ú
__module__Ú__qualname__ÚUSERÚ	ASSISTANTÚSYSTEMÚ	TOOL_CALLÚTOOL_RESPONSEÚclassmethodr   © ó    r   r   r       s-   „ Ø€DØ€IØ€FØ€IØ#€Màñ&ó ñ&r$   r   Úmessage_listÚrole_conversionsc                 óž  — g }t        | «      } | D ]º  }t        |j                  «       «      ddhk(  st        d«      ‚|d   }|t        j                  «       vr$t        d|› dt        j                  «       › d�«      ‚||v r||   |d<   t        |«      dkD  r%|d   |d   d   k(  r|d   dxx   d	|d   z   z  cc<   Œª|j                  |«       Œ¼ |S )
z«
    Subsequent messages with the same role will be concatenated to a single message.

    Args:
        message_list (`List[Dict[str, str]]`): List of chat messages.
    ÚroleÚcontentz6Message should contain only 'role' and 'content' keys!zIncorrect role z, only z are supported for now.r   éÿÿÿÿz	
=======
)r   ÚsetÚkeysÚ
ValueErrorr   r   ÚlenÚappend)r%   r&   Úfinal_message_listÚmessager(   s        r   Úget_clean_message_listr2   ,   sø   € ð ÐÜ˜LÓ)€LØò /ˆÜ�7—<‘<“>Ó" v¨yÐ&9Ò9ÜÐUÓVÐVà�v‰ˆØ”{×(Ñ(Ó*Ñ*Ü˜¨t¨f°G¼K×<MÑ<MÓ<OÐ;PÐPgÐhÓiÐiàÐ#Ñ#Ø.¨tÑ4ˆG�F‰OäÐ!Ó" QÒ&¨7°6©?Ð>PÐQSÑ>TÐU[Ñ>\Ò+\Ø˜rÑ" 9Ó-°ÀÈÑASÑ1SÑSÔ-à×%Ñ% gÕ.ð/ð Ðr$   c            	       ó¸   — e Zd Z edd¬«      ddee   fd„«       Zd„ Z	 ddee	eef      d	eee      d
ee   fd„Z
	 ddee	eef      d	eee      d
ee   defd„Zy)ÚHfEnginez4.51.0zzSwitch to smolagents instead, with the same functionalities and similar API (https://huggingface.co/docs/smolagents/index))Úversionr1   NÚmodel_idc                 ó(  — d | _         d | _        |€d}t        j                  d|› d�«       	 t	        j
                  |«      | _        y # t        $ r@}t        j                  d|› d|› d�«       t	        j
                  d«      | _        Y d }~y d }~ww xY w)Nz#HuggingFaceTB/SmolLM2-1.7B-Instructz)Using default model for token counting: 'ú'z#Failed to load tokenizer for model z: z$. Loading default tokenizer instead.)Úlast_input_token_countÚlast_output_token_countÚloggerÚwarningr   Úfrom_pretrainedÚ	tokenizerÚ	Exception)Úselfr6   Úes      r   Ú__init__zHfEngine.__init__M   s’   € ð
 '+ˆÔ#Ø'+ˆÔ$ØÐØ<ˆHÜ�N‰NÐFÀxÀjÐPQÐRÔSð	bÜ*×:Ñ:¸8ÓDˆD�NøÜò 	bÜ�N‰NÐ@ÀÀ
È"ÈQÈCÐOsÐtÔuÜ*×:Ñ:Ð;`ÓaˆD�N‰Nûð	bús   ­A Á	BÁ6BÂBc                 ó4   — | j                   | j                  dœS )N)Úinput_token_countÚoutput_token_count)r9   r:   )r@   s    r   Úget_token_countszHfEngine.get_token_counts]   s   € à!%×!<Ñ!<Ø"&×">Ñ">ñ
ð 	
r$   ÚmessagesÚstop_sequencesÚgrammarc                 ó   — t         ‚r   )ÚNotImplementedError)r@   rG   rH   rI   s       r   ÚgeneratezHfEngine.generatec   s
   € ô "Ð!r$   Úreturnc                 ód  — t        |t        «      st        d«      ‚|€g }| j                  |||«      }t	        | j
                  j                  |d¬«      «      | _        t	        | j
                  j                  |«      «      | _	        |D ]$  }|t	        |«       d |k(  sŒ|dt	        |«        }Œ& |S )a9  Process the input messages and return the model's response.

        This method sends a list of messages to the Hugging Face Inference API, optionally with stop sequences and grammar customization.

        Parameters:
            messages (`List[Dict[str, str]]`):
                A list of message dictionaries to be processed. Each dictionary should have the structure `{"role": "user/system", "content": "message content"}`.
            stop_sequences (`List[str]`, *optional*):
                A list of strings that will stop the generation if encountered in the model's output.
            grammar (`str`, *optional*):
                The grammar or formatting structure to use in the model's response.

        Returns:
            `str`: The text content of the model's response.

        Example:
            ```python
            >>> engine = HfApiEngine(
            ...     model="meta-llama/Meta-Llama-3.1-8B-Instruct",
            ...     token="your_hf_token_here",
            ...     max_tokens=2000
            ... )
            >>> messages = [{"role": "user", "content": "Explain quantum mechanics in simple terms."}]
            >>> response = engine(messages, stop_sequences=["END"])
            >>> print(response)
            "Quantum mechanics is the branch of physics that studies..."
            ```
        zIMessages should be a list of dictionaries with 'role' and 'content' keys.NT)Útokenize)
Ú
isinstancer   r-   rL   r.   r>   Úapply_chat_templater9   Úencoder:   )r@   rG   rH   rI   ÚresponseÚstop_seqs         r   Ú__call__zHfEngine.__call__h   s¶   € ô> ˜(¤DÔ)ÜÐhÓiÐiØÐ!ØˆNØ—=‘= ¨>¸7ÓCˆÜ&)¨$¯.©.×*LÑ*LÈXÐ`dÐ*LÓ*eÓ&fˆÔ#Ü'*¨4¯>©>×+@Ñ+@ÀÓ+JÓ'KˆÔ$ð 'ò 	6ˆHØœ˜X›˜Ð(Ð)¨XÓ5Ø#Ð$4¤s¨8£} nÐ5‘ð	6ð ˆr$   r   ©NN)r   r   r   r	   r   ÚstrrB   rF   r   r   rL   rU   r#   r$   r   r4   r4   L   s½   „ ÙØð Môñ
b ¨#¡ò 
bó	ð
bò
ð txñ"Ø˜T # s (™^Ñ,ð"Ø>FÀtÈCÁyÑ>Qð"ØckÐloÑcpó"ð txñ+Ø˜T # s (™^Ñ,ð+Ø>FÀtÈCÁyÑ>Qð+ØckÐloÑcpð+à	ô+r$   r4   c            
       óŽ   ‡ — e Zd ZdZ	 	 	 	 ddedee   dee   dee   fˆ fd„Z	 ddee	eef      deee      d	ee   d
efd„Z
ˆ xZS )ÚHfApiEnginea7  A class to interact with Hugging Face's Inference API for language model interaction.

    This engine allows you to communicate with Hugging Face's models using the Inference API. It can be used in both serverless mode or with a dedicated endpoint, supporting features like stop sequences and grammar customization.

    Parameters:
        model (`str`, *optional*, defaults to `"meta-llama/Meta-Llama-3.1-8B-Instruct"`):
            The Hugging Face model ID to be used for inference. This can be a path or model identifier from the Hugging Face model hub.
        token (`str`, *optional*):
            Token used by the Hugging Face API for authentication.
            If not provided, the class will use the token stored in the Hugging Face CLI configuration.
        max_tokens (`int`, *optional*, defaults to 1500):
            The maximum number of tokens allowed in the output.
        timeout (`int`, *optional*, defaults to 120):
            Timeout for the API request, in seconds.

    Raises:
        ValueError:
            If the model name is not provided.
    ÚmodelÚtokenÚ
max_tokensÚtimeoutc                 ó|   •— t         ‰| �  |¬«       || _        t        | j                  ||¬«      | _        || _        y )N)r6   )r[   r]   )ÚsuperrB   rZ   r   Úclientr\   )r@   rZ   r[   r\   r]   Ú	__class__s        €r   rB   zHfApiEngine.__init__«   s7   ø€ ô 	‰Ñ %ÐÔ(ØˆŒ
Ü% d§j¡j¸ÀwÔOˆŒØ$ˆ�r$   rG   rH   rI   rM   c                 ó  — t        |t        ¬«      }|�*| j                  j                  ||| j                  |¬«      }n(| j                  j                  ||| j                  ¬«      }|j
                  d   j                  j                  }|S )N©r&   )Ústopr\   Úresponse_format)rd   r\   r   )r2   Úllama_role_conversionsr`   Úchat_completionr\   Úchoicesr1   r)   )r@   rG   rH   rI   rS   s        r   rL   zHfApiEngine.generate·   s…   € ô *¨(ÔE[Ô\ˆð ÐØ—{‘{×2Ñ2Ø˜~¸$¿/¹/Ð[bð 3ó ‰Hð —{‘{×2Ñ2°8À.Ð]a×]lÑ]lÐ2ÓmˆHà×#Ñ# AÑ&×.Ñ.×6Ñ6ˆØˆr$   )z%meta-llama/Meta-Llama-3.1-8B-InstructNéÜ  éx   rV   )r   r   r   Ú__doc__rW   r   ÚintrB   r   r   rL   Ú__classcell__©ra   s   @r   rY   rY   –   s•   ø„ ñð, =Ø#Ø$(Ø!$ñ
%àð
%ð ˜‰}ð
%ð ˜S‘Mð	
%ð
 ˜#‘õ
%ð txñØ˜T # s (™^Ñ,ðØ>FÀtÈCÁyÑ>QðØckÐloÑcpðà	÷r$   rY   c                   óz   ‡ — e Zd ZdZddedee   fˆ fd„Z	 	 	 ddee	eef      deee      dee   de
d	ef
d
„Zˆ xZS )ÚTransformersEnginezBThis engine uses a pre-initialized local text-generation pipeline.Úpipeliner6   c                 ó2   •— t         ‰| �  |«       || _        y r   )r_   rB   rq   )r@   rq   r6   ra   s      €r   rB   zTransformersEngine.__init__Ì   s   ø€ Ü‰Ñ˜Ô"Ø ˆ�r$   rG   rH   rI   Ú
max_lengthrM   c                 óÀ   — t        |t        ¬«      }|�t        |«      dkD  r|}nd }| j                  |||| j                  j                  ¬«      }|d   d   d   d   }|S )Nrc   r   )Ústop_stringsrs   r>   Úgenerated_textr*   r)   )r2   rf   r.   rq   r>   )r@   rG   rH   rI   rs   ru   ÚoutputrS   s           r   rL   zTransformersEngine.generateÐ   sx   € ô *¨(ÔE[Ô\ˆð Ð%¬#¨nÓ*=ÀÒ*AØ)‰LàˆLà—‘ØØ%Ø!Ø—m‘m×-Ñ-ð	 ó 
ˆð ˜!‘9Ð-Ñ.¨rÑ2°9Ñ=ˆØˆr$   r   )NNri   )r   r   r   rk   r   r   rW   rB   r   r   rl   rL   rm   rn   s   @r   rp   rp   É   sw   ø„ ÙLñ! ð !°X¸c±]õ !ð /3Ø!%Øñà�t˜C ˜H‘~Ñ&ðð !  c¡Ñ+ðð ˜#‘ð	ð
 ðð 
÷r$   rp   ÚregexzhThought: .+?\nAction:\n\{\n\s{4}"action":\s"[^"\n]+",\n\s{4}"action_input":\s"[^"\n]+"\n\}\n<end_action>)Útyper   zCThought: .+?\nCode:\n```(?:py|python)?\n(?:.|\s)+?\n```<end_action>N) Úcopyr   Úenumr   Útypingr   r   r   Úhuggingface_hubr   Ú"huggingface_hub.utils._deprecationr	   Ú r   Úpipelines.baser   Úutilsr   Ú
get_loggerr   r;   rW   r   r2   r!   r   rf   r4   rY   rp   ÚDEFAULT_JSONAGENT_REGEX_GRAMMARÚDEFAULT_CODEAGENT_REGEX_GRAMMARr#   r$   r   ú<module>r…      sÝ   ðõ" Ý ß 'Ñ 'å +Ý @å Ý %Ý ð 
ˆ×	Ñ	˜HÓ	%€ô	&�#�tô 	&ð ceñ ¨¨d°3¸°8©nÑ)=ð ÐQUÐVYÐ[^ÐV^ÑQ_ó ð8 ×Ñ˜{×/Ñ/ðÐ ÷
Gñ GôT0�(ô 0ôf˜ô ðF ð Fñ#Ð ð ØWñ#Ñ r$   