File size: 1,570 Bytes
f54201d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45


# ./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)}"