avi080704 commited on
Commit
2de5380
·
verified ·
1 Parent(s): f3d3186

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -52
app.py CHANGED
@@ -1,10 +1,11 @@
1
  import os
 
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
 
6
  from smolagents import CodeAgent, DuckDuckGoSearchTool
7
- from smolagents.models import InferenceClientModel
8
 
9
  # ---------------------------------------------------
10
  # Constants
@@ -12,46 +13,73 @@ from smolagents.models import InferenceClientModel
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
 
14
  # ---------------------------------------------------
15
- # Agent Definition
16
  # ---------------------------------------------------
17
  class BasicAgent:
18
 
19
  def __init__(self):
20
 
21
- print("Initializing Hugging Face Agent...")
22
 
23
- # Hugging Face Inference API model
24
- model = InferenceClientModel(
25
- model_id="Qwen/Qwen2.5-72B-Instruct",
26
- token=os.getenv("HF_TOKEN")
27
  )
28
 
29
- # Build agent
30
  self.agent = CodeAgent(
31
  tools=[
32
  DuckDuckGoSearchTool()
33
  ],
34
- model=model,
35
- max_steps=6,
36
- verbosity_level=1
37
  )
38
 
39
- print("Agent initialized successfully.")
40
 
41
- def __call__(self, question: str) -> str:
 
 
 
 
 
 
 
 
42
 
43
- print(f"\nQuestion: {question[:100]}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  prompt = f"""
46
- You are an expert GAIA benchmark solving agent.
47
 
48
- Your job:
49
- - Think step-by-step.
50
- - Use web search if needed.
51
- - Solve the task accurately.
52
  - Return ONLY the final answer.
53
- - Keep answers concise.
54
- - No explanations unless necessary.
 
 
 
 
55
 
56
  Question:
57
  {question}
@@ -61,20 +89,18 @@ Question:
61
 
62
  result = self.agent.run(prompt)
63
 
64
- if result is None:
65
- return "Could not determine the answer."
66
 
67
- final_answer = str(result).strip()
 
68
 
69
- print(f"Answer: {final_answer}")
70
-
71
- return final_answer
72
 
73
  except Exception as e:
74
 
75
  print(f"Agent error: {e}")
76
 
77
- return f"Error: {str(e)}"
78
 
79
 
80
  # ---------------------------------------------------
@@ -82,17 +108,15 @@ Question:
82
  # ---------------------------------------------------
83
  def run_and_submit_all(profile: gr.OAuthProfile | None):
84
 
85
- # Get Space ID
86
  space_id = os.getenv("SPACE_ID")
87
 
88
- # Check login
89
  if profile:
90
  username = profile.username
91
  print(f"Logged in as: {username}")
92
  else:
93
- return "Please login with Hugging Face first.", None
94
 
95
- # API URLs
96
  api_url = DEFAULT_API_URL
97
  questions_url = f"{api_url}/questions"
98
  submit_url = f"{api_url}/submit"
@@ -101,15 +125,16 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
101
  # Initialize Agent
102
  # ---------------------------------------------------
103
  try:
 
104
  agent = BasicAgent()
105
 
106
  except Exception as e:
107
 
108
- print(f"Error initializing agent: {e}")
109
 
110
  return f"Error initializing agent: {e}", None
111
 
112
- # Link to your Space code
113
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
114
 
115
  # ---------------------------------------------------
@@ -132,7 +157,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
132
 
133
  except Exception as e:
134
 
135
- print(f"Error fetching questions: {e}")
136
 
137
  return f"Error fetching questions: {e}", None
138
 
@@ -150,7 +175,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
150
  if not task_id or question_text is None:
151
  continue
152
 
153
- print(f"\nRunning task: {task_id}")
154
 
155
  try:
156
 
@@ -178,7 +203,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
178
  })
179
 
180
  # ---------------------------------------------------
181
- # Submit Answers
182
  # ---------------------------------------------------
