
    g                        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m	Z	 d dl
mZmZmZmZmZmZ d dlmZmZmZmZmZ d dlmZmZ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$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z.  e+j/        e0          Z1 e)            rd dl2Z2 e(            rd dl3m4Z4 d dl5m6Z6 dZ7d1dZ8dZ9d Z:e: G d d                      Z;dZ<e<fde;de=de=fdZ>ed             Z? G d de;          Z@de;fdZAdd d!d"d#d$d%d&ZBd2d'ZCd( ZD G d) d*          ZEd+ee=e=f         dee=e=f         fd,ZF G d- d.          ZGd/ede;fd0ZHdS )3    N)	lru_cachewraps)AnyCallableDictListOptionalUnion)create_repoget_collectionhf_hub_downloadmetadata_updateupload_folder)RepositoryNotFoundErrorbuild_hf_headersget_session)version   )custom_object_saveget_class_from_dynamic_moduleget_imports)AutoProcessor)CONFIG_NAMETypeHintParsingExceptioncached_fileget_json_schemais_accelerate_availableis_torch_availableis_vision_availablelogging   )handle_agent_inputshandle_agent_outputs)PartialState)send_to_devicetool_config.jsonc                     ||S 	 t          | t          fddi| dS # t          $ rH 	 t          | t          fddi| Y dS # t          $ r t          d|  d          t          $ r Y Y dS w xY wt          $ r Y dS w xY w)N	repo_typespacemodel`z9` does not seem to be a valid repo identifier on the Hub.)r   TOOL_CONFIG_FILEr   EnvironmentError	Exception)repo_idr(   
hub_kwargss      U/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/agents/tools.pyget_repo_typer2   @   s    !1SSWS
SSSw"   	G%5WWWJWWW77& 	k 	k 	k"#iw#i#i#ijjj 	 	 	777	   wws,    
A;A  &A+&A;*A++A;:A;zufrom transformers import launch_gradio_demo
from {module_name} import {class_name}

launch_gradio_demo({class_name})
c                 X    | j         t                    fd            }|| _         | S )Nc                 v     | g|R i | t          | t                    s|                                  d S d S N)
isinstancePipelineToolvalidate_arguments)selfargskwargsoriginal_inits      r1   new_initz%validate_after_init.<locals>.new_init]   sW    d,T,,,V,,,$-- 	&##%%%%%	& 	&    )__init__r   )clsr=   r<   s     @r1   validate_after_initrA   Z   sD    LM
=& & & & &
 CLJr>   c                   P   e Zd ZU dZeed<   eed<   eeeeeeef         f         f         ed<   eed<   d Z	d Z
d Zd	 Zd
 Zd Ze	 	 ddedee         dee         fd            Z	 	 	 	 ddededee         deeeef                  dedefdZed             Zed             ZdS )Toolak  
    A base class for the functions used by the agent. Subclass this and implement the `__call__` method as well as the
    following class attributes:

    - **description** (`str`) -- A short description of what your tool does, the inputs it expects and the output(s) it
      will return. For instance 'This is a tool that downloads a file from a `url`. It takes the `url` as input, and
      returns the text contained in the file'.
    - **name** (`str`) -- A performative name that will be used for your tool in the prompt to the agent. For instance
      `"text-classifier"` or `"image_generator"`.
    - **inputs** (`Dict[str, Dict[str, Union[str, type]]]`) -- The dict of modalities expected for the inputs.
      It has one `type`key and a `description`key.
      This is used by `launch_gradio_demo` or to make a nice space from your tool, and also can be used in the generated
      description for your tool.
    - **output_type** (`type`) -- The type of the tool output. This is used by `launch_gradio_demo`
      or to make a nice space from your tool, and also can be used in the generated description for your tool.

    You can also override the method [`~Tool.setup`] if your tool as an expensive operation to perform before being
    usable (such as loading a model). [`~Tool.setup`] will be called the first time you use your tool, but not at
    instantiation.
    namedescriptioninputsoutput_typec                     d| _         d S )NFis_initializedr9   r:   r;   s      r1   r?   zTool.__init__   s    #r>   c           
         t           t           t          t           d}g d}|                                D ]A\  }}t          | |d           }t	          ||          st          d| d|j         d          B| j                                        D ]R\  }}d|v sJ d| d            |d         |vrt          d| d	|d          d
