antonioschiro commited on
Commit
4ba071b
·
verified ·
1 Parent(s): be6f029

Update tools.py

Browse files
Files changed (1) hide show
  1. tools.py +24 -3
tools.py CHANGED
@@ -14,6 +14,7 @@ from transformers import pipeline
14
  import asyncio
15
  import os
16
  import io
 
17
  from dotenv import load_dotenv
18
  #from PIL import Image
19
  #from io import StringIO
@@ -227,7 +228,7 @@ def detect_objects(image_path: str) -> str:
227
  @tool
228
  def run_python(code: str) -> str:
229
  """
230
- Executes Python code safely and returns stdout.
231
 
232
  Args:
233
  code (str): The Python code to execute.
@@ -235,14 +236,34 @@ def run_python(code: str) -> str:
235
  Returns:
236
  str: Captured stdout and/or result.
237
  """
 
238
  stdout = io.StringIO()
239
  local_vars = {}
 
240
  try:
 
 
 
 
 
 
 
241
  with contextlib.redirect_stdout(stdout):
242
- exec(code, {}, local_vars)
243
- # Return printed output or last expression result
 
 
 
 
 
 
 
 
244
  if "_result" in local_vars:
245
  return str(local_vars["_result"])
 
 
246
  return stdout.getvalue().strip() or "Code executed successfully."
 
247
  except Exception as e:
248
  return f"Execution error: {e}"
 
14
  import asyncio
15
  import os
16
  import io
17
+ import ast
18
  from dotenv import load_dotenv
19
  #from PIL import Image
20
  #from io import StringIO
 
228
  @tool
229
  def run_python(code: str) -> str:
230
  """
231
+ Executes Python code safely and returns stdout or the last expression result.
232
 
233
  Args:
234
  code (str): The Python code to execute.
 
236
  Returns:
237
  str: Captured stdout and/or result.
238
  """
239
+
240
  stdout = io.StringIO()
241
  local_vars = {}
242
+
243
  try:
244
+ # Parse code into AST
245
+ parsed = ast.parse(code, mode="exec")
246
+ last_expr = None
247
+ if parsed.body and isinstance(parsed.body[-1], ast.Expr):
248
+ # If last node is an expression, separate it
249
+ last_expr = parsed.body.pop()
250
+
251
  with contextlib.redirect_stdout(stdout):
252
+ # Run everything except the last expression
253
+ exec(compile(parsed, filename="<ast>", mode="exec"), {}, local_vars)
254
+
255
+ # Evaluate last expression if present
256
+ if last_expr is not None:
257
+ _result = eval(compile(ast.Expression(last_expr.value),
258
+ filename="<ast>", mode="eval"), {}, local_vars)
259
+ local_vars["_result"] = _result
260
+
261
+ # Return _result if set
262
  if "_result" in local_vars:
263
  return str(local_vars["_result"])
264
+
265
+ # Otherwise, return stdout
266
  return stdout.getvalue().strip() or "Code executed successfully."
267
+
268
  except Exception as e:
269
  return f"Execution error: {e}"