File size: 13,676 Bytes
63e18a9 10e9b7d eccf8e4 3c4371f 10e9b7d 63e18a9 e80aab9 31243f4 63e18a9 31243f4 63e18a9 31243f4 4021bf3 63e18a9 31243f4 63e18a9 31243f4 63e18a9 3c4371f 7e4a06b 63e18a9 3c4371f 63e18a9 7e4a06b 63e18a9 3c4371f 63e18a9 3c4371f 7e4a06b 63e18a9 31243f4 63e18a9 31243f4 e80aab9 63e18a9 31243f4 63e18a9 31243f4 63e18a9 31243f4 3c4371f 63e18a9 eccf8e4 63e18a9 7d65c66 63e18a9 31243f4 63e18a9 31243f4 63e18a9 7d65c66 e80aab9 63e18a9 7d65c66 63e18a9 7d65c66 63e18a9 31243f4 63e18a9 31243f4 63e18a9 31243f4 63e18a9 31243f4 63e18a9 31243f4 63e18a9 31243f4 63e18a9 31243f4 63e18a9 31243f4 e80aab9 63e18a9 e80aab9 63e18a9 e80aab9 63e18a9 e80aab9 63e18a9 31243f4 63e18a9 e80aab9 63e18a9 e80aab9 63e18a9 e80aab9 63e18a9 3c4371f 63e18a9 e80aab9 63e18a9 7d65c66 63e18a9 e80aab9 63e18a9 e80aab9 63e18a9 0ee0419 63e18a9 e514fd7 63e18a9 e514fd7 63e18a9 e514fd7 e80aab9 7e4a06b e80aab9 63e18a9 e80aab9 31243f4 63e18a9 e80aab9 63e18a9 e80aab9 7d65c66 63e18a9 7d65c66 3c4371f 63e18a9 | 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 | # ============================================================
# INSTALL REQUIRED LIBRARIES
# ============================================================
import subprocess
import sys
subprocess.check_call([
sys.executable, "-m", "pip", "install", "-q",
"smolagents[toolkit]",
"gradio",
"requests",
"pandas"
])
# ============================================================
# IMPORT LIBRARIES
# ============================================================
import os
import gradio as gr
import requests
import pandas as pd
from smolagents import (
CodeAgent,
InferenceClientModel,
DuckDuckGoSearchTool,
PythonInterpreterTool
)
# ============================================================
# CONSTANTS
# ============================================================
DEFAULT_API_URL = "https://huggingface.co/Shrutipanchal086/structrural_AI_agent"
# ============================================================
# STRUCTURALGPT / GAIA AGENT
# ============================================================
class BasicAgent:
def __init__(self):
print("Initializing StructuralGPT GAIA Agent...")
# ----------------------------------------------------
# Hugging Face token
# Add HF_TOKEN in Space Settings -> Secrets
# ----------------------------------------------------
hf_token = os.getenv("hf_token")
if not hf_token:
raise ValueError(
"HF_TOKEN not found. "
"Please add HF_TOKEN in Space Settings -> Secrets."
)
# ----------------------------------------------------
# Hugging Face model
# ----------------------------------------------------
self.model = InferenceClientModel(
model_id="Qwen/Qwen3-Next-80B-A3B-Thinking",
token=hf_token,
max_tokens=3000
)
# ----------------------------------------------------
# Web search
# ----------------------------------------------------
self.search_tool = DuckDuckGoSearchTool(
max_results=8
)
# ----------------------------------------------------
# Python calculator / reasoning tool
# ----------------------------------------------------
self.python_tool = PythonInterpreterTool(
authorized_imports=[
"math",
"statistics",
"datetime",
"json",
"re"
]
)
# ----------------------------------------------------
# Agent
# ----------------------------------------------------
self.agent = CodeAgent(
model=self.model,
tools=[
self.search_tool,
self.python_tool
],
max_steps=10
)
print("StructuralGPT GAIA Agent initialized successfully.")
def __call__(self, question: str) -> str:
print("\n" + "=" * 60)
print("QUESTION:")
print(question)
print("=" * 60)
prompt = f"""
You are a powerful general-purpose AI agent participating
in the GAIA benchmark.
Your job is to solve the user's question accurately.
IMPORTANT RULES:
1. Understand the question completely before answering.
2. If the question requires current, factual, or external
information, use the web search tool.
3. If calculations are required, use the Python tool.
Do not rely on mental arithmetic for complicated calculations.
4. Break difficult problems into smaller steps.
5. Verify important calculations and facts before producing
the final answer.
6. If multiple pieces of information are required, collect
all necessary information before answering.
7. Do not invent facts, sources, numbers, or results.
8. Give ONLY the final answer required by the question.
Do not unnecessarily explain your internal reasoning.
9. Pay very close attention to:
- units
- dates
- names
- numerical values
- percentages
- requested formats
10. If the question asks for a specific format, follow that
format exactly.
You are also knowledgeable in civil and structural engineering,
including RCC design, steel design, structural analysis,
foundation engineering, transportation engineering,
water resources engineering, and construction management.
For engineering questions, use Indian Standards when relevant,
including IS 456, IS 875, IS 1893, IS 800 and IS 13920.
USER QUESTION:
{question}
"""
try:
result = self.agent.run(prompt)
answer = str(result).strip()
print("\nFINAL ANSWER:")
print(answer)
return answer
except Exception as e:
print("Agent error:", e)
return f"Unable to solve the question because of an agent error: {e}"
# ============================================================
# RUN AND SUBMIT ALL
# ============================================================
def run_and_submit_all(profile: gr.OAuthProfile | None):
"""
Fetch all GAIA questions,
run the agent,
submit answers,
and display results.
"""
# --------------------------------------------------------
# Check login
# --------------------------------------------------------
if profile:
username = profile.username
print(f"User logged in: {username}")
else:
print("User not logged in.")
return (
"Please login to Hugging Face using the Login button.",
None
)
# --------------------------------------------------------
# API URLs
# --------------------------------------------------------
api_url = DEFAULT_API_URL
questions_url = f"{api_url}/questions"
submit_url = f"{api_url}/submit"
# --------------------------------------------------------
# Space information
# --------------------------------------------------------
space_id = os.getenv("SPACE_ID")
if space_id:
agent_code = (
f"https://huggingface.co/spaces/"
f"{space_id}/tree/main"
)
else:
agent_code = "Local/Unknown-Space"
print("Agent code URL:")
print(agent_code)
# ========================================================
# 1. CREATE AGENT
# ========================================================
try:
agent = BasicAgent()
except Exception as e:
print("Error creating agent:", e)
return (
f"Error initializing agent: {e}",
None
)
# ========================================================
# 2. FETCH QUESTIONS
# ========================================================
print("\nFetching GAIA questions...")
try:
response = requests.get(
questions_url,
timeout=30
)
response.raise_for_status()
questions_data = response.json()
if not questions_data:
return (
"No questions were received.",
None
)
print(
f"Fetched {len(questions_data)} questions."
)
except Exception as e:
print("Error fetching questions:", e)
return (
f"Error fetching questions: {e}",
None
)
# ========================================================
# 3. RUN AGENT
# ========================================================
results_log = []
answers_payload = []
print("\nRunning agent...")
for number, item in enumerate(
questions_data,
start=1
):
task_id = item.get("task_id")
question_text = item.get("question")
if not task_id or question_text is None:
print(
"Skipping invalid question:",
item
)
continue
print(
f"\nProcessing question "
f"{number}/{len(questions_data)}"
)
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:
print(
f"Agent error on task {task_id}: {e}"
)
results_log.append(
{
"Task ID": task_id,
"Question": question_text,
"Submitted Answer":
f"AGENT ERROR: {e}"
}
)
# ========================================================
# 4. CHECK ANSWERS
# ========================================================
if not answers_payload:
return (
"Agent did not produce any answers.",
pd.DataFrame(results_log)
)
# ========================================================
# 5. PREPARE SUBMISSION
# ========================================================
submission_data = {
"username":
username.strip(),
"agent_code":
agent_code,
"answers":
answers_payload
}
status_update = (
f"Agent finished. "
f"Submitting {len(answers_payload)} answers..."
)
print(status_update)
# ========================================================
# 6. SUBMIT TO GAIA
# ========================================================
try:
response = requests.post(
submit_url,
json=submission_data,
timeout=120
)
response.raise_for_status()
result_data = response.json()
final_status = (
"Submission Successful!\n\n"
f"User: "
f"{result_data.get('username')}\n"
f"Overall Score: "
f"{result_data.get('score', 'N/A')}%\n"
f"Correct: "
f"{result_data.get('correct_count', '?')}/"
f"{result_data.get('total_attempted', '?')}\n\n"
f"Message: "
f"{result_data.get('message', '')}"
)
results_df = pd.DataFrame(
results_log
)
return (
final_status,
results_df
)
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]}"
)
return (
f"Submission Failed: {error_detail}",
pd.DataFrame(results_log)
)
except requests.exceptions.Timeout:
return (
"Submission Failed: Request timed out.",
pd.DataFrame(results_log)
)
except requests.exceptions.RequestException as e:
return (
f"Submission Failed: Network error - {e}",
pd.DataFrame(results_log)
)
except Exception as e:
return (
f"Unexpected submission error: {e}",
pd.DataFrame(results_log)
)
# ============================================================
# GRADIO INTERFACE
# ============================================================
with gr.Blocks() as demo:
gr.Markdown(
"# 🚀 StructuralGPT - GAIA Agent"
)
gr.Markdown(
"""
### Instructions
1. Login to Hugging Face.
2. The agent uses Qwen through Hugging Face.
3. The agent can search the web.
4. The agent can perform calculations using Python.
5. Click **Run Evaluation & Submit All Answers**.
"""
)
gr.LoginButton()
run_button = gr.Button(
"Run Evaluation & Submit All Answers"
)
status_output = gr.Textbox(
label="Run Status / Submission Result",
lines=8,
interactive=False
)
results_table = gr.DataFrame(
label="Questions and Agent Answers",
wrap=True
)
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_host = os.getenv(
"SPACE_HOST"
)
space_id = os.getenv(
"SPACE_ID"
)
if space_host:
print(
f"SPACE_HOST: {space_host}"
)
if space_id:
print(
f"SPACE_ID: {space_id}"
)
print(
"Repository:"
)
print(
f"https://huggingface.co/spaces/{space_id}"
)
print(
"\nLaunching StructuralGPT..."
)
demo.launch(
debug=True,
share=False
) |