
    ~h                        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 d dlmZ d dlmZ d dlmZ d dlmZmZmZ d dlmZ d	d
lmZ d	dlmZmZ  ej:                  e      Z G d de       Z! e"e      D  ci c],  }  e# e$e|       e%      r e& e$e|       e'      r
|  e$e|       . c} Z(dZ)dZ*dZ+d Z,ddZ-i de,de#de.de/de0de1de2de3de4de5de6de7dejp                  d ejr                  d!ejt                  d"ejv                  d#ejx                  i d$ejz                  d%ej|                  d&ej~                  d'ej                  d(ej                  d)ej                  d*ej                  d+ej                  d,eEd-ej                  d.eGd/eHd0eId1eJd2eKd3eLd4eMi d5eNd6eOd7ePd8eQd9eRd:eSd;eTd<eUd=eVd>eWd?eXd@eYdAe-dBeZdCe[dDe&dEe%dFe\iZ]g dGZ^g dHZ_ddIedJe5e2ef   dKe4e2   fdLZ`dMefdNZae]efdMedJe5e2ef   dKe4e2   fdOZb G dP dQ      Zc G dR dSed      Ze G dT dUed      Zf G dV dWed      ZgdX ZhdYe2dZe2fd[ZidKe4e2   dZe5e2ef   fd\Zjd]e2dKe4e2   dZe1fd^Zkd_e j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZefdbZmd_e j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZefdcZodde j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZefdeZqdfe j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZdfdgZsdhe j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZefdiZudhe j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZefdjZvdke j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZe%fdlZxdme j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZefdnZzd_e j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZefdoZ|dpe j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZefdqZ~dre j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZefdsZdte j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZefduZdve j                  dwed`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZdfdxZdye j
                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZefdzZd{e j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZefd|Zd}e j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZefd~Zde j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZe1ez  fdZde j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZefdZde j                   d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZefdZde j$                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZe4e   fdZde j(                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZe3e   fdZde j,                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZdfdZde j0                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZdfdZde j4                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZdfdZde j8                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZdfdZddZd Zde j@                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZe5eef   fdZde jD                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   dZdfdZeaefd_e j                  d`e5e2ef   dJe5e2ef   dae5e2ef   dKe4e2   f
d       Z G d ded      Zdddee)fdYe2dJe5e2ef   dz  dae5e2ef   dz  d`e5e2ef   dz  dKe4e2   de0fdZe G d d             Z G d d      Z G d de      ZddgZyc c} w )    N)CallableMapping)	dataclass)wraps)import_module)	find_spec)BuiltinFunctionTypeFunctionType
ModuleType)Any   )Tool)BASE_BUILTIN_MODULEStruncate_contentc                       e Zd ZdZy)InterpreterErrorz
    An error raised when the interpreter cannot evaluate a Python expression, due to syntax error or unsupported
    operations.
    N)__name__
__module____qualname____doc__     \/opt/mcp/mcp-sentiment/venv/lib/python3.12/site-packages/smolagents/local_python_executor.pyr   r   '   s    
 	r   r   iP  i i@B c                       y Nr   )argss    r   custom_printr   ;   s    r   c                 |    |j                  d      r|j                  d      rt        d|       t        | ||      S N__z&Forbidden access to dunder attribute: )
startswithendswithr   getattr)objnamedefaults      r   nodunder_getattrr'   ?   s;    tt!4!GvNOO3g&&r   print
isinstancerangefloatintboolstrsetlistdicttupleroundceilfloorlogexpsincostanasinacosatanatan2degreesradianspowsqrtlensummaxminabs	enumeratezipreversedsortedallanymapfilterordchrnextiterdivmodcallabler#   hasattrsetattr
issubclasstypecomplex)
builtinsiomultiprocessingospathlibptyshutilsocket
subprocesssys)	zbuiltins.compilezbuiltins.evalzbuiltins.execzbuiltins.globalszbuiltins.localszbuiltins.__import__zos.popenz	os.systemzposix.systemresultstatic_toolsauthorized_importsc                    t        | t              r/t        | j                  |      st	        d| j                         yt        | t
              r2| j                  d      r!t        | d   |      st	        d| d          yt        | t        t        f      rUt        D ]K  }|j                  dd      \  }}|||vs| j                  |k(  s/| j                  |k(  s?t	        d|        yy)aZ  
    Checks if a result is safer according to authorized imports and static tools.

    Args:
        result (Any): The result to check.
        static_tools (dict[str, Callable]): Dictionary of static tools.
        authorized_imports (list[str]): List of authorized imports.

    Raises:
        InterpreterError: If the result is not safe
    zForbidden access to module: __spec__r   .r   NzForbidden access to function: )r)   r   check_import_authorizedr   r   r1   getr
   r	   DANGEROUS_FUNCTIONSrsplitr   )re   rf   rg   qualified_function_namemodule_namefunction_names         r   check_safer_resultrr      s     &*%&v8JK"%A&//AR#STT L	FD	!fjj&<&vj'9;MN"%A&BTAU#VWW O	F\+>?	@': 	Y#)@)G)GQ)O&K%l)JOO}4%%4&)G'WXX	Y 
Ar   funcc                 :     t               t        f fd	       }|S )a   
    Decorator to enhance the security of an evaluation function by checking its return value.

    Args:
        func (Callable): Evaluation function to be made safer.

    Returns:
        Callable: Safer evaluation function with return value check.
    c                 <     | ||||      }t        |||       |S )N)rg   rr   )
expressionstaterf   custom_toolsrg   re   rs   s         r   _check_returnz!safer_eval.<locals>._check_return   s*     j%|Xjk6<1CDr   )r   r   )rs   rz   s   ` r   
safer_evalr{      s(     4[ 0	 	 r   c                 Z     t         t              r S t                fd       }|S )ao  
    Decorator to enhance the security of a function call by checking its return value.

    Args:
        func (Callable): Function to be made safer.
        static_tools (dict[str, Callable]): Dictionary of static tools.
        authorized_imports (list[str]): List of authorized imports.

    Returns:
        Callable: Safer function with return value check.
    c                  2     | i |}t        |       |S r   rv   )r   kwargsre   rg   rs   rf   s      r   rz   z!safer_func.<locals>._check_return   s$    t&v&6<1CDr   )r)   rY   r   )rs   rf   rg   rz   s   ``` r   
safer_funcr      s2    " $
4[ 
 r   c                   0    e Zd Zd Zd Zd Zd Zd Zd Zy)PrintContainerc                     d| _         y )N valueselfs    r   __init__zPrintContainer.__init__   s	    
r   c                 0    | xj                   |z  c_         | S r   r   )r   texts     r   appendzPrintContainer.append   s    

d
r   c                 B    | xj                   t        |      z  c_         | S )zImplements the += operator)r   r.   )r   others     r   __iadd__zPrintContainer.__iadd__   s    

