omega21 commited on
Commit
aacc1dd
ยท
verified ยท
1 Parent(s): 6172d6b

Update app.py

Browse files

import json
import os
import re
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
import gradio as gr
import pandas as pd
import requests
from smolagents import (
CodeAgent,
DuckDuckGoSearchTool,
InferenceClientModel,
LiteLLMModel,
VisitWebpageTool,
tool,
)

# ZeroGPU ํ•˜๋“œ์›จ์–ด์—์„œ ์‹œ์ž‘ ์˜ค๋ฅ˜๋ฅผ ๋ง‰๊ธฐ ์œ„ํ•œ ์•ˆ์ „ํ•œ ๋”๋ฏธ ํ•จ์ˆ˜
try:
import spaces
@spaces.GPU
def _gpu_placeholder():
return "ok"
except ImportError:
pass

# ---------------------------------------------------------------------------
# ์„ค์ • (Space์˜ Variables ๋˜๋Š” Secrets์—์„œ ์กฐ์ • ๊ฐ€๋Šฅ)
# ---------------------------------------------------------------------------
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
FILES_DIR = "/tmp/task_files"
CACHE_PATH = "/tmp/answers_cache.json"
os.makedirs(FILES_DIR, exist_ok=True)

WORKERS = int(os.getenv("WORKERS", "3")) # ๋™์‹œ ์‹คํ–‰ ๋ฌธํ•ญ ์ˆ˜
QUESTION_TIMEOUT = int(os.getenv("QUESTION_TIMEOUT", "240")) # ๋ฌธํ•ญ๋‹น ์ œํ•œ ์‹œ๊ฐ„(์ดˆ)
MAX_STEPS = int(os.getenv("MAX_STEPS", "12")) # ์—์ด์ „ํŠธ ์ตœ๋Œ€ ๋‹จ๊ณ„

ANSWER_RULES = """You are a careful research and reasoning agent solving GAIA-style questions.
Rules:
1. Use the tools (web search, webpage visit, file reading, python code) whenever the
question needs facts you are not 100% sure about. Do not guess.
2. The final answer is graded by EXACT MATCH. Return ONLY the answer value, with no
explanation, no units unless asked, no trailing period, no "FINAL ANSWER:" prefix.
3. If the answer is a number: no thousands separators, no currency/percent symbols
unless the question asks for them.
4. If the answer is a list: comma-separated, in the order the question requests.
5. If the answer is a string: no articles (a, an, the) and no abbreviations unless
the question asks for them.
6. If a file path is given, read it with the read_local_file tool or with python code.
7. Be efficient: stop researching as soon as you have a reliable answer.
8. Finish by calling final_answer(...) with the answer only."""

# ---------------------------------------------------------------------------
# ์บ์‹œ ๊ด€๋ฆฌ
# ---------------------------------------------------------------------------
_cache_lock = threading.Lock()

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_entry(task_id: str, answer: str):
with _cache_lock:
cache = load_cache()
cache[task_id] = answer
with open(CACHE_PATH, "w", encoding="utf-8") as f:
json.dump(cache, f, ensure_ascii=False)

# ---------------------------------------------------------------------------
# ๋„๊ตฌ (ํŒŒ์ผ ๊ฒฝ๋กœ ๋ณด์™„ ๊ธฐ๋Šฅ ํฌํ•จ)
# ---------------------------------------------------------------------------
@tool
def read_local_file(path: str) -> str:
"""Reads a local file (txt, csv, json, py, md, xlsx) and returns its content as text.
Args:
path: Absolute or relative path of the file to read.
"""
try:
# ์—์ด์ „ํŠธ๊ฐ€ ํŒŒ์ผ๋ช…๋งŒ ์ž…๋ ฅํ•˜๊ฑฐ๋‚˜ ๊ฒฝ๋กœ๊ฐ€ ์ž˜๋ชป๋œ ๊ฒฝ์šฐ FILES_DIR์—์„œ ํƒ์ƒ‰
if not os.path.exists(path):
basename = os.path.basename(path)
candidate = os.path.join(FILES_DIR, basename)
if os.path.exists(candidate):
path = candidate

lower = path.lower()
if lower.endswith((".xlsx", ".xls")):
sheets = pd.read_excel(path, sheet_name=None)
return "\n\n".join(
f"## Sheet: {n}\n{df.to_string(max_rows=200)}" for n, df in sheets.items()
)
if lower.endswith(".csv"):
return pd.read_csv(path).to_string(max_rows=200)
with open(path, "r", encoding="utf-8", errors="ignore") as f:
return f.read()[:20000]
except Exception as e: # noqa: BLE001
return f"Could not read file: {e}"

# ---------------------------------------------------------------------------
# ์—์ด์ „ํŠธ ๋ฐ ๋ชจ๋ธ ์„ค์ • (gemini-3.8-flash ๋ฐ˜์˜)
# ---------------------------------------------------------------------------
def build_model():
gemini_key = os.getenv("GEMINI_API_KEY")
if gemini_key:
model_id = os.getenv("GEMINI_MODEL", "gemini-3.8-flash")
print(f"[model] Gemini: {model_id}")
return LiteLLMModel(model_id=f"gemini/{model_id}", api_key=gemini_key)

