First_agent_template / tools /write_code.py
mohamedelfeky-mo's picture
Create write_code.py
655c8ff verified
raw
history blame contribute delete
885 Bytes
from smolagents import tool
import os
@tool
def write_code_to_file(filename: str, content: str) -> str:
"""
Writes the provided text or code content to a specific file.
Use this tool to save code, documentation, or text files.
Args:
filename: The name of the file (e.g., 'script.py', 'README.md').
content: The full content to write into the file.
"""
try:
# Ensure we don't overwrite critical system files by restricting path (optional safety)
if ".." in filename or filename.startswith("/"):
return "Error: File path must be relative and strictly within the working directory."
with open(filename, 'w', encoding='utf-8') as f:
f.write(content)
return f"Successfully created file: {filename}"
except Exception as e:
return f"Error writing file: {str(e)}"