Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -4,9 +4,8 @@ import requests
|
|
4 |
import string
|
5 |
import warnings
|
6 |
import pandas as pd
|
7 |
-
from huggingface_hub import login
|
8 |
import re
|
9 |
-
import
|
10 |
from groq import Groq
|
11 |
|
12 |
# --- Constants ---
|
@@ -16,7 +15,7 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
16 |
class BasicAgent:
|
17 |
def __init__(self):
|
18 |
print("BasicAgent initialized.")
|
19 |
-
self.client = Groq(api_key=os.environ
|
20 |
self.agent_prompt = (
|
21 |
"""You are a general AI assistant. I will ask you a question. Report your thoughts, and
|
22 |
finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
|
@@ -75,7 +74,7 @@ class BasicAgent:
|
|
75 |
"true": "false", "yes": "no", "black": "white"
|
76 |
}
|
77 |
opposite = opposites.get(word, f"UNKNOWN_OPPOSITE_OF_{word}")
|
78 |
-
return "FINAL ANSWER:
|
79 |
return self.format_final_answer("COULD_NOT_SOLVE")
|
80 |
|
81 |
def query_groq(self, question: str) -> str:
|
@@ -86,6 +85,7 @@ class BasicAgent:
|
|
86 |
messages=[{"role": "user", "content": full_prompt}]
|
87 |
)
|
88 |
answer = response.choices[0].message.content
|
|
|
89 |
if "FINAL ANSWER: " in answer:
|
90 |
return answer.split("FINAL ANSWER: ")[-1].strip().upper()
|
91 |
else:
|
@@ -103,68 +103,6 @@ class BasicAgent:
|
|
103 |
return self.solve_riddle(question)
|
104 |
return self.query_groq(question)
|
105 |
|
106 |
-
# --- Answer Scoring ---
|
107 |
-
def question_scorer(model_answer: str, ground_truth: str) -> bool:
|
108 |
-
def normalize_str(input_str, remove_punct=True) -> str:
|
109 |
-
no_spaces = re.sub(r"\s", "", input_str)
|
110 |
-
if remove_punct:
|
111 |
-
translator = str.maketrans("", "", string.punctuation)
|
112 |
-
return no_spaces.lower().translate(translator)
|
113 |
-
else:
|
114 |
-
return no_spaces.lower()
|
115 |
-
|
116 |
-
def normalize_number_str(number_str: str) -> float | None:
|
117 |
-
for char in ["$", "%", ","]:
|
118 |
-
number_str = number_str.replace(char, "")
|
119 |
-
try:
|
120 |
-
return float(number_str)
|
121 |
-
except ValueError:
|
122 |
-
print(f"String '{number_str}' cannot be normalized to number.")
|
123 |
-
return None
|
124 |
-
|
125 |
-
def split_string(s: str, char_list: list[str] = [",", ";"]) -> list[str]:
|
126 |
-
pattern = f"[{''.join(map(re.escape, char_list))}]"
|
127 |
-
return [elem.strip() for elem in re.split(pattern, s)]
|
128 |
-
|
129 |
-
def is_float(val) -> bool:
|
130 |
-
try:
|
131 |
-
float(val)
|
132 |
-
return True
|
133 |
-
except ValueError:
|
134 |
-
return False
|
135 |
-
|
136 |
-
if model_answer is None:
|
137 |
-
model_answer = "None"
|
138 |
-
|
139 |
-
if is_float(ground_truth):
|
140 |
-
print(f"Evaluating '{model_answer}' as a number.")
|
141 |
-
normalized = normalize_number_str(model_answer)
|
142 |
-
return normalized == float(ground_truth) if normalized is not None else False
|
143 |
-
|
144 |
-
elif any(char in ground_truth for char in [",", ";"]):
|
145 |
-
print(f"Evaluating '{model_answer}' as a comma/semicolon-separated list.")
|
146 |
-
gt_elems = split_string(ground_truth)
|
147 |
-
ma_elems = split_string(model_answer)
|
148 |
-
|
149 |
-
if len(gt_elems) != len(ma_elems):
|
150 |
-
warnings.warn("Answer lists have different lengths, returning False.", UserWarning)
|
151 |
-
return False
|
152 |
-
|
153 |
-
for ma_elem, gt_elem in zip(ma_elems, gt_elems):
|
154 |
-
if is_float(gt_elem):
|
155 |
-
normalized = normalize_number_str(ma_elem)
|
156 |
-
if normalized != float(gt_elem):
|
157 |
-
return False
|
158 |
-
else:
|
159 |
-
if normalize_str(ma_elem, remove_punct=False) != normalize_str(gt_elem, remove_punct=False):
|
160 |
-
return False
|
161 |
-
return True
|
162 |
-
|
163 |
-
else:
|
164 |
-
print(f"Evaluating '{model_answer}' as a string.")
|
165 |
-
return normalize_str(model_answer) == normalize_str(ground_truth)
|
166 |
-
|
167 |
-
# --- Run and Submit All ---
|
168 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
169 |
space_id = os.getenv("SPACE_ID")
|
170 |
if profile:
|
@@ -184,7 +122,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
184 |
return f"Error initializing agent: {e}", None
|
185 |
|
186 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
187 |
-
|
188 |
try:
|
189 |
response = requests.get(questions_url, timeout=15)
|
190 |
response.raise_for_status()
|
@@ -196,45 +133,31 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
196 |
|
197 |
results_log = []
|
198 |
answers_payload = []
|
199 |
-
correct_count = 0
|
200 |
-
total_with_gold = 0
|
201 |
-
|
202 |
for item in questions_data:
|
203 |
task_id = item.get("task_id")
|
204 |
question_text = item.get("question")
|
205 |
-
gold_answer = item.get("
|
206 |
-
|
207 |
if not task_id or question_text is None:
|
208 |
continue
|
209 |
-
|
210 |
try:
|
211 |
submitted_answer = agent(question_text)
|
212 |
-
|
213 |
-
|
214 |
-
if is_correct is not None:
|
215 |
-
total_with_gold += 1
|
216 |
-
if is_correct:
|
217 |
-
correct_count += 1
|
218 |
-
|
219 |
-
answers_payload.append({
|
220 |
-
"task_id": task_id,
|
221 |
-
"submitted_answer": submitted_answer
|
222 |
-
})
|
223 |
|
|
|
224 |
results_log.append({
|
225 |
"Task ID": task_id,
|
226 |
"Question": question_text,
|
227 |
-
"Submitted Answer": submitted_answer,
|
228 |
"Gold Answer": gold_answer,
|
229 |
-
"
|
230 |
})
|
231 |
except Exception as e:
|
232 |
results_log.append({
|
233 |
"Task ID": task_id,
|
234 |
"Question": question_text,
|
235 |
-
"Submitted Answer": f"AGENT ERROR: {e}",
|
236 |
"Gold Answer": gold_answer,
|
237 |
-
"
|
238 |
})
|
239 |
|
240 |
if not answers_payload:
|
@@ -251,22 +174,14 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
251 |
response.raise_for_status()
|
252 |
result_data = response.json()
|
253 |
print(result_data)
|
254 |
-
|
255 |
-
accuracy_text = ""
|
256 |
-
if total_with_gold > 0:
|
257 |
-
accuracy = (correct_count / total_with_gold) * 100
|
258 |
-
accuracy_text = f"\nLocal Accuracy: {accuracy:.2f}% ({correct_count}/{total_with_gold} correct)"
|
259 |
-
|
260 |
final_status = (
|
261 |
f"Submission Successful!\n"
|
262 |
f"User: {result_data.get('username')}\n"
|
263 |
-
f"Overall Score
|
264 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
265 |
f"Message: {result_data.get('message', 'No message received.')}"
|
266 |
-
f"{accuracy_text}"
|
267 |
)
|
268 |
return final_status, pd.DataFrame(results_log)
|
269 |
-
|
270 |
except Exception as e:
|
271 |
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
272 |
|
@@ -285,4 +200,4 @@ with gr.Blocks() as demo:
|
|
285 |
|
286 |
if __name__ == "__main__":
|
287 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
288 |
-
demo.launch(debug=True, share=False)
|
|
|
4 |
import string
|
5 |
import warnings
|
6 |
import pandas as pd
|
|
|
7 |
import re
|
8 |
+
from huggingface_hub import login
|
9 |
from groq import Groq
|
10 |
|
11 |
# --- Constants ---
|
|
|
15 |
class BasicAgent:
|
16 |
def __init__(self):
|
17 |
print("BasicAgent initialized.")
|
18 |
+
self.client = Groq(api_key=os.environ.get("GROQ_API_KEY", ""))
|
19 |
self.agent_prompt = (
|
20 |
"""You are a general AI assistant. I will ask you a question. Report your thoughts, and
|
21 |
finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
|
|
|
74 |
"true": "false", "yes": "no", "black": "white"
|
75 |
}
|
76 |
opposite = opposites.get(word, f"UNKNOWN_OPPOSITE_OF_{word}")
|
77 |
+
return f"FINAL ANSWER: {opposite.upper()}"
|
78 |
return self.format_final_answer("COULD_NOT_SOLVE")
|
79 |
|
80 |
def query_groq(self, question: str) -> str:
|
|
|
85 |
messages=[{"role": "user", "content": full_prompt}]
|
86 |
)
|
87 |
answer = response.choices[0].message.content
|
88 |
+
print(f"[Groq Raw Response]: {answer}")
|
89 |
if "FINAL ANSWER: " in answer:
|
90 |
return answer.split("FINAL ANSWER: ")[-1].strip().upper()
|
91 |
else:
|
|
|
103 |
return self.solve_riddle(question)
|
104 |
return self.query_groq(question)
|
105 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
107 |
space_id = os.getenv("SPACE_ID")
|
108 |
if profile:
|
|
|
122 |
return f"Error initializing agent: {e}", None
|
123 |
|
124 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
|
125 |
try:
|
126 |
response = requests.get(questions_url, timeout=15)
|
127 |
response.raise_for_status()
|
|
|
133 |
|
134 |
results_log = []
|
135 |
answers_payload = []
|
|
|
|
|
|
|
136 |
for item in questions_data:
|
137 |
task_id = item.get("task_id")
|
138 |
question_text = item.get("question")
|
139 |
+
gold_answer = item.get("answer") or item.get("ground_truth")
|
140 |
+
|
141 |
if not task_id or question_text is None:
|
142 |
continue
|
|
|
143 |
try:
|
144 |
submitted_answer = agent(question_text)
|
145 |
+
print(f"Q: {question_text}")
|
146 |
+
print(f"Predicted: {submitted_answer} | Gold: {gold_answer}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
147 |
|
148 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
149 |
results_log.append({
|
150 |
"Task ID": task_id,
|
151 |
"Question": question_text,
|
|
|
152 |
"Gold Answer": gold_answer,
|
153 |
+
"Submitted Answer": submitted_answer
|
154 |
})
|
155 |
except Exception as e:
|
156 |
results_log.append({
|
157 |
"Task ID": task_id,
|
158 |
"Question": question_text,
|
|
|
159 |
"Gold Answer": gold_answer,
|
160 |
+
"Submitted Answer": f"AGENT ERROR: {e}"
|
161 |
})
|
162 |
|
163 |
if not answers_payload:
|
|
|
174 |
response.raise_for_status()
|
175 |
result_data = response.json()
|
176 |
print(result_data)
|
|
|
|
|
|
|
|
|
|
|
|
|
177 |
final_status = (
|
178 |
f"Submission Successful!\n"
|
179 |
f"User: {result_data.get('username')}\n"
|
180 |
+
f"Overall Score: {result_data.get('score', '?')}% "
|
181 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
182 |
f"Message: {result_data.get('message', 'No message received.')}"
|
|
|
183 |
)
|
184 |
return final_status, pd.DataFrame(results_log)
|
|
|
185 |
except Exception as e:
|
186 |
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
187 |
|
|
|
200 |
|
201 |
if __name__ == "__main__":
|
202 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
203 |
+
demo.launch(debug=True, share=False)
|