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

41 lines
1.6 KiB
Python

import os
from google.genai import types
def write_file(working_directory, file_path, content):
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 write to "{file_path}" as it is outside the permitted working directory'
if os.path.isdir(new_file_path):
return f'Error: Cannot write to "{file_path}" as it is a directory'
os.makedirs(os.path.dirname(new_file_path), exist_ok=True)
try:
with open(new_file_path, "w") as f:
f.write(content)
except Exception as e:
return f"Error: {e}"
return f'Successfully wrote to "{file_path}" ({len(content)} characters written)'
schema_write_file = types.FunctionDeclaration(
name="write_file",
description="Open file and write content into",
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",
),
"content": types.Schema(
type=types.Type.STRING,
description="Content what should have been written to the file",
),
},
),
)