[docs]asyncdefexecute_python_code(code:str,timeout:float=300,**kwargs:Any,)->ToolResponse:"""Execute the given python code in a temp file and capture the return code, standard output and error. Note you must `print` the output to get the result, and the tmp file will be removed right after the execution. Args: code (`str`): The Python code to be executed. timeout (`float`, defaults to `300`): The maximum time (in seconds) allowed for the code to run. Returns: `ToolResponse`: The response containing the return code, standard output, and standard error of the executed code. """withtempfile.TemporaryDirectory()astemp_dir:temp_file=os.path.join(temp_dir,f"tmp_{shortuuid.uuid()}.py")withopen(temp_file,"w",encoding="utf-8")asf:f.write(code)proc=awaitasyncio.create_subprocess_exec(sys.executable,"-u",temp_file,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,)try:awaitasyncio.wait_for(proc.wait(),timeout=timeout)stdout,stderr=awaitproc.communicate()stdout_str=stdout.decode("utf-8")stderr_str=stderr.decode("utf-8")returncode=proc.returncodeexceptasyncio.TimeoutError:stderr_suffix=(f"TimeoutError: The code execution exceeded "f"the timeout of {timeout} seconds.")returncode=-1try:proc.terminate()stdout,stderr=awaitproc.communicate()stdout_str=stdout.decode("utf-8")stderr_str=stderr.decode("utf-8")ifstderr_str:stderr_str+=f"\n{stderr_suffix}"else:stderr_str=stderr_suffixexceptProcessLookupError:stdout_str=""stderr_str=stderr_suffixreturnToolResponse(content=[TextBlock(type="text",text=f"<returncode>{returncode}</returncode>"f"<stdout>{stdout_str}</stdout>"f"<stderr>{stderr_str}</stderr>",),],)