likki1715 commited on
Commit
604b768
·
verified ·
1 Parent(s): 81917a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +278 -89
app.py CHANGED
@@ -1,34 +1,262 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
 
 
 
6
 
7
- # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
- class BasicAgent:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  def __init__(self):
15
- print("BasicAgent initialized.")
 
 
 
 
 
 
16
  def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
21
-
22
- def run_and_submit_all( profile: gr.OAuthProfile | None):
23
- """
24
- Fetches all questions, runs the BasicAgent on them, submits all answers,
25
- and displays the results.
26
- """
27
- # --- Determine HF Space Runtime URL and Repo URL ---
28
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  if profile:
31
- username= f"{profile.username}"
32
  print(f"User logged in: {username}")
33
  else:
34
  print("User not logged in.")
@@ -38,13 +266,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
38
  questions_url = f"{api_url}/questions"
39
  submit_url = f"{api_url}/submit"
40
 
41
- # 1. Instantiate Agent ( modify this part to create your agent)
42
  try:
43
- agent = BasicAgent()
44
  except Exception as e:
45
  print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
47
- # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
48
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
  print(agent_code)
50
 
@@ -55,21 +283,12 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
55
  response.raise_for_status()
56
  questions_data = response.json()
57
  if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
  print(f"Fetched {len(questions_data)} questions.")
61
- except requests.exceptions.RequestException as e:
62
- print(f"Error fetching questions: {e}")
63
- return f"Error fetching questions: {e}", None
64
- except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
  except Exception as e:
69
- print(f"An unexpected error occurred fetching questions: {e}")
70
- return f"An unexpected error occurred fetching questions: {e}", None
71
 
72
- # 3. Run your Agent
73
  results_log = []
74
  answers_payload = []
75
  print(f"Running agent on {len(questions_data)} questions...")
@@ -84,22 +303,17 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
84
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
  except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
89
 
90
  if not answers_payload:
91
- print("Agent did not produce any answers to submit.")
92
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
 
94
- # 4. Prepare Submission
95
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
- print(status_update)
98
-
99
- # 5. Submit
100
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
101
  try:
102
- response = requests.post(submit_url, json=submission_data, timeout=60)
103
  response.raise_for_status()
104
  result_data = response.json()
105
  final_status = (
@@ -110,60 +324,40 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
110
  f"Message: {result_data.get('message', 'No message received.')}"
111
  )
112
  print("Submission successful.")
113
- results_df = pd.DataFrame(results_log)
114
- return final_status, results_df
115
  except requests.exceptions.HTTPError as e:
116
  error_detail = f"Server responded with status {e.response.status_code}."
117
  try:
118
  error_json = e.response.json()
119
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
120
- except requests.exceptions.JSONDecodeError:
121
  error_detail += f" Response: {e.response.text[:500]}"
122
- status_message = f"Submission Failed: {error_detail}"
123
- print(status_message)
124
- results_df = pd.DataFrame(results_log)
125
- return status_message, results_df
126
- except requests.exceptions.Timeout:
127
- status_message = "Submission Failed: The request timed out."
128
- print(status_message)
129
- results_df = pd.DataFrame(results_log)
130
- return status_message, results_df
131
- except requests.exceptions.RequestException as e:
132
- status_message = f"Submission Failed: Network error - {e}"
133
- print(status_message)
134
- results_df = pd.DataFrame(results_log)
135
- return status_message, results_df
136
  except Exception as e:
137
- status_message = f"An unexpected error occurred during submission: {e}"
138
- print(status_message)
139
- results_df = pd.DataFrame(results_log)
140
- return status_message, results_df
141
 
142
 
143
- # --- Build Gradio Interface using Blocks ---
144
  with gr.Blocks() as demo:
145
- gr.Markdown("# Basic Agent Evaluation Runner")
146
  gr.Markdown(
147
  """
 
 
148
  **Instructions:**
149
-
150
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
-
154
- ---
155
- **Disclaimers:**
156
- Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
157
- This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
158
  """
159
  )
160
 
161
  gr.LoginButton()
162
 
163
- run_button = gr.Button("Run Evaluation & Submit All Answers")
164
 
165
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
- # Removed max_rows=10 from DataFrame constructor
167
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
168
 
169
  run_button.click(
@@ -172,25 +366,20 @@ with gr.Blocks() as demo:
172
  )
173
 
174
  if __name__ == "__main__":
175
- print("\n" + "-"*30 + " App Starting " + "-"*30)
176
- # Check for SPACE_HOST and SPACE_ID at startup for information
177
  space_host_startup = os.getenv("SPACE_HOST")