openai_key = os.getenv("OPENAI_API_KEY")
if openai_key:
model_id = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
print(f"[model] OpenAI: {model_id}")
return LiteLLMModel(model_id=f"openai/{model_id}", api_key=openai_key)

model_id = os.getenv("HF_MODEL", "Qwen/Qwen2.5-Coder-32B-Instruct")
print(f"[model] HF Inference: {model_id}")
return InferenceClientModel(model_id=model_id, token=os.getenv("HF_TOKEN"))

def build_agent() -> CodeAgent:
# ์Šค๋ ˆ๋“œ ์•ˆ์ „ ๋ฐ ๋ฌธํ•ญ๋ณ„ ๋…๋ฆฝ ์ปจํ…์ŠคํŠธ ์œ ์ง€๋ฅผ ์œ„ํ•ด ๋งค๋ฒˆ ์ƒˆ ์—์ด์ „ํŠธ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
return CodeAgent(
tools=[DuckDuckGoSearchTool(), VisitWebpageTool(), read_local_file],
model=build_model(),
additional_authorized_imports=[
"pandas", "numpy", "re", "json", "math", "datetime",
"collections", "itertools", "statistics", "requests", "bs4",
],
max_steps=MAX_STEPS,
verbosity_level=1,
)

def clean_answer(answer) -> str:
text = str(answer).strip()
text = re.sub(r"^\s*final answer\s*:\s*", "", text, flags=re.IGNORECASE)
return text.strip().rstrip(".").strip()

# ---------------------------------------------------------------------------
# ์ฑ„์  ์„œ๋ฒ„ ํ†ต์‹  ๋ฐ ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ
# ---------------------------------------------------------------------------
def fetch_questions(api_url: str) -> list[dict]:
resp = requests.get(f"{api_url}/questions", timeout=30)
resp.raise_for_status()
data = resp.json()
if not data:
raise ValueError("์งˆ๋ฌธ ๋ชฉ๋ก์ด ๋น„์–ด ์žˆ์Šต๋‹ˆ๋‹ค.")
return data

def download_task_file(api_url: str, task_id: str, file_name: str):
if not file_name:
return None
try:
resp = requests.get(f"{api_url}/files/{task_id}", timeout=60)
resp.raise_for_status()
path = os.path.join(FILES_DIR, f"{task_id}_{file_name}")
with open(path, "wb") as f:
f.write(resp.content)
return path
except Exception as e: # noqa: BLE001
print(f"ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ ์‹คํŒจ ({task_id}): {e}")
return None

# ---------------------------------------------------------------------------
# ๊ฐœ๋ณ„ ๋ฌธํ•ญ ํ’€์ด (์บ์‹œ + ํƒ€์ž„์•„์›ƒ)
# ---------------------------------------------------------------------------
def solve_one(item: dict, api_url: str) -> str:
prompt = ANSWER_RULES + "\n\nQuestion:\n" + item["question"]
file_path = download_task_file(api_url, item["task_id"], item.get("file_name", ""))
if file_path:
prompt += f"\n\nAn attached file is available at: {file_path}"

agent = build_agent()
result = agent.run(prompt)
return clean_answer(result)

def solve_with_timeout(item: dict, api_url: str) -> tuple[str, bool]:
task_id = item["task_id"]
cached = load_cache().get(task_id)
if cached:
print(f"[cache] {task_id} -> {cached}")
return cached, True

box: dict = {}
def target():
try:
box["answer"] = solve_one(item, api_url)
except Exception as e: # noqa: BLE001
box["error"] = str(e)

print(f"[start] {task_id}")
t = threading.Thread(target=target, daemon=True)
t.start()
t.join(QUESTION_TIMEOUT)

if t.is_alive():
print(f"[timeout] {task_id}")
return "unknown", False
if "error" in box:
print(f"[error] {task_id}: {box['error']}")
return "unknown", False

save_cache_entry(task_id, box["answer"])
print(f"[done] {task_id} -> {box['answer']}")
return box["answer"], True

def iter_solve(questions: list[dict], api_url: str):
valid = [q for q in questions if q.get("task_id") and q.get("question") is not None]
with ThreadPoolExecutor(max_workers=WORKERS) as pool:
futures = {pool.submit(solve_with_timeout, q, api_url): q for q in valid}
for fut in as_completed(futures):
answer, ok = fut.result()
yield futures[fut], answer, ok

def make_df(rows: dict, order: list[str]) -> pd.DataFrame:
data = [rows[tid] for tid in order if tid in rows]
return pd.DataFrame(data, columns=["Task ID", "Question", "Submitted Answer", "OK"])

# ---------------------------------------------------------------------------
# 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

username = profile.username
api_url = DEFAULT_API_URL
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"

yield "์งˆ๋ฌธ์„ ๊ฐ€์ ธ์˜ค๋Š” ์ค‘...", None
try:
questions = fetch_questions(api_url)
except Exception as e: # noqa: BLE001
yield f"์งˆ๋ฌธ ๊ฐ€์ ธ์˜ค๊ธฐ ์˜ค๋ฅ˜: {e}", None
return

