dawid-lorek commited on
Commit
703ec74
·
verified ·
1 Parent(s): 4f6eaec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +173 -43
app.py CHANGED
@@ -1,66 +1,143 @@
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
 
5
  import time
6
- from agent import BasicAgent
 
7
 
 
 
 
 
 
 
 
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
- def run_and_submit_all(profile: gr.OAuthProfile | None):
11
- space_id = os.getenv("SPACE_ID")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  if profile:
13
- username = f"{profile.username}"
14
  print(f"User logged in: {username}")
15
  else:
16
  print("User not logged in.")
17
  return "Please Login to Hugging Face with the button.", None
18
 
19
- questions_url = f"{DEFAULT_API_URL}/questions"
20
- submit_url = f"{DEFAULT_API_URL}/submit"
21
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else ""
 
 
 
 
 
 
 
 
 
 
 
22
 
 
23
  print(f"Fetching questions from: {questions_url}")
24
  try:
25
  response = requests.get(questions_url, timeout=15)
26
  response.raise_for_status()
27
  questions_data = response.json()
28
  if not questions_data:
29
- print("Fetched questions list is empty.")
30
- return "Fetched questions list is empty or invalid format.", None
31
  print(f"Fetched {len(questions_data)} questions.")
32
- except Exception as e:
33
  print(f"Error fetching questions: {e}")
34
  return f"Error fetching questions: {e}", None
 
 
 
 
 
 
 
35
 
36
- agent = BasicAgent()
37
  results_log = []
38
  answers_payload = []
39
- print(f"Running agent on {len(questions_data)} questions...")
40
-
41
- for item in questions_data:
42
- task_id = item.get("task_id")
43
- question_text = item.get("question")
44
- if not task_id or question_text is None:
45
- print(f"Skipping item with missing task_id or question: {item}")
46
- continue
47
- try:
48
- submitted_answer = agent(question_text)
49
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
50
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
51
- time.sleep(2)
52
- except Exception as e:
53
- print(f"Error running agent on task {task_id}: {e}")
54
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
55
-
56
- if not answers_payload:
57
- print("Agent did not produce any answers to submit.")
58
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
61
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
62
  print(status_update)
63
 
 
64
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
65
  try:
66
  response = requests.post(submit_url, json=submission_data, timeout=60)
@@ -76,30 +153,83 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
76
  print("Submission successful.")
77
  results_df = pd.DataFrame(results_log)
78
  return final_status, results_df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  except Exception as e:
80
- status_message = f"Submission Failed: {e}"
81
  print(status_message)
82
  results_df = pd.DataFrame(results_log)
83
  return status_message, results_df
84
 
 
 
85
  with gr.Blocks() as demo:
86
  gr.Markdown("# Basic Agent Evaluation Runner")
87
- gr.Markdown("""
88
- **Instructions:**
89
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
90
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
91
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
92
- ---
93
- **Disclaimers:**
94
- 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).
95
- This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution.
96
- """)
 
 
 
97
  gr.LoginButton()
 
98
  run_button = gr.Button("Run Evaluation & Submit All Answers")
 
99
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
100
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
101
- run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
 
 
102
 
103
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  print("Launching Gradio Interface for Basic Agent Evaluation...")
105
  demo.launch(debug=True, share=False)
 
1
  import os
2
  import gradio as gr
3
  import requests
4
+ import inspect
5
  import pandas as pd
6
+ from agent import GaiaAgent
7
  import time
8
+ from smolagents import LiteLLMModel
9
+ import json
10
 
11
+ model = LiteLLMModel(model_id="gemini/gemini-2.0-flash", api_key=os.getenv("GEMINI_API_KEY"))
12
+ MODEL_RPM_LIMIT = 15
13
+
14
+ RERUN = False
15
+
16
+ # (Keep Constants as is)
17
+ # --- Constants ---
18
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
19
 
20
+ # --- Basic Agent Definition ---
21
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
22
+ class BasicAgent:
23
+ def __init__(self):
24
+ print("BasicAgent initialized.")
25
+ def __call__(self, question: str) -> str:
26
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
27
+ fixed_answer = "This is a default answer."
28
+ print(f"Agent returning fixed answer: {fixed_answer}")
29
+ return fixed_answer
30
+
31
+ def load_json_list(filename):
32
+ """
33
+ Loads a list of JSON objects from a file.
34
+ Args:
35
+ filename (str): The name of the file to load from.
36
+ Returns:
37
+ list: The loaded list of dictionaries, or an empty list if an error occurs.
38
+ """
39
+ try:
40
+ with open(filename, 'r', encoding='utf-8') as f:
41
+ data = json.load(f)
42
+ print(f"Data successfully loaded from '{filename}'")
43
+ return data
44
+ except FileNotFoundError:
45
+ print(f"Error: File '{filename}' not found.")
46
+ return []
47
+ except json.JSONDecodeError as e:
48
+ print(f"Error decoding JSON from file '{filename}': {e}")
49
+ return []
50
+ except IOError as e:
51
+ print(f"Error reading data from file: {e}")
52
+ return []
53
+
54
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
55
+ """
56
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
57
+ and displays the results.
58
+ """
59
+ # --- Determine HF Space Runtime URL and Repo URL ---
60
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
61
+
62
  if profile:
63
+ username= f"{profile.username}"
64
  print(f"User logged in: {username}")
65
  else:
66
  print("User not logged in.")
67
  return "Please Login to Hugging Face with the button.", None
68
 