178
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
179
 
180
  if space_host_startup:
181
  print(f"✅ SPACE_HOST found: {space_host_startup}")
182
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
183
  else:
184
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
185
 
186
- if space_id_startup: # Print repo URLs if SPACE_ID is found
187
  print(f"✅ SPACE_ID found: {space_id_startup}")
188
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
190
  else:
191
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
192
-
193
- print("-"*(60 + len(" App Starting ")) + "\n")
194
 
195
- print("Launching Gradio Interface for Basic Agent Evaluation...")
 
196
  demo.launch(debug=True, share=False)
 
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
+ import anthropic
6
+ import re
7
+ from duckduckgo_search import DDGS
8
 
 
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
12
+ # --- Tool Implementations ---
13
+
14
+ def web_search(query: str) -> str:
15
+ """Search the web using DuckDuckGo."""
16
+ try:
17
+ with DDGS() as ddgs:
18
+ results = list(ddgs.text(query, max_results=5))
19
+ if not results:
20
+ return "No results found."
21
+ output = []
22
+ for r in results:
23
+ output.append(f"Title: {r.get('title', '')}\nURL: {r.get('href', '')}\nSnippet: {r.get('body', '')}\n")
24
+ return "\n---\n".join(output)
25
+ except Exception as e:
26
+ return f"Search error: {e}"
27
+
28
+
29
+ def fetch_page(url: str) -> str:
30
+ """Fetch content from a URL."""
31
+ try:
32
+ headers = {"User-Agent": "Mozilla/5.0"}
33
+ response = requests.get(url, headers=headers, timeout=10)
34
+ response.raise_for_status()
35
+ # Basic text extraction
36
+ text = response.text
37
+ # Remove HTML tags crudely
38
+ text = re.sub(r'<[^>]+>', ' ', text)
39
+ text = re.sub(r'\s+', ' ', text).strip()
40
+ return text[:3000]
41
+ except Exception as e:
42
+ return f"Error fetching page: {e}"
43
+
44
+
45
+ def run_python(code: str) -> str:
46
+ """Execute Python code and return the output."""
47
+ import sys
48
+ from io import StringIO
49
+ old_stdout = sys.stdout
50
+ sys.stdout = StringIO()
51
+ try:
52
+ exec_globals = {}
53
+ exec(code, exec_globals)
54
+ output = sys.stdout.getvalue()
55
+ return output if output else "Code executed successfully (no output)."
56
+ except Exception as e:
57
+ return f"Error executing code: {e}"
58
+ finally:
59
+ sys.stdout = old_stdout
60
+
61
+
62
+ def wikipedia_search(query: str) -> str:
63
+ """Search Wikipedia for a topic."""
64
+ try:
65
+ search_url = "https://en.wikipedia.org/w/api.php"
66
+ params = {
67
+ "action": "query",
68
+ "list": "search",
69
+ "srsearch": query,
70
+ "format": "json",
71
+ "srlimit": 3,
72
+ }
73
+ response = requests.get(search_url, params=params, timeout=10)
74
+ data = response.json()
75
+ results = data.get("query", {}).get("search", [])
76
+ if not results:
77
+ return "No Wikipedia results found."
78
+
79
+ # Fetch first result's summary
80
+ title = results[0]["title"]
81
+ summary_params = {
82
+ "action": "query",
83
+ "titles": title,
84
+ "prop": "extracts",
85
+ "exintro": True,
86
+ "explaintext": True,
87
+ "format": "json",
88
+ }
89
+ summary_response = requests.get(search_url, params=summary_params, timeout=10)
90
+ summary_data = summary_response.json()
91
+ pages = summary_data.get("query", {}).get("pages", {})
92
+ for page_id, page in pages.items():
93
+ extract = page.get("extract", "No content available.")
94
+ return f"Wikipedia: {title}\n\n{extract[:2000]}"
95
+ return "No content found."
96
+ except Exception as e:
97
+ return f"Wikipedia error: {e}"
98
+
99
+
100
+ # --- Tool Definitions for Claude API ---
101
+ TOOLS = [
102
+ {
103
+ "name": "web_search",
104
+ "description": "Search the web for current information. Use this for facts, recent events, or anything that requires looking up.",
105
+ "input_schema": {
106
+ "type": "object",
107
+ "properties": {
108
+ "query": {
109
+ "type": "string",
110
+ "description": "The search query"
111
+ }
112
+ },
113
+ "required": ["query"]
114
+ }
115
+ },
116
+ {
117
+ "name": "wikipedia_search",
118
+ "description": "Search Wikipedia for factual information about people, places, events, concepts, etc.",
119
+ "input_schema": {
120
+ "type": "object",
121
+ "properties": {
122
+ "query": {
123
+ "type": "string",
124
+ "description": "The topic to search on Wikipedia"
125
+ }
126
+ },
127
+ "required": ["query"]
128
+ }
129
+ },
130
+ {
131
+ "name": "fetch_page",
132
+ "description": "Fetch and read the content of a specific URL/webpage.",
133
+ "input_schema": {
134
+ "type": "object",
135
+ "properties": {
136
+ "url": {
137
+ "type": "string",
138
+ "description": "The URL to fetch"
139
+ }
140
+ },
141
+ "required": ["url"]
142
+ }
143
+ },
144
+ {
145
+ "name": "run_python",
146
+ "description": "Execute Python code for calculations, data processing, or logic. Returns stdout output.",
147
+ "input_schema": {
148
+ "type": "object",
149
+ "properties": {
150
+ "code": {
151
+ "type": "string",
152
+ "description": "Python code to execute"
153
+ }
154
+ },
155
+ "required": ["code"]
156
+ }
157
+ }
158
+ ]
159
+
160
+ TOOL_FUNCTIONS = {
161
+ "web_search": web_search,
162
+ "wikipedia_search": wikipedia_search,
163
+ "fetch_page": fetch_page,
164
+ "run_python": run_python,
165
+ }
166
+
167
+ SYSTEM_PROMPT = """You are a general AI assistant solving benchmark questions.
168
+
169
+ For each question:
170
+ 1. Think carefully about what information you need
171
+ 2. Use tools to search for facts, do calculations, or fetch web pages
172
+ 3. Reason step by step
173
+ 4. Give ONLY the final answer - no explanation, no "FINAL ANSWER:" prefix
174
+
175
+ Your answer should be:
176
+ - A number (no units unless specified, no commas in numbers)
177
+ - A short phrase (no articles like "the" or "a", no abbreviations for proper nouns)
178
+ - A comma-separated list of numbers/strings
179
+
180
+ Be precise. The answer is checked by exact match."""
181
+
182
+
183
+ class SmartAgent:
184
  def __init__(self):
