Spaces:
Sleeping
Sleeping
File size: 32,427 Bytes
a212dc5 43846ee a212dc5 43846ee 6172d6b 43846ee 10e9b7d 07f8a9d a212dc5 07f8a9d 9564d9d 1520c10 10e9b7d 3c4371f 07f8a9d 10e9b7d 9564d9d 6172d6b 9564d9d 6172d6b 43846ee 07f8a9d 43846ee 07f8a9d 43846ee a212dc5 07f8a9d a212dc5 07f8a9d e80aab9 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 07f8a9d a212dc5 43846ee a212dc5 43846ee a212dc5 07f8a9d 6172d6b a212dc5 9564d9d a212dc5 9564d9d 43846ee 9564d9d 43846ee 9564d9d 6172d6b 9564d9d 43846ee 6172d6b 9564d9d 07f8a9d a212dc5 07f8a9d 43846ee 9564d9d 07f8a9d a212dc5 43846ee 9564d9d 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee e80aab9 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee 07f8a9d 9564d9d 43846ee 07f8a9d 9564d9d 07f8a9d a212dc5 07f8a9d 43846ee a212dc5 43846ee a212dc5 07f8a9d 9564d9d a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee 07f8a9d eccf8e4 43846ee 07f8a9d 43846ee 07f8a9d 43846ee 07f8a9d 9564d9d 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee 6172d6b a212dc5 6172d6b a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee 9564d9d 6172d6b a212dc5 9564d9d 43846ee a212dc5 9564d9d 43846ee 9564d9d a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee a212dc5 43846ee 9564d9d 31243f4 07f8a9d 9564d9d 07f8a9d 6172d6b 43846ee 07f8a9d 43846ee 07f8a9d 6172d6b 43846ee a212dc5 43846ee 6172d6b 43846ee 6172d6b 43846ee a212dc5 e80aab9 43846ee e80aab9 43846ee 07f8a9d 6172d6b aacc1dd 07f8a9d 9564d9d 07f8a9d 43846ee 07f8a9d 43846ee 07f8a9d 6172d6b 43846ee aacc1dd 9564d9d 43846ee a212dc5 43846ee a212dc5 9564d9d 43846ee a212dc5 9564d9d 43846ee 9564d9d 43846ee a212dc5 43846ee a212dc5 9564d9d 6172d6b 43846ee 6172d6b 43846ee 6172d6b 43846ee 07f8a9d 9564d9d 07f8a9d 9564d9d 07f8a9d e80aab9 a212dc5 0ee0419 43846ee a212dc5 43846ee a212dc5 e80aab9 7e4a06b 07f8a9d 9564d9d 07f8a9d 6172d6b 31243f4 a212dc5 7d65c66 e80aab9 9564d9d 07f8a9d 6172d6b e80aab9 aacc1dd | 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 | """HF Agents Course ์ต์ข
๊ณผ์ - ๋ค๋จ๊ณ ์์ด์ ํธ ๋ฒ์ (Gemini ๋๋ Hugging Face)
LLM์ด ํ ๋จ๊ณ์ ํ๋์ ๋๊ตฌ๋ฅผ ๊ณจ๋ผ ์ฐ๊ณ (๊ฒ์/์ํค/์นํ์ด์ง/ํ์ด์ฌ/์ ํ๋ธ ์๋ง), ๊ฒฐ๊ณผ๋ฅผ ๋ณด๊ณ ๋ค์ ๋จ๊ณ๋ฅผ ์ ํฉ๋๋ค.
์ต๋ MAX_STEPS ๋จ๊ณ ์์ ์ต์ข
๋ต์ ๋ด๋๋ก ์ ํํด ๋น์ฉ์ ํต์ ํฉ๋๋ค.
"""
import base64
import json
import mimetypes
import os
import re
import subprocess
import sys
import tempfile
import threading
import time
from collections import deque
import gradio as gr
import pandas as pd
import requests
# ZeroGPU ํ๋์จ์ด์์ ์์ ์ค๋ฅ๋ฅผ ๋ง๊ธฐ ์ํ ๋๋ฏธ ํจ์ (CPU ํ๋์จ์ด์์๋ ๋ฌด์๋จ)
try:
import spaces
@spaces.GPU
def _gpu_placeholder():
return "ok"
except ImportError:
pass
try:
from ddgs import DDGS
except ImportError:
try:
from duckduckgo_search import DDGS
except ImportError:
DDGS = None
# ---------------------------------------------------------------------------
# ์ค์ (Space Variables/Secrets๋ก ์กฐ์ )
# ---------------------------------------------------------------------------
SCORING_API = "https://agents-course-unit4-scoring.hf.space"
GEMINI_API = "https://generativelanguage.googleapis.com/v1beta"
HF_ROUTER = "https://router.huggingface.co/v1"
FILES_DIR = "/tmp/task_files"
CACHE_PATH = "/tmp/answers_cache_v4.json"
os.makedirs(FILES_DIR, exist_ok=True)
PROVIDER = (os.getenv("PROVIDER", "") or ("gemini" if os.getenv("GEMINI_API_KEY") else "hf")).lower() # gemini | hf
MIN_INTERVAL = float(os.getenv("MIN_INTERVAL", "7" if PROVIDER == "gemini" else "1")) # LLM ํธ์ถ ๊ฐ ์ต์ ๊ฐ๊ฒฉ(์ด)
MAX_RETRY = int(os.getenv("MAX_RETRY", "3")) # 429 ์ฌ์๋ ํ์
MAX_STEPS = int(os.getenv("MAX_STEPS", "6")) # ๋ฌธํญ๋น ์ต๋ ๋จ๊ณ(=์ต๋ LLM ํธ์ถ ์)
QUESTION_TIMEOUT = int(os.getenv("QUESTION_TIMEOUT", "240")) # ๋ฌธํญ๋น ๋ชฉํ ์ ํ ์๊ฐ(์ด). ๋์ผ๋ฉด ๋ฐ๋ก ๋ต์ ๋ด๊ฒ ํจ
OBS_CHARS = int(os.getenv("OBS_CHARS", "6000")) # ๋๊ตฌ ๊ฒฐ๊ณผ 1ํ ์ต๋ ๊ธ์ ์
PY_TIMEOUT = int(os.getenv("PY_TIMEOUT", "25")) # ํ์ด์ฌ ์คํ ์ ํ ์๊ฐ(์ด)
GEMINI_MODELS = os.getenv("GEMINI_MODELS", "") # ์ ํ: ์ผํ๋ก ๊ตฌ๋ถํ Gemini ๋ชจ๋ธ ๋ชฉ๋ก
HF_MODELS = [m.strip() for m in (os.getenv("HF_MODELS") or os.getenv("HF_MODEL") or "Qwen/Qwen2.5-72B-Instruct").split(",") if m.strip()]
UA = {"User-Agent": "Mozilla/5.0 (agents-course-runner)"}
AGENT_PROMPT = """You are a careful research agent solving a GAIA-style benchmark question. The final answer is graded by EXACT MATCH.
You work in steps. In each turn reply with EXACTLY ONE action, in this format and nothing else:
Thought: <short reasoning>
Action: <search|wiki|fetch|python|youtube|final>
Input: <input for the action>
Actions:
- search: Input = a web search query. Returns titles, URLs and snippets.
- wiki: Input = "Page Title" or "Page Title | keyword". Returns the English Wikipedia article text including tables; with a keyword you also get the passages around it.
- fetch: Input = a URL, or "URL | keyword". Returns the page text.
- python: Input = Python code (may span several lines). Use print() to output results. pandas, openpyxl, re, json and math are available. Use it for ANY arithmetic, counting, sorting, string manipulation, and for reading attached files.
- youtube: Input = a YouTube URL. Returns the transcript if available.
- final: Input = ONLY the final answer value.
Rules for the final answer:
- Output only the answer value: no explanation, no trailing period, no units unless asked.
- Numbers: digits only, no thousands separators, no currency or percent symbols unless asked.
- Lists: comma-separated, in the order the question asks.
- Strings: no leading articles (a, an, the) and no abbreviations unless asked.
- Follow any formatting instruction inside the question exactly.
Be efficient: you have at most {max_steps} steps. Prefer verifying facts with tools over guessing. If a tool result is not helpful, change your approach instead of repeating it. If you cannot find the answer, give your best reasoned answer rather than leaving it empty."""
# ---------------------------------------------------------------------------
# ๋ก๊ทธ / ์บ์
# ---------------------------------------------------------------------------
_events = deque(maxlen=14)
def log(msg: str):
line = f"[{time.strftime('%H:%M:%S')}] {msg}"
print(line, flush=True)
_events.append(line)
def recent_log() -> str:
return "\n".join(_events)
def load_cache() -> dict:
try:
with open(CACHE_PATH, "r", encoding="utf-8") as f:
return json.load(f)
except Exception: # noqa: BLE001
return {}
def save_cache(task_id: str, answer: str):
cache = load_cache()
cache[task_id] = answer
with open(CACHE_PATH, "w", encoding="utf-8") as f:
json.dump(cache, f, ensure_ascii=False)
# ---------------------------------------------------------------------------
# LLM ํธ์ถ (Gemini REST / Hugging Face ๋ผ์ฐํฐ)
# ---------------------------------------------------------------------------
class LLMUnavailable(Exception):
pass
_last_call = 0.0
def throttle():
global _last_call
wait = MIN_INTERVAL - (time.time() - _last_call)
if wait > 0:
time.sleep(wait)
_last_call = time.time()
def api_key() -> str:
return os.getenv("GEMINI_API_KEY", "")
def hf_token() -> str:
return os.getenv("HF_TOKEN", "")
def list_models() -> list[str]:
r = requests.get(f"{GEMINI_API}/models", headers={"x-goog-api-key": api_key()}, params={"pageSize": 200}, timeout=30)
r.raise_for_status()
return [m["name"].replace("models/", "") for m in r.json().get("models", [])
if "generateContent" in m.get("supportedGenerationMethods", [])]
_BAD = ("image", "tts", "audio", "live", "embed", "vision", "robotics", "computer", "imagen", "veo")
_candidates: list[str] = []
def candidate_models() -> list[str]:
global _candidates
if _candidates:
return _candidates
if GEMINI_MODELS.strip():
_candidates = [m.strip().replace("models/", "") for m in GEMINI_MODELS.split(",") if m.strip()]
return _candidates
names = [n for n in list_models() if n.startswith("gemini") and not any(b in n for b in _BAD)]
lite = [n for n in names if "flash-lite" in n]
flash = [n for n in names if "flash" in n and "flash-lite" not in n]
_candidates = (lite[:2] + flash[:2]) or names[:3]
log(f"์๋ ์ ํ๋ Gemini ๋ชจ๋ธ ํ๋ณด: {_candidates}")
return _candidates
def call_gemini(parts: list[dict]) -> tuple[str, str]:
if not api_key():
raise LLMUnavailable("GEMINI_API_KEY๊ฐ ์ค์ ๋์ง ์์์ต๋๋ค.")
last_err = ""
for model in candidate_models():
for attempt in range(MAX_RETRY + 1):
throttle()
try:
r = requests.post(
f"{GEMINI_API}/models/{model}:generateContent",
headers={"x-goog-api-key": api_key(), "Content-Type": "application/json"},
json={"contents": [{"role": "user", "parts": parts}],
"generationConfig": {"temperature": 0, "maxOutputTokens": 2048}},
timeout=120,
)
except requests.RequestException as e:
last_err = f"{model}: ๋คํธ์ํฌ ์ค๋ฅ {e}"
time.sleep(5)
continue
if r.status_code == 200:
cand = (r.json().get("candidates") or [{}])[0]
text = "".join(p.get("text", "") for p in cand.get("content", {}).get("parts", []) if not p.get("thought"))
if text.strip():
return text, model
last_err = f"{model}: ๋น ์๋ต({cand.get('finishReason')})"
break
body = r.text
last_err = f"{model}: HTTP {r.status_code} {body[:180].replace(chr(10), ' ')}"
if r.status_code == 429:
if "PerDay" in body or "limit: 0" in body:
log(f"{model}: ์ผ์ผ ํ๋ ์์ง ๋๋ ํ๋ 0 -> ๋ค์ ๋ชจ๋ธ")
break
if attempt == MAX_RETRY:
break
m = re.search(r'"retryDelay":\s*"(\d+(?:\.\d+)?)s"', body)
wait = min(float(m.group(1)) + 1, 60) if m else 15 * (attempt + 1)
log(f"{model}: 429, {int(wait)}์ด ํ ์ฌ์๋ ({attempt + 1}/{MAX_RETRY})")
time.sleep(wait)
continue
if r.status_code >= 500:
time.sleep(5)
continue
break
raise LLMUnavailable(last_err or "์ฌ์ฉ ๊ฐ๋ฅํ ๋ชจ๋ธ์ด ์์ต๋๋ค.")
def call_hf(parts: list[dict]) -> tuple[str, str]:
if not hf_token():
raise LLMUnavailable("HF_TOKEN์ด ์ค์ ๋์ง ์์์ต๋๋ค.")
text = "\n".join(p["text"] for p in parts if "text" in p)
if any("inline_data" in p for p in parts):
text = "NOTE: An image/audio attachment exists but you cannot view it; answer from the other information.\n\n" + text
last_err = ""
for model in HF_MODELS:
for attempt in range(MAX_RETRY + 1):
throttle()
try:
r = requests.post(
f"{HF_ROUTER}/chat/completions",
headers={"Authorization": f"Bearer {hf_token()}", "Content-Type": "application/json"},
json={"model": model, "messages": [{"role": "user", "content": text}],
"max_tokens": 1500, "temperature": 0},
timeout=120,
)
except requests.RequestException as e:
last_err = f"{model}: ๋คํธ์ํฌ ์ค๋ฅ {e}"
time.sleep(5)
continue
if r.status_code == 200:
content = (r.json().get("choices") or [{}])[0].get("message", {}).get("content") or ""
content = re.sub(r"(?s)<think>.*?</think>", "", content).strip()
if content:
return content, model
last_err = f"{model}: ๋น ์๋ต"
break
body = r.text
last_err = f"{model}: HTTP {r.status_code} {body[:180].replace(chr(10), ' ')}"
if r.status_code == 402:
raise LLMUnavailable("HF ํฌ๋ ๋ง ์์ง(402). " + body[:150])
if r.status_code in (401, 403):
raise LLMUnavailable(f"HF_TOKEN ์ธ์ฆ/๊ถํ ์ค๋ฅ({r.status_code}). Inference Providers ๊ถํ์ ํ์ธํ์ธ์.")
if r.status_code == 429:
if attempt == MAX_RETRY:
break
wait = 15 * (attempt + 1)
log(f"{model}: 429, {wait}์ด ํ ์ฌ์๋ ({attempt + 1}/{MAX_RETRY})")
time.sleep(wait)
continue
if r.status_code >= 500:
time.sleep(5)
continue
break
raise LLMUnavailable(last_err or "์ฌ์ฉ ๊ฐ๋ฅํ ๋ชจ๋ธ์ด ์์ต๋๋ค.")
def call_llm(parts: list[dict]) -> tuple[str, str]:
return call_hf(parts) if PROVIDER == "hf" else call_gemini(parts)
# ---------------------------------------------------------------------------
# ๋๊ตฌ ๊ตฌํ
# ---------------------------------------------------------------------------
def html_to_text(html: str) -> str:
html = re.sub(r"(?is)<(script|style|noscript|svg|header|footer|nav)[^>]*>.*?</\1>", " ", html)
html = re.sub(r"(?is)<sup[^>]*class=\"[^\"]*reference[^\"]*\"[^>]*>.*?</sup>", "", html)
html = re.sub(r"(?i)</t[dh]>", " | ", html)
html = re.sub(r"(?i)</tr>|<br\s*/?>|</p>|</li>|</h[1-6]>|</caption>", "\n", html)
text = re.sub(r"(?s)<[^>]+>", " ", html)
text = (text.replace(" ", " ").replace(" ", " ").replace("&", "&")
.replace("<", "<").replace(">", ">").replace(""", '"').replace("'", "'"))
text = re.sub(r"[ \t\u00a0]+", " ", text)
text = re.sub(r"(\s*\|\s*)+\n", "\n", text)
text = re.sub(r"\n\s*\n+", "\n", text)
return text.strip()
def windows(text: str, keyword: str, head: int = 1500, win: int = 1600, max_hits: int = 3) -> str:
"""ํค์๋ ์ฃผ๋ณ ๋ฌธ๋จ๋ง ์๋ผ ๋ณด์ฌ์ค๋๋ค. ํค์๋๊ฐ ์์ผ๋ฉด ์๋ถ๋ถ์ ๋ณด์ฌ์ค๋๋ค."""
if not keyword:
return text[:OBS_CHARS]
low, key = text.lower(), keyword.lower()
spans, pos = [], 0
while len(spans) < max_hits:
i = low.find(key, pos)
if i < 0:
break
spans.append((max(0, i - win // 4), min(len(text), i + win)))
pos = i + win
if not spans:
return f"(ํค์๋ '{keyword}'๋ฅผ ์ฐพ์ง ๋ชปํจ. ๋ฌธ์ ์๋ถ๋ถ:)\n" + text[:OBS_CHARS]
out = [text[:head]] + [f"...\n{text[a:b]}" for a, b in spans]
return "\n".join(out)[: OBS_CHARS * 2]
def tool_search(query: str) -> str:
if DDGS is None:
return "๊ฒ์ ๋๊ตฌ๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค."
try:
results = list(DDGS().text(query, max_results=6))
except Exception as e: # noqa: BLE001
return f"๊ฒ์ ์คํจ: {type(e).__name__}: {str(e)[:150]}"
if not results:
return "๊ฒ์ ๊ฒฐ๊ณผ ์์"
return "\n\n".join(f"[{i}] {r.get('title', '')}\n{r.get('href', '')}\n{r.get('body', '')}"
for i, r in enumerate(results, 1))[:OBS_CHARS]
def _wiki_parse(title: str):
r = requests.get("https://en.wikipedia.org/w/api.php", headers=UA, timeout=25,
params={"action": "parse", "page": title, "prop": "text", "format": "json",
"redirects": 1, "formatversion": 2})
j = r.json()
if "parse" in j:
return j["parse"]["text"], j["parse"]["title"]
return None
def tool_wiki(inp: str) -> str:
title, _, kw = inp.partition("|")
title, kw = title.strip(), kw.strip()
try:
got = _wiki_parse(title)
if not got:
r = requests.get("https://en.wikipedia.org/w/api.php", headers=UA, timeout=25,
params={"action": "query", "list": "search", "srsearch": title,
"format": "json", "srlimit": 1})
hits = r.json().get("query", {}).get("search", [])
got = _wiki_parse(hits[0]["title"]) if hits else None
if not got:
return f"Wikipedia ๋ฌธ์๋ฅผ ์ฐพ์ง ๋ชปํ์ต๋๋ค: {title}"
html, real = got
return f"[Wikipedia: {real}]\n" + windows(html_to_text(html), kw)
except Exception as e: # noqa: BLE001
return f"Wikipedia ์กฐํ ์คํจ: {type(e).__name__}: {str(e)[:150]}"
def tool_fetch(inp: str) -> str:
url, _, kw = inp.partition("|")
url, kw = url.strip(), kw.strip()
if not url.startswith("http"):
return "URL์ http๋ก ์์ํด์ผ ํฉ๋๋ค."
try:
r = requests.get(url, headers=UA, timeout=25)
ctype = r.headers.get("content-type", "")
if "pdf" in ctype or url.lower().endswith(".pdf"):
return "PDF๋ ์ง์ํ์ง ์์ต๋๋ค."
if "html" not in ctype and "text" not in ctype and "json" not in ctype:
return f"์ง์ํ์ง ์๋ ํ์์
๋๋ค: {ctype}"
text = html_to_text(r.text) if "html" in ctype else r.text
return windows(text, kw)
except Exception as e: # noqa: BLE001
return f"ํ์ด์ง๋ฅผ ๊ฐ์ ธ์ค์ง ๋ชปํ์ต๋๋ค: {type(e).__name__}: {str(e)[:150]}"
def tool_python(code: str) -> str:
code = re.sub(r"^```(?:python)?\s*\n?", "", code.strip())
code = re.sub(r"\n?```\s*$", "", code)
with tempfile.NamedTemporaryFile("w", suffix=".py", dir="/tmp", delete=False, encoding="utf-8") as f:
f.write(code)
path = f.name
# ํ ํฐ ๋ฑ ๋น๋ฐ ํ๊ฒฝ๋ณ์๊ฐ ์ฝ๋์ ๋
ธ์ถ๋์ง ์๋๋ก ์ต์ ํ๊ฒฝ๋ง ์ ๋ฌ
env = {"PATH": os.environ.get("PATH", ""), "HOME": "/tmp", "PYTHONIOENCODING": "utf-8"}
try:
r = subprocess.run([sys.executable, path], capture_output=True, text=True,
timeout=PY_TIMEOUT, cwd=FILES_DIR, env=env)
out = r.stdout or ""
if r.stderr:
out += "\n[stderr]\n" + r.stderr[-1500:]
except subprocess.TimeoutExpired:
out = f"(์คํ ์๊ฐ ์ด๊ณผ {PY_TIMEOUT}์ด)"
except Exception as e: # noqa: BLE001
out = f"์คํ ์ค๋ฅ: {e}"
finally:
try:
os.remove(path)
except OSError:
pass
return out[:OBS_CHARS] if out.strip() else "(์ถ๋ ฅ ์์. ๊ฒฐ๊ณผ๋ print()๋ก ์ถ๋ ฅํด์ผ ํฉ๋๋ค.)"
def tool_youtube(url: str) -> str:
m = re.search(r"(?:v=|youtu\.be/)([\w-]{11})", url)
if not m:
return "์ ํจํ YouTube URL์ด ์๋๋๋ค."
try:
from youtube_transcript_api import YouTubeTranscriptApi
except ImportError:
return "youtube-transcript-api๊ฐ ์ค์น๋์ง ์์์ต๋๋ค."
vid = m.group(1)
try:
try:
items = YouTubeTranscriptApi.get_transcript(vid)
text = " ".join(i.get("text", "") for i in items)
except AttributeError:
text = " ".join(getattr(s, "text", "") for s in YouTubeTranscriptApi().fetch(vid))
return text[: OBS_CHARS * 2] or "์๋ง์ด ๋น์ด ์์ต๋๋ค."
except Exception as e: # noqa: BLE001
return f"์๋ง์ ๊ฐ์ ธ์ค์ง ๋ชปํ์ต๋๋ค(์์ ๋ด์ฉ์ ๋ณผ ์ ์์): {type(e).__name__}: {str(e)[:150]}"
TOOLS = {"search": tool_search, "wiki": tool_wiki, "fetch": tool_fetch, "python": tool_python, "youtube": tool_youtube}
# ---------------------------------------------------------------------------
# ์ฒจ๋ถ ํ์ผ
# ---------------------------------------------------------------------------
def download_file(task_id: str, file_name: str):
if not file_name:
return None
try:
r = requests.get(f"{SCORING_API}/files/{task_id}", timeout=60)
r.raise_for_status()
path = os.path.join(FILES_DIR, f"{task_id}_{file_name}")
with open(path, "wb") as f:
f.write(r.content)
return path
except Exception as e: # noqa: BLE001
log(f"ํ์ผ ๋ค์ด๋ก๋ ์คํจ: {e}")
return None
def file_to_parts(path: str) -> tuple[str, list[dict]]:
"""(๋ฏธ๋ฆฌ๋ณด๊ธฐ ํ
์คํธ, Gemini์ ์ง์ ๋ฃ์ inline_data ํํธ๋ค)"""
lower = path.lower()
try:
if lower.endswith((".png", ".jpg", ".jpeg", ".webp", ".mp3", ".wav", ".m4a")):
if os.path.getsize(path) > 15 * 1024 * 1024:
return "(ํ์ผ์ด ๋๋ฌด ์ปค์ ์๋ต๋จ)", []
mime = "audio/mp3" if lower.endswith(".mp3") else (mimetypes.guess_type(path)[0] or "application/octet-stream")
with open(path, "rb") as f:
data = base64.b64encode(f.read()).decode()
return "(์ด๋ฏธ์ง/์ค๋์ค ํ์ผ. Gemini์ผ ๋๋ง ๋ด์ฉ์ ๋ณผ ์ ์์)", [{"inline_data": {"mime_type": mime, "data": data}}]
if lower.endswith((".xlsx", ".xls")):
sheets = pd.read_excel(path, sheet_name=None)
return "\n\n".join(f"## Sheet {n} (shape {df.shape})\n{df.head(25).to_string()}" for n, df in sheets.items()), []
if lower.endswith(".csv"):
df = pd.read_csv(path)
return f"shape {df.shape}\n{df.head(25).to_string()}", []
with open(path, "r", encoding="utf-8", errors="ignore") as f:
return f.read()[:12000], []
except Exception as e: # noqa: BLE001
return f"(ํ์ผ ์ฝ๊ธฐ ์คํจ: {e})", []
# ---------------------------------------------------------------------------
# ์์ด์ ํธ ๋ฃจํ
# ---------------------------------------------------------------------------
def clean_answer(ans: str) -> str:
ans = (ans.strip().splitlines() or [""])[0]
return ans.strip().strip("`").strip().strip('"').strip().rstrip(".").strip()
def parse_action(text: str):
m = re.search(r"Action:\s*([A-Za-z_]+)\s*\n?\s*Input:\s*(.*)", text, flags=re.S | re.I)
if m:
inp = re.split(r"\n\s*Observation:", m.group(2))[0].strip()
return m.group(1).lower(), inp
m = re.findall(r"FINAL ANSWER:\s*(.+)", text, flags=re.I)
if m:
return "final", m[-1].strip()
return None, ""
def solve(item: dict) -> tuple[str, str]:
"""(๋ต๋ณ, ๋น๊ณ )๋ฅผ ๋ฐํํฉ๋๋ค."""
question = item["question"]
extra_parts: list[dict] = []
file_note = ""
path = download_file(item["task_id"], item.get("file_name", ""))
if path:
preview, extra_parts = file_to_parts(path)
file_note = (f"ATTACHED FILE path: {path}\nPreview:\n{preview[:6000]}\n"
"(The file can be read by the python action at that exact path.)\n\n")
head = AGENT_PROMPT.replace("{max_steps}", str(MAX_STEPS)) + "\n\nQUESTION:\n" + question + "\n\n" + file_note
history: list[str] = []
start = time.time()
model_used, last_text = "", ""
for step in range(1, MAX_STEPS + 1):
last = step == MAX_STEPS or (time.time() - start) > QUESTION_TIMEOUT
prompt = head + "\n".join(history)
prompt += ("\n\nThis is your LAST step: reply now with Action: final." if last
else "\n\nReply with your next step (one action).")
text, model_used = call_llm([{"text": prompt}] + extra_parts)
last_text = text
action, inp = parse_action(text)
log(f" [{question[:28]}โฆ] ๋จ๊ณ {step}: {action or 'ํ์์ค๋ฅ'} {inp[:50].replace(chr(10), ' ')}")
if action == "final":
return clean_answer(inp), f"{model_used} / {step}๋จ๊ณ"
if last:
break
if action not in TOOLS:
history.append(f"[Step {step}]\n{text[:800]}\nObservation: Invalid format or action. Reply exactly with "
"Thought/Action/Input using one of: search, wiki, fetch, python, youtube, final.")
continue
obs = TOOLS[action](inp)
history.append(f"[Step {step}]\nThought/Action: {action}\nInput: {inp[:1500]}\nObservation: {obs[:OBS_CHARS]}")
# ๋ง์ง๋ง ์๋ต์์ ๋ต์ ์ต๋ํ ๊ฑด์ ธ๋
m = re.findall(r"FINAL ANSWER:\s*(.+)", last_text, flags=re.I)
fallback = clean_answer(m[-1]) if m else clean_answer(last_text.splitlines()[-1] if last_text.strip() else "unknown")
return fallback or "unknown", f"{model_used} / ๋จ๊ณ์ด๊ณผ"
# ---------------------------------------------------------------------------
# ์ฑ์ ์๋ฒ
# ---------------------------------------------------------------------------
def fetch_questions() -> list[dict]:
r = requests.get(f"{SCORING_API}/questions", timeout=30)
r.raise_for_status()
data = r.json()
if not data:
raise ValueError("์ง๋ฌธ ๋ชฉ๋ก์ด ๋น์ด ์์ต๋๋ค.")
return data
def make_df(rows: dict, order: list[str]) -> pd.DataFrame:
return pd.DataFrame([rows[t] for t in order if t in rows],
columns=["Task ID", "Question", "Submitted Answer", "OK", "Note"])
def run_batch(questions: list[dict], label: str):
"""๋ฌธํญ์ ์์๋๋ก ํ๋ฉฐ ์งํ ์ํฉ์ ๊ณ์ ๋ด๋ณด๋
๋๋ค. ๋ง์ง๋ง์ (rows, order, aborted)๋ฅผ ๋ฐํ."""
order = [q["task_id"] for q in questions if q.get("task_id")]
rows: dict = {}
cache = load_cache()
start = time.time()
fails, aborted = 0, False
log(f"{label} ์์: {len(order)}๋ฌธํญ, ๋ชจ๋ธ ์ ๊ณต์={PROVIDER}, ๋ฌธํญ๋น ์ต๋ {MAX_STEPS}๋จ๊ณ")
def status(i: int) -> str:
return (f"{label}: {len(rows)}/{len(order)} ์๋ฃ, {i}๋ฒ์งธ ๋ฌธํญ ์ฒ๋ฆฌ ์ค (๊ฒฝ๊ณผ {int(time.time() - start)}์ด)\n"
f"--- ์ต๊ทผ ๊ธฐ๋ก ---\n{recent_log()}")
for i, item in enumerate(questions, start=1):
tid = item.get("task_id")
if not tid or item.get("question") is None:
continue
yield status(i), make_df(rows, order)
if tid in cache:
answer, ok, note = cache[tid], True, "cache"
log(f"์บ์ ์ฌ์ฉ {tid[:8]}")
else:
box: dict = {}
def work(it=item):
try:
box["r"] = solve(it)
except LLMUnavailable as e:
box["llm"] = str(e)
except Exception as e: # noqa: BLE001
box["err"] = f"{type(e).__name__}: {e}"
th = threading.Thread(target=work, daemon=True)
th.start()
while th.is_alive():
th.join(2)
yield status(i), make_df(rows, order)
if "r" in box:
answer, note = box["r"]
ok, fails = True, 0
save_cache(tid, answer)
log(f"์๋ฃ {tid[:8]} -> {answer}")
elif "llm" in box:
answer, ok, note = "unknown", False, box["llm"][:250]
fails += 1
log(f"LLM ์คํจ {tid[:8]}: {note}")
else:
answer, ok, note = "unknown", False, box.get("err", "์ ์ ์๋ ์ค๋ฅ")[:250]
log(f"์ค๋ฅ {tid[:8]}: {note}")
rows[tid] = {"Task ID": tid, "Question": item["question"], "Submitted Answer": answer,
"OK": "O" if ok else "X", "Note": note}
if fails >= 2:
aborted = True
log("LLM์ด ์ฐ์ 2ํ ์คํจํ์ฌ ์ค๋จํฉ๋๋ค. (ํ๋/ํฌ๋ ๋ง ๋ฌธ์ ๊ฐ๋ฅ์ฑ)")
break
yield f"{label} ์ข
๋ฃ (๊ฒฝ๊ณผ {int(time.time() - start)}์ด)\n--- ์ต๊ทผ ๊ธฐ๋ก ---\n{recent_log()}", make_df(rows, order)
return rows, order, aborted
# ---------------------------------------------------------------------------
# Gradio ์ฝ๋ฐฑ
# ---------------------------------------------------------------------------
def run_and_submit_all(profile: gr.OAuthProfile | None):
space_id = os.getenv("SPACE_ID")
if not profile:
yield "๋จผ์ Hugging Face ๋ก๊ทธ์ธ ๋ฒํผ์ผ๋ก ๋ก๊ทธ์ธํด ์ฃผ์ธ์.", None
return
if not space_id:
yield "SPACE_ID๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค. Space ์์์ ์คํํด์ผ ํฉ๋๋ค.", None
return
yield "์ง๋ฌธ์ ๊ฐ์ ธ์ค๋ ์ค...", None
try:
questions = fetch_questions()
except Exception as e: # noqa: BLE001
yield f"์ง๋ฌธ ๊ฐ์ ธ์ค๊ธฐ ์ค๋ฅ: {e}", None
return
rows, order, aborted = yield from run_batch(questions, "๋ณธ ์คํ")
if aborted:
yield ("LLM ํ๋/ํฌ๋ ๋ง ๋ฌธ์ ๋ก ์ค๋จํ์ผ๋ฏ๋ก ์ ์ถํ์ง ์์์ต๋๋ค.\n"
"ํผ ๋ต์ ์ ์ฅ๋์ด ์์ด ํด๊ฒฐ ํ ๋ค์ ๋๋ฅด๋ฉด ์ด์ด์ ์งํํฉ๋๋ค. "
"(Space๊ฐ ์ฌ์์๋๋ฉด ์ ์ฅ๋ ๋ต์ ์ฌ๋ผ์ง๋๋ค.)\n\n" + recent_log()), make_df(rows, order)
return
payload = [{"task_id": t, "submitted_answer": rows[t]["Submitted Answer"]} for t in order if t in rows]
failed = sum(1 for r in rows.values() if r["OK"] == "X")
yield f"ํ์ด ์๋ฃ (์คํจ {failed}๊ฐ). ์ ์ถ ์ค...", make_df(rows, order)
submission = {"username": profile.username.strip(),
"agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
"answers": payload}
try:
r = requests.post(f"{SCORING_API}/submit", json=submission, timeout=120)
r.raise_for_status()
res = r.json()
status = (f"์ ์ถ ์ฑ๊ณต!\n์ฌ์ฉ์: {res.get('username')}\n"
f"์ ์: {res.get('score', 'N/A')}% ({res.get('correct_count', '?')}/{res.get('total_attempted', '?')} ์ ๋ต)\n"
f"๋ฉ์์ง: {res.get('message', '')}")
except requests.exceptions.HTTPError as e:
status = f"์ ์ถ ์คํจ: {e.response.text[:500] if e.response is not None else e}"
except Exception as e: # noqa: BLE001
status = f"์ ์ถ ์ค ์ค๋ฅ: {e}"
yield status, make_df(rows, order)
def run_test_only(n_questions: int):
yield "์ง๋ฌธ์ ๊ฐ์ ธ์ค๋ ์ค...", None
try:
questions = fetch_questions()[: int(n_questions)]
except Exception as e: # noqa: BLE001
yield f"์ค๋น ์ค ์ค๋ฅ: {e}", None
return
yield from run_batch(questions, "ํ
์คํธ")
def diagnose():
lines = [f"PROVIDER={PROVIDER}, MAX_STEPS={MAX_STEPS}, MIN_INTERVAL={MIN_INTERVAL}์ด, QUESTION_TIMEOUT={QUESTION_TIMEOUT}์ด"]
yield "\n".join(lines + ["", "๋ชจ๋ธ ํ์ธ ์ค..."])
if PROVIDER == "hf":
lines.append(f"HF_TOKEN: {'์์' if hf_token() else '์์'}, ๋ชจ๋ธ: {HF_MODELS}")
try:
r = requests.get(f"{HF_ROUTER}/models", headers={"Authorization": f"Bearer {hf_token()}"}, timeout=30)
r.raise_for_status()
ids = [m.get("id") for m in r.json().get("data", [])]
lines.append("1) ๋ชจ๋ธ ๋ชฉ๋ก: " + ", ".join(f"{m}={'์์' if m in ids else '๋ชฉ๋ก์ ์์'}" for m in HF_MODELS))
except Exception as e: # noqa: BLE001
lines.append(f"1) ๋ชจ๋ธ ๋ชฉ๋ก ์กฐํ ์คํจ(์งํ์ ๊ณ์): {type(e).__name__}: {str(e)[:150]}")
else:
lines.append(f"GEMINI_API_KEY: {'์์' if api_key() else '์์'}")
try:
lines.append("1) ์ฌ์ฉ ๊ฐ๋ฅํ Gemini ๋ชจ๋ธ(์ผ๋ถ): " + ", ".join([n for n in list_models() if n.startswith('gemini')][:25]))
lines.append(f" ์ฌ์ฉํ ํ๋ณด ์์: {candidate_models()}")
except Exception as e: # noqa: BLE001
lines.append(f"1) ๋ชจ๋ธ ๋ชฉ๋ก ์กฐํ ์คํจ: {type(e).__name__}: {str(e)[:200]}")
yield "\n".join(lines)
return
yield "\n".join(lines + ["", "LLM ํธ์ถ ํ
์คํธ ์ค..."])
try:
text, model = call_llm([{"text": "Reply with the single word OK."}])
lines.append(f"2) LLM ํธ์ถ: ์ ์ (๋ชจ๋ธ {model}, ์๋ต '{text.strip()[:30]}')")
except LLMUnavailable as e:
lines.append(f"2) LLM ํธ์ถ: ์คํจ - {str(e)[:300]}")
yield "\n".join(lines + ["", "๋๊ตฌ ํ
์คํธ ์ค..."])
s = tool_search("Hugging Face")
lines.append(f"3) ์น ๊ฒ์: {'์ ์' if len(s) > 100 else '์คํจ/๊ฒฐ๊ณผ ๋ถ์กฑ'} ({len(s)}์)")
w = tool_wiki("Mercedes Sosa | studio album")
lines.append(f"4) ์ํค๋ฐฑ๊ณผ: {'์ ์' if 'Wikipedia:' in w[:30] else '์คํจ'} ({len(w)}์) {'' if 'Wikipedia:' in w[:30] else w[:100]}")
p = tool_python("print(sum(range(1, 11)))")
lines.append(f"5) ํ์ด์ฌ ์คํ: {'์ ์' if p.strip() == '55' else '์ด์ - ' + p[:100]}")
yield "\n".join(lines)
def clear_cache():
global _candidates
_candidates = []
try:
os.remove(CACHE_PATH)
return "์บ์์ ๋ชจ๋ธ ์ ํ ์ ๋ณด๋ฅผ ์ด๊ธฐํํ์ต๋๋ค."
except FileNotFoundError:
return "์ญ์ ํ ์บ์๊ฐ ์์ต๋๋ค. (๋ชจ๋ธ ์ ํ ์ ๋ณด๋ ์ด๊ธฐํ๋จ)"
# ---------------------------------------------------------------------------
# UI
# ---------------------------------------------------------------------------
with gr.Blocks() as demo:
gr.Markdown("# Basic Agent Evaluation Runner (๋ค๋จ๊ณ ์์ด์ ํธ ๋ฒ์ )")
gr.Markdown(
"""**์ฌ์ฉ ์์**
1. '์ฐ๊ฒฐ ์ง๋จ'์ผ๋ก ๋ชจ๋ธ๊ณผ ๋๊ตฌ(๊ฒ์, ์ํค, ํ์ด์ฌ)๊ฐ ์ ์์ธ์ง ํ์ธํฉ๋๋ค.
2. ๋ก๊ทธ์ธ ํ 'ํ
์คํธ ์คํ'(1~2๋ฌธํญ)์ผ๋ก ํ์ธํฉ๋๋ค. (์ ์ถ ์ ํจ)
3. ๋ฌธ์ ์์ผ๋ฉด '์บ์ ์ด๊ธฐํ' ํ 'Run Evaluation & Submit All Answers'๋ฅผ ๋๋ฆ
๋๋ค."""
)
gr.LoginButton()
with gr.Row():
diag_button = gr.Button("์ฐ๊ฒฐ ์ง๋จ")
test_n = gr.Number(value=2, label="ํ
์คํธํ ๋ฌธํญ ์ (์ ์ถ ์ ํจ)", precision=0)
test_button = gr.Button("ํ
์คํธ ์คํ (์ ์ถ ์ ํจ)")
cache_button = gr.Button("์บ์ ์ด๊ธฐํ")
run_button = gr.Button("Run Evaluation & Submit All Answers")
status_output = gr.Textbox(label="Run Status / Submission Result", lines=16, interactive=False)
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
diag_button.click(fn=diagnose, outputs=[status_output])
test_button.click(fn=run_test_only, inputs=[test_n], outputs=[status_output, results_table])
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
cache_button.click(fn=clear_cache, outputs=[status_output])
if __name__ == "__main__":
demo.queue().launch(debug=True, share=False) |