| d          d|v sJ d| d            St          | dd           |v sJ t	          | t                    svt          j        | j                  }t          |j                                                  t          | j                                                  k    st          d          d S d S )N)rE   rD   rF   rG   )stringintegernumberimageaudioanybooleanzYou must set an attribute z	 of type .typezInput 'z' should specify a type.z	': type 'z/' is not an authorized value, should be one of rE   z' should have a description.rG   zTool's 'forward' method should take 'self' as its first argument, then its next arguments should match the keys of tool attribute 'inputs'.)strr   itemsgetattrr6   	TypeError__name__rF   r.   r7   inspect	signatureforwardset
parameterskeys)	r9   required_attributesauthorized_typesattrexpected_type
attr_value
input_nameinput_contentr\   s	            r1   r8   zTool.validate_arguments   s   	
 
 _^^#6#<#<#>#> 	g 	gD- tT22Jj-88 g eT e eMLb e e efffg)-):):)<)< 	f 	f%J]***,Zj,Z,Z,Z***V$,<<< Mj  M  M=3H  M  M  zJ  M  M  M   !M1113eZ3e3e3e1111t]D115EEEEE$-- 	)$,77Iy+002233s4;;K;K;M;M7N7NNN b  	 	NNr>   c                      t          d          S )Nz-Write this method in your subclass of `Tool`.)NotImplementedrK   s      r1   r]   zTool.forward   s    MNNNr>   c                 d    t          |i |\  }} | j        |i |}t          || j                  S r5   )r"   r]   r#   rG   )r9   r:   r;   outputss       r1   __call__zTool.__call__   sA    *D;F;;f$,///#GT-=>>>r>   c                     d| _         dS )z
        Overwrite this method here for any operation that is expensive and needs to be executed before you start using
        your tool. Such as loading a big model.
        TNrI   )r9   s    r1   setupz
Tool.setup   s    
 #r>   c                    t          j        |d           | j        dk    rt          d|  d| d          t	          | |          }| j        j        }|                    d          d         }| d| j        j         }t           j        	                    |d	          }t           j        
                    |          r?t          |d
d          5 }t          j        |          }ddd           n# 1 swxY w Y   ni }|| j        | j        | j        t#          | j                  d}t          |dd          5 }|                    t          j        |dd          dz              ddd           n# 1 swxY w Y   t           j        	                    |d          }	t          |	dd          5 }|                    t*                              || j        j                             ddd           n# 1 swxY w Y   t           j        	                    |d          }
g }|D ]$}|                    t1          |                     %t3          t5          |                    }t          |
dd          5 }|                    d	                    |          dz              ddd           dS # 1 swxY w Y   dS )a  
        Saves the relevant code files for your tool so it can be pushed to the Hub. This will copy the code of your
        tool in `output_dir` as well as autogenerate:

        - a config file named `tool_config.json`
        - an `app.py` file so that your tool can be converted to a space
        - a `requirements.txt` containing the names of the module used by your tool (as detected when inspecting its
          code)

        You should only use this method to save tools that are defined in a separate module (not `__main__`).

        Args:
            output_dir (`str`): The folder in which you want to save your tool.
        T)exist_ok__main__z We can't save the code defining z in z{ as it's been defined in __main__. You have to put this code in a separate module so we can include it in the saved folder.rT   r&   rutf-8encodingN)