order = [q["task_id"] for q in questions if q.get("task_id")]
total = len(order)
rows: dict = {}
start = time.time()

for item, answer, ok in iter_solve(questions, api_url):
rows[item["task_id"]] = {
"Task ID": item["task_id"],
"Question": item["question"],
"Submitted Answer": answer,
"OK": "O" if ok else "X",
}
elapsed = int(time.time() - start)
yield f"์ง„ํ–‰ {len(rows)}/{total} ์™„๋ฃŒ (๊ฒฝ๊ณผ {elapsed}

Files changed (1) hide show
  1. app.py +43 -50
app.py CHANGED
@@ -4,7 +4,6 @@ import re
4
  import threading
5
  import time
6
  from concurrent.futures import ThreadPoolExecutor, as_completed
7
-
8
  import gradio as gr
9
  import pandas as pd
10
  import requests
@@ -17,10 +16,9 @@ from smolagents import (
17
  tool,
18
  )
19
 
20
- # ZeroGPU ํ•˜๋“œ์›จ์–ด์—์„œ ์‹œ์ž‘ ์˜ค๋ฅ˜๋ฅผ ๋ง‰๊ธฐ ์œ„ํ•œ ๋”๋ฏธ ํ•จ์ˆ˜ (CPU ํ•˜๋“œ์›จ์–ด์—์„œ๋Š” ๋ฌด์‹œ๋จ)
21
  try:
22
  import spaces
23
-
24
  @spaces.GPU
25
  def _gpu_placeholder():
26
  return "ok"
@@ -28,7 +26,7 @@ except ImportError:
28
  pass
29
 
30
  # ---------------------------------------------------------------------------
31
- # ์„ค์ • (Space์˜ Variables์—์„œ ์กฐ์ • ๊ฐ€๋Šฅ)
32
  # ---------------------------------------------------------------------------
33
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
34
  FILES_DIR = "/tmp/task_files"
@@ -37,10 +35,9 @@ os.makedirs(FILES_DIR, exist_ok=True)
37
 
38
  WORKERS = int(os.getenv("WORKERS", "3")) # ๋™์‹œ ์‹คํ–‰ ๋ฌธํ•ญ ์ˆ˜
39
  QUESTION_TIMEOUT = int(os.getenv("QUESTION_TIMEOUT", "240")) # ๋ฌธํ•ญ๋‹น ์ œํ•œ ์‹œ๊ฐ„(์ดˆ)
40
- MAX_STEPS = int(os.getenv("MAX_STEPS", "8")) # ์—์ด์ „ํŠธ ์ตœ๋Œ€ ๋‹จ๊ณ„
41
 
42
- ANSWER_RULES = """
43
- You are a careful research and reasoning agent solving GAIA-style questions.
44
  Rules:
45
  1. Use the tools (web search, webpage visit, file reading, python code) whenever the
46
  question needs facts you are not 100% sure about. Do not guess.
@@ -53,15 +50,13 @@ Rules:
53
  the question asks for them.
54
  6. If a file path is given, read it with the read_local_file tool or with python code.
55
  7. Be efficient: stop researching as soon as you have a reliable answer.
56
- 8. Finish by calling final_answer(...) with the answer only.
57
- """
58
 
59
  # ---------------------------------------------------------------------------
60
- # ์บ์‹œ (๋Š๊ฒจ๋„ ํ‘ผ ๋‹ต์€ ๋ณด์กด. ์ปจํ…Œ์ด๋„ˆ๊ฐ€ ์žฌ์‹œ์ž‘๋˜๋ฉด ์ดˆ๊ธฐํ™”๋จ)
61
  # ---------------------------------------------------------------------------
62
  _cache_lock = threading.Lock()
63
 
64
-
65
  def load_cache() -> dict:
66
  try:
67
  with open(CACHE_PATH, "r", encoding="utf-8") as f:
@@ -69,7 +64,6 @@ def load_cache() -> dict:
69
  except Exception: # noqa: BLE001
70
  return {}
71
 
72
-
73
  def save_cache_entry(task_id: str, answer: str):
74
  with _cache_lock:
75
  cache = load_cache()
@@ -77,18 +71,23 @@ def save_cache_entry(task_id: str, answer: str):
77
  with open(CACHE_PATH, "w", encoding="utf-8") as f:
78
  json.dump(cache, f, ensure_ascii=False)
79
 
80
-
81
  # ---------------------------------------------------------------------------
82
- # ๋„๊ตฌ
83
  # ---------------------------------------------------------------------------
84
  @tool
85
  def read_local_file(path: str) -> str:
86
  """Reads a local file (txt, csv, json, py, md, xlsx) and returns its content as text.
87
-
88
  Args:
89
- path: Absolute path of the file to read.
90
  """
91
  try:
 
 
 
 
 
 
 
92
  lower = path.lower()
93
  if lower.endswith((".xlsx", ".xls")):
94
  sheets = pd.read_excel(path, sheet_name=None)
@@ -102,25 +101,28 @@ def read_local_file(path: str) -> str:
102
  except Exception as e: # noqa: BLE001
