
    ~hy                       d dl m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Z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 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'm(Z( d	dl)m*Z*m+Z+ d	dl,m-Z-m.Z.m/Z/m0Z0m1Z1 erd dl2Z2 ejf                  e4      Z5d Z6g dZ7ddddZ8 G d d      Z9d!dZ:	 	 	 d"	 	 	 	 	 d#dZ;d Z< G d d      Z=d$dZ> G d de9      Z?d%dZ@d&dZAg d ZBy)'    )annotationsN)Callable)contextmanager)wraps)Path)TYPE_CHECKINGAny)CommitOperationAddcreate_commitcreate_repoget_collectionhf_hub_downloadmetadata_update   )TypeHintParsingException"_convert_type_hints_to_json_schema_get_json_schema_typeget_importsget_json_schema)
AgentAudio
AgentImagehandle_agent_input_typeshandle_agent_output_types)MethodCheckervalidate_tool_attributes)BASE_BUILTIN_MODULES_is_package_available
get_sourceinstance_to_sourceis_valid_namec                T    | j                   t              fd       }|| _         | S )Nc                >     | g|i | | j                          y N)validate_arguments)selfargskwargsoriginal_inits      L/opt/mcp/mcp-sentiment/venv/lib/python3.12/site-packages/smolagents/tools.pynew_initz%validate_after_init.<locals>.new_initH   s!    d,T,V,!    )__init__r   )clsr*   r(   s     @r)   validate_after_initr.   E   s1    LLM
=" " CLJr+   )
stringbooleanintegernumberimageaudioarrayobjectanynullr/   r1   r2   )strintfloatc                  x    e Zd ZU dZded<   ded<   ded<   ded<   d Z fd	Zd
 Zd ZddddZ	d Z
d dZed!d       Zd"d#dZd$dZ	 	 	 	 d%	 	 	 	 	 	 	 	 	 	 	 d&dZed'd       Zd(dZd)dZd*d+dZd)dZe	 	 d,	 	 	 	 	 d-d       Zed.d       Ze	 	 d/	 	 	 	 	 	 	 	 	 d0d       Zed        Zed        Z xZS )1Toolaq  
    A base class for the functions used by the agent. Subclass this and implement the `forward` 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, bool]]]`) -- 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 has 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.
    r9   namedescriptionz'dict[str, dict[str, str | type | bool]]inputsoutput_typec                    d| _         y NFis_initializedr%   r&   r'   s      r)   r,   zTool.__init__|   s
    #r+   c                :    t        |   di | t        |        y )N )super__init_subclass__r.   )r-   r'   	__class__s     r)   rJ   zTool.__init_subclass__   s    !+F+C r+   c                >   t         t         t        t         d}|j                         D ]W  \  }}t        | |d       }|t	        d| d      t        ||      r1t	        d| d|j                   dt        |       d       t        | j                        st        d| j                   d	      | j                  j                         D ]  \  }}t        |t              sJ d
| d       d|v rd|v s%J d
| dt        |j                                d       t        |d   t               r|d   g}net        |d   t              r+|d   }t        d |D              s;t	        d
| d|d          t	        d
| dt        |d         j                         |D cg c]  }|t        vs| }	}|	st!        d
| d|	 dt                t        | dd       t        v sJ t#        | d      rt        | d      du st%        j&                  | j(                        }
t+        d |
j,                  j                         D              }t+        | j                  j                               }||k7  rt        d| j                   d| d| d      t/        | j(                  d      d   }| j                  j                         D ]V  \  }}||v sJ d
| d|j                                 d |v rd ||   v sJ d!| d"       ||v s@d ||   v sHd |v rMJ d!| d#        y y c c}w )$N)r?   r>   r@   rA   zYou must set an attribute .z
Attribute z should have type z, got z	 instead.zInvalid Tool name 'z?': must be a valid Python identifier and not a reserved keywordzInput 'z' should be a dictionary.typer?   z6' should have keys 'type' and 'description', has only c              3  <   K   | ]  }t        |t                y wr#   )
isinstancer9   ).0ts     r)   	<genexpr>z*Tool.validate_arguments.<locals>.<genexpr>   s     C!:a-Cs   z:': when type is a list, all elements must be strings, got z1': type must be a string or list of strings, got z	': types z must be one of rA   !skip_forward_signature_validationTc              3  ,   K   | ]  }|d k7  s	|  yw)r%   NrH   )rQ   keys     r)   rS   z*Tool.validate_arguments.<locals>.<genexpr>   s     ZcCSYMcZs   
z	In tool 'z$', 'forward' method parameters were z, but expected zx. It should take 'self' as its first argument, then its next arguments should match the keys of tool attribute 'inputs'.F)error_on_missing_type_hints
propertiesz6' should be present in function signature, found only nullablezNullable argument 'zI' in inputs should have key 'nullable' set to True in function signature.zI' in function signature should have key 'nullable' set to True in inputs.)r9   dictitemsgetattr	TypeErrorrP   __name__rN   r    r>   	Exceptionr@   listkeysallAUTHORIZED_TYPES
ValueErrorhasattrinspect	signatureforwardset
parametersr   )r%   required_attributesattrexpected_type
attr_value
input_nameinput_contentinput_typesrR   invalid_typesrg   actual_keysexpected_keysjson_schemarV   values                   r)   r$   zTool.validate_arguments   s   	
 $7#<#<#> 	D- tT2J!"<TF! DEEj-8 &89O9O8PPVW[\fWgVhhqr 	 TYY'%dii[0op  *.):):)< 	s%JmT2cgj\Ib4cc2]*}/M *%[\`anasasau\v[wwxyM -/5,V45M&148+F3C{CC#!*-ghuv|h}g~   j\)Z[_`mnt`u[v[[  [A  B  )4Q1q@P7PQQMQ 7:,iN^_o^p!qrr-	s0 t]D15EEEE D=>ABdJ))$,,7IZY-A-A-F-F-HZZK 0 0 23Mm+		{*N{m[jkxjy zM N 
 =T\\glmK #kk//1 
Uk) cU"XYdYiYiYkXlm) &%S)99 -cU2{|9 +%*C8H*H%. -cU2{|. K Rs   L)Lc                    t        d      S )Nz-Write this method in your subclass of `Tool`.)NotImplementedErrorrF   s      r)   rh   zTool.forward   s    "#RSSr+   Fsanitize_inputs_outputsc               L     j                   s j                          t        |      dk(  r>t        |      dk(  r0t        |d   t              r|d   }t         fd|D              rd}|}|rt        |i |\  }}  j                  |i |}|rt        | j                        }|S )Nr   r   c              3  :   K   | ]  }|j                   v   y wr#   )r@   )rQ   rV   r%   s     r)   rS   z Tool.__call__.<locals>.<genexpr>   s     B#3$++%Bs   rH   )
rE   setuplenrP   rZ   rb   r   rh   r   rA   )r%   rz   r&   r'   potential_kwargsoutputss   `     r)   __call__zTool.__call__   s    ""JJL t9>c&kQ.:d1gt3L#Aw B1ABB)"3TDVDLD&$,,//"/9I9IJGr+   c                    d| _         y)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.
        TNrD   r%   s    r)   r}   z
