mohdadrian commited on
Commit
c8c764b
Β·
verified Β·
1 Parent(s): 87acbb5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -86
app.py CHANGED
@@ -3,90 +3,45 @@ import time
3
  import requests
4
  import gradio as gr
5
  import pandas as pd
6
- from groq import Groq
7
 
8
- # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # ============================================
12
- # SIMPLE FAST AGENT
13
- # ============================================
14
 
15
  class BasicAgent:
16
  def __init__(self):
17
- api_key = os.environ.get("GROQ_API_KEY")
18
- if not api_key:
19
- raise ValueError("GROQ_API_KEY not set!")
20
- self.client = Groq(api_key=api_key)
21
- print("βœ… Agent ready")
22
-
23
- def search(self, query: str) -> str:
24
- """Quick web search"""
25
- try:
26
- from duckduckgo_search import DDGS
27
- with DDGS() as ddgs:
28
- results = list(ddgs.text(query, max_results=3))
29
- if results:
30
- return "\n".join([f"- {r.get('title','')}: {r.get('body','')}" for r in results])
31
- except:
32
- pass
33
- return ""
34
-
35
- def ask(self, prompt: str) -> str:
36
- """Ask LLM - use 8B model for speed and rate limits"""
37
- try:
38
- response = self.client.chat.completions.create(
39
- model="llama-3.1-8b-instant", # Fast, high rate limit
40
- messages=[{"role": "user", "content": prompt}],
41
- temperature=0,
42
- max_tokens=50, # Short answers only
43
- )
44
- return response.choices[0].message.content.strip()
45
- except Exception as e:
46
- if "rate" in str(e).lower():
47
- time.sleep(5)
48
- try:
49
- response = self.client.chat.completions.create(
50
- model="llama-3.1-8b-instant",
51
- messages=[{"role": "user", "content": prompt}],
52
- temperature=0,
53
- max_tokens=50,
54
- )
55
- return response.choices[0].message.content.strip()
56
- except:
57
- return ""
58
- return ""
59
 
60
  def __call__(self, question: str, task_id: str = None) -> str:
61
  # Handle reversed text
62
- if '.rewsna' in question or 'eht sa' in question or 'tfel' in question:
63
  question = question[::-1]
64
 
65
- # Search for info
66
- search_results = self.search(question[:80])
67
-
68
- # Build prompt
69
- context = f"Info: {search_results[:1000]}\n\n" if search_results else ""
70
-
71
- prompt = f"""{context}Q: {question}
72
-
73
- Give only the final answer in 1-5 words. No explanation."""
74
-
75
- answer = self.ask(prompt)
76
-
77
- # Clean answer
78
- for prefix in ["Answer:", "The answer is", "A:", "Final answer:"]:
79
- if answer.lower().startswith(prefix.lower()):
80
- answer = answer[len(prefix):].strip()
81
-
82
- answer = answer.strip('."\'')
83
-
84
- # Filter bad responses
85
- if any(x in answer.lower() for x in ["i cannot", "i'm unable", "no code", "no image", "i don't"]):
86
- answer = self.ask(f"Answer in 1-3 words only: {question}")
87
- answer = answer.strip('."\'')
88
-
89
- return answer if answer else "unknown"
90
 
91
 
92
  def run_and_submit_all(profile: gr.OAuthProfile | None):
@@ -96,15 +51,12 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
96
  username = profile.username
97
  space_id = os.getenv("SPACE_ID")
98
 
99
- if not os.environ.get("GROQ_API_KEY"):
100
- return "❌ Add GROQ_API_KEY!", None
101
-
102
- print(f"\n{'='*40}\nUser: {username}\n{'='*40}")
103
 
104
  try:
105
  agent = BasicAgent()
106
  except Exception as e:
107
- return f"❌ {e}", None
108
 
109
  try:
110
  questions = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15).json()
@@ -122,12 +74,10 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
122
 
123
  print(f"[{i+1}] {question[:50]}...")
124
  answer = agent(question, task_id)
