in src/smolagents/remote_executors.py [0:0]
def run_code_raise_errors(self, code: str) -> CodeOutput:
"""
Execute Python code in the Pyodide environment and return the result.
Args:
code (`str`): Python code to execute.
Returns:
`CodeOutput`: Code output containing the result, logs, and whether it is the final answer.
"""
try:
# Prepare the request payload
payload = {
"code": code,
"packages": self.installed_packages,
}
# Send the request to the Deno server
response = requests.post(self.server_url, json=payload, timeout=self.timeout)
if response.status_code != 200:
raise AgentError(f"Server error: {response.text}", self.logger)
result = None
is_final_answer = False
# Parse the response
result_data = response.json()
# Process the result
if result_data.get("result"):
result = result_data.get("result")
# Check for execution errors
elif result_data.get("error"):
error = result_data["error"]
if (
error.get("pythonExceptionType") == RemotePythonExecutor.FINAL_ANSWER_EXCEPTION
and "pythonExceptionValue" in error
):
result = pickle.loads(base64.b64decode(error["pythonExceptionValue"]))
is_final_answer = True
else:
error_message = f"{error.get('name', 'Error')}: {error.get('message', 'Unknown error')}"
if "stack" in error:
error_message += f"\n{error['stack']}"
raise AgentError(error_message, self.logger)
# Get the execution logs
execution_logs = result_data.get("stdout", "")
# Handle image results
if isinstance(result, dict) and result.get("type") == "image":
image_data = result.get("data", "")
decoded_bytes = base64.b64decode(image_data.encode("utf-8"))
return PIL.Image.open(BytesIO(decoded_bytes)), execution_logs
return CodeOutput(output=result, logs=execution_logs, is_final_answer=is_final_answer)
except requests.RequestException as e:
raise AgentError(f"Failed to communicate with Deno server: {e}", self.logger)