103
  return f"Could not read file: {e}"
104
 
105
-
106
  # ---------------------------------------------------------------------------
107
- # ์—์ด์ „ํŠธ
108
  # ---------------------------------------------------------------------------
109
  def build_model():
110
  gemini_key = os.getenv("GEMINI_API_KEY")
111
  if gemini_key:
112
- model_id = os.getenv("GEMINI_MODEL", "gemini-2.5-flash")
 
113
  return LiteLLMModel(model_id=f"gemini/{model_id}", api_key=gemini_key)
 
114
  openai_key = os.getenv("OPENAI_API_KEY")
115
  if openai_key:
116
  model_id = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
 
117
  return LiteLLMModel(model_id=f"openai/{model_id}", api_key=openai_key)
 
118
  model_id = os.getenv("HF_MODEL", "Qwen/Qwen2.5-Coder-32B-Instruct")
 
119
  return InferenceClientModel(model_id=model_id, token=os.getenv("HF_TOKEN"))
120
 
121
-
122
  def build_agent() -> CodeAgent:
123
- # ์Šค๋ ˆ๋“œ ์•ˆ์ „์„ ์œ„ํ•ด ๋ฌธํ•ญ๋งˆ๋‹ค ์ƒˆ ์—์ด์ „ํŠธ๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค.
124
  return CodeAgent(
125
  tools=[DuckDuckGoSearchTool(), VisitWebpageTool(), read_local_file],
126
  model=build_model(),
@@ -132,15 +134,13 @@ def build_agent() -> CodeAgent:
132
  verbosity_level=1,
133
  )
134
 
135
-
136
  def clean_answer(answer) -> str:
137
  text = str(answer).strip()
138
  text = re.sub(r"^\s*final answer\s*:\s*", "", text, flags=re.IGNORECASE)
139
  return text.strip().rstrip(".").strip()
140
 
141
-
142
  # ---------------------------------------------------------------------------
143
- # ์ฑ„์  ์„œ๋ฒ„ ํ†ต์‹ 
144
  # ---------------------------------------------------------------------------
145
  def fetch_questions(api_url: str) -> list[dict]:
146
  resp = requests.get(f"{api_url}/questions", timeout=30)
@@ -150,7 +150,6 @@ def fetch_questions(api_url: str) -> list[dict]:
150
  raise ValueError("์งˆ๋ฌธ ๋ชฉ๋ก์ด ๋น„์–ด ์žˆ์Šต๋‹ˆ๋‹ค.")
151
  return data
152
 
153
-
154
  def download_task_file(api_url: str, task_id: str, file_name: str):
155
  if not file_name:
156
  return None
@@ -165,20 +164,20 @@ def download_task_file(api_url: str, task_id: str, file_name: str):
165
  print(f"ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ ์‹คํŒจ ({task_id}): {e}")
166
  return None
167
 
168
-
169
  # ---------------------------------------------------------------------------
170
- # ๋ฌธํ•ญ ํ’€์ด (์บ์‹œ + ์‹œ๊ฐ„ ์ œํ•œ)
171
  # ---------------------------------------------------------------------------
172
  def solve_one(item: dict, api_url: str) -> str:
173
  prompt = ANSWER_RULES + "\n\nQuestion:\n" + item["question"]
174
  file_path = download_task_file(api_url, item["task_id"], item.get("file_name", ""))
175
  if file_path:
176
  prompt += f"\n\nAn attached file is available at: {file_path}"
177
- return clean_answer(build_agent().run(prompt))
178
-
 
 
179
 
180
  def solve_with_timeout(item: dict, api_url: str) -> tuple[str, bool]:
181
- """(๋‹ต๋ณ€, ์„ฑ๊ณต ์—ฌ๋ถ€)๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. ์„ฑ๊ณตํ•œ ๋‹ต๋งŒ ์บ์‹œ์— ์ €์žฅํ•ฉ๋‹ˆ๋‹ค."""
182
  task_id = item["task_id"]
183
  cached = load_cache().get(task_id)
184
  if cached:
@@ -186,7 +185,6 @@ def solve_with_timeout(item: dict, api_url: str) -> tuple[str, bool]:
186
  return cached, True
187
 
188
  box: dict = {}
189
-
190
  def target():
191
  try:
192
  box["answer"] = solve_one(item, api_url)
@@ -204,13 +202,12 @@ def solve_with_timeout(item: dict, api_url: str) -> tuple[str, bool]:
204
  if "error" in box:
205
  print(f"[error] {task_id}: {box['error']}")
206
  return "unknown", False
 
207
  save_cache_entry(task_id, box["answer"])
208
  print(f"[done] {task_id} -> {box['answer']}")
209
  return box["answer"], True
210
 
211
-
212
  def iter_solve(questions: list[dict], api_url: str):
213
- """๋ฌธํ•ญ์„ ๋ณ‘๋ ฌ๋กœ ํ’€๋ฉด์„œ, ๋๋‚˜๋Š” ๋Œ€๋กœ (item, answer, ok)๋ฅผ ๋‚ด๋ณด๋ƒ…๋‹ˆ๋‹ค."""
214
  valid = [q for q in questions if q.get("task_id") and q.get("question") is not None]