tool_classrE   rD   rF   rG   wr   )indent	sort_keys
zapp.py)module_name
class_namezrequirements.txt)osmakedirs
__module__
ValueErrorr   	__class__splitrZ   pathjoinisfileopenjsonloadrE   rD   rF   rV   rG   writedumpsAPP_FILE_TEMPLATEformatextendr   listr^   )r9   
output_dirmodule_filesr|   last_module	full_nameconfig_fileftool_configapp_filerequirements_fileimportsmodules                r1   savez	Tool.save   s    	J....?j((g4 g gZ g g g   *$
;;n/!'',,R0">>T^%<>>	 gll:/ABB7>>+&& 	k3999 +Q"ill+ + + + + + + + + + + + + + + K $+Ikt/00
 
 +sW555 	NGGDJ{1EEELMMM	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 7<<
H55(C'222 	kaGG%,,QUQ_Qh,iijjj	k 	k 	k 	k 	k 	k 	k 	k 	k 	k 	k 	k 	k 	k 	k GLL5GHH" 	0 	0FNN;v..////s7||$$#S7;;; 	/qGGDIIg&&-...	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/sH   C22C69C6;.E55E9<E92:G88G<?G<:,J33J7:J7Nr/   model_repo_idtokenc                    g dfd|                                 D             }t          |fi ||d<   t          |t          fd|i|dddd}|du}|t          |t          fd|i|dddd}|t          | d          t          |d	
          5 }t          j        |          }	ddd           n# 1 swxY w Y   |sd|	vrt          | d          |	d         }
n|	}
|
d         }t          ||fd|i|}t          |j                  dk    r|
d         |_        |j        |
d         k    r/t                              |j         d           |
d         |_        t          |j                  dk    r|
d         |_        |j        |
d         k    r/t                              |j         d           |
d         |_        |j        |
d         k    r|
d         |_        |j        |
d         k    r|
d         |_         |di |S )a  
        Loads a tool defined on the Hub.

        <Tip warning={true}>

        Loading a tool from the Hub means that you'll download the tool and execute it locally.
        ALWAYS inspect the tool you're downloading before loading it within your runtime, as you would do when
        installing a package using pip/npm/apt.

        </Tip>

        Args:
            repo_id (`str`):
                The name of the repo on the Hub where your tool is defined.
            model_repo_id (`str`, *optional*):
                If your tool uses a model and you want to use a different model than the default, you can pass a second
                repo ID or an endpoint url to this argument.
            token (`str`, *optional*):
                The token to identify you on hf.co. If unset, will use the token generated when running
                `huggingface-cli login` (stored in `~/.huggingface`).
            kwargs (additional keyword arguments, *optional*):
                Additional keyword arguments that will be split in two: all arguments relevant to the Hub (such as
                `cache_dir`, `revision`, `subfolder`) will be used when downloading the files for your tool, and the
                others will be passed along to its init.
        )	cache_dirforce_downloadresume_downloadproxiesrevisionr(   	subfolderlocal_files_onlyc                 $    i | ]\  }}|v 	||S  r   ).0kvhub_kwargs_namess      r1   
<dictcomp>z!Tool.from_hub.<locals>.<dictcomp>  s*    OOOtq!>N9N9Na9N9N9Nr>   r(   r   F) _raise_exceptions_for_gated_repo%_raise_exceptions_for_missing_entries'_raise_exceptions_for_connection_errorsNzY does not appear to provide a valid configuration in `tool_config.json` or `config.json`.rt   ru   custom_toolzO does not provide a mapping to custom tools in its configuration `config.json`.rw   r   rD   z_ implements a different name in its configuration and class. Using the tool configuration name.rE   zm implements a different description in its configuration and class. Using the tool configuration description.rF   rG   r   )rW   r2   r   r,   r   r-   r   r   r   r   lenrD   loggerwarningrZ   rE   rF   rG   )r@   r/   r   r   r;   r0   resolved_config_fileis_tool_configreaderconfigr   rw   r   s               @r1   from_hubzTool.from_hub   s6   B	
 	
 	
 POOOv||~~OOO
 #0"F"F:"F"F
;* 
  
  
 	 

 .32749 
  
  
  
 .T9'#.$ $ $ 	$
 276;8=$ $ $ $   '"uuu   &999 	'VYv&&F	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	'  	!F**&ooo   !/KK K .
