ScottzillaSystems commited on
Commit
90f7e9c
·
verified ·
1 Parent(s): b20273d

Upload wrapper.py

Browse files
Files changed (1) hide show
  1. wrapper.py +82 -0
wrapper.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Agent Zero Research - Literature analysis agent with workspace isolation."""
3
+
4
+ import os, sys, json, time, threading
5
+ from pathlib import Path
6
+ from datetime import datetime
7
+ import gradio as gr
8
+ import requests as req
9
+
10
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
11
+ AGENT_NAME = "Research"
12
+ AGENT_ROLE = "research_analyst"
13
+ MODEL_NAME = os.environ.get("MODEL_NAME", "DavidAU/Gemma-The-Writer-N-Restless-Quill-10B-Uncensored-GGUF")
14
+
15
+ WORKSPACE_DIR = Path("/app/workspace/projects/research")
16
+ SHARED_DIR = Path("/app/workspace/shared")
17
+ TASK_QUEUE_DIR = SHARED_DIR / "task_queue"
18
+ for d in [WORKSPACE_DIR, TASK_QUEUE_DIR]: d.mkdir(parents=True, exist_ok=True)
19
+
20
+ def query_model(prompt: str) -> str:
21
+ api_url = f"https://api-inference.huggingface.co/models/{MODEL_NAME}"
22
+ for attempt in range(3):
23
+ try:
24
+ resp = req.post(api_url, headers={"Authorization": f"Bearer {HF_TOKEN}"},
25
+ json={"inputs": prompt, "parameters": {"max_new_tokens": 4096, "temperature": 0.6}},
26
+ timeout=180)
27
+ if resp.status_code == 200:
28
+ r = resp.json()
29
+ return r[0].get("generated_text","") if isinstance(r,list) else str(r)
30
+ time.sleep(10*(attempt+1))
31
+ except: time.sleep(5)
32
+ return "[ERROR] Model unavailable"
33
+
34
+ def check_tasks():
35
+ tasks = []
36
+ for f in TASK_QUEUE_DIR.glob("*.json"):
37
+ t = json.loads(f.read_text())
38
+ if t.get("assigned_to") == "research" and t.get("status") == "pending":
39
+ tasks.append(t)
40
+ return tasks
41
+
42
+ def execute_task(task):
43
+ task["status"] = "in_progress"
44
+ (TASK_QUEUE_DIR / f"{task['task_id']}.json").write_text(json.dumps(task, indent=2))
45
+ prompt = f"You are a research analyst. Conduct thorough research on: {task['description']}. Provide citations, analysis, and recommendations."
46
+ result = query_model(prompt)
47
+ out_file = WORKSPACE_DIR / f"{task['task_id']}.md"
48
+ out_file.write_text(f"# Research: {task['description']}\n\n{result}")
49
+ task["status"] = "completed"
50
+ task["result"] = result[:2000]
51
+ task["output_file"] = str(out_file)
52
+ task["completed_at"] = datetime.now().isoformat()
53
+ (TASK_QUEUE_DIR / f"{task['task_id']}.json").write_text(json.dumps(task, indent=2))
54
+
55
+ def autonomous_loop():
56
+ while True:
57
+ for task in check_tasks(): execute_task(task)
58
+ time.sleep(60)
59
+
60
+ threading.Thread(target=autonomous_loop, daemon=True).start()
61
+
62
+ demo = gr.Blocks(title=f"Agent Zero - {AGENT_NAME}", theme=gr.themes.Soft())
63
+ with demo:
64
+ gr.Markdown(f"# 🔬 Agent Zero: {AGENT_NAME}\n**Role:** {AGENT_ROLE} | **Model:** {MODEL_NAME}")
65
+ with gr.Tabs():
66
+ with gr.TabItem("💬 Chat"):
67
+ chatbot = gr.Chatbot(height=400)
68
+ msg = gr.Textbox(label="Research topic")
69
+ send = gr.Button("Send")
70
+ def respond(m, h):
71
+ r = query_model(f"Research topic: {m}. Provide comprehensive analysis with citations.")
72
+ h = h or []; h.append((m, r[:2000])); return "", h
73
+ send.click(respond, [msg, chatbot], [msg, chatbot])
74
+ with gr.TabItem("📄 Research Reports"):
75
+ files = gr.Dropdown(label="Reports", choices=[f.name for f in WORKSPACE_DIR.glob("*.md")])
76
+ report = gr.Markdown()
77
+ def load_report(fname):
78
+ if fname: return (WORKSPACE_DIR / fname).read_text()
79
+ return ""
80
+ files.change(load_report, files, report)
81
+
82
+ demo.queue().launch(server_name="0.0.0.0", server_port=7860)