gaia-agent / tools /code.py
AdityaW's picture
Added tools
0078c1e
Raw
History Blame Contribute Delete
2.49 kB
import json
import textwrap
def run_python_code(code: str) -> str:
"""Execute Python code and return output.
Args:
code: Python code to execute
Returns:
JSON string with stdout, stderr, and result
"""
stdout_output = []
stderr_output = []
result = None
error = None
# Capture stdout
import io
import sys
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = io.StringIO()
sys.stderr = io.StringIO()
try:
# Execute the code
exec_globals = {}
exec(code.strip(), exec_globals)
# Get any last expression result (check for common patterns)
sys.stdout = old_stdout
sys.stderr = old_stderr
# Check for printed output
stdout_text = ""
# Try to get result from exec
try:
# Check for variables that might hold the result
for var_name in ['result', 'answer', 'output', 'final_answer', 'x']:
if var_name in exec_globals:
result = exec_globals[var_name]
break
except Exception:
pass
except Exception as e:
sys.stdout = old_stdout
sys.stderr = old_stderr
error = str(e)
stdout_text = sys.stdout.getvalue() if hasattr(sys.stdout, 'getvalue') else ""
sys.stdout = old_stdout
sys.stderr = old_stderr
# If we still have no result, try to evaluate the last line
if result is None and not error:
lines = code.strip().split('\n')
for line in reversed(lines):
stripped = line.strip()
# Look for print statements or assignments
if stripped.startswith('print('):
try:
result = eval(stripped[6:-1], {})
break
except Exception:
continue
elif '=' in stripped and not stripped.startswith('#'):
parts = stripped.split('=', 1)
if len(parts) == 2:
var_name = parts[0].strip()
try:
result = eval(parts[1].strip(), {})
break
except Exception:
continue
output = {
'stdout': stdout_text,
'stderr': stderr_output,
'result': str(result) if result is not None else None,
'error': error,
}
return json.dumps(output, indent=2)