c%j 
r   c                     | j                   S )zString representationr   r   s    r   __str__zPrintContainer.__str__   s    zzr   c                 "    d| j                    dS )zRepresentation for debuggingzPrintContainer()r   r   s    r   __repr__zPrintContainer.__repr__   s     A..r   c                 ,    t        | j                        S )z!Implements len() function support)rC   r   r   s    r   __len__zPrintContainer.__len__   s    4::r   N)	r   r   r   r   r   r   r   r   r   r   r   r   r   r      s     
/r   r   c                       e Zd Zy)BreakExceptionNr   r   r   r   r   r   r   r         r   r   c                       e Zd Zy)ContinueExceptionNr   r   r   r   r   r   	  r   r   r   c                       e Zd Zd Zy)ReturnExceptionc                     || _         y r   r   r   r   s     r   r   zReturnException.__init__  	    
r   Nr   r   r   r   r   r   r   r   r         r   r   c                 j    t        | t              r| S t        | d      rt        |       S t        d      )N__iter__zObject is not iterable)r)   r0   rV   r   )r$   s    r   get_iterabler     s1    #t
	j	!Cy788r   codereturnc                     d}d| vst        j                  ||       s| S d}t        j                  |d|       } d}t        j                  |d|       } | S )a  
    Sometimes an LLM can try to assign a variable to final_answer, which would break the final_answer() tool.
    This function fixes this behaviour by replacing variable assignments to final_answer with final_answer_variable,
    while preserving function calls to final_answer().
    z (?<!\.)(?<!\w)\bfinal_answer\s*=zfinal_answer(z$(?<!\.)(?<!\w)(\bfinal_answer)(\s*=)zfinal_answer_variable\2z)(?<!\.)(?<!\w)(\bfinal_answer\b)(?!\s*\()final_answer_variable)researchsub)r   assignment_patternassignment_regexvariable_regexs       r   fix_final_answer_coder     sc     =d""))4F*M 
 ?66"$>ED
 BN66."94@DKr   c                 h    i }| D ]*  }|j                  d      }|}|D ]  }||vri ||<   ||   } , |S )Nrj   )split)rg   treeimport_pathpartscurrentparts         r   build_import_treer   7  s[    D) $!!#& 	$D7" "dmG	$$ Kr   import_to_checkc                 h    t        |      }| j                  d      D ]  }d|v r y||vr y||   } y)Nrj   *TF)r   r   )r   rg   current_noder   s       r   rk   rk   C  sL    $%78L%%c* *,|##D)* r   rw   rx   ry   c                     | j                   j                  d      r3| j                   j                  d      rt        d| j                          t	        | j
                  ||||      }t        || j                         S r   )attrr!   r"   r   evaluate_astr   r#   )rw   rx   rf   ry   rg   r   s         r   evaluate_attributer   N  si     !!$'JOO,D,DT,J!G
GXYZZ))5,N`aE5*//**r   c                    t        | j                  ||||      }t        | j                  t        j
                        r| S t        | j                  t        j                        r|S t        | j                  t        j                        r| S t        | j                  t        j                        r| S t        d| j                  j                  j                   d      )NzUnary operation  is not supported.)r   operandr)   opastUSubUAddNotInvertr   	__class__r   )rw   rx   rf   ry   rg   r   s         r   evaluate_unaryopr   [  s     :--ulLRdeG*--*x	JMM388	,	JMM377	+{	JMM3::	.x!1*--2I2I2R2R1SSefggr   lambda_expressionc                       j                   j                   D cg c]  }|j                   c}dt        dt        f fd}|S c c}w )Nvaluesr   c                      j                         }t        |       D ]
  \  }}|||<    t        j                  |	      S r   )copyrI   r   body)
r   	new_stateargr   r   rg   ry   r   rx   rf   s
       r   lambda_funcz$evaluate_lambda.<locals>.lambda_funcx  sS    JJL	dF+ 	#JC"IcN	#""
 	
r   )r   r   r   )r   rx   rf   ry   rg   r   r   r   s   `````  @r   evaluate_lambdar   o  sJ      155::;CGG;D

S 

S 

 

  <s   A
while_loopc                 (   d}t        | j                  ||||      r\| j                  D ]  }	 t        |||||        |dz  }|t
        kD  rt        dt
         d      t        | j                  ||||      r\y # t        $ r Y  y t        $ r Y  Sw xY w)Nr   r   zMaximum number of z" iterations in While loop exceeded)r   testr   r   r   MAX_WHILE_ITERATIONSr   )r   rx   rf   ry   rg   
iterationsnodes          r   evaluate_whiler     s     J
z|\K]
^OO 	DT5,FXY	 	a
,,"%78L7MMo#pqq z|\K]
^  " $ s   A99	BBBfunc_defc                      t        j                         }dt        dt        dt        f fd} |_        ||_         j
                  |_        |S )Nr   r~   r   c            
      2   j                         }j                  j                  D cg c]  }|j                   }}j                  j                  D cg c]  }t	        |       }}t        t        |t        |       d  |            }t        ||       D ]
  \  }}	|	||<    |j                         D ]
  \  }}	|	||<    j                  j                  r%j                  j                  j                  }