2:wbbebWabb
z1$$)&1JO?k&111NN& & & &   *&1JOz%&&!++%0%?J"![%???NN& 2 2 2   &1%?J"H 555 +H 5J![%???%0%?J"z##F###s   B88B<?B<Upload toolFcommit_messageprivate	create_prreturnc                    t          |||ddd          }|j        }t          |ddgid           t          j                    5 }|                     |           t                              d| d	d
                    t          j
        |                                t          |||||d          cddd           S # 1 swxY w Y   dS )a  
        Upload the tool to the Hub.

        For this method to work properly, your tool must have been defined in a separate module (not `__main__`).
        For instance:
        ```
        from my_tool_module import MyTool
        my_tool = MyTool()
        my_tool.push_to_hub("my-username/my-space")
        ```

        Parameters:
            repo_id (`str`):
                The name of the repository you want to push your tool to. It should contain your organization name when
                pushing to a given organization.
            commit_message (`str`, *optional*, defaults to `"Upload tool"`):
                Message to commit while pushing.
            private (`bool`, *optional*):
                Whether or not the repository created should be private.
            token (`bool` or `str`, *optional*):
                The token to use as HTTP bearer authorization for remote files. If unset, will use the token generated
                when running `huggingface-cli login` (stored in `~/.huggingface`).
            create_pr (`bool`, *optional*, defaults to `False`):
                Whether or not to create a PR with the uploaded files or directly commit.
        Tr)   gradio)r/   r   r   rp   r(   	space_sdktagstool)r(   z!Uploading the following files to z: ,)r/   r   folder_pathr   r   r(   N)r   r/   r   tempfileTemporaryDirectoryr   r   infor   r~   listdirr   )r9   r/   r   r   r   r   repo_urlwork_dirs           r1   push_to_hubzTool.push_to_hub_  s3   B 
 
 
 "&6(!3wGGGG(** 	hIIhKKgGggsxxPRPZ[cPdPdGeGegghhh -$#!  		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   A/CCCc                 L    ddl  G fddt                    } ||           S )z8
        Creates a [`Tool`] from a gradio tool.
        r   Nc                   (     e Zd Z fdZd Z xZS )+Tool.from_gradio.<locals>.GradioToolWrapperc                 (   t                                                       |j        | _        |j        | _        d| _        || _        t           j        |j                  j	        
                                          }d |D             | _        d S )NrM   c                     i | ]}|d S ) r   )r   keys     r1   r   zHTool.from_gradio.<locals>.GradioToolWrapper.__init__.<locals>.<dictcomp>  s    <<<3sB<<<r>   )superr?   rD   rE   rG   _gradio_toolr   r\   runr_   r`   rF   )r9   r   	func_argsr   r[   s      r1   r?   z4Tool.from_gradio.<locals>.GradioToolWrapper.__init__  s      """(-	#/#; #+ $0! !2!2<3C!D!D!O!T!T!V!VWW	<<)<<<r>   c                 &     | j         j        |i |S r5   )r   r   rK   s      r1   r]   z3Tool.from_gradio.<locals>.GradioToolWrapper.forward  s    ,t(,d=f===r>   rZ   r   __qualname__r?   r]   __classcell__)r   r[   s   @r1   GradioToolWrapperr     sM        = = = = = => > > > > > >r>   r   )r[   rC   )gradio_toolr   r[   s     @r1   from_gradiozTool.from_gradio  sU    
 		> 	> 	> 	> 	> 	> 	> 	> 	> 	> ! ---r>   c                 >     G d dt                     } ||           S )z;
        Creates a [`Tool`] from a langchain tool.
        c                   $     e Zd Z fdZd Z xZS )1Tool.from_langchain.<locals>.LangChainToolWrapperc                     t                                                       |j                                        | _        |j        | _        t          |j                  | _        d| _        || _	        d S )NrM   )
r   r?   rD   lowerrE   parse_langchain_argsr:   rF   rG   langchain_tool)r9   _langchain_toolr   s     r1   r?   z:Tool.from_langchain.<locals>.LangChainToolWrapper.__init__  sb      """+06688	#2#> 2?3GHH#+ &5###r>   c                    |                                 }t          |          D ]C\  }}|t          | j                  k     r&t	          t          | j                            }|||<   D| j                            |          S r5   )copy	enumerater   rF   nextiterr   r   )r9   r:   r;   
tool_inputindexargument	input_keys          r1   r]   z9Tool.from_langchain.<locals>.LangChainToolWrapper.forward  sv    #[[]]
'0 9 9OE8s4;////$(dk):):$;$;	08
9-*..z:::r>   r   r   s   @r1   LangChainToolWrapperr     sG        6 6 6 6 6; ; ; ; ; ; ;r>   r   )rC   )r   r   s     r1   from_langchainzTool.from_langchain  s?    	; 	; 	; 	; 	;4 	; 	; 	;" $#N333r>   NN)r   NNF)rZ   r   r   __doc__rV   __annotations__r   r
   rU   r?   r8   r]   rl   rn   r   classmethodr	   r   boolr   staticmethodr   r   r   r>   r1   rC   rC   g   s         * IIId3c4i 00112222$ $ $  <O O O? ? ?
# # #:/ :/ :/x  (,#	m$ m$m$  }m$ }	m$ m$ m$ [m$d ,"&,07 77 7 $	7
 dCi()7 7 
7 7 7 7r . . \.* 4 4 \4 4 4r>   rC   z
- {{ tool.name }}: {{ tool.description }}
    Takes inputs: {{tool.inputs}}
    Returns an output of type: {{tool.output_type}}
r   description_templater   c                 P    t          |          }|                    |           }|S )N)r   )compile_jinja_templaterender)r   r   compiled_templaterendereds       r1   get_tool_description_with_argsr     s5    ./CDD '' (  H Or>   c                 R   	 dd l }ddlm ddlm} n# t
          $ r t          d          w xY wt          j        |j                  t          j        d          k     rt          d|j         d          fd} |d	d	
          }||j	        d<   |
                    |           S )Nr   )TemplateError)ImmutableSandboxedEnvironmentz)template requires jinja2 to be installed.z3.1.0zAtemplate requires jinja2>=3.1.0 to be installed. Your version is rT   c                      |           r5   r   )messager   s    r1   raise_exceptionz/compile_jinja_template.<locals>.raise_exception  s    mG$$$r>   T)trim_blockslstrip_blocksr  )jinja2jinja2.exceptionsr   jinja2.sandboxr  ImportErrorr   parse__version__globalsfrom_string)templater  r  r  	jinja_envr   s        @r1   r   r     s    G333333@@@@@@@ G G GEFFFG }V'((7=+A+AAAvagasvvvwww% % % % % .-$dSSSI+:I'(  ***s    .c                   x     e Zd ZdZeZdZeZdZdZ	dZ
deiZeZ	 	 	 	 	 	 	 d fd	Z fdZd Zd	 Zd
 Zd Z xZS )r7   a0	  
    A [`Tool`] tailored towards Transformer models. On top of the class attributes of the base class [`Tool`], you will
    need to specify:

    - **model_class** (`type`) -- The class to use to load the model in this tool.
    - **default_checkpoint** (`str`) -- The default checkpoint that should be used when the user doesn't specify one.
    - **pre_processor_class** (`type`, *optional*, defaults to [`AutoProcessor`]) -- The class to use to load the
      pre-processor
    - **post_processor_class** (`type`, *optional*, defaults to [`AutoProcessor`]) -- The class to use to load the
      post-processor (when different from the pre-processor).

    Args:
        model (`str` or [`PreTrainedModel`], *optional*):
            The name of the checkpoint to use for the model, or the instantiated model. If unset, will default to the
            value of the class attribute `default_checkpoint`.
        pre_processor (`str` or `Any`, *optional*):
            The name of the checkpoint to use for the pre-processor, or the instantiated pre-processor (can be a
            tokenizer, an image processor, a feature extractor or a processor). Will default to the value of `model` if
            unset.
        post_processor (`str` or `Any`, *optional*):
            The name of the checkpoint to use for the post-processor, or the instantiated pre-processor (can be a
            tokenizer, an image processor, a feature extractor or a processor). Will default to the `pre_processor` if
            unset.
        device (`int`, `str` or `torch.device`, *optional*):
            The device on which to execute the model. Will default to any accelerator available (GPU, MPS etc...), the
            CPU otherwise.
        device_map (`str` or `dict`, *optional*):
            If passed along, will be used to instantiate the model.
        model_kwargs (`dict`, *optional*):
            Any keyword argument to send to the model instantiation.
        token (`str`, *optional*):
            The token to use as HTTP bearer authorization for remote files. If unset, will use the token generated when
            running `huggingface-cli login` (stored in `~/.huggingface`).
        hub_kwargs (additional keyword arguments, *optional*):
            Any additional keyword argument to send to the methods that will load the data from the Hub.
    NzThis is a pipeline toolpipelinepromptc                    t                      st          d          t                      st          d          || j        t	          d          | j        }||}|| _        || _        || _        || _        || _	        |i n|| _
        |
|| j
        d<   || _        || j        d<   t                                                       d S )Nz/Please install torch in order to use this tool.z4Please install accelerate in order to use this tool.zHThis tool does not implement a default checkpoint, you need to pass one.
device_mapr   )r   r
  r   default_checkpointr   r*   pre_processorpost_processordevicer  model_kwargsr0   r   r?   )
r9   r*   r  r  r  r  r  r   r0   r   s
            r1   r?   zPipelineTool.__init__  s     "## 	QOPPP&(( 	VTUUU=&. !klll+E !M
*,$"."6BBL!.8Dl+$#( r>   c                    t          | j        t                    r" | j        j        | j        fi | j        | _        t          | j        t                    r) | j        j        | j        fi | j        | j        | _        | j	        | j        | _	        n<t          | j	        t                    r" | j
        j        | j	        fi | j        | _	        | j        V| j        7t          | j        j                                                  d         | _        nt!                      j        | _        | j        | j                            | j                   t'                                                       dS )z^
        Instantiates the `pre_processor`, `model` and `post_processor` if necessary.
        Nr   )r6   r  rV   pre_processor_classfrom_pretrainedr0   r*   model_classr  r  post_processor_classr  r  r   hf_device_mapvaluesr$   default_devicetor   rn   )r9   r   s    r1   rn   zPipelineTool.setup?  sP    d(#.. 	q!I!9!I$J\!p!p`d`o!p!pDdj#&& 	n9)9$*mmHYm]a]lmmDJ&"&"4D+S11 	t"K$";"KDL_"s"scgcr"s"sD;*"4:#;#B#B#D#DEEaH*nn;?"JMM$+&&&r>   c                 ,    |                      |          S )zQ
        Uses the `pre_processor` to prepare the inputs for the `model`.
        )r  )r9   
raw_inputss     r1   encodezPipelineTool.encodeY  s     !!*---r>   c                 v    t          j                    5   | j        di |cddd           S # 1 swxY w Y   dS )z7
        Sends the inputs through the `model`.
        Nr   )torchno_gradr*   )r9   rF   s     r1   r]   zPipelineTool.forward_  s     ]__ 	( 	(4:''''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(s   .22c                 ,    |                      |          S )zG
        Uses the `post_processor` to decode the model output.
        )r  )r9   rk   s     r1   decodezPipelineTool.decodef  s     ""7+++r>   c                    t          |i |\  }}| j        s|                                   | j        |i |}d |                                D             }d |                                D             }t          || j                  }|                     i ||          }t          |d          }|                     |          }t          || j
                  S )Nc                 N    i | ]"\  }}t          |t          j                  ||#S r   r6   r(  Tensorr   r   r   s      r1   r   z)PipelineTool.__call__.<locals>.<dictcomp>t  s1    ```$!QJqRWR^D_D_`A```r>   c                 N    i | ]"\  }}t          |t          j                  ||#S r   r.  r0  s      r1   r   z)PipelineTool.__call__.<locals>.<dictcomp>u  s2    hhhdaJWXZ_ZfLgLghQhhhr>   cpu)r"   rJ   rn   r&  rW   r%   r  r]   r+  r#   rG   )r9   r:   r;   encoded_inputstensor_inputsnon_tensor_inputsrk   decoded_outputss           r1   rl   zPipelineTool.__call__l  s    *D;F;;f" 	JJLLL$d5f55``.*>*>*@*@```hhn.B.B.D.Dhhh't{CC,,F.F4EFGG %00++g..#OT5EFFFr>   )NNNNNNN)rZ   r   r   r   r   r  r  r  r  rE   rD   rV   rF   rG   r?   rn   r&  r]   r+  rl   r   r   s   @r1   r7   r7     s        # #J (K(+KD_FK # # # # # #J    4. . .( ( (, , ,G G G G G G Gr>   r7   rw   c                   	 	 ddl }n# t          $ r t          d          w xY w |             		fd}g }| j                                        D ]\  }}|d         }|dk    r*|                    |                    |                     =|dk    r*|                    |                    |                     m|d	v r*|                    |                    |                     d
