puravky commited on
Commit
a3fbafa
·
verified ·
1 Parent(s): 19c50da
Files changed (1) hide show
  1. app.py +87 -96
app.py CHANGED
@@ -1,144 +1,135 @@
1
- import os
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
  import spaces
6
  from smolagents import CodeAgent, tool, LiteLLMModel
7
 
8
- # Lightweight tools - no heavy imports inside, fixed timeouts
9
  @tool
10
  def web_search(query: str) -> str:
11
- """Searches the web for facts.
12
  Args:
13
- query: Search query
14
  """
15
  try:
16
  try:
17
  from duckduckgo_search import DDGS
18
  except ImportError:
19
  from ddgs import DDGS
20
- with DDGS(timeout=8) as ddgs:
21
- res = list(ddgs.text(query, max_results=3))
22
- if not res:
23
- return "No results"
24
- return "\n".join([f"{r['title']}: {r['body'][:120]}" for r in res[:3]])
25
  except Exception as e:
26
- return f"Search failed: {e}"
27
-
28
- @tool
29
- def visit_webpage(url: str) -> str:
30
- """Visits a webpage.
31
- Args:
32
- url: URL to visit
33
- """
34
- try:
35
- from markdownify import markdownify
36
- r = requests.get(url, timeout=6, headers={"User-Agent": "Mozilla/5.0"})
37
- r.raise_for_status()
38
- return markdownify(r.text)[:5000]
39
- except Exception as e:
40
- return f"Visit error: {e}"
41
 
42
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
43
 
44
- class UltraFastGroqAgent:
45
  def __init__(self):
46
  key = os.getenv("GROQ_API_KEY")
47
  if not key:
48
- raise ValueError("Add GROQ_API_KEY secret in Settings -> Secrets (get from https://console.groq.com/keys)")
49
- # 8B-instant is 5x faster than 70B - critical to stay under 192s
50
- self.model = LiteLLMModel(
51
- model_id="groq/llama-3.1-8b-instant",
52
- api_key=key,
53
- temperature=0.1,
54
- )
55
- self.agent = CodeAgent(
56
- tools=[web_search, visit_webpage],
57
- model=self.model,
58
- add_base_tools=True,
59
- max_steps=4, # 4 steps only - fastest
60
- )
61
- self.agent.prompt_templates["system_prompt"] = "You are fast GAIA solver. Rules: FINAL ANSWER must be ONLY answer, short. Format: FINAL ANSWER: [answer]. Use web_search once max. Be quick.\n" + self.agent.prompt_templates["system_prompt"]
62
 
63
- def ask(self, q, file_path=None):
64
- full = q
65
- if file_path:
66
- full = f"File at {file_path}. Question: {q}"
67
  try:
68
- res = self.agent.run(full)
69
- s = str(res)
70
  if "FINAL ANSWER:" in s:
71
  s = s.split("FINAL ANSWER:")[-1]
72
- return s.split("\n")[0].strip().strip('"').strip("'")[:200]
73
- except Exception as e:
74
  return "0"
75
 
76
- # ONLY ONE GPU DECORATOR, DURATION 60s (not 270s) - this is the key to fit in 192s quota
77
- # Actual runtime ~90-110s, billed less than 192s
78
- @spaces.GPU(duration=60)
79
- def run_and_submit_all(profile: gr.OAuthProfile | None):
80
  if not profile:
81
- return "Login first with HF button", None
82
  username = profile.username
83
 
84
  if not os.getenv("GROQ_API_KEY"):
85
- return "❌ Add GROQ_API_KEY secret in Space Settings", None
86
 
87
- try:
88
- agent = UltraFastGroqAgent()
89
- except Exception as e:
90
- return f"Init error: {e}", None
 
 
 
 
 
91
 
92
- space_id = os.getenv("SPACE_ID", f"{username}/Final_Assignment_Template")
93
  try:
94
- qs = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15).json()
95
  except Exception as e:
96
  return f"Fetch error: {e}", None
97
 
98
- payload_answers = []
99
- logs = []
100
- for i, item in enumerate(qs[:20]): # 20 questions max
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  tid = item["task_id"]
102
  qtxt = item["question"]