Tool.setup   s    
 #r+   c                H   | j                   j                  }t        |       j                  dk(  rt        | j                        j                  dd      }t        j                  |      }t        t                     }|j                  |       t        |j                        dkD  rG|j                  D cg c]  }d| 	 }}t        d| j                   ddj                  |      z         t        | j                        }t!        j"                  d	| d
| j                   dt%        j&                  t!        j"                  | j(                        j+                                dt-        | j.                         d| j0                   d      j+                         }ddldfd}	|j                  | j                  d      } |	|      }|j                  dd      j+                         }|dt!        j4                  |d      z   z  }nKt        |       j                  dv rt        d      t7        | j                          dt9        | t:              z   }t=        |      D 
ch c]  }
|
t>        j@                  vs|
 c}
dhz  }| j                  |tC        |      dS c c}w c c}
w )z*Returns a dictionary representing the tool
SimpleToolz@tool r   z- z!SimpleTool validation failed for :

zi
            from smolagents import Tool
            from typing import Any, Optional

            class z (Tool):
                name = "z "
                description = z
                inputs = z 
                output_type = "z"
            Nc                4    d}d }j                  |||       S )zEAdd 'self' as first argument to a function definition if not present.zdef forward\(((?!self)[^)]*)\)c                R    | j                  d      j                         }|rd| dS y)Nr   zdef forward(self, )zdef forward(self))groupstrip)matchr&   s     r)   replacementz<Tool.to_dict.<locals>.add_self_argument.<locals>.replacement  s-     ;;q>//1D!3D6;;.r+   )sub)source_codepatternr   res      r)   add_self_argumentz'Tool.to_dict.<locals>.add_self_argument  s"    ;/ vvg{K@@r+   rh   

    )SpaceToolWrapperLangChainToolWrapperGradioToolWrapperzhCannot save objects created with from_space, from_langchain or from_gradio, as this would create errors.z!from typing import Any, Optional
base_cls
smolagents)r>   coderequirements)r   r9   returnr9   )"rK   r^   rN   r   rh   replaceastparser   ri   visitr~   errorsrd   r>   jointextwrapdedentjsondumpsr?   r   reprr@   rA   r   indentr   r   r=   r   sysstdlib_module_namessorted)r%   
class_namer   forward_nodemethod_checkererrorr   forward_source_code	tool_coder   elr   r   s               @r)   to_dictzTool.to_dict   sg   ^^,,
:,.$T\\2::7BGK99[1L*351N  .>(()A-4B4I4IJ5Bug,JJ!$Edii[PS"TW[W`W`agWh"hij",T\\":  ,  $#zz(//$:J:J*K*Q*Q*STU Vt{{+, -  $ 0 01 2	 eg  
A #6"="=dii"S"34G"H"5"="=gr"J"P"P"R(//2Ev"NNNI Dz"" ' 
 !~  %T^^4<?QRVae?ffI%0%;arrI`I`?`aeqdrr		9f\FZ[[g Kb bs   5JJ6Jc                L    d|vrt        d       | j                  |d   fi |S )a(  
        Create tool from a dictionary representation.

        Args:
            tool_dict (`dict[str, Any]`): Dictionary representation of the tool.
            **kwargs: Additional keyword arguments to pass to the tool's constructor.

        Returns:
            `Tool`: Tool object.
        r   zATool dictionary must contain 'code' key with the tool source code)rd   	from_code)r-   	tool_dictr'   s      r)   	from_dictzTool.from_dict0  s3     "`aas}}Yv.9&99r+   c                "   t        |      }|j                  dd       | j                  || dz  | j                                |rI| j                  |dz  | j	                  |             | j                  |dz  | j                                yy)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 `{tool_file_name}.py` file containing the logic for your tool.
        If you pass `make_gradio_app=True`, this will also write:
        - an `app.py` file providing a UI for your tool when it is exported to a Space with `tool.push_to_hub()`
        - a `requirements.txt` containing the names of the modules used by your tool (as detected when inspecting its
          code)

        Args:
            output_dir (`str` or `Path`): The folder in which you want to save your tool.
            tool_file_name (`str`, *optional*): The file name in which you want to save your tool.
            make_gradio_app (`bool`, *optional*, defaults to True): Whether to also export a `requirements.txt` file and Gradio UI.
        T)parentsexist_okz.pyapp.py)tool_module_namerequirements.txtN)r   mkdir_write_file_get_tool_code_get_gradio_app_code_get_requirements)r%   