| ||
<   j                  j                  r%j                  j                  j                  }|||<   |j                         D ]  \  }}	||vs|	||<    j                  j                  rBj                  j                  d   j                  dk(  r| r| d   |d<   | d   j                  |d<   d }	 j                  D ]  }t	        ||      } 	 j                  dk(  ry |S c c}w c c}w # t        $ r}|j                  }Y d }~6d }~ww xY w)Nr   r   r   r   )r   r   r   defaultsr   r1   rI   rC   itemsvarargkwargr   r   r   r   r%   )r   r~   
func_stater   	arg_namesddefault_valuesr   r%   r   vararg_name
kwarg_namere   stmterg   ry   r   rx   rf   s                  r   new_funcz!create_function.<locals>.new_func  s   ZZ\
(0(:(:;SWW;	;\d\i\i\r\r
WXLE<?QR
 

 Is>':&:&<=~NO y$/ 	%KD%$Jt	% "<<> 	%KD%$Jt	% =="--..22K&*J{#==!,,00J%+Jz" $>>+ 	)KD%:%#(
4 	)
 ==(--"4"4Q"7";";v"E%)!W
6"*.q'*;*;
;'	  h%dJlTfgh
 ==J&] <
N  	WWF	s#   G-G2: G7 7	H HH)r   unparser   __ast__
__source__r%   r   )r   rx   rf   ry   rg   source_coder   s   `````  r   create_functionr     sV     ++h'K0 0s 0s 0 0f  H%H HOr   c                 X    t        | ||||      || j                  <   || j                     S r   )r   r%   )r   rx   rf   ry   rg   s        r   evaluate_function_defr     s0     #2(E<Q]_q"rL&&r   	class_defc           
      |   | j                   }| j                  D cg c]  }t        |||||       }}i }| j                  D ]W  }	t	        |	t
        j                        rt        |	||||      ||	j                   <   ;t	        |	t
        j                        r||	j                  rt        |	j                  ||||      }
|	j                  }t	        |t
        j                        rUt        |	j                  ||||      }||j                  di       |j                  <   |	j                  s
||j                  <   t	        |t
        j                        r@t        |j                  ||||      }|	j                  s7t        ||j                   
       Pt	        |t
        j"                        rGt        |j                  ||||      }t        |j$                  ||||      }|	j                  s
||<   t'        dt)        |      j*                         t	        |	t
        j,                        rt        |	j                  ||||      }
|	j.                  D ]w  }t	        |t
        j                        r|
||j                  <   -t	        |t
        j                        sHt        |j                  ||||      }t        ||j                   |
       y t	        |	t
        j0                        rt	        |	t
        j2                        ru|	| j                  d   k(  rct	        |	j                  t
        j4                        r?t	        |	j                  j                  t6              r|	j                  j                  |d<   8t'        d|	j8                  j*                          t)        |t;        |      |      }|||<   |S c c}w )N__annotations__z,Unsupported AnnAssign target in class body: r   r   z%Unsupported statement in class body: )r%   basesr   r   r)   r   FunctionDef	AnnAssignr   targetName
annotation
setdefaultid	AttributerW   r   	Subscriptslicer   rY   r   AssigntargetsPassExprConstantr.   r   r2   )r   rx   rf   ry   rg   
class_namebaser   
class_dictr   r   r   r   r$   	containerindex	new_classs                    r   evaluate_class_defr    s    Jclcrcrs[_\$|\CUVsEsJ 1fdCOO,$0ulLZl$mJtyy!cmm,zz$TZZlTfg[[F&#((+)$//5,P\^pq
JT
%%&7<VYYG::,1Jvyy)FCMM2"6<<\<Ykl::Ce4FCMM2(z<Q]_qr	$V\\5,Vhi::',Ie$&)UVZ[aVbVkVkUl'mnncjj) UL,PbcE,, 5fchh/,1Jvyy)6&v||Z|]opCCe45 chh'tSXX&	q))4::s||44::++S1 %)JJ$4$4Jy!"%J4>>KbKbJc#deec1ff Zuz:I!E*q ts   N9	annassignc                     | j                   r5t        | j                   ||||      }t        | j                  |||||       |S y r   )r   r   	set_valuer   )r  rx   rf   ry   rg   r   s         r   evaluate_annassignr  .  sC     Y__e\<Qcd)""E5,N`ar   c                    dt         j                  dt        ffd | j                        }t	        | j
                        }t        | j                  t         j                        r=t        |t              r&t        |t              st        d| d      ||z  }n||z  }nt        | j                  t         j                        r||z  }nt        | j                  t         j                        r||z  }nt        | j                  t         j                        r||z  }n~t        | j                  t         j                        r||z  }nSt        | j                  t         j                        r||z  }n(t        | j                  t         j                         r||z  }nt        | j                  t         j"                        r||z  }nt        | j                  t         j$                        r||z  }nt        | j                  t         j&                        r||z  }nt        | j                  t         j(                        r||z  }nVt        | j                  t         j*                        r||z  }n,t        dt-        | j                        j.                   d      t1        | j                  |       |S )Nr   r   c                    t        | t        j                        rj                  | j                  d      S t        | t        j
                        r7t        | j                        }t        | j                        }||   S t        | t        j                        r/t        | j                        }t        || j                        S t        | t        j                        rt        fd| j                  D              S t        | t        j                        r | j                  D cg c]
  } |       c}S t!        d      c c}w )Nr   c              3   .   K   | ]  } |        y wr   r   ).0eltget_current_values     r   	<genexpr>z@evaluate_augassign.<locals>.get_current_value.<locals>.<genexpr>Q  s     GC*3/Gs   z3AugAssign not supported for {type(target)} targets.)r)   r   r   rl   r   r   r   r   r  r   r#   r   Tupler2   eltsListr   )	r   r$   keyr  rg   ry   r  rx   rf   s	       r   r  z-evaluate_augassign.<locals>.get_current_valueF  s    fchh'99VYY**.v||UL,PbcCv||UL,PbcCs8O.v||UL,PbcC3,,		*G6;;GGG)6<kkBs%c*BB"#XYY Cs   2EzCannot add non-list value z to a list.z
Operation r   )r   ASTr   r   r   r   r)   r   Addr0   r   SubMultDivModPowFloorDivBitAndBitOrBitXorLShiftRShiftrY   r   r  )rw   rx   rf   ry   rg   current_valuevalue_to_addr  s    ````  @r   evaluate_augassignr,  ?  s!   Z#'' Zc Z Z" &j&7&78M
 0 0%|UghL*--)mT*lD1&)CL>Q\']^^\)M\)M	JMM377	+%	JMM388	,%	JMM377	+%	JMM377	+%	JMM377	+,&	JMM3<<	0,&	JMM3::	.%	JMM399	-%	JMM3::	.%	JMM3::	.,&	JMM3::	.,&D,?,H,H+II[\]]  r   r   c                     t        | j                  t        j                        rd nd }| j                  D ]  }t        |||||      } ||      s|c S  S )Nc                     |  S r   r   xs    r   <lambda>z!evaluate_boolop.<locals>.<lambda>  s    A r   c                     t        |       S r   )r-   r/  s    r   r1  z!evaluate_boolop.<locals>.<lambda>  s    _cde_f r   )r)   r   r   Andr   r   )r   rx   rf   ry   rg   is_short_circuit_valuer   re   s           r   evaluate_boolopr5    sX     3=TWWcgg2NoUf eUL,HZ[!&)M	 Mr   binopc                    t        | j                  ||||      }t        | j                  ||||      }t        | j                  t
        j                        r||z   S t        | j                  t
        j                        r||z
  S t        | j                  t
        j                        r||z  S t        | j                  t
        j                        r||z  S t        | j                  t
        j                        r||z  S t        | j                  t
        j                        r||z  S t        | j                  t
        j                        r||z  S t        | j                  t
        j                        r||z  S t        | j                  t
        j                        r||z  S t        | j                  t
        j                        r||z  S t        | j                  t
        j                         r||z  S t        | j                  t
        j"                        r||z	  S t%        dt'        | j                        j(                   d      )NzBinary operation z is not implemented.)r   leftrightr)   r   r   r  r  r   r!  r"  r#  r$  r%  r&  r'  r(  r)  NotImplementedErrorrY   r   )r6  rx   rf   ry   rg   left_val	right_vals          r   evaluate_binopr=    s    EJJ|\K]^HU[[%|M_`I %((CGG$)##	EHHcgg	&)##	EHHchh	')##	EHHcgg	&)##	EHHcgg	&)##	EHHcgg	&""	EHHcll	+9$$	EHHcjj	))##	EHHcii	()##	EHHcjj	))##	EHHcjj	)9$$	EHHcjj	)9$$!$5d588n6M6M5NNb"cddr   assignc           	         t        | j                  ||||      }t        | j                        dk(  r!| j                  d   }t	        ||||||       |S g }| j                  D ]?  }t        |t        j                        r|j                  |       /|j                  |       A t        | j                  |      D ]  \  }}	t	        ||	||||        |S )Nr   r   )r   r   rC   r  r  r)   r   Starredextendr   rI   )
