Spaces:
Runtime error
Runtime error
Upload 9 files
Browse files- agents/critic.py +1 -5
- agents/executor.py +1 -8
- agents/planner.py +1 -9
- app.py +1 -206
- knowledge/state.json +1 -19
- memory.py +5 -33
- src/core/cognitive_engine.py +3 -15
- src/utils/hf_packager.py +1 -21
agents/critic.py
CHANGED
@@ -1,5 +1 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
def review_result(step, result):
|
4 |
-
# Placeholder: review the execution result and return feedback
|
5 |
-
return f"Review for step '{step}': Success"
|
|
|
1 |
+
def review_result(step, result): return f'Reviewed {step} -> {result}'
|
|
|
|
|
|
|
|
agents/executor.py
CHANGED
@@ -1,8 +1 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
def execute_step(step):
|
4 |
-
# Placeholder: execute the given step and return a result string
|
5 |
-
return f"Executed: {step}"
|
6 |
-
|
7 |
-
def execute_step(step):
|
8 |
-
return f"Executed: {step} (simulated)"
|
|
|
1 |
+
def execute_step(step): return f'Executed: {step}'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
agents/planner.py
CHANGED
@@ -1,9 +1 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
def plan_task(goal, memory):
|
4 |
-
# Placeholder: create a plan (list of steps) to accomplish the goal
|
5 |
-
return [f"Step 1 towards {goal}", f"Step 2 towards {goal}"]
|
6 |
-
|
7 |
-
def plan_task(goal, memory):
|
8 |
-
return [f"Analyze: {goal}", "Generate code", "Review & validate"]
|
9 |
-
|
|
|
1 |
+
def plan_task(goal, memory): return [f'Plan step for: {goal}']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app.py
CHANGED
@@ -1,206 +1 @@
|
|
1 |
-
# app.
|
2 |
-
|
3 |
-
from fastapi import FastAPI, Request, HTTPException
|
4 |
-
from fastapi.responses import JSONResponse
|
5 |
-
import gradio as gr
|
6 |
-
import uuid
|
7 |
-
import time
|
8 |
-
import logging
|
9 |
-
import os
|
10 |
-
import json
|
11 |
-
import psutil
|
12 |
-
from datetime import datetime
|
13 |
-
from pydantic import BaseModel, constr
|
14 |
-
from ctransformers import AutoModelForCausalLM
|
15 |
-
from src.core.cognitive_engine import CognitiveEngine
|
16 |
-
from src.utils.hf_packager import HFSpacePackager
|
17 |
-
from agents.planner import plan_task
|
18 |
-
from agents.executor import execute_step
|
19 |
-
from agents.critic import review_result
|
20 |
-
from memory import init_memory, add_to_memory, get_memory, get_summary, search_memory
|
21 |
-
|
22 |
-
# ========== Initialization ==========
|
23 |
-
logging.basicConfig(filename="app.log", level=logging.INFO)
|
24 |
-
app = FastAPI()
|
25 |
-
memory = init_memory()
|
26 |
-
|
27 |
-
llm_model = AutoModelForCausalLM.from_pretrained(
|
28 |
-
"TheBloke/zephyr-7B-alpha-GGUF",
|
29 |
-
model_file="zephyr-7b-alpha.Q4_K_M.gguf",
|
30 |
-
model_type="llama",
|
31 |
-
max_new_tokens=256,
|
32 |
-
temperature=0.7
|
33 |
-
)
|
34 |
-
cognitive_engine = CognitiveEngine(llm_model)
|
35 |
-
packager = HFSpacePackager()
|
36 |
-
|
37 |
-
# ========== Pydantic Models ==========
|
38 |
-
class GenerateRequest(BaseModel):
|
39 |
-
prompt: constr(min_length=5, max_length=1000)
|
40 |
-
session_id: constr(min_length=3, max_length=50)
|
41 |
-
|
42 |
-
# ========== Routes ==========
|
43 |
-
@app.get("/")
|
44 |
-
def home():
|
45 |
-
return {"message": "✅ Autonomous AI API is live", "routes": ["/status", "/generate", "/ui"]}
|
46 |
-
|
47 |
-
@app.get("/status")
|
48 |
-
def status():
|
49 |
-
return {"status": "active", "agents": ["planner", "executor", "critic"]}
|
50 |
-
|
51 |
-
@app.post("/generate")
|
52 |
-
def generate_post(data: GenerateRequest):
|
53 |
-
start = time.time()
|
54 |
-
try:
|
55 |
-
response = llm_model(data.prompt)
|
56 |
-
latency = round(time.time() - start, 2)
|
57 |
-
add_to_memory(data.session_id, data.prompt, response)
|
58 |
-
logging.info(f"[{data.session_id}] Prompt processed in {latency}s")
|
59 |
-
return {"session_id": data.session_id, "response": response, "latency": latency}
|
60 |
-
except Exception as e:
|
61 |
-
raise HTTPException(status_code=500, detail=str(e))
|
62 |
-
|
63 |
-
@app.get("/memory")
|
64 |
-
def view_memory():
|
65 |
-
return {"history": get_memory()}
|
66 |
-
|
67 |
-
@app.get("/memory/{session_id}")
|
68 |
-
def session_memory(session_id: str):
|
69 |
-
return {"session_id": session_id, "history": get_memory(session_id)}
|
70 |
-
|
71 |
-
@app.get("/summary/{session_id}")
|
72 |
-
def memory_summary(session_id: str):
|
73 |
-
return {"session_id": session_id, "summary": get_summary(session_id)}
|
74 |
-
|
75 |
-
@app.middleware("http")
|
76 |
-
async def auth_middleware(request: Request, call_next):
|
77 |
-
if request.url.path.startswith("/generate") and request.headers.get("X-API-Key") != "your-secret":
|
78 |
-
return JSONResponse(status_code=401, content={"detail": "Invalid API Key"})
|
79 |
-
return await call_next(request)
|
80 |
-
|
81 |
-
# ========== Knowledge Base ==========
|
82 |
-
def load_knowledge():
|
83 |
-
try:
|
84 |
-
with open("knowledge/state.json", "r") as f:
|
85 |
-
return json.load(f)
|
86 |
-
except:
|
87 |
-
return {"improvements": [], "solutions": {}, "tasks": []}
|
88 |
-
|
89 |
-
def save_knowledge(data):
|
90 |
-
with open("knowledge/state.json", "w") as f:
|
91 |
-
json.dump(data, f, indent=2)
|
92 |
-
|
93 |
-
# ========== Autonomous Agents ==========
|
94 |
-
def run_cycle(task_description):
|
95 |
-
knowledge = load_knowledge()
|
96 |
-
knowledge["tasks"].append(task_description)
|
97 |
-
save_knowledge(knowledge)
|
98 |
-
try:
|
99 |
-
improvements = cognitive_engine.identify_improvements(task_description)
|
100 |
-
code_updates = cognitive_engine.generate_enhancements(improvements)
|
101 |
-
if cognitive_engine.apply_enhancements(code_updates):
|
102 |
-
snapshot_url = packager.create_snapshot()
|
103 |
-
return f"✅ Task completed! Snapshot: {snapshot_url}", code_updates, "\n".join(improvements)
|
104 |
-
return "❌ Improvement failed - see logs", "", ""
|
105 |
-
except Exception as e:
|
106 |
-
return f"⚠️ Critical error: {str(e)}", "", ""
|
107 |
-
|
108 |
-
def run_agents(goal, memory, session_id=None):
|
109 |
-
session_id = session_id or str(uuid.uuid4())[:8]
|
110 |
-
timestamp = datetime.now().isoformat(timespec="seconds")
|
111 |
-
log = f"[{timestamp}] Session {session_id}: Goal: {goal}\n"
|
112 |
-
history = search_memory(goal, memory)
|
113 |
-
context = "\n".join(history[:3]) if history else "No relevant memory found."
|
114 |
-
plan = plan_task(goal, memory)
|
115 |
-
add_to_memory(session_id, f"🧠 Context: {context}")
|
116 |
-
add_to_memory(session_id, f"🗂 Plan: {plan}")
|
117 |
-
outputs = []
|
118 |
-
for step in plan:
|
119 |
-
result = execute_step(step)
|
120 |
-
add_to_memory(session_id, f"🔧 Executor ran: {step} -> {result}")
|
121 |
-
review = review_result(step, result)
|
122 |
-
add_to_memory(session_id, f"🔍 Critic: {review}")
|
123 |
-
step_log = f"🔹 Step: {step}\n🛠 Result: {result}\n🧠 Review: {review}\n"
|
124 |
-
log += step_log + "\n"
|
125 |
-
outputs.append(step_log)
|
126 |
-
with open("log.txt", "a") as f:
|
127 |
-
f.write(log + "\n")
|
128 |
-
return "\n".join(outputs)
|
129 |
-
|
130 |
-
def agent_interface(goal):
|
131 |
-
return run_agents(goal, memory)
|
132 |
-
|
133 |
-
def get_resource_usage():
|
134 |
-
return {"cpu": f"{psutil.cpu_percent()}%", "memory": f"{psutil.virtual_memory().percent}%", "disk": f"{psutil.disk_usage('/').percent}%"}
|
135 |
-
|
136 |
-
def get_task_history():
|
137 |
-
knowledge = load_knowledge()
|
138 |
-
return "\n".join([f"- {task}" for task in knowledge.get("tasks", [])[-5:]]) or "No task history available."
|
139 |
-
|
140 |
-
def submit_manual_code(code):
|
141 |
-
try:
|
142 |
-
if cognitive_engine.apply_enhancements(code):
|
143 |
-
snapshot_url = packager.create_snapshot()
|
144 |
-
return f"✅ Code applied! Snapshot: {snapshot_url}", code
|
145 |
-
return "❌ Code application failed", code
|
146 |
-
except Exception as e:
|
147 |
-
return f"⚠️ Error: {str(e)}", code
|
148 |
-
|
149 |
-
# ========== Gradio UI ==========
|
150 |
-
with gr.Blocks(css="static/style.css", theme=gr.themes.Soft()) as demo:
|
151 |
-
gr.Markdown("# 🤖 Multi-Agent Autonomous AI System")
|
152 |
-
with gr.Tab("Multi-Agent Task"):
|
153 |
-
goal_input = gr.Textbox(label="Describe your task", placeholder="What do you want to accomplish?", lines=3)
|
154 |
-
agent_output = gr.Textbox(label="Multi-Agent Process", lines=10, interactive=False)
|
155 |
-
run_agents_btn = gr.Button("🚀 Run Agents", variant="primary")
|
156 |
-
run_agents_btn.click(agent_interface, inputs=[goal_input], outputs=[agent_output])
|
157 |
-
gr.Markdown("### Code Guidelines")
|
158 |
-
gr.Markdown("""
|
159 |
-
1. Ensure backward compatibility
|
160 |
-
2. Include necessary imports
|
161 |
-
3. Add comments explaining changes
|
162 |
-
4. Avoid system-critical modifications
|
163 |
-
""")
|
164 |
-
with gr.Tab("Cognitive Engine"):
|
165 |
-
with gr.Row():
|
166 |
-
with gr.Column():
|
167 |
-
task_input = gr.Textbox(label="Describe your improvement task", lines=3)
|
168 |
-
submit_task = gr.Button("🚀 Execute Task", variant="primary")
|
169 |
-
resource_display = gr.JSON(value=get_resource_usage(), label="Current Status")
|
170 |
-
refresh_btn = gr.Button("🔄 Refresh Status")
|
171 |
-
with gr.Column():
|
172 |
-
task_output = gr.Textbox(label="Task Status", interactive=False)
|
173 |
-
improvement_list = gr.Textbox(label="Identified Improvements", interactive=False)
|
174 |
-
generated_code = gr.Code(label="Generated Code", language="python", interactive=True)
|
175 |
-
submit_task.click(run_cycle, inputs=[task_input], outputs=[task_output, generated_code, improvement_list])
|
176 |
-
refresh_btn.click(get_resource_usage, inputs=[], outputs=resource_display)
|
177 |
-
with gr.Tab("Manual Code"):
|
178 |
-
with gr.Row():
|
179 |
-
with gr.Column():
|
180 |
-
manual_code = gr.Code(label="Submit Your Own Code", language="python", value="# Write your code enhancements here", interactive=True)
|
181 |
-
submit_manual = gr.Button("💾 Apply Code", variant="primary")
|
182 |
-
manual_output = gr.Textbox(label="Result")
|
183 |
-
with gr.Column():
|
184 |
-
gr.Markdown("### Code Guidelines")
|
185 |
-
gr.Markdown("""
|
186 |
-
1. Ensure backward compatibility
|
187 |
-
2. Include necessary imports
|
188 |
-
3. Add comments explaining changes
|
189 |
-
4. Avoid system-critical modifications
|
190 |
-
""")
|
191 |
-
submit_manual.click(submit_manual_code, inputs=[manual_code], outputs=[manual_output, manual_code])
|
192 |
-
with gr.Tab("Knowledge & History"):
|
193 |
-
task_history = gr.Textbox(label="Recent Tasks", value=get_task_history(), interactive=False)
|
194 |
-
gr.Markdown("### Memory Log")
|
195 |
-
memory_display = gr.Textbox(label="Agent Memory", value="\n".join(memory["texts"][-5:]), interactive=False)
|
196 |
-
refresh_knowledge = gr.Button("🔁 Refresh Knowledge")
|
197 |
-
refresh_knowledge.click(lambda: load_knowledge(), inputs=[], outputs=task_history)
|
198 |
-
|
199 |
-
# ========== Mount UI ==========
|
200 |
-
from fastapi.middleware.cors import CORSMiddleware
|
201 |
-
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
202 |
-
app = gr.mount_gradio_app(app, demo, path="/ui")
|
203 |
-
|
204 |
-
if __name__ == "__main__":
|
205 |
-
import uvicorn
|
206 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
1 |
+
# Full working app content will go here.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
knowledge/state.json
CHANGED
@@ -1,19 +1 @@
|
|
1 |
-
{
|
2 |
-
"knowledge_base": {
|
3 |
-
"name": "AutonomousAI_KnowledgeBase",
|
4 |
-
"description": "Used by the autonomous AI system for context and reasoning.",
|
5 |
-
"created_at": "2025-06-26T12:00:00Z",
|
6 |
-
"last_updated": "2025-06-26T12:00:00Z",
|
7 |
-
"total_documents": 0,
|
8 |
-
"total_tokens": 0,
|
9 |
-
"embedding_model": "sentence-transformers/all-MiniLM-L6-v2",
|
10 |
-
"vector_store": {
|
11 |
-
"type": "FAISS",
|
12 |
-
"index_file": "vector_index/faiss.index",
|
13 |
-
"dimension": 384,
|
14 |
-
"metric": "cosine"
|
15 |
-
},
|
16 |
-
"memory_enabled": true,
|
17 |
-
"status": "initialized"
|
18 |
-
}
|
19 |
-
}
|
|
|
1 |
+
{}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
memory.py
CHANGED
@@ -1,33 +1,5 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
def
|
6 |
-
if not os.path.exists(MEMORY_FILE):
|
7 |
-
with open(MEMORY_FILE, "w") as f:
|
8 |
-
json.dump({}, f)
|
9 |
-
with open(MEMORY_FILE, "r") as f:
|
10 |
-
return json.load(f)
|
11 |
-
|
12 |
-
def save_memory(memory):
|
13 |
-
with open(MEMORY_FILE, "w") as f:
|
14 |
-
json.dump(memory, f, indent=2)
|
15 |
-
|
16 |
-
def add_to_memory(session_id, prompt, response):
|
17 |
-
memory = init_memory()
|
18 |
-
memory.setdefault(session_id, [])
|
19 |
-
memory[session_id].append({"prompt": prompt, "response": response})
|
20 |
-
memory[session_id] = memory[session_id][-50:]
|
21 |
-
save_memory(memory)
|
22 |
-
|
23 |
-
def get_memory(session_id):
|
24 |
-
return init_memory().get(session_id, [])
|
25 |
-
|
26 |
-
def get_summary(session_id, max_items=3):
|
27 |
-
history = get_memory(session_id)
|
28 |
-
return history[-max_items:] if history else []
|
29 |
-
|
30 |
-
def search_memory(session_id, keyword):
|
31 |
-
history = get_memory(session_id)
|
32 |
-
results = [entry for entry in history if keyword.lower() in entry.get("prompt", "").lower()]
|
33 |
-
return results
|
|
|
1 |
+
def init_memory(): return {'texts': []}
|
2 |
+
def add_to_memory(sid, prompt, response): pass
|
3 |
+
def get_memory(sid=None): return []
|
4 |
+
def get_summary(sid): return 'summary'
|
5 |
+
def search_memory(q, mem): return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/core/cognitive_engine.py
CHANGED
@@ -1,16 +1,4 @@
|
|
1 |
class CognitiveEngine:
|
2 |
-
def
|
3 |
-
|
4 |
-
|
5 |
-
def identify_improvements(self, task_description):
|
6 |
-
prompt = f"Suggest improvements:\n\nTask: {task_description}"
|
7 |
-
return self.model(prompt).split("\n")
|
8 |
-
|
9 |
-
def generate_enhancements(self, improvements):
|
10 |
-
prompt = "Generate code for improvements:\n" + "\n".join(improvements)
|
11 |
-
return self.model(prompt)
|
12 |
-
|
13 |
-
def apply_enhancements(self, code):
|
14 |
-
print("Applying enhancements...")
|
15 |
-
print(code)
|
16 |
-
return True
|
|
|
1 |
class CognitiveEngine:
|
2 |
+
def identify_improvements(self, task): return ['Fix bug']
|
3 |
+
def generate_enhancements(self, targets): return 'def fix(): pass'
|
4 |
+
def apply_enhancements(self, code): return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/utils/hf_packager.py
CHANGED
@@ -1,22 +1,2 @@
|
|
1 |
-
# src/utils/hf_packager.py
|
2 |
-
|
3 |
-
import os
|
4 |
-
from datetime import datetime
|
5 |
-
|
6 |
class HFSpacePackager:
|
7 |
-
def
|
8 |
-
self.snapshot_dir = snapshot_dir
|
9 |
-
os.makedirs(snapshot_dir, exist_ok=True)
|
10 |
-
|
11 |
-
def create_snapshot(self, data=None):
|
12 |
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
13 |
-
filename = f"snapshot_{timestamp}.txt"
|
14 |
-
filepath = os.path.join(self.snapshot_dir, filename)
|
15 |
-
|
16 |
-
with open(filepath, "w") as f:
|
17 |
-
f.write("Snapshot created.\n")
|
18 |
-
if data:
|
19 |
-
f.write(str(data))
|
20 |
-
|
21 |
-
return f"https://huggingface.co/spaces/your-username/your-space-name/blob/main/{self.snapshot_dir}/{filename}"
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
class HFSpacePackager:
|
2 |
+
def create_snapshot(self, data=None): return 'https://fake.snapshot.url'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|