File size: 4,514 Bytes
c5997d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# agent/agent.py

import json
import re
import os
from openai import OpenAI
from environment.file_system import FileSystem
from actions.file_actions import execute_action
from utils.helpers import build_prompt_context
from config import MAX_AGENT_STEPS

# Safe OpenAI client setup (NO HARDCODED TOKEN)
API_KEY = os.getenv("HF_TOKEN")
API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")

client = OpenAI(
    base_url=API_BASE_URL,
    api_key=API_KEY
)

SYSTEM_PROMPT = """You are an AI Data Janitor agent responsible for cleaning and organizing a cloud file system.

You have access to the following actions (respond ONLY with valid JSON):
- create_folder(name)
- move_file(filename, destination)
- rename_file(old_name, new_name)
- delete_file(filename)
- zip_folder(folder_name)
- inspect_file(filename)
- list_all_files()
- done()

Each response must be valid JSON exactly like this:
{
  "thought": "your reasoning here",
  "action": "action_name",
  "params": { ...parameters... }
}

Rules:
- Think carefully before deleting anything
- Never delete recent files unless clearly unnecessary
- Prefer moving files to proper folders first
- If unsure, use inspect_file first
"""


class DataJanitorAgent:

    def __init__(self, task_description: str, fs: FileSystem):
        self.task_description = task_description
        self.fs = fs
        self.messages = [{"role": "system", "content": SYSTEM_PROMPT}]
        self.step = 0
        self.done = False

    def _build_first_message(self):

        obs = self.fs.get_observation()
        context = build_prompt_context(obs)

        return (
            f"TASK: {self.task_description}\n\n"
            f"CURRENT FILE SYSTEM STATE:\n{context}\n\n"
            f"What is your next action?"
        )

    def _build_next_message(self):

        obs = self.fs.get_observation()
        context = build_prompt_context(obs)

        return (
            f"CURRENT FILE SYSTEM STATE:\n{context}\n\n"
            f"What is your next action? Reply in JSON only."
        )

    def _parse_response(self, text):

        text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()

        try:
            return json.loads(text)

        except:

            match = re.search(r"\{.*\}", text, re.DOTALL)

            if match:

                try:
                    return json.loads(match.group(0))
                except:
                    pass

        return {
            "thought": "Failed to parse",
            "action": "done",
            "params": {}
        }

    def step_once(self):

        if self.done:

            return {
                "step": self.step,
                "done": True
            }

        if self.step == 0:

            user_content = self._build_first_message()

        else:

            user_content = self._build_next_message()

        self.messages.append({
            "role": "user",
            "content": user_content
        })

        response = client.chat.completions.create(
            model=MODEL_NAME,
            messages=self.messages,
            temperature=0.0
        )

        assistant_text = response.choices[0].message.content

        self.messages.append({
            "role": "assistant",
            "content": assistant_text
        })

        parsed = self._parse_response(assistant_text)

        action_name = parsed.get("action", "")
        params = parsed.get("params", {})
        thought = parsed.get("thought", "")

        self.step += 1

        if action_name == "done":

            self.done = True

            return {
                "step": self.step,
                "thought": thought,
                "action": "done",
                "result": {
                    "success": True,
                    "message": "Task completed"
                },
                "done": True
            }

        result = execute_action(
            self.fs,
            action_name,
            params
        )

        return {
            "step": self.step,
            "thought": thought,
            "action": action_name,
            "params": params,
            "result": result,
            "done": False
        }

    def run(self, verbose=False):

        while not self.done and self.step < MAX_AGENT_STEPS:

            result = self.step_once()

            if result.get("done"):
                break

        self.fs.save_state()

        return []