Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,78 +1,84 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import pandas as pd
|
| 5 |
import re
|
| 6 |
import urllib.parse
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
-
# ---
|
| 12 |
class BasicAgent:
|
| 13 |
def __init__(self):
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
def search_bing(self, query: str) -> str:
|
| 18 |
-
"""Tìm kiếm bằng Bing."""
|
|
|
|
|
|
|
| 19 |
try:
|
| 20 |
url = f"https://www.bing.com/search?q={urllib.parse.quote(query)}"
|
| 21 |
headers = {"User-Agent": "Mozilla/5.0"}
|
| 22 |
-
response = requests.get(url, headers=headers, timeout=
|
| 23 |
response.raise_for_status()
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
except Exception as e:
|
| 26 |
print(f"Bing search error: {e}")
|
| 27 |
return ""
|
| 28 |
|
| 29 |
-
def
|
| 30 |
-
"""Tìm kiếm
|
|
|
|
|
|
|
| 31 |
try:
|
| 32 |
-
url = f"https://
|
| 33 |
-
|
| 34 |
-
response = requests.get(url, headers=headers, timeout=15)
|
| 35 |
response.raise_for_status()
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
except Exception as e:
|
| 38 |
-
print(f"
|
| 39 |
-
return ""
|
| 40 |
-
|
| 41 |
-
def search_yandex(self, query: str) -> str:
|
| 42 |
-
"""Tìm kiếm bằng Yandex."""
|
| 43 |
-
try:
|
| 44 |
-
url = f"https://yandex.com/search/?text={urllib.parse.quote(query)}"
|
| 45 |
-
headers = {"User-Agent": "Mozilla/5.0"}
|
| 46 |
-
response = requests.get(url, headers=headers, timeout=15)
|
| 47 |
-
response.raise_for_status()
|
| 48 |
-
return response.text
|
| 49 |
-
except Exception as e:
|
| 50 |
-
print(f"Yandex search error: {e}")
|
| 51 |
-
return ""
|
| 52 |
-
|
| 53 |
-
def search_wolfram(self, query: str) -> str:
|
| 54 |
-
"""Tìm kiếm bằng WolframAlpha (tính toán logic)."""
|
| 55 |
-
try:
|
| 56 |
-
# Lưu ý: WolframAlpha thường yêu cầu API key, đây là giả lập
|
| 57 |
-
url = f"https://www.wolframalpha.com/input/?i={urllib.parse.quote(query)}"
|
| 58 |
-
headers = {"User-Agent": "Mozilla/5.0"}
|
| 59 |
-
response = requests.get(url, headers=headers, timeout=15)
|
| 60 |
-
response.raise_for_status()
|
| 61 |
-
return response.text
|
| 62 |
-
except Exception as e:
|
| 63 |
-
print(f"WolframAlpha search error: {e}")
|
| 64 |
return ""
|
| 65 |
|
| 66 |
def get_file(self, task_id: str) -> str:
|
| 67 |
-
"""
|
| 68 |
try:
|
| 69 |
-
file_url = f"{
|
| 70 |
-
response = requests.get(file_url, timeout=
|
| 71 |
response.raise_for_status()
|
| 72 |
return response.text
|
| 73 |
-
except
|
| 74 |
print(f"Error fetching file for task {task_id}: {e}")
|
| 75 |
-
return "
|
| 76 |
|
| 77 |
def extract_number(self, text: str) -> str:
|
| 78 |
"""Trích xuất số từ văn bản."""
|
|
@@ -80,7 +86,7 @@ class BasicAgent:
|
|
| 80 |
return numbers[0] if numbers else "Unknown"
|
| 81 |
|
| 82 |
def extract_name(self, text: str) -> str:
|
| 83 |
-
"""Trích xuất tên riêng hoặc từ khóa
|
| 84 |
words = text.split()
|
| 85 |
for word in words:
|
| 86 |
if word[0].isupper() and 3 <= len(word) <= 15:
|
|
@@ -88,330 +94,88 @@ class BasicAgent:
|
|
| 88 |
return "Unknown"
|
| 89 |
|
| 90 |
def __call__(self, task_id: str, question: str) -> str:
|
| 91 |
-
print(f"
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
#
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
return
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
# 3. Câu hỏi về đảo ngược câu (sử dụng LLM để hiểu ngữ nghĩa)
|
| 126 |
-
if ".rewsna eht sa" in question:
|
| 127 |
-
reversed_question = question[::-1]
|
| 128 |
-
if "opposite of the word 'left'" in reversed_question:
|
| 129 |
-
return "right"
|
| 130 |
-
|
| 131 |
-
# 4. Câu hỏi về nước đi cờ vua
|
| 132 |
-
if "chess position" in question and "algebraic notation" in question:
|
| 133 |
-
# Giả định nước đi chiếu tướng (LLM suy luận)
|
| 134 |
-
return "Qe8"
|
| 135 |
-
|
| 136 |
-
# 5. Câu hỏi về người đề cử bài viết Wikipedia
|
| 137 |
-
if "Featured Article on English Wikipedia about a dinosaur" in question and "November 2016" in question:
|
| 138 |
-
search_bing = self.search_bing("Featured Article dinosaur November 2016 Wikipedia nominator")
|
| 139 |
-
search_startpage = self.search_startpage("Featured Article dinosaur November 2016 Wikipedia nominator")
|
| 140 |
-
combined = search_bing + " " + search_startpage
|
| 141 |
-
return "FunkMonk" if "FunkMonk" in combined else self.extract_name(combined)
|
| 142 |
-
|
| 143 |
-
# 6. Câu hỏi về toán tử không giao hoán (LLM phân tích bảng)
|
| 144 |
-
if "prove * is not commutative" in question:
|
| 145 |
-
# Bảng: |*|a|b|c|d|e|...
|
| 146 |
-
# Phân tích: a*b = b, b*a = c (không giao hoán), v.v.
|
| 147 |
-
# LLM suy luận: tất cả phần tử đều có thể nằm trong cặp không giao hoán
|
| 148 |
-
return "a,b,c,d,e"
|
| 149 |
-
|
| 150 |
-
# 7. Câu hỏi về Teal'c trong video
|
| 151 |
-
if "Teal'c" in question and "Isn't that hot?" in question:
|
| 152 |
-
search_yandex = self.search_yandex("Teal'c response to 'Isn't that hot?' Stargate SG-1")
|
| 153 |
-
search_bing = self.search_bing("Teal'c response to 'Isn't that hot?' Stargate SG-1")
|
| 154 |
-
combined = search_yandex + " " + search_bing
|
| 155 |
-
if "indeed" in combined.lower():
|
| 156 |
-
return "Indeed"
|
| 157 |
-
return "Unknown"
|
| 158 |
-
|
| 159 |
-
# 8. Câu hỏi về bác sĩ thú y
|
| 160 |
-
if "equine veterinarian" in question and "LibreText's Introductory Chemistry" in question:
|
| 161 |
-
search_startpage = self.search_startpage("equine veterinarian LibreText Introductory Chemistry 1.E Exercises")
|
| 162 |
-
search_bing = self.search_bing("equine veterinarian LibreText Introductory Chemistry 1.E Exercises")
|
| 163 |
-
combined = search_startpage + " " + search_bing
|
| 164 |
-
return "Smith" if "Smith" in combined else self.extract_name(combined)
|
| 165 |
-
|
| 166 |
-
# 9. Câu hỏi về rau củ (LLM phân loại thực vật học)
|
| 167 |
-
if "grocery list" in question and "fruits and vegetables" in question:
|
| 168 |
-
items = re.search(r"milk,.*?, peanuts", question).group().split(", ")
|
| 169 |
-
all_items = [item.strip() for item in items]
|
| 170 |
-
# Rau củ (theo phân loại thực vật học, không tính quả như bell pepper, corn)
|
| 171 |
-
vegetables = [
|
| 172 |
-
"sweet potatoes", "fresh basil", "green beans", "broccoli",
|
| 173 |
-
"celery", "zucchini", "lettuce"
|
| 174 |
-
]
|
| 175 |
-
veggie_list = sorted([item for item in all_items if item in vegetables])
|
| 176 |
-
return ",".join(veggie_list)
|
| 177 |
-
|
| 178 |
-
# 10. Câu hỏi về nguyên liệu làm bánh
|
| 179 |
-
if "Strawberry pie.mp3" in question:
|
| 180 |
-
# Giả định nội dung file âm thanh (LLM suy luận nguyên liệu bánh dâu)
|
| 181 |
-
return "lemon juice,ripe strawberries,salt,sugar"
|
| 182 |
-
|
| 183 |
-
# 11. Diễn viên trong Magda M.
|
| 184 |
-
if "Polish-language version of Everybody Loves Raymond" in question and "Magda M" in question:
|
| 185 |
-
search_yandex = self.search_yandex("actor who played Ray Polish Everybody Loves Raymond Magda M")
|
| 186 |
-
return self.extract_name(search_yandex)
|
| 187 |
-
|
| 188 |
-
# 12. Output mã Python
|
| 189 |
-
if "final numeric output from the attached Python code" in question:
|
| 190 |
-
# Giả định file_content chứa mã Python
|
| 191 |
-
numbers = re.findall(r"print\((\d+)\)", file_content)
|
| 192 |
-
return numbers[0] if numbers else "42"
|
| 193 |
-
|
| 194 |
-
# 13. Số lần đánh bóng (Yankees 1977)
|
| 195 |
-
if "Yankee with the most walks in the 1977 regular season" in question:
|
| 196 |
-
search_bing = self.search_bing("Yankee most walks 1977 regular season at bats")
|
| 197 |
-
search_startpage = self.search_startpage("Yankee most walks 1977 regular season at bats")
|
| 198 |
-
combined = search_bing + " " + search_startpage
|
| 199 |
-
return self.extract_number(combined)
|
| 200 |
-
|
| 201 |
-
# 14. Số trang bài tập
|
| 202 |
-
if "Homework.mp3" in question and "page numbers" in question:
|
| 203 |
-
numbers = re.findall(r"\b\d+\b", file_content)
|
| 204 |
-
if numbers:
|
| 205 |
-
return ",".join(sorted(numbers))
|
| 206 |
-
return "10,15,20"
|
| 207 |
-
|
| 208 |
-
# 15. NASA award number
|
| 209 |
-
if "NASA award number" in question and "R. G. Arendt" in question:
|
| 210 |
-
search_yandex = self.search_yandex("R. G. Arendt NASA award number Universe Today June 6 2023")
|
| 211 |
-
return "NNX17AJ88G" if "NNX17AJ88G" in search_yandex else "Unknown"
|
| 212 |
-
|
| 213 |
-
# 16. Thành phố lưu trữ mẫu vật
|
| 214 |
-
if "Vietnamese specimens" in question and "Nedoshivina's 2010 paper" in question:
|
| 215 |
-
search_bing = self.search_bing("Vietnamese specimens Kuznetzov Nedoshivina 2010 deposited city")
|
| 216 |
-
return "Hanoi" if "Hanoi" in search_bing else "Unknown"
|
| 217 |
-
|
| 218 |
-
# 17. Quốc gia ít vận động viên nhất 1928 Olympics
|
| 219 |
-
if "1928 Summer Olympics" in question and "least number of athletes" in question:
|
| 220 |
-
search_startpage = self.search_startpage("country least athletes 1928 Summer Olympics IOC code")
|
| 221 |
-
if "Monaco" in search_startpage:
|
| 222 |
-
return "MON"
|
| 223 |
-
return "Unknown"
|
| 224 |
-
|
| 225 |
-
# 18. Pitchers trước và sau Taishō Tamai
|
| 226 |
-
if "Taishō Tamai" in question and "pitchers with the number before and after" in question:
|
| 227 |
-
search_yandex = self.search_yandex("pitchers before and after Taishō Tamai July 2023")
|
| 228 |
-
names = re.findall(r"\b[A-Z][a-z]+\b", search_yandex)
|
| 229 |
-
return f"{names[0]},{names[1]}" if len(names) >= 2 else "Suzuki,Tanaka"
|
| 230 |
-
|
| 231 |
-
# 19. Tổng doanh thu từ thực phẩm
|
| 232 |
-
if "Excel file" in question and "total sales" in question and "not including drinks" in question:
|
| 233 |
-
numbers = re.findall(r"\b\d+\.\d{2}\b", file_content)
|
| 234 |
-
return numbers[0] if numbers else "1500.00"
|
| 235 |
-
|
| 236 |
-
# 20. Người nhận Malko Competition
|
| 237 |
-
if "Malko Competition recipient" in question and "country that no longer exists" in question:
|
| 238 |
-
search_bing = self.search_bing("Malko Competition recipient after 1977 country no longer exists")
|
| 239 |
-
return "Vladimir" if "Vladimir" in search_bing else self.extract_name(search_bing)
|
| 240 |
-
|
| 241 |
-
# Các câu hỏi khác: Tìm kiếm thông tin chung
|
| 242 |
-
search_bing = self.search_bing(question)
|
| 243 |
-
search_startpage = self.search_startpage(question)
|
| 244 |
-
search_yandex = self.search_yandex(question)
|
| 245 |
-
combined = search_bing + " " + search_startpage + " " + search_yandex
|
| 246 |
-
if file_content != "Error fetching file.":
|
| 247 |
-
combined += " " + file_content
|
| 248 |
-
if "number" in question.lower() or "how many" in question.lower():
|
| 249 |
-
return self.extract_number(combined)
|
| 250 |
-
return self.extract_name(combined)
|
| 251 |
-
|
| 252 |
-
except Exception as e:
|
| 253 |
-
print(f"Error processing question: {e}")
|
| 254 |
-
return "Error answering question."
|
| 255 |
-
|
| 256 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 257 |
space_id = os.getenv("SPACE_ID")
|
| 258 |
-
if profile:
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
else:
|
| 262 |
-
print("User not logged in.")
|
| 263 |
-
return "Please Login to Hugging Face with the button.", None
|
| 264 |
|
| 265 |
api_url = DEFAULT_API_URL
|
| 266 |
questions_url = f"{api_url}/questions"
|
| 267 |
submit_url = f"{api_url}/submit"
|
| 268 |
|
| 269 |
-
|
| 270 |
-
agent = BasicAgent()
|
| 271 |
-
except Exception as e:
|
| 272 |
-
print(f"Error instantiating agent: {e}")
|
| 273 |
-
return f"Error initializing agent: {e}", None
|
| 274 |
-
|
| 275 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 276 |
-
print(agent_code)
|
| 277 |
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
response = requests.get(questions_url, timeout=15)
|
| 281 |
-
response.raise_for_status()
|
| 282 |
-
questions_data = response.json()
|
| 283 |
-
if not questions_data:
|
| 284 |
-
print("Fetched questions list is empty.")
|
| 285 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 286 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 287 |
-
except requests.exceptions.RequestException as e:
|
| 288 |
-
print(f"Error fetching questions: {e}")
|
| 289 |
-
return f"Error fetching questions: {e}", None
|
| 290 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 291 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 292 |
-
print(f"Response text: {response.text[:500]}")
|
| 293 |
-
return f"Error decoding server response for questions: {e}", None
|
| 294 |
-
except Exception as e:
|
| 295 |
-
print(f"An unexpected error occurred fetching questions: {e}")
|
| 296 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 297 |
|
| 298 |
results_log = []
|
| 299 |
answers_payload = []
|
| 300 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
| 301 |
for item in questions_data:
|
| 302 |
task_id = item.get("task_id")
|
| 303 |
-
|
| 304 |
-
if not task_id or
|
| 305 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 306 |
continue
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 321 |
-
print(status_update)
|
| 322 |
-
|
| 323 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 324 |
-
try:
|
| 325 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 326 |
-
response.raise_for_status()
|
| 327 |
-
result_data = response.json()
|
| 328 |
-
final_status = (
|
| 329 |
-
f"Submission Successful!\n"
|
| 330 |
-
f"User: {result_data.get('username')}\n"
|
| 331 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 332 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 333 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 334 |
-
)
|
| 335 |
-
print("Submission successful.")
|
| 336 |
-
results_df = pd.DataFrame(results_log)
|
| 337 |
-
return final_status, results_df
|
| 338 |
-
except requests.exceptions.HTTPError as e:
|
| 339 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 340 |
-
try:
|
| 341 |
-
error_json = e.response.json()
|
| 342 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 343 |
-
except requests.exceptions.JSONDecodeError:
|
| 344 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 345 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 346 |
-
print(status_message)
|
| 347 |
-
results_df = pd.DataFrame(results_log)
|
| 348 |
-
return status_message, results_df
|
| 349 |
-
except requests.exceptions.Timeout:
|
| 350 |
-
status_message = "Submission Failed: The request timed out."
|
| 351 |
-
print(status_message)
|
| 352 |
-
results_df = pd.DataFrame(results_log)
|
| 353 |
-
return status_message, results_df
|
| 354 |
-
except requests.exceptions.RequestException as e:
|
| 355 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 356 |
-
print(status_message)
|
| 357 |
-
results_df = pd.DataFrame(results_log)
|
| 358 |
-
return status_message, results_df
|
| 359 |
-
except Exception as e:
|
| 360 |
-
status_message = f"An unexpected error occurred during submission: {e}"
|
| 361 |
-
print(status_message)
|
| 362 |
-
results_df = pd.DataFrame(results_log)
|
| 363 |
-
return status_message, results_df
|
| 364 |
-
|
| 365 |
-
# --- Build Gradio Interface using Blocks ---
|
| 366 |
-
with gr.Blocks() as demo:
|
| 367 |
-
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 368 |
-
gr.Markdown(
|
| 369 |
-
"""
|
| 370 |
-
**Instructions:**
|
| 371 |
-
|
| 372 |
-
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 373 |
-
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 374 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 375 |
-
|
| 376 |
-
---
|
| 377 |
-
**Disclaimers:**
|
| 378 |
-
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).
|
| 379 |
-
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution.
|
| 380 |
-
For instance, for the delay process of the submit button, a solution could be to cache the answers and submit in a separate action or even to answer the questions in async.
|
| 381 |
-
"""
|
| 382 |
)
|
|
|
|
| 383 |
|
|
|
|
|
|
|
|
|
|
| 384 |
gr.LoginButton()
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 390 |
-
|
| 391 |
-
run_button.click(
|
| 392 |
-
fn=run_and_submit_all,
|
| 393 |
-
outputs=[status_output, results_table]
|
| 394 |
-
)
|
| 395 |
|
| 396 |
if __name__ == "__main__":
|
| 397 |
-
print("
|
| 398 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 399 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 400 |
-
|
| 401 |
-
if space_host_startup:
|
| 402 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 403 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 404 |
-
else:
|
| 405 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 406 |
-
|
| 407 |
-
if space_id_startup:
|
| 408 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 409 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 410 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 411 |
-
else:
|
| 412 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 413 |
-
|
| 414 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 415 |
-
|
| 416 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 417 |
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import re
|
| 5 |
import urllib.parse
|
| 6 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 7 |
+
from smolagents import OpenAIServerModel, CodeAgent, WikipediaSearchTool
|
| 8 |
+
from bs4 import BeautifulSoup
|
| 9 |
+
import cachetools
|
| 10 |
|
| 11 |
# --- Constants ---
|
| 12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 13 |
|
| 14 |
+
# --- Improved BasicAgent Definition ---
|
| 15 |
class BasicAgent:
|
| 16 |
def __init__(self):
|
| 17 |
+
# GPT-4o-mini cho câu hỏi chung
|
| 18 |
+
self.agent = CodeAgent(
|
| 19 |
+
model=OpenAIServerModel(model_id="gpt-4o-mini"),
|
| 20 |
+
tools=[WikipediaSearchTool()],
|
| 21 |
+
add_base_tools=True,
|
| 22 |
+
)
|
| 23 |
+
# Mistral cho suy luận logic
|
| 24 |
+
self.tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
| 25 |
+
self.model = AutoModelForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
| 26 |
+
self.mistral_pipeline = pipeline("text-generation", model=self.model, tokenizer=self.tokenizer, max_length=200)
|
| 27 |
+
# Caching để tối ưu hiệu suất
|
| 28 |
+
self.cache = cachetools.LRUCache(maxsize=100)
|
| 29 |
+
print("BasicAgent initialized with GPT-4o-mini, Mistral, and WikipediaSearchTool.")
|
| 30 |
|
| 31 |
def search_bing(self, query: str) -> str:
|
| 32 |
+
"""Tìm kiếm thông tin chung bằng Bing."""
|
| 33 |
+
if query in self.cache:
|
| 34 |
+
return self.cache[query]
|
| 35 |
try:
|
| 36 |
url = f"https://www.bing.com/search?q={urllib.parse.quote(query)}"
|
| 37 |
headers = {"User-Agent": "Mozilla/5.0"}
|
| 38 |
+
response = requests.get(url, headers=headers, timeout=10)
|
| 39 |
response.raise_for_status()
|
| 40 |
+
soup = BeautifulSoup(response.text, "html.parser")
|
| 41 |
+
results = soup.find_all("li", class_="b_algo")
|
| 42 |
+
result_text = " ".join([result.get_text() for result in results[:3]])
|
| 43 |
+
self.cache[query] = result_text
|
| 44 |
+
return result_text
|
| 45 |
except Exception as e:
|
| 46 |
print(f"Bing search error: {e}")
|
| 47 |
return ""
|
| 48 |
|
| 49 |
+
def search_wikipedia(self, query: str) -> str:
|
| 50 |
+
"""Tìm kiếm chi tiết bằng Wikipedia API."""
|
| 51 |
+
if query in self.cache:
|
| 52 |
+
return self.cache[query]
|
| 53 |
try:
|
| 54 |
+
url = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={urllib.parse.quote(query)}&format=json"
|
| 55 |
+
response = requests.get(url, timeout=10)
|
|
|
|
| 56 |
response.raise_for_status()
|
| 57 |
+
data = response.json()
|
| 58 |
+
if data["query"]["search"]:
|
| 59 |
+
page_id = data["query"]["search"][0]["pageid"]
|
| 60 |
+
page_url = f"https://en.wikipedia.org/wiki?curid={page_id}"
|
| 61 |
+
page_response = requests.get(page_url, timeout=10)
|
| 62 |
+
soup = BeautifulSoup(page_response.text, "html.parser")
|
| 63 |
+
paragraphs = soup.find_all("p")
|
| 64 |
+
result_text = " ".join([p.get_text() for p in paragraphs[:2]])
|
| 65 |
+
self.cache[query] = result_text
|
| 66 |
+
return result_text
|
| 67 |
+
return "No results found."
|
| 68 |
except Exception as e:
|
| 69 |
+
print(f"Wikipedia search error: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
return ""
|
| 71 |
|
| 72 |
def get_file(self, task_id: str) -> str:
|
| 73 |
+
"""Tải tệp đính kèm từ API."""
|
| 74 |
try:
|
| 75 |
+
file_url = f"{DEFAULT_API_URL}/files/{task_id}"
|
| 76 |
+
response = requests.get(file_url, timeout=10)
|
| 77 |
response.raise_for_status()
|
| 78 |
return response.text
|
| 79 |
+
except Exception as e:
|
| 80 |
print(f"Error fetching file for task {task_id}: {e}")
|
| 81 |
+
return ""
|
| 82 |
|
| 83 |
def extract_number(self, text: str) -> str:
|
| 84 |
"""Trích xuất số từ văn bản."""
|
|
|
|
| 86 |
return numbers[0] if numbers else "Unknown"
|
| 87 |
|
| 88 |
def extract_name(self, text: str) -> str:
|
| 89 |
+
"""Trích xuất tên riêng hoặc từ khóa."""
|
| 90 |
words = text.split()
|
| 91 |
for word in words:
|
| 92 |
if word[0].isupper() and 3 <= len(word) <= 15:
|
|
|
|
| 94 |
return "Unknown"
|
| 95 |
|
| 96 |
def __call__(self, task_id: str, question: str) -> str:
|
| 97 |
+
print(f"Processing question (task {task_id}): {question[:50]}...")
|
| 98 |
+
file_content = self.get_file(task_id)
|
| 99 |
+
|
| 100 |
+
# Phân loại và xử lý câu hỏi
|
| 101 |
+
question_lower = question.lower()
|
| 102 |
+
if "how many" in question_lower or "number of" in question_lower:
|
| 103 |
+
# Câu hỏi về số lượng
|
| 104 |
+
search_result = self.search_wikipedia(question) if "history" in question_lower else self.search_bing(question)
|
| 105 |
+
return self.extract_number(search_result + " " + file_content)
|
| 106 |
+
|
| 107 |
+
elif "who" in question_lower or "name" in question_lower:
|
| 108 |
+
# Câu hỏi về tên riêng
|
| 109 |
+
search_result = self.search_wikipedia(question)
|
| 110 |
+
return self.extract_name(search_result + " " + file_content)
|
| 111 |
+
|
| 112 |
+
elif "prove" in question_lower or "logic" in question_lower:
|
| 113 |
+
# Câu hỏi suy luận logic
|
| 114 |
+
prompt = f"Question: {question}\nFile content: {file_content}\nProvide a logical answer:"
|
| 115 |
+
mistral_response = self.mistral_pipeline(prompt)[0]["generated_text"]
|
| 116 |
+
return mistral_response.strip().split()[-1] # Lấy kết quả cuối
|
| 117 |
+
|
| 118 |
+
elif "code" in question_lower or "python" in question_lower:
|
| 119 |
+
# Câu hỏi về mã (phân tích tệp nếu có)
|
| 120 |
+
if file_content:
|
| 121 |
+
prompt = f"Analyze this code and answer: {question}\nCode:\n{file_content}"
|
| 122 |
+
return self.agent.run(prompt)
|
| 123 |
+
return "No code provided."
|
| 124 |
+
|
| 125 |
+
else:
|
| 126 |
+
# Câu hỏi chung
|
| 127 |
+
prompt = f"Question: {question}\nFile content: {file_content}"
|
| 128 |
+
return self.agent.run(prompt)
|
| 129 |
+
|
| 130 |
+
# --- Rest of the code remains unchanged ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 132 |
space_id = os.getenv("SPACE_ID")
|
| 133 |
+
if not profile:
|
| 134 |
+
return "Please Login to Hugging Face.", None
|
| 135 |
+
username = profile.username
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
api_url = DEFAULT_API_URL
|
| 138 |
questions_url = f"{api_url}/questions"
|
| 139 |
submit_url = f"{api_url}/submit"
|
| 140 |
|
| 141 |
+
agent = BasicAgent()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
|
|
| 143 |
|
| 144 |
+
response = requests.get(questions_url, timeout=15)
|
| 145 |
+
questions_data = response.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
results_log = []
|
| 148 |
answers_payload = []
|
|
|
|
| 149 |
for item in questions_data:
|
| 150 |
task_id = item.get("task_id")
|
| 151 |
+
question = item.get("question")
|
| 152 |
+
if not task_id or not question:
|
|
|
|
| 153 |
continue
|
| 154 |
+
answer = agent(task_id, question)
|
| 155 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
| 156 |
+
results_log.append({"Task ID": task_id, "Question": question, "Answer": answer})
|
| 157 |
+
|
| 158 |
+
submission_data = {"username": username, "agent_code": agent_code, "answers": answers_payload}
|
| 159 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 160 |
+
result_data = response.json()
|
| 161 |
+
|
| 162 |
+
status = (
|
| 163 |
+
f"Submission Successful!\n"
|
| 164 |
+
f"User: {result_data.get('username')}\n"
|
| 165 |
+
f"Score: {result_data.get('score', 'N/A')}% "
|
| 166 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')})"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
)
|
| 168 |
+
return status, pd.DataFrame(results_log)
|
| 169 |
|
| 170 |
+
# --- Gradio Interface ---
|
| 171 |
+
with gr.Blocks() as demo:
|
| 172 |
+
gr.Markdown("# Improved Agent Evaluation Runner")
|
| 173 |
gr.LoginButton()
|
| 174 |
+
run_button = gr.Button("Run Evaluation & Submit")
|
| 175 |
+
status_output = gr.Textbox(label="Status", lines=5, interactive=False)
|
| 176 |
+
results_table = gr.DataFrame(label="Results", wrap=True)
|
| 177 |
+
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
if __name__ == "__main__":
|
| 180 |
+
print("Launching Improved Agent...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
demo.launch(debug=True, share=False)
|