output_dirtool_file_namemake_gradio_appoutput_paths        r)   savez	Tool.save@  s    " :&$6.)9'==t?R?R?TU[83T5N5N`n5N5op[+==t?U?U?WX	 r+   c                *    |j                  |d       y)z-Writes content to a file with UTF-8 encoding.zutf-8)encodingN)
write_text)r%   	file_pathcontents      r)   r   zTool._write_file[  s    Ww7r+   c                j    | j                  |||      }| j                         }t        |||||d      S )a  
        Upload the tool to the Hub.

        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 to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
            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 to create a PR with the uploaded files or directly commit.
        space)repo_id
operationscommit_messagetoken	create_pr	repo_type)_initialize_hub_repo_prepare_hub_filesr   )r%   r   r   privater   r   	additionss          r)   push_to_hubzTool.push_to_hub_  sE    4 ++GUGD++-	 )
 	
r+   c                v    t        | ||ddd      }t        |j                  dddgid|       |j                  S )	z*Initialize repository on Hugging Face Hub.Tr   gradio)r   r   r   r   r   	space_sdktagsr   tool)r   r   )r   r   r   )r   r   r   repo_urls       r)   r   zTool._initialize_hub_repo  sN     
 	((6L&3I*JV]ejkr+   c                    t        d| j                         j                               t        d| j                         j                               t        d| j	                         j                               g}|S )zPrepare files for Hub commit.tool.py)path_in_repopath_or_fileobjr   r   )r
   r   encoder   r   )r%   r   s     r)   r   zTool._prepare_hub_files  sw     & $ 3 3 5 < < >
 % $ 9 9 ; B B D
 / $ 6 6 8 ? ? A
	" r+   c                (    | j                         d   S )zGet the tool's code.r   )r   r   s    r)   r   zTool._get_tool_code  s    ||~f%%r+   c           	     l    | j                   j                  }t        j                  d| d| d| d      S )zGet the Gradio app code.zG            from smolagents import launch_gradio_demo
            from z import z

            tool = z4()
            launch_gradio_demo(tool)
            )rK   r^   r   r   )r%   r   r   s      r)   r   zTool._get_gradio_app_code  sG    ^^,,
"#8J< 8<  	
 	