r>  rx   rf   ry   rg   re   r   expanded_valuestgtvals
             r   evaluate_assignrE    s     &,,|\K]^F
6>>a"&&%|EWX M >> 	/C#s{{+&&v.&&v.		/ FNNO< 	WHCc3|\CUV	WMr   r   r   c           	      `   t        | t        j                        r7| j                  |v rt	        d| j                   d      ||| j                  <   y t        | t        j
                        rt        |t              s9t        |d      r"t        |t        t        f      st        |      }nt	        d      t        | j                        t        |      k7  rt	        d      t        | j                        D ]  \  }}t        |||   ||||        y t        | t        j                        r8t        | j                   ||||      }t        | j"                  ||||      }	|||	<   y t        | t        j$                        r1t        | j                   ||||      }t'        || j(                  |       y y )NzCannot assign to name 'z,': doing this would erase the existing tool!r   zCannot unpack non-tuple valuez!Cannot unpack tuple of wrong size)r)   r   r   r   r   r  r2   rV   r.   bytesrC   r  rH   r  r   r   r   r  r   rW   r   )
r   r   rx   rf   ry   rg   ielemr$   r  s
             r   r  r    s_    &#((#99$"%<VYYKGs#tuu fii	FCII	&%'uj)*US%L2Qe&'FGGv{{s5z)"#FGG - 	]GAtdE!He\<I[\	]	FCMM	*6<<lL^_6<<lL^_C	FCMM	*6<<lL^_V[[%( 
+r   callc                    t        | j                  t        j                  t        j                  t        j
                  t        j                  t        j                  f      st        d| j                   d      d\  }}t        | j                  t        j                        rt        | j                  ||||      }nt        | j                  t        j                        rt        | j                  ||||      }nwt        | j                  t        j
                        rct        | j                  j                  ||||      }| j                  j                  }t        ||      st        d| d|       t        ||      }nt        | j                  t        j                        ri| j                  j                  }||v r||   }n||v r||   }n||v r||   }n|t        v r
t        |   }nt        d| j                  j                   d      t        | j                  t        j                        r?t        | j                  ||||      }t!        |      st        d| j                   d      d }g }| j"                  D ]c  }	t        |	t        j$                        r)|j'                  t        |	j                  ||||             F|j)                  t        |	||||             e | j*                  D 
ci c]&  }
|
j,                  t        |
j                  ||||      ( }}
|dk(  r|s%d	|v rd
|v rt/        |d	   |d
         S t        d      |d   }t        |t0              st        d      t3        |      dk(  rt/        |      S t3        |      dk(  r|d   }t/        ||      S t        d      |dk(  r.|dxx   dj5                  t7        t8        |            dz   z  cc<   y t;        j<                  |      t>        k(  r6t;        j@                  |      r!||jC                         vrt        d| d       ||i |S c c}
w )Nz This is not a correct function: z).NNzObject  has no attribute z Forbidden function evaluation: 'zU' is not among the explicitly allowed tools or defined/imported in the preceding codesuperr   r   z#super() needs at least one argumentr   zsuper() argument 1 must be typer      z!super() takes at most 2 argumentsr(   _print_outputs 
zYInvoking a builtin function that has not been explicitly added as a tool is not allowed ()"r)   rs   r   CallLambdar   r   r   r   r   r   r   rV   r#   r   ERRORSrU   r   r@  rA  r   keywordsr   rN  rY   rC   joinrN   r.   inspect	getmoduler[   	isbuiltinr   )rJ  rx   rf   ry   rg   rs   	func_namer$   r   r   keywordr~   clsinstances                 r   evaluate_callr_    s    dii#((CJJsxxQTQ^Q^!_`!A$))BOPP OD)$))SXX&DIIulLJ\]	DIIszz	*DIIulLJ\]	DIIs}}	-499??E<OabIINN	sI&"WSE1CI;#OPPsI&	DIIsxx	(IILL	#D,&	*D,&	*D& )$D"2499<<.  AV  W  
DIIs}}	-DIIulLJ\]~"%Edii[PR#STT	Dyy bc3;;'KKSYY|\SefgKKS%|M_`a	b }} 	\'--lTfggF 
 Ge#%U;/v??&'LMM1g#t$"#DEEt9>:Y!^AwHh''"#FGG	g	388CTN#;d#BBd#x/W5F5Ft5LRV^j^q^q^sRs"klukvvxy  T$V$$;s   7+Q 	subscriptc           	         t        | j                  ||||      }t        | j                  ||||      }	 ||   S # t        t        t
        f$ r}d| d| dt        |      j                   d| }t        |t              r\t        |t              rLt        j                  |t        |j                                     }	t        |	      dkD  r|dt        |	       z  }t!        |      |d }~ww xY w)NzCould not index z with 'z': : r   z0. Maybe you meant one of these indexes instead: )r   r  r   KeyError
