
    3fi<                       d dl mZ d dlZd dlZd dlZd dlmZ d dlmZ d dl	m
Z
mZmZmZmZmZmZmZ d dlmZmZmZ d dlmZmZ d dlmZmZmZ d d	lmZ erd d
lm Z  d dl!m"Z" dZ#ddZ$ddZ% G d de      Z& G d de      Z' G d de      Z(y)    )annotationsN)StringIO)version_info)IOTYPE_CHECKINGAnyCallableListOptionalTypeUnion)AsyncCallbackManagerForToolRunCallbackManagerCallbackManagerForToolRun)BaseToolTool)	BaseModelFieldPrivateAttr)Unparser)EnvVars)Artifacta  Evaluates python code in a sandbox environment. The environment is long running and exists across multiple executions. You must send the whole script every time and print your outputs. Script should be pure python code that can be evaluated. It should be in python format NOT markdown. The code should NOT be wrapped in backticks. All python packages including requests, matplotlib, scipy, numpy, pandas, etc are available. Create and display chart using `plt.show()`.c                    t         j                  dk  r9t               }t        | |       |j	                         }|j                          |S t        j                  |       }|S )zUnparse the AST.	   )file)r   minorr   r   getvaluecloseastunparse)treessource_codes      n/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_community/tools/e2b_data_analysis/tool.py_unparser%   "   sS    AJAjjl		  kk$'    c           	        t        j                  |       }|j                  d   }t        |t         j                        rt        |j
                  t         j                        r\t        |j
                  j                  t         j                        r.|j
                  j                  j                  dk(  rt        |      S t        |t         j                        rkt        j                  t        j                  t        j                  dt        j                               |j
                  gg             |j                  d<   t        |      S )a  Add print statement to the last line if it's missing.

    Sometimes, the LLM-generated code doesn't have `print(variable_name)`, instead the
        LLM tries to print the variable only by writing `variable_name` (as you would in
        REPL, for example).

    This methods checks the AST of the generated Python code and adds the print
        statement to the last line if it's missing.
    print)idctx)funcargskeywords)value)r   parsebody
isinstanceExprr/   Callr,   Namer*   r%   Load)coder!   nodes      r$   add_last_line_printr9   .   s     99T?D99R=D$!jSXX&Fdjjoosxx0TZZ__5G5G75RD>!$!((XXchhj9jj\
		" D>r&   c                  0    e Zd ZU dZded<   ded<   ded<   y)UploadedFilez6Description of the uploaded path with its remote path.strnameremote_pathdescriptionN)__name__
__module____qualname____doc____annotations__ r&   r$   r;   r;   J   s    @
Ir&   r;   c                  4    e Zd ZU dZ eddgd      Zded<   y)	E2BDataAnalysisToolArgumentsz&Arguments for the E2BDataAnalysisTool..zprint('Hello World')zhThe python script to be evaluated. The contents will be in main.py. It should not be in markdown format.)examplesr?   r<   python_codeN)r@   rA   rB   rC   r   rI   rD   rE   r&   r$   rG   rG   R   s$    0()3	K r&   rG   c                  ,    e Zd ZU dZdZded<   eZded<   ded<   ded	<    ee	
      Z
ded<   	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZedd       Z	 	 d	 	 	 	 	 	 	 ddZ	 d	 	 	 	 	 d dZ	 	 	 	 d!dZd"dZd"dZd#dZd$dZd%dZd&dZ xZS )'E2BDataAnalysisToolzJTool for running python code in a sandboxed environment for data analysis.e2b_data_analysisr<   r=   zType[BaseModel]args_schemar   sessionr?   )default_factoryzList[UploadedFile]_uploaded_filesc           	         	 ddl m}	 t        |   ddt
        i|  |	|||||||      | _        y # t        $ r}
t        d      |
d }
~
ww xY w)Nr   )DataAnalysisz<Unable to import e2b, please install with `pip install e2b`.r?   )api_keycwdenv_vars	on_stdout	on_stderron_exiton_artifactrE   )e2brR   ImportErrorsuper__init__base_descriptionrN   )selfrS   rT   rU   rV   rW   rY   rX   kwargsrR   e	__class__s              r$   r]   zE2BDataAnalysisTool.__init__i   si    	( 	@%5@@##
  	N	s   3 	AAAc                F    g | _         | j                  j                          y)zClose the cloud sandbox.N)rP   rN   r   r_   s    r$   r   zE2BDataAnalysisTool.close   s    !r&   c                4   t        | j                        dk(  rydg}| j                  D ]]  }|j                  dk(  r |j                  d|j                   d       2|j                  d|j                   d|j                   d       _ dj                  |      S )Nr    z-The following files available in the sandbox:z	- path: ``z` 
 description: `
)lenrP   r?   appendr>   join)r_   linesfs      r$   uploaded_files_descriptionz.E2BDataAnalysisTool.uploaded_files_description   s    t##$)@A%% 	A}}"yq9:.A!--PQR		 yyr&   c                    t        |      }|t        |j                  dd       }nd }| j                  j	                  ||      \  }}}||t        t        d |            d}t        j                  |      S )NrY   )rY   c                    | j                   S N)r=   )artifacts    r$   <lambda>z*E2BDataAnalysisTool._run.<locals>.<lambda>   s
    8== r&   )stdoutstderr	artifacts)	r9   getattrmetadatarN   
