
    g                        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m	Z	m
Z
mZmZ d dlZddlmZ  e            rd dlZ G d de          Zd	  ee          D             Zg d
Zd\  aZd\  aZ G d de          Z G d de          Z G d de          Zd Z d Z!d Z"d Z#d Z$d Z%d Z&d Z'd Z(d Z)d Z*d Z+d Z,d  Z-d! Z.d" Z/d# Z0d$ Z1d% Z2d& Z3d' Z4d( Z5d) Z6d* Z7d+ Z8d, Z9efd-e j:        d.e
e;ef         d/e
e;e	f         d0e
e;e	f         d1ee;         f
d2Z<dddefd3e;d/ee
e;e	f                  d0ee
e;e	f                  d.ee
e;ef                  d1ee;         f
d4Z=dS )5    N)Mapping)import_module)AnyCallableDictListOptional   )is_pandas_availablec                       e Zd ZdZdS )InterpreterErrorz
    An error raised when the interpretor cannot evaluate a Python expression, due to syntax error or unsupported
    operations.
    N)__name__
__module____qualname____doc__     b/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/agents/python_interpreter.pyr   r   !   s         
 	Dr   r   c                     i | ]h}t          t          t          |          t                    *t	          t          t          |          t
                    R|t          t          |          iS r   )
isinstancegetattrbuiltinstype
issubclassBaseException).0names     r   
<dictcomp>r   *   so     
 
 
'(D))400
 6@RV@W@WYf5g5g
'(D
!
!
 
 
r   )
randomcollectionsmathtimequeue	itertoolsrestat
statisticsunicodedata) iP  )r   i c                       e Zd ZdS )BreakExceptionNr   r   r   r   r   r   r+   r+   B           Dr   r+   c                       e Zd ZdS )ContinueExceptionNr,   r   r   r   r/   r/   F   r-   r   r/   c                       e Zd Zd ZdS )ReturnExceptionc                     || _         d S N)value)selfr4   s     r   __init__zReturnException.__init__K   s    


r   N)r   r   r   r6   r   r   r   r1   r1   J   s#            r   r1   c                     t          | t                    r| S t          | d          rt          |           S t          d          )N__iter__zObject is not iterable)r   listhasattrr   )objs    r   get_iterabler<   O   sF    #t 9
	j	!	! 9Cyy7888r   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.)evaluate_astoperandr   opastUSubUAddNotInvertr   	__class__r   )
expressionstatestatic_toolscustom_toolsr@   s        r   evaluate_unaryoprL   X   s    :-ulLQQG*-** 	hx	JM38	,	, h	JM37	+	+ h{	JM3:	.	. hxf*-2I2Rfffgggr   c                 N     d  j         j         D              fd}|S )Nc                     g | ]	}|j         
S r   argr   rP   s     r   
<listcomp>z#evaluate_lambda.<locals>.<listcomp>g   s    ;;;CG;;;r   c                                                       }t          |           D ]
\  }}|||<   t          j        |          S r3   )copyzipr?   body)	values	new_staterP   r4   argsrK   lambda_expressionrI   rJ   s	       r   lambda_funcz$evaluate_lambda.<locals>.lambda_funci   sP    JJLL	dF++ 	# 	#JC"IcNN-2I|\ZZZr   )rY   )rZ   rI   rJ   rK   r[   rY   s   ```` @r   evaluate_lambdar\   f   s_    ;;05:;;;D[ [ [ [ [ [ [ [ [ r   c                    d}d}t          | j        |||          rp| j        D ]3}	 t          ||||           # t          $ r Y  d S t          $ r Y  nw xY w|dz  }||k    rt          d| d          t          | j        |||          pd S )Ni  r      zMaximum number of z" iterations in While loop exceeded)r?   testrV   r+   r/   r   )
while_looprI   rJ   rK   max_iterations
iterationsnodes          r   evaluate_whilerd   r   s    NJ
z|\
J
J 
lO 	 	DT5,EEEE!   ttt$   a
&&"#j#j#j#jkkk z|\
J
J 
l 4s   9
A	AAc                       fd}|S )Nc                  <                                    }d j        j        D             }fdj        j        D             }t          t	          |t          |           d          |                    }t	          ||           D ]
\  }}|||<   |                                D ]
\  }}|||<   j        j        rj        j        j        }| ||<   j        j	        rj        j	        j        }	|||	<   |                                D ]\  }}||vr|||<   j        j        r8j        j        d         j        dk    r| r| d         |d<   | d         j
        |d<   d }
	 j        D ]}t          ||          }
