File size: 22,536 Bytes
f04b8a4 10e9b7d eccf8e4 3c4371f 10e9b7d f04b8a4 3db6293 e80aab9 f04b8a4 31243f4 f04b8a4 31243f4 f04b8a4 31243f4 4021bf3 f04b8a4 31243f4 f04b8a4 31243f4 f04b8a4 3c4371f 7e4a06b f04b8a4 7e4a06b f04b8a4 3c4371f 7e4a06b f04b8a4 31243f4 f04b8a4 31243f4 e80aab9 f04b8a4 31243f4 f04b8a4 31243f4 f04b8a4 31243f4 f04b8a4 eccf8e4 f04b8a4 7d65c66 f04b8a4 31243f4 f04b8a4 31243f4 f04b8a4 e80aab9 f04b8a4 7d65c66 e80aab9 f04b8a4 7d65c66 f04b8a4 7d65c66 f04b8a4 31243f4 f04b8a4 31243f4 f04b8a4 31243f4 f04b8a4 31243f4 f04b8a4 31243f4 e80aab9 f04b8a4 e80aab9 f04b8a4 e80aab9 f04b8a4 e80aab9 f04b8a4 31243f4 f04b8a4 e80aab9 f04b8a4 e80aab9 f04b8a4 e80aab9 f04b8a4 31243f4 f04b8a4 3c4371f f04b8a4 3c4371f f04b8a4 e80aab9 f04b8a4 31243f4 f04b8a4 7d65c66 f04b8a4 31243f4 e80aab9 f04b8a4 e80aab9 f04b8a4 0ee0419 e514fd7 f04b8a4 e514fd7 f04b8a4 e514fd7 f04b8a4 e514fd7 e80aab9 f04b8a4 7e4a06b e80aab9 f04b8a4 e80aab9 31243f4 f04b8a4 e80aab9 f04b8a4 e80aab9 f04b8a4 7d65c66 3c4371f f04b8a4 3c4371f 7d65c66 f04b8a4 7d65c66 f04b8a4 3c4371f f04b8a4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 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 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 | # ============================================================
# HUGGING FACE AGENTS COURSE - UNIT 4
# GENERAL PURPOSE GAIA AGENT
# ============================================================
import os
import gradio as gr
import requests
import pandas as pd
from smolagents import (
CodeAgent,
InferenceClientModel,
DuckDuckGoSearchTool,
VisitWebpageTool,
WikipediaSearchTool,
PythonInterpreterTool,
)
# ============================================================
# CONSTANTS
# ============================================================
# IMPORTANT:
# DO NOT CHANGE THIS URL.
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
# ============================================================
# GENERAL PURPOSE GAIA AGENT
# ============================================================
class BasicAgent:
def __init__(self):
print("=" * 60)
print("Initializing General Purpose GAIA Agent...")
print("=" * 60)
# ----------------------------------------------------
# Hugging Face token
# ----------------------------------------------------
hf_token = os.getenv("HF_TOKEN")
if not hf_token:
raise RuntimeError(
"HF_TOKEN is missing.\n"
"Go to Space Settings -> Secrets and create:\n"
"Name: HF_TOKEN\n"
"Value: Your Hugging Face token"
)
# ----------------------------------------------------
# MODEL
# ----------------------------------------------------
self.model = InferenceClientModel(
model_id="Qwen/Qwen3-Next-80B-A3B-Thinking",
token=hf_token,
temperature=0.1,
max_tokens=3000,
)
# ----------------------------------------------------
# WEB SEARCH TOOL
# ----------------------------------------------------
self.search_tool = DuckDuckGoSearchTool(
max_results=8,
rate_limit=1.0
)
# ----------------------------------------------------
# WEBPAGE TOOL
# ----------------------------------------------------
self.webpage_tool = VisitWebpageTool(
max_output_length=40000
)
# ----------------------------------------------------
# WIKIPEDIA TOOL
# ----------------------------------------------------
self.wikipedia_tool = WikipediaSearchTool(
user_agent="StructuralGPT-GAIA-Agent/1.0",
language="en",
content_type="text",
extract_format="WIKI"
)
# ----------------------------------------------------
# PYTHON / CALCULATION TOOL
# ----------------------------------------------------
self.python_tool = PythonInterpreterTool(
authorized_imports=[
"math",
"statistics",
"datetime",
"json",
"re",
"decimal"
],
timeout_seconds=30
)
# ----------------------------------------------------
# SYSTEM INSTRUCTIONS
# ----------------------------------------------------
self.instructions = """
You are a highly capable general-purpose AI agent designed
to solve GAIA benchmark questions.
Your objective is to provide the CORRECT answer to the
user's question.
IMPORTANT RULES
===============
1. READ THE COMPLETE QUESTION CAREFULLY.
2. Determine exactly what the question is asking.
3. Use tools whenever they are useful.
4. Use web search for:
- current information
- factual information
- obscure information
- information that should be verified
- people, companies, events, dates, statistics, etc.
5. Use the webpage tool when the question provides a URL
or when you need the contents of a webpage.
6. Use Wikipedia search when the question specifically
refers to Wikipedia or historical/general information.
7. Use Python for:
- arithmetic
- percentages
- dates
- counting
- comparisons
- numerical reasoning
- data processing
8. NEVER guess a numerical answer when you can calculate it.
9. When a question contains several steps:
solve every required step before giving the answer.
10. Verify important facts whenever possible.
11. Do not invent information.
12. Pay close attention to:
- exact dates
- names
- numbers
- units
- percentages
- spelling
- requested formats
13. If the question asks:
"How many?"
return the number.
14. If it asks:
"Who?"
return the person's name.
15. If it asks:
"When?"
return the date/year.
16. If it asks for a calculation,
calculate it using Python.
17. If the question asks for a specific list,
provide exactly the requested list.
18. If the question contains a URL,
investigate the URL rather than guessing.
19. Do not include citations unless the question asks for them.
20. Do not say "FINAL ANSWER".
21. Do not write:
"Here is the answer:"
"The answer is:"
or unnecessary explanations.
22. The final response must contain ONLY the answer
required by the question.
23. The GAIA evaluator uses exact matching, so be precise
and concise.
24. Think through the problem carefully before producing
the final response.
25. NEVER intentionally return a generic response.
SPECIAL CASES
=============
For calculations:
- Use Python.
- Verify the result.
- Give the exact required number.
For web research:
- Search using precise keywords.
- Open useful results.
- Compare information when needed.
For Wikipedia questions:
- Use Wikipedia search.
- Pay attention to the requested Wikipedia version/date.
For questions involving a webpage:
- Visit the webpage.
- Extract the relevant information.
- Answer only what is requested.
For civil/structural engineering questions:
- You may use engineering knowledge.
- Use Indian Standards when appropriate.
- Keep the final answer focused on what was requested.
FINAL RESPONSE
==============
Return ONLY the concise answer.
"""
# ----------------------------------------------------
# CREATE AGENT
# ----------------------------------------------------
self.agent = CodeAgent(
model=self.model,
tools=[
self.search_tool,
self.webpage_tool,
self.wikipedia_tool,
self.python_tool,
],
max_steps=12,
instructions=self.instructions,
add_base_tools=True
)
print("GAIA Agent initialized successfully.")
print("=" * 60)
# ========================================================
# AGENT CALL
# ========================================================
def __call__(self, question: str) -> str:
print("\n")
print("=" * 70)
print("NEW GAIA QUESTION")
print("=" * 70)
print(question)
print("=" * 70)
try:
result = self.agent.run(question)
answer = str(result).strip()
# ------------------------------------------------
# Remove accidental answer labels
# ------------------------------------------------
unwanted_prefixes = [
"FINAL ANSWER:",
"FINAL ANSWER",
"Answer:",
"ANSWER:",
"The answer is:",
"The answer is"
]
for prefix in unwanted_prefixes:
if answer.lower().startswith(prefix.lower()):
answer = answer[len(prefix):].strip()
print("\nAGENT ANSWER:")
print(answer)
print("=" * 70)
return answer
except Exception as e:
print("\nAGENT ERROR:")
print(str(e))
print("=" * 70)
return f"Agent execution error: {e}"
# ============================================================
# RUN AND SUBMIT ALL QUESTIONS
# ============================================================
def run_and_submit_all(profile: gr.OAuthProfile | None):
"""
Fetches all GAIA questions,
runs the General Purpose Agent,
submits all answers,
and displays the results.
"""
# --------------------------------------------------------
# 1. CHECK HUGGING FACE LOGIN
# --------------------------------------------------------
if profile:
username = profile.username
print(
f"User logged in: {username}"
)
else:
print("User is not logged in.")
return (
"Please Login to Hugging Face with the button.",
None
)
# --------------------------------------------------------
# 2. SCORING API URLS
# --------------------------------------------------------
api_url = DEFAULT_API_URL
questions_url = f"{api_url}/questions"
submit_url = f"{api_url}/submit"
# --------------------------------------------------------
# 3. GET SPACE CODE URL
# --------------------------------------------------------
space_id = os.getenv("SPACE_ID")
if not space_id:
print(
"WARNING: SPACE_ID was not found."
)
agent_code = "SPACE_ID_NOT_FOUND"
else:
agent_code = (
f"https://huggingface.co/spaces/"
f"{space_id}/tree/main"
)
print(
f"Agent code URL: {agent_code}"
)
# --------------------------------------------------------
# 4. CREATE AGENT
# --------------------------------------------------------
try:
agent = BasicAgent()
except Exception as e:
print(
f"Error initializing agent: {e}"
)
return (
f"Error initializing agent: {e}",
None
)
# --------------------------------------------------------
# 5. FETCH QUESTIONS
# --------------------------------------------------------
print("\n")
print("=" * 70)
print("FETCHING GAIA QUESTIONS")
print("=" * 70)
try:
response = requests.get(
questions_url,
timeout=30
)
response.raise_for_status()
questions_data = response.json()
if not questions_data:
print("Questions list is empty.")
return (
"Fetched questions list is empty.",
None
)
print(
f"Fetched {len(questions_data)} questions."
)
except requests.exceptions.RequestException as e:
print(
f"Error fetching questions: {e}"
)
return (
f"Error fetching questions: {e}",
None
)
except ValueError as e:
print(
f"Invalid JSON response: {e}"
)
return (
f"Invalid JSON response: {e}",
None
)
except Exception as e:
print(
f"Unexpected error fetching questions: {e}"
)
return (
f"Unexpected error fetching questions: {e}",
None
)
# --------------------------------------------------------
# 6. RUN AGENT ON EVERY QUESTION
# --------------------------------------------------------
results_log = []
answers_payload = []
total_questions = len(questions_data)
print("\n")
print("=" * 70)
print("RUNNING GENERAL PURPOSE AGENT")
print("=" * 70)
for number, item in enumerate(
questions_data,
start=1
):
task_id = item.get(
"task_id"
)
question_text = item.get(
"question"
)
# ----------------------------------------------------
# Validate question
# ----------------------------------------------------
if not task_id:
print(
f"Skipping question {number}: "
"missing task_id."
)
continue
if question_text is None:
print(
f"Skipping question {number}: "
"missing question text."
)
continue
print("\n")
print(
f"QUESTION {number}/{total_questions}"
)
print(
f"TASK ID: {task_id}"
)
# ----------------------------------------------------
# Run agent
# ----------------------------------------------------
try:
submitted_answer = agent(
question_text
)
answers_payload.append(
{
"task_id": task_id,
"submitted_answer": submitted_answer
}
)
results_log.append(
{
"Task ID": task_id,
"Question": question_text,
"Submitted Answer":
submitted_answer
}
)
except Exception as e:
error_message = (
f"AGENT ERROR: {e}"
)
print(error_message)
results_log.append(
{
"Task ID": task_id,
"Question": question_text,
"Submitted Answer":
error_message
}
)
# --------------------------------------------------------
# 7. CHECK ANSWERS
# --------------------------------------------------------
if not answers_payload:
print(
"Agent did not produce any answers."
)
return (
"Agent did not produce any answers.",
pd.DataFrame(results_log)
)
print("\n")
print("=" * 70)
print(
f"Agent produced {len(answers_payload)} "
f"answers."
)
print("=" * 70)
# --------------------------------------------------------
# 8. PREPARE SUBMISSION
# --------------------------------------------------------
submission_data = {
"username":
username.strip(),
"agent_code":
agent_code,
"answers":
answers_payload
}
status_update = (
f"Agent finished.\n"
f"Submitting {len(answers_payload)} answers "
f"for user '{username}'..."
)
print(status_update)
# --------------------------------------------------------
# 9. SUBMIT ANSWERS
# --------------------------------------------------------
print("\n")
print("=" * 70)
print("SUBMITTING TO GAIA SCORING SERVER")
print("=" * 70)
try:
response = requests.post(
submit_url,
json=submission_data,
timeout=120
)
response.raise_for_status()
result_data = response.json()
# ----------------------------------------------------
# SCORE
# ----------------------------------------------------
score = result_data.get(
"score",
"N/A"
)
correct_count = result_data.get(
"correct_count",
"?"
)
total_attempted = result_data.get(
"total_attempted",
"?"
)
message = result_data.get(
"message",
"No message received."
)
final_status = (
"Submission Successful!\n\n"
f"User: "
f"{result_data.get('username', username)}\n"
f"Overall Score: "
f"{score}%\n"
f"Correct: "
f"{correct_count}/"
f"{total_attempted}\n\n"
f"Message: "
f"{message}"
)
print(final_status)
results_df = pd.DataFrame(
results_log
)
return (
final_status,
results_df
)
# --------------------------------------------------------
# HTTP ERROR
# --------------------------------------------------------
except requests.exceptions.HTTPError as e:
error_detail = (
f"Server responded with "
f"status {e.response.status_code}."
)
try:
error_json = e.response.json()
error_detail += (
f" Detail: "
f"{error_json.get('detail', '')}"
)
except Exception:
error_detail += (
f" Response: "
f"{e.response.text[:500]}"
)
status_message = (
f"Submission Failed: "
f"{error_detail}"
)
print(status_message)
return (
status_message,
pd.DataFrame(results_log)
)
# --------------------------------------------------------
# TIMEOUT
# --------------------------------------------------------
except requests.exceptions.Timeout:
status_message = (
"Submission Failed: "
"The request timed out."
)
print(status_message)
return (
status_message,
pd.DataFrame(results_log)
)
# --------------------------------------------------------
# NETWORK ERROR
# --------------------------------------------------------
except requests.exceptions.RequestException as e:
status_message = (
f"Submission Failed: "
f"Network error - {e}"
)
print(status_message)
return (
status_message,
pd.DataFrame(results_log)
)
# --------------------------------------------------------
# OTHER ERROR
# --------------------------------------------------------
except Exception as e:
status_message = (
f"Unexpected error during submission: "
f"{e}"
)
print(status_message)
return (
status_message,
pd.DataFrame(results_log)
)
# ============================================================
# GRADIO INTERFACE
# ============================================================
with gr.Blocks() as demo:
gr.Markdown(
"""
# 🤖 General Purpose GAIA Agent
This agent uses:
- Qwen through Hugging Face
- Web Search
- Webpage retrieval
- Wikipedia
- Python calculations
- Multi-step reasoning
It is designed for the Hugging Face Agents Course
Unit 4 GAIA evaluation.
"""
)
gr.Markdown(
"""
### Instructions
1. Log in to your Hugging Face account.
2. Make sure `HF_TOKEN` is configured as a Space Secret.
3. Click **Run Evaluation & Submit All Answers**.
4. Wait while the agent processes all questions.
5. Your score will appear below.
**Important:** The evaluation can take several minutes
because the agent processes each question individually.
"""
)
# --------------------------------------------------------
# LOGIN
# --------------------------------------------------------
gr.LoginButton()
# --------------------------------------------------------
# RUN BUTTON
# --------------------------------------------------------
run_button = gr.Button(
"Run Evaluation & Submit All Answers",
variant="primary"
)
# --------------------------------------------------------
# STATUS
# --------------------------------------------------------
status_output = gr.Textbox(
label="Run Status / Submission Result",
lines=8,
interactive=False
)
# --------------------------------------------------------
# RESULTS
# --------------------------------------------------------
results_table = gr.DataFrame(
label="Questions and Agent Answers",
wrap=True
)
# --------------------------------------------------------
# BUTTON ACTION
# --------------------------------------------------------
run_button.click(
fn=run_and_submit_all,
outputs=[
status_output,
results_table
]
)
# ============================================================
# START APPLICATION
# ============================================================
if __name__ == "__main__":
print(
"\n" +
"-" * 30 +
" App Starting " +
"-" * 30
)
# --------------------------------------------------------
# SPACE INFORMATION
# --------------------------------------------------------
space_host_startup = os.getenv(
"SPACE_HOST"
)
space_id_startup = os.getenv(
"SPACE_ID"
)
# --------------------------------------------------------
# SPACE HOST
# --------------------------------------------------------
if space_host_startup:
print(
f"SPACE_HOST found: "
f"{space_host_startup}"
)
print(
"Runtime URL:"
)
print(
f"https://{space_host_startup}.hf.space"
)
else:
print(
"SPACE_HOST not found."
)
# --------------------------------------------------------
# SPACE ID
# --------------------------------------------------------
if space_id_startup:
print(
f"SPACE_ID found: "
f"{space_id_startup}"
)
print(
"Repository URL:"
)
print(
f"https://huggingface.co/spaces/"
f"{space_id_startup}"
)
print(
"Code URL:"
)
print(
f"https://huggingface.co/spaces/"
f"{space_id_startup}/tree/main"
)
else:
print(
"SPACE_ID not found."
)
print(
"\nLaunching General Purpose GAIA Agent..."
)
# --------------------------------------------------------
# LAUNCH
# --------------------------------------------------------
demo.launch(
debug=True,
share=False
) |