| d}t          |          | j	        }|dv sJ d| d            |
                    |||| j        	j                                                   dS )z
    Launches a gradio demo for a tool. The corresponding tool class needs to properly implement the class attributes
    `inputs` and `output_type`.

    Args:
        tool_class (`type`): The class of the tool for which to launch the demo.
    r   Nz<Gradio should be installed in order to launch a gradio demo.c                       | i |S r5   r   )r:   r;   r   s     r1   fnzlaunch_gradio_demo.<locals>.fn  s    tT$V$$$r>   rU   rP   )labelrQ   )rM   rN   rO   zInput type 'z' not supported.)rM   rP   rQ   zOutput type ')r9  rF   rk   titlearticle)r   r
  rF   rW   appendImageAudioTextboxr   rG   	InterfacerZ   rE   launch)
rw   grr9  gradio_inputsrf   input_details
input_typeerror_messagegradio_outputr   s
            @r1   launch_gradio_demorI    s   Z Z Z ZXYYYZ :<<D% % % % % M%/%6%<%<%>%> 
, 
,!
M"6*
    
!;!;<<<<7""  
!;!;<<<<:::  *!=!=>>>>G:GGGM]+++*M8888:i-:i:i:i888LL!     fhhhhhs    "DocumentQuestionAnsweringToolImageQuestionAnsweringToolSpeechToTextToolTextToSpeechToolTranslationToolPythonInterpreterToolDuckDuckGoSearchTool)document_question_answeringimage_question_answeringspeech_to_texttext_to_speechtranslationpython_interpreter
web_searchc                     | t           v rCt           |          }t          j        d          }|j        }t	          ||          } ||fd|i|S t
                              d| d           t          j        | f||d|S )a  
    Main function to quickly load a tool, be it on the Hub or in the Transformers library.

    <Tip warning={true}>

    Loading a tool means that you'll download the tool and execute it locally.
    ALWAYS inspect the tool you're downloading before loading it within your runtime, as you would do when
    installing a package using pip/npm/apt.

    </Tip>

    Args:
        task_or_repo_id (`str`):
            The task for which to load the tool or a repo ID of a tool on the Hub. Tasks implemented in Transformers
            are:

            - `"document_question_answering"`
            - `"image_question_answering"`
            - `"speech_to_text"`
            - `"text_to_speech"`
            - `"translation"`

        model_repo_id (`str`, *optional*):
            Use this argument to use a different model than the default one for the tool you selected.
        token (`str`, *optional*):
            The token to identify you on hf.co. If unset, will use the token generated when running `huggingface-cli
            login` (stored in `~/.huggingface`).
        kwargs (additional keyword arguments, *optional*):
            Additional keyword arguments that will be split in two: all arguments relevant to the Hub (such as
            `cache_dir`, `revision`, `subfolder`) will be used when downloading the files for your tool, and the others
            will be passed along to its init.
    transformersr   z(You're loading a tool from the Hub from a  . Please make sure this is a source that you trust as the code within that tool will be executed on your machine. Always verify the code of the tools that you load. We recommend specifying a `revision` to ensure you're loading the code that you have checked.)r   r   )	TOOL_MAPPING	importlibimport_moduleagentsrX   r   warning_oncerC   r   )task_or_repo_idr   r   r;   tool_class_namemain_moduletools_modulerw   s           r1   	load_toolrc    s    B ,&&&7-n==")\?;;