n# t          $ r}|j        }
Y d }~nd }~ww xY w|
S )Nc                     g | ]	}|j         
S r   rO   rQ   s     r   rR   z5create_function.<locals>.new_func.<locals>.<listcomp>   s    ;;;SW;;;r   c                 4    g | ]}t          |          S r   r?   )r   drK   rI   rJ   s     r   rR   z5create_function.<locals>.new_func.<locals>.<listcomp>   s(    mmmQR,q%|LLmmmr   r   r5   rG   )rT   rY   defaultsdictrU   lenitemsvarargrP   kwargrG   rV   r?   r1   r4   )rY   kwargs
func_state	arg_namesdefault_valuesrk   r   r4   vararg_name
kwarg_nameresultstmterK   func_defrI   rJ   s                r   new_funcz!create_function.<locals>.new_func   s   ZZ\\
;;(:;;;	mmmmmmV^VcVlmmm Is>':':&:&<&<=~NNOO y$// 	% 	%KD%$Jt "<<>> 	% 	%KD%$Jt = 	+"-.2K&*J{#= 	,!,0J%+Jz" $>>++ 	) 	)KD%:%%#(
4  = 	<(-"4Q"7";v"E"E <%)!W
6"*.q'*;
;'	  T T%dJlSST 	 	 	WFFFFFF	s   !E> >
FFFr   )rz   rI   rJ   rK   r{   s   ```` r   create_functionr|      s6    * * * * * * * *X Or   c                     i }|                                 D ]
\  }}|||<   t          | t          |          |          S r3   )rn   r   tuple)
class_nameclass_bases
class_body
class_dictkeyr4   s         r   create_classr      sK    J &&((    
U
3
E+..
;;;r   c                 P    t          | |||          || j        <   || j                 S r3   )r|   r   )rz   rI   rJ   rK   s       r   evaluate_function_defr      s*    "1(E<Q]"^"^L&&r   c                 r   | j         }fd| j        D             }i }| j        D ]}t          |t          j                  rt          |          ||j         <   7t          |t          j                  r~|j        D ]u}t          |t          j	                  r t          |j                  ||j        <   <t          |t          j                  rt          |j                  ||j        <   vt          d|j        j                   t%          |t'          |          |          }	|	|<   |	S )Nc                 4    g | ]}t          |          S r   ri   )r   baserK   rI   rJ   s     r   rR   z&evaluate_class_def.<locals>.<listcomp>   s'    ___t\$|\BB___r   z%Unsupported statement in class body: )r   basesrV   r   rB   FunctionDefr   AssigntargetsNamer?   r4   id	Attributeattrr   rG   r   r   r~   )
	class_defrI   rJ   rK   r   r   r   rx   target	new_classs
    ```      r   evaluate_class_defr      sS   J______y___EJ 
f 
fdCO,, 		f$9$|Ua$b$bJty!!cj)) 	f, j jfch// j,8ULZf,g,gJvy))66 j.:4:ul\h.i.iJv{+	j ##d4>Kb#d#deeeZuz::I!E*r   c                    fd | j                   }t          | j                  }t          | j        t
          j                  rKt          |t                    r/t          |t                    st          d| d          ||z   }n||z   }nt          | j        t
          j	                  r||z
  }nt          | j        t
          j
                  r||z  }nzt          | j        t
          j                  r||z  }nTt          | j        t
          j                  r||z  }n.t          | 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  }ntt          | j        t
          j                  r||z  }nOt          | j        t
          j                  r||z	  }n*t          dt)          | j                  j         d          t-          | j         |           |S )Nc                    t          | t          j                  r                    | j        d          S t          | t          j                  r6t          | 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fd| j        D             S t!          d          )Nr   c              3   .   K   | ]} |          V  d S r3   r   r   eltget_current_values     r   	<genexpr>z@evaluate_augassign.<locals>.get_current_value.<locals>.<genexpr>   s/      GGC**3//GGGGGGr   c                 &    g | ]} |          S r   r   r   s     r   rR   zAevaluate_augassign.<locals>.get_current_value.<locals>.<listcomp>   s%    BBBs%%c**BBBr   z3AugAssign not supported for {type(target)} targets.)r   rB   r   getr   	Subscriptr?   r4   slicer   r   r   Tupler~   eltsr   r   )r   r;   r   rK   r   rI   rJ   s      r   r   z-evaluate_augassign.<locals>.get_current_value   s,   fch'' 	Z99VY***.. 	Zv|UL,OOCv|UL,OOCs8O.. 	Zv|UL,OOC3,,,	** 	ZGGGG6;GGGGGG)) 	ZBBBBfkBBBB"#XYYYr   zCannot add non-list value z to a list.z
Operation r>   )r   r?   r4   r   rA   rB   Addr9   r   SubMultDivModPowFloorDivBitAndBitOrBitXorLShiftRShiftr   r   	set_value)rH   rI   rJ   rK   current_valuevalue_to_addupdated_valuer   s    ```   @r   evaluate_augassignr      s   Z Z Z Z Z Z Z Z" &%j&788M
 0%|TTL *-)) ^mT** 	9lD11 _&']L']']']^^^)L8MM)L8MM	JM37	+	+ ^%4	JM38	,	, ^%4	JM37	+	+ ^%4	JM37	+	+ ^%4	JM37	+	+ ^%|3	JM3<	0	0 ^%5	JM3:	.	. ^%4	JM39	-	- 	^%4	JM3:	.	. ^%4	JM3:	.	. ^%5	JM3:	.	. ^%5\D,?,?,H\\\]]] j|\RRRr   c                    t          | j        t          j                  r!| j        D ]}t          ||||          s dS dS t          | j        t          j                  r!| j        D ]}t          ||||          r dS dS d S NFT)r   rA   rB   AndrW   r?   Or)rc   rI   rJ   rK   r4   s        r   evaluate_boolopr     s    $'37## 	[ 	 	EulLII uut	DGSV	$	$ [ 	 	EE5,EE ttu	 r   c                    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   rA   rB   r   r   r   r   r   r   r   r   r   r   r   r   NotImplementedErrorr   r   )binoprI   rJ   rK   left_val	right_vals         r   evaluate_binopr     s   EJ|\JJHU[%|LLI %(CG$$ e)##	EHcg	&	& e)##	EHch	'	' e)##	EHcg	&	& e)##	EHcg	&	& e)##	EHcg	&	& e""	EHcl	+	+ e9$$	EHcj	)	) e)##	EHci	(	( 	e)##	EHcj	)	) e)##	EHcj	)	) e9$$	EHcj	)	) e9$$!"cd58nn6M"c"c"cdddr   c                 X   t          | j        |||          }t          | j                  dk    r!| j        d         }t	          |||||           nt          | j                  t          |          k    r5t          dt          |           dt          | j                   d          g }| j        D ]G}t          |t          j                  r|	                    |           2|
                    |           Ht          | j        |          D ]\  }}t	          |||||           |S )Nr^   r   zAssign failed: expected z values but got .)r?   r4   rm   r   r   r   r   rB   StarredextendappendrU   )	assignrI   rJ   rK   rw   r   expanded_valuestgtvals	            r   evaluate_assignr   A  s8   &,|\JJF
