Files
ai-agent-gemini/functions/run_python_file.py
T

63 lines
2.4 KiB
Python

import os
import subprocess
from google.genai import types
def run_python_file(working_directory, file_path, args=None):
try:
abs_path = os.path.abspath(working_directory)
new_file_path = os.path.normpath(os.path.join(abs_path, file_path))
valid_target_file = os.path.commonpath([abs_path, new_file_path]) == abs_path
if not valid_target_file:
return f'Error: Cannot execute "{file_path}" as it is outside the permitted working directory'
if not os.path.isfile(new_file_path):
return f'Error: "{file_path}" does not exist or is not a regular file'
if not file_path.endswith(".py"):
return f'Error: "{file_path}" is not a Python file'
command = ["python", new_file_path]
if args:
command.extend(args)
completed_process = subprocess.run(
command,
cwd=abs_path,
capture_output=True,
text=True,
timeout=30
)
output = []
if completed_process.returncode != 0:
output.append(f"Process exited with code {completed_process.returncode}")
if not completed_process.stdout and not completed_process.stderr:
output.append("No output produced")
if completed_process.stdout:
output.append(f"STDOUT: {completed_process.stdout}")
if completed_process.stderr:
output.append(f"STDERR: {completed_process.stderr}")
return "\n".join(output)
except Exception as e:
return f"Error: executing Python file: {e}"
schema_run_python_file = types.FunctionDeclaration(
name="run_python_file",
description="Run the file provided in the path",
parameters=types.Schema(
type=types.Type.OBJECT,
properties={
"working_directory": types.Schema(
type=types.Type.STRING,
description="Directory path to list files from, relative to the working directory (default is the working directory itself)",
),
"file_path": types.Schema(
type=types.Type.STRING,
description="File path",
),
"args": types.Schema(
type=types.Type.ARRAY,
items=types.Schema(type=types.Type.STRING),
description="Optional arguments to run subprocess",
),
},
),
)