z-??u????+} + + +	
 	
 	
 }_aMQVaaZ`aaar>   c                       fd}|S )z<
    A decorator that adds a description to a function.
    c                 .    | _         | j        | _        | S r5   )rE   rZ   rD   )funcrE   s    r1   innerzadd_description.<locals>.inner  s    &M	r>   r   )rE   rg  s   ` r1   add_descriptionrh    s#    
    
 Lr>   c                       e Zd Zddedee         fdZed             Zed             Z	 	 	 	 ddee	ee
ee         eee                  f                  d	ee
         d
ee         dedef
dZdS )EndpointClientNendpoint_urlr   c                 J    i t          |          ddi| _        || _        d S )Nr   zContent-Typezapplication/json)r   headersrk  )r9   rk  r   s      r1   r?   zEndpointClient.__init__  s>    
U+++
.
 
 )r>   c                     t          j                    }|                     |d           t          j        |                                          }|                    d          S )NPNG)r   rt   )ioBytesIOr   base64	b64encodegetvaluer+  )rP   _bytesb64s      r1   encode_imagezEndpointClient.encode_image  sO    

6%
(((v0011zz'"""r>   c                     t                      st          d          ddlm} t	          j        |           }t          j        |          }|                    |          S )NzbThis tool returned an image but Pillow is not installed. Please install it (`pip install Pillow`).r   )r>  )	r   r
  PILr>  rs  	b64decoderq  rr  r   )	raw_imager>  rw  rv  s       r1   decode_imagezEndpointClient.decode_image  sh    "$$ 	t   	y))Czz&!!!r>   FrF   paramsdataoutput_imager   c                     i }|r||d<   |r||d<   t                                          | j        | j        ||          }|r|                     |j                  S |                                S )NrF   r_   )rn  r   r  )r   postrk  rn  r}  contentr   )r9   rF   r~  r  r  payloadresponses          r1   rl   zEndpointClient.__call__  s      	' &GH 	+$*GL! ==%%d&7T[bf%gg  	#$$X%5666==??"r>   r5   )NNNF)rZ   r   r   rV   r	   r?   r   rx  r}  r
   r   r   bytesr   r   rl   r   r>   r1   rj  rj    s        ) )S )# ) ) ) ) # # \# 