185
+ api_key = os.getenv("ANTHROPIC_API_KEY")
186
+ if not api_key:
187
+ raise ValueError("ANTHROPIC_API_KEY environment variable not set!")
188
+ self.client = anthropic.Anthropic(api_key=api_key)
189
+ self.model = "claude-opus-4-5"
190
+ print("SmartAgent (Claude-powered) initialized.")
191
+
192
  def __call__(self, question: str) -> str:
193
+ print(f"\nQuestion: {question[:100]}...")
194
+ messages = [{"role": "user", "content": question}]
195
+
196
+ max_iterations = 10
197
+ for iteration in range(max_iterations):
198
+ response = self.client.messages.create(
199
+ model=self.model,
200
+ max_tokens=4096,
201
+ system=SYSTEM_PROMPT,
202
+ tools=TOOLS,
203
+ messages=messages,
204
+ )
205
+
206
+ # Check if we're done
207
+ if response.stop_reason == "end_turn":
208
+ # Extract text answer
209
+ for block in response.content:
210
+ if hasattr(block, "text"):
211
+ answer = block.text.strip()
212
+ # Clean up any "FINAL ANSWER:" prefix if model adds it
213
+ answer = re.sub(r'^FINAL ANSWER:\s*', '', answer, flags=re.IGNORECASE).strip()
214
+ print(f"Answer: {answer}")
215
+ return answer
216
+ return "No answer"
217
+
218
+ # Process tool calls
219
+ if response.stop_reason == "tool_use":
220
+ # Add assistant's response to messages
221
+ messages.append({"role": "assistant", "content": response.content})
222
+
223
+ # Execute all tool calls
224
+ tool_results = []
225
+ for block in response.content:
226
+ if block.type == "tool_use":
227
+ tool_name = block.name
228
+ tool_input = block.input
229
+ print(f" Tool: {tool_name}({list(tool_input.values())[0] if tool_input else ''})")
230
+
231
+ try:
232
+ func = TOOL_FUNCTIONS.get(tool_name)
233
+ if func:
234
+ result = func(**tool_input)
235
+ else:
236
+ result = f"Unknown tool: {tool_name}"
237
+ except Exception as e:
238
+ result = f"Tool error: {e}"
239
+
240
+ tool_results.append({
241
+ "type": "tool_result",
242
+ "tool_use_id": block.id,
243
+ "content": str(result)[:5000],
244
+ })
245
+
246
+ messages.append({"role": "user", "content": tool_results})
247
+ else:
248
+ # Unexpected stop reason
249
+ break
250
+
251
+ return "Unable to determine answer"
252
+
253
+
254
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
255
+ """Fetches all questions, runs the SmartAgent, submits answers, and displays results."""
256
+ space_id = os.getenv("SPACE_ID")
257
 
