Spaces:
Sleeping
Update app.py
Browse files"""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
|
@@ -1,13 +1,17 @@
|
|
| 1 |
-
"""HF Agents Course ์ต์ข
๊ณผ์ - Gemini ๋๋ Hugging Face
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
| 5 |
"""
|
| 6 |
import base64
|
| 7 |
import json
|
| 8 |
import mimetypes
|
| 9 |
import os
|
| 10 |
import re
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
import time
|
| 12 |
from collections import deque
|
| 13 |
|
|
@@ -38,40 +42,51 @@ except ImportError:
|
|
| 38 |
# ---------------------------------------------------------------------------
|
| 39 |
SCORING_API = "https://agents-course-unit4-scoring.hf.space"
|
| 40 |
GEMINI_API = "https://generativelanguage.googleapis.com/v1beta"
|
|
|
|
| 41 |
FILES_DIR = "/tmp/task_files"
|
| 42 |
-
CACHE_PATH = "/tmp/
|
| 43 |
os.makedirs(FILES_DIR, exist_ok=True)
|
| 44 |
|
| 45 |
PROVIDER = (os.getenv("PROVIDER", "") or ("gemini" if os.getenv("GEMINI_API_KEY") else "hf")).lower() # gemini | hf
|
| 46 |
-
MIN_INTERVAL = float(os.getenv("MIN_INTERVAL", "7" if PROVIDER == "gemini" else "
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
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()]
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
-
Rules:
|
| 58 |
-
-
|
| 59 |
-
- Give ONLY the answer value: no explanation, no trailing period, no units unless asked.
|
| 60 |
- Numbers: digits only, no thousands separators, no currency or percent symbols unless asked.
|
| 61 |
- Lists: comma-separated, in the order the question asks.
|
| 62 |
-
- Strings: no leading articles (a, an, the)
|
| 63 |
-
-
|
| 64 |
-
FINAL ANSWER: <answer>
|
| 65 |
|
| 66 |
-
|
| 67 |
-
{question}
|
| 68 |
-
|
| 69 |
-
{extra}"""
|
| 70 |
|
| 71 |
# ---------------------------------------------------------------------------
|
| 72 |
-
# ๋ก๊ทธ
|
| 73 |
# ---------------------------------------------------------------------------
|
| 74 |
-
_events = deque(maxlen=
|
| 75 |
|
| 76 |
|
| 77 |
def log(msg: str):
|
|
@@ -84,9 +99,6 @@ def recent_log() -> str:
|
|
| 84 |
return "\n".join(_events)
|
| 85 |
|
| 86 |
|
| 87 |
-
# ---------------------------------------------------------------------------
|
| 88 |
-
# ์บ์
|
| 89 |
-
# ---------------------------------------------------------------------------
|
| 90 |
def load_cache() -> dict:
|
| 91 |
try:
|
| 92 |
with open(CACHE_PATH, "r", encoding="utf-8") as f:
|
|
@@ -103,29 +115,36 @@ def save_cache(task_id: str, answer: str):
|
|
| 103 |
|
| 104 |
|
| 105 |
# ---------------------------------------------------------------------------
|
| 106 |
-
#
|
| 107 |
# ---------------------------------------------------------------------------
|
| 108 |
class LLMUnavailable(Exception):
|
| 109 |
pass
|
| 110 |
|
| 111 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
def api_key() -> str:
|
| 113 |
return os.getenv("GEMINI_API_KEY", "")
|
| 114 |
|
| 115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
def list_models() -> list[str]:
|
| 117 |
-
r = requests.get(
|
| 118 |
-
f"{GEMINI_API}/models",
|
| 119 |
-
headers={"x-goog-api-key": api_key()},
|
| 120 |
-
params={"pageSize": 200},
|
| 121 |
-
timeout=30,
|
| 122 |
-
)
|
| 123 |
r.raise_for_status()
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
if "generateContent" in m.get("supportedGenerationMethods", []):
|
| 127 |
-
names.append(m["name"].replace("models/", ""))
|
| 128 |
-
return names
|
| 129 |
|
| 130 |
|
| 131 |
_BAD = ("image", "tts", "audio", "live", "embed", "vision", "robotics", "computer", "imagen", "veo")
|
|
@@ -133,7 +152,6 @@ _candidates: list[str] = []
|
|
| 133 |
|
| 134 |
|
| 135 |
def candidate_models() -> list[str]:
|
| 136 |
-
"""GEMINI_MODELS๊ฐ ์์ผ๋ฉด ๊ทธ ๋ชฉ๋ก, ์์ผ๋ฉด ํค๋ก ์ธ ์ ์๋ ๋ชจ๋ธ์์ ์๋ ์ ํ."""
|
| 137 |
global _candidates
|
| 138 |
if _candidates:
|
| 139 |
return _candidates
|
|
@@ -144,23 +162,11 @@ def candidate_models() -> list[str]:
|
|
| 144 |
lite = [n for n in names if "flash-lite" in n]
|
| 145 |
flash = [n for n in names if "flash" in n and "flash-lite" not in n]
|
| 146 |
_candidates = (lite[:2] + flash[:2]) or names[:3]
|
| 147 |
-
log(f"์๋ ์ ํ๋ ๋ชจ๋ธ ํ๋ณด: {_candidates}")
|
| 148 |
return _candidates
|
| 149 |
|
| 150 |
|
| 151 |
-
_last_call = 0.0
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
def throttle():
|
| 155 |
-
global _last_call
|
| 156 |
-
wait = MIN_INTERVAL - (time.time() - _last_call)
|
| 157 |
-
if wait > 0:
|
| 158 |
-
time.sleep(wait)
|
| 159 |
-
_last_call = time.time()
|
| 160 |
-
|
| 161 |
-
|
| 162 |
def call_gemini(parts: list[dict]) -> tuple[str, str]:
|
| 163 |
-
"""(์๋ต ํ
์คํธ, ์ฌ์ฉํ ๋ชจ๋ธ)์ ๋ฐํ. ๋ชจ๋ ํ๋ณด๊ฐ ์คํจํ๋ฉด LLMUnavailable."""
|
| 164 |
if not api_key():
|
| 165 |
raise LLMUnavailable("GEMINI_API_KEY๊ฐ ์ค์ ๋์ง ์์์ต๋๋ค.")
|
| 166 |
last_err = ""
|
|
@@ -171,33 +177,24 @@ def call_gemini(parts: list[dict]) -> tuple[str, str]:
|
|
| 171 |
r = requests.post(
|
| 172 |
f"{GEMINI_API}/models/{model}:generateContent",
|
| 173 |
headers={"x-goog-api-key": api_key(), "Content-Type": "application/json"},
|
| 174 |
-
json={
|
| 175 |
-
|
| 176 |
-
"generationConfig": {"temperature": 0, "maxOutputTokens": 2048},
|
| 177 |
-
},
|
| 178 |
timeout=120,
|
| 179 |
)
|
| 180 |
except requests.RequestException as e:
|
| 181 |
last_err = f"{model}: ๋คํธ์ํฌ ์ค๋ฅ {e}"
|
| 182 |
time.sleep(5)
|
| 183 |
continue
|
| 184 |
-
|
| 185 |
if r.status_code == 200:
|
| 186 |
cand = (r.json().get("candidates") or [{}])[0]
|
| 187 |
-
text = "".join(
|
| 188 |
-
p.get("text", "")
|
| 189 |
-
for p in cand.get("content", {}).get("parts", [])
|
| 190 |
-
if not p.get("thought")
|
| 191 |
-
)
|
| 192 |
if text.strip():
|
| 193 |
return text, model
|
| 194 |
last_err = f"{model}: ๋น ์๋ต({cand.get('finishReason')})"
|
| 195 |
break
|
| 196 |
-
|
| 197 |
body = r.text
|
| 198 |
last_err = f"{model}: HTTP {r.status_code} {body[:180].replace(chr(10), ' ')}"
|
| 199 |
if r.status_code == 429:
|
| 200 |
-
# ๏ฟฝ๏ฟฝ์ผ ํ๋ ์์ง ๋๋ ํ๋ 0์ด๋ฉด ์ฌ์๋ํด๋ ์์ฉ์์ผ๋ฏ๋ก ๋ค์ ๋ชจ๋ธ๋ก
|
| 201 |
if "PerDay" in body or "limit: 0" in body:
|
| 202 |
log(f"{model}: ์ผ์ผ ํ๋ ์์ง ๋๋ ํ๋ 0 -> ๋ค์ ๋ชจ๋ธ")
|
| 203 |
break
|
|
@@ -211,25 +208,16 @@ def call_gemini(parts: list[dict]) -> tuple[str, str]:
|
|
| 211 |
if r.status_code >= 500:
|
| 212 |
time.sleep(5)
|
| 213 |
continue
|
| 214 |
-
break
|
| 215 |
raise LLMUnavailable(last_err or "์ฌ์ฉ ๊ฐ๋ฅํ ๋ชจ๋ธ์ด ์์ต๋๋ค.")
|
| 216 |
|
| 217 |
|
| 218 |
-
# ---------------------------------------------------------------------------
|
| 219 |
-
# Hugging Face Inference Providers (OpenAI ํธํ ๋ผ์ฐํฐ)
|
| 220 |
-
# ---------------------------------------------------------------------------
|
| 221 |
-
def hf_token() -> str:
|
| 222 |
-
return os.getenv("HF_TOKEN", "")
|
| 223 |
-
|
| 224 |
-
|
| 225 |
def call_hf(parts: list[dict]) -> tuple[str, str]:
|
| 226 |
-
"""(์๋ต ํ
์คํธ, ์ฌ์ฉํ ๋ชจ๋ธ)์ ๋ฐํ. ํ
์คํธ ์ ์ฉ์ด๋ฏ๋ก ์ด๋ฏธ์ง/์ค๋์ค ํํธ๋ ์ ๋ฌํ์ง ๋ชปํฉ๋๋ค."""
|
| 227 |
if not hf_token():
|
| 228 |
raise LLMUnavailable("HF_TOKEN์ด ์ค์ ๋์ง ์์์ต๋๋ค.")
|
| 229 |
text = "\n".join(p["text"] for p in parts if "text" in p)
|
| 230 |
if any("inline_data" in p for p in parts):
|
| 231 |
-
text =
|
| 232 |
-
"answer from the other information.\n\n" + text)
|
| 233 |
last_err = ""
|
| 234 |
for model in HF_MODELS:
|
| 235 |
for attempt in range(MAX_RETRY + 1):
|
|
@@ -239,7 +227,7 @@ def call_hf(parts: list[dict]) -> tuple[str, str]:
|
|
| 239 |
f"{HF_ROUTER}/chat/completions",
|
| 240 |
headers={"Authorization": f"Bearer {hf_token()}", "Content-Type": "application/json"},
|
| 241 |
json={"model": model, "messages": [{"role": "user", "content": text}],
|
| 242 |
-
"max_tokens":
|
| 243 |
timeout=120,
|
| 244 |
)
|
| 245 |
except requests.RequestException as e:
|
|
@@ -256,9 +244,9 @@ def call_hf(parts: list[dict]) -> tuple[str, str]:
|
|
| 256 |
body = r.text
|
| 257 |
last_err = f"{model}: HTTP {r.status_code} {body[:180].replace(chr(10), ' ')}"
|
| 258 |
if r.status_code == 402:
|
| 259 |
-
raise LLMUnavailable("HF
|
| 260 |
if r.status_code in (401, 403):
|
| 261 |
-
raise LLMUnavailable(f"HF_TOKEN ์ธ์ฆ/๊ถํ ์ค๋ฅ({r.status_code}).
|
| 262 |
if r.status_code == 429:
|
| 263 |
if attempt == MAX_RETRY:
|
| 264 |
break
|
|
@@ -269,7 +257,7 @@ def call_hf(parts: list[dict]) -> tuple[str, str]:
|
|
| 269 |
if r.status_code >= 500:
|
| 270 |
time.sleep(5)
|
| 271 |
continue
|
| 272 |
-
break
|
| 273 |
raise LLMUnavailable(last_err or "์ฌ์ฉ ๊ฐ๋ฅํ ๋ชจ๋ธ์ด ์์ต๋๋ค.")
|
| 274 |
|
| 275 |
|
|
@@ -278,39 +266,148 @@ def call_llm(parts: list[dict]) -> tuple[str, str]:
|
|
| 278 |
|
| 279 |
|
| 280 |
# ---------------------------------------------------------------------------
|
| 281 |
-
#
|
| 282 |
# ---------------------------------------------------------------------------
|
| 283 |
def html_to_text(html: str) -> str:
|
| 284 |
html = re.sub(r"(?is)<(script|style|noscript|svg|header|footer|nav)[^>]*>.*?</\1>", " ", html)
|
|
|
|
|
|
|
|
|
|
| 285 |
text = re.sub(r"(?s)<[^>]+>", " ", html)
|
| 286 |
-
text =
|
| 287 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
|
| 289 |
|
| 290 |
-
def
|
| 291 |
if DDGS is None:
|
| 292 |
-
return ""
|
| 293 |
try:
|
| 294 |
results = list(DDGS().text(query, max_results=6))
|
| 295 |
except Exception as e: # noqa: BLE001
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
try:
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
|
| 313 |
|
|
|
|
|
|
|
| 314 |
# ---------------------------------------------------------------------------
|
| 315 |
# ์ฒจ๋ถ ํ์ผ
|
| 316 |
# ---------------------------------------------------------------------------
|
|
@@ -330,67 +427,88 @@ def download_file(task_id: str, file_name: str):
|
|
| 330 |
|
| 331 |
|
| 332 |
def file_to_parts(path: str) -> tuple[str, list[dict]]:
|
| 333 |
-
"""(
|
| 334 |
lower = path.lower()
|
| 335 |
try:
|
| 336 |
if lower.endswith((".png", ".jpg", ".jpeg", ".webp", ".mp3", ".wav", ".m4a")):
|
| 337 |
if os.path.getsize(path) > 15 * 1024 * 1024:
|
| 338 |
-
return "(
|
| 339 |
-
mime = mimetypes.guess_type(path)[0] or "application/octet-stream"
|
| 340 |
-
if lower.endswith(".mp3"):
|
| 341 |
-
mime = "audio/mp3"
|
| 342 |
with open(path, "rb") as f:
|
| 343 |
data = base64.b64encode(f.read()).decode()
|
| 344 |
-
return "(
|
| 345 |
if lower.endswith((".xlsx", ".xls")):
|
| 346 |
sheets = pd.read_excel(path, sheet_name=None)
|
| 347 |
-
return "\n\n".join(f"## Sheet {n}\n{df.to_string(
|
| 348 |
if lower.endswith(".csv"):
|
| 349 |
-
|
|
|
|
| 350 |
with open(path, "r", encoding="utf-8", errors="ignore") as f:
|
| 351 |
-
return f.read()[:
|
| 352 |
except Exception as e: # noqa: BLE001
|
| 353 |
return f"(ํ์ผ ์ฝ๊ธฐ ์คํจ: {e})", []
|
| 354 |
|
| 355 |
|
| 356 |
# ---------------------------------------------------------------------------
|
| 357 |
-
#
|
| 358 |
# ---------------------------------------------------------------------------
|
| 359 |
-
def
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
return ans.strip().strip("`").strip().rstrip(".").strip()
|
| 363 |
|
| 364 |
|
| 365 |
-
def
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
|
| 375 |
|
| 376 |
def solve(item: dict) -> tuple[str, str]:
|
| 377 |
-
"""(๋ต๋ณ,
|
| 378 |
question = item["question"]
|
| 379 |
extra_parts: list[dict] = []
|
| 380 |
-
|
| 381 |
-
|
| 382 |
path = download_file(item["task_id"], item.get("file_name", ""))
|
| 383 |
if path:
|
| 384 |
-
|
| 385 |
-
|
|
|
|
| 386 |
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 390 |
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
|
|
|
| 394 |
|
| 395 |
|
| 396 |
# ---------------------------------------------------------------------------
|
|
@@ -406,49 +524,64 @@ def fetch_questions() -> list[dict]:
|
|
| 406 |
|
| 407 |
|
| 408 |
def make_df(rows: dict, order: list[str]) -> pd.DataFrame:
|
| 409 |
-
return pd.DataFrame(
|
| 410 |
-
|
| 411 |
-
columns=["Task ID", "Question", "Submitted Answer", "OK", "Note"],
|
| 412 |
-
)
|
| 413 |
|
| 414 |
|
| 415 |
def run_batch(questions: list[dict], label: str):
|
| 416 |
-
"""๋ฌธํญ์ ์์๋๋ก ํ๋ฉฐ ์งํ ์ํฉ์ ๋ด๋ณด๋
๋๋ค. ๋ง์ง๋ง์ (rows, order, aborted)๋ฅผ ๋ฐํ."""
|
| 417 |
order = [q["task_id"] for q in questions if q.get("task_id")]
|
| 418 |
rows: dict = {}
|
| 419 |
cache = load_cache()
|
| 420 |
start = time.time()
|
| 421 |
-
fails = 0
|
| 422 |
-
|
| 423 |
-
|
|
|
|
|
|
|
|
|
|
| 424 |
|
| 425 |
for i, item in enumerate(questions, start=1):
|
| 426 |
tid = item.get("task_id")
|
| 427 |
if not tid or item.get("question") is None:
|
| 428 |
continue
|
| 429 |
-
|
| 430 |
-
yield f"{head}\n--- ์ต๊ทผ ๊ธฐ๋ก ---\n{recent_log()}", make_df(rows, order)
|
| 431 |
|
| 432 |
if tid in cache:
|
| 433 |
answer, ok, note = cache[tid], True, "cache"
|
| 434 |
log(f"์บ์ ์ฌ์ฉ {tid[:8]}")
|
| 435 |
else:
|
| 436 |
-
|
| 437 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 438 |
save_cache(tid, answer)
|
| 439 |
-
ok, note = True, model
|
| 440 |
-
fails = 0
|
| 441 |
log(f"์๋ฃ {tid[:8]} -> {answer}")
|
| 442 |
-
|
| 443 |
-
answer, ok, note = "unknown", False,
|
| 444 |
fails += 1
|
| 445 |
log(f"LLM ์คํจ {tid[:8]}: {note}")
|
| 446 |
-
|
| 447 |
-
answer, ok, note = "unknown", False,
|
| 448 |
log(f"์ค๋ฅ {tid[:8]}: {note}")
|
| 449 |
|
| 450 |
-
rows[tid] = {"Task ID": tid, "Question": item["question"],
|
| 451 |
-
"
|
| 452 |
if fails >= 2:
|
| 453 |
aborted = True
|
| 454 |
log("LLM์ด ์ฐ์ 2ํ ์คํจํ์ฌ ์ค๋จํฉ๋๋ค. (ํ๋/ํฌ๋ ๋ง ๋ฌธ์ ๊ฐ๋ฅ์ฑ)")
|
|
@@ -479,18 +612,16 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 479 |
rows, order, aborted = yield from run_batch(questions, "๋ณธ ์คํ")
|
| 480 |
if aborted:
|
| 481 |
yield ("LLM ํ๋/ํฌ๋ ๋ง ๋ฌธ์ ๋ก ์ค๋จํ์ผ๋ฏ๋ก ์ ์ถํ์ง ์์์ต๋๋ค.\n"
|
| 482 |
-
"ํผ ๋ต์ ์ ์ฅ๋์ด ์์ด
|
| 483 |
"(Space๊ฐ ์ฌ์์๋๋ฉด ์ ์ฅ๋ ๋ต์ ์ฌ๋ผ์ง๋๋ค.)\n\n" + recent_log()), make_df(rows, order)
|
| 484 |
return
|
| 485 |
|
| 486 |
payload = [{"task_id": t, "submitted_answer": rows[t]["Submitted Answer"]} for t in order if t in rows]
|
| 487 |
failed = sum(1 for r in rows.values() if r["OK"] == "X")
|
| 488 |
yield f"ํ์ด ์๋ฃ (์คํจ {failed}๊ฐ). ์ ์ถ ์ค...", make_df(rows, order)
|
| 489 |
-
submission = {
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
"answers": payload,
|
| 493 |
-
}
|
| 494 |
try:
|
| 495 |
r = requests.post(f"{SCORING_API}/submit", json=submission, timeout=120)
|
| 496 |
r.raise_for_status()
|
|
@@ -516,23 +647,21 @@ def run_test_only(n_questions: int):
|
|
| 516 |
|
| 517 |
|
| 518 |
def diagnose():
|
| 519 |
-
lines = [f"PROVIDER={PROVIDER}, MIN_INTERVAL={MIN_INTERVAL}์ด,
|
| 520 |
yield "\n".join(lines + ["", "๋ชจ๋ธ ํ์ธ ์ค..."])
|
| 521 |
if PROVIDER == "hf":
|
| 522 |
-
lines.append(f"HF_TOKEN: {'์์' if hf_token() else '์์'},
|
| 523 |
try:
|
| 524 |
r = requests.get(f"{HF_ROUTER}/models", headers={"Authorization": f"Bearer {hf_token()}"}, timeout=30)
|
| 525 |
r.raise_for_status()
|
| 526 |
ids = [m.get("id") for m in r.json().get("data", [])]
|
| 527 |
-
|
| 528 |
-
lines.append(f"1) ๋ผ์ฐํฐ ์ ๊ณต ๋ชจ๋ธ {len(ids)}๊ฐ / {check}")
|
| 529 |
except Exception as e: # noqa: BLE001
|
| 530 |
lines.append(f"1) ๋ชจ๋ธ ๋ชฉ๋ก ์กฐํ ์คํจ(์งํ์ ๊ณ์): {type(e).__name__}: {str(e)[:150]}")
|
| 531 |
else:
|
| 532 |
lines.append(f"GEMINI_API_KEY: {'์์' if api_key() else '์์'}")
|
| 533 |
try:
|
| 534 |
-
|
| 535 |
-
lines.append("1) ์ด ํค๋ก ์ฌ์ฉ ๊ฐ๋ฅํ ๋ชจ๋ธ(์ผ๋ถ): " + ", ".join(names))
|
| 536 |
lines.append(f" ์ฌ์ฉํ ํ๋ณด ์์: {candidate_models()}")
|
| 537 |
except Exception as e: # noqa: BLE001
|
| 538 |
lines.append(f"1) ๋ชจ๋ธ ๋ชฉ๋ก ์กฐํ ์คํจ: {type(e).__name__}: {str(e)[:200]}")
|
|
@@ -544,12 +673,13 @@ def diagnose():
|
|
| 544 |
lines.append(f"2) LLM ํธ์ถ: ์ ์ (๋ชจ๋ธ {model}, ์๋ต '{text.strip()[:30]}')")
|
| 545 |
except LLMUnavailable as e:
|
| 546 |
lines.append(f"2) LLM ํธ์ถ: ์คํจ - {str(e)[:300]}")
|
| 547 |
-
yield "\n".join(lines + ["", "
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
|
|
|
| 553 |
yield "\n".join(lines)
|
| 554 |
|
| 555 |
|
|
@@ -567,12 +697,12 @@ def clear_cache():
|
|
| 567 |
# UI
|
| 568 |
# ---------------------------------------------------------------------------
|
| 569 |
with gr.Blocks() as demo:
|
| 570 |
-
gr.Markdown("# Basic Agent Evaluation Runner (
|
| 571 |
gr.Markdown(
|
| 572 |
"""**์ฌ์ฉ ์์**
|
| 573 |
-
1. '์ฐ๊ฒฐ ์ง๋จ'์ผ๋ก ๋ชจ๋ธ๊ณผ
|
| 574 |
2. ๋ก๊ทธ์ธ ํ 'ํ
์คํธ ์คํ'(1~2๋ฌธํญ)์ผ๋ก ํ์ธํฉ๋๋ค. (์ ์ถ ์ ํจ)
|
| 575 |
-
3. ๋ฌธ์ ์์ผ๋ฉด 'Run Evaluation & Submit All Answers'๋ฅผ ๋๋ฆ
๋๋ค."""
|
| 576 |
)
|
| 577 |
gr.LoginButton()
|
| 578 |
with gr.Row():
|
|
@@ -581,7 +711,7 @@ with gr.Blocks() as demo:
|
|
| 581 |
test_button = gr.Button("ํ
์คํธ ์คํ (์ ์ถ ์ ํจ)")
|
| 582 |
cache_button = gr.Button("์บ์ ์ด๊ธฐํ")
|
| 583 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 584 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=
|
| 585 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 586 |
|
| 587 |
diag_button.click(fn=diagnose, outputs=[status_output])
|
|
|
|
| 1 |
+
"""HF Agents Course ์ต์ข
๊ณผ์ - ๋ค๋จ๊ณ ์์ด์ ํธ ๋ฒ์ (Gemini ๋๋ Hugging Face)
|
| 2 |
|
| 3 |
+
LLM์ด ํ ๋จ๊ณ์ ํ๋์ ๋๊ตฌ๋ฅผ ๊ณจ๋ผ ์ฐ๊ณ (๊ฒ์/์ํค/์นํ์ด์ง/ํ์ด์ฌ/์ ํ๋ธ ์๋ง), ๊ฒฐ๊ณผ๋ฅผ ๋ณด๊ณ ๋ค์ ๋จ๊ณ๋ฅผ ์ ํฉ๋๋ค.
|
| 4 |
+
์ต๋ MAX_STEPS ๋จ๊ณ ์์ ์ต์ข
๋ต์ ๋ด๋๋ก ์ ํํด ๋น์ฉ์ ํต์ ํฉ๋๋ค.
|
| 5 |
"""
|
| 6 |
import base64
|
| 7 |
import json
|
| 8 |
import mimetypes
|
| 9 |
import os
|
| 10 |
import re
|
| 11 |
+
import subprocess
|
| 12 |
+
import sys
|
| 13 |
+
import tempfile
|
| 14 |
+
import threading
|
| 15 |
import time
|
| 16 |
from collections import deque
|
| 17 |
|
|
|
|
| 42 |
# ---------------------------------------------------------------------------
|
| 43 |
SCORING_API = "https://agents-course-unit4-scoring.hf.space"
|
| 44 |
GEMINI_API = "https://generativelanguage.googleapis.com/v1beta"
|
| 45 |
+
HF_ROUTER = "https://router.huggingface.co/v1"
|
| 46 |
FILES_DIR = "/tmp/task_files"
|
| 47 |
+
CACHE_PATH = "/tmp/answers_cache_v4.json"
|
| 48 |
os.makedirs(FILES_DIR, exist_ok=True)
|
| 49 |
|
| 50 |
PROVIDER = (os.getenv("PROVIDER", "") or ("gemini" if os.getenv("GEMINI_API_KEY") else "hf")).lower() # gemini | hf
|
| 51 |
+
MIN_INTERVAL = float(os.getenv("MIN_INTERVAL", "7" if PROVIDER == "gemini" else "1")) # LLM ํธ์ถ ๊ฐ ์ต์ ๊ฐ๊ฒฉ(์ด)
|
| 52 |
+
MAX_RETRY = int(os.getenv("MAX_RETRY", "3")) # 429 ์ฌ์๋ ํ์
|
| 53 |
+
MAX_STEPS = int(os.getenv("MAX_STEPS", "6")) # ๋ฌธํญ๋น ์ต๋ ๋จ๊ณ(=์ต๋ LLM ํธ์ถ ์)
|
| 54 |
+
QUESTION_TIMEOUT = int(os.getenv("QUESTION_TIMEOUT", "240")) # ๋ฌธํญ๋น ๋ชฉํ ์ ํ ์๊ฐ(์ด). ๋์ผ๋ฉด ๋ฐ๋ก ๋ต์ ๋ด๊ฒ ํจ
|
| 55 |
+
OBS_CHARS = int(os.getenv("OBS_CHARS", "6000")) # ๋๊ตฌ ๊ฒฐ๊ณผ 1ํ ์ต๋ ๊ธ์ ์
|
| 56 |
+
PY_TIMEOUT = int(os.getenv("PY_TIMEOUT", "25")) # ํ์ด์ฌ ์คํ ์ ํ ์๊ฐ(์ด)
|
| 57 |
+
GEMINI_MODELS = os.getenv("GEMINI_MODELS", "") # ์ ํ: ์ผํ๋ก ๊ตฌ๋ถํ Gemini ๋ชจ๋ธ ๋ชฉ๋ก
|
| 58 |
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()]
|
| 59 |
+
UA = {"User-Agent": "Mozilla/5.0 (agents-course-runner)"}
|
| 60 |
+
|
| 61 |
+
AGENT_PROMPT = """You are a careful research agent solving a GAIA-style benchmark question. The final answer is graded by EXACT MATCH.
|
| 62 |
+
|
| 63 |
+
You work in steps. In each turn reply with EXACTLY ONE action, in this format and nothing else:
|
| 64 |
+
|
| 65 |
+
Thought: <short reasoning>
|
| 66 |
+
Action: <search|wiki|fetch|python|youtube|final>
|
| 67 |
+
Input: <input for the action>
|
| 68 |
|
| 69 |
+
Actions:
|
| 70 |
+
- search: Input = a web search query. Returns titles, URLs and snippets.
|
| 71 |
+
- 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.
|
| 72 |
+
- fetch: Input = a URL, or "URL | keyword". Returns the page text.
|
| 73 |
+
- 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.
|
| 74 |
+
- youtube: Input = a YouTube URL. Returns the transcript if available.
|
| 75 |
+
- final: Input = ONLY the final answer value.
|
| 76 |
|
| 77 |
+
Rules for the final answer:
|
| 78 |
+
- Output only the answer value: no explanation, no trailing period, no units unless asked.
|
|
|
|
| 79 |
- Numbers: digits only, no thousands separators, no currency or percent symbols unless asked.
|
| 80 |
- Lists: comma-separated, in the order the question asks.
|
| 81 |
+
- Strings: no leading articles (a, an, the) and no abbreviations unless asked.
|
| 82 |
+
- Follow any formatting instruction inside the question exactly.
|
|
|
|
| 83 |
|
| 84 |
+
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."""
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
# ---------------------------------------------------------------------------
|
| 87 |
+
# ๋ก๊ทธ / ์บ์
|
| 88 |
# ---------------------------------------------------------------------------
|
| 89 |
+
_events = deque(maxlen=14)
|
| 90 |
|
| 91 |
|
| 92 |
def log(msg: str):
|
|
|
|
| 99 |
return "\n".join(_events)
|
| 100 |
|
| 101 |
|
|
|
|
|
|
|
|
|
|
| 102 |
def load_cache() -> dict:
|
| 103 |
try:
|
| 104 |
with open(CACHE_PATH, "r", encoding="utf-8") as f:
|
|
|
|
| 115 |
|
| 116 |
|
| 117 |
# ---------------------------------------------------------------------------
|
| 118 |
+
# LLM ํธ์ถ (Gemini REST / Hugging Face ๋ผ์ฐํฐ)
|
| 119 |
# ---------------------------------------------------------------------------
|
| 120 |
class LLMUnavailable(Exception):
|
| 121 |
pass
|
| 122 |
|
| 123 |
|
| 124 |
+
_last_call = 0.0
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def throttle():
|
| 128 |
+
global _last_call
|
| 129 |
+
wait = MIN_INTERVAL - (time.time() - _last_call)
|
| 130 |
+
if wait > 0:
|
| 131 |
+
time.sleep(wait)
|
| 132 |
+
_last_call = time.time()
|
| 133 |
+
|
| 134 |
+
|
| 135 |
def api_key() -> str:
|
| 136 |
return os.getenv("GEMINI_API_KEY", "")
|
| 137 |
|
| 138 |
|
| 139 |
+
def hf_token() -> str:
|
| 140 |
+
return os.getenv("HF_TOKEN", "")
|
| 141 |
+
|
| 142 |
+
|
| 143 |
def list_models() -> list[str]:
|
| 144 |
+
r = requests.get(f"{GEMINI_API}/models", headers={"x-goog-api-key": api_key()}, params={"pageSize": 200}, timeout=30)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
r.raise_for_status()
|
| 146 |
+
return [m["name"].replace("models/", "") for m in r.json().get("models", [])
|
| 147 |
+
if "generateContent" in m.get("supportedGenerationMethods", [])]
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
|
| 150 |
_BAD = ("image", "tts", "audio", "live", "embed", "vision", "robotics", "computer", "imagen", "veo")
|
|
|
|
| 152 |
|
| 153 |
|
| 154 |
def candidate_models() -> list[str]:
|
|
|
|
| 155 |
global _candidates
|
| 156 |
if _candidates:
|
| 157 |
return _candidates
|
|
|
|
| 162 |
lite = [n for n in names if "flash-lite" in n]
|
| 163 |
flash = [n for n in names if "flash" in n and "flash-lite" not in n]
|
| 164 |
_candidates = (lite[:2] + flash[:2]) or names[:3]
|
| 165 |
+
log(f"์๋ ์ ํ๋ Gemini ๋ชจ๋ธ ํ๋ณด: {_candidates}")
|
| 166 |
return _candidates
|
| 167 |
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
def call_gemini(parts: list[dict]) -> tuple[str, str]:
|
|
|
|
| 170 |
if not api_key():
|
| 171 |
raise LLMUnavailable("GEMINI_API_KEY๊ฐ ์ค์ ๋์ง ์์์ต๋๋ค.")
|
| 172 |
last_err = ""
|
|
|
|
| 177 |
r = requests.post(
|
| 178 |
f"{GEMINI_API}/models/{model}:generateContent",
|
| 179 |
headers={"x-goog-api-key": api_key(), "Content-Type": "application/json"},
|
| 180 |
+
json={"contents": [{"role": "user", "parts": parts}],
|
| 181 |
+
"generationConfig": {"temperature": 0, "maxOutputTokens": 2048}},
|
|
|
|
|
|
|
| 182 |
timeout=120,
|
| 183 |
)
|
| 184 |
except requests.RequestException as e:
|
| 185 |
last_err = f"{model}: ๋คํธ์ํฌ ์ค๋ฅ {e}"
|
| 186 |
time.sleep(5)
|
| 187 |
continue
|
|
|
|
| 188 |
if r.status_code == 200:
|
| 189 |
cand = (r.json().get("candidates") or [{}])[0]
|
| 190 |
+
text = "".join(p.get("text", "") for p in cand.get("content", {}).get("parts", []) if not p.get("thought"))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
if text.strip():
|
| 192 |
return text, model
|
| 193 |
last_err = f"{model}: ๋น ์๋ต({cand.get('finishReason')})"
|
| 194 |
break
|
|
|
|
| 195 |
body = r.text
|
| 196 |
last_err = f"{model}: HTTP {r.status_code} {body[:180].replace(chr(10), ' ')}"
|
| 197 |
if r.status_code == 429:
|
|
|
|
| 198 |
if "PerDay" in body or "limit: 0" in body:
|
| 199 |
log(f"{model}: ์ผ์ผ ํ๋ ์์ง ๋๋ ํ๋ 0 -> ๋ค์ ๋ชจ๋ธ")
|
| 200 |
break
|
|
|
|
| 208 |
if r.status_code >= 500:
|
| 209 |
time.sleep(5)
|
| 210 |
continue
|
| 211 |
+
break
|
| 212 |
raise LLMUnavailable(last_err or "์ฌ์ฉ ๊ฐ๋ฅํ ๋ชจ๋ธ์ด ์์ต๋๋ค.")
|
| 213 |
|
| 214 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
def call_hf(parts: list[dict]) -> tuple[str, str]:
|
|
|
|
| 216 |
if not hf_token():
|
| 217 |
raise LLMUnavailable("HF_TOKEN์ด ์ค์ ๋์ง ์์์ต๋๋ค.")
|
| 218 |
text = "\n".join(p["text"] for p in parts if "text" in p)
|
| 219 |
if any("inline_data" in p for p in parts):
|
| 220 |
+
text = "NOTE: An image/audio attachment exists but you cannot view it; answer from the other information.\n\n" + text
|
|
|
|
| 221 |
last_err = ""
|
| 222 |
for model in HF_MODELS:
|
| 223 |
for attempt in range(MAX_RETRY + 1):
|
|
|
|
| 227 |
f"{HF_ROUTER}/chat/completions",
|
| 228 |
headers={"Authorization": f"Bearer {hf_token()}", "Content-Type": "application/json"},
|
| 229 |
json={"model": model, "messages": [{"role": "user", "content": text}],
|
| 230 |
+
"max_tokens": 1500, "temperature": 0},
|
| 231 |
timeout=120,
|
| 232 |
)
|
| 233 |
except requests.RequestException as e:
|
|
|
|
| 244 |
body = r.text
|
| 245 |
last_err = f"{model}: HTTP {r.status_code} {body[:180].replace(chr(10), ' ')}"
|
| 246 |
if r.status_code == 402:
|
| 247 |
+
raise LLMUnavailable("HF ํฌ๋ ๋ง ์์ง(402). " + body[:150])
|
| 248 |
if r.status_code in (401, 403):
|
| 249 |
+
raise LLMUnavailable(f"HF_TOKEN ์ธ์ฆ/๊ถํ ์ค๋ฅ({r.status_code}). Inference Providers ๊ถํ์ ํ์ธํ์ธ์.")
|
| 250 |
if r.status_code == 429:
|
| 251 |
if attempt == MAX_RETRY:
|
| 252 |
break
|
|
|
|
| 257 |
if r.status_code >= 500:
|
| 258 |
time.sleep(5)
|
| 259 |
continue
|
| 260 |
+
break
|
| 261 |
raise LLMUnavailable(last_err or "์ฌ์ฉ ๊ฐ๋ฅํ ๋ชจ๋ธ์ด ์์ต๋๋ค.")
|
| 262 |
|
| 263 |
|
|
|
|
| 266 |
|
| 267 |
|
| 268 |
# ---------------------------------------------------------------------------
|
| 269 |
+
# ๋๊ตฌ ๊ตฌํ
|
| 270 |
# ---------------------------------------------------------------------------
|
| 271 |
def html_to_text(html: str) -> str:
|
| 272 |
html = re.sub(r"(?is)<(script|style|noscript|svg|header|footer|nav)[^>]*>.*?</\1>", " ", html)
|
| 273 |
+
html = re.sub(r"(?is)<sup[^>]*class=\"[^\"]*reference[^\"]*\"[^>]*>.*?</sup>", "", html)
|
| 274 |
+
html = re.sub(r"(?i)</t[dh]>", " | ", html)
|
| 275 |
+
html = re.sub(r"(?i)</tr>|<br\s*/?>|</p>|</li>|</h[1-6]>|</caption>", "\n", html)
|
| 276 |
text = re.sub(r"(?s)<[^>]+>", " ", html)
|
| 277 |
+
text = (text.replace(" ", " ").replace(" ", " ").replace("&", "&")
|
| 278 |
+
.replace("<", "<").replace(">", ">").replace(""", '"').replace("'", "'"))
|
| 279 |
+
text = re.sub(r"[ \t\u00a0]+", " ", text)
|
| 280 |
+
text = re.sub(r"(\s*\|\s*)+\n", "\n", text)
|
| 281 |
+
text = re.sub(r"\n\s*\n+", "\n", text)
|
| 282 |
+
return text.strip()
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def windows(text: str, keyword: str, head: int = 1500, win: int = 1600, max_hits: int = 3) -> str:
|
| 286 |
+
"""ํค์๋ ์ฃผ๋ณ ๋ฌธ๋จ๋ง ์๋ผ ๋ณด์ฌ์ค๋๋ค. ํค์๋๊ฐ ์์ผ๋ฉด ์๋ถ๋ถ์ ๋ณด์ฌ์ค๋๋ค."""
|
| 287 |
+
if not keyword:
|
| 288 |
+
return text[:OBS_CHARS]
|
| 289 |
+
low, key = text.lower(), keyword.lower()
|
| 290 |
+
spans, pos = [], 0
|
| 291 |
+
while len(spans) < max_hits:
|
| 292 |
+
i = low.find(key, pos)
|
| 293 |
+
if i < 0:
|
| 294 |
+
break
|
| 295 |
+
spans.append((max(0, i - win // 4), min(len(text), i + win)))
|
| 296 |
+
pos = i + win
|
| 297 |
+
if not spans:
|
| 298 |
+
return f"(ํค์๋ '{keyword}'๋ฅผ ์ฐพ์ง ๋ชปํจ. ๋ฌธ์ ์๋ถ๋ถ:)\n" + text[:OBS_CHARS]
|
| 299 |
+
out = [text[:head]] + [f"...\n{text[a:b]}" for a, b in spans]
|
| 300 |
+
return "\n".join(out)[: OBS_CHARS * 2]
|
| 301 |
|
| 302 |
|
| 303 |
+
def tool_search(query: str) -> str:
|
| 304 |
if DDGS is None:
|
| 305 |
+
return "๊ฒ์ ๋๊ตฌ๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค."
|
| 306 |
try:
|
| 307 |
results = list(DDGS().text(query, max_results=6))
|
| 308 |
except Exception as e: # noqa: BLE001
|
| 309 |
+
return f"๊ฒ์ ์คํจ: {type(e).__name__}: {str(e)[:150]}"
|
| 310 |
+
if not results:
|
| 311 |
+
return "๊ฒ์ ๊ฒฐ๊ณผ ์์"
|
| 312 |
+
return "\n\n".join(f"[{i}] {r.get('title', '')}\n{r.get('href', '')}\n{r.get('body', '')}"
|
| 313 |
+
for i, r in enumerate(results, 1))[:OBS_CHARS]
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def _wiki_parse(title: str):
|
| 317 |
+
r = requests.get("https://en.wikipedia.org/w/api.php", headers=UA, timeout=25,
|
| 318 |
+
params={"action": "parse", "page": title, "prop": "text", "format": "json",
|
| 319 |
+
"redirects": 1, "formatversion": 2})
|
| 320 |
+
j = r.json()
|
| 321 |
+
if "parse" in j:
|
| 322 |
+
return j["parse"]["text"], j["parse"]["title"]
|
| 323 |
+
return None
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def tool_wiki(inp: str) -> str:
|
| 327 |
+
title, _, kw = inp.partition("|")
|
| 328 |
+
title, kw = title.strip(), kw.strip()
|
| 329 |
+
try:
|
| 330 |
+
got = _wiki_parse(title)
|
| 331 |
+
if not got:
|
| 332 |
+
r = requests.get("https://en.wikipedia.org/w/api.php", headers=UA, timeout=25,
|
| 333 |
+
params={"action": "query", "list": "search", "srsearch": title,
|
| 334 |
+
"format": "json", "srlimit": 1})
|
| 335 |
+
hits = r.json().get("query", {}).get("search", [])
|
| 336 |
+
got = _wiki_parse(hits[0]["title"]) if hits else None
|
| 337 |
+
if not got:
|
| 338 |
+
return f"Wikipedia ๋ฌธ์๋ฅผ ์ฐพ์ง ๋ชปํ์ต๋๋ค: {title}"
|
| 339 |
+
html, real = got
|
| 340 |
+
return f"[Wikipedia: {real}]\n" + windows(html_to_text(html), kw)
|
| 341 |
+
except Exception as e: # noqa: BLE001
|
| 342 |
+
return f"Wikipedia ์กฐํ ์คํจ: {type(e).__name__}: {str(e)[:150]}"
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def tool_fetch(inp: str) -> str:
|
| 346 |
+
url, _, kw = inp.partition("|")
|
| 347 |
+
url, kw = url.strip(), kw.strip()
|
| 348 |
+
if not url.startswith("http"):
|
| 349 |
+
return "URL์ http๋ก ์์ํด์ผ ํฉ๋๋ค."
|
| 350 |
+
try:
|
| 351 |
+
r = requests.get(url, headers=UA, timeout=25)
|
| 352 |
+
ctype = r.headers.get("content-type", "")
|
| 353 |
+
if "pdf" in ctype or url.lower().endswith(".pdf"):
|
| 354 |
+
return "PDF๋ ์ง์ํ์ง ์์ต๋๋ค."
|
| 355 |
+
if "html" not in ctype and "text" not in ctype and "json" not in ctype:
|
| 356 |
+
return f"์ง์ํ์ง ์๋ ํ์์
๋๋ค: {ctype}"
|
| 357 |
+
text = html_to_text(r.text) if "html" in ctype else r.text
|
| 358 |
+
return windows(text, kw)
|
| 359 |
+
except Exception as e: # noqa: BLE001
|
| 360 |
+
return f"ํ์ด์ง๋ฅผ ๊ฐ์ ธ์ค์ง ๋ชปํ์ต๋๋ค: {type(e).__name__}: {str(e)[:150]}"
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def tool_python(code: str) -> str:
|
| 364 |
+
code = re.sub(r"^```(?:python)?\s*\n?", "", code.strip())
|
| 365 |
+
code = re.sub(r"\n?```\s*$", "", code)
|
| 366 |
+
with tempfile.NamedTemporaryFile("w", suffix=".py", dir="/tmp", delete=False, encoding="utf-8") as f:
|
| 367 |
+
f.write(code)
|
| 368 |
+
path = f.name
|
| 369 |
+
# ํ ํฐ ๋ฑ ๋น๋ฐ ํ๊ฒฝ๋ณ์๊ฐ ์ฝ๋์ ๋
ธ์ถ๋์ง ์๋๋ก ์ต์ ํ๊ฒฝ๋ง ์ ๋ฌ
|
| 370 |
+
env = {"PATH": os.environ.get("PATH", ""), "HOME": "/tmp", "PYTHONIOENCODING": "utf-8"}
|
| 371 |
+
try:
|
| 372 |
+
r = subprocess.run([sys.executable, path], capture_output=True, text=True,
|
| 373 |
+
timeout=PY_TIMEOUT, cwd=FILES_DIR, env=env)
|
| 374 |
+
out = r.stdout or ""
|
| 375 |
+
if r.stderr:
|
| 376 |
+
out += "\n[stderr]\n" + r.stderr[-1500:]
|
| 377 |
+
except subprocess.TimeoutExpired:
|
| 378 |
+
out = f"(์คํ ์๊ฐ ์ด๊ณผ {PY_TIMEOUT}์ด)"
|
| 379 |
+
except Exception as e: # noqa: BLE001
|
| 380 |
+
out = f"์คํ ์ค๋ฅ: {e}"
|
| 381 |
+
finally:
|
| 382 |
try:
|
| 383 |
+
os.remove(path)
|
| 384 |
+
except OSError:
|
| 385 |
+
pass
|
| 386 |
+
return out[:OBS_CHARS] if out.strip() else "(์ถ๋ ฅ ์์. ๊ฒฐ๊ณผ๋ print()๋ก ์ถ๋ ฅํด์ผ ํฉ๋๋ค.)"
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def tool_youtube(url: str) -> str:
|
| 390 |
+
m = re.search(r"(?:v=|youtu\.be/)([\w-]{11})", url)
|
| 391 |
+
if not m:
|
| 392 |
+
return "์ ํจํ YouTube URL์ด ์๋๋๋ค."
|
| 393 |
+
try:
|
| 394 |
+
from youtube_transcript_api import YouTubeTranscriptApi
|
| 395 |
+
except ImportError:
|
| 396 |
+
return "youtube-transcript-api๊ฐ ์ค์น๋์ง ์์์ต๋๋ค."
|
| 397 |
+
vid = m.group(1)
|
| 398 |
+
try:
|
| 399 |
+
try:
|
| 400 |
+
items = YouTubeTranscriptApi.get_transcript(vid)
|
| 401 |
+
text = " ".join(i.get("text", "") for i in items)
|
| 402 |
+
except AttributeError:
|
| 403 |
+
text = " ".join(getattr(s, "text", "") for s in YouTubeTranscriptApi().fetch(vid))
|
| 404 |
+
return text[: OBS_CHARS * 2] or "์๋ง์ด ๋น์ด ์์ต๋๋ค."
|
| 405 |
+
except Exception as e: # noqa: BLE001
|
| 406 |
+
return f"์๋ง์ ๊ฐ์ ธ์ค์ง ๋ชปํ์ต๋๋ค(์์ ๋ด์ฉ์ ๋ณผ ์ ์์): {type(e).__name__}: {str(e)[:150]}"
|
| 407 |
|
| 408 |
|
| 409 |
+
TOOLS = {"search": tool_search, "wiki": tool_wiki, "fetch": tool_fetch, "python": tool_python, "youtube": tool_youtube}
|
| 410 |
+
|
| 411 |
# ---------------------------------------------------------------------------
|
| 412 |
# ์ฒจ๋ถ ํ์ผ
|
| 413 |
# ---------------------------------------------------------------------------
|
|
|
|
| 427 |
|
| 428 |
|
| 429 |
def file_to_parts(path: str) -> tuple[str, list[dict]]:
|
| 430 |
+
"""(๋ฏธ๋ฆฌ๋ณด๊ธฐ ํ
์คํธ, Gemini์ ์ง์ ๋ฃ์ inline_data ํํธ๋ค)"""
|
| 431 |
lower = path.lower()
|
| 432 |
try:
|
| 433 |
if lower.endswith((".png", ".jpg", ".jpeg", ".webp", ".mp3", ".wav", ".m4a")):
|
| 434 |
if os.path.getsize(path) > 15 * 1024 * 1024:
|
| 435 |
+
return "(ํ์ผ์ด ๋๋ฌด ์ปค์ ์๋ต๋จ)", []
|
| 436 |
+
mime = "audio/mp3" if lower.endswith(".mp3") else (mimetypes.guess_type(path)[0] or "application/octet-stream")
|
|
|
|
|
|
|
| 437 |
with open(path, "rb") as f:
|
| 438 |
data = base64.b64encode(f.read()).decode()
|
| 439 |
+
return "(์ด๋ฏธ์ง/์ค๋์ค ํ์ผ. Gemini์ผ ๋๋ง ๋ด์ฉ์ ๋ณผ ์ ์์)", [{"inline_data": {"mime_type": mime, "data": data}}]
|
| 440 |
if lower.endswith((".xlsx", ".xls")):
|
| 441 |
sheets = pd.read_excel(path, sheet_name=None)
|
| 442 |
+
return "\n\n".join(f"## Sheet {n} (shape {df.shape})\n{df.head(25).to_string()}" for n, df in sheets.items()), []
|
| 443 |
if lower.endswith(".csv"):
|
| 444 |
+
df = pd.read_csv(path)
|
| 445 |
+
return f"shape {df.shape}\n{df.head(25).to_string()}", []
|
| 446 |
with open(path, "r", encoding="utf-8", errors="ignore") as f:
|
| 447 |
+
return f.read()[:12000], []
|
| 448 |
except Exception as e: # noqa: BLE001
|
| 449 |
return f"(ํ์ผ ์ฝ๊ธฐ ์คํจ: {e})", []
|
| 450 |
|
| 451 |
|
| 452 |
# ---------------------------------------------------------------------------
|
| 453 |
+
# ์์ด์ ํธ ๋ฃจํ
|
| 454 |
# ---------------------------------------------------------------------------
|
| 455 |
+
def clean_answer(ans: str) -> str:
|
| 456 |
+
ans = (ans.strip().splitlines() or [""])[0]
|
| 457 |
+
return ans.strip().strip("`").strip().strip('"').strip().rstrip(".").strip()
|
|
|
|
| 458 |
|
| 459 |
|
| 460 |
+
def parse_action(text: str):
|
| 461 |
+
m = re.search(r"Action:\s*([A-Za-z_]+)\s*\n?\s*Input:\s*(.*)", text, flags=re.S | re.I)
|
| 462 |
+
if m:
|
| 463 |
+
inp = re.split(r"\n\s*Observation:", m.group(2))[0].strip()
|
| 464 |
+
return m.group(1).lower(), inp
|
| 465 |
+
m = re.findall(r"FINAL ANSWER:\s*(.+)", text, flags=re.I)
|
| 466 |
+
if m:
|
| 467 |
+
return "final", m[-1].strip()
|
| 468 |
+
return None, ""
|
| 469 |
|
| 470 |
|
| 471 |
def solve(item: dict) -> tuple[str, str]:
|
| 472 |
+
"""(๋ต๋ณ, ๋น๊ณ )๋ฅผ ๋ฐํํฉ๋๋ค."""
|
| 473 |
question = item["question"]
|
| 474 |
extra_parts: list[dict] = []
|
| 475 |
+
file_note = ""
|
|
|
|
| 476 |
path = download_file(item["task_id"], item.get("file_name", ""))
|
| 477 |
if path:
|
| 478 |
+
preview, extra_parts = file_to_parts(path)
|
| 479 |
+
file_note = (f"ATTACHED FILE path: {path}\nPreview:\n{preview[:6000]}\n"
|
| 480 |
+
"(The file can be read by the python action at that exact path.)\n\n")
|
| 481 |
|
| 482 |
+
head = AGENT_PROMPT.replace("{max_steps}", str(MAX_STEPS)) + "\n\nQUESTION:\n" + question + "\n\n" + file_note
|
| 483 |
+
history: list[str] = []
|
| 484 |
+
start = time.time()
|
| 485 |
+
model_used, last_text = "", ""
|
| 486 |
+
|
| 487 |
+
for step in range(1, MAX_STEPS + 1):
|
| 488 |
+
last = step == MAX_STEPS or (time.time() - start) > QUESTION_TIMEOUT
|
| 489 |
+
prompt = head + "\n".join(history)
|
| 490 |
+
prompt += ("\n\nThis is your LAST step: reply now with Action: final." if last
|
| 491 |
+
else "\n\nReply with your next step (one action).")
|
| 492 |
+
text, model_used = call_llm([{"text": prompt}] + extra_parts)
|
| 493 |
+
last_text = text
|
| 494 |
+
action, inp = parse_action(text)
|
| 495 |
+
log(f" [{question[:28]}โฆ] ๋จ๊ณ {step}: {action or 'ํ์์ค๋ฅ'} {inp[:50].replace(chr(10), ' ')}")
|
| 496 |
+
|
| 497 |
+
if action == "final":
|
| 498 |
+
return clean_answer(inp), f"{model_used} / {step}๋จ๊ณ"
|
| 499 |
+
if last:
|
| 500 |
+
break
|
| 501 |
+
if action not in TOOLS:
|
| 502 |
+
history.append(f"[Step {step}]\n{text[:800]}\nObservation: Invalid format or action. Reply exactly with "
|
| 503 |
+
"Thought/Action/Input using one of: search, wiki, fetch, python, youtube, final.")
|
| 504 |
+
continue
|
| 505 |
+
obs = TOOLS[action](inp)
|
| 506 |
+
history.append(f"[Step {step}]\nThought/Action: {action}\nInput: {inp[:1500]}\nObservation: {obs[:OBS_CHARS]}")
|
| 507 |
|
| 508 |
+
# ๋ง์ง๋ง ์๋ต์์ ๋ต์ ์ต๋ํ ๊ฑด์ ธ๋
|
| 509 |
+
m = re.findall(r"FINAL ANSWER:\s*(.+)", last_text, flags=re.I)
|
| 510 |
+
fallback = clean_answer(m[-1]) if m else clean_answer(last_text.splitlines()[-1] if last_text.strip() else "unknown")
|
| 511 |
+
return fallback or "unknown", f"{model_used} / ๋จ๊ณ์ด๊ณผ"
|
| 512 |
|
| 513 |
|
| 514 |
# ---------------------------------------------------------------------------
|
|
|
|
| 524 |
|
| 525 |
|
| 526 |
def make_df(rows: dict, order: list[str]) -> pd.DataFrame:
|
| 527 |
+
return pd.DataFrame([rows[t] for t in order if t in rows],
|
| 528 |
+
columns=["Task ID", "Question", "Submitted Answer", "OK", "Note"])
|
|
|
|
|
|
|
| 529 |
|
| 530 |
|
| 531 |
def run_batch(questions: list[dict], label: str):
|
| 532 |
+
"""๋ฌธํญ์ ์์๋๋ก ํ๋ฉฐ ์งํ ์ํฉ์ ๊ณ์ ๋ด๋ณด๋
๋๋ค. ๋ง์ง๋ง์ (rows, order, aborted)๋ฅผ ๋ฐํ."""
|
| 533 |
order = [q["task_id"] for q in questions if q.get("task_id")]
|
| 534 |
rows: dict = {}
|
| 535 |
cache = load_cache()
|
| 536 |
start = time.time()
|
| 537 |
+
fails, aborted = 0, False
|
| 538 |
+
log(f"{label} ์์: {len(order)}๋ฌธํญ, ๋ชจ๋ธ ์ ๊ณต์={PROVIDER}, ๋ฌธํญ๋น ์ต๋ {MAX_STEPS}๋จ๊ณ")
|
| 539 |
+
|
| 540 |
+
def status(i: int) -> str:
|
| 541 |
+
return (f"{label}: {len(rows)}/{len(order)} ์๋ฃ, {i}๋ฒ์งธ ๋ฌธํญ ์ฒ๋ฆฌ ์ค (๊ฒฝ๊ณผ {int(time.time() - start)}์ด)\n"
|
| 542 |
+
f"--- ์ต๊ทผ ๊ธฐ๋ก ---\n{recent_log()}")
|
| 543 |
|
| 544 |
for i, item in enumerate(questions, start=1):
|
| 545 |
tid = item.get("task_id")
|
| 546 |
if not tid or item.get("question") is None:
|
| 547 |
continue
|
| 548 |
+
yield status(i), make_df(rows, order)
|
|
|
|
| 549 |
|
| 550 |
if tid in cache:
|
| 551 |
answer, ok, note = cache[tid], True, "cache"
|
| 552 |
log(f"์บ์ ์ฌ์ฉ {tid[:8]}")
|
| 553 |
else:
|
| 554 |
+
box: dict = {}
|
| 555 |
+
|
| 556 |
+
def work(it=item):
|
| 557 |
+
try:
|
| 558 |
+
box["r"] = solve(it)
|
| 559 |
+
except LLMUnavailable as e:
|
| 560 |
+
box["llm"] = str(e)
|
| 561 |
+
except Exception as e: # noqa: BLE001
|
| 562 |
+
box["err"] = f"{type(e).__name__}: {e}"
|
| 563 |
+
|
| 564 |
+
th = threading.Thread(target=work, daemon=True)
|
| 565 |
+
th.start()
|
| 566 |
+
while th.is_alive():
|
| 567 |
+
th.join(2)
|
| 568 |
+
yield status(i), make_df(rows, order)
|
| 569 |
+
|
| 570 |
+
if "r" in box:
|
| 571 |
+
answer, note = box["r"]
|
| 572 |
+
ok, fails = True, 0
|
| 573 |
save_cache(tid, answer)
|
|
|
|
|
|
|
| 574 |
log(f"์๋ฃ {tid[:8]} -> {answer}")
|
| 575 |
+
elif "llm" in box:
|
| 576 |
+
answer, ok, note = "unknown", False, box["llm"][:250]
|
| 577 |
fails += 1
|
| 578 |
log(f"LLM ์คํจ {tid[:8]}: {note}")
|
| 579 |
+
else:
|
| 580 |
+
answer, ok, note = "unknown", False, box.get("err", "์ ์ ์๋ ์ค๋ฅ")[:250]
|
| 581 |
log(f"์ค๋ฅ {tid[:8]}: {note}")
|
| 582 |
|
| 583 |
+
rows[tid] = {"Task ID": tid, "Question": item["question"], "Submitted Answer": answer,
|
| 584 |
+
"OK": "O" if ok else "X", "Note": note}
|
| 585 |
if fails >= 2:
|
| 586 |
aborted = True
|
| 587 |
log("LLM์ด ์ฐ์ 2ํ ์คํจํ์ฌ ์ค๋จํฉ๋๋ค. (ํ๋/ํฌ๋ ๋ง ๋ฌธ์ ๊ฐ๋ฅ์ฑ)")
|
|
|
|
| 612 |
rows, order, aborted = yield from run_batch(questions, "๋ณธ ์คํ")
|
| 613 |
if aborted:
|
| 614 |
yield ("LLM ํ๋/ํฌ๋ ๋ง ๋ฌธ์ ๋ก ์ค๋จํ์ผ๋ฏ๋ก ์ ์ถํ์ง ์์์ต๋๋ค.\n"
|
| 615 |
+
"ํผ ๋ต์ ์ ์ฅ๋์ด ์์ด ํด๊ฒฐ ํ ๋ค์ ๋๋ฅด๋ฉด ์ด์ด์ ์งํํฉ๋๋ค. "
|
| 616 |
"(Space๊ฐ ์ฌ์์๋๋ฉด ์ ์ฅ๋ ๋ต์ ์ฌ๋ผ์ง๋๋ค.)\n\n" + recent_log()), make_df(rows, order)
|
| 617 |
return
|
| 618 |
|
| 619 |
payload = [{"task_id": t, "submitted_answer": rows[t]["Submitted Answer"]} for t in order if t in rows]
|
| 620 |
failed = sum(1 for r in rows.values() if r["OK"] == "X")
|
| 621 |
yield f"ํ์ด ์๋ฃ (์คํจ {failed}๊ฐ). ์ ์ถ ์ค...", make_df(rows, order)
|
| 622 |
+
submission = {"username": profile.username.strip(),
|
| 623 |
+
"agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
|
| 624 |
+
"answers": payload}
|
|
|
|
|
|
|
| 625 |
try:
|
| 626 |
r = requests.post(f"{SCORING_API}/submit", json=submission, timeout=120)
|
| 627 |
r.raise_for_status()
|
|
|
|
| 647 |
|
| 648 |
|
| 649 |
def diagnose():
|
| 650 |
+
lines = [f"PROVIDER={PROVIDER}, MAX_STEPS={MAX_STEPS}, MIN_INTERVAL={MIN_INTERVAL}์ด, QUESTION_TIMEOUT={QUESTION_TIMEOUT}์ด"]
|
| 651 |
yield "\n".join(lines + ["", "๋ชจ๋ธ ํ์ธ ์ค..."])
|
| 652 |
if PROVIDER == "hf":
|
| 653 |
+
lines.append(f"HF_TOKEN: {'์์' if hf_token() else '์์'}, ๋ชจ๋ธ: {HF_MODELS}")
|
| 654 |
try:
|
| 655 |
r = requests.get(f"{HF_ROUTER}/models", headers={"Authorization": f"Bearer {hf_token()}"}, timeout=30)
|
| 656 |
r.raise_for_status()
|
| 657 |
ids = [m.get("id") for m in r.json().get("data", [])]
|
| 658 |
+
lines.append("1) ๋ชจ๋ธ ๋ชฉ๋ก: " + ", ".join(f"{m}={'์์' if m in ids else '๋ชฉ๋ก์ ์์'}" for m in HF_MODELS))
|
|
|
|
| 659 |
except Exception as e: # noqa: BLE001
|
| 660 |
lines.append(f"1) ๋ชจ๋ธ ๋ชฉ๋ก ์กฐํ ์คํจ(์งํ์ ๊ณ์): {type(e).__name__}: {str(e)[:150]}")
|
| 661 |
else:
|
| 662 |
lines.append(f"GEMINI_API_KEY: {'์์' if api_key() else '์์'}")
|
| 663 |
try:
|
| 664 |
+
lines.append("1) ์ฌ์ฉ ๊ฐ๋ฅํ Gemini ๋ชจ๋ธ(์ผ๋ถ): " + ", ".join([n for n in list_models() if n.startswith('gemini')][:25]))
|
|
|
|
| 665 |
lines.append(f" ์ฌ์ฉํ ํ๋ณด ์์: {candidate_models()}")
|
| 666 |
except Exception as e: # noqa: BLE001
|
| 667 |
lines.append(f"1) ๋ชจ๋ธ ๋ชฉ๋ก ์กฐํ ์คํจ: {type(e).__name__}: {str(e)[:200]}")
|
|
|
|
| 673 |
lines.append(f"2) LLM ํธ์ถ: ์ ์ (๋ชจ๋ธ {model}, ์๋ต '{text.strip()[:30]}')")
|
| 674 |
except LLMUnavailable as e:
|
| 675 |
lines.append(f"2) LLM ํธ์ถ: ์คํจ - {str(e)[:300]}")
|
| 676 |
+
yield "\n".join(lines + ["", "๋๊ตฌ ํ
์คํธ ์ค..."])
|
| 677 |
+
s = tool_search("Hugging Face")
|
| 678 |
+
lines.append(f"3) ์น ๊ฒ์: {'์ ์' if len(s) > 100 else '์คํจ/๊ฒฐ๊ณผ ๋ถ์กฑ'} ({len(s)}์)")
|
| 679 |
+
w = tool_wiki("Mercedes Sosa | studio album")
|
| 680 |
+
lines.append(f"4) ์ํค๋ฐฑ๊ณผ: {'์ ์' if 'Wikipedia:' in w[:30] else '์คํจ'} ({len(w)}์) {'' if 'Wikipedia:' in w[:30] else w[:100]}")
|
| 681 |
+
p = tool_python("print(sum(range(1, 11)))")
|
| 682 |
+
lines.append(f"5) ํ์ด์ฌ ์คํ: {'์ ์' if p.strip() == '55' else '์ด์ - ' + p[:100]}")
|
| 683 |
yield "\n".join(lines)
|
| 684 |
|
| 685 |
|
|
|
|
| 697 |
# UI
|
| 698 |
# ---------------------------------------------------------------------------
|
| 699 |
with gr.Blocks() as demo:
|
| 700 |
+
gr.Markdown("# Basic Agent Evaluation Runner (๋ค๋จ๊ณ ์์ด์ ํธ ๋ฒ์ )")
|
| 701 |
gr.Markdown(
|
| 702 |
"""**์ฌ์ฉ ์์**
|
| 703 |
+
1. '์ฐ๊ฒฐ ์ง๋จ'์ผ๋ก ๋ชจ๋ธ๊ณผ ๋๊ตฌ(๊ฒ์, ์ํค, ํ์ด์ฌ)๊ฐ ์ ์์ธ์ง ํ์ธํฉ๋๋ค.
|
| 704 |
2. ๋ก๊ทธ์ธ ํ 'ํ
์คํธ ์คํ'(1~2๋ฌธํญ)์ผ๋ก ํ์ธํฉ๋๋ค. (์ ์ถ ์ ํจ)
|
| 705 |
+
3. ๋ฌธ์ ์์ผ๋ฉด '์บ์ ์ด๊ธฐํ' ํ 'Run Evaluation & Submit All Answers'๋ฅผ ๋๋ฆ
๋๋ค."""
|
| 706 |
)
|
| 707 |
gr.LoginButton()
|
| 708 |
with gr.Row():
|
|
|
|
| 711 |
test_button = gr.Button("ํ
์คํธ ์คํ (์ ์ถ ์ ํจ)")
|
| 712 |
cache_button = gr.Button("์บ์ ์ด๊ธฐํ")
|
| 713 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 714 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=16, interactive=False)
|
| 715 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 716 |
|
| 717 |
diag_button.click(fn=diagnose, outputs=[status_output])
|