run_pythonlistmapjsondumps)	r_   rI   run_manager	callbacksrY   rt   ru   rv   outs	            r$   _runzE2BDataAnalysisTool._run   s     *+6 !)"4"4mTJKK$(LL$;$;[ %< %
!	
 c"@)LM

 zz#r&   c                    K   t        d      w)Nz(e2b_data_analysis does not support async)NotImplementedError)r_   rI   r~   s      r$   _arunzE2BDataAnalysisTool._arun   s     
 ""LMMs   c                    | j                   j                  j                  |      }|j                         }|j                  |j
                  |j                  dS )z!Run shell command in the sandbox.)rt   ru   	exit_code)rN   processstartwaitrt   ru   r   )r_   cmdprocoutputs       r$   run_commandzE2BDataAnalysisTool.run_command   sJ    
 ||##))#.mmmm))
 	
r&   c                :    | j                   j                  |       y)z'Install python packages in the sandbox.N)rN   install_python_packagesr_   package_namess     r$   r   z+E2BDataAnalysisTool.install_python_packages       ,,];r&   c                :    | j                   j                  |       y)z1Install system packages (via apt) in the sandbox.N)rN   install_system_packagesr   s     r$   r   z+E2BDataAnalysisTool.install_system_packages   r   r&   c                8    | j                   j                  |      S )zDownload file from the sandbox.)rN   download_file)r_   r>   s     r$   r   z!E2BDataAnalysisTool.download_file   s    ||))+66r&   c                   | j                   j                  |      }t        t        j                  j                  |j                        ||      }| j                  j                  |       | j                  dz   | j                  z   | _	        |S )z^Upload file to the sandbox.

        The file is uploaded to the '/home/user/<filename>' path.)r=   r>   r?   rh   )rN   upload_filer;   ospathbasenamer=   rP   rj   r?   rn   )r_   r   r?   r>   rm   s        r$   r   zE2BDataAnalysisTool.upload_file   sw     ll..t4!!$)),##

 	##A&++d2T5T5TTr&   c                   | j                   j                  j                  |j                         | j                  D cg c]  }|j                  |j                  k7  r| c}| _        | j
                  dz   | j                  z   | _        yc c}w )z&Remove uploaded file from the sandbox.rh   N)rN   
filesystemremover>   rP   r?   rn   )r_   uploaded_filerm   s      r$   remove_uploaded_filez(E2BDataAnalysisTool.remove_uploaded_file   sz    &&}'@'@A )) 
}} 9 99  

  ++d2T5T5TT 
s   "B
c                    t        j                  | j                  | j                  | j                  | j
                        S )N)r,   r=   r?   rM   )r   from_functionr   r=   r?   rM   rd   s    r$   as_toolzE2BDataAnalysisTool.as_tool   s5    !!((((	
 	
r&   )NNNNNNN)rS   Optional[str]rT   r   rU   zOptional[EnvVars]rV   Optional[Callable[[str], Any]]rW   r   rY   z#Optional[Callable[[Artifact], Any]]rX   zOptional[Callable[[int], Any]]r`   r   )returnNone)r   r<   )NN)rI   r<   r~   z#Optional[CallbackManagerForToolRun]r   zOptional[CallbackManager]r   r<   rq   )rI   r<   r~   z(Optional[AsyncCallbackManagerForToolRun]r   r<   )r   r<   r   dict)r   zUnion[str, List[str]]r   r   )r>   r<   r   bytes)r   r   r?   r<   r   r;   )r   r;   r   r   )r   r   )r@   rA   rB   rC   r=   rD   rG   rM   r   rz   rP   r]   r   propertyrn   r   r   r   r   r   r   r   r   r   __classcell__)rb   s   @r$   rK   rK   `   sN   T#D###?K?L*5d*KO'K "&!&*4848;?26

 
 $	

 2
 2
 9
 0
 
>
    " <@/3	 9 -	
 
6 AENN >N 
	N

 

<<7U
r&   rK   )r!   zast.ASTr   r<   )r7   r<   r   r<   ))
__future__r   r   r|   r   ior   sysr   typingr   r   r   r	   r
   r   r   r   langchain_core.callbacksr   r   r   langchain_core.toolsr   r   pydanticr   r   r   3langchain_community.tools.e2b_data_analysis.unparser   rZ   r   e2b.templates.data_analysisr   r^   r%   r9   r;   rG   rK   rE   r&   r$   <module>r      sz    " 
  	   P P P 
 0 2 2 H4C 	89 9 S
( S
r&   