183
  submission_data = {
184
  "username": username.strip(),
@@ -186,10 +211,10 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
186
  "answers": answers_payload
187
  }
188
 
189
- print("Submitting answers...")
190
-
191
  try:
192
 
 
 
193
  response = requests.post(
194
  submit_url,
195
  json=submission_data,
@@ -216,15 +241,15 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
216
 
217
  except Exception as e:
218
 
219
- error_msg = f"Submission failed: {e}"
220
 
221
- print(error_msg)
222
 
223
- return error_msg, pd.DataFrame(results_log)
224
 
225
 
226
  # ---------------------------------------------------
227
- # Gradio Interface
228
  # ---------------------------------------------------
229
  with gr.Blocks() as demo:
230
 
@@ -234,22 +259,19 @@ with gr.Blocks() as demo:
234
  """
235
  This agent uses:
236
 
237
- - Hugging Face Inference API
 
238
  - smolagents
239
- - DuckDuckGo web search
240
- - Qwen2.5-72B-Instruct
241
  """
242
  )
243
 
244
- # HF Login
245
  gr.LoginButton()
246
 
247
- # Run Button
248
  run_button = gr.Button(
249
  "Run Evaluation & Submit"
250
  )
251
 
252
- # Outputs
253
  status_output = gr.Textbox(
254
  label="Submission Result",
255
  lines=8,
@@ -261,7 +283,6 @@ This agent uses:
261
  wrap=True
262
  )
263
 