6>a"&&%|DDDDv~#f++--"#qc&kk#q#q[^_e_m[n[n#q#q#qrrr> 	/ 	/C#s{++ /&&v....&&v....FNO<< 	C 	CHCc3|\BBBBMr   c                    t          | t          j                  r-| j        |v rt	          d| j         d          ||| j        <   d S t          | t          j                  rt          |t                    sKt          |d          r,t          |t          t          f          st          |          }nt	          d          t          | j                  t          |          k    rt	          d          t          | j                  D ]\  }}t          |||         |||           d S t          | t          j                  r5t          | j        |||          }t          | j        |||          }|||<   d S t          | t          j                  r/t          | j        |||          }t'          || j        |           d S d S )NzCannot assign to name 'z,': doing this would erase the existing tool!r8   zCannot unpack non-tuple valuez!Cannot unpack tuple of wrong size)r   rB   r   r   r   r   r~   r:   strbytesrm   r   	enumerater   r   r?   r4   r   r   setattrr   )	r   r4   rI   rJ   rK   ielemr;   r   s	            r   r   r   T  s   &#(## )9$$"#tVY#t#t#tuuu fi	FCI	&	& )%'' 	Huj)) H*US%L2Q2Q He&'FGGGv{s5zz))"#FGGG -- 	I 	IGAtdE!He\<HHHH	I 	I	FCM	*	* )6<lKK6<lKKC	FCM	*	* )6<lKKV[%((((() )r   c           	      8   t          | j        t          j                  s7t          | j        t          j                  st          d| j         d          t          | j        t          j                  r^t          | j        j                  }| j        j        }t          ||          st          d| d|           t          ||          }nt          | j        t          j                  rg| j        j        }|v r	|         }nN|v r	|         }nA|v r	|         }n4|t          v rt          |         }nt          d| j        j         d          g }| j        D ]l}t          |t          j                  r+|                    t          |j                             G|                    t          |                     mg }| j        D ]}t          |t          j                  rkt          |j                  }	t          |	d          rt          |	t"          t$          f          rt          d|	           |                    |	           |                    t          |                     fd| j        D             }
t          |t(                    r_t+          |j                            d	                    d
k    r4|                    |          }t          |d          r |j        |i |
 |S |dk    r|s3dv r dv rt5          d         d                   S t          d          |d         }t          |t(                    st          d          t+          |          d
k    rt5          |          S t+          |          dk    r|d
         }t5          ||          S t          d          |dk    r7d                    t9          t"          |                    }t:          |dz   z  ad S  ||i |
}|S )Nz This is not a correct function: z).zObject z has no attribute zIt is not permitted to evaluate other functions than the provided tools or functions defined in previous code (tried to execute r8   z!Cannot unpack non-iterable value c           	      J    i | ]}|j         t          |j                   S r   )rP   r?   r4   )r   keywordrK   rI   rJ   s     r   r   z!evaluate_call.<locals>.<dictcomp>  s.    www^egk<ulLYYwwwr   r   r^   r6   superrG   r5   z#super() needs at least one argumentr   zsuper() argument 1 must be typer
   z!super() takes at most 2 argumentsprint 
)r   funcrB   r   r   r   r?   r4   r   r:   r   r   ERRORSrY   r   r   r   r   r   keywordsr   rm   r   split__new__r6   r   joinmapPRINT_OUTPUTS)callrI   rJ   rK   r;   	func_namer   rY   rP   unpackedrq   clsinstanceoutputs    ```          r   evaluate_callr   l  sd   ty#-00 QJty#(4S4S QO$)OOOPPP$)S]++ 49?E<NNIN	sI&& 	Q"#OS#O#OI#O#OPPPsI&&	DIsx	(	( IL	#DD,&&	*DD,&&	*DD&  )$DD" d  TX  T]  T`  d  d  d   Dy N Nc3;'' 	NKKSY|\RRSSSSKKS%|LLMMMMDy N Nc3;'' 	N#CIulLQQH8Z00 WJx#u4V4V W&'U8'U'UVVVKK!!!!KKS%|LLMMMMwwwwwwimivwwwF$  #do&;&;C&@&@"A"AA"E"Ell4  3
## 	*CL$)&)))
 R%''FeOO {!3U6]CCC*+PQQQq'Cc4(( J&'HIII4yyA~~Szz!Ta7S(+++&'JKKKG###c4..11$.tt.v..r   c                 \   t          | j        |||          }t          | j        |||          }t          |t                    r$t          |t                    rt          d          t          |t          j        j        j	                  r|j
        }|j        |         S t          |t          j        t          j        t          j        f          r||         S t          |t          j        j        j        j                  r||         S t          |t                    r||         S t          |t&          t(          f          rat+          |           |cxk    rt+          |          k     s$n t          d| dt+          |                     |t-          |                   S t          |t                    rTt+          |           |cxk    rt+          |          k     s$n t          d| dt+          |                     ||         S ||v r||         S t          |t                    rjt          |t.                    rUt1          j        |t'          |                                                    }t+          |          dk    r||d                  S t          d| d| d          )	NzLYou're trying to subscript a string with a string index, which is impossiblezIndex z" out of bounds for list of length z$ out of bounds for string of length r   zCould not index z with 'z'.)r?   r   r4   r   r   r   pdcoreindexing_LocIndexerr;   loc	DataFrameSeriesnpndarraygroupbygenericDataFrameGroupByr9   r~   rm   intr   difflibget_close_matcheskeys)	subscriptrI   rJ   rK   indexr4   parent_objectclose_matchess           r   evaluate_subscriptr     s   %|LLE%|LLE% o*UC"8"8 omnnn%)566 (	 ''%",	2:>?? +U|	E27?2C	D	D +U|	E5	!	! +U|	ED%=	)	) +Uu1111s5zz1111"#aE#a#aUXY^U_U_#a#abbbSZZ  	E3		 	+Uu1111s5zz1111"#cE#c#cWZ[`WaWa#c#cdddU|	%U|	E3		 +Jug$>$> +1%ejjll9K9KLL}!!q)**
