self-trained2 / agent /tools /file_tools.py
DeepImagix's picture
Upload 5 files
fb1a676 verified
Raw
History Blame Contribute Delete
2.6 kB
"""
NeuraPrompt Agent β€” File Tools (v7.5)
"""
from pathlib import Path
from typing import List, Dict, Optional
import logging
import base64
log = logging.getLogger("agent.tools.file")
def create_file(filename: str, content: str, file_type: str = "text", extra_files: Optional[List[Dict]] = None) -> str:
"""Create one or more files"""
try:
created_files = []
# Main file
Path(filename).parent.mkdir(parents=True, exist_ok=True)
Path(filename).write_text(content, encoding="utf-8")
created_files.append(filename)
# Additional files if provided
if extra_files:
for file_info in extra_files:
if isinstance(file_info, dict):
f_name = file_info.get("filename")
f_content = file_info.get("content", "")
if f_name:
Path(f_name).parent.mkdir(parents=True, exist_ok=True)
Path(f_name).write_text(f_content, encoding="utf-8")
created_files.append(f_name)
return f"βœ… Successfully created {len(created_files)} file(s): {', '.join(created_files)}"
except Exception as e:
return f"File creation error: {str(e)}"
def read_file(path: str) -> str:
"""Read content from a file"""
if ".." in path or path.startswith("/"):
return "Error: Access denied"
try:
return Path(path).read_text(encoding="utf-8")[:8000]
except Exception as e:
return f"Error reading file: {str(e)}"
def write_file(path: str, content: str) -> str:
"""Write content to a file"""
if ".." in path or path.startswith("/"):
return "Error: Access denied"
try:
Path(path).parent.mkdir(parents=True, exist_ok=True)
Path(path).write_text(content, encoding="utf-8")
return f"βœ… Successfully wrote {len(content)} characters to {path}"
except Exception as e:
return f"Error writing file: {str(e)}"
def list_directory(path: str = ".") -> str:
"""List files in a directory"""
if ".." in path or path.startswith("/"):
return "Error: Access denied"
try:
entries = list(Path(path).iterdir())
if not entries:
return "Directory is empty"
result = []
for entry in entries:
icon = "πŸ“" if entry.is_dir() else "πŸ“„"
result.append(f"{icon} {entry.name}")
return "\n".join(result)
except Exception as e:
return f"Error listing directory: {str(e)}"