" 
" \
" JN!% $"# #sD$s)T$s)_DEF# # uo	#
 # 
# # # # # #r>   rj  r:   c                     |                                  }|                                D ]}d|v r|                    d           |S )zTParse the args attribute of a LangChain tool to create a matching inputs dictionary.r;  )r   r!  pop)r:   rF   arg_detailss      r1   r   r   (  sI    YY[[F}} % %k!!OOG$$$Mr>   c                   0    e Zd ZdZddedee         fdZdS )ToolCollectionai  
    Tool collections enable loading all Spaces from a collection in order to be added to the agent's toolbox.

    > [!NOTE]
    > Only Spaces will be fetched, so you can feel free to add models and datasets to your collection if you'd
    > like for this collection to showcase them.

    Args:
        collection_slug (str):
            The collection slug referencing the collection.
        token (str, *optional*):
            The authentication token if the collection is private.

    Example:

    ```py
    >>> from transformers import ToolCollection, ReactCodeAgent

    >>> image_tool_collection = ToolCollection(collection_slug="huggingface-tools/diffusion-tools-6630bb19a942c2306a2cdb6f")
    >>> agent = ReactCodeAgent(tools=[*image_tool_collection.tools], add_base_tools=True)

    >>> agent.run("Please draw me a picture of rivers and lakes.")
    ```
    Ncollection_slugr   c                     t          ||          | _        d | j        j        D             | _        d | j        D             | _        d S )Nrm  c                 2    h | ]}|j         d k    |j        S )r)   )	item_typeitem_id)r   items     r1   	<setcomp>z*ToolCollection.__init__.<locals>.<setcomp>M  s)    kkktQUQ_cjQjQjdlQjQjQjr>   c                 B    h | ]}t                               |          S r   )rC   r   )r   r/   s     r1   r  z*ToolCollection.__init__.<locals>.<setcomp>N  s$    OOOdmmG,,OOOr>   )r   _collectionrW   _hub_repo_idstools)r9   r  r   s      r1   r?   zToolCollection.__init__K  sO    )/GGGkkt7G7MkkkOOD<NOOO


