Agnuxo commited on
Commit
c330796
Β·
verified Β·
1 Parent(s): 03d2fe3

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +212 -0
app.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ OpenCLAW Agent β€” HuggingFace Spaces Dashboard
3
+ ================================================
4
+ Gradio interface with background agent loop.
5
+ """
6
+ import os
7
+ import sys
8
+ import json
9
+ import threading
10
+ import time
11
+ import logging
12
+ import gradio as gr
13
+ from datetime import datetime, timezone
14
+ from pathlib import Path
15
+
16
+ # Setup path
17
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
18
+
19
+ from core.config import Config
20
+ from core.agent import OpenCLAWAgent, AgentState
21
+ from core.strategy import StrategyReflector
22
+ from research.arxiv_fetcher import ArxivFetcher
23
+
24
+ # Logging
25
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
26
+ logger = logging.getLogger("openclaw")
27
+
28
+ STATE_DIR = Path(os.getenv("STATE_DIR", "state"))
29
+
30
+ # Background agent thread
31
+ agent_running = False
32
+ cycle_log = []
33
+
34
+
35
+ def run_background_agent():
36
+ """Background thread for autonomous operation."""
37
+ global agent_running, cycle_log
38
+ agent_running = True
39
+ interval = int(os.getenv("DAEMON_INTERVAL", "3600"))
40
+
41
+ while agent_running:
42
+ try:
43
+ config = Config.from_env()
44
+ agent = OpenCLAWAgent(config)
45
+ results = agent.run_cycle()
46
+
47
+ cycle_log.append({
48
+ "time": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"),
49
+ "cycle": results.get("cycle", "?"),
50
+ "actions": len(results.get("actions", [])),
51
+ "details": results.get("actions", [])
52
+ })
53
+ # Keep last 50 entries
54
+ cycle_log = cycle_log[-50:]
55
+
56
+ except Exception as e:
57
+ logger.error(f"Cycle error: {e}")
58
+ cycle_log.append({
59
+ "time": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"),
60
+ "error": str(e)
61
+ })
62
+
63
+ time.sleep(interval)
64
+
65
+
66
+ def get_status():
67
+ """Get current agent status as formatted text."""
68
+ try:
69
+ config = Config.from_env()
70
+ agent = OpenCLAWAgent(config)
71
+ status = agent.get_status()
72
+
73
+ lines = [
74
+ "πŸ€– **OpenCLAW Autonomous Agent**",
75
+ f"Advanced AI Systems Laboratory, Madrid",
76
+ "",
77
+ f"πŸ“Š **Statistics:**",
78
+ f" β€’ Cycles completed: {status['cycle_count']}",
79
+ f" β€’ Posts created: {status['posts_created']}",
80
+ f" β€’ Engagements: {status['engagement_count']}",
81
+ f" β€’ Papers shared: {status['papers_posted']}",
82
+ "",
83
+ f"πŸ”§ **Services:** {', '.join(status['services']) or 'None configured'}",
84
+ f"🧠 **LLM:** {'βœ… Online' if status['llm_available'] else '⚠️ Offline'}",
85
+ f"⚠️ **Errors:** {status['errors_count']}",
86
+ "",
87
+ f"πŸ• **Last Research:** {status['last_research'] or 'Never'}",
88
+ f"πŸ“ **Last Post:** {status['last_post'] or 'Never'}",
89
+ f"πŸ’¬ **Last Engage:** {status['last_engage'] or 'Never'}",
90
+ ]
91
+ return "\n".join(lines)
92
+ except Exception as e:
93
+ return f"Error getting status: {e}"
94
+
95
+
96
+ def get_papers():
97
+ """Get cached research papers."""
98
+ try:
99
+ fetcher = ArxivFetcher()
100
+ papers = fetcher.get_all_papers()
101
+
102
+ lines = [f"πŸ“š **{len(papers)} papers available:**\n"]
103
+ for p in papers:
104
+ lines.append(f"**{p.title}**")
105
+ lines.append(f" Authors: {', '.join(p.authors)}")
106
+ lines.append(f" URL: {p.url}")
107
+ lines.append("")
108
+ return "\n".join(lines)
109
+ except Exception as e:
110
+ return f"Error fetching papers: {e}"
111
+
112
+
113
+ def get_cycle_log():
114
+ """Get recent cycle log."""
115
+ if not cycle_log:
116
+ return "No cycles completed yet. Agent will run its first cycle within 1 hour."
117
+
118
+ lines = ["πŸ“‹ **Recent Agent Activity:**\n"]
119
+ for entry in reversed(cycle_log[-20:]):
120
+ if "error" in entry:
121
+ lines.append(f"❌ {entry['time']}: Error - {entry['error']}")
122
+ else:
123
+ lines.append(f"βœ… {entry['time']}: Cycle #{entry['cycle']} β€” {entry['actions']} actions")
124
+ for a in entry.get("details", []):
125
+ status = "βœ…" if a.get("status") == "ok" else "⚠️"
126
+ lines.append(f" {status} {a.get('task')}: {a.get('status')}")
127
+
128
+ return "\n".join(lines)
129
+
130
+
131
+ def run_manual_cycle():
132
+ """Manually trigger an agent cycle."""
133
+ try:
134
+ config = Config.from_env()
135
+ agent = OpenCLAWAgent(config)
136
+ results = agent.run_cycle()
137
+
138
+ lines = [f"βœ… Cycle #{results['cycle']} completed!\n"]
139
+ for a in results.get("actions", []):
140
+ status = "βœ…" if a.get("status") == "ok" else "⚠️"
141
+ lines.append(f"{status} {a.get('task')}: {json.dumps(a, indent=2)}")
142
+
143
+ return "\n".join(lines)
144
+ except Exception as e:
145
+ return f"❌ Error: {e}"
146
+
147
+
148
+ def get_strategy():
149
+ """Run strategy analysis."""
150
+ try:
151
+ reflector = StrategyReflector(str(STATE_DIR))
152
+ report = reflector.analyze()
153
+
154
+ lines = [
155
+ "🧠 **Strategy Analysis**\n",
156
+ "**Metrics:**"
157
+ ]
158
+ for k, v in report["metrics"].items():
159
+ lines.append(f" β€’ {k}: {v}")
160
+
161
+ lines.append("\n**Insights:**")
162
+ for i in report["insights"]:
163
+ lines.append(f" πŸ’‘ {i}")
164
+
165
+ lines.append("\n**Recommended Actions:**")
166
+ for a in report["strategy"]["actions"]:
167
+ lines.append(f" 🎯 {a}")
168
+
169
+ return "\n".join(lines)
170
+ except Exception as e:
171
+ return f"Error: {e}"
172
+
173
+
174
+ # Start background agent
175
+ bg_thread = threading.Thread(target=run_background_agent, daemon=True)
176
+ bg_thread.start()
177
+ logger.info("πŸ€– Background agent started")
178
+
179
+ # Gradio Interface
180
+ with gr.Blocks(title="OpenCLAW Agent", theme=gr.themes.Monochrome()) as demo:
181
+ gr.Markdown("""
182
+ # πŸ€– OpenCLAW β€” Autonomous Multi-Agent Scientific Research Platform
183
+ **Advanced AI Systems Laboratory, Madrid, Spain**
184
+ *Francisco Angulo de Lafuente β€” Winner NVIDIA & LlamaIndex Developer Contest 2024*
185
+
186
+ [GitHub](https://github.com/Agnuxo1) | [Scholar](https://scholar.google.com/citations?user=6nOpJ9IAAAAJ) | [ArXiv](https://arxiv.org/search/cs?searchtype=author&query=de+Lafuente,+F+A) | [Moltbook](https://www.moltbook.com/u/OpenCLAW-Neuromorphic)
187
+ """)
188
+
189
+ with gr.Tab("πŸ“Š Status"):
190
+ status_output = gr.Markdown(get_status())
191
+ gr.Button("πŸ”„ Refresh").click(fn=get_status, outputs=status_output)
192
+
193
+ with gr.Tab("πŸ“‹ Activity Log"):
194
+ log_output = gr.Markdown(get_cycle_log())
195
+ gr.Button("πŸ”„ Refresh").click(fn=get_cycle_log, outputs=log_output)
196
+
197
+ with gr.Tab("πŸ“š Research Papers"):
198
+ papers_output = gr.Markdown(get_papers())
199
+ gr.Button("πŸ”„ Refresh").click(fn=get_papers, outputs=papers_output)
200
+
201
+ with gr.Tab("🧠 Strategy"):
202
+ strategy_output = gr.Markdown(get_strategy())
203
+ gr.Button("πŸ”„ Analyze").click(fn=get_strategy, outputs=strategy_output)
204
+
205
+ with gr.Tab("⚑ Manual Trigger"):
206
+ gr.Markdown("Manually trigger an agent cycle:")
207
+ trigger_output = gr.Markdown("")
208
+ gr.Button("πŸš€ Run Cycle Now").click(fn=run_manual_cycle, outputs=trigger_output)
209
+
210
+
211
+ if __name__ == "__main__":
212
+ demo.launch(server_name="0.0.0.0", server_port=7860)