r+   c                F    dj                  | j                         d         S )zGet the requirements.r   r   )r   r   r   s    r)   r   zTool._get_requirements  s    yy788r+   c                X   |st        d      t        |d|d|j                  d      |j                  d      |j                  d      |j                  d      |j                  d      |j                  d	      

      }t        |      j	                         }t        j                  |f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 Space repo on the Hub where your tool is defined.
            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`).
            trust_remote_code(`str`, *optional*, defaults to False):
                This flags marks that you understand the risk of running remote code and that you trust this tool.
                If not setting this to True, loading the tool from Hub will fail.
            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.
        zlLoading a tool from Hub requires to acknowledge you trust its code: to do so, pass `trust_remote_code=True`.r   r   	cache_dirforce_downloadproxiesrevision	subfolderlocal_files_only)r   r   r   r   r   r   r   r   )rd   r   getr   	read_textr=   r   )r-   r   r   trust_remote_coder'   	tool_filer   s          r)   from_hubzTool.from_hub  s    B !~ 
 $jj-!::&67JJy)ZZ
+jj-#ZZ(:;
	 O--/	~~i2622r+   c                h   t        j                  d      }t        ||j                         t	        d t        j                  |t
        j                        D        d       }|t        d      t        |j                  t              s$t        j                  |j                        |_
         |di |S )Ndynamic_toolc              3  V   K   | ]!  \  }}t        |t              r|t        ur| # y wr#   )
issubclassr=   )rQ   _objs      r)   rS   z!Tool.from_code.<locals>.<genexpr>  s,      Asc4(S_ s   ')z#No Tool subclass found in the code.rH   )types
ModuleTypeexec__dict__nextrf   
getmembersisclassrd   rP   r@   rZ   r   literal_eval)r-   r   r'   module
tool_classs        r)   r   zTool.from_code  s    !!.1Y( %00I
 

 BCC*++T2 # 0 01B1B CJ#F##r+   c                T    ddl mm  G fddt              } || ||||      S )ae  
        Creates a [`Tool`] from a Space given its id on the Hub.

        Args:
            space_id (`str`):
                The id of the Space on the Hub.
            name (`str`):
                The name of the tool.
            description (`str`):
                The description of the tool.
            api_name (`str`, *optional*):
                The specific api_name to use, if the space has several tabs. If not precised, will default to the first available api.
            token (`str`, *optional*):
                Add your token to access private spaces or increase your GPU quotas.
        Returns:
            [`Tool`]:
                The Space, as a tool.

        Examples:
        ```py
        >>> image_generator = Tool.from_space(
        ...     space_id="black-forest-labs/FLUX.1-schnell",
        ...     name="image-generator",
        ...     description="Generate an image from a prompt"
        ... )
        >>> image = image_generator("Generate an image of a cool surfer in Tahiti")
        ```
        ```py
        >>> face_swapper = Tool.from_space(
        ...     "tuan2308/face-swap",
        ...     "face_swapper",
        ...     "Tool that puts the face shown on the first image on the second image. You can give it paths to images.",
        ... )
        >>> image = face_swapper('./aymeric.jpeg', './ruth.jpg')
        ```
        r   Clienthandle_filec                  F    e Zd ZdZ	 	 d	 	 	 	 	 	 	 	 	 d fdZfdZd Zy))Tool.from_space.<locals>.SpaceToolWrapperTNc                h   || _         || _         ||      | _        | j                  j                  dd      }t	        |t
              sJ |d   }|5t        |j                               d   }t        j                  d| d       || _
        	 ||   }i | _        |d   D ]0  }	|	d   d   }
|
dk(  rd}
|
|	d   d   |	d   d| j                  |	d   <   2 |d   d   d   }|dk(  rd| _        d| _        y |dk(  rd| _        d| _        y d| _        d| _        y # t        $ r t        d	|d
      w xY w)N)hf_tokenrZ   F)return_format
print_infonamed_endpointsr   zXSince `api_name` was not defined, it was automatically set to the first available API: `z`.z"Could not find specified api_name=z among available api names.rj   rN   r6   r7   python_typer?   parameter_has_default)rN   r?   rY   parameter_namereturns	componentImager3   Audior4   T)r>   r?   clientview_apirP   rZ   r`   ra   loggerwarningapi_nameKeyErrorr@   rA   rE   )r%   space_idr>   r?   r  r   	space_apispace_descriptionspace_description_api	parameterparameter_typeoutput_componentr	  s               r)   r,   z2Tool.from_space.<locals>.SpaceToolWrapper.__init__>  s    !	#. $X> KK00vRW0X	!)T222$-.?$@! ##$5$:$:$<=a@HNNrs{r||~ !)g,=h,G) !!6|!D I%.v%6v%>N%1). .'0'?'N$-.E$F@DKK	*: ;<	 $9#CA#F{#S #w.'.D$
 '+#	 &0'.D$ '+# (-D$&*#'   g"%HxkId#effgs   D D1c                   ddl m} ddlm} t	        ||      r>t        j                  dd      }|j                  |j                         |j                  }t	        |t              rt        j                  j                  |      s8t	        |t              r |j                         r|j                         s ||      r |      }|S )Nr   )is_http_url_like)r  .pngF)suffixdelete)gradio_client.utilsr'  	PIL.Imager  rP   tempfileNamedTemporaryFiler   r>   r9   ospathisfiler   existsis_file)r%   argr'  r  	temp_filer
  s        r)    sanitize_argument_for_predictionzJTool.from_space.<locals>.SpaceToolWrapper.sanitize_argument_for_predictionl  s    @+c5) ( ; ;6RW XIHHY^^,#..CS)bggnnS.A"3-#**,3;;=',%c*C
r+   c                   t        |      }t        |      D ]  \  }}| j                  |      ||<    |j                         D ]  \  }}| j                  |      ||<     | j                  j
                  |d| j                  i|}t        |t              st        |t               r)t        |d   t              rt        d|d   z         |d   }g d}g d}t        |t              r5t        |D 	cg c]  }	|j                  |	       c}	      rt        |      }|S t        |t              r3t        |D 	cg c]  }	|j                  |	       c}	      rt        |      }|S c c}	w c c}	w )Nr  r   z!The space returned this message: r   )r(  z.jpgz.jpegz.gifz.webp)z.mp3z.wavz.oggz.m4az.flac)r`   	enumerater6  r[   r  predictr  rP   tupler9   rd   r7   endswithr   r   )
r%   r&   r'   ir4  arg_nameoutputIMAGE_EXTENTIONSAUDIO_EXTENTIONSexts
             r)   rh   z1Tool.from_space.<locals>.SpaceToolWrapper.forward|  sX   Dz'o IFAs"CCCHDGI%+\\^ RMHc'+'L'LS'QF8$R -,,dUT]]UfUfe,
640H!&)S1()LvVWy)XYY#F $N #L fc*sTd3eSFOOC4H3e/f'/F   ,Vf5gsfooc6J5g1h'/F	 4f5gs   1E"6E'NN
r  r9   r>   r9   r?   r9   r  
str | Noner   rD  )r^   
__module____qualname__rT   r,   r6  rh   r  s   r)   r   r  ;  sQ    04- (,$(,+,+ ,+ !	,+
 %,+ ",+\ r+   r   )r  r>   r?   r  r   )gradio_clientr	  r
  r=   )r  r>   r?   r  r   r   r	  r
  s         @@r)   
from_spacezTool.from_space  s6    X 	6V	t V	p  #
 	
r+   c                >    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y)+Tool.from_gradio.<locals>.GradioToolWrapperc                   |j                   | _         |j                  | _        d| _        || _        t	         j
                  |j                        j                  j                               }|D ci c]  \  }}|t        |j                     dd c}}| _        | j                  j                  | _        y c c}}w )Nr/   r   )rN   r?   )r>   r?   rA   _gradio_toolr`   rg   runrj   r[   CONVERSION_DICT
annotationr@   rh   )r%   rM  	func_argsrV   rv   rf   s        r)   r,   z4Tool.from_gradio.<locals>.GradioToolWrapper.__init__  s    (--	#/#;#; #+ $0! !2!2!2<3C3C!D!O!O!U!U!WX	js\f\_afC/%2B2B"CTVWW  $0044s   4!B:Nr^   rE  rF  r,   )rf   s   r)   r   rK    s    	5r+   r   )rf   r=   )gradio_toolr   rf   s     @r)   from_gradiozTool.from_gradio  s!    
 	
	5 
	5 !--r+   c                0     G d dt               } ||       S )z;
        Creates a [`Tool`] from a langchain tool.
        c                      e Zd ZdZd Zd Zy)1Tool.from_langchain.<locals>.LangChainToolWrapperTc                >   |j                   j                         | _         |j                  | _        |j                  j	                         | _        | j
                  j                         D ]  }d|v r|j                  d       d|d<    d| _        || _	        d| _
        y )Ntitler   r?   r/   T)r>   lowerr?   r&   copyr@   valuespoprA   langchain_toolrE   )r%   _langchain_toolrp   s      r)   r,   z:Tool.from_langchain.<locals>.LangChainToolWrapper.__init__  s    +00668	#2#>#> -22779%)[[%7%7%9 6M-/%))'235M-06 $, &5#&*#r+   c                    |j                         }t        |      D ]A  \  }}|t        | j                        k  st	        t        | j                              }|||<   C | j                  j                  |      S r#   )r[  r8  r~   r@   r  iterr^  rN  )r%   r&   r'   