103
- fname = item.get("file_name")
104
- fpath = None
105
- if fname:
106
- try:
107
- fr = requests.get(f"{DEFAULT_API_URL}/files/{tid}", timeout=10)
108
- fr.raise_for_status()
109
- fpath = f"/tmp/{fname}"
110
- os.makedirs("/tmp", exist_ok=True)
111
- open(fpath, "wb").write(fr.content)
112
- except:
113
- pass
114
- ans = agent.ask(qtxt, fpath)
115
- if not ans:
116
  ans = "0"
117
- payload_answers.append({"task_id": tid, "submitted_answer": ans})
118
- logs.append({"Task": tid, "Answer": ans})
119
- print(f"[{i+1}/20] {tid} -> {ans}")
 
 
 
 
120
 
121
- try:
122
- r = requests.post(f"{DEFAULT_API_URL}/submit", json={
123
- "username": username,
124
- "agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
125
- "answers": payload_answers
126
- }, timeout=20)
127
- r.raise_for_status()
128
- data = r.json()
129
- msg = f"✅ Score: {data.get('score')}% ({data.get('correct_count')}/{data.get('total_attempted')})\n{data.get('message')}\nClaim cert: https://huggingface.co/spaces/agents-course/Unit4_Final_Certificate"
130
- return msg, pd.DataFrame(logs)
131
- except Exception as e:
132
- return f"Submit failed: {e}", pd.DataFrame(logs)
 
 
 
133
 
134
  with gr.Blocks() as demo:
135
- gr.Markdown("# ⚡ ZeroGPU <192s - Groq 8B Fast")
136
- gr.Markdown("**Fix for quota 192s:** Only 1 GPU function with duration=60s (old code used 90+180=270s). Uses Groq 8B-instant (3 sec per Q) so total ~100s < 192s. No CPU needed. Just add GROQ_API_KEY secret and click Run.")
137
  gr.LoginButton()
138
- btn = gr.Button("Run (60s GPU, ~100s total) - Pass 30%")
139
- out = gr.Textbox(label="Result", lines=6)
 
 
140
  table = gr.DataFrame(label="Answers")
141
- btn.click(fn=run_and_submit_all, outputs=[out, table])
 
142
 
143
  if __name__ == "__main__":
144
- demo.launch(share=True)
 
1
+ import os, json, time
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
  import spaces
6
  from smolagents import CodeAgent, tool, LiteLLMModel
7
 
 
8
  @tool
9
  def web_search(query: str) -> str:
10
+ """Search web.
11
  Args:
12
+ query: query
13
  """
14
  try:
15
  try:
16
  from duckduckgo_search import DDGS
17
  except ImportError:
18
  from ddgs import DDGS
19
+ with DDGS(timeout=6) as ddgs:
20
+ res = list(ddgs.text(query, max_results=2))
21
+ return "\n".join([f"{r['title']}: {r['body'][:100]}" for r in res[:2]]) if res else "No results"
 
 
22
  except Exception as e:
23
+ return f"Search fail: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
26
+ PROGRESS_FILE = "/tmp/gaia_progress.json"
27
 
28
+ class TinyAgent:
29
  def __init__(self):
30
  key = os.getenv("GROQ_API_KEY")
31
  if not key:
32
+ raise ValueError("Add GROQ_API_KEY secret!")
33
+ self.model = LiteLLMModel(model_id="groq/llama-3.1-8b-instant", api_key=key, temperature=0.1)
34
+ self.agent = CodeAgent(tools=[web_search], model=self.model, add_base_tools=True, max_steps=3)
 
 
 
 
 
 
 
 
 
 
 
35
 
36
+ def ask(self, q):
 
 
 
37
  try:
38
+ r = self.agent.run(q + "\nFINAL ANSWER: short")
39
+ s = str(r)
40
  if "FINAL ANSWER:" in s:
41
  s = s.split("FINAL ANSWER:")[-1]
42
+ return s.split("\n")[0].strip().strip('"')[:150]
43
+ except:
44
  return "0"
45
 
46
+ # ONLY 20s REQUESTED - fits in 81s left (4 clicks = 80s total)
47
+ @spaces.GPU(duration=20)
48
+ def run_chunk(profile: gr.OAuthProfile | None):
 
49
  if not profile:
50
+ return "Login first", None
51
  username = profile.username
52
 