IndexError	TypeErrorrY   r   r)   r.   r   difflibget_close_matchesr0   keysrC   r   )
r`  rx   rf   ry   rg   r  r   r   error_messageclose_matchess
             r   evaluate_subscriptrk  K  s     %|M_`E%|M_`E5U|j), 5*5's47CSCSBTTVWXVYZeS!j&@#55eT%**,=OPM=!A%#STWXeTfSg!hh}-145s   9 C+BC&&C+r%   c                    | j                   |v r|| j                      S | j                   |v rt        || j                      ||      S | j                   |v r|| j                      S | j                   t        v rt        | j                      S t        j                  | j                   t        |j                                     }t        |      dkD  r||d      S t        d| j                    d      )N)rf   rg   r   zThe variable `z` is not defined.)	r   r   rU  rf  rg  r0   rh  rC   r   )r%   rx   rf   ry   rg   rj  s         r   evaluate_namerm  _  s     ww%TWW~	L	 ,tww/l_qrr	L	 DGG$$	F	dgg--dggtEJJL7IJM
=A]1%&&
^DGG94EF
GGr   	conditionc                    d}t        | j                  ||||      }t        t        | j                  | j
                              D ]<  \  }\  }}	t        |      }t        |	||||      }
|t        j                  k(  r||
k(  }n|t        j                  k(  r||
k7  }n|t        j                  k(  r||
k  }n|t        j                  k(  r||
k  }n|t        j                  k(  r||
kD  }n|t        j                  k(  r||
k\  }nn|t        j                  k(  r||
u }nV|t        j                  k(  r||
u}n>|t        j                   k(  r||
v }n&|t        j"                  k(  r||
v}nt%        d|       |du r y|dk(  r|n|xr |}|
}? |S )NTz!Unsupported comparison operator: Fr   )r   r8  rH   rI   opscomparatorsrY   r   EqNotEqLtLtEGtGtEIsIsNotInNotInr   )rn  rx   rf   ry   rg   re   r8  rH  r   
comparatorr9  current_results               r   evaluate_conditionr~  t  sq    F	|\K]^D(Y]]I<Q<Q)RS B
"XZlL^_<!U]N399_!U]N366\!E\N377]!U]N366\!E\N377]!U]N366\!U]N399_!.N366\!U]N399_!.N"%Frd#KLLU"#$60I>;< Mr   if_statementc                     d }t        | j                  ||||      }|r'| j                  D ]  }t        |||||      }||} |S | j                  D ]  }t        |||||      }||} |S r   )r   r   r   orelse)	r  rx   rf   ry   rg   re   test_resultlineline_results	            r   evaluate_ifr    s     F|00%|UghK %% 	%D&tUL,PbcK&$	% M	 !'' 	%D&tUL,PbcK&$	% Mr   for_loopc           	          d }t        | j                  ||||      }|D ]A  }t        | j                  |||||       | j                  D ]  }	 t        |||||      }	|	|	} C |S # t
        $ r Y   |S t        $ r Y 5w xY wr   )r   rS   r  r   r   r   r   )
r  rx   rf   ry   rg   re   iteratorcounterr   r  s
             r   evaluate_forr    s     FHMM5,N`aH OO	
 MM 
	D*4lTfg*(F	
	 '* M " 
 	M % s   A$$	A=2A=<A=listcompc           	           dt         t        j                     dt        dt        t
        t        f   dt         t           f fd  j                  d|      S )N
generatorsr  current_stater   c                 2  	 |t        |       k\  rt        j                  |
      gS | |   }t        |j                  |
      }g }|D ]  }|j	                         	t        |j                  t        j                        r:t        |j                  j                        D ]  \  }}||   	|j                  <    n|	|j                  j                  <   t        
	fd|j                  D              s|j                   | |dz   	              |S )Nc              3   <   K   | ]  }t        |        y wr   r   r  	if_clauserg   ry   r   rf   s     r   r  z<evaluate_listcomp.<locals>.inner_evaluate.<locals>.<genexpr>  '       Y	<Oab   r   )rC   r   r  rS   r   r)   r   r   r  rH   r  r   rL   ifsrA  )r  r  r  	generator
iter_valuere   r   idxrI  r   rg   ry   inner_evaluater  rf   s            @r   r  z)evaluate_listcomp.<locals>.inner_evaluate  s    C
O#LL!  &  u%	!NN

  	PE%**,I)**CII6!*9+;+;+@+@!A 4IC).sIdgg&4 27	)**--. !*  nZINO	P r   r   )r0   r   comprehensionr,   r1   r.   r   r  )r  rx   rf   ry   rg   r  s   ` ```@r   evaluate_listcompr    s`     4(9(9#:  3  W[\_ad\dWe  jnorjs    D (--q%88r   setcompc           
      p  
 t               }| j                  D ]  }t        |j                  |      }|D ]x  }|j	                         
t        |j                  |
       t        
fd|j                  D              sOt        | j                  
      }	|j                  |	       z  |S )Nc              3   <   K   | ]  }t        |        y wr   r  r  s     r   r  z#evaluate_setcomp.<locals>.<genexpr>  r  r  )r/   r  r   rS   r   r  r   rL   r  r  add)r  rx   rf   ry   rg   re   genr  r   elementr   s     ```     @r   evaluate_setcompr    s     UF!! $!#((E<Oab
 	$E

I

"  !$  'KK  & 

7#+	$$0 Mr   try_nodec                    	 | j                   D ]  }t        |||||        	 | j                  r!| j                  D ]  }t        |||||        	 | j                  r!| j                  D ]  }t        |||||        y y # t        $ r}d}| j                  D ]p  }|j
                  $t        |t        |j
                  ||||            s3d}|j                  r|||j                  <   |j                   D ]  }t        |||||         n |s|Y d }~d }~ww xY w# | j                  r!| j                  D ]  }t        |||||        w w xY w)NFT)	r   r   r  	ExceptionhandlersrY   r)   r%   	finalbody)	r  rx   rf   ry   rg   r   r   matchedhandlers	            r   evaluate_tryr  $  sw   ZMM 	VDulLBTU	V$ ??  ZT5,FXYZ  ** ZT5,FXYZ )  (( 
	G||#zW\\5,N`a( <<*+E',,'#LL ^D ulLJ\]^
	 G (  ** ZT5,FXYZ s6    A> -D >	DA DADD DD /E
raise_nodec                     | j                   t        | j                   ||||      }nd }| j                  t        | j                  ||||      }nd }|||||t        d      )Nz5Re-raise is not supported without an active exception)excr   causer   )r  rx   rf   ry   rg   r  r  s          r   evaluate_raiser  G  sx     ~~!:>>5,N`a#Z--ulLRde
5 IVWWr   assert_nodec                     t        | j                  ||||      }|s]| j                  r$t        | j                  ||||      }t        |      t	        j
                  | j                        }t        d|       y )NzAssertion failed: )r   r   msgAssertionErrorr   r   )r  rx   rf   ry   rg   r  r  	test_codes           r   evaluate_assertr  _  sw     {//lTfgK??{|\SefC %% K$4$45I #5i[!ABB r   	with_nodec                 p   g }| j                   D ]  }t        |j                  ||||      }|j                  rP|j	                         ||j                  j
                  <   |j                  ||j                  j
                            x|j	                         }|j                  |        	 | j                  D ]  }	t        |	||||        	 t        |      D ]  }
|
j                  d d d         y # t        $ r<}t        |      D ](  }
|
j                  t        |      ||j                         *  d }~ww xY wr   )r   r   context_exproptional_vars	__enter__r   r   r   rJ   __exit__r  rY   __traceback__)r  rx   rf   ry   rg   contextsitemr  context_varr   contextr   s               r   evaluate_withr  q  s*    H )#D$5$5ulLZlm+7+A+A+CE$$$''(OOE$"4"4"7"789&002KOOK()	/NN 	VDulLBTU	V  ) 	/GT4.	/  ) 	:GT!Wa9	:s   + C0 0	D597D00D5c                    t        | t              s| S |
t               }t        |       }||v r| S |j	                  |       t        | j
                        }t        |       D ]:  }	 t        | |      }t        |t              rt        |||      }t        |||       < |S # t        t        f$ rH}t        j                  d| j
                   d| dt        |      j
                   d|        Y d}~d}~ww xY w)zJCreates a safe copy of a module or returns the original if it's a functionNz$Skipping import error while copying rj   rb  z - )visited)r)   r   r/   r   r  r   dirr#   ImportErrorAttributeErrorloggerinforY   get_safe_modulerW   )
raw_modulerg   r  	module_idsafe_module	attr_name
attr_valuer   s           r   r  r    s
    j*- %:IGKK	 Z001K _ 4		 Y7J j*-(5GQXYJY
34  ^, 	KK6z7J7J6K1YKWYZ^_`ZaZjZjYkknopnqr 	s   %B  C7/>C22C7c           	      z   t        | t        j                        r| j                  D ]x  }t	        |j
                  |      r=t        |j
                        }t        ||      ||j                  xs |j
                  <   Vt        d|j
                   dt        |              y t        | t        j                        ryt	        | j                  |      r>t        | j                  | j                  D cg c]  }|j
                   c}      }t        ||      }| j                  d   j
                  dk(  r_t        |d      r!|j                  D ]  }t!        ||      ||<    y t#        |      D ]#  }|j%                  d      rt!        ||      ||<   % y | j                  D ]n  }t        ||j
                        r2t!        ||j
                        ||j                  xs |j
                  <   Kt        d| j                   d	|j
                          y t        d
