Spaces:
Sleeping
Sleeping
| # ./file_agent.py | |
| # The Writer - Encapsulates your content generation logic, properly decoupled from the main interface. | |
| import os | |
| import yaml | |
| import toml | |
| from docx import Document | |
| from agent_logging import log_agent_action | |
| def write_document(content, filename): | |
| """Handles parsing and physical generation of files, then logs the event.""" | |
| output_dir = "outputs" | |
| if not os.path.exists(output_dir): | |
| os.makedirs(output_dir) | |
| file_path = os.path.join(output_dir, filename) | |
| ext = os.path.splitext(filename)[1].lower() | |
| try: | |
| if ext in ['.md', '.txt']: | |
| with open(file_path, "w", encoding="utf-8") as f: | |
| f.write(content) | |
| elif ext == '.yaml': | |
| data = yaml.safe_load(content) if isinstance(content, str) else content | |
| with open(file_path, "w") as f: | |
| yaml.dump(data, f) | |
| elif ext == '.toml': | |
| data = toml.loads(content) if isinstance(content, str) else content | |
| with open(file_path, "w") as f: | |
| toml.dump(data, f) | |
| elif ext == '.docx': | |
| doc = Document() | |
| doc.add_paragraph(content) | |
| doc.save(file_path) | |
| else: | |
| with open(file_path, "w", encoding="utf-8") as f: | |
| f.write(str(content)) | |
| log_agent_action("FILE_CREATION", f"Successfully generated {filename}") | |
| return file_path | |
| except Exception as e: | |
| log_agent_action("FILE_ERROR", f"Failed to save {filename}: {str(e)}") | |
| return f"Error: {str(e)}" |