r>   r5   )rZ   r   r   r   rV   r	   r?   r   r>   r1   r  r  1  sR         2P P PHSM P P P P P Pr>   r  tool_functionc                     t                     d         dvrt          d          d                                          d} G  fddt                    }t	          j                   }t	          j        dt          j        j                  gt          |j	        
                                          z   }|                    |	          }||j        _        ||_         |            S )
a&  
    Converts a function into an instance of a Tool subclass.

    Args:
        tool_function: Your function. Should have type hints for each input and a type hint for the output.
        Should also have a docstring description including an 'Args:' part where each argument is described.
    functionr   zKTool return type not found: make sure your function has a return type hint!rD   rC   c                       e Zd Z d         Z d         Z d         d         Z d         d         Z e          fd            ZdS )	tool.<locals>.SpecificToolrD   rE   r_   
propertiesr   rU   c                      |i |S r5   r   )r9   r:   r;   r  s      r1   r]   z"tool.<locals>.SpecificTool.forwardd  s     =$1&111r>   N)	rZ   r   r   rD   rE   rF   rG   r   r]   )r_   r  s   r1   SpecificToolr  ^  su        &! /L),7 *62	}			2 	2 	2 	2 
		2 	2 	2r>   r  r9   )r_   )r   r   
capitalizerC   r[   r\   	ParameterPOSITIONAL_OR_KEYWORDr   r_   r!  replacer]   __signature__rZ   )r  r}   r  original_signaturenew_parametersnew_signaturer_   s   `     @r1   r   r   Q  s    !//
;Jz!!&'tuuuv&1133999J2 2 2 2 2 2 2 2t 2 2 2 !*=99'0A0WXXY\`%,,..] ] N '....IIM)6L&&L<>>r>   r5   r   )Irs  r[  r[   rq  r   r~   r   	functoolsr   r   typingr   r   r   r   r	   r
   huggingface_hubr   r   r   r   r   huggingface_hub.utilsr   r   r   	packagingr   dynamic_module_utilsr   r   r   models.autor   utilsr   r   r   r   r   r   r   r    agent_typesr"   r#   
get_loggerrZ   r   r(  
accelerater$   accelerate.utilsr%   r,   r2   r   rA   rC   !DEFAULT_TOOL_DESCRIPTION_TEMPLATErV   r   r   r7   rI  rZ  rc  rh  rj  r   r  r   r   r>   r1   <module>r     s:  "       				  				  & & & & & & & & = = = = = = = = = = = = = = = = h h h h h h h h h h h h h h X X X X X X X X X X               
 ( ' ' ' ' '	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 C B B B B B B B 
	H	%	%  LLL 0''''''////// &    & 
 
 
 ]4 ]4 ]4 ]4 ]4 ]4 ]4 ]4@% ! Lm   S qt     + + +&QG QG QG QG QG4 QG QG QGh(4 ( ( ( (X $C <(($1( .b .b .b .bb
 
 
1# 1# 1# 1# 1# 1# 1# 1#htCH~ $sCx.    P P P P P P P P@ T      r>   