omega21's picture
Update app.py
a212dc5 verified
Raw History Blame Contribute Delete
32.4 kB
"""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("&nbsp;", " ").replace("&#160;", " ").replace("&amp;", "&")
.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", '"').replace("&#39;", "'"))
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)