| j                   dt        |             y c c}w )Nz
Import of z) is not allowed. Authorized imports are: )fromlistr   r   __all___zModule rM  zImport from )r)   r   Importnamesrk   r%   r   r  asnamer   r.   
ImportFrommodule
__import__rV   r  r#   r  r!   )rw   rx   rg   aliasr  r  r%   s          r   evaluate_importr    s   *cjj)%% 	E&uzz3EF*5::6
4CJPb4cell0ejj1& ,UVYZlVmUno 	 	J	/":#4#46HI#J$5$5YcYiYi@jPU@jkJ$Z1CDF"''3.69- & <&-fd&;d<   !$F @#s3*1&$*?E$K@  (-- lEvuzz2<CFEJJ<Well8ejj9.9J9J8KK]^c^h^h]i/jkk	l  #z0011Z[^_q[rZst ' 
0@js   3H8
dictcompc           
      z   i }| j                   D ]  }t        |j                  |      }|D ]  }|j                         t	        |j
                  |       t        fd|j                  D              sOt        | j                        }	t        | j                        }
|
||	<     |S )Nc              3   <   K   | ]  }t        |        y wr   r  r  s     r   r  z$evaluate_dictcomp.<locals>.<genexpr>  r  r  )
r  r   rS   r   r  r   rL   r  r  r   )r  rx   rf   ry   rg   re   r  r  r   r  rD  r   s     ```      @r   evaluate_dictcompr    s     F"" "!#((E<Oab
 	"E

I

"  !$  #LL  & #NN  & "s9	""> Mr   delete_nodec                    | j                   D ]  }t        |t        j                        r5|j                  |v r||j                  = 9t        d|j                   d      t        |t        j                        r7t        |j                  ||||      }t        |j                  ||||      }	 ||= t        dt        |      j                   d       y# t        t        t        f$ r}t        dt        |             d}~ww xY w)a=  
    Evaluate a delete statement (del x, del x[y]).

    Args:
        delete_node: The AST Delete node to evaluate
        state: The current state dictionary
        static_tools: Dictionary of static tools
        custom_tools: Dictionary of custom tools
        authorized_imports: List of authorized imports
    zCannot delete name 'z': name is not definedzCannot delete index/key: NzDeletion of z targets is not supported)r  r)   r   r   r   r   r   r   r   r  re  rc  rd  r.   rY   r   )	r  rx   rf   ry   rg   r   r$   r  r   s	            r   evaluate_deleter    s    " %% dfchh'yyE!&))$&)=fii[H^'_``.v||UL,PbcC ulLRdeEMJ #\$v,2G2G1HHa#bcc!d x4 M&)B3q6('KLLMs   ,CD(C??Dc                 $   |j                  dddi      d   t        k\  rt        dt         d      |d   dxx   dz  cc<   ||||ft        | t        j
                        rt        | g S t        | t        j                        rt        | g S t        | t        j                        rt        | g S t        | t        j                        rt        | g S t        | t        j                        r| j                  S t        | t        j                        rt!        fd| j"                  D              S t        | t        j$                  t        j&                  f      rt)        | g S t        | t        j*                        rt-        | g S t        | t        j.                        rt1        | g S t        | t        j2                        rt5        | g S t        | t        j6                        rt9        | j                  g S t        | t        j:                        rt=        | g S t        | t        j>                        r
tA               t        | t        jB                        r
tE               t        | t        jF                        rtI        | g S t        | t        jJ                        rtM        | g S t        | t        jN                        rtQ        | g S t        | t        jR                        rtU        | g S t        | t        jV                        r?fd| jX                  D        }fd	| jZ                  D        }t]        t_        ||            S t        | t        j`                        rt9        | j                  g S t        | t        jb                        rte        | g S t        | t        jf                        rFt9        | j                  g }| jh                  s|S t9        | jh                  g }tk        ||      S t        | t        jl                        rto        | g S tq        t        d
      r0t        | t        jr                        rt9        | j                  g S t        | t        jt                        r<djw                  | jZ                  D 	cg c]  }	ty        t9        |	g        c}	      S t        | t        jz                        r$| j"                  D 
