KarthikMuraliM commited on
Commit
aa9714c
·
1 Parent(s): f757484

Fix: Correctly configure sandbox scope for code execution

Browse files
Files changed (1) hide show
  1. tools.py +15 -11
tools.py CHANGED
@@ -106,24 +106,28 @@ def run_python_code_on_dataframe(df: pd.DataFrame, python_code: str) -> str:
106
  """
107
  output_stream = io.StringIO()
108
 
109
- # --- ADD THE NEW LIBRARIES TO THE SCOPE ---
110
- local_scope = {
 
 
111
  'df': df,
112
  'pd': pd,
113
  're': re,
114
- 'plt': plt, # Matplotlib
115
- 'sns': sns, # Seaborn
116
- 'np': np, # NumPy
117
- 'LinearRegression': LinearRegression, # Scikit-learn
118
- 'io': io, # IO for in-memory files
119
- 'base64': base64 # Base64 for encoding
 
120
  }
121
 
122
  try:
123
  with redirect_stdout(output_stream):
124
- exec(python_code, {'__builtins__': __builtins__}, local_scope)
 
 
125
 
126
- # After execution, close any open matplotlib plots to free up memory
127
  plt.close('all')
128
 
129
  result = output_stream.getvalue()
@@ -132,5 +136,5 @@ def run_python_code_on_dataframe(df: pd.DataFrame, python_code: str) -> str:
132
  return result
133
 
134
  except Exception as e:
135
- plt.close('all') # Also close plots on error
136
  return f"Error executing code: {type(e).__name__}: {e}\n---\nCode that failed:\n{python_code}"
 
106
  """
107
  output_stream = io.StringIO()
108
 
109
+ # --- THIS IS THE CORRECTED SANDBOX SETUP ---
110
+ # Create a single dictionary to serve as the global and local scope.
111
+ # This ensures that all libraries are accessible everywhere inside the exec'd code.
112
+ execution_scope = {
113
  'df': df,
114
  'pd': pd,
115
  're': re,
116
+ 'plt': plt,
117
+ 'sns': sns,
118
+ 'np': np,
119
+ 'LinearRegression': LinearRegression,
120
+ 'io': io,
121
+ 'base64': base64,
122
+ '__builtins__': __builtins__ # Ensure basic built-ins are available
123
  }
124
 
125
  try:
126
  with redirect_stdout(output_stream):
127
+ # Pass the scope dictionary as the 'globals' argument.
128
+ # This makes 'pd', 're', etc. globally available to the script.
129
+ exec(python_code, execution_scope)
130
 
 
131
  plt.close('all')
132
 
133
  result = output_stream.getvalue()
 
136
  return result
137
 
138
  except Exception as e:
139
+ plt.close('all')
140
  return f"Error executing code: {type(e).__name__}: {e}\n---\nCode that failed:\n{python_code}"