Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,11 +1,12 @@
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
import json
|
|
|
|
|
|
|
|
|
|
| 4 |
import traceback
|
| 5 |
import tempfile
|
| 6 |
-
|
| 7 |
-
import sys
|
| 8 |
-
import time
|
| 9 |
import spaces
|
| 10 |
import wikipedia
|
| 11 |
import gradio as gr
|
|
@@ -14,23 +15,30 @@ import pandas as pd
|
|
| 14 |
|
| 15 |
from ddgs import DDGS
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
# =========================================================
|
| 19 |
-
# CONFIGURATION
|
| 20 |
# =========================================================
|
| 21 |
|
| 22 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
)
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
| 34 |
|
| 35 |
SYSTEM_PROMPT = """
|
| 36 |
You are a precise AI assistant solving GAIA benchmark questions.
|
|
@@ -49,101 +57,73 @@ Follow these rules:
|
|
| 49 |
|
| 50 |
|
| 51 |
# =========================================================
|
| 52 |
-
#
|
| 53 |
# =========================================================
|
| 54 |
|
| 55 |
-
def
|
| 56 |
-
api_key = os.getenv("
|
| 57 |
|
| 58 |
if not api_key:
|
| 59 |
raise RuntimeError(
|
| 60 |
-
"
|
| 61 |
"Hugging Face Space Settings > Variables and secrets."
|
| 62 |
)
|
| 63 |
|
| 64 |
-
return
|
| 65 |
-
"Authorization": f"Bearer {api_key}",
|
| 66 |
-
"Content-Type": "application/json",
|
| 67 |
-
"HTTP-Referer": "https://huggingface.co/spaces/Haider67/Final_Assignment_Agent",
|
| 68 |
-
"X-OpenRouter-Title": "GAIA Benchmark Agent",
|
| 69 |
-
}
|
| 70 |
-
|
| 71 |
-
RETRY_STATUS = {429, 500, 502, 503, 504}
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
def post_with_retry(url: str, max_attempts: int = 4, **kwargs):
|
| 75 |
-
last_error = None
|
| 76 |
-
|
| 77 |
-
for attempt in range(1, max_attempts + 1):
|
| 78 |
-
try:
|
| 79 |
-
response = requests.post(url, **kwargs)
|
| 80 |
-
except requests.RequestException as error:
|
| 81 |
-
last_error = error
|
| 82 |
-
print(f"Request error (attempt {attempt}): {error}")
|
| 83 |
-
time.sleep(5 * attempt)
|
| 84 |
-
continue
|
| 85 |
-
|
| 86 |
-
if response.status_code in RETRY_STATUS and attempt < max_attempts:
|
| 87 |
-
wait = 10 * attempt
|
| 88 |
-
print(f"HTTP {response.status_code}, retrying in {wait}s...")
|
| 89 |
-
time.sleep(wait)
|
| 90 |
-
continue
|
| 91 |
|
| 92 |
-
return response
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def generate_openrouter_response(prompt: str) -> str:
|
| 97 |
payload = {
|
| 98 |
-
"model":
|
| 99 |
"messages": [
|
| 100 |
{"role": "system", "content": SYSTEM_PROMPT},
|
| 101 |
{"role": "user", "content": prompt},
|
| 102 |
],
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
"
|
| 106 |
-
"reasoning": {
|
| 107 |
-
"effort": "medium",
|
| 108 |
-
},
|
| 109 |
}
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
json=payload,
|
| 115 |
-
timeout=
|
| 116 |
)
|
| 117 |
|
| 118 |
if not response.ok:
|
| 119 |
try:
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
| 123 |
error_message = response.text
|
| 124 |
|
| 125 |
raise RuntimeError(
|
| 126 |
-
f"
|
| 127 |
)
|
| 128 |
|
| 129 |
try:
|
| 130 |
result = response.json()
|
| 131 |
except ValueError as error:
|
| 132 |
raise RuntimeError(
|
| 133 |
-
f"
|
| 134 |
) from error
|
| 135 |
|
| 136 |
choices = result.get("choices") or []
|
| 137 |
if not choices:
|
| 138 |
-
raise RuntimeError(
|
| 139 |
-
f"OpenRouter returned no choices. Response: {json.dumps(result)[:2000]}"
|
| 140 |
-
)
|
| 141 |
|
| 142 |
choice = choices[0] or {}
|
| 143 |
message = choice.get("message") or {}
|
| 144 |
answer = message.get("content")
|
| 145 |
|
| 146 |
-
# Some providers return content as a list of text blocks.
|
| 147 |
if isinstance(answer, list):
|
| 148 |
answer = "".join(
|
| 149 |
block.get("text", "")
|
|
@@ -154,23 +134,9 @@ def generate_openrouter_response(prompt: str) -> str:
|
|
| 154 |
if isinstance(answer, str) and answer.strip():
|
| 155 |
return answer.strip()
|
| 156 |
|
| 157 |
-
# Do not expose or submit private reasoning as the benchmark answer.
|
| 158 |
-
# Instead, report safe diagnostics that identify truncation/budget issues.
|
| 159 |
-
finish_reason = choice.get("finish_reason", "unknown")
|
| 160 |
-
usage = result.get("usage") or {}
|
| 161 |
-
completion_details = usage.get("completion_tokens_details") or {}
|
| 162 |
-
reasoning_tokens = completion_details.get("reasoning_tokens", "unknown")
|
| 163 |
-
completion_tokens = usage.get("completion_tokens", "unknown")
|
| 164 |
-
message_keys = sorted(message.keys())
|
| 165 |
-
|
| 166 |
raise RuntimeError(
|
| 167 |
-
"
|
| 168 |
-
f"finish_reason={finish_reason
|
| 169 |
-
f"completion_tokens={completion_tokens}; "
|
| 170 |
-
f"reasoning_tokens={reasoning_tokens}; "
|
| 171 |
-
f"message_fields={message_keys}. "
|
| 172 |
-
"If finish_reason is 'length' and reasoning_tokens is close to "
|
| 173 |
-
"completion_tokens, the model used its output budget for reasoning."
|
| 174 |
)
|
| 175 |
|
| 176 |
|
|
@@ -190,23 +156,24 @@ def generate_answers(prompts: list[str]) -> list[str]:
|
|
| 190 |
answers = []
|
| 191 |
|
| 192 |
for index, user_prompt in enumerate(prompts, start=1):
|
| 193 |
-
print(
|
| 194 |
-
f"Generating OpenRouter answer {index}/{len(prompts)} "
|
| 195 |
-
f"with {OPENROUTER_MODEL}"
|
| 196 |
-
)
|
| 197 |
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
|
|
|
| 207 |
|
| 208 |
answers.append(answer)
|
| 209 |
-
time.sleep(
|
| 210 |
|
| 211 |
return answers
|
| 212 |
|
|
@@ -216,7 +183,7 @@ def generate_answers(prompts: list[str]) -> list[str]:
|
|
| 216 |
# =========================================================
|
| 217 |
|
| 218 |
# Keep this registered handler for the existing ZeroGPU setup.
|
| 219 |
-
# It is not used for
|
| 220 |
|
| 221 |
@spaces.GPU(duration=60)
|
| 222 |
def zerogpu_compatibility_check():
|
|
@@ -265,7 +232,7 @@ def read_attached_file(file_path: str) -> str:
|
|
| 265 |
ext = os.path.splitext(file_path)[1].lower()
|
| 266 |
|
| 267 |
try:
|
| 268 |
-
# Python source files
|
| 269 |
if ext == ".py":
|
| 270 |
with open(file_path, "r", encoding="utf-8") as file:
|
| 271 |
code = file.read()
|
|
@@ -283,12 +250,12 @@ def read_attached_file(file_path: str) -> str:
|
|
| 283 |
output, errors = "", "Execution timed out after 30 seconds."
|
| 284 |
|
| 285 |
return (
|
| 286 |
-
f"Python Source Code:\n{code[:
|
| 287 |
-
f"Actual Program Output (stdout):\n{output[:
|
| 288 |
-
f"Errors (stderr):\n{errors[:
|
| 289 |
)
|
| 290 |
|
| 291 |
-
# Excel files
|
| 292 |
elif ext in [".xlsx", ".xls"]:
|
| 293 |
df = pd.read_excel(file_path)
|
| 294 |
|
|
@@ -296,13 +263,13 @@ def read_attached_file(file_path: str) -> str:
|
|
| 296 |
column_totals = numeric_columns.sum().round(2).to_string()
|
| 297 |
|
| 298 |
return (
|
| 299 |
-
"
|
| 300 |
-
+ df.to_string(index=False)[:10000]
|
| 301 |
-
+ "\n\nColumn Totals (computed exactly with pandas):\n"
|
| 302 |
+ column_totals
|
|
|
|
|
|
|
| 303 |
)
|
| 304 |
|
| 305 |
-
# Audio files: transcribe through
|
| 306 |
elif ext in [
|
| 307 |
".mp3",
|
| 308 |
".wav",
|
|
@@ -312,14 +279,13 @@ def read_attached_file(file_path: str) -> str:
|
|
| 312 |
".flac",
|
| 313 |
".aac",
|
| 314 |
]:
|
| 315 |
-
headers =
|
| 316 |
-
headers.pop("Content-Type", None) # requests sets the multipart boundary.
|
| 317 |
|
| 318 |
with open(file_path, "rb") as audio_file:
|
| 319 |
response = requests.post(
|
| 320 |
-
|
| 321 |
headers=headers,
|
| 322 |
-
data={"model":
|
| 323 |
files={
|
| 324 |
"file": (
|
| 325 |
os.path.basename(file_path),
|
|
@@ -331,8 +297,8 @@ def read_attached_file(file_path: str) -> str:
|
|
| 331 |
|
| 332 |
if not response.ok:
|
| 333 |
raise RuntimeError(
|
| 334 |
-
f"
|
| 335 |
-
f"{response.text}"
|
| 336 |
)
|
| 337 |
|
| 338 |
transcript = response.json().get("text", "").strip()
|
|
@@ -349,7 +315,7 @@ def read_attached_file(file_path: str) -> str:
|
|
| 349 |
encoding="utf-8",
|
| 350 |
errors="ignore",
|
| 351 |
) as file:
|
| 352 |
-
return file.read()[:
|
| 353 |
|
| 354 |
except Exception as error:
|
| 355 |
return (
|
|
@@ -362,6 +328,7 @@ def read_attached_file(file_path: str) -> str:
|
|
| 362 |
"This file format is not currently supported."
|
| 363 |
)
|
| 364 |
|
|
|
|
| 365 |
# =========================================================
|
| 366 |
# WEB SEARCH
|
| 367 |
# =========================================================
|
|
@@ -409,7 +376,7 @@ def search_web_and_wiki(question: str) -> str:
|
|
| 409 |
except Exception as error:
|
| 410 |
print(f"DuckDuckGo search error: {error}")
|
| 411 |
|
| 412 |
-
# Wikipedia:
|
| 413 |
try:
|
| 414 |
titles = wikipedia.search(query, results=2)
|
| 415 |
|
|
@@ -421,9 +388,7 @@ def search_web_and_wiki(question: str) -> str:
|
|
| 421 |
print(f"Wikipedia page error for {title}: {page_error}")
|
| 422 |
continue
|
| 423 |
|
| 424 |
-
snippets.append(
|
| 425 |
-
f"[Wikipedia: {title}] {content[:2500]}"
|
| 426 |
-
)
|
| 427 |
|
| 428 |
for heading in [
|
| 429 |
"== Discography",
|
|
@@ -437,18 +402,20 @@ def search_web_and_wiki(question: str) -> str:
|
|
| 437 |
if position != -1:
|
| 438 |
snippets.append(
|
| 439 |
f"[Wikipedia: {title} - section] "
|
| 440 |
-
f"{content[position:position +
|
| 441 |
)
|
| 442 |
break
|
| 443 |
|
| 444 |
except Exception as error:
|
| 445 |
print(f"Wikipedia search error: {error}")
|
| 446 |
|
| 447 |
-
return "\n".join(snippets)
|
|
|
|
| 448 |
|
| 449 |
# =========================================================
|
| 450 |
-
#
|
| 451 |
# =========================================================
|
|
|
|
| 452 |
def reversed_text_hint(question: str) -> str:
|
| 453 |
if question.strip().startswith(".") or "rewsna" in question.lower():
|
| 454 |
return (
|
|
@@ -456,7 +423,12 @@ def reversed_text_hint(question: str) -> str:
|
|
| 456 |
"Reversed, it reads:\n" + question[::-1]
|
| 457 |
)
|
| 458 |
return ""
|
| 459 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 460 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 461 |
try:
|
| 462 |
# Check Hugging Face login
|
|
@@ -483,9 +455,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 483 |
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 484 |
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 485 |
|
| 486 |
-
agent_code =
|
| 487 |
-
f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 488 |
-
)
|
| 489 |
|
| 490 |
# -------------------------------------------------
|
| 491 |
# FETCH QUESTIONS
|
|
@@ -493,10 +463,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 493 |
|
| 494 |
print("Fetching GAIA questions...")
|
| 495 |
|
| 496 |
-
response = requests.get(
|
| 497 |
-
questions_url,
|
| 498 |
-
timeout=30,
|
| 499 |
-
)
|
| 500 |
response.raise_for_status()
|
| 501 |
|
| 502 |
questions_data = response.json()
|
|
@@ -524,15 +491,10 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 524 |
if not task_id or question_text is None:
|
| 525 |
continue
|
| 526 |
|
| 527 |
-
print(
|
| 528 |
-
f"Preparing question {index}/{len(questions_data)}"
|
| 529 |
-
)
|
| 530 |
|
| 531 |
# Download attachment if available
|
| 532 |
-
file_path = download_file(
|
| 533 |
-
task_id,
|
| 534 |
-
file_name,
|
| 535 |
-
)
|
| 536 |
|
| 537 |
# Reversed-text hint, attachment, or web search context
|
| 538 |
hint = reversed_text_hint(question_text)
|
|
@@ -549,7 +511,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 549 |
if context:
|
| 550 |
user_prompt += (
|
| 551 |
"\n\n--- Supporting Context ---\n"
|
| 552 |
-
+ context
|
| 553 |
)
|
| 554 |
|
| 555 |
valid_items.append(item)
|
|
@@ -565,7 +527,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 565 |
# GENERATE ANSWERS
|
| 566 |
# -------------------------------------------------
|
| 567 |
|
| 568 |
-
print("Starting
|
| 569 |
|
| 570 |
final_answers = generate_answers(prompts)
|
| 571 |
|
|
@@ -611,11 +573,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 611 |
|
| 612 |
print("Submitting answers to the scoring API...")
|
| 613 |
|
| 614 |
-
response = requests.post(
|
| 615 |
-
submit_url,
|
| 616 |
-
json=submission_data,
|
| 617 |
-
timeout=60,
|
| 618 |
-
)
|
| 619 |
response.raise_for_status()
|
| 620 |
|
| 621 |
result_data = response.json()
|
|
@@ -637,19 +595,13 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 637 |
|
| 638 |
print(final_status)
|
| 639 |
|
| 640 |
-
return (
|
| 641 |
-
final_status,
|
| 642 |
-
pd.DataFrame(results_log),
|
| 643 |
-
)
|
| 644 |
|
| 645 |
except Exception:
|
| 646 |
error_details = traceback.format_exc()
|
| 647 |
print(error_details)
|
| 648 |
|
| 649 |
-
return
|
| 650 |
-
f"Detailed Error:\n{error_details}",
|
| 651 |
-
None,
|
| 652 |
-
)
|
| 653 |
|
| 654 |
|
| 655 |
# =========================================================
|
|
@@ -657,13 +609,9 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 657 |
# =========================================================
|
| 658 |
|
| 659 |
with gr.Blocks() as demo:
|
| 660 |
-
gr.Markdown(
|
| 661 |
-
"# Multi-Modal GAIA Agent Evaluation Runner"
|
| 662 |
-
)
|
| 663 |
|
| 664 |
-
gr.Markdown(
|
| 665 |
-
"Log in with Hugging Face and run your GAIA evaluation."
|
| 666 |
-
)
|
| 667 |
|
| 668 |
gr.LoginButton()
|
| 669 |
|
|
@@ -689,9 +637,7 @@ with gr.Blocks() as demo:
|
|
| 689 |
visible=False,
|
| 690 |
)
|
| 691 |
|
| 692 |
-
compatibility_output = gr.Textbox(
|
| 693 |
-
visible=False,
|
| 694 |
-
)
|
| 695 |
|
| 696 |
compatibility_button.click(
|
| 697 |
fn=zerogpu_compatibility_check,
|
|
@@ -699,14 +645,11 @@ with gr.Blocks() as demo:
|
|
| 699 |
outputs=compatibility_output,
|
| 700 |
)
|
| 701 |
|
| 702 |
-
# Actual evaluation uses
|
| 703 |
run_button.click(
|
| 704 |
fn=run_and_submit_all,
|
| 705 |
inputs=[],
|
| 706 |
-
outputs=[
|
| 707 |
-
status_output,
|
| 708 |
-
results_table,
|
| 709 |
-
],
|
| 710 |
)
|
| 711 |
|
| 712 |
|
|
@@ -715,4 +658,4 @@ with gr.Blocks() as demo:
|
|
| 715 |
# =========================================================
|
| 716 |
|
| 717 |
if __name__ == "__main__":
|
| 718 |
-
demo.launch()
|
|
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
import json
|
| 4 |
+
import time
|
| 5 |
+
import sys
|
| 6 |
+
import subprocess
|
| 7 |
import traceback
|
| 8 |
import tempfile
|
| 9 |
+
|
|
|
|
|
|
|
| 10 |
import spaces
|
| 11 |
import wikipedia
|
| 12 |
import gradio as gr
|
|
|
|
| 15 |
|
| 16 |
from ddgs import DDGS
|
| 17 |
|
| 18 |
+
wikipedia.wikipedia.USER_AGENT = (
|
| 19 |
+
"GAIA-Agent-Haider/1.0 "
|
| 20 |
+
"(https://huggingface.co/spaces/Haider67/Final_Assignment_Template)"
|
| 21 |
+
)
|
| 22 |
+
wikipedia.set_rate_limiting(True)
|
| 23 |
+
|
| 24 |
|
| 25 |
# =========================================================
|
| 26 |
+
# CONFIGURATION (Groq)
|
| 27 |
# =========================================================
|
| 28 |
|
| 29 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 30 |
+
|
| 31 |
+
GROQ_CHAT_URL = "https://api.groq.com/openai/v1/chat/completions"
|
| 32 |
+
GROQ_AUDIO_URL = "https://api.groq.com/openai/v1/audio/transcriptions"
|
| 33 |
+
|
| 34 |
+
GROQ_MODEL = os.getenv("LLM_MODEL", "openai/gpt-oss-120b")
|
| 35 |
+
GROQ_AUDIO_MODEL = os.getenv("GROQ_AUDIO_MODEL", "whisper-large-v3")
|
| 36 |
+
|
| 37 |
+
# Seconds to wait between questions (protects Groq's per-minute token limit).
|
| 38 |
+
PAUSE_SECONDS = float(os.getenv("PAUSE_SECONDS", "10"))
|
| 39 |
+
|
| 40 |
+
# Maximum characters of supporting context sent with each question.
|
| 41 |
+
MAX_CONTEXT_CHARS = 4500
|
| 42 |
|
| 43 |
SYSTEM_PROMPT = """
|
| 44 |
You are a precise AI assistant solving GAIA benchmark questions.
|
|
|
|
| 57 |
|
| 58 |
|
| 59 |
# =========================================================
|
| 60 |
+
# GROQ CLIENT AND ANSWER GENERATION
|
| 61 |
# =========================================================
|
| 62 |
|
| 63 |
+
def get_groq_key() -> str:
|
| 64 |
+
api_key = os.getenv("LLM_API_KEY") or os.getenv("GROQ_API_KEY")
|
| 65 |
|
| 66 |
if not api_key:
|
| 67 |
raise RuntimeError(
|
| 68 |
+
"Groq key is missing. Add a secret named LLM_API_KEY under "
|
| 69 |
"Hugging Face Space Settings > Variables and secrets."
|
| 70 |
)
|
| 71 |
|
| 72 |
+
return api_key
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
|
|
|
| 74 |
|
| 75 |
+
def generate_groq_response(prompt: str) -> str:
|
|
|
|
|
|
|
| 76 |
payload = {
|
| 77 |
+
"model": GROQ_MODEL,
|
| 78 |
"messages": [
|
| 79 |
{"role": "system", "content": SYSTEM_PROMPT},
|
| 80 |
{"role": "user", "content": prompt},
|
| 81 |
],
|
| 82 |
+
"temperature": 0,
|
| 83 |
+
"max_completion_tokens": 3000,
|
| 84 |
+
"reasoning_effort": "low",
|
|
|
|
|
|
|
|
|
|
| 85 |
}
|
| 86 |
|
| 87 |
+
headers = {
|
| 88 |
+
"Authorization": f"Bearer {get_groq_key()}",
|
| 89 |
+
"Content-Type": "application/json",
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
# Single attempt only: no retries.
|
| 93 |
+
response = requests.post(
|
| 94 |
+
GROQ_CHAT_URL,
|
| 95 |
+
headers=headers,
|
| 96 |
json=payload,
|
| 97 |
+
timeout=60,
|
| 98 |
)
|
| 99 |
|
| 100 |
if not response.ok:
|
| 101 |
try:
|
| 102 |
+
error_message = response.json().get("error", {}).get(
|
| 103 |
+
"message", response.text
|
| 104 |
+
)
|
| 105 |
+
except (ValueError, AttributeError, TypeError):
|
| 106 |
error_message = response.text
|
| 107 |
|
| 108 |
raise RuntimeError(
|
| 109 |
+
f"Groq request failed ({response.status_code}): {error_message}"
|
| 110 |
)
|
| 111 |
|
| 112 |
try:
|
| 113 |
result = response.json()
|
| 114 |
except ValueError as error:
|
| 115 |
raise RuntimeError(
|
| 116 |
+
f"Groq returned invalid JSON: {response.text[:500]}"
|
| 117 |
) from error
|
| 118 |
|
| 119 |
choices = result.get("choices") or []
|
| 120 |
if not choices:
|
| 121 |
+
raise RuntimeError("Groq returned no choices.")
|
|
|
|
|
|
|
| 122 |
|
| 123 |
choice = choices[0] or {}
|
| 124 |
message = choice.get("message") or {}
|
| 125 |
answer = message.get("content")
|
| 126 |
|
|
|
|
| 127 |
if isinstance(answer, list):
|
| 128 |
answer = "".join(
|
| 129 |
block.get("text", "")
|
|
|
|
| 134 |
if isinstance(answer, str) and answer.strip():
|
| 135 |
return answer.strip()
|
| 136 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
raise RuntimeError(
|
| 138 |
+
"Groq returned no visible answer text. "
|
| 139 |
+
f"finish_reason={choice.get('finish_reason', 'unknown')}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
)
|
| 141 |
|
| 142 |
|
|
|
|
| 156 |
answers = []
|
| 157 |
|
| 158 |
for index, user_prompt in enumerate(prompts, start=1):
|
| 159 |
+
print(f"Generating answer {index}/{len(prompts)} with {GROQ_MODEL}")
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
+
try:
|
| 162 |
+
answer = clean_answer(generate_groq_response(user_prompt))
|
| 163 |
+
except Exception as error:
|
| 164 |
+
message = str(error).lower()
|
| 165 |
|
| 166 |
+
if "per day" in message or "(tpd)" in message or "(rpd)" in message:
|
| 167 |
+
raise RuntimeError(
|
| 168 |
+
"Groq daily limit reached. Nothing was submitted. "
|
| 169 |
+
"Run again after the reset.\n" + str(error)
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
print(f"Question {index} failed: {error}")
|
| 173 |
+
answer = "unknown"
|
| 174 |
|
| 175 |
answers.append(answer)
|
| 176 |
+
time.sleep(PAUSE_SECONDS)
|
| 177 |
|
| 178 |
return answers
|
| 179 |
|
|
|
|
| 183 |
# =========================================================
|
| 184 |
|
| 185 |
# Keep this registered handler for the existing ZeroGPU setup.
|
| 186 |
+
# It is not used for inference.
|
| 187 |
|
| 188 |
@spaces.GPU(duration=60)
|
| 189 |
def zerogpu_compatibility_check():
|
|
|
|
| 232 |
ext = os.path.splitext(file_path)[1].lower()
|
| 233 |
|
| 234 |
try:
|
| 235 |
+
# Python source files: include the real program output
|
| 236 |
if ext == ".py":
|
| 237 |
with open(file_path, "r", encoding="utf-8") as file:
|
| 238 |
code = file.read()
|
|
|
|
| 250 |
output, errors = "", "Execution timed out after 30 seconds."
|
| 251 |
|
| 252 |
return (
|
| 253 |
+
f"Python Source Code:\n{code[:2500]}\n\n"
|
| 254 |
+
f"Actual Program Output (stdout):\n{output[:1500]}\n\n"
|
| 255 |
+
f"Errors (stderr):\n{errors[:500]}"
|
| 256 |
)
|
| 257 |
|
| 258 |
+
# Excel files: include exact column totals
|
| 259 |
elif ext in [".xlsx", ".xls"]:
|
| 260 |
df = pd.read_excel(file_path)
|
| 261 |
|
|
|
|
| 263 |
column_totals = numeric_columns.sum().round(2).to_string()
|
| 264 |
|
| 265 |
return (
|
| 266 |
+
"Column Totals (computed exactly with pandas):\n"
|
|
|
|
|
|
|
| 267 |
+ column_totals
|
| 268 |
+
+ "\n\nExcel Table Contents:\n"
|
| 269 |
+
+ df.to_string(index=False)[:3000]
|
| 270 |
)
|
| 271 |
|
| 272 |
+
# Audio files: transcribe through Groq Whisper
|
| 273 |
elif ext in [
|
| 274 |
".mp3",
|
| 275 |
".wav",
|
|
|
|
| 279 |
".flac",
|
| 280 |
".aac",
|
| 281 |
]:
|
| 282 |
+
headers = {"Authorization": f"Bearer {get_groq_key()}"}
|
|
|
|
| 283 |
|
| 284 |
with open(file_path, "rb") as audio_file:
|
| 285 |
response = requests.post(
|
| 286 |
+
GROQ_AUDIO_URL,
|
| 287 |
headers=headers,
|
| 288 |
+
data={"model": GROQ_AUDIO_MODEL},
|
| 289 |
files={
|
| 290 |
"file": (
|
| 291 |
os.path.basename(file_path),
|
|
|
|
| 297 |
|
| 298 |
if not response.ok:
|
| 299 |
raise RuntimeError(
|
| 300 |
+
f"Groq transcription failed ({response.status_code}): "
|
| 301 |
+
f"{response.text[:500]}"
|
| 302 |
)
|
| 303 |
|
| 304 |
transcript = response.json().get("text", "").strip()
|
|
|
|
| 315 |
encoding="utf-8",
|
| 316 |
errors="ignore",
|
| 317 |
) as file:
|
| 318 |
+
return file.read()[:4000]
|
| 319 |
|
| 320 |
except Exception as error:
|
| 321 |
return (
|
|
|
|
| 328 |
"This file format is not currently supported."
|
| 329 |
)
|
| 330 |
|
| 331 |
+
|
| 332 |
# =========================================================
|
| 333 |
# WEB SEARCH
|
| 334 |
# =========================================================
|
|
|
|
| 376 |
except Exception as error:
|
| 377 |
print(f"DuckDuckGo search error: {error}")
|
| 378 |
|
| 379 |
+
# Wikipedia: intro plus the most useful section of the full article
|
| 380 |
try:
|
| 381 |
titles = wikipedia.search(query, results=2)
|
| 382 |
|
|
|
|
| 388 |
print(f"Wikipedia page error for {title}: {page_error}")
|
| 389 |
continue
|
| 390 |
|
| 391 |
+
snippets.append(f"[Wikipedia: {title}] {content[:1200]}")
|
|
|
|
|
|
|
| 392 |
|
| 393 |
for heading in [
|
| 394 |
"== Discography",
|
|
|
|
| 402 |
if position != -1:
|
| 403 |
snippets.append(
|
| 404 |
f"[Wikipedia: {title} - section] "
|
| 405 |
+
f"{content[position:position + 2500]}"
|
| 406 |
)
|
| 407 |
break
|
| 408 |
|
| 409 |
except Exception as error:
|
| 410 |
print(f"Wikipedia search error: {error}")
|
| 411 |
|
| 412 |
+
return "\n".join(snippets)
|
| 413 |
+
|
| 414 |
|
| 415 |
# =========================================================
|
| 416 |
+
# HELPERS
|
| 417 |
# =========================================================
|
| 418 |
+
|
| 419 |
def reversed_text_hint(question: str) -> str:
|
| 420 |
if question.strip().startswith(".") or "rewsna" in question.lower():
|
| 421 |
return (
|
|
|
|
| 423 |
"Reversed, it reads:\n" + question[::-1]
|
| 424 |
)
|
| 425 |
return ""
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
# =========================================================
|
| 429 |
+
# MAIN GAIA EVALUATION
|
| 430 |
+
# =========================================================
|
| 431 |
+
|
| 432 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 433 |
try:
|
| 434 |
# Check Hugging Face login
|
|
|
|
| 455 |
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 456 |
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 457 |
|
| 458 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
|
|
|
|
|
| 459 |
|
| 460 |
# -------------------------------------------------
|
| 461 |
# FETCH QUESTIONS
|
|
|
|
| 463 |
|
| 464 |
print("Fetching GAIA questions...")
|
| 465 |
|
| 466 |
+
response = requests.get(questions_url, timeout=30)
|
|
|
|
|
|
|
|
|
|
| 467 |
response.raise_for_status()
|
| 468 |
|
| 469 |
questions_data = response.json()
|
|
|
|
| 491 |
if not task_id or question_text is None:
|
| 492 |
continue
|
| 493 |
|
| 494 |
+
print(f"Preparing question {index}/{len(questions_data)}")
|
|
|
|
|
|
|
| 495 |
|
| 496 |
# Download attachment if available
|
| 497 |
+
file_path = download_file(task_id, file_name)
|
|
|
|
|
|
|
|
|
|
| 498 |
|
| 499 |
# Reversed-text hint, attachment, or web search context
|
| 500 |
hint = reversed_text_hint(question_text)
|
|
|
|
| 511 |
if context:
|
| 512 |
user_prompt += (
|
| 513 |
"\n\n--- Supporting Context ---\n"
|
| 514 |
+
+ context[:MAX_CONTEXT_CHARS]
|
| 515 |
)
|
| 516 |
|
| 517 |
valid_items.append(item)
|
|
|
|
| 527 |
# GENERATE ANSWERS
|
| 528 |
# -------------------------------------------------
|
| 529 |
|
| 530 |
+
print("Starting Groq answer generation...")
|
| 531 |
|
| 532 |
final_answers = generate_answers(prompts)
|
| 533 |
|
|
|
|
| 573 |
|
| 574 |
print("Submitting answers to the scoring API...")
|
| 575 |
|
| 576 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 577 |
response.raise_for_status()
|
| 578 |
|
| 579 |
result_data = response.json()
|
|
|
|
| 595 |
|
| 596 |
print(final_status)
|
| 597 |
|
| 598 |
+
return final_status, pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
| 599 |
|
| 600 |
except Exception:
|
| 601 |
error_details = traceback.format_exc()
|
| 602 |
print(error_details)
|
| 603 |
|
| 604 |
+
return f"Detailed Error:\n{error_details}", None
|
|
|
|
|
|
|
|
|
|
| 605 |
|
| 606 |
|
| 607 |
# =========================================================
|
|
|
|
| 609 |
# =========================================================
|
| 610 |
|
| 611 |
with gr.Blocks() as demo:
|
| 612 |
+
gr.Markdown("# Multi-Modal GAIA Agent Evaluation Runner")
|
|
|
|
|
|
|
| 613 |
|
| 614 |
+
gr.Markdown("Log in with Hugging Face and run your GAIA evaluation.")
|
|
|
|
|
|
|
| 615 |
|
| 616 |
gr.LoginButton()
|
| 617 |
|
|
|
|
| 637 |
visible=False,
|
| 638 |
)
|
| 639 |
|
| 640 |
+
compatibility_output = gr.Textbox(visible=False)
|
|
|
|
|
|
|
| 641 |
|
| 642 |
compatibility_button.click(
|
| 643 |
fn=zerogpu_compatibility_check,
|
|
|
|
| 645 |
outputs=compatibility_output,
|
| 646 |
)
|
| 647 |
|
| 648 |
+
# Actual evaluation uses Groq.
|
| 649 |
run_button.click(
|
| 650 |
fn=run_and_submit_all,
|
| 651 |
inputs=[],
|
| 652 |
+
outputs=[status_output, results_table],
|
|
|
|
|
|
|
|
|
|
| 653 |
)
|
| 654 |
|
| 655 |
|
|
|
|
| 658 |
# =========================================================
|
| 659 |
|
| 660 |
if __name__ == "__main__":
|
| 661 |
+
demo.launch()
|