tool_inputindexargument	input_keys          r)   rh   z9Tool.from_langchain.<locals>.LangChainToolWrapper.forward  sk    #[[]
'0 9OE8s4;;//$(dkk):$;	08
9-9 **..z::r+   N)r^   rE  rF  rT   r,   rh   rH   r+   r)   r   rW    s    04-
+;r+   r   )r=   )r^  r   s     r)   from_langchainzTool.from_langchain  s    	;4 	;. $N33r+   rz   bool)r   rZ   )r   zdict[str, Any]r   z'Tool')r   T)r   z
str | Pathr   r9   r   rh  )r   r   r   r9   r   None)zUpload toolNNF)r   r9   r   r9   r   bool | Noner   bool | str | Noner   rh  r   r9   )r   r9   r   rk  r   rj  r   r9   )r   r`   )r   r9   )r   )r   r9   r   r9   rC   )r   r9   r   rD  r   rh  )r   r9   rB  rC  )r^   rE  rF  __doc____annotations__r,   rJ   r$   rh   r   r}   r   classmethodr   r   r   r   staticmethodr   r   r   r   r   r   r   rH  rT  rf  __classcell__rK   s   @r)   r=   r=   a   s   * I33$!L\T ?D (#?\B : :Y68 ,##'%
%
 %
 	%

 !%
 %
 
%
N    *&
9  !"'	4343 43  	43 43l $ $. 
  $ K
K
K
 K
 	K

 K
 K
Z . .( 4 4r+   r=   c                ^    	 ddl }|j                  |j                  |j                  |j
                  |j
                  |j
                  d} fd}t        j                   j                        |_	        g } j                  j                         D ]'  \  }}||d      } ||      }|j                  |       ) | j                     }	 |	d      }
|j                  |||
 j                   j                    j                  	      j#                          y# t        $ r t        d      w xY w)
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 (`Tool`): The tool for which to launch the demo.
    r   Nz<Gradio should be installed in order to launch a gradio demo.)r0   r3   r4   r/   r1   r2   c                      | ddi|S )Nrz   TrH   )r&   r'   r   s     r)   tool_forwardz(launch_gradio_demo.<locals>.tool_forward  s    TB4B6BBr+   rN   )labelOutput)fnr@   r   rY  r?   r  )r   ImportErrorCheckboxr  r  Textboxrf   rg   rh   __signature__r@   r[   appendrA   	Interfacer>   r?   launch)r   grTYPE_TO_COMPONENT_CLASS_MAPPINGrt  gradio_inputsro   input_detailsinput_gradio_component_classnew_componentoutput_gradio_component_classgradio_outputs   `          r)   launch_gradio_demor    s&   Z
 ;;**::**'#C ")!2!24<<!@LM%)[[%6%6%8 ,!
M'F}U[G\']$4:F]+,
 %DDDTDT$U!1AMLLii$$   fhC  ZXYYZs   D D,c                6    t        j                  | f|||d|S )a  
    Main function to quickly load a tool from the Hub.

    <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:
        repo_id (`str`):
            Space repo ID of a tool on the Hub.
        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`).
        trust_remote_code (`bool`, *optional*, defaults to False):
            This needs to be accepted in order to load a tool from Hub.
        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.
    )model_repo_idr   r   )r=   r   )r   r  r   r   r'   s        r)   	load_toolr    s1    B ==#+	
  r+   c                      fd}|S )z<
    A decorator that adds a description to a function.
    c                8    | _         | j                  | _        | S r#   )r?   r^   r>   )funcr?   s    r)   innerzadd_description.<locals>.inner-  s    &MM	r+   rH   )r?   r  s   ` r)   add_descriptionr  (  s    

 Lr+   c                  h    e Zd ZdZddZe	 	 d	 	 	 	 	 	 	 dd       Zee	 d		 	 	 	 	 d
d              Zy)ToolCollectionaP  
    Tool collections enable loading a collection of tools in the agent's toolbox.

    Collections can be loaded from a collection in the Hub or from an MCP server, see:
    - [`ToolCollection.from_hub`]
    - [`ToolCollection.from_mcp`]

    For example and usage, see: [`ToolCollection.from_hub`] and [`ToolCollection.from_mcp`]
    c                    || _         y r#   )tools)r%   r  s     r)   r,   zToolCollection.__init__@  s	    