215
  with ThreadPoolExecutor(max_workers=WORKERS) as pool:
216
  futures = {pool.submit(solve_with_timeout, q, api_url): q for q in valid}
@@ -218,14 +215,12 @@ def iter_solve(questions: list[dict], api_url: str):
218
  answer, ok = fut.result()
219
  yield futures[fut], answer, ok
220
 
221
-
222
  def make_df(rows: dict, order: list[str]) -> pd.DataFrame:
223
  data = [rows[tid] for tid in order if tid in rows]
224
  return pd.DataFrame(data, columns=["Task ID", "Question", "Submitted Answer", "OK"])
225
 
226
-
227
  # ---------------------------------------------------------------------------
228
- # Gradio ์ฝœ๋ฐฑ (์ œ๋„ˆ๋ ˆ์ดํ„ฐ: ์ง„ํ–‰ ์ƒํ™ฉ์ด ์‹ค์‹œ๊ฐ„์œผ๋กœ ํ™”๋ฉด์— ํ‘œ์‹œ๋จ)
229
  # ---------------------------------------------------------------------------
230
  def run_and_submit_all(profile: gr.OAuthProfile | None):
231
  space_id = os.getenv("SPACE_ID")
@@ -235,6 +230,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
235
  if not space_id:
236
  yield "SPACE_ID๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. Space ์•ˆ์—์„œ ์‹คํ–‰ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.", None
237
  return
 
238
  username = profile.username
239
  api_url = DEFAULT_API_URL
240
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
@@ -289,11 +285,10 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
289
  status = f"์ œ์ถœ ์‹คํŒจ: {detail}"
290
  except Exception as e: # noqa: BLE001
291
  status = f"์ œ์ถœ ์ค‘ ์˜ค๋ฅ˜: {e}"
292
- yield status, make_df(rows, order)
293
 
 
294
 
295
  def run_test_only(n_questions: int):
296
- """์ œ์ถœ ์—†์ด ์•ž์˜ N๊ฐœ ๋ฌธํ•ญ๋งŒ ์‹คํ–‰ (์ ์ˆ˜์— ์˜ํ–ฅ ์—†์Œ)"""
297
  api_url = DEFAULT_API_URL
298
  yield "์งˆ๋ฌธ์„ ๊ฐ€์ ธ์˜ค๋Š” ์ค‘...", None
299
  try:
@@ -301,9 +296,11 @@ def run_test_only(n_questions: int):
301
  except Exception as e: # noqa: BLE001
302
  yield f"์ค€๋น„ ์ค‘ ์˜ค๋ฅ˜: {e}", None
303
  return
 
304
  order = [q["task_id"] for q in questions if q.get("task_id")]
305
  rows: dict = {}
306
  start = time.time()
 
307
  for item, answer, ok in iter_solve(questions, api_url):
308
  rows[item["task_id"]] = {
309
  "Task ID": item["task_id"],
@@ -315,8 +312,8 @@ def run_test_only(n_questions: int):
315
  f"ํ…Œ์ŠคํŠธ ์ง„ํ–‰ {len(rows)}/{len(order)} (๊ฒฝ๊ณผ {int(time.time() - start)}์ดˆ)",
316
  make_df(rows, order),
317
  )
318
- yield f"ํ…Œ์ŠคํŠธ ์™„๋ฃŒ ({int(time.time() - start)}์ดˆ, ์ œ์ถœ ์•ˆ ํ•จ)", make_df(rows, order)
319
 
 
320
 
321
  def clear_cache():
322
  try:
@@ -325,28 +322,25 @@ def clear_cache():
325
  except FileNotFoundError:
326
  return "์‚ญ์ œํ•  ์บ์‹œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."
327
 
328
-
329
  # ---------------------------------------------------------------------------
330
- # UI
331
  # ---------------------------------------------------------------------------
332
  with gr.Blocks() as demo:
333
- gr.Markdown("# Basic Agent Evaluation Runner")
334
  gr.Markdown(
335
- """
336
- **Instructions:**
337
  1. ์ด Space๋ฅผ ๋ณต์ œ(Duplicate)ํ•œ ๋’ค ์ฝ”๋“œ๋ฅผ ์ˆ˜์ •ํ•ด ์—์ด์ „ํŠธ ๋กœ์ง์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค.
338
  2. ์•„๋ž˜ ๋ฒ„ํŠผ์œผ๋กœ Hugging Face์— ๋กœ๊ทธ์ธํ•ฉ๋‹ˆ๋‹ค. (HF ์‚ฌ์šฉ์ž๋ช…์œผ๋กœ ์ œ์ถœ๋ฉ๋‹ˆ๋‹ค)
339
- 3. ๋จผ์ € 'ํ…Œ์ŠคํŠธ ์‹คํ–‰'์œผ๋กœ ์†Œ์ˆ˜ ๋ฌธํ•ญ์„ ํ™•์ธํ•˜๊ณ , ๋ฌธ์ œ์—†์œผ๋ฉด 'Run Evaluation & Submit All Answers'๋ฅผ ๋ˆ„๋ฆ…๋‹ˆ๋‹ค.
340
- """
341
  )