69
+ api_url = DEFAULT_API_URL
70
+ questions_url = f"{api_url}/questions"
71
+ submit_url = f"{api_url}/submit"
72
+
73
+ # 1. Instantiate Agent ( modify this part to create your agent)
74
+ try:
75
+ #agent = BasicAgent()
76
+ agent = GaiaAgent(model, MODEL_RPM_LIMIT )
77
+ except Exception as e:
78
+ print(f"Error instantiating agent: {e}")
79
+ return f"Error initializing agent: {e}", None
80
+ # 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)
81
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
82
+ print(agent_code)
83
 
84
+ # 2. Fetch Questions
85
  print(f"Fetching questions from: {questions_url}")
86
  try:
87
  response = requests.get(questions_url, timeout=15)
88
  response.raise_for_status()
89
  questions_data = response.json()
90
  if not questions_data:
91
+ print("Fetched questions list is empty.")
92
+ return "Fetched questions list is empty or invalid format.", None
93
  print(f"Fetched {len(questions_data)} questions.")
94
+ except requests.exceptions.RequestException as e:
95
  print(f"Error fetching questions: {e}")
96
  return f"Error fetching questions: {e}", None
97
+ except requests.exceptions.JSONDecodeError as e:
98
+ print(f"Error decoding JSON response from questions endpoint: {e}")
99
+ print(f"Response text: {response.text[:500]}")
100
+ return f"Error decoding server response for questions: {e}", None
101
+ except Exception as e:
102
+ print(f"An unexpected error occurred fetching questions: {e}")
103
+ return f"An unexpected error occurred fetching questions: {e}", None
104
 
105
+ # 3. Run your Agent
106
  results_log = []
107
  answers_payload = []
108
+ if RERUN:
109
+ print(f"Running agent on {len(questions_data)} questions...")
110
+ for item in questions_data:
111
+ task_id = item.get("task_id")
112
+ question_text = item.get("question")
113
+ file_name = item.get("file_name")
114
+ if(item.get("file_name") != None):
115
+ question_text = question_text + f" To answer use the file provided, download it with the tool provided with the task_id {task_id} and the file name {file_name}."
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
+ if not task_id or question_text is None:
118
+ print(f"Skipping item with missing task_id or question: {item}")
119
+ continue
120
+ try:
121
+ submitted_answer = agent(question_text)
122
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
123
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
124
+ except Exception as e:
125
+ print(f"Error running agent on task {task_id}: {e}")
126
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
127
+ time.sleep(60)
128
+
129
+ if not answers_payload:
130
+ print("Agent did not produce any answers to submit.")
131
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
132
+ else:
133
+ answers_payload = load_json_list("answers_payload.json")
134
+
135
+ # 4. Prepare Submission
136
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
137
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
138
  print(status_update)
139
 
140
+ # 5. Submit
141
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
142
  try:
143
  response = requests.post(submit_url, json=submission_data, timeout=60)
 
153
  print("Submission successful.")
154
  results_df = pd.DataFrame(results_log)
155
  return final_status, results_df
156
+ except requests.exceptions.HTTPError as e:
157
+ error_detail = f"Server responded with status {e.response.status_code}."
158
+ try:
159
+ error_json = e.response.json()
160
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
161
+ except requests.exceptions.JSONDecodeError:
162
+ error_detail += f" Response: {e.response.text[:500]}"
163
+ status_message = f"Submission Failed: {error_detail}"
164
+ print(status_message)
165
+ results_df = pd.DataFrame(results_log)
166
+ return status_message, results_df
167
+ except requests.exceptions.Timeout:
168
+ status_message = "Submission Failed: The request timed out."
169
+ print(status_message)
170
+ results_df = pd.DataFrame(results_log)
171
+ return status_message, results_df
172
+ except requests.exceptions.RequestException as e:
173
+ status_message = f"Submission Failed: Network error - {e}"
174
+ print(status_message)
175
+ results_df = pd.DataFrame(results_log)
176
+ return status_message, results_df
177
  except Exception as e:
178
+ status_message = f"An unexpected error occurred during submission: {e}"
179
  print(status_message)
180
  results_df = pd.DataFrame(results_log)
181
  return status_message, results_df
182
 
183
+
184
+ # --- Build Gradio Interface using Blocks ---
185
  with gr.Blocks() as demo:
186
  gr.Markdown("# Basic Agent Evaluation Runner")
187
+ gr.Markdown(
188
+ """
189
+ **Instructions:**
190
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
191
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
192
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
193
+ ---
194
+ **Disclaimers:**
195
+ 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).
196
+ 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.
197
+ """
198
+ )
199
+
200
  gr.LoginButton()
201
+
202
  run_button = gr.Button("Run Evaluation & Submit All Answers")
203
+
204
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
205
+ # Removed max_rows=10 from DataFrame constructor
206
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
207
+
208
+ run_button.click(
209
+ fn=run_and_submit_all,
210
+ outputs=[status_output, results_table]
211
+ )
212
 
213
  if __name__ == "__main__":
214
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
215
+ # Check for SPACE_HOST and SPACE_ID at startup for information
216
+ space_host_startup = os.getenv("SPACE_HOST")
217
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
218
+
219
+ if space_host_startup:
220
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
221
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
222
+ else:
223
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
224
+
225
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
226
+ print(f"✅ SPACE_ID found: {space_id_startup}")
227
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
228
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
229
+ else:
230
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
231
+
232
+ print("-"*(60 + len(" App Starting ")) + "\n")
233
+
234
  print("Launching Gradio Interface for Basic Agent Evaluation...")
235
  demo.launch(debug=True, share=False)