Spaces:
Runtime error
Runtime error
Upload 10 files
Browse files- README.md +2 -38
- app.py +74 -131
- memory/__init__.py +3 -0
- requirements.txt +2 -7
- src/agents/critic.py +1 -2
- src/agents/executor.py +1 -2
- src/agents/planner.py +1 -2
- src/core/cognitive_engine.py +2 -3
README.md
CHANGED
@@ -1,39 +1,3 @@
|
|
1 |
-
# Autonomous AI
|
2 |
|
3 |
-
This
|
4 |
-
- Search the web for information
|
5 |
-
- Learn from new information
|
6 |
-
- Generate and execute its own code
|
7 |
-
- Diagnose and repair itself
|
8 |
-
- Continuously improve its capabilities
|
9 |
-
|
10 |
-
## Features
|
11 |
-
|
12 |
-
1. **Goal-Oriented Processing**
|
13 |
-
Enter any goal and the AI will create a plan to achieve it
|
14 |
-
|
15 |
-
2. **Web Search Integration**
|
16 |
-
Uses DuckDuckGo to research topics and gather information
|
17 |
-
|
18 |
-
3. **Self-Coding Capability**
|
19 |
-
Generates Python code to solve problems and executes it safely
|
20 |
-
|
21 |
-
4. **Self-Diagnostic System**
|
22 |
-
Regularly checks its own performance and identifies improvements
|
23 |
-
|
24 |
-
5. **Continuous Learning**
|
25 |
-
Maintains memory of all sessions for context-aware operations
|
26 |
-
|
27 |
-
6. **Self-Repair Mechanism**
|
28 |
-
Automatically fixes identified issues in its own systems
|
29 |
-
|
30 |
-
7. **Snapshot System**
|
31 |
-
Creates recoverable snapshots of system state
|
32 |
-
|
33 |
-
## Setup Instructions
|
34 |
-
|
35 |
-
1. Install Python 3.8 or higher
|
36 |
-
|
37 |
-
2. Install requirements:
|
38 |
-
```bash
|
39 |
-
pip install -r requirements.txt
|
|
|
1 |
+
# Autonomous AI App
|
2 |
|
3 |
+
This app includes a FastAPI backend, Gradio frontend, and a multi-agent LLM system with learning capabilities.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app.py
CHANGED
@@ -1,140 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
-
import uuid
|
3 |
-
import json
|
4 |
-
import logging
|
5 |
import os
|
6 |
-
from memory import MemoryManager
|
7 |
-
from planner import Planner
|
8 |
-
from executor import Executor
|
9 |
-
from critic import Critic
|
10 |
-
from cognitive_engine import CognitiveEngine
|
11 |
-
from web_searcher import WebSearcher
|
12 |
-
from hf_packager import HFSpacePackager
|
13 |
|
14 |
-
|
15 |
-
|
16 |
-
planner = Planner()
|
17 |
-
executor = Executor()
|
18 |
-
critic = Critic()
|
19 |
-
cog_engine = CognitiveEngine()
|
20 |
-
web_searcher = WebSearcher()
|
21 |
-
packager = HFSpacePackager()
|
22 |
|
23 |
-
|
24 |
-
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
-
class
|
28 |
-
|
29 |
-
|
30 |
-
self.load_state()
|
31 |
-
|
32 |
-
def load_state(self):
|
33 |
-
try:
|
34 |
-
with open(self.state_file, 'r') as f:
|
35 |
-
self.state = json.load(f)
|
36 |
-
except (FileNotFoundError, json.JSONDecodeError):
|
37 |
-
self.state = {"sessions": {}}
|
38 |
-
self.save_state()
|
39 |
-
|
40 |
-
def save_state(self):
|
41 |
-
with open(self.state_file, 'w') as f:
|
42 |
-
json.dump(self.state, f, indent=2)
|
43 |
-
|
44 |
-
def process_goal(self, goal, session_id=None):
|
45 |
-
try:
|
46 |
-
if not session_id:
|
47 |
-
session_id = str(uuid.uuid4())
|
48 |
-
self.state["sessions"][session_id] = {"goal": goal, "status": "processing"}
|
49 |
-
memory.init_session(session_id)
|
50 |
-
self.save_state()
|
51 |
-
|
52 |
-
# Add to memory
|
53 |
-
memory.add(session_id, "user_goal", goal)
|
54 |
-
|
55 |
-
# Plan the task
|
56 |
-
plan = planner.plan_task(goal, memory.get(session_id))
|
57 |
-
memory.add(session_id, "plan", plan)
|
58 |
-
|
59 |
-
# Execute plan
|
60 |
-
results = []
|
61 |
-
for step in plan:
|
62 |
-
if "research" in step.lower() or "search" in step.lower():
|
63 |
-
# Perform web search
|
64 |
-
search_query = step.split(":")[1].strip() if ":" in step else goal
|
65 |
-
search_results = web_searcher.search(search_query)
|
66 |
-
memory.add(session_id, f"search:{search_query}", search_results)
|
67 |
-
results.append(f"🔍 Search results for '{search_query}':\n{search_results[:500]}...")
|
68 |
-
|
69 |
-
elif "develop" in step.lower() or "code" in step.lower():
|
70 |
-
# Generate and execute code
|
71 |
-
code = cog_engine.generate_code(step, memory.get(session_id))
|
72 |
-
execution_result = executor.execute_code(code)
|
73 |
-
memory.add(session_id, "generated_code", code)
|
74 |
-
memory.add(session_id, "execution_result", execution_result)
|
75 |
-
|
76 |
-
# Review and improve
|
77 |
-
review = critic.review(step, execution_result)
|
78 |
-
memory.add(session_id, "review", review)
|
79 |
-
|
80 |
-
if "error" in review.lower() or "improve" in review.lower():
|
81 |
-
enhanced_code = cog_engine.improve_code(code, review)
|
82 |
-
memory.add(session_id, "enhanced_code", enhanced_code)
|
83 |
-
execution_result = executor.execute_code(enhanced_code)
|
84 |
-
results.append(f"🛠️ Enhanced code execution:\n{execution_result}")
|
85 |
-
else:
|
86 |
-
results.append(f"✅ Code executed successfully:\n{execution_result}")
|
87 |
-
|
88 |
-
elif "diagnose" in step.lower() or "check" in step.lower():
|
89 |
-
# Self-diagnostic
|
90 |
-
issues = cog_engine.identify_improvements(step)
|
91 |
-
memory.add(session_id, "diagnosis", issues)
|
92 |
-
|
93 |
-
if issues:
|
94 |
-
fixes = cog_engine.generate_enhancements(issues)
|
95 |
-
cog_engine.apply_enhancements(fixes)
|
96 |
-
results.append(f"⚙️ System repaired: {', '.join(issues)}")
|
97 |
-
else:
|
98 |
-
results.append("✅ System health check passed")
|
99 |
-
|
100 |
-
self.state["sessions"][session_id]["status"] = "completed"
|
101 |
-
self.save_state()
|
102 |
-
snapshot_url = packager.create_snapshot({
|
103 |
-
"session_id": session_id,
|
104 |
-
"memory": memory.get(session_id),
|
105 |
-
"results": results
|
106 |
-
})
|
107 |
-
return "\n\n".join(results), session_id, snapshot_url
|
108 |
-
|
109 |
-
except Exception as e:
|
110 |
-
logging.error(f"Error processing goal: {str(e)}", exc_info=True)
|
111 |
-
# Attempt self-repair
|
112 |
-
issues = [f"Runtime error: {str(e)}"]
|
113 |
-
fixes = cog_engine.generate_enhancements(issues)
|
114 |
-
cog_engine.apply_enhancements(fixes)
|
115 |
-
return f"⚠️ Error occurred. Self-repair initiated: {str(e)}", session_id, ""
|
116 |
|
117 |
-
|
118 |
-
|
|
|
|
|
|
|
|
|
119 |
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
138 |
|
139 |
if __name__ == "__main__":
|
140 |
-
|
|
|
|
1 |
+
from fastapi import FastAPI, Request, HTTPException
|
2 |
+
from fastapi.responses import JSONResponse
|
3 |
+
from pydantic import BaseModel, constr
|
4 |
+
from memory import add_to_memory, get_memory, get_summary
|
5 |
+
from ctransformers import AutoModelForCausalLM
|
6 |
+
from src.core.cognitive_engine import CognitiveEngine
|
7 |
+
from src.agents.planner import plan_task
|
8 |
+
from src.agents.executor import execute_step
|
9 |
+
from src.agents.critic import review_result
|
10 |
+
import uuid, time, logging
|
11 |
import gradio as gr
|
|
|
|
|
|
|
12 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
+
app = FastAPI()
|
15 |
+
logging.basicConfig(filename="log.txt", level=logging.INFO)
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
+
llm_model = AutoModelForCausalLM.from_pretrained(
|
18 |
+
"TheBloke/zephyr-7B-alpha-GGUF",
|
19 |
+
model_file="zephyr-7b-alpha.Q4_K_M.gguf",
|
20 |
+
model_type="llama",
|
21 |
+
max_new_tokens=256,
|
22 |
+
temperature=0.7
|
23 |
+
)
|
24 |
+
cognitive_engine = CognitiveEngine(llm_model)
|
25 |
|
26 |
+
class GenerateRequest(BaseModel):
|
27 |
+
prompt: constr(min_length=5, max_length=1000)
|
28 |
+
session_id: constr(min_length=3, max_length=50)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
+
@app.get("/status")
|
31 |
+
def status():
|
32 |
+
return {
|
33 |
+
"message": "✅ Autonomous AI API is live",
|
34 |
+
"routes": ["/status", "/generate?prompt=...", "/generate [POST]", "/memory/{session_id}", "/summary/{session_id}"]
|
35 |
+
}
|
36 |
|
37 |
+
@app.get("/generate")
|
38 |
+
def generate(prompt: str):
|
39 |
+
return {"response": llm_model(prompt)}
|
40 |
+
|
41 |
+
@app.post("/generate")
|
42 |
+
def generate_post(data: GenerateRequest):
|
43 |
+
start = time.time()
|
44 |
+
try:
|
45 |
+
response = llm_model(data.prompt)
|
46 |
+
latency = round(time.time() - start, 2)
|
47 |
+
add_to_memory(data.session_id, data.prompt, response)
|
48 |
+
logging.info(f"[{data.session_id}] Prompt processed in {latency}s")
|
49 |
+
return {"session_id": data.session_id, "response": response, "latency": latency}
|
50 |
+
except Exception as e:
|
51 |
+
raise HTTPException(status_code=500, detail=str(e))
|
52 |
+
|
53 |
+
@app.get("/memory/{session_id}")
|
54 |
+
def session_memory(session_id: str):
|
55 |
+
return {"session_id": session_id, "history": get_memory(session_id)}
|
56 |
+
|
57 |
+
@app.get("/summary/{session_id}")
|
58 |
+
def memory_summary(session_id: str):
|
59 |
+
return {"session_id": session_id, "summary": get_summary(session_id)}
|
60 |
+
|
61 |
+
def agent_interface(goal):
|
62 |
+
session_id = str(uuid.uuid4())[:8]
|
63 |
+
context = get_summary(session_id)
|
64 |
+
plan = plan_task(goal, context)
|
65 |
+
output = []
|
66 |
+
for step in plan:
|
67 |
+
result = execute_step(step)
|
68 |
+
review = review_result(step, result)
|
69 |
+
output.append(f"Step: {step}\nResult: {result}\nReview: {review}\n")
|
70 |
+
return "\n".join(output)
|
71 |
+
|
72 |
+
with gr.Blocks() as demo:
|
73 |
+
with gr.Tab("Multi-Agent"):
|
74 |
+
inp = gr.Textbox(label="Task", placeholder="Describe your goal")
|
75 |
+
out = gr.Textbox(label="Agent Output")
|
76 |
+
btn = gr.Button("Run")
|
77 |
+
btn.click(agent_interface, inputs=[inp], outputs=[out])
|
78 |
+
|
79 |
+
gr.mount_gradio_app(app, demo, path="/")
|
80 |
|
81 |
if __name__ == "__main__":
|
82 |
+
import uvicorn
|
83 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
memory/__init__.py
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
def add_to_memory(sid, prompt, response): pass
|
2 |
+
def get_memory(sid): return []
|
3 |
+
def get_summary(sid): return 'Summary not implemented.'
|
requirements.txt
CHANGED
@@ -1,10 +1,5 @@
|
|
1 |
fastapi
|
2 |
uvicorn
|
3 |
-
ctransformers
|
4 |
gradio
|
5 |
-
|
6 |
-
|
7 |
-
faiss-cpu
|
8 |
-
duckduckgo-search
|
9 |
-
requests
|
10 |
-
python-dotenv
|
|
|
1 |
fastapi
|
2 |
uvicorn
|
|
|
3 |
gradio
|
4 |
+
pydantic
|
5 |
+
ctransformers
|
|
|
|
|
|
|
|
src/agents/critic.py
CHANGED
@@ -1,2 +1 @@
|
|
1 |
-
def review_result(step, result):
|
2 |
-
return f"Review passed for step: {step}"
|
|
|
1 |
+
def review_result(step, result): return f"Review OK for {step}"
|
|
src/agents/executor.py
CHANGED
@@ -1,2 +1 @@
|
|
1 |
-
def execute_step(step):
|
2 |
-
return f"Executed: {step} (simulated)"
|
|
|
1 |
+
def execute_step(step): return f"Executed {step}"
|
|
src/agents/planner.py
CHANGED
@@ -1,2 +1 @@
|
|
1 |
-
def plan_task(goal,
|
2 |
-
return [f"Analyze: {goal}", "Generate code", "Review & validate"]
|
|
|
1 |
+
def plan_task(goal, context): return [f"Plan for {goal}"]
|
|
src/core/cognitive_engine.py
CHANGED
@@ -1,4 +1,3 @@
|
|
1 |
class CognitiveEngine:
|
2 |
-
def
|
3 |
-
def
|
4 |
-
def apply_enhancements(self, code): return True
|
|
|
1 |
class CognitiveEngine:
|
2 |
+
def __init__(self, model=None): self.model = model
|
3 |
+
def learn(self, *args): return 'Learning completed.'
|
|