342
  gr.LoginButton()
343
-
344
  with gr.Row():
345
  test_n = gr.Number(value=2, label="ํ…Œ์ŠคํŠธํ•  ๋ฌธํ•ญ ์ˆ˜ (์ œ์ถœ ์•ˆ ํ•จ)", precision=0)
346
  test_button = gr.Button("ํ…Œ์ŠคํŠธ ์‹คํ–‰ (์ œ์ถœ ์•ˆ ํ•จ)")
347
  cache_button = gr.Button("์บ์‹œ ์ดˆ๊ธฐํ™”")
 
348
  run_button = gr.Button("Run Evaluation & Submit All Answers")
349
-
350
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=6, interactive=False)
351
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
352
 
@@ -355,5 +349,4 @@ with gr.Blocks() as demo:
355
  cache_button.click(fn=clear_cache, outputs=[status_output])
356
 
357
  if __name__ == "__main__":
358
- demo.queue().launch(debug=True, share=False)
359
-
 
4
  import threading
5
  import time
6
  from concurrent.futures import ThreadPoolExecutor, as_completed
 
7
  import gradio as gr
8
  import pandas as pd
9
  import requests
 
16
  tool,
17
  )
18
 
19
+ # ZeroGPU ํ•˜๋“œ์›จ์–ด์—์„œ ์‹œ์ž‘ ์˜ค๋ฅ˜๋ฅผ ๋ง‰๊ธฐ ์œ„ํ•œ ์•ˆ์ „ํ•œ ๋”๋ฏธ ํ•จ์ˆ˜
20
  try:
21
  import spaces
 
22
  @spaces.GPU
23
  def _gpu_placeholder():
24
  return "ok"
 
26
  pass
27
 
28
  # ---------------------------------------------------------------------------
29
+ # ์„ค์ • (Space์˜ Variables ๋˜๋Š” Secrets์—์„œ ์กฐ์ • ๊ฐ€๋Šฅ)
30
  # ---------------------------------------------------------------------------
31
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
32
  FILES_DIR = "/tmp/task_files"
 
35
 
36
  WORKERS = int(os.getenv("WORKERS", "3")) # ๋™์‹œ ์‹คํ–‰ ๋ฌธํ•ญ ์ˆ˜
37
  QUESTION_TIMEOUT = int(os.getenv("QUESTION_TIMEOUT", "240")) # ๋ฌธํ•ญ๋‹น ์ œํ•œ ์‹œ๊ฐ„(์ดˆ)
38
+ MAX_STEPS = int(os.getenv("MAX_STEPS", "12")) # ์—์ด์ „ํŠธ ์ตœ๋Œ€ ๋‹จ๊ณ„
39
 
40
+ ANSWER_RULES = """You are a careful research and reasoning agent solving GAIA-style questions.
 
41
  Rules:
42
  1. Use the tools (web search, webpage visit, file reading, python code) whenever the
43
  question needs facts you are not 100% sure about. Do not guess.
 
50
  the question asks for them.
51
  6. If a file path is given, read it with the read_local_file tool or with python code.
52
  7. Be efficient: stop researching as soon as you have a reliable answer.
53
+ 8. Finish by calling final_answer(...) with the answer only."""
 
54
 
55
  # ---------------------------------------------------------------------------
56
+ # ์บ์‹œ ๊ด€๋ฆฌ
57
  # ---------------------------------------------------------------------------
58
  _cache_lock = threading.Lock()
59
 
 
60
  def load_cache() -> dict:
61
  try:
62
  with open(CACHE_PATH, "r", encoding="utf-8") as f:
 
64
  except Exception: # noqa: BLE001
65
  return {}
66
 
 
67
  def save_cache_entry(task_id: str, answer: str):
68
  with _cache_lock:
69
  cache = load_cache()
 
71
  with open(CACHE_PATH, "w", encoding="utf-8") as f:
72
  json.dump(cache, f, ensure_ascii=False)
73
 
 
74
  # ---------------------------------------------------------------------------
75
+ # ๋„๊ตฌ (ํŒŒ์ผ ๊ฒฝ๋กœ ๋ณด์™„ ๊ธฐ๋Šฅ ํฌํ•จ)
76
  # ---------------------------------------------------------------------------
77
  @tool
78
  def read_local_file(path: str) -> str:
79
  """Reads a local file (txt, csv, json, py, md, xlsx) and returns its content as text.
 
80
  Args:
81
+ path: Absolute or relative path of the file to read.
82
  """
83
  try:
84
+ # ์—์ด์ „ํŠธ๊ฐ€ ํŒŒ์ผ๋ช…๋งŒ ์ž…๋ ฅํ•˜๊ฑฐ๋‚˜ ๊ฒฝ๋กœ๊ฐ€ ์ž˜๋ชป๋œ ๊ฒฝ์šฐ FILES_DIR์—์„œ ํƒ์ƒ‰
85
+ if not os.path.exists(path):
86
+ basename = os.path.basename(path)
87
+ candidate = os.path.join(FILES_DIR, basename)
88
+ if os.path.exists(candidate):
89
+ path = candidate
90
+
91
  lower = path.lower()
