Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -13,12 +13,10 @@ from smolagents import (
|
|
13 |
OpenAIServerModel
|
14 |
)
|
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 |
self.model = OpenAIServerModel(
|
@@ -43,22 +41,15 @@ If you are asked for a number, don't use comma to write your number neither use
|
|
43 |
If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
|
44 |
If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
|
45 |
"""
|
46 |
-
|
47 |
|
48 |
-
|
49 |
-
#self.agent.prompt_templates['system_prompt'] = """
|
50 |
-
|
51 |
-
#You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
|
52 |
-
|
53 |
-
#"""
|
54 |
-
print("BasicAgent initialized.")
|
55 |
def __call__(self, question: str) -> str:
|
56 |
-
|
57 |
fixed_answer = self.agent.run(question)
|
58 |
-
|
59 |
return fixed_answer
|
60 |
|
61 |
-
def run_and_submit_all(
|
62 |
"""
|
63 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
64 |
and displays the results.
|
@@ -68,76 +59,76 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
68 |
|
69 |
if profile:
|
70 |
username= f"{profile.username}"
|
71 |
-
|
72 |
else:
|
73 |
-
|
74 |
return "Please Login to Hugging Face with the button.", None
|
75 |
|
76 |
api_url = DEFAULT_API_URL
|
77 |
questions_url = f"{api_url}/questions"
|
78 |
submit_url = f"{api_url}/submit"
|
79 |
|
80 |
-
# 1. Instantiate Agent
|
81 |
try:
|
82 |
agent = BasicAgent()
|
83 |
except Exception as e:
|
84 |
-
|
85 |
return f"Error initializing agent: {e}", None
|
86 |
-
# In the case of an app running as a hugging Face space, this link points toward your codebase
|
87 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
88 |
-
|
89 |
|
90 |
# 2. Fetch Questions
|
91 |
-
|
92 |
try:
|
93 |
response = requests.get(questions_url, timeout=15)
|
94 |
response.raise_for_status()
|
95 |
questions_data = response.json()
|
96 |
if not questions_data:
|
97 |
-
|
98 |
return "Fetched questions list is empty or invalid format.", None
|
99 |
-
|
100 |
except requests.exceptions.RequestException as e:
|
101 |
-
|
102 |
return f"Error fetching questions: {e}", None
|
103 |
except requests.exceptions.JSONDecodeError as e:
|
104 |
-
|
105 |
-
|
106 |
return f"Error decoding server response for questions: {e}", None
|
107 |
except Exception as e:
|
108 |
-
|
109 |
return f"An unexpected error occurred fetching questions: {e}", None
|
110 |
|
111 |
# 3. Run your Agent
|
112 |
results_log = []
|
113 |
answers_payload = []
|
114 |
-
|
115 |
for i, item in enumerate(questions_data):
|
116 |
task_id = item.get("task_id")
|
117 |
question_text = item.get("question")
|
118 |
if not task_id or question_text is None:
|
119 |
-
|
120 |
continue
|
121 |
try:
|
122 |
submitted_answer = agent(question_text)
|
123 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
124 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
125 |
except Exception as e:
|
126 |
-
|
127 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
128 |
|
129 |
|
130 |
if not answers_payload:
|
131 |
-
|
132 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
133 |
|
134 |
# 4. Prepare Submission
|
135 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
136 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
137 |
-
|
138 |
|
139 |
# 5. Submit
|
140 |
-
|
141 |
try:
|
142 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
143 |
response.raise_for_status()
|
@@ -149,7 +140,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
149 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
150 |
f"Message: {result_data.get('message', 'No message received.')}"
|
151 |
)
|
152 |
-
|
153 |
results_df = pd.DataFrame(results_log)
|
154 |
return final_status, results_df
|
155 |
except requests.exceptions.HTTPError as e:
|
@@ -160,22 +151,22 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
160 |
except requests.exceptions.JSONDecodeError:
|
161 |
error_detail += f" Response: {e.response.text[:500]}"
|
162 |
status_message = f"Submission Failed: {error_detail}"
|
163 |
-
|
164 |
results_df = pd.DataFrame(results_log)
|
165 |
return status_message, results_df
|
166 |
except requests.exceptions.Timeout:
|
167 |
status_message = "Submission Failed: The request timed out."
|
168 |
-
|
169 |
results_df = pd.DataFrame(results_log)
|
170 |
return status_message, results_df
|
171 |
except requests.exceptions.RequestException as e:
|
172 |
status_message = f"Submission Failed: Network error - {e}"
|
173 |
-
|
174 |
results_df = pd.DataFrame(results_log)
|
175 |
return status_message, results_df
|
176 |
except Exception as e:
|
177 |
status_message = f"An unexpected error occurred during submission: {e}"
|
178 |
-
|
179 |
results_df = pd.DataFrame(results_log)
|
180 |
return status_message, results_df
|
181 |
|
@@ -203,7 +194,6 @@ with gr.Blocks() as demo:
|
|
203 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
204 |
|
205 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
206 |
-
# Removed max_rows=10 from DataFrame constructor
|
207 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
208 |
|
209 |
run_button.click(
|
@@ -212,25 +202,5 @@ with gr.Blocks() as demo:
|
|
212 |
)
|
213 |
|
214 |
if __name__ == "__main__":
|
215 |
-
|
216 |
-
|
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(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
230 |
-
else:
|
231 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
232 |
-
|
233 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
234 |
-
|
235 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
236 |
-
demo.launch(debug=True, share=False)
|
|
|
13 |
OpenAIServerModel
|
14 |
)
|
15 |
|
|
|
16 |
# --- Constants ---
|
17 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
18 |
|
19 |
# --- Basic Agent Definition ---
|
|
|
20 |
class BasicAgent:
|
21 |
def __init__(self):
|
22 |
self.model = OpenAIServerModel(
|
|
|
41 |
If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
|
42 |
If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
|
43 |
"""
|
44 |
+
# 移除打印语句
|
45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
def __call__(self, question: str) -> str:
|
47 |
+
# 移除打印语句
|
48 |
fixed_answer = self.agent.run(question)
|
49 |
+
# 移除打印语句
|
50 |
return fixed_answer
|
51 |
|
52 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
53 |
"""
|
54 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
55 |
and displays the results.
|
|
|
59 |
|
60 |
if profile:
|
61 |
username= f"{profile.username}"
|
62 |
+
# 移除打印语句
|
63 |
else:
|
64 |
+
# 移除打印语句
|
65 |
return "Please Login to Hugging Face with the button.", None
|
66 |
|
67 |
api_url = DEFAULT_API_URL
|
68 |
questions_url = f"{api_url}/questions"
|
69 |
submit_url = f"{api_url}/submit"
|
70 |
|
71 |
+
# 1. Instantiate Agent
|
72 |
try:
|
73 |
agent = BasicAgent()
|
74 |
except Exception as e:
|
75 |
+
# 移除打印语句
|
76 |
return f"Error initializing agent: {e}", None
|
77 |
+
# In the case of an app running as a hugging Face space, this link points toward your codebase
|
78 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
79 |
+
# 移除打印语句
|
80 |
|
81 |
# 2. Fetch Questions
|
82 |
+
# 移除打印语句
|
83 |
try:
|
84 |
response = requests.get(questions_url, timeout=15)
|
85 |
response.raise_for_status()
|
86 |
questions_data = response.json()
|
87 |
if not questions_data:
|
88 |
+
# 移除打印语句
|
89 |
return "Fetched questions list is empty or invalid format.", None
|
90 |
+
# 移除打印语句
|
91 |
except requests.exceptions.RequestException as e:
|
92 |
+
# 移除打印语句
|
93 |
return f"Error fetching questions: {e}", None
|
94 |
except requests.exceptions.JSONDecodeError as e:
|
95 |
+
# 移除打印语句
|
96 |
+
# 移除打印语句
|
97 |
return f"Error decoding server response for questions: {e}", None
|
98 |
except Exception as e:
|
99 |
+
# 移除打印语句
|
100 |
return f"An unexpected error occurred fetching questions: {e}", None
|
101 |
|
102 |
# 3. Run your Agent
|
103 |
results_log = []
|
104 |
answers_payload = []
|
105 |
+
# 移除打印语句
|
106 |
for i, item in enumerate(questions_data):
|
107 |
task_id = item.get("task_id")
|
108 |
question_text = item.get("question")
|
109 |
if not task_id or question_text is None:
|
110 |
+
# 移除打印语句
|
111 |
continue
|
112 |
try:
|
113 |
submitted_answer = agent(question_text)
|
114 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
115 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
116 |
except Exception as e:
|
117 |
+
# 移除打印语句
|
118 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
119 |
|
120 |
|
121 |
if not answers_payload:
|
122 |
+
# 移除打印语句
|
123 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
124 |
|
125 |
# 4. Prepare Submission
|
126 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
127 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
128 |
+
# 移除打印语句
|
129 |
|
130 |
# 5. Submit
|
131 |
+
# 移除打印语句
|
132 |
try:
|
133 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
134 |
response.raise_for_status()
|
|
|
140 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
141 |
f"Message: {result_data.get('message', 'No message received.')}"
|
142 |
)
|
143 |
+
# 移除打印语句
|
144 |
results_df = pd.DataFrame(results_log)
|
145 |
return final_status, results_df
|
146 |
except requests.exceptions.HTTPError as e:
|
|
|
151 |
except requests.exceptions.JSONDecodeError:
|
152 |
error_detail += f" Response: {e.response.text[:500]}"
|
153 |
status_message = f"Submission Failed: {error_detail}"
|
154 |
+
# 移除打印语句
|
155 |
results_df = pd.DataFrame(results_log)
|
156 |
return status_message, results_df
|
157 |
except requests.exceptions.Timeout:
|
158 |
status_message = "Submission Failed: The request timed out."
|
159 |
+
# 移除打印语句
|
160 |
results_df = pd.DataFrame(results_log)
|
161 |
return status_message, results_df
|
162 |
except requests.exceptions.RequestException as e:
|
163 |
status_message = f"Submission Failed: Network error - {e}"
|
164 |
+
# 移除打印语句
|
165 |
results_df = pd.DataFrame(results_log)
|
166 |
return status_message, results_df
|
167 |
except Exception as e:
|
168 |
status_message = f"An unexpected error occurred during submission: {e}"
|
169 |
+
# 移除打印语句
|
170 |
results_df = pd.DataFrame(results_log)
|
171 |
return status_message, results_df
|
172 |
|
|
|
194 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
195 |
|
196 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
197 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
198 |
|
199 |
run_button.click(
|
|
|
202 |
)
|
203 |
|
204 |
if __name__ == "__main__":
|
205 |
+
# 移除所有启动时的打印语句
|
206 |
+
demo.launch(debug=False, share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|