125
- print(f" β†’ {answer}")
126
 
127
  answers.append({"task_id": task_id, "submitted_answer": answer})
128
- results.append({"#": i+1, "Q": question[:40]+"...", "A": answer})
129
-
130
- time.sleep(2) # Small delay
131
 
132
  total = time.time() - start
133
  print(f"\n⏱️ {total:.0f}s")
@@ -151,11 +101,13 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
151
 
152
 
153
  with gr.Blocks() as demo:
154
- gr.Markdown("# 🎯 GAIA Agent")
155
- gr.Markdown("Fast mode - ~2 min")
156
  gr.LoginButton()
157
- gr.Button("πŸš€ Run", variant="primary").click(run_and_submit_all, outputs=[gr.Textbox(label="Status", lines=5), gr.DataFrame(label="Results")])
 
 
 
158
 
159
  if __name__ == "__main__":
160
- print(f"GROQ: {'βœ…' if os.environ.get('GROQ_API_KEY') else '❌'}")
161
  demo.launch()
 
3
  import requests
4
  import gradio as gr
5
  import pandas as pd
6
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, VisitWebpageTool
7
 
 
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
 
 
 
10
 
11
  class BasicAgent:
12
  def __init__(self):
13
+ print("Initializing HuggingFace agent...")
14
+
15
+ self.model = HfApiModel(
16
+ model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
17
+ token=os.environ.get("HF_TOKEN"),
18
+ )
19
+
20
+ self.agent = CodeAgent(
21
+ model=self.model,
22
+ tools=[DuckDuckGoSearchTool(), VisitWebpageTool()],
23
+ max_steps=3,
24
+ verbosity_level=0,
25
+ )
26
+ print("βœ… Ready")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  def __call__(self, question: str, task_id: str = None) -> str:
29
  # Handle reversed text
30
+ if '.rewsna' in question or 'tfel' in question:
31
  question = question[::-1]
32
 
33
+ try:
34
+ prompt = f"Answer in 1-5 words only: {question}"
35
+ answer = str(self.agent.run(prompt)).strip()
36
+
37
+ # Clean
38
+ for p in ["Answer:", "The answer is", "Final answer:"]:
39
+ if answer.lower().startswith(p.lower()):
40
+ answer = answer[len(p):].strip()
41
+ return answer.strip('."\'') or "unknown"
42
+ except Exception as e:
43
+ print(f"Error: {e}")
44
+ return "unknown"
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
 
47
  def run_and_submit_all(profile: gr.OAuthProfile | None):
 
51
  username = profile.username
52
  space_id = os.getenv("SPACE_ID")
53
 
54
+ print(f"\nUser: {username}")
 
 
 
55
 
56
  try:
57
  agent = BasicAgent()
58
  except Exception as e:
59
+ return f"❌ Agent failed: {e}", None
60
 
61
  try:
62
  questions = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15).json()
 
74
 
75
  print(f"[{i+1}] {question[:50]}...")
76
  answer = agent(question, task_id)
77
+ print(f" β†’ {answer[:50]}")
78
 
79
  answers.append({"task_id": task_id, "submitted_answer": answer})
80
+ results.append({"#": i+1, "Q": question[:40]+"...", "A": answer[:50]})
 
 
81
 
82
  total = time.time() - start
83
  print(f"\n⏱️ {total:.0f}s")
 
101
 
102
 
103
  with gr.Blocks() as demo:
104
+ gr.Markdown("# 🎯 GAIA Agent - HuggingFace")
 
105
  gr.LoginButton()
106
+ btn = gr.Button("πŸš€ Run", variant="primary")
107
+ status = gr.Textbox(label="Status", lines=5)
108
+ table = gr.DataFrame(label="Results")
109
+ btn.click(run_and_submit_all, outputs=[status, table])
110
 
111
  if __name__ == "__main__":
112
+ print(f"HF_TOKEN: {'βœ…' if os.environ.get('HF_TOKEN') else '❌'}")
113
  demo.launch()