Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -21,4 +21,317 @@ gr.mount_gradio_app(app, gr_interface, path="/gradio")
|
|
21 |
|
22 |
@app.get("/")
|
23 |
def root():
|
24 |
-
return {"message": "Multi-Agent AI system with logging and memory."}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
@app.get("/")
|
23 |
def root():
|
24 |
+
return {"message": "Multi-Agent AI system with logging and memory."}
|
25 |
+
''',
|
26 |
+
|
27 |
+
from src.core.cognitive_engine import CognitiveEngine
|
28 |
+
from src.utils.hf_packager import HFSpacePackager
|
29 |
+
import gradio as gr
|
30 |
+
import time
|
31 |
+
import os
|
32 |
+
import psutil
|
33 |
+
import json
|
34 |
+
|
35 |
+
# Initialize components
|
36 |
+
cognitive_engine = CognitiveEngine()
|
37 |
+
packager = HFSpacePackager()
|
38 |
+
|
39 |
+
# Load knowledge base
|
40 |
+
def load_knowledge():
|
41 |
+
try:
|
42 |
+
with open("knowledge/state.json", "r") as f:
|
43 |
+
return json.load(f)
|
44 |
+
except:
|
45 |
+
return {"improvements": [], "solutions": {}, "tasks": []}
|
46 |
+
|
47 |
+
# Save knowledge base
|
48 |
+
def save_knowledge(data):
|
49 |
+
with open("knowledge/state.json", "w") as f:
|
50 |
+
json.dump(data, f, indent=2)
|
51 |
+
|
52 |
+
# Main autonomous cycle
|
53 |
+
def run_cycle(task_description):
|
54 |
+
knowledge = load_knowledge()
|
55 |
+
knowledge["tasks"].append(task_description)
|
56 |
+
save_knowledge(knowledge)
|
57 |
+
|
58 |
+
try:
|
59 |
+
improvement_targets = cognitive_engine.identify_improvements(task_description)
|
60 |
+
code_updates = cognitive_engine.generate_enhancements(improvement_targets)
|
61 |
+
|
62 |
+
if cognitive_engine.apply_enhancements(code_updates):
|
63 |
+
snapshot_url = packager.create_snapshot()
|
64 |
+
return (
|
65 |
+
f"β
Task completed! Snapshot: {snapshot_url}",
|
66 |
+
code_updates,
|
67 |
+
"\n".join(improvement_targets)
|
68 |
+
)
|
69 |
+
return (
|
70 |
+
"β Improvement failed - see logs",
|
71 |
+
"",
|
72 |
+
""
|
73 |
+
)
|
74 |
+
except Exception as e:
|
75 |
+
return (
|
76 |
+
f"β οΈ Critical error: {str(e)}",
|
77 |
+
"",
|
78 |
+
""
|
79 |
+
)
|
80 |
+
|
81 |
+
# Get system resources
|
82 |
+
def get_resource_usage():
|
83 |
+
return {
|
84 |
+
"cpu": f"{psutil.cpu_percent()}%",
|
85 |
+
"memory": f"{psutil.virtual_memory().percent}%",
|
86 |
+
"disk": f"{psutil.disk_usage('/').percent}%"
|
87 |
+
}
|
88 |
+
|
89 |
+
# Get task history
|
90 |
+
def get_task_history():
|
91 |
+
knowledge = load_knowledge()
|
92 |
+
return "\n".join([f"- {task}" for task in knowledge["tasks"][-5:]])
|
93 |
+
|
94 |
+
# Manual code submission
|
95 |
+
def submit_manual_code(code):
|
96 |
+
try:
|
97 |
+
if cognitive_engine.apply_enhancements(code):
|
98 |
+
snapshot_url = packager.create_snapshot()
|
99 |
+
return f"β
Code applied! Snapshot: {snapshot_url}", code
|
100 |
+
return "β Code application failed", code
|
101 |
+
except Exception as e:
|
102 |
+
return f"β οΈ Error: {str(e)}", code
|
103 |
+
|
104 |
+
with gr.Blocks(css="static/style.css", theme=gr.themes.Soft()) as demo:
|
105 |
+
knowledge = load_knowledge()
|
106 |
+
|
107 |
+
gr.Markdown("# π€ Interactive Autonomous AI System")
|
108 |
+
|
109 |
+
with gr.Tab("Task-Based Improvement"):
|
110 |
+
with gr.Row():
|
111 |
+
with gr.Column():
|
112 |
+
task_input = gr.Textbox(
|
113 |
+
label="Describe your improvement task",
|
114 |
+
placeholder="e.g., 'Optimize the validation system' or 'Add user authentication'",
|
115 |
+
lines=3
|
116 |
+
)
|
117 |
+
submit_task = gr.Button("π Execute Task", variant="primary")
|
118 |
+
|
119 |
+
gr.Markdown("### System Resources")
|
120 |
+
resource_display = gr.JSON(value=get_resource_usage(), label="Current Status")
|
121 |
+
refresh_btn = gr.Button("π Refresh Status")
|
122 |
+
|
123 |
+
with gr.Column():
|
124 |
+
task_output = gr.Textbox(label="Task Status", interactive=False)
|
125 |
+
improvement_list = gr.Textbox(label="Identified Improvements", interactive=False)
|
126 |
+
generated_code = gr.Code(
|
127 |
+
label="Generated Code",
|
128 |
+
language="python",
|
129 |
+
interactive=True
|
130 |
+
)
|
131 |
+
|
132 |
+
with gr.Tab("Manual Code Submission"):
|
133 |
+
with gr.Row():
|
134 |
+
with gr.Column():
|
135 |
+
manual_code = gr.Code(
|
136 |
+
label="Submit Your Own Code",
|
137 |
+
language="python",
|
138 |
+
value="# Write your code enhancements here",
|
139 |
+
interactive=True
|
140 |
+
)
|
141 |
+
submit_manual = gr.Button("πΎ Apply Code", variant="primary")
|
142 |
+
manual_output = gr.Textbox(label="Result")
|
143 |
+
with gr.Column():
|
144 |
+
gr.Markdown("### Code Guidelines")
|
145 |
+
gr.Markdown("""
|
146 |
+
1. Ensure backward compatibility
|
147 |
+
2. Include necessary imports
|
148 |
+
3. Add comments explaining changes
|
149 |
+
4. Avoid system-critical modifications
|
150 |
+
""")
|
151 |
+
|
152 |
+
with gr.Tab("Knowledge & History"):
|
153 |
+
task_history = gr.Textbox(
|
154 |
+
label="Recent Tasks",
|
155 |
+
value=get_task_history(),
|
156 |
+
interactive=False
|
157 |
+
)
|
158 |
+
gr.Markdown("### Improvement Database")
|
159 |
+
knowledge_display = gr.JSON(
|
160 |
+
value={k: v for k, v in knowledge.items() if k != "solutions"},
|
161 |
+
label="System Knowledge"
|
162 |
+
)
|
163 |
+
refresh_knowledge = gr.Button("π Refresh Knowledge")
|
164 |
+
|
165 |
+
# Task submission
|
166 |
+
submit_task.click(
|
167 |
+
run_cycle,
|
168 |
+
inputs=[task_input],
|
169 |
+
outputs=[task_output, generated_code, improvement_list]
|
170 |
+
)
|
171 |
+
|
172 |
+
# Manual code submission
|
173 |
+
submit_manual.click(
|
174 |
+
submit_manual_code,
|
175 |
+
inputs=[manual_code],
|
176 |
+
outputs=[manual_output, manual_code]
|
177 |
+
)
|
178 |
+
|
179 |
+
# Refresh actions
|
180 |
+
refresh_btn.click(
|
181 |
+
get_resource_usage,
|
182 |
+
inputs=[],
|
183 |
+
outputs=resource_display
|
184 |
+
)
|
185 |
+
|
186 |
+
refresh_knowledge.click(
|
187 |
+
lambda: load_knowledge(),
|
188 |
+
inputs=[],
|
189 |
+
outputs=knowledge_display
|
190 |
+
)
|
191 |
+
|
192 |
+
if __name__ == "__main__":
|
193 |
+
demo.launch(
|
194 |
+
server_name="0.0.0.0",
|
195 |
+
server_port=7860,
|
196 |
+
show_api=True
|
197 |
+
)
|
198 |
+
|
199 |
+
"orchestrator.py": '''
|
200 |
+
from agents.planner import plan_task
|
201 |
+
from agents.executor import execute_step
|
202 |
+
from agents.critic import review_result
|
203 |
+
from memory import add_to_memory, search_memory
|
204 |
+
import uuid
|
205 |
+
from datetime import datetime
|
206 |
+
|
207 |
+
def run_agents(goal, memory, session_id=None):
|
208 |
+
session_id = session_id or str(uuid.uuid4())[:8]
|
209 |
+
timestamp = datetime.now().isoformat(timespec="seconds")
|
210 |
+
|
211 |
+
log = f"[{timestamp}] Session {session_id}: Goal: {goal}\\n"
|
212 |
+
history = search_memory(goal, memory)
|
213 |
+
context = "\\n".join(history[:3]) if history else "No relevant memory found."
|
214 |
+
|
215 |
+
plan = plan_task(goal, memory)
|
216 |
+
add_to_memory(f"[{session_id}] π§ Context: {context}", memory)
|
217 |
+
add_to_memory(f"[{session_id}] π Plan: {plan}", memory)
|
218 |
+
|
219 |
+
outputs = []
|
220 |
+
for step in plan:
|
221 |
+
result = execute_step(step)
|
222 |
+
add_to_memory(f"[{session_id}] π§ Executor ran: {step} -> {result}", memory)
|
223 |
+
|
224 |
+
review = review_result(step, result)
|
225 |
+
add_to_memory(f"[{session_id}] π Critic: {review}", memory)
|
226 |
+
|
227 |
+
step_log = f"πΉ Step: {step}\\nπ Result: {result}\\nπ§ Review: {review}\\n"
|
228 |
+
log += step_log + "\\n"
|
229 |
+
outputs.append(step_log)
|
230 |
+
|
231 |
+
with open("log.txt", "a") as f:
|
232 |
+
f.write(log + "\\n")
|
233 |
+
|
234 |
+
return "\\n".join(outputs)
|
235 |
+
''',
|
236 |
+
|
237 |
+
"memory.py": '''
|
238 |
+
from sentence_transformers import SentenceTransformer
|
239 |
+
import numpy as np
|
240 |
+
import faiss
|
241 |
+
import json
|
242 |
+
import os
|
243 |
+
|
244 |
+
model = SentenceTransformer("all-MiniLM-L6-v2")
|
245 |
+
MEMORY_LOG = "memory_log.json"
|
246 |
+
|
247 |
+
def init_memory():
|
248 |
+
dim = 384
|
249 |
+
index = faiss.IndexFlatL2(dim)
|
250 |
+
memory = {"index": index, "texts": []}
|
251 |
+
if os.path.exists(MEMORY_LOG):
|
252 |
+
with open(MEMORY_LOG, "r") as f:
|
253 |
+
memory["texts"] = json.load(f)
|
254 |
+
vectors = np.array([model.encode([text])[0] for text in memory["texts"]])
|
255 |
+
if len(vectors) > 0:
|
256 |
+
memory["index"].add(vectors)
|
257 |
+
return memory
|
258 |
+
|
259 |
+
def add_to_memory(text, memory):
|
260 |
+
vec = model.encode([text])[0]
|
261 |
+
memory["index"].add(np.array([vec]))
|
262 |
+
memory["texts"].append(text)
|
263 |
+
with open(MEMORY_LOG, "w") as f:
|
264 |
+
json.dump(memory["texts"], f)
|
265 |
+
|
266 |
+
def search_memory(query, memory, k=5):
|
267 |
+
vec = model.encode([query])[0]
|
268 |
+
D, I = memory["index"].search(np.array([vec]), k)
|
269 |
+
return [memory["texts"][i] for i in I[0] if i < len(memory["texts"])]
|
270 |
+
''',
|
271 |
+
|
272 |
+
"agents/planner.py": '''
|
273 |
+
def plan_task(goal, memory):
|
274 |
+
plan = []
|
275 |
+
if "website" in goal:
|
276 |
+
plan.extend([
|
277 |
+
"Create basic HTML structure",
|
278 |
+
"Add styling with CSS",
|
279 |
+
"Add interactivity with JavaScript",
|
280 |
+
"Review and test website"
|
281 |
+
])
|
282 |
+
else:
|
283 |
+
plan.extend([
|
284 |
+
f"Understand the goal: {goal}",
|
285 |
+
"Find the best method to solve it",
|
286 |
+
"Execute and gather result"
|
287 |
+
])
|
288 |
+
return plan
|
289 |
+
''',
|
290 |
+
|
291 |
+
"agents/executor.py": '''
|
292 |
+
import subprocess
|
293 |
+
|
294 |
+
def execute_step(step):
|
295 |
+
step_lower = step.lower()
|
296 |
+
if "html" in step_lower:
|
297 |
+
return "<html><body>Hello Multi-Agent World!</body></html>"
|
298 |
+
elif "calculate" in step_lower:
|
299 |
+
try:
|
300 |
+
expression = step_lower.replace("calculate", "").strip()
|
301 |
+
return str(eval(expression))
|
302 |
+
except:
|
303 |
+
return "Calculation error."
|
304 |
+
elif "python" in step_lower or "code" in step_lower:
|
305 |
+
try:
|
306 |
+
code = step.split("```python")[1].split("```")[0] if "```python" in step else step
|
307 |
+
result = subprocess.check_output(["python3", "-c", code], stderr=subprocess.STDOUT, timeout=5)
|
308 |
+
return result.decode()
|
309 |
+
except Exception as e:
|
310 |
+
return f"Error running Python code: {e}"
|
311 |
+
else:
|
312 |
+
return f"No defined execution path for: {step}"
|
313 |
+
''',
|
314 |
+
|
315 |
+
"agents/critic.py": '''
|
316 |
+
def review_result(step, result):
|
317 |
+
if not result or "error" in result.lower():
|
318 |
+
return f"β Step failed or incomplete: {step}. Result: {result[:80]}"
|
319 |
+
if len(result) < 10:
|
320 |
+
return f"β οΈ Result seems too short for step: {step}."
|
321 |
+
return f"β
Step successful. Result preview: {result[:80]}"
|
322 |
+
''',
|
323 |
+
|
324 |
+
"requirements.txt": '''
|
325 |
+
fastapi
|
326 |
+
uvicorn
|
327 |
+
gradio
|
328 |
+
faiss-cpu
|
329 |
+
sentence-transformers
|
330 |
+
numpy
|
331 |
+
''',
|
332 |
+
|
333 |
+
".huggingface.yaml": '''
|
334 |
+
sdk: gradio
|
335 |
+
sdk_version: 3.50.2
|
336 |
+
app_file: app.py
|
337 |
+
''',
|