r+   Nc                    t        ||      }|j                  D ch c]  }|j                  dk(  s|j                    }}|D cg c]  }t        j                  |||       }} | |      S c c}w c c}w )aS  Loads a tool collection from the Hub.

        it adds a collection of tools from all Spaces in the collection 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.
            trust_remote_code (bool, *optional*, defaults to False): Whether to trust the remote code.

        Returns:
            ToolCollection: A tool collection instance loaded with the tools.

        Example:
        ```py
        >>> from smolagents import ToolCollection, CodeAgent

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

        >>> agent.run("Please draw me a picture of rivers and lakes.")
        ```
        )r   r   )r   r[   	item_typeitem_idr=   r   )	r-   collection_slugr   r   _collectionitem_hub_repo_idsr   r  s	            r)   r   zToolCollection.from_hubC  sn    B %_EB2=2C2Ca$t~~Y`G`aaQ^_gw/@A__5z	 b_s   A-A-A2c              #  x  K   	 ddl m} ddlm} t        |t              rG|j                  d      }|!t        j                  dt               d}||d<   |d	vrt        d
| d      |st        d       || |             5 } | |       ddd       y# t        $ r t	        d      w xY w# 1 sw Y   yxY ww)a  Automatically load a tool collection from an MCP server.

        This method supports Stdio, Streamable HTTP, and legacy HTTP+SSE MCP servers. Look at the `server_parameters`
        argument for more details on how to connect to each MCP server.

        Note: a separate thread will be spawned to run an asyncio event loop handling
        the MCP server.

        Args:
            server_parameters (`mcp.StdioServerParameters` or `dict`):
                Configuration parameters to connect to the MCP server. This can be:

                - An instance of `mcp.StdioServerParameters` for connecting a Stdio MCP server via standard input/output using a subprocess.

                - A `dict` with at least:
                  - "url": URL of the server.
                  - "transport": Transport protocol to use, one of:
                    - "streamable-http": (recommended) Streamable HTTP transport.
                    - "sse": Legacy HTTP+SSE transport (deprecated).
                  If "transport" is omitted, the legacy "sse" transport is assumed (a deprecation warning will be issued).

                <Deprecated version="1.17.0">
                The HTTP+SSE transport is deprecated and future behavior will default to the Streamable HTTP transport.
                Please pass explicitly the "transport" key.
                </Deprecated>
            trust_remote_code (`bool`, *optional*, defaults to `False`):
                Whether to trust the execution of code from tools defined on the MCP server.
                This option should only be set to `True` if you trust the MCP server,
                and undertand the risks associated with running remote code on your local machine.
                If set to `False`, loading tools from MCP will fail.


        Returns:
            ToolCollection: A tool collection instance.

        Example with a Stdio MCP server:
        ```py
        >>> import os
        >>> from smolagents import ToolCollection, CodeAgent, InferenceClientModel
        >>> from mcp import StdioServerParameters

        >>> model = InferenceClientModel()

        >>> server_parameters = StdioServerParameters(
        >>>     command="uvx",
        >>>     args=["--quiet", "pubmedmcp@0.1.3"],
        >>>     env={"UV_PYTHON": "3.12", **os.environ},
        >>> )

        >>> with ToolCollection.from_mcp(server_parameters, trust_remote_code=True) as tool_collection:
        >>>     agent = CodeAgent(tools=[*tool_collection.tools], add_base_tools=True, model=model)
        >>>     agent.run("Please find a remedy for hangover.")
        ```

        Example with a Streamable HTTP MCP server:
        ```py
        >>> with ToolCollection.from_mcp({"url": "http://127.0.0.1:8000/mcp", "transport": "streamable-http"}, trust_remote_code=True) as tool_collection:
        >>>     agent = CodeAgent(tools=[*tool_collection.tools], add_base_tools=True, model=model)
        >>>     agent.run("Please find a remedy for hangover.")
        ```
        r   )MCPAdapt)SmolAgentsAdapterz[Please install 'mcp' extra to use ToolCollection.from_mcp: `pip install "smolagents[mcp]"`.	transportNa  Passing a dict as server_parameters without specifying the 'transport' key is deprecated. For now, it defaults to the legacy 'sse' (HTTP+SSE) transport, but this default will change to 'streamable-http' in version 1.20. Please add the 'transport' key explicitly. sse>   streamable-httpr  zUnsupported transport: z7. Supported transports are 'streamable-http' and 'sse'.zLoading tools from MCP requires you to acknowledge you trust the MCP server, as it will execute code on your local machine: pass `trust_remote_code=True`.)mcpadapt.corer  mcpadapt.smolagents_adapterr  rx  rP   rZ   r   warningswarnFutureWarningrd   )r-   server_parametersr   r  r  r  r  s          r)   from_mcpzToolCollection.from_mcpk  s     D	.E
 '.)--k:I h "	 "	1:!+. :: -i[8op  !`  '):)<= 	e*	 	1  	q 	0	 	s4   B:B A2B:B.	B:B++B:.B73B:)r  z