258
  if profile:
259
+ username = f"{profile.username}"
260
  print(f"User logged in: {username}")
261
  else:
262
  print("User not logged in.")
 
266
  questions_url = f"{api_url}/questions"
267
  submit_url = f"{api_url}/submit"
268
 
269
+ # 1. Instantiate Agent
270
  try:
271
+ agent = SmartAgent()
272
  except Exception as e:
273
  print(f"Error instantiating agent: {e}")
274
  return f"Error initializing agent: {e}", None
275
+
276
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
277
  print(agent_code)
278
 
 
283
  response.raise_for_status()
284
  questions_data = response.json()
285
  if not questions_data:
286
+ return "Fetched questions list is empty or invalid format.", None
 
287
  print(f"Fetched {len(questions_data)} questions.")
 
 
 
 
 
 
 
288
  except Exception as e:
289
+ return f"Error fetching questions: {e}", None
 
290
 
291
+ # 3. Run Agent on all questions
292
  results_log = []
293
  answers_payload = []
294
  print(f"Running agent on {len(questions_data)} questions...")
 
303
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
304
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
305
  except Exception as e:
306
+ print(f"Error running agent on task {task_id}: {e}")
307
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
308
 
309
  if not answers_payload:
 
310
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
311
 
312
+ # 4. Submit
313
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
314
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
315
  try:
316
+ response = requests.post(submit_url, json=submission_data, timeout=120)
317
  response.raise_for_status()
318
  result_data = response.json()
319
  final_status = (
 
324
  f"Message: {result_data.get('message', 'No message received.')}"
325
  )
326
  print("Submission successful.")
327
+ return final_status, pd.DataFrame(results_log)
 
328
  except requests.exceptions.HTTPError as e:
329
  error_detail = f"Server responded with status {e.response.status_code}."
330
  try:
331
  error_json = e.response.json()
332
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
333
+ except Exception:
334
  error_detail += f" Response: {e.response.text[:500]}"
335
+ return f"Submission Failed: {error_detail}", pd.DataFrame(results_log)
 
 
 
 
 
 
 
 
 
 
 
 
 
336
  except Exception as e:
337
+ return f"An unexpected error occurred during submission: {e}", pd.DataFrame(results_log)
 
 
 
338
 
339
 
340
+ # --- Gradio Interface ---
341
  with gr.Blocks() as demo:
342
+ gr.Markdown("# 🤖 Smart Agent GAIA Benchmark Runner")
343
  gr.Markdown(
344
  """
345
+ **Powered by Claude with Web Search, Wikipedia, and Python tools**
346
+
347
  **Instructions:**
348
+ 1. Make sure `ANTHROPIC_API_KEY` is set in your Space secrets
349
+ 2. Log in with your Hugging Face account below
350
+ 3. Click **Run Evaluation & Submit All Answers**
351
+
352
+ The agent will fetch all 20 GAIA questions, reason through each one using tools, and submit your answers.
 
 
 
 
353
  """
354
  )
355
 
356
  gr.LoginButton()
357
 
358
+ run_button = gr.Button("🚀 Run Evaluation & Submit All Answers", variant="primary")
359
 
360
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
361
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
362
 
363
  run_button.click(
 
366
  )
367
 
368
  if __name__ == "__main__":
369
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
 
370
  space_host_startup = os.getenv("SPACE_HOST")
371
+ space_id_startup = os.getenv("SPACE_ID")
372
 
373
  if space_host_startup:
374
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
375
  else:
376
+ print("ℹ️ SPACE_HOST not found (running locally?)")
377
 
378
+ if space_id_startup:
379
  print(f"✅ SPACE_ID found: {space_id_startup}")
 
 
380
  else:
381
+ print("ℹ️ SPACE_ID not found (running locally?)")
 
 
382
 
383
+ print("-" * 74 + "\n")
384
+ print("Launching Gradio Interface...")
385
  demo.launch(debug=True, share=False)