Gary commited on
Commit
d1f5d46
·
1 Parent(s): e891cbe
Files changed (3) hide show
  1. README copy.md +15 -0
  2. app.py +240 -0
  3. requirements.txt +3 -0
README copy.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Template 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,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import pandas as pd
5
+ from smolagents import (
6
+ CodeAgent,
7
+ OpenAIServerModel,
8
+ DuckDuckGoSearchTool,
9
+ )
10
+
11
+ # (Keep Constants as is)
12
+ # --- Constants ---
13
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
+
15
+
16
+ # --- Basic Agent Definition ---
17
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
18
+ class BasicAgent:
19
+ def __init__(self):
20
+ print("BasicAgent initialized.")
21
+
22
+ def __call__(self, question: str) -> str:
23
+ model = OpenAIServerModel(
24
+ model_id="gpt-4o-mini",
25
+ api_base="https://api.openai.com/v1",
26
+ api_key=os.getenv("API_KEY"),
27
+ )
28
+ search_tool = DuckDuckGoSearchTool()
29
+ code_agent = CodeAgent(
30
+ tools=[search_tool],
31
+ model=model,
32
+ add_base_tools=True,
33
+ max_steps=1,
34
+ )
35
+ response = code_agent.run(
36
+ f"""
37
+ You are an expert in answering questions with the tools provided. Answer the question below and only return a single string or number as answer. Do not elaborate on the answer.
38
+ Question:
39
+ {question}
40
+ """
41
+ )
42
+ return response
43
+
44
+
45
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
46
+ """
47
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
48
+ and displays the results.
49
+ """
50
+ # --- Determine HF Space Runtime URL and Repo URL ---
51
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
52
+
53
+ if profile:
54
+ username = f"{profile.username}"
55
+ print(f"User logged in: {username}")
56
+ else:
57
+ print("User not logged in.")
58
+ return "Please Login to Hugging Face with the button.", None
59
+
60
+ api_url = DEFAULT_API_URL
61
+ questions_url = f"{api_url}/questions"
62
+ submit_url = f"{api_url}/submit"
63
+
64
+ # 1. Instantiate Agent ( modify this part to create your agent)
65
+ try:
66
+ agent = BasicAgent()
67
+ except Exception as e:
68
+ print(f"Error instantiating agent: {e}")
69
+ return f"Error initializing agent: {e}", None
70
+ # 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)
71
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
72
+ print(agent_code)
73
+
74
+ # 2. Fetch Questions
75
+ print(f"Fetching questions from: {questions_url}")
76
+ try:
77
+ response = requests.get(questions_url, timeout=15)
78
+ response.raise_for_status()
79
+ questions_data = response.json()
80
+ if not questions_data:
81
+ print("Fetched questions list is empty.")
82
+ return "Fetched questions list is empty or invalid format.", None
83
+ print(f"Fetched {len(questions_data)} questions.")
84
+ except requests.exceptions.RequestException as e:
85
+ print(f"Error fetching questions: {e}")
86
+ return f"Error fetching questions: {e}", None
87
+ except requests.exceptions.JSONDecodeError as e:
88
+ print(f"Error decoding JSON response from questions endpoint: {e}")
89
+ print(f"Response text: {response.text[:500]}")
90
+ return f"Error decoding server response for questions: {e}", None
91
+ except Exception as e:
92
+ print(f"An unexpected error occurred fetching questions: {e}")
93
+ return f"An unexpected error occurred fetching questions: {e}", None
94
+
95
+ # 3. Run your Agent
96
+ results_log = []
97
+ answers_payload = []
98
+ print(f"Running agent on {len(questions_data)} questions...")
99
+ for item in questions_data:
100
+ task_id = item.get("task_id")
101
+ question_text = item.get("question")
102
+ if not task_id or question_text is None:
103
+ print(f"Skipping item with missing task_id or question: {item}")
104
+ continue
105
+ try:
106
+ submitted_answer = agent(question_text)
107
+ answers_payload.append(
108
+ {"task_id": task_id, "submitted_answer": submitted_answer}
109
+ )
110
+ results_log.append(
111
+ {
112
+ "Task ID": task_id,
113
+ "Question": question_text,
114
+ "Submitted Answer": submitted_answer,
115
+ }
116
+ )
117
+ except Exception as e:
118
+ print(f"Error running agent on task {task_id}: {e}")
119
+ results_log.append(
120
+ {
121
+ "Task ID": task_id,
122
+ "Question": question_text,
123
+ "Submitted Answer": f"AGENT ERROR: {e}",
124
+ }
125
+ )
126
+
127
+ if not answers_payload:
128
+ print("Agent did not produce any answers to submit.")
129
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
130
+
131
+ # 4. Prepare Submission
132
+ submission_data = {
133
+ "username": username.strip(),
134
+ "agent_code": agent_code,
135
+ "answers": answers_payload,
136
+ }
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)
144
+ response.raise_for_status()
145
+ result_data = response.json()
146
+ final_status = (
147
+ f"Submission Successful!\n"
148
+ f"User: {result_data.get('username')}\n"
149
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
150
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
151
+ f"Message: {result_data.get('message', 'No message received.')}"
152
+ )
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
+
191
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
192
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
193
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
194
+
195
+ ---
196
+ **Disclaimers:**
197
+ 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).
198
+ 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.
199
+ """
200
+ )
201
+
202
+ gr.LoginButton()
203
+
204
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
205
+
206
+ status_output = gr.Textbox(
207
+ label="Run Status / Submission Result", lines=5, interactive=False
208
+ )
209
+ # Removed max_rows=10 from DataFrame constructor
210
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
211
+
212
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
213
+
214
+ if __name__ == "__main__":
215
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
216
+ # Check for SPACE_HOST and SPACE_ID at startup for information
217
+ space_host_startup = os.getenv("SPACE_HOST")
218
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
219
+
220
+ if space_host_startup:
221
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
222
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
223
+ else:
224
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
225
+
226
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
227
+ print(f"✅ SPACE_ID found: {space_id_startup}")
228
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
229
+ print(
230
+ f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
231
+ )
232
+ else:
233
+ print(
234
+ "ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
235
+ )
236
+
237
+ print("-" * (60 + len(" App Starting ")) + "\n")
238
+
239
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
240
+ demo.launch(debug=True, share=False)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio
2
+ requests
3
+ smolagents