list[Tool]rC   )r  r9   r   rD  r   rh  r   'ToolCollection')F)r  z"'mcp.StdioServerParameters' | dictr   rh  r   r  )	r^   rE  rF  rl  r,   rn  r   r   r  rH   r+   r)   r  r  5  s      !"'	%% %  	%
 
% %N ^c\ B\W[\	\  \r+   r  c                l    t               d   }d|vr't        |d   d         dk(  rddi|d<   nt        d       G d	 d
t              }|d   |_        |d   |_        |d   d   |_        |d   d   |_        t                fd       }t        |      |_
        t        j                         }|j                  t        j                  dt        j                  j                        gt!        |j"                  j%                               z         }||j                  _        t        j(                         }dj+                  |j-                  d      dd       }t/        j0                  |      }dt3        |       dt/        j4                  |d       }t/        j0                  d|d    dt7        j8                  t/        j0                  |d         j;                                d|d   d    d|d   d    d	      t/        j4                  |d      z   }	|	|_        ||j                  _         |       }
|
S )a  
    Convert a function into an instance of a dynamically created Tool subclass.

    Args:
        tool_function (`Callable`): Function to convert into a Tool subclass.
            Should have type hints for each input and a type hint for the output.
            Should also have a docstring including the description of the function
            and an 'Args:' part where each argument is described.
    functionr   rj   rX   r   rN   r8   zKTool return type not found: make sure your function has a return type hint!c                      e Zd Zd Zy)tool.<locals>.SimpleToolc                    d| _         y )NTrD   r   s    r)   r,   z!tool.<locals>.SimpleTool.__init__  s
    "&Dr+   NrR  rH   r+   r)   r   r    s    	'r+   r   r>   r?   c                      | i |S r#   rH   )r&   r'   tool_functions     r)   wrapped_functionztool.<locals>.wrapped_function  s    d-f--r+   r%   )rj   r      Nzdef forwardr   r   z:
        class SimpleTool(Tool):
            name: str = "z!"
            description: str = z1
            inputs: dict[str, dict[str, str]] = z!
            output_type: str = "zW"

            def __init__(self):
                self.is_initialized = True

        )r   r~   r   r=   r>   r?   r@   rA   r   ro  rh   rf   rg   r   	ParameterPOSITIONAL_OR_KEYWORDr`   rj   r\  r{  	getsourcer   splitr   r   r9   r   r   r   r   
__source__)r  tool_json_schemar   r  signew_sigtool_sourcetool_source_bodyforward_method_sourceclass_sourcesimple_tools   `          r)   r   r     sa    '}5jA''-l;<A*0&)9X&*] 'T '
 'v.JO-m<J(6|DJ-h7?J
=. . &&67J 

M
*Ckk%%fg.?.?.U.UVWZ^_b_m_m_t_t_vZww  G (/J$ ##M2Kyy!2!24!8!<='78)#g,s8??K[]c;d:ef 	 *623 4  $

8??;KM;Z+[+a+a+c de f11A,1OP\1]0^ _!!1(!;F!C D E	
 
	 ///
8	9  )J$9J!,Kr+   c                       e Zd ZdZdZdZdZdZdZdZ	de
iZe
ZdZ	 	 	 	 	 	 	 d fd	Z fdZd	 Zd
 Zd ZddddZ xZS )PipelineToolaW	  
    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 [`transformers.AutoProcessor`]) -- The class to use to load the
      pre-processor
    - **post_processor_class** (`type`, *optional*, defaults to [`transformers.AutoProcessor`]) -- The class to use to load the
      post-processor (when different from the pre-processor).

    Args:
        model (`str` or [`transformers.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promptTc                `   t        d      rt        d      st        d      |#| j                  t        d      | j                  }||}|| _        || _        || _        || _        || _        |i n|| _	        ||| j                  d<   || _
        || j                  d<   t        	| 1          y )N
acceleratetorchzcPlease install 'transformers' extra to use a PipelineTool: `pip install 'smolagents[transformers]'`zHThis tool does not implement a default checkpoint, you need to pass one.
device_mapr   )r   ModuleNotFoundErrordefault_checkpointrd   modelpre_processorpost_processordevicer  model_kwargs
hub_kwargsrI   r,   )
r%   r  r  r  r  r  r  r   r  rK   s
            r)   r,   zPipelineTool.__init__I  s     %\2:OPW:X%u  =&&. !kll++E !M
*,$"."6BL!.8Dl+$#( r+   c                   t        | j                  t              rO| j                  ddlm} || _         | j                  j                  | j                  fi | j                  | _        t        | j                  t              rB | j                  j                  | j                  fi | j                  | j                  | _        | j                  | j                  | _        nit        | j                  t              rO| j                  ddlm} || _         | j                  j                  | j                  fi | j                  | _        | j                  ^| j                  6t        | j                  j                   j#                               d   | _        nddlm}  |       j(                  | _        | j                  %| j                  j+                  | j                         t,        | ]          y)z^
        Instantiates the `pre_processor`, `model` and `post_processor` if necessary.
        Nr   )AutoProcessor)PartialState)rP   r  r9   pre_processor_classtransformersr  from_pretrainedr  r  model_classr  r  post_processor_classr  r  r`   hf_device_mapr\  r  r  default_devicetorI   r}   )r%   r  r  rK   s      r)   r}   zPipelineTool.setupm  s{    d((#.''/6+8(!I!9!9!I!I$J\J\!p`d`o`o!pDdjj#&9))99$**mHYHYm]a]l]lmDJ&"&"4"4D++S1((06,9)"K$";";"K"KDL_L_"scgcrcr"sD;;*"4::#;#;#B#B#DEaH3*n;;??"JJMM$++&r+   c                $    | j                  |      S )zQ
        Uses the `pre_processor` to prepare the inputs for the `model`.
        )r  )r%   
