File size: 6,844 Bytes
19a826b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8680b8f
 
 
19a826b
8680b8f
 
 
 
8a190fe
8680b8f
 
 
 
 
 
cfdb7f5
8680b8f
 
 
 
 
 
 
 
cfdb7f5
8680b8f
 
 
cfdb7f5
8680b8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19a826b
 
 
 
 
 
 
8680b8f
19a826b
8680b8f
19a826b
 
8680b8f
19a826b
 
 
 
 
8680b8f
19a826b
 
8680b8f
 
 
 
 
19a826b
8680b8f
19a826b
8680b8f
 
 
19a826b
 
8680b8f
19a826b
 
8680b8f
 
19a826b
cfdb7f5
8680b8f
cfdb7f5
8680b8f
19a826b
 
8680b8f
 
19a826b
 
 
 
 
 
8680b8f
19a826b
 
 
 
 
 
 
 
8a190fe
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
"""
Project Name: Autonomous AI Orchestrator

Description:
An end-to-end, self-improving AI agent framework that takes user goals and autonomously:

- Plans multi-step workflows (Research, Learn, Develop, Execute, Diagnose, Review)
- Performs web searches and aggregates reliable information
- Generates and safely executes Python code
- Self-evaluates and optimizes its own processes
- Provides a Learning Coach for personalized, source-backed teaching
- Persists session memory, logs activities, and snapshots full state for audit and rollback

Instructions:
1. **Dependencies**: Ensure your `requirements.txt` contains:
   ```
   duckduckgo-search
   gradio
   requests
   python-dotenv
   feedparser
   ```
2. **Module Structure**: Place the following modules alongside your main script (`app.py`):
   - `memory.py`
   - `planner.py`
   - `executor.py`
   - `critic.py`
   - `cognitive_engine.py`
   - `web_searcher.py`
   - `hf_packager.py`
   - (Optional CSS: `style.css` for UI styling)
3. **Run the Application**:
   ```bash
   python app.py
   ```
4. **Access Interfaces**:
   - **Gradio UI**: Navigate to `http://<host>:<port>/ui` for Task Execution and Learning Coach tabs
   - **API Endpoints**:
     - `GET /status` β€” Health check and available routes
     - `GET /generate?prompt=<text>` β€” Quick text generation
     - `POST /generate` β€” JSON-based generation with session tracking
     - `GET /memory/{session_id}` β€” Retrieve session history
     - `GET /summary/{session_id}` β€” Summarize recent interactions
5. **Persistence & Logs**:
   - Activity logs in `log.txt`
   - Session memory stored in `memory.json`
   - Snapshots saved under `snapshots/` with recoverable JSON files
"""

import os
import zipfile
import base64
import gradio as gr
import uuid
import json
import logging
import datetime
from memory_manager import MemoryManager
from planner import Planner
from executor import Executor
from critic import Critic
from cognitive_engine import CognitiveEngine
from web_searcher import WebSearcher
from hf_packager import HFSpacePackager

# Initialize components
memory = MemoryManager()
planner = Planner()
executor = Executor()
critic = Critic()
cog_engine = CognitiveEngine()
web_searcher = WebSearcher()
packager = HFSpacePackager()

# Set up logging
logging.basicConfig(filename='log.txt', level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')

class AutonomousAgent:
    def __init__(self):
        self.state_file = "state.json"
        self.load_state()
        
    def load_state(self):
        try:
            with open(self.state_file, 'r') as f:
                self.state = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            self.state = {"sessions": {}}
            self.save_state()
    
    def save_state(self):
        with open(self.state_file, 'w') as f:
            json.dump(self.state, f, indent=2)
    
    def process_goal(self, goal, session_id=None):
        try:
            if not session_id:
                session_id = str(uuid.uuid4())
                self.state["sessions"][session_id] = {"goal": goal, "status": "processing"}
                memory.init_session(session_id)
                self.save_state()
            
            # Add to memory
            memory.add(session_id, "user_goal", goal)
            
            # Plan the task
            plan = planner.plan_task(goal, memory.get(session_id))
            memory.add(session_id, "plan", plan)
            
            # Execute plan
            results = []
            for step in plan:
                key = step.split(":")[0].lower()
                if key in ["research", "search"]:
                    query = step.split(":",1)[1].strip()
                    res = web_searcher.search(query)
                    memory.add(session_id, f"search:{query}", res)
                    results.append(f"πŸ” Search '{query}': {res[:300]}...")
                elif key in ["develop", "code"]:
                    code = cog_engine.generate_code(step, memory.get(session_id))
                    out = executor.execute_code(code)
                    memory.add(session_id, "generated_code", code)
                    memory.add(session_id, "execution_result", out)
                    review = critic.review(step, out)
                    memory.add(session_id, "review", review)
                    if "error" in review.lower():
                        improved = cog_engine.improve_code(code, review)
                        memory.add(session_id, "enhanced_code", improved)
                        out = executor.execute_code(improved)
                        results.append(f"πŸ› οΈ Enhanced code: {out}")
                    else:
                        results.append(f"βœ… Code executed: {out}")
                elif key in ["diagnose", "check"]:
                    issues = cog_engine.identify_improvements(step)
                    memory.add(session_id, "diagnosis", issues)
                    if issues:
                        fixes = cog_engine.generate_enhancements(issues)
                        cog_engine.apply_enhancements(fixes)
                        results.append(f"βš™οΈ Repaired: {', '.join(issues)}")
                    else:
                        results.append("βœ… Healthy")
            
            self.state["sessions"][session_id]["status"] = "completed"
            self.save_state()
            snap = packager.create_snapshot({"session_id": session_id, "memory": memory.get(session_id), "results": results})
            return "\n\n".join(results), session_id, snap
        except Exception as e:
            logging.error(f"Error: {e}", exc_info=True)
            issues = [str(e)]
            fixes = cog_engine.generate_enhancements(issues)
            cog_engine.apply_enhancements(fixes)
            return f"⚠️ Error occurred: {e}", session_id, ""

agent = AutonomousAgent()

with gr.Blocks(css="style.css", title="Autonomous AI") as demo:
    sid = gr.State()
    hist = gr.State({"history": []})
    gr.Markdown("# πŸ€– Autonomous AI System")
    with gr.Tab("Task Execution"):
        inp = gr.Textbox(label="Your Goal")
        btn = gr.Button("Execute Goal")
        out = gr.Textbox(label="Results", lines=10)
        sid_box = gr.Textbox(label="Session ID")
        snap_box = gr.Textbox(label="Snapshot URL")
        btn.click(agent.process_goal, [inp, sid], [out, sid_box, snap_box])
    with gr.Tab("Learning Coach"):
        chat = gr.Chatbot()
        q_in = gr.Textbox(label="Your Question")
        ask = gr.Button("Ask")
        clear = gr.Button("Clear")
        kb = gr.Markdown("")
        ask.click(lambda q,h: (h+[(q, cog_engine.learning_coach_response(q))], h), [q_in, hist], [chat, hist])
        clear.click(lambda h: ([],h), [hist], [chat, hist])

demo.launch()