92
  if lower.endswith((".xlsx", ".xls")):
93
  sheets = pd.read_excel(path, sheet_name=None)
 
101
  except Exception as e: # noqa: BLE001
102
  return f"Could not read file: {e}"
103
 
 
104
  # ---------------------------------------------------------------------------
105
+ # ์—์ด์ „ํŠธ ๋ฐ ๋ชจ๋ธ ์„ค์ • (gemini-3.8-flash ๋ฐ˜์˜)
106
  # ---------------------------------------------------------------------------
107
  def build_model():
108
  gemini_key = os.getenv("GEMINI_API_KEY")
109
  if gemini_key:
110
+ model_id = os.getenv("GEMINI_MODEL", "gemini-3.8-flash")
111
+ print(f"[model] Gemini: {model_id}")
112
  return LiteLLMModel(model_id=f"gemini/{model_id}", api_key=gemini_key)
113
+
114
  openai_key = os.getenv("OPENAI_API_KEY")
115
  if openai_key:
116
  model_id = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
117
+ print(f"[model] OpenAI: {model_id}")
118
  return LiteLLMModel(model_id=f"openai/{model_id}", api_key=openai_key)
119
+
120
  model_id = os.getenv("HF_MODEL", "Qwen/Qwen2.5-Coder-32B-Instruct")
121
+ print(f"[model] HF Inference: {model_id}")
122
  return InferenceClientModel(model_id=model_id, token=os.getenv("HF_TOKEN"))
123
 
 
124
  def build_agent() -> CodeAgent:
125
+ # ์Šค๋ ˆ๋“œ ์•ˆ์ „ ๋ฐ ๋ฌธํ•ญ๋ณ„ ๋…๋ฆฝ ์ปจํ…์ŠคํŠธ ์œ ์ง€๋ฅผ ์œ„ํ•ด ๋งค๋ฒˆ ์ƒˆ ์—์ด์ „ํŠธ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
126
  return CodeAgent(
127
  tools=[DuckDuckGoSearchTool(), VisitWebpageTool(), read_local_file],
128
  model=build_model(),
 
134
  verbosity_level=1,
135
  )
136
 
 
137
  def clean_answer(answer) -> str:
138
  text = str(answer).strip()
139
  text = re.sub(r"^\s*final answer\s*:\s*", "", text, flags=re.IGNORECASE)
140
  return text.strip().rstrip(".").strip()
141
 
 
142
  # ---------------------------------------------------------------------------
143
+ # ์ฑ„์  ์„œ๋ฒ„ ํ†ต์‹  ๋ฐ ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ
144
  # ---------------------------------------------------------------------------
145
  def fetch_questions(api_url: str) -> list[dict]:
146
  resp = requests.get(f"{api_url}/questions", timeout=30)
 
150
  raise ValueError("์งˆ๋ฌธ ๋ชฉ๋ก์ด ๋น„์–ด ์žˆ์Šต๋‹ˆ๋‹ค.")
151
  return data
152
 
 
153
  def download_task_file(api_url: str, task_id: str, file_name: str):
154
  if not file_name:
155
  return None
 
164
  print(f"ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ ์‹คํŒจ ({task_id}): {e}")
165
  return None
166
 
 
167
  # ---------------------------------------------------------------------------
168
+ # ๊ฐœ๋ณ„ ๋ฌธํ•ญ ํ’€์ด (์บ์‹œ + ํƒ€์ž„์•„์›ƒ)
169
  # ---------------------------------------------------------------------------
170
  def solve_one(item: dict, api_url: str) -> str:
171
  prompt = ANSWER_RULES + "\n\nQuestion:\n" + item["question"]
172
  file_path = download_task_file(api_url, item["task_id"], item.get("file_name", ""))
173
  if file_path:
174
  prompt += f"\n\nAn attached file is available at: {file_path}"
175
+
176
+ agent = build_agent()
177
+ result = agent.run(prompt)
178
+ return clean_answer(result)
179
 
180
  def solve_with_timeout(item: dict, api_url: str) -> tuple[str, bool]:
 
181
  task_id = item["task_id"]
182
  cached = load_cache().get(task_id)
183
  if cached:
 
185
  return cached, True
186
 
187
  box: dict = {}
 
188
  def target():
189
  try:
190
  box["answer"] = solve_one(item, api_url)
 
202
  if "error" in box:
203
  print(f"[error] {task_id}: {box['error']}")
204
  return "unknown", False
205
+
206
  save_cache_entry(task_id, box["answer"])
207
  print(f"[done] {task_id} -> {box['answer']}")
208
  return box["answer"], True
209
 
 
210
  def iter_solve(questions: list[dict], api_url: str):
 
211
  valid = [q for q in questions if q.get("task_id") and q.get("question") is not None]
212
  with ThreadPoolExecutor(max_workers=WORKERS) as pool:
213
  futures = {pool.submit(solve_with_timeout, q, api_url): q for q in valid}
 
215
  answer, ok = fut.result()
216
  yield futures[fut], answer, ok
217
 
 
218
  def make_df(rows: dict, order: list[str]) -> pd.DataFrame:
