YI Zhongyue commited on
Commit
d142da5
·
1 Parent(s): 1b22afc
Files changed (7) hide show
  1. .python-version +1 -0
  2. README.md +8 -5
  3. app.py +221 -0
  4. main.py +6 -0
  5. pyproject.toml +11 -0
  6. requirements.txt +2 -0
  7. uv.lock +0 -0
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.11
README.md CHANGED
@@ -1,12 +1,15 @@
1
  ---
2
  title: Agents Course Final Assignment
3
- emoji: 🏃
4
- colorFrom: purple
5
- colorTo: green
6
  sdk: gradio
7
- sdk_version: 5.34.0
8
  app_file: app.py
9
  pinned: false
 
 
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
  title: Agents Course Final Assignment
3
+ emoji: 🕵🏻‍♂️
4
+ colorFrom: indigo
5
+ colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 5.25.2
8
  app_file: app.py
9
  pinned: false
10
+ hf_oauth: true
11
+ # optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
12
+ hf_oauth_expiration_minutes: 480
13
  ---
14
 
15
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import os
3
+
4
+ import gradio as gr
5
+ import pandas as pd
6
+ import requests
7
+
8
+ # (Keep Constants as is)
9
+ # --- Constants ---
10
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
+
12
+
13
+ # --- Basic Agent Definition ---
14
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
15
+ class BasicAgent:
16
+ def __init__(self):
17
+ print("BasicAgent initialized.")
18
+
19
+ def __call__(self, question: str) -> str:
20
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
21
+ fixed_answer = "This is a default answer."
22
+ print(f"Agent returning fixed answer: {fixed_answer}")
23
+ return fixed_answer
24
+
25
+
26
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
27
+ """
28
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
29
+ and displays the results.
30
+ """
31
+ # --- Determine HF Space Runtime URL and Repo URL ---
32
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
33
+
34
+ if profile:
35
+ username = f"{profile.username}"
36
+ print(f"User logged in: {username}")
37
+ else:
38
+ print("User not logged in.")
39
+ return "Please Login to Hugging Face with the button.", None
40
+
41
+ api_url = DEFAULT_API_URL
42
+ questions_url = f"{api_url}/questions"
43
+ submit_url = f"{api_url}/submit"
44
+
45
+ # 1. Instantiate Agent ( modify this part to create your agent)
46
+ try:
47
+ agent = BasicAgent()
48
+ except Exception as e:
49
+ print(f"Error instantiating agent: {e}")
50
+ return f"Error initializing agent: {e}", None
51
+ # 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)
52
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
53
+ print(agent_code)
54
+
55
+ # 2. Fetch Questions
56
+ print(f"Fetching questions from: {questions_url}")
57
+ try:
58
+ response = requests.get(questions_url, timeout=15)
59
+ response.raise_for_status()
60
+ questions_data = response.json()
61
+ if not questions_data:
62
+ print("Fetched questions list is empty.")
63
+ return "Fetched questions list is empty or invalid format.", None
64
+ print(f"Fetched {len(questions_data)} questions.")
65
+ except requests.exceptions.JSONDecodeError as e:
66
+ print(f"Error decoding JSON response from questions endpoint: {e}")
67
+ print(f"Response text: {response.text[:500]}")
68
+ return f"Error decoding server response for questions: {e}", None
69
+ except requests.exceptions.RequestException as e:
70
+ print(f"Error fetching questions: {e}")
71
+ return f"Error fetching questions: {e}", None
72
+ except Exception as e:
73
+ print(f"An unexpected error occurred fetching questions: {e}")
74
+ return f"An unexpected error occurred fetching questions: {e}", None
75
+
76
+ # 3. Run your Agent
77
+ results_log = []
78
+ answers_payload = []
79
+ print(f"Running agent on {len(questions_data)} questions...")
80
+ for item in questions_data:
81
+ task_id = item.get("task_id")
82
+ question_text = item.get("question")
83
+ if not task_id or question_text is None:
84
+ print(f"Skipping item with missing task_id or question: {item}")
85
+ continue
86
+ try:
87
+ submitted_answer = agent(question_text)
88
+ answers_payload.append(
89
+ {"task_id": task_id, "submitted_answer": submitted_answer}
90
+ )
91
+ results_log.append(
92
+ {
93
+ "Task ID": task_id,
94
+ "Question": question_text,
95
+ "Submitted Answer": submitted_answer,
96
+ }
97
+ )
98
+ except Exception as e:
99
+ print(f"Error running agent on task {task_id}: {e}")
100
+ results_log.append(
101
+ {
102
+ "Task ID": task_id,
103
+ "Question": question_text,
104
+ "Submitted Answer": f"AGENT ERROR: {e}",
105
+ }
106
+ )
107
+
108
+ if not answers_payload:
109
+ print("Agent did not produce any answers to submit.")
110
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
111
+
112
+ # 4. Prepare Submission
113
+ submission_data = {
114
+ "username": username.strip(),
115
+ "agent_code": agent_code,
116
+ "answers": answers_payload,
117
+ }
118
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
119
+ print(status_update)
120
+
121
+ # 5. Submit
122
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
123
+ try:
124
+ response = requests.post(submit_url, json=submission_data, timeout=60)
125
+ response.raise_for_status()
126
+ result_data = response.json()
127
+ final_status = (
128
+ f"Submission Successful!\n"
129
+ f"User: {result_data.get('username')}\n"
130
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
131
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
132
+ f"Message: {result_data.get('message', 'No message received.')}"
133
+ )
134
+ print("Submission successful.")
135
+ results_df = pd.DataFrame(results_log)
136
+ return final_status, results_df
137
+ except requests.exceptions.HTTPError as e:
138
+ error_detail = f"Server responded with status {e.response.status_code}."
139
+ try:
140
+ error_json = e.response.json()
141
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
142
+ except requests.exceptions.JSONDecodeError:
143
+ error_detail += f" Response: {e.response.text[:500]}"
144
+ status_message = f"Submission Failed: {error_detail}"
145
+ print(status_message)
146
+ results_df = pd.DataFrame(results_log)
147
+ return status_message, results_df
148
+ except requests.exceptions.Timeout:
149
+ status_message = "Submission Failed: The request timed out."
150
+ print(status_message)
151
+ results_df = pd.DataFrame(results_log)
152
+ return status_message, results_df
153
+ except requests.exceptions.RequestException as e:
154
+ status_message = f"Submission Failed: Network error - {e}"
155
+ print(status_message)
156
+ results_df = pd.DataFrame(results_log)
157
+ return status_message, results_df
158
+ except Exception as e:
159
+ status_message = f"An unexpected error occurred during submission: {e}"
160
+ print(status_message)
161
+ results_df = pd.DataFrame(results_log)
162
+ return status_message, results_df
163
+
164
+
165
+ # --- Build Gradio Interface using Blocks ---
166
+ with gr.Blocks() as demo:
167
+ gr.Markdown("# Basic Agent Evaluation Runner")
168
+ gr.Markdown(
169
+ """
170
+ **Instructions:**
171
+
172
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
173
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
174
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
175
+
176
+ ---
177
+ **Disclaimers:**
178
+ 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).
179
+ 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.
180
+ """
181
+ )
182
+
183
+ gr.LoginButton()
184
+
185
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
186
+
187
+ status_output = gr.Textbox(
188
+ label="Run Status / Submission Result", lines=5, interactive=False
189
+ )
190
+ # Removed max_rows=10 from DataFrame constructor
191
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
192
+
193
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
194
+
195
+ if __name__ == "__main__":
196
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
197
+ # Check for SPACE_HOST and SPACE_ID at startup for information
198
+ space_host_startup = os.getenv("SPACE_HOST")
199
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
200
+
201
+ if space_host_startup:
202
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
203
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
204
+ else:
205
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
206
+
207
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
208
+ print(f"✅ SPACE_ID found: {space_id_startup}")
209
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
210
+ print(
211
+ f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
212
+ )
213
+ else:
214
+ print(
215
+ "ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
216
+ )
217
+
218
+ print("-" * (60 + len(" App Starting ")) + "\n")
219
+
220
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
221
+ demo.launch(debug=True, share=False)
main.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ def main():
2
+ print("Hello from final-assignment-template!")
3
+
4
+
5
+ if __name__ == "__main__":
6
+ main()
pyproject.toml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "Agents-Course-Final-Assignment"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ dependencies = [
8
+ "gradio>=5.34.0",
9
+ "requests>=2.32.4",
10
+ "types-requests>=2.32.4.20250611",
11
+ ]
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ gradio
2
+ requests
uv.lock ADDED
The diff for this file is too large to render. See raw diff