raw_inputss     r)   r   zPipelineTool.encode  s     !!*--r+   c                z    ddl }|j                         5   | j                  di |cddd       S # 1 sw Y   yxY w)z7
        Sends the inputs through the `model`.
        r   NrH   )r  no_gradr  )r%   r@   r  s      r)   rh   zPipelineTool.forward  s6     	]]_ 	(4::''	( 	( 	(s   1:c                $    | j                  |      S )zG
        Uses the `post_processor` to decode the model output.
        )r  )r%   r   s     r)   decodezPipelineTool.decode  s     ""7++r+   Fry   c               J   dd l }ddlm} | j                  s| j	                          |rt        |i |\  }} | j                  |i |}|j                         D ci c]  \  }}t        ||j                        s||! }	}}|j                         D ci c]  \  }}t        ||j                        r||! }
}} ||	| j                        }| j                  i ||
      } ||d      }| j                  |      }|rt        || j                        }|S c c}}w c c}}w )Nr   )send_to_devicecpu)r  accelerate.utilsr  rE   r}   r   r   r[   rP   Tensorr  rh   r  r   rA   )r%   rz   r&   r'   r  r  encoded_inputskvtensor_inputsnon_tensor_inputsr   decoded_outputss                r)   r   zPipelineTool.__call__  s   3""JJL"3TDVDLD&$d5f5*8*>*>*@`$!QJqRWR^R^D_A``.<.B.B.DhdaJWXZ_ZfZfLgQThh't{{C,,F.F4EFG %0++g."7IYIYZO ahs   D;DD5D)NNNNNNNrg  )r^   rE  rF  rl  r  r  r  r  r?   r>   r9   r@   rA   rT   r,   r}   r   rh   r  r   rp  rq  s   @r)   r  r    s    #J K+KD_FK(,% "H"H.(, ?D  r+   r  c                   g }| j                         D ]w  }t        |j                  d       t        |t              }|j                  dd      }|d|j                   d|j                  j                   dz  }|j                  |       y d	j                  t        D cg c]  }d
| 	 c}      }|t        j                  d      z  }|dj                  |      z  }|S c c}w )NF)check_importsr   z!from smolagents.tools import Toolr   r   z = z()
r   zimport z
    from typing import Any

    class Tool:
        def __call__(self, *args, **kwargs):
            return self.forward(*args, **kwargs)

        def forward(self, *args, **kwargs):
            pass # to be implemented in child class
    )r\  r   rK   r   r=   r   r>   r^   r|  r   r   r   r   )r  
tool_codesr   r   r  tool_definition_codes         r)   get_tools_definition_coder    s    J % uE&td;	%%&I2N	tDII;c$..*A*A)B$GG	)$%  99G[%\Vx&8%\]HOO		  FKK
33 &]s    C!c                   t        |t              r|j                         D ]  \  }}|| j                  vrd| dc S t	        t        |            d   }| j                  |   d   }| j                  |   j                  dd      }t        |t              r||k7  szn||vs|dk7  s|dk(  r|rd| d| d	| j                  |   d    d
c S  | j                  j                         D ]&  \  }}|j                  dd      }||vs|r d| dc S  y t        | j                  j                               d   d   }t	        t        |            d   |k7  r!|dk(  sdt        |      j                   d	| d
S y )Nz	Argument z# is not in the tool's input schema.rN   rY   Fr7   r8   z has type 'z' but should be 'z'.z is required.r   zArgument has type ')rP   rZ   r[   r@   r   rN   r   r9   r`   r\  r^   )	r   	argumentsrV   rv   actual_typerm   expected_type_is_nullableschemakey_is_nullables	            r)   validate_tool_argumentsr    s   )T"#//+ 	nJC$++%"3%'JKK/U<VDK KK,V4M(,C(8(<(<Z(O% 2<M31O-U`huUu!U*$.3L"3%{;-?PQUQ\Q\]`QabhQiPjjlmm	n   ;;,,. 	6KC$jjU;O)#O"3%}55	6 T[[//1215f= i1&9]JS`diSi(i)A)A(BBSTaSbbdeer+   )rc   r=   r   r  r  r  )r   r=   )NNF)r  rD  r   rD  r   rh  )r  r   r   r=   )r  zdict[str, Tool]r   r9   )r   r=   r  r	   r   rD  )C
__future__r   r   rf   r   loggingr/  r   r-  r   r   r  collections.abcr   
contextlibr   	functoolsr   pathlibr   typingr   r	   huggingface_hubr
   r   r   r   r   r   _function_type_hints_utilsr   r   r   r   r   agent_typesr   r   r   r   tool_validationr   r   utilsr   r   r   r   r    mcp	getLoggerr^   r  r.   rc   rO  r=   r  r  r  r  r   r  r  r  __all__rH   r+   r)   <module>r     s  " # 
    	 
     $ %   %   e d D   
		8	$	  #9xHl	4 l	4^+` !%#	'' ' 	'T
T TnJZa4 aH 4<r+   