53
  if not os.getenv("GROQ_API_KEY"):
54
+ return "Add GROQ_API_KEY secret in Settings", None
55
 
56
+ # Load progress
57
+ if os.path.exists(PROGRESS_FILE):
58
+ with open(PROGRESS_FILE, "r") as f:
59
+ data = json.load(f)
60
+ answers = data.get("answers", [])
61
+ done_ids = set(a["task_id"] for a in answers)
62
+ else:
63
+ answers = []
64
+ done_ids = set()
65
 
66
+ # Fetch all questions
67
  try:
68
+ all_qs = requests.get(f"{DEFAULT_API_URL}/questions", timeout=10).json()
69
  except Exception as e:
70
  return f"Fetch error: {e}", None
71
 
72
+ # Find 5 not done yet
73
+ todo = [q for q in all_qs if q["task_id"] not in done_ids][:5]
74
+
75
+ if not todo and len(answers) >= 20:
76
+ # All done, submit
77
+ try:
78
+ r = requests.post(f"{DEFAULT_API_URL}/submit", json={
79
+ "username": username,
80
+ "agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main",
81
+ "answers": answers
82
+ }, timeout=15).json()
83
+ return f"✅ SUBMITTED! Score: {r.get('score')}% {r.get('correct_count')}/{r.get('total_attempted')} - {r.get('message')}", pd.DataFrame(answers)
84
+ except Exception as e:
85
+ return f"Submit failed: {e}", pd.DataFrame(answers)
86
+
87
+ if not todo:
88
+ return f"Already did {len(answers)}/20, click again to submit", pd.DataFrame(answers)
89
+
90
+ agent = TinyAgent()
91
+ start = time.time()
92
+ for item in todo:
93
  tid = item["task_id"]
94
  qtxt = item["question"]
95
+ # skip file questions to save time (return 0 fast)
96
+ if item.get("file_name"):
 
 
 
 
 
 
 
 
 
 
 
97
  ans = "0"
98
+ else:
99
+ ans = agent.ask(qtxt)
100
+ answers.append({"task_id": tid, "submitted_answer": ans})
101
+ print(f"{tid} -> {ans} | elapsed {time.time()-start:.1f}s")
102
+ # Stop if near 18s to avoid killing
103
+ if time.time() - start > 15:
104
+ break
105
 
106
+ # Save progress
107
+ with open(PROGRESS_FILE, "w") as f:
108
+ json.dump({"answers": answers}, f)
109
+
110
+ remaining = 20 - len(answers)
111
+ if remaining > 0:
112
+ return f"Progress: {len(answers)}/20 done in {time.time()-start:.1f}s (used 20s of your 81s). Click RUN AGAIN to do next 5. Need {remaining} more. After 20/20, click once more to submit.", pd.DataFrame(answers)
113
+ else:
114
+ return f"All 20 done! Click RUN AGAIN to SUBMIT now.", pd.DataFrame(answers)
115
+
116
+ @spaces.GPU(duration=20)
117
+ def reset_progress():
118
+ if os.path.exists(PROGRESS_FILE):
119
+ os.remove(PROGRESS_FILE)
120
+ return "Progress reset", None
121
 
122
  with gr.Blocks() as demo:
123
+ gr.Markdown("# 🆘 ZeroGPU 81s Left - Chunked 20s Version")
124
+ gr.Markdown("**You have 81s quota left, old code needed 270s so it fails. This version only requests 20s per click and does 5 Qs at a time. 4 clicks = 80s total < 81s. For file questions it returns 0 to save time (you still pass 30% on text Qs).**\n\n**BETTER: Go to Settings -> Hardware -> CPU basic (free) -> Save. Then use previous app.py with no GPU decorator and you get infinite time, no quota.**")
125
  gr.LoginButton()
126
+ with gr.Row():
127
+ btn = gr.Button("Run 5 Questions (20s)")
128
+ reset = gr.Button("Reset Progress")
129
+ out = gr.Textbox(label="Status", lines=5)
130
  table = gr.DataFrame(label="Answers")
131
+ btn.click(fn=run_chunk, outputs=[out, table])
132
+ reset.click(fn=reset_progress, outputs=[out, table])
133
 
134
  if __name__ == "__main__":
135
+ demo.launch()