EeEEEEEE
F
FFr   c                 ~   | j         |v r|| j                  S | j         |v r|| j                  S | j         t          v rt          | j                  S t          j        | j         t	          |                                                    }t          |          dk    r||d                  S t          d| j          d          )Nr   zThe variable `z` is not defined.)r   r   r   r   r9   r   rm   r   )r   rI   rJ   rK   r   s        r   evaluate_namer     s    w%TW~	L	 	 DG$$	F		dg-dgtEJJLL7I7IJJM
=A]1%&&
FDGFFF
G
GGr   c                 H   t          | j                  }fd| j        D             }d | j        D             }d}|}t	          ||          D ]\  }	}
|	t
          j        k    r||
k    }n|	t
          j        k    r||
k    }n|	t
          j        k    r||
k     }n|	t
          j	        k    r||
k    }n|	t
          j
        k    r||
k    }n}|	t
          j        k    r||
k    }nf|	t
          j        k    r||
u }nQ|	t
          j        k    r||
u}n<|	t
          j        k    r||
v }n'|	t
          j        k    r||
v}nt!          d|	           ||z  }|
}t#          |t$                    r|s nt#          |t$          t&          j        f          r|n|                                S )Nc                 4    g | ]}t          |          S r   ri   )r   crK   rI   rJ   s     r   rR   z&evaluate_condition.<locals>.<listcomp>  s'    eee!<5,EEeeer   c                 ,    g | ]}t          |          S r   )r   )r   rA   s     r   rR   z&evaluate_condition.<locals>.<listcomp>  s    
,
,
,488
,
,
,r   TzOperator not supported: )r?   r   comparatorsopsrU   rB   EqNotEqLtLtEGtGtEIsIsNotInNotInr   r   boolr   r   all)	conditionrI   rJ   rK   r   r  r  rw   current_leftrA   
comparatorcurrent_results    ```        r   evaluate_conditionr    s   	|\JJDeeeeeeyOdeeeK
,
,im
,
,
,CFLc;//  J<<)Z7NN39__)Z7NN36\\)J6NN37]])Z7NN36\\)J6NN37]])Z7NN36\\)Z7NN39__);NN36\\)Z7NN39__);NN"#Bb#B#BCCC.(!fd## 	F 	Ery(9::L66

Lr   c                     d }t          | j        |||          }|r!| j        D ]}t          ||||          }||}n | j        D ]}t          ||||          }||}|S r3   )r?   r_   rV   orelse)if_statementrI   rJ   rK   rw   test_resultlineline_results           r   evaluate_ifr    s    F|0%|TTK 	% % 	% 	%D&tUL,OOK&$	%
 !' 	% 	%D&tUL,OOK&$Mr   c                     d }t          | j        |||          }|D ]X}t          | j        ||||           | j        D ]5}	 t          ||||          }||}# t
          $ r Y  nt          $ r Y 2w xY wX |S r3   )r?   iterr   r   rV   r+   r/   )	for_looprI   rJ   rK   rw   iteratorcounterrc   r  s	            r   evaluate_forr#  !  s    FHM5,MMH  (/7E<NNNM 
	 
	D*4lSS*(F!   $    Ms    A
A0$	A0/A0c                 >      fd  j         d|          S )Nc                   	 |t          |           k    rt          j        |
          gS | |         }t          |j        |
          }g }|D ]}|                                	t          |j        t          j                  r0t          |j        j
                  D ]\  }}||         	|j        <   n|	|j        j        <   t          
	fd|j        D                       r#|                     | |dz   	                     |S )Nc              3   <   K   | ]}t          |          V  d S r3   ri   r   	if_clauserK   rX   rJ   s     r   r   z<evaluate_listcomp.<locals>.inner_evaluate.<locals>.<genexpr>C  s2      qqV_<	9lLQQqqqqqqr   r^   )rm   r?   r   r  rT   r   r   rB   r   r   r   r   r  ifsr   )
generatorsr   current_state	generator
iter_valuerw   r4   idxr   rX   rK   inner_evaluatelistcomprJ   s            @r   r/  z)evaluate_listcomp.<locals>.inner_evaluate6  s0   C
OO## }lLYYZZu%	!).-|\\
 	P 	PE%**,,I)*CI66 7!*9+;+@!A!A 4 4IC).sIdg&&4 27	)*-.qqqqqqclcpqqqqq PnnZINNOOOr   r   )r*  )r0  rI   rJ   rK   r/  s   ` ``@r   evaluate_listcompr1  5  sG           " >(-q%888r   c                 .   	 | j         D ]}t          ||||           	 | j        r| j        D ]}t          ||||           n# t          $ rw}d}| j        D ]_}|j        %t          |t          |j        |||                    r1d}|j        r