cg c]  }
t9        |
g  c}
S t        | t        j|                        rt        | g S t        | t        j                        rt        | g S t        | t        j                        rDt9        | j                  g }|rt9        | j                  g S t9        | j                  g S t        | t        j                        rt        | g S t        | t        j                        rwt        | j                  t9        | j                  g nd| j                  t9        | j                  g nd| j                  t9        | j                  g       S d      S t        | t        j                        rt        | g S t        | t        j                  t        j                  f      rt        | ||      S t        | t        j                        rt        | g S t        | t        j                        rt        | g S t        | t        j                        rt        | g S t        | t        j                        rt        | g S t        | t        j                        rt        | g S t        | t        j                        rt        fd| j"                  D              S t        | t        j                        r1t        | j                  rt9        | j                  g       d      t        | t        j                        ryt        | t        j                        rt        | g S t        | j                  j                   d      c c}	w c c}
w )a2  
    Evaluate an abstract syntax tree using the content of the variables stored in a state and only evaluating a given
    set of functions.

    This function will recurse through the nodes of the tree provided.

    Args:
        expression (`ast.AST`):
            The code to evaluate, as an abstract syntax tree.
        state (`Dict[str, Any]`):
            A dictionary mapping variable names to values. The `state` is updated if need be when the evaluation
            encounters assignments.
        static_tools (`Dict[str, Callable]`):
            Functions that may be called during the evaluation. Trying to change one of these static_tools will raise an error.
        custom_tools (`Dict[str, Callable]`):
            Functions that may be called during the evaluation. These custom_tools can be overwritten.
        authorized_imports (`List[str]`):
            The list of modules that can be imported by the code. By default, only a few safe modules are allowed.
            If it contains "*", it will authorize any import. Use this at your own risk!
    _operations_countr  r   z(Reached the max number of operations of ze. Maybe there is an infinite loop somewhere in the code, or you're just asking too many calculations.r   c              3   6   K   | ]  }t        |g   y wr   r  r  r  common_paramss     r   r  zevaluate_ast.<locals>.<genexpr>W  s     SCl377S   c              3   6   K   | ]  }t        |g   y wr   r  )r  kr  s     r   r  zevaluate_ast.<locals>.<genexpr>u  s     IAQ//Ir  c              3   6   K   | ]  }t        |g   y wr   r  )r  vr  s     r   r  zevaluate_ast.<locals>.<genexpr>v  s     Ma,q1=1Mr  Indexr   Nc              3   6   K   | ]  }t        |g   y wr   r  r  s     r   r  zevaluate_ast.<locals>.<genexpr>  s     Q#L5}5Qr  r   )er   MAX_OPERATIONSr   r)   r   r  rE  r   r  	AugAssignr,  rS  r_  r  r   r  r2   r  ListCompGeneratorExpr  DictCompr  SetCompr  UnaryOpr   r@  r   BoolOpr5  Breakr   Continuer   BinOpr=  Comparer~  rT  r   r   r   Dictrh  r   r1   rI   r  Forr  FormattedValueformat_specformatIfr  rV   r  	JoinedStrrW  r.   r  r   rm  r   rk  IfExpr   r   r  r   r   Slicer  lowerupperstepWhiler   r  r  r  ClassDefr  Tryr  Raiser  Assertr  Withr  Setr/   Returnr   r  Deleter  r   r   )rw   rx   rf   ry   rg   rh  r   r   r  r  r  test_valr  s               @r   r   r   &  s   8 +i^<YG>Y6~6F  Gl  m
 	
 

y)Q.)L,8JKM*cjj) z:M::	J	.!*=}==	J	.!*=}==	J	)Z8-88	J	-	J			*S:??STT	Js/?/? @	A <m<<	J	- <m<<	J	,
;];;	J	,
;];;	J	,J,,=}==	J

	+z:M::	J			*	J	-!!	J			*j9=99	J	,!*=}==	J

	+z:M::	J	0$Z@-@@	J	)IIM:;L;LMCf%&&	J	)J,,=}==	J	(J777	J 2 2	3Z-->>%%L":#9#9JMJe[))	J	':666	g	:j#))#DJ,,=}==	J	.wwjFWFWXL;];<XYY	J	)=G__McS1=1MM	J	)Z8-88	J	.!*=}==	J			*
@-@
@-@@
 1 1BMBB	J	.!*=}==	J			*>H>N>N>ZL)):M:`d>H>N>N>ZL)):M:`d=G__=XL9=9
 	
 _c
 	

 
J			*j9=99	JS^^ <	=z52DEE	J	-!*=}==	J	(J777	J			*j9=99	J

	+z:M::	J	)Z8-88	J	(QQRR	J

	+PZP`P`l:+;+;LmLkkfjkk	J	)	J

	+z:M:: *"6"6"?"?!@@RSTTa Y Ns   bbc                       e Zd Zd Zy)FinalAnswerExceptionc                     || _         y r   r   r   s     r   r   zFinalAnswerException.__init__  r   r   Nr   r   r   r   r  r    r   r   r  max_print_outputs_lengthc                    	 t        j                  |       }|i }||j                         ni }||ni }d}t               |d<   d	di|d
<   d|v r|d   fd}	|	|d<   	 |j                  D ]  }
t        |
||||      } t        t        |d         |      |d   _        d}||fS # t        $ r_}t        d|j                   dt        |      j                   d|j                   d|j                  xs dz   dt        |       	      d}~ww xY w# t         $ r;}t        t        |d         |      |d   _        d}|j                  |fcY d}~S d}~wt"        $ ra}t        t        |d         |      |d   _        t        dt        j$                  | 
       dt        |      j                   d|       d}~ww xY w)aK  
    Evaluate a python expression using the content of the variables stored in a state and only evaluating a given set
    of functions.

    This function will recurse through the nodes of the tree provided.

    Args:
        code (`str`):
            The code to evaluate.
        static_tools (`Dict[str, Callable]`):
            The functions that may be called during the evaluation. These can also be agents in a multiagent setting.
            These tools cannot be overwritten in the code: any assignment to their name will raise an error.
        custom_tools (`Dict[str, Callable]`):
            The functions that may be called during the evaluation.
            These tools can be overwritten in the code: any assignment to their name will overwrite them.
        state (`Dict[str, Any]`):
            A dictionary mapping variable names to values. The `state` should contain the initial inputs but will be
            updated by this function to contain all variables as they are evaluated.
            The print outputs will be stored in the state under the key "_print_outputs".
    zCode parsing failed on line z	 due to: rR  rQ  r   z	^
Error: NrP  r  r  final_answerc                  &    t         | i |      r   )r  )r   r~   previous_final_answers     r   r  z*evaluate_python_code.<locals>.final_answer  s    &'<d'Mf'MNNr   )
max_lengthFTzCode execution failed at line 'z
' due to: rb  )r   parseSyntaxErrorr   linenorY   r   r   offsetr.   r   r   r   r   r   r   r  r  get_source_segment)r   rf   ry   rx   rg   r  rw   r   re   r  r   is_final_answerr  s               @r   evaluate_python_coder     s   8
YYt_
 }*6*B<$$&L#/#;<LF,.E