219
  data = [rows[tid] for tid in order if tid in rows]
220
  return pd.DataFrame(data, columns=["Task ID", "Question", "Submitted Answer", "OK"])
221
 
 
222
  # ---------------------------------------------------------------------------
223
+ # Gradio ์ฝœ๋ฐฑ (์‹ค์‹œ๊ฐ„ ์ง„ํ–‰ ์ƒํ™ฉ ์ œ๋„ˆ๋ ˆ์ดํ„ฐ ๋ฐ˜์˜)
224
  # ---------------------------------------------------------------------------
225
  def run_and_submit_all(profile: gr.OAuthProfile | None):
226
  space_id = os.getenv("SPACE_ID")
 
230
  if not space_id:
231
  yield "SPACE_ID๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. Space ์•ˆ์—์„œ ์‹คํ–‰ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.", None
232
  return
233
+
234
  username = profile.username
235
  api_url = DEFAULT_API_URL
236
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
285
  status = f"์ œ์ถœ ์‹คํŒจ: {detail}"
286
  except Exception as e: # noqa: BLE001
287
  status = f"์ œ์ถœ ์ค‘ ์˜ค๋ฅ˜: {e}"
 
288
 
289
+ yield status, make_df(rows, order)
290
 
291
  def run_test_only(n_questions: int):
 
292
  api_url = DEFAULT_API_URL
293
  yield "์งˆ๋ฌธ์„ ๊ฐ€์ ธ์˜ค๋Š” ์ค‘...", None
294
  try:
 
296
  except Exception as e: # noqa: BLE001
297
  yield f"์ค€๋น„ ์ค‘ ์˜ค๋ฅ˜: {e}", None
298
  return
299
+
300
  order = [q["task_id"] for q in questions if q.get("task_id")]
301
  rows: dict = {}
302
  start = time.time()
303
+
304
  for item, answer, ok in iter_solve(questions, api_url):
305
  rows[item["task_id"]] = {
306
  "Task ID": item["task_id"],
 
312
  f"ํ…Œ์ŠคํŠธ ์ง„ํ–‰ {len(rows)}/{len(order)} (๊ฒฝ๊ณผ {int(time.time() - start)}์ดˆ)",
313
  make_df(rows, order),
314
  )
 
315
 
316
+ yield f"ํ…Œ์ŠคํŠธ ์™„๋ฃŒ ({int(time.time() - start)}์ดˆ, ์ œ์ถœ ์•ˆ ํ•จ)", make_df(rows, order)
317
 
318
  def clear_cache():
319
  try:
 
322
  except FileNotFoundError:
323
  return "์‚ญ์ œํ•  ์บ์‹œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."
324
 
 
325
  # ---------------------------------------------------------------------------
326
+ # Gradio UI ๊ตฌ์„ฑ
327
  # ---------------------------------------------------------------------------
328
  with gr.Blocks() as demo:
329
+ gr.Markdown("# Basic Agent Evaluation Runner (Gemini 3.8 Flash)")
330
  gr.Markdown(
331
+ """**Instructions:**
 
332
  1. ์ด Space๋ฅผ ๋ณต์ œ(Duplicate)ํ•œ ๋’ค ์ฝ”๋“œ๋ฅผ ์ˆ˜์ •ํ•ด ์—์ด์ „ํŠธ ๋กœ์ง์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค.
333
  2. ์•„๋ž˜ ๋ฒ„ํŠผ์œผ๋กœ Hugging Face์— ๋กœ๊ทธ์ธํ•ฉ๋‹ˆ๋‹ค. (HF ์‚ฌ์šฉ์ž๋ช…์œผ๋กœ ์ œ์ถœ๋ฉ๋‹ˆ๋‹ค)
334
+ 3. ๋จผ์ € 'ํ…Œ์ŠคํŠธ ์‹คํ–‰'์œผ๋กœ ์†Œ์ˆ˜ ๋ฌธํ•ญ์„ ํ™•์ธํ•˜๊ณ , ๋ฌธ์ œ์—†์œผ๋ฉด 'Run Evaluation & Submit All Answers'๋ฅผ ๋ˆ„๋ฆ…๋‹ˆ๋‹ค."""
 
335
  )
336
  gr.LoginButton()
337
+
338
  with gr.Row():
339
  test_n = gr.Number(value=2, label="ํ…Œ์ŠคํŠธํ•  ๋ฌธํ•ญ ์ˆ˜ (์ œ์ถœ ์•ˆ ํ•จ)", precision=0)
340
  test_button = gr.Button("ํ…Œ์ŠคํŠธ ์‹คํ–‰ (์ œ์ถœ ์•ˆ ํ•จ)")
341
  cache_button = gr.Button("์บ์‹œ ์ดˆ๊ธฐํ™”")
342
+
343
  run_button = gr.Button("Run Evaluation & Submit All Answers")
 
344
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=6, interactive=False)
345
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
346
 
 
349
  cache_button.click(fn=clear_cache, outputs=[status_output])
350
 
351
  if __name__ == "__main__":
352
+ demo.queue().launch(debug=True, share=False)