264
- # Button Action
265
  run_button.click(
266
  fn=run_and_submit_all,
267
  outputs=[
@@ -271,12 +292,12 @@ This agent uses:
271
  )
272
 
273
  # ---------------------------------------------------
274
- # Launch App
275
  # ---------------------------------------------------
276
  if __name__ == "__main__":
277
 
278
  print("\n==============================")
279
- print("Starting Hugging Face Agent...")
280
  print("==============================\n")
281
 
282
  demo.launch(
 
1
  import os
2
+ import re
3
  import gradio as gr
4
  import requests
5
  import pandas as pd
6
 
7
  from smolagents import CodeAgent, DuckDuckGoSearchTool
8
+ from smolagents.models import OpenAIServerModel
9
 
10
  # ---------------------------------------------------
11
  # Constants
 
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
15
  # ---------------------------------------------------
16
+ # Agent
17
  # ---------------------------------------------------
18
  class BasicAgent:
19
 
20
  def __init__(self):
21
 
22
+ print("Initializing Groq Agent...")
23
 
24
+ self.model = OpenAIServerModel(
25
+ model_id="llama-3.3-70b-versatile",
26
+ api_base="https://api.groq.com/openai/v1",
27
+ api_key=os.getenv("GROQ_API_KEY")
28
  )
29
 
 
30
  self.agent = CodeAgent(
31
  tools=[
32
  DuckDuckGoSearchTool()
33
  ],
34
+ model=self.model,
35
+ max_steps=3,
36
+ verbosity_level=0
37
  )
38
 
39
+ print("Groq Agent initialized.")
40
 
41
+ # ---------------------------------------------------
42
+ # Clean outputs for exact-match grading
43
+ # ---------------------------------------------------
44
+ def clean_answer(self, text):
45
+
46
+ if text is None:
47
+ return ""
48
+
49
+ text = str(text)
50
 
51
+ # remove markdown/code
52
+ text = text.replace("```", "")
53
+ text = text.replace("FINAL ANSWER:", "")
54
+ text = text.replace("Answer:", "")
55
+
56
+ # remove excessive whitespace
57
+ text = re.sub(r"\s+", " ", text)
58
+
59
+ # first line only
60
+ text = text.split("\n")[0]
61
+
62
+ # concise
63
+ text = text.strip()
64
+
65
+ return text[:300]
66
+
67
+ # ---------------------------------------------------
68
+ # Run agent
69
+ # ---------------------------------------------------
70
+ def __call__(self, question: str) -> str:
71
 
72
  prompt = f"""
73
+ You are solving a GAIA benchmark question.
74
 
75
+ IMPORTANT:
 
 
 
76
  - Return ONLY the final answer.
77
+ - No reasoning.
78
+ - No explanations.
79
+ - No markdown.
80
+ - No bullet points.
81
+ - Be concise and accurate.
82
+ - Use web search if needed.
83
 
84
  Question:
85
  {question}
 
89
 
90
  result = self.agent.run(prompt)
91
 
92
+ cleaned = self.clean_answer(result)
 
93
 
94
+ print(f"\nQUESTION:\n{question}")
95
+ print(f"\nANSWER:\n{cleaned}")
96
 
97
+ return cleaned
 
 
98
 
99
  except Exception as e:
100
 
101
  print(f"Agent error: {e}")
102
 
103
+ return ""
104
 
105
 
106
  # ---------------------------------------------------
 
108
  # ---------------------------------------------------
109
  def run_and_submit_all(profile: gr.OAuthProfile | None):
110
 
 
111
  space_id = os.getenv("SPACE_ID")
112
 
113
+ # Login check
114
  if profile:
115
  username = profile.username
116
  print(f"Logged in as: {username}")
117
  else:
118
+ return "Please login with Hugging Face.", None
119
 
 
120
  api_url = DEFAULT_API_URL
121
  questions_url = f"{api_url}/questions"
122
  submit_url = f"{api_url}/submit"
 
125
  # Initialize Agent
126
  # ---------------------------------------------------
127
  try:
128
+
129
  agent = BasicAgent()
130
 
131
  except Exception as e:
132
 
133
+ print(f"Initialization error: {e}")
134
 
135
  return f"Error initializing agent: {e}", None
136
 
137
+ # Space repo link
138
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
139
 
140
  # ---------------------------------------------------
 
157
 
158
  except Exception as e:
159
 
160
+ print(f"Question fetch error: {e}")
161
 
162
  return f"Error fetching questions: {e}", None
163
 
 
175
  if not task_id or question_text is None:
176
  continue
177
 
178
+ print(f"\nRunning task {task_id}")
179
 
180
  try:
181
 
 
203
  })
204
 
205
  # ---------------------------------------------------
206
+ # Submit
207
  # ---------------------------------------------------
208
  submission_data = {
209
  "username": username.strip(),
 
211
  "answers": answers_payload
212
  }
213
 
 
 
214
  try:
215
 
216
+ print("Submitting answers...")
217
+
218
  response = requests.post(
219
  submit_url,
220
  json=submission_data,
 
241
 
242
  except Exception as e:
243
 
244
+ error_message = f"Submission failed: {e}"
245
 
246
+ print(error_message)
247
 
248
+ return error_message, pd.DataFrame(results_log)
249
 
250
 
251
  # ---------------------------------------------------
252
+ # UI
253
  # ---------------------------------------------------
254
  with gr.Blocks() as demo:
255
 
 
259
  """
260
  This agent uses:
261
 
262
+ - Groq API
263
+ - Llama 3.3 70B
264
  - smolagents
265
+ - DuckDuckGo Search
 
266
  """
267
  )
268
 
 
269
  gr.LoginButton()
270
 
 
271
  run_button = gr.Button(
272
  "Run Evaluation & Submit"
273
  )
274
 
 
275
  status_output = gr.Textbox(
276
  label="Submission Result",
277
  lines=8,
 
283
  wrap=True
284
  )
285
 
 
286
  run_button.click(
287
  fn=run_and_submit_all,
288
  outputs=[
 
292
  )
293
 
294
  # ---------------------------------------------------
295
+ # Launch
296
  # ---------------------------------------------------
297
  if __name__ == "__main__":
298
 
299
  print("\n==============================")
300
+ print("Starting Groq Agent...")
301
  print("==============================\n")
302
 
303
  demo.launch(