"+QE
% ,^ <	O (4^$
OO 	_D!$|\K]^F	_(8&'(5M)
%  &&?  
*188*Id1g>N>N=Orvvhahhm!$% &!fX
 	

@   ((8&'(5M)
% ww'' 
(8&'(5M)
% -c.D.DT4.P-QQ[\`ab\c\l\l[mmopqors
 	
	
sD   B'  AD '	D0AD

D	F>0EF>F>AF99F>c                   ,    e Zd ZU eed<   eed<   eed<   y)
CodeOutputoutputlogsr  N)r   r   r   r   r   r.   r-   r   r   r   r"  r"    s    K
Ir   r"  c                       e Zd Zy)PythonExecutorNr   r   r   r   r&  r&    r   r   r&  c            	       ~    e Zd ZdZ	 	 ddee   dedz  deeef   dz  fdZ	d Z
ded	efd
ZdefdZdeeef   fdZy)LocalPythonExecutora  
    Executor of Python code in a local environment.

    This executor evaluates Python code with restricted access to imports and built-in functions,
    making it suitable for running untrusted code. It maintains state between executions,
    allows for custom tools and functions to be made available to the code, and captures
    print outputs separately from return values.

    Args:
        additional_authorized_imports (`list[str]`):
            Additional authorized imports for the executor.
        max_print_outputs_length (`int`, defaults to `DEFAULT_MAX_LEN_OUTPUT=50_000`):
            Maximum length of the print outputs.
        additional_functions (`dict[str, Callable]`, *optional*):
            Additional Python functions to be added to the executor.
    Nadditional_authorized_importsr  additional_functionsc                    i | _         ddi| _        || _        |t        | _        || _        t        t        t              t        | j                        z        | _        | j                          d | _
        |xs i | _        y )Nr   __main__)ry   rx   r  DEFAULT_MAX_LEN_OUTPUTr)  r0   r/   r   rg   '_check_authorized_imports_are_installedrf   r*  )r   r)  r  r*  s       r   r   zLocalPythonExecutor.__init__/  sz      *-
(@%#+,BD)-J*"&s+?'@3tGiGiCj'j"k446 $8$>B!r   c                     | j                   D cg c](  }|dk7  r!t        |j                  d      d   x}      |* }}|rt        ddj	                  |       d      yc c}w )a  
        Check that all authorized imports are installed on the system.

        Handles wildcard imports ("*") and partial star-pattern imports (e.g., "os.*").

        Raises:
            InterpreterError: If any of the authorized modules are not installed.
        r   rj   r   Nz"Non-installed authorized modules: z, zO. Please install these modules or remove them from the authorized imports list.)rg   r   r   r   rW  )r   impbase_modulemissing_moduless       r   r.  z;LocalPythonExecutor._check_authorized_imports_are_installed@  s     ..
czisyy~a7H(HIQ 
 

 "4TYY5O4P Q` a  
s   -Acode_actionr   c                     t        || j                  | j                  | j                  | j                  | j
                        \  }}t        | j                  d         }t        |||      S )N)rf   ry   rx   rg   r  rP  )r#  r$  r  )r   rf   ry   rx   rg   r  r.   r"  )r   r3  r#  r  r$  s        r   __call__zLocalPythonExecutor.__call__T  sd    "6******#66%)%B%B#
 4::./0dOTTr   	variablesc                 :    | j                   j                  |       y r   )rx   update)r   r6  s     r   send_variablesz"LocalPythonExecutor.send_variables`  s    

)$r   toolsc                 V    i |t         j                         | j                  | _        y r   )BASE_PYTHON_TOOLSr   r*  rf   )r   r:  s     r   
send_toolszLocalPythonExecutor.send_toolsc  s)    ^u^(9(>(>(@^DD]D]^r   rL  )r   r   r   r   r0   r.   r,   r1   r   r   r.  r"  r5  r9  r   r=  r   r   r   r(  r(    s    ( 04;?	?'+Cy? #&*? #3=1D8	?"(
UC 
UJ 
U% %_S$Y _r   r(  r   r   rL  )r   r[   rf  rX  loggingmathr   collections.abcr   r   dataclassesr   	functoolsr   	importlibr   importlib.utilr   typesr	   r
   r   typingr   r:  r   utilsr   r   	getLoggerr   r  
ValueErrorr   r  r)   r#   rY   rX   BaseExceptionrU  r-  r  r   r   r'   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rZ   r<  DANGEROUS_MODULESrm   rr   r{   r   r   r  r   r   r   r   r   r   rk   r   r   r  r   rT  r   r  r   r   r   r   r  r  r   r  r  r,  r  r5  r  r=  r  rE  r  r  rS  r_  r   rk  r   rm  r  objectr~  r   r  r  r  r  r  r  r  r	  r  r
  r  r  r  r  r  r  r  r  r  r  r  r   r  r   r"  r&  r(  r  )r%   s   0r   <module>rM     st  "       	 - !  # $ ? ?   9 
		8	$	z 	 H
'(D)40ZRV@WYf5g 	'(D
!!
   '5\5*5 U5 U	5
 
35 D5 
35 
35 D5 D5 U5 U5 DII5 TZZ5 
4885  
488!5" 
488#5$ 
488%5& 
488'5( DII)5* DII+5, DII-5. TZZ/50 t||152 t||354 
3556 DII758 
395: 
3;5< 
3=5> 
3?5@ 
3A5B C5D 
3E5F G5H fI5J 
3K5L 
3M5N 
3O5P fQ5R 
3S5T 
3U5V DW5X DY5Z f[5\ ]5^ _5` wa5b wc5d *e5f Dg5h wi5 p 
 Ys Y$sH}2E Ybfgjbk Y:X 8 ):$8
sH}% S	: 4	Y 			 	i 
9  8	$s) 	S#X 	S d3i TX 
+
+S>
+ sH}%
+ sH}%	
+
 S	
+ 	
+hhS>h sH}%h sH}%	h
 S	h 	h(zzS> sH}% sH}%	
 S	 0		S> sH}% sH}%	
 S	 
,@oo@S>@ sH}%@ sH}%	@
 S	@ @F'oo'S>' sH}%' sH}%	'
 S	' '@||@S>@ sH}%@ sH}%	@
 S	@ 
@F}}S> sH}% sH}%	
 S	 	"EES>E sH}%E sH}%	E
 S	E 	EP
**S> sH}% sH}%	
 S	 	(%e99%eS>%e sH}%%e sH}%	%e
 S	%e 	%ePJJS> sH}% sH}%	
 S	 	0)GG)) S>) sH}%	)
 sH}%) S	) 
)>N%
((N%S>N% sH}%N% sH}%	N%
 S	N% 	N%b5}}5S>5 sH}%5 sH}%	5
 S	5 	5(H
((HS>H sH}%H sH}%	H
 S	H 	H*'{{'S>' sH}%' sH}%	'
 S	' 
F]'T&&S> sH}% sH}%	
 S	 	,ggS> sH}% sH}%	
 S	 	B)9ll)9S>)9 sH}%)9 sH}%	)9
 S	)9 
#Y)9X [[ S>  sH}%  sH}%	 
 S	  	X F Zgg ZS> Z sH}% Z sH}%	 Z
 S	 Z 
 ZFX		XS>X sH}%X sH}%	X
 S	X 
X0CCS>C sH}%C sH}%	C
 S	C 
C$/xx/S>/ sH}%/ sH}%	/
 S	/ 
/:#L!H'll'S>' sH}%' sH}%	'
 S	' 
#s(^'T!d!dS>!d sH}%!d sH}%	!d
 S	!d 
!dH  %9VUVUS>VU sH}%VU sH}%	VU
 S	VU VUr9  04/3#'$8$:J

J
sH}%,J
 sH}%,J
 S>D 	J

 S	J
 "J
Z   	 	H_. H_V "#8
9q1
s   1_