|||j        <   |j         D ]}t          ||||            n`|s|Y d }~nd }~ww xY w| j        r| j        D ]}t          ||||           d S d S # | j        r| j        D ]}t          ||||           w w xY wr   )	rV   r?   r  	Exceptionhandlersr   r   r   	finalbody)try_noderI   rJ   rK   rx   ry   matchedhandlers           r   evaluate_tryr9  J  s   FM 	B 	BDulLAAAA	B ? 	F  F FT5,EEEE    ( 	 	G|#z!\',PUWceq5r5r's's#< ,*+E','#L J JD ulLIIII $  	G	 	 	 	 	"  	F * F FT5,EEEE	F 	FF F  	F * F FT5,EEEE	FFs/   A $C. 
CA-B?:C. ?CC. .&Dc                     | j         t          | j         |||          }nd }| j        t          | j        |||          }nd }|||||t          d          )Nz5Re-raise is not supported without an active exception)excr?   causer   )
raise_noderI   rJ   rK   r;  r<  s         r   evaluate_raiser>  d  ss    ~!:>5,MM#Z-ulLQQ
5 IVWWWr   c                     t          | j        |||          }|sX| j        r&t          | j        |||          }t          |          t	          j        | j                  }t          d|           d S )NzAssertion failed: )r?   r_   msgAssertionErrorrB   unparse)assert_noderI   rJ   rK   r  r@  	test_codes          r   evaluate_assertrE  v  s    {/lSSK C? 	C{|\RRC %%% K$455I !Ai!A!ABBBC Cr   c                 d   g }| j         D ]}t          |j        |||          }|j        rG|                                ||j        j        <   |                    ||j        j                            g|                                }|                    |           	 | j        D ]}t          ||||           	 t          |          D ]}	|		                    d d d            d S # t          $ rA}
t          |          D ]+}	|		                    t          |
          |
|
j                   , d }
~
ww xY wr3   )rn   r?   context_exproptional_vars	__enter__r   r   rV   reversed__exit__r3  r   __traceback__)	with_noderI   rJ   rK   contextsitemrG  context_varrx   contextry   s              r   evaluate_withrR    sl   H ) )#D$5ulLYY 	)+7+A+A+C+CE$$'(OOE$"4"789999&0022KOOK((((	/N 	B 	BDulLAAAA	B  )) 	/ 	/GT4....	/ 	/    )) 	: 	:GT!WWa9999s   C$ $
D/.<D**D/c           	      F   fd}t          | t          j                  rh| j        D ]^} ||j                  r&t          |j                  }|||j        p|j        <   8t          d|j         dt                               d S t          | t          j	                  r~ || j
                  rTt          | j
        d | j        D                       }| j        D ]&}t          ||j                  ||j        p|j        <   'nt          d| j
         d          d S d S )Nc                     |                      d          fdt          dt                    dz             D             }t          fd|D                       S )Nr   c                 J    g | ]}d                      d|                    S )r   N)r   )r   r   module_paths     r   rR   zCimport_modules.<locals>.check_module_authorized.<locals>.<listcomp>  s-    ]]]388KO44]]]r   r^   c              3       K   | ]}|v V  	d S r3   r   )r   subpathauthorized_importss     r   r   zBimport_modules.<locals>.check_module_authorized.<locals>.<genexpr>  s)      PPW700PPPPPPr   )r   rangerm   any)module_namemodule_subpathsrV  rY  s     @r   check_module_authorizedz/import_modules.<locals>.check_module_authorized  sk    !'',,]]]]eAs;GWGWZ[G[>\>\]]]PPPPPPPPPPr   z
Import of z) is not allowed. Authorized imports are: c                     g | ]	}|j         
S r   )r   )r   aliass     r   rR   z"import_modules.<locals>.<listcomp>  s    <f<f<fEUZ<f<f<fr   )fromlistzImport from z is not allowed.)r   rB   Importnamesr   r   asnamer   r   
ImportFrommodule
__import__r   )rH   rI   rY  r^  r`  rf  s     `   r   import_modulesrh    sx   Q Q Q Q Q
 *cj)) % 	 	E&&uz22 &uz224:el0ej11&oooVYZlVmVmoo   t	J	/	/ "":#455 	W
 1<f<fU_Ue<f<f<fgggF#) P P4;FEJ4O4Oel0ej11P ##U*2C#U#U#UVVVt r   c           	      ^  
 i }| j         D ]}t          |j        |          }|D ]}|                                
t	          |j        |
           t          
fd|j        D                       r3t          | j        
          }t          | j	        
          }	|	||<   |S )Nc              3   <   K   | ]}t          |          V  d S r3   ri   r'  s     r   r   z$evaluate_dictcomp.<locals>.<genexpr>  s2      kkV_<	9lLQQkkkkkkr   )
r*  r?   r  rT   r   r   r  r)  r   r4   )dictcomprI   rJ   rK   rw   genr-  r4   r   r   rX   s     ``      @r   evaluate_dictcomprm    s    F" " "!#(E<NN
 	" 	"E

Icj%L,OOOkkkkkkcfcjkkkkk ""8<L,WW"8>9lLYY!s	" Mr   rH   rI   rJ   rK   rY  c           
      V   t           t          k    rt          dt           d          t           dz  a t          | t          j                  rt          |           S t          | t          j                  rt          |           S t          | t          j	                  rt          |           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%          |           S t          | t          j                  rt)          |           S t          | t          j                  rt-          | j                  S t          | t          j                  rt1          |           S t          | t          j                  rt5                      t          | t          j                  rt9                      t          | t          j                  rt=          |           S t          | t          j                  rtA          |           S t          | t          j!                  rtE          |           S t          | t          j#                  rtI          |           S t          | t          j%                  rGfd| j&        D             }fd| j'        D             }tQ          tS          ||                    S t          | t          j*                  rt-          | j                  S t          | t          j+                  rtY          |           S t          | t          j-                  rt-          | j                  S t          | t          j.                  rt_          |           S ta          t          d          r1t          | t          j1                  rt-          | j                  S t          | t          j2                  r(d3                    fd	| j'        D                       S t          | t          j4                  rfd
| j        D             S t          | t          j5                  rtm          |           S t          | t          j7                  rtq          |           S t          | t          j9                  rGt-          | j:                  }|rt-          | j;                  S t-          | j<                  S t          | t          j=                  r,t-          | j                  }t}          || j?                  S t          | t          j@                  rkt          | jB        t-          | jB                  nd| jC        t-          | jC                  nd| jD        t-          | jD                  nd          S t          | t          jE                  rt          |           S t          | t          jG                  rt          |           S t          | t          jI        t          jJ        f          rt          | |          S t          | t          jL                  rt          |           S t          | t          jN                  rt          |           S t          | t          jP                  rt          |           S t          | t          jR                  rt          |           S t          | t          jT                  rt          |           S t          | t          jV                  rfd| j        D             S t          | t          jW                  r-t          | j        rt-          | j                  nd          t          | jY        jZ         d          )a   
    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 trough 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 assignements.
        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 static_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.
            Add more at your own risk!
    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   <   K   | ]}t          |          V  d S r3   ri   r   r   rK   rI   rJ   s     r   r   zevaluate_ast.<locals>.<genexpr>  s1      eec\#ulLIIeeeeeer   c                 4    g | ]}t          |          S r   ri   )r   krK   rI   rJ   s     r   rR   z evaluate_ast.<locals>.<listcomp>	  s'    \\\qQ|\BB\\\r   c                 4    g | ]}t          |          S r   ri   r   vrK   rI   rJ   s     r   rR   z evaluate_ast.<locals>.<listcomp>
  s'    ```,q%|DD```r   Indexr)   c           
      N    g | ]!}t          t          |                    "S r   )r   r?   rt  s     r   rR   z evaluate_ast.<locals>.<listcomp>  s0    kkkTULE<NNOOkkkr   c                 4    g | ]}t          |          S r   ri   rp  s     r   rR   z evaluate_ast.<locals>.<listcomp>  '    ```S%|DD```r   Nc                 4    h | ]}t          |          S r   ri   rp  s     r   	<setcomp>zevaluate_ast.<locals>.<setcomp>I  ry  r   r>   )[OPERATIONS_COUNTMAX_OPERATIONSr   r   rB   r   r   	AugAssignr   Callr   Constantr4   r   r~   r   ListCompGeneratorExpr1  UnaryOprL   r   r?   BoolOpr   Breakr+   Continuer/   BinOpr   Comparer  Lambdar\   r   r   r   r   rW   rl   rU   ExprForr#  FormattedValueIfr  r:   rv  	JoinedStrr   r   r   r   r   r   IfExpr_   rV   r  r   r   r   Slicer   lowerupperstepDictComprm  Whilerd   rb  re  rh  ClassDefr   Tryr9  Raiser>  AssertrE  WithrR  SetReturnr1   rG   r   )	rH   rI   rJ   rK   rY  r   rW   test_valr4   s	    ```     r   r?   r?     s   8 >)) m~  m  m  m
 
 	
 *cj)) nU z5,MMM	J	.	. jU!*e\<PPP	J	)	) hUZlKKK	J	-	- eU	J		*	* bUeeeeeeU_Udeeeeee	Js/? @	A	A `U UL,OOO	J	,	, ^U
E<NNN	J	,	, \UJ,e\<PPP	J
	+	+ ZUz5,MMM	J		*	* WU	J	-	- UU!!!	J		*	* SUj%|LLL	J	,	, PU!*e\<PPP	J
	+	+ MUz5,MMM	J	0	0 KU$ZlSSS	J	)	) IU\\\\\\JO\\\``````jN_```Cf%%&&&	J	)	) DUJ,e\<PPP	J	(	( AUJ|\JJJ	J 2	3	3 >UJ,e\<PPP	J	'	' ;U:ulLIII	g		 8U:j#)#D#D 8UJ,e\<PPP	J	.	. 6UwwkkkkkkYcYjkkklll	J	)	) 4U``````PZP_````	J	)	) 1UZlKKK	J	.	. .U!*e\<PPP	J		*	* +U
lSS 	V
lSSS
 15,UUU	J	.	. %UZ-ulLQQujo...	J		*	* "U+ )5,MMM+ )5,MMMPZP_PkL%|LLLqu
 
 	
 
J	-	- U UL,OOO	J		*	* Uj%|LLL	JS^ <	=	= Uj%1CDDD	J	-	- U!*e\<PPP	J	(	( UJ|\JJJ	J		*	* Uj%|LLL	J
	+	+ Uz5,MMM	J	)	) 
UZlKKK	J	(	( U``````PZP_````	J
	+	+ UQ[QakL)5,MMMgk
 
 	

 *"6"?SSSTTTr   codec                 h   	 t          j        |           }n$# t          $ r}t          d|           d}~ww xY w|i }|i }|i }d}dada|j        D ]\}	 t          |||||          }n# t          $ r}d}	t          t                    dk    rOt          t                    t          k     r|	dt           dz  }	n#|	dt          dt                    dt           dz  }	|	d	t          j
        | |           d
| z  }	t          |	          d}~ww xY w	 t          t                    t          k     rt          |d<   t          dt                   dt           dz   |d<   # t          t                    t          k     rt          |d<   n#t          dt                   dt           dz   |d<   w xY w|S )a  
    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 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.The code generated by the agent is not valid.
Nr)   r   zPrint outputs:
z
====
z
_Print outputs were over z0 characters, so they have been truncated._
====
z.EXECUTION FAILED:
Evaluation stopped at line 'z"' because of the following error:
print_outputsz* characters, so they have been truncated._)rB   parseSyntaxErrorr   r|  rV   r?   r   rm   MAX_LEN_OUTPUTget_source_segment)
r  rJ   rK   rI   rY  rH   ry   rw   rc   r@  s
             r   evaluate_python_coder  S  s]   6QYt__

 Q Q QOAOOPPPQ}FM  	!$|\K]^^FF 	( 	( 	(C=!!A%%}%%66EmEEEECC  lmO^O.L  l  liw  l  l  l  lC  PSE[\`bfEgEg  P  P  MN  P  P  PC"3'''	(  =!!N22)6o&& "/>/2nNnnno o&& =!!N22)6o&& "/>/2nNnnno o&    
 Ms<    
838A,+E",
D6BDDE""AF/)>rB   r   r   collections.abcr   	importlibr   typingr   r   r   r   r	   numpyr   utilsr   pandasr   
ValueErrorr   dirr   LIST_SAFE_MODULESr   r  r|  r}  r3  r+   r/   r1   r<   rL   r\   rd   r|   r   r   r   r   r   r   r   r   r   r   r   r  r  r#  r1  r9  r>  rE  rR  rh  rm  ASTr   r?   r  r   r   r   <module>r     sX  " 


   # # # # # # # # # # # # 6 6 6 6 6 6 6 6 6 6 6 6 6 6     ' ' ' ' ' '  	 	 	 	 	z 	 	 	
 
H
 
 
    !* ~#.   .	 	 	 	 	Y 	 	 		 	 	 	 		 	 	 	    i   
9 9 9h h h	 	 	  "- - -`< < <' ' '
  ,: : :z
 
 
e e eD  &) ) )0L L L^G G G@
H 
H 
H&M &M &MR     (9 9 9*F F F4X X X$	C 	C 	C/ / /.  4  & %6OU OUOUS>OU sH}%OU sH}%	OU
 S	OU OU OU OUh 3726&*$5? ?
?4X./? 4X./? DcN#	?
 S	? ? ? ? ? ?r   