Files
bootdev_python_agent/functions/run_python.py

58 lines
2.2 KiB
Python
Raw Normal View History

2025-08-15 16:14:02 +02:00
import os
import subprocess
from google.genai import types
def run_python_file(working_directory, file_path, args=[]):
abs_working_dir = os.path.abspath(working_directory)
abs_file_path = os.path.abspath(os.path.join(working_directory, file_path))
if not abs_file_path.startswith(abs_working_dir):
return f'Error: Cannot execute "{file_path}" as it is outside the permitted working directory'
if not os.path.isfile(abs_file_path):
return f'Error: File "{file_path}" not found'
if not abs_file_path.endswith(".py"):
return f'Error: "{file_path}" is not a Python file.'
try:
completed = subprocess.run(args=["python3", abs_file_path]+args, capture_output=True, cwd=abs_working_dir, timeout=30)
if completed == None:
raise Exception("Subprocess holder is empty")
if completed.stdout == None or completed.stdout == "":
return f"No output produced."
message = f"STDOUT: {completed.stdout.decode()}. STDERR: {completed.stderr.decode()}."
if completed.returncode != 0:
message += f" Error: Process exited with code {completed.returncode}"
except Exception as e:
return f"Error: executing Python file: {e}"
return message
schema_run_python_file = types.FunctionDeclaration(
name="run_python_file",
description="Run the python file",
parameters=types.Schema(
type=types.Type.OBJECT,
properties={
"working_directory": types.Schema(
type=types.Type.STRING,
description="The directory to read the file from. If not provided, lists files in the working directory itself.",
),
"file_path": types.Schema(
type=types.Type.STRING,
description="The file to execute. If not provided, the function will not work."
),
"args": types.Schema(
type=types.Type.ARRAY,
items=types.Schema(
type=types.Type.STRING,
description="Optional arguments to pass to the Python file.",
),
description="Arguments to run the python file with."
)
},
),
)