Files changed (1) hide show
  1. App.py +249 -0
App.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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("Initializing GAIA Agent...")
16
+
17
+ hf_token = os.getenv("HF_TOKEN")
18
+
19
+ if not hf_token:
20
+ raise ValueError("HF_TOKEN is not configured in Space Secrets.")
21
+
22
+ model = InferenceClientModel(
23
+ model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
24
+ token=hf_token,
25
+ max_tokens=2048
26
+ )
27
+
28
+ self.agent = CodeAgent(
29
+ tools=[WebSearchTool(max_results=8)],
30
+ model=model,
31
+ additional_authorized_imports=[
32
+ "pandas",
33
+ "numpy",
34
+ "math",
35
+ "statistics",
36
+ "datetime",
37
+ "json",
38
+ "re"
39
+ ],
40
+ max_steps=8
41
+ )
42
+
43
+ print("GAIA Agent initialized successfully.")
44
+
45
+ def __call__(self, question: str) -> str:
46
+ print(f"Agent received question: {question[:100]}...")
47
+
48
+ prompt = f"""
49
+ You are solving a GAIA benchmark question.
50
+
51
+ Solve the question carefully and use tools when necessary.
52
+
53
+ You can:
54
+ - Search the web when the question requires external information.
55
+ - Use Python for calculations, data processing, and reasoning.
56
+ - Carefully inspect the question before answering.
57
+ - Verify calculations before giving the final answer.
58
+
59
+ IMPORTANT:
60
+ Return ONLY the final answer.
61
+ Do not explain your reasoning.
62
+ Do not write "FINAL ANSWER".
63
+ Do not add unnecessary text.
64
+
65
+ Question:
66
+ {question}
67
+ """
68
+
69
+ result = self.agent.run(prompt)
70
+
71
+ answer = str(result).strip()
72
+
73
+ print(f"Agent final answer: {answer}")
74
+
75
+ return answer
76
+
77
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
78
+ """
79
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
80
+ and displays the results.
81
+ """
82
+ # --- Determine HF Space Runtime URL and Repo URL ---
83
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
84
+
85
+ if profile:
86
+ username= f"{profile.username}"
87
+ print(f"User logged in: {username}")
88
+ else:
89
+ print("User not logged in.")
90
+ return "Please Login to Hugging Face with the button.", None
91
+
92
+ api_url = DEFAULT_API_URL
93
+ questions_url = f"{api_url}/questions"
94
+ submit_url = f"{api_url}/submit"
95
+
96
+ # 1. Instantiate Agent ( modify this part to create your agent)
97
+ try:
98
+ agent = BasicAgent()
99
+ except Exception as e:
100
+ print(f"Error instantiating agent: {e}")
101
+ return f"Error initializing agent: {e}", None
102
+ # 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)
103
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
104
+ print(agent_code)
105
+
106
+ # 2. Fetch Questions
107
+ print(f"Fetching questions from: {questions_url}")
108
+ try:
109
+ response = requests.get(questions_url, timeout=15)
110
+ response.raise_for_status()
111
+ questions_data = response.json()
112
+ if not questions_data:
113
+ print("Fetched questions list is empty.")
114
+ return "Fetched questions list is empty or invalid format.", None
115
+ print(f"Fetched {len(questions_data)} questions.")
116
+ except requests.exceptions.RequestException as e:
117
+ print(f"Error fetching questions: {e}")
118
+ return f"Error fetching questions: {e}", None
119
+ except requests.exceptions.JSONDecodeError as e:
120
+ print(f"Error decoding JSON response from questions endpoint: {e}")
121
+ print(f"Response text: {response.text[:500]}")
122
+ return f"Error decoding server response for questions: {e}", None
123
+ except Exception as e:
124
+ print(f"An unexpected error occurred fetching questions: {e}")
125
+ return f"An unexpected error occurred fetching questions: {e}", None
126
+
127
+ # 3. Run your Agent
128
+ results_log = []
129
+ answers_payload = []
130
+ print(f"Running agent on {len(questions_data)} questions...")
131
+ for item in questions_data:
132
+ task_id = item.get("task_id")
133
+ question_text = item.get("question")
134
+ if not task_id or question_text is None:
135
+ print(f"Skipping item with missing task_id or question: {item}")
136
+ continue
137
+ try:
138
+ submitted_answer = agent(question_text)
139
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
140
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
141
+ except Exception as e:
142
+ print(f"Error running agent on task {task_id}: {e}")
143
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
144
+
145
+ if not answers_payload:
146
+ print("Agent did not produce any answers to submit.")
147
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
148
+
149
+ # 4. Prepare Submission
150
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
151
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
152
+ print(status_update)
153
+
154
+ # 5. Submit
155
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
156
+ try:
157
+ response = requests.post(submit_url, json=submission_data, timeout=60)
158
+ response.raise_for_status()
159
+ result_data = response.json()
160
+ final_status = (
161
+ f"Submission Successful!\n"
162
+ f"User: {result_data.get('username')}\n"
163
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
164
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
165
+ f"Message: {result_data.get('message', 'No message received.')}"
166
+ )
167
+ print("Submission successful.")
168
+ results_df = pd.DataFrame(results_log)
169
+ return final_status, results_df
170
+ except requests.exceptions.HTTPError as e:
171
+ error_detail = f"Server responded with status {e.response.status_code}."
172
+ try:
173
+ error_json = e.response.json()
174
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
175
+ except requests.exceptions.JSONDecodeError:
176
+ error_detail += f" Response: {e.response.text[:500]}"
177
+ status_message = f"Submission Failed: {error_detail}"
178
+ print(status_message)
179
+ results_df = pd.DataFrame(results_log)
180
+ return status_message, results_df
181
+ except requests.exceptions.Timeout:
182
+ status_message = "Submission Failed: The request timed out."
183
+ print(status_message)
184
+ results_df = pd.DataFrame(results_log)
185
+ return status_message, results_df
186
+ except requests.exceptions.RequestException as e:
187
+ status_message = f"Submission Failed: Network error - {e}"
188
+ print(status_message)
189
+ results_df = pd.DataFrame(results_log)
190
+ return status_message, results_df
191
+ except Exception as e:
192
+ status_message = f"An unexpected error occurred during submission: {e}"
193
+ print(status_message)
194
+ results_df = pd.DataFrame(results_log)
195
+ return status_message, results_df
196
+
197
+
198
+ # --- Build Gradio Interface using Blocks ---
199
+ with gr.Blocks() as demo:
200
+ gr.Markdown("# Basic Agent Evaluation Runner")
201
+ gr.Markdown(
202
+ """
203
+ **Instructions:**
204
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
205
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
206
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
207
+ ---
208
+ **Disclaimers:**
209
+ 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).
210
+ 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.
211
+ """
212
+ )
213
+
214
+ gr.LoginButton()
215
+
216
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
217
+
218
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
219
+ # Removed max_rows=10 from DataFrame constructor
220
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
221
+
222
+ run_button.click(
223
+ fn=run_and_submit_all,
224
+ outputs=[status_output, results_table]
225
+ )
226
+
227
+ if __name__ == "__main__":
228
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
229
+ # Check for SPACE_HOST and SPACE_ID at startup for information
230
+ space_host_startup = os.getenv("SPACE_HOST")
231
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
232
+
233
+ if space_host_startup:
234
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
235
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
236
+ else:
237
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
238
+
239
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
240
+ print(f"✅ SPACE_ID found: {space_id_startup}")
241
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
242
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
243
+ else:
244
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
245
+
246
+ print("-"*(60 + len(" App Starting ")) + "\n")
247
+
248
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
249
+ demo.launch(debug=True, share=False)