Add pre-imports for common libraries
Browse files- Modules/Code_Interpreter.py +26 -2
Modules/Code_Interpreter.py
CHANGED
|
@@ -26,15 +26,39 @@ def Code_Interpreter(code: Annotated[str, "Python source code to run; stdout is
|
|
| 26 |
result = "No code provided."
|
| 27 |
_log_call_end("Code_Interpreter", result)
|
| 28 |
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
old_stdout = sys.stdout
|
| 30 |
old_cwd = os.getcwd()
|
| 31 |
redirected_output = sys.stdout = StringIO()
|
| 32 |
try:
|
| 33 |
os.chdir(ROOT_DIR)
|
| 34 |
-
exec(
|
| 35 |
result = redirected_output.getvalue()
|
|
|
|
|
|
|
| 36 |
except Exception as exc: # pylint: disable=broad-except
|
| 37 |
-
|
|
|
|
| 38 |
finally:
|
| 39 |
sys.stdout = old_stdout
|
| 40 |
try:
|
|
|
|
| 26 |
result = "No code provided."
|
| 27 |
_log_call_end("Code_Interpreter", result)
|
| 28 |
return result
|
| 29 |
+
|
| 30 |
+
# Pre-import commonly used libraries to make them available
|
| 31 |
+
pre_imports = """
|
| 32 |
+
try:
|
| 33 |
+
import pandas as pd
|
| 34 |
+
import numpy as np
|
| 35 |
+
import matplotlib.pyplot as plt
|
| 36 |
+
import seaborn as sns
|
| 37 |
+
import io
|
| 38 |
+
import requests
|
| 39 |
+
import json
|
| 40 |
+
from datetime import datetime, timedelta
|
| 41 |
+
import re
|
| 42 |
+
except ImportError as e:
|
| 43 |
+
print(f"Warning: Could not import some libraries: {e}")
|
| 44 |
+
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
# Combine pre-imports with user code
|
| 48 |
+
full_code = pre_imports + "\n" + code
|
| 49 |
+
|
| 50 |
old_stdout = sys.stdout
|
| 51 |
old_cwd = os.getcwd()
|
| 52 |
redirected_output = sys.stdout = StringIO()
|
| 53 |
try:
|
| 54 |
os.chdir(ROOT_DIR)
|
| 55 |
+
exec(full_code, globals())
|
| 56 |
result = redirected_output.getvalue()
|
| 57 |
+
if not result:
|
| 58 |
+
result = "Code executed successfully (no output)"
|
| 59 |
except Exception as exc: # pylint: disable=broad-except
|
| 60 |
+
import traceback
|
| 61 |
+
result = f"Error: {exc}\n\nFull traceback:\n{traceback.format_exc()}"
|
| 62 |
finally:
|
| 63 |
sys.stdout = old_stdout
|
| 64 |
try:
|