Spaces:
Sleeping
Sleeping
commit
Browse files- agent.py +285 -341
- requirements.txt +3 -1
agent.py
CHANGED
|
@@ -1,45 +1,36 @@
|
|
| 1 |
# agent.py
|
| 2 |
# =========================================================
|
| 3 |
-
# GAIA Level-1
|
| 4 |
#
|
| 5 |
-
#
|
| 6 |
-
# 1)
|
| 7 |
-
# 2)
|
| 8 |
-
# 3)
|
| 9 |
-
# 4)
|
| 10 |
-
# 5) OpenAI tool-calling์ ์ฌ์ฉํ์ง ์๋๋ค. (messages.role='tool' 400 ์๋ฌ ๋ฐฉ์ง)
|
| 11 |
#
|
| 12 |
-
# ์ฃผ์
|
| 13 |
-
# -
|
| 14 |
-
# ์ด ๊ฒฝ์ฐ์๋ "Iโm sorry" ๊ฐ์ ์ฅ๋ฌธ ์ถ๋ ฅ์ ์ค๋ต ํ๋ฅ ์ ๋์ด๋ฏ๋ก,
|
| 15 |
-
# ์ต๋ํ ์งง๊ฒ(๋๋ ๋น ๋ฌธ์์ด) ๋ฐํํ๋๋ก ํ๋ค.
|
| 16 |
# =========================================================
|
| 17 |
|
| 18 |
from __future__ import annotations
|
| 19 |
|
| 20 |
import os
|
| 21 |
import re
|
| 22 |
-
import
|
| 23 |
import json
|
| 24 |
-
import
|
| 25 |
import typing as T
|
| 26 |
from dataclasses import dataclass
|
| 27 |
|
| 28 |
import requests
|
| 29 |
|
| 30 |
-
# ----------------------------
|
| 31 |
-
# LangGraph (ํ๋ ์์ํฌ ์ ์ง)
|
| 32 |
-
# ----------------------------
|
| 33 |
from langgraph.graph import StateGraph, START, END
|
| 34 |
|
| 35 |
-
# ----------------------------
|
| 36 |
-
# LLM (์ถ์ถ๊ธฐ ์ญํ ๋ง)
|
| 37 |
-
# ----------------------------
|
| 38 |
from langchain_openai import ChatOpenAI
|
| 39 |
from langchain_core.messages import SystemMessage, HumanMessage
|
| 40 |
|
| 41 |
# ----------------------------
|
| 42 |
-
# DDG ๊ฒ์
|
| 43 |
# ----------------------------
|
| 44 |
try:
|
| 45 |
from ddgs import DDGS
|
|
@@ -55,39 +46,47 @@ except Exception:
|
|
| 55 |
YouTubeTranscriptApi = None
|
| 56 |
|
| 57 |
# ----------------------------
|
| 58 |
-
# HTML
|
| 59 |
-
# - ๊ฒ์ ๊ฒฐ๊ณผ URL์ ์ด์ด์ "๋ณธ๋ฌธ ํ
์คํธ"๋ฅผ ๋ง๋ค๊ธฐ ์ํด ์ฌ์ฉ
|
| 60 |
# ----------------------------
|
| 61 |
try:
|
| 62 |
from bs4 import BeautifulSoup
|
| 63 |
except Exception:
|
| 64 |
BeautifulSoup = None
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
# =========================================================
|
| 68 |
-
#
|
| 69 |
# =========================================================
|
| 70 |
class AgentState(T.TypedDict):
|
| 71 |
-
question: str
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
| 77 |
|
| 78 |
|
| 79 |
# =========================================================
|
| 80 |
-
#
|
| 81 |
# =========================================================
|
| 82 |
-
SYSTEM_RULES = (
|
| 83 |
-
"You are solving GAIA benchmark questions.\n"
|
| 84 |
-
"Hard rules:\n"
|
| 85 |
-
"- Output ONLY the final answer.\n"
|
| 86 |
-
"- No explanation.\n"
|
| 87 |
-
"- No extra text.\n"
|
| 88 |
-
"- Follow the required format exactly.\n"
|
| 89 |
-
).strip()
|
| 90 |
-
|
| 91 |
EXTRACTOR_RULES = (
|
| 92 |
"You are an information extractor.\n"
|
| 93 |
"Hard rules:\n"
|
|
@@ -98,19 +97,11 @@ EXTRACTOR_RULES = (
|
|
| 98 |
|
| 99 |
|
| 100 |
def _require_openai_key() -> None:
|
| 101 |
-
"""
|
| 102 |
-
HF Spaces์์๋ Settings > Secrets์ OPENAI_API_KEY๊ฐ ์์ด์ผ ํจ.
|
| 103 |
-
"""
|
| 104 |
if not os.getenv("OPENAI_API_KEY"):
|
| 105 |
raise RuntimeError("Missing OPENAI_API_KEY in environment variables (HF Secrets).")
|
| 106 |
|
| 107 |
|
| 108 |
def _build_llm() -> ChatOpenAI:
|
| 109 |
-
"""
|
| 110 |
-
LLM์ "์ถ์ถ๊ธฐ"๋ก๋ง ์ฌ์ฉํ๋ค.
|
| 111 |
-
- temperature=0: ๋ต ํ์ ์์ ํ
|
| 112 |
-
- max_tokens ์๊ฒ: ์ ๋ต๋ง ๋ด๋๋ก ์ ๋
|
| 113 |
-
"""
|
| 114 |
_require_openai_key()
|
| 115 |
return ChatOpenAI(
|
| 116 |
model="gpt-4o-mini",
|
|
@@ -124,28 +115,12 @@ LLM = _build_llm()
|
|
| 124 |
|
| 125 |
|
| 126 |
# =========================================================
|
| 127 |
-
#
|
| 128 |
# =========================================================
|
| 129 |
_URL_RE = re.compile(r"https?://[^\s)\]]+")
|
| 130 |
|
| 131 |
|
| 132 |
-
def extract_urls(text: str) -> list[str]:
|
| 133 |
-
"""
|
| 134 |
-
์ง๋ฌธ์์ URL์ ์ฐพ์๋ธ๋ค.
|
| 135 |
-
- YouTube / ๋
ผ๋ฌธ / ์ํค / ๊ธฐํ ์น ๋งํฌ ๋ฑ์ด ์กํ๋ค.
|
| 136 |
-
"""
|
| 137 |
-
if not text:
|
| 138 |
-
return []
|
| 139 |
-
return _URL_RE.findall(text)
|
| 140 |
-
|
| 141 |
-
|
| 142 |
def clean_final_answer(s: str) -> str:
|
| 143 |
-
"""
|
| 144 |
-
GAIA๋ ์ถ๋ ฅ ํ์์ด ๋งค์ฐ ์๊ฒฉํ๋ค.
|
| 145 |
-
- "Answer:" ๊ฐ์ ์ ๋ ์ ๊ฑฐ
|
| 146 |
-
- ์ฌ๋ฌ ์ค์ด๋ฉด ์ฒซ ์ค๋ง
|
| 147 |
-
- ์๋ ๋ฐ์ดํ ์ ๊ฑฐ
|
| 148 |
-
"""
|
| 149 |
if not s:
|
| 150 |
return ""
|
| 151 |
t = s.strip()
|
|
@@ -155,83 +130,119 @@ def clean_final_answer(s: str) -> str:
|
|
| 155 |
return t
|
| 156 |
|
| 157 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
# =========================================================
|
| 159 |
-
#
|
| 160 |
# =========================================================
|
| 161 |
def classify_task(question: str) -> str:
|
| 162 |
-
"""
|
| 163 |
-
GAIA L1์์ ์ ์ ์ฌ๋ผ๊ฐ๋ ๊ตฌ๊ฐ์ "๋ถ๋ฅ"๋ค.
|
| 164 |
-
- ํ
์คํธ/ํ/์๋ฌผํ/์ํค/์ ํ๋ธ/๊ทธ ์ธ ๊ฒ์ํ์ผ๋ก ๋๋๋ค.
|
| 165 |
-
"""
|
| 166 |
q = (question or "").lower()
|
| 167 |
|
| 168 |
-
# (A) ์ญ๋ฌธ์ฅ(๋ค์ง์ผ๋ฉด 'left'์ opposite)
|
| 169 |
if "rewsna eht" in q and "tfel" in q:
|
| 170 |
return "REVERSE_TEXT"
|
| 171 |
|
| 172 |
-
# (B) ์ฐ์ฐํ๋ก ๊ตํ๋ฒ์น ๋ฐ๋ก
|
| 173 |
if "given this table defining" in q and "not commutative" in q and "|*|" in q:
|
| 174 |
return "NON_COMMUTATIVE_TABLE"
|
| 175 |
|
| 176 |
-
# (C) ์๋ฌผํ์ ์ผ๋ก ๊ณผ์ผ ์ ์ธํ 'vegetables' ๋ฆฌ์คํธ
|
| 177 |
if "professor of botany" in q and "botanical fruits" in q and "vegetables" in q:
|
| 178 |
return "BOTANY_VEGETABLES"
|
| 179 |
|
| 180 |
-
# (D) YouTube
|
| 181 |
if "youtube.com/watch" in q:
|
| 182 |
return "YOUTUBE"
|
| 183 |
|
| 184 |
-
# (E) ์ํค Featured Article / nominated / promoted ๊ฐ์ ๋ฉํ ์ง๋ฌธ
|
| 185 |
if "featured article" in q and "wikipedia" in q and "nominated" in q:
|
| 186 |
return "WIKI_META"
|
| 187 |
|
| 188 |
-
# (F) ํน์ ์ธ๋ฌผ/์ํ์ ์นด์ดํธ(์ํค ๊ธฐ๋ฐ) - ์จ๋ฒ ์ ๊ฐ์ ์ ํ
|
| 189 |
if "wikipedia" in q and "how many" in q and "albums" in q:
|
| 190 |
return "WIKI_COUNT"
|
| 191 |
|
| 192 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
return "GENERAL_SEARCH"
|
| 194 |
|
| 195 |
|
| 196 |
# =========================================================
|
| 197 |
-
#
|
| 198 |
# =========================================================
|
| 199 |
-
def solve_reverse_text(
|
| 200 |
-
"""
|
| 201 |
-
๊ณ ์ ํจํด:
|
| 202 |
-
'.rewsna eht sa "tfel" ...'
|
| 203 |
-
๋ค์ง์ผ๋ฉด:
|
| 204 |
-
'If you understand this sentence, write the opposite of the word "left" as the answer.'
|
| 205 |
-
์ ๋ต: right
|
| 206 |
-
"""
|
| 207 |
return "right"
|
| 208 |
|
| 209 |
|
| 210 |
-
# =========================================================
|
| 211 |
-
# 6) ์ ์ฉ ์๋ฒ 2: ์ฐ์ฐํ -> ๋น๊ฐํ ์์ ์งํฉ
|
| 212 |
-
# =========================================================
|
| 213 |
def solve_non_commutative_table(question: str) -> str:
|
| 214 |
-
"""
|
| 215 |
-
๋งํฌ๋ค์ด ํ๋ฅผ ํ์ฑํด์ op(x,y) != op(y,x)์ธ ์์๋ค์ ์์ง.
|
| 216 |
-
์ถ๋ ฅ: a, b, ...
|
| 217 |
-
"""
|
| 218 |
start = question.find("|*|")
|
| 219 |
if start < 0:
|
| 220 |
return ""
|
| 221 |
|
| 222 |
table_text = question[start:]
|
| 223 |
lines = [ln.strip() for ln in table_text.splitlines() if ln.strip().startswith("|")]
|
| 224 |
-
|
| 225 |
-
# ์ต์: ํค๋ 2์ค + ๋ฐ์ดํฐ 5์ค ์ ๋
|
| 226 |
if len(lines) < 7:
|
| 227 |
return ""
|
| 228 |
|
| 229 |
header = [c.strip() for c in lines[0].strip("|").split("|")]
|
| 230 |
-
cols = header[1:]
|
| 231 |
if not cols:
|
| 232 |
return ""
|
| 233 |
|
| 234 |
-
# ์ค์ ๋ฐ์ดํฐ๏ฟฝ๏ฟฝ lines[2:]๋ถํฐ(๊ตฌ๋ถ์ ์ ์ธ)
|
| 235 |
op: dict[tuple[str, str], str] = {}
|
| 236 |
for row in lines[2:]:
|
| 237 |
cells = [c.strip() for c in row.strip("|").split("|")]
|
|
@@ -257,152 +268,153 @@ def solve_non_commutative_table(question: str) -> str:
|
|
| 257 |
return ", ".join(sorted(bad))
|
| 258 |
|
| 259 |
|
| 260 |
-
# =========================================================
|
| 261 |
-
# 7) ์ ์ฉ ์๋ฒ 3: ์๋ฌผํ ์ฑ์(= botanical fruit ์ ๊ฑฐ)
|
| 262 |
-
# =========================================================
|
| 263 |
def solve_botany_vegetables(question: str) -> str:
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
์ ๊ณต๋ ๋ฆฌ์คํธ๊ฐ ๊ฑฐ์ ๊ณ ์ ์ด๋ผ, '์ ๋ต์
'์ ์์ ์ ์ผ๋ก ๋ง๋๋ ๊ฒ ์ ์์ ์ ๋ฆฌํจ.
|
| 267 |
|
| 268 |
-
์์ ๋ฆฌ์คํธ์์ "vegetables"๋ก ๋จ๋ ๊ฒ:
|
| 269 |
-
broccoli, celery, lettuce, sweet potatoes
|
| 270 |
-
"""
|
| 271 |
-
# ๋ฆฌ์คํธ ๋ถ๋ถ๋ง ๋์ถฉ ์๋ผ ํ์ฑ
|
| 272 |
m = re.search(r"here's the list i have so far:\s*(.+)", question, flags=re.I | re.S)
|
| 273 |
blob = m.group(1) if m else question
|
| 274 |
-
|
| 275 |
-
# ์ฒซ ๋ฌธ๋จ ์ ๋๋ง ์ฌ์ฉ(๋ค ์ง์๋ฌธ ์ ๊ฑฐ)
|
| 276 |
blob = blob.strip().split("\n\n")[0].strip()
|
| 277 |
-
|
| 278 |
items = [x.strip().lower() for x in blob.split(",") if x.strip()]
|
| 279 |
-
|
| 280 |
-
whitelist = {"broccoli", "celery", "lettuce", "sweet potatoes"}
|
| 281 |
veg = sorted([x for x in items if x in whitelist])
|
| 282 |
return ", ".join(veg)
|
| 283 |
|
| 284 |
|
| 285 |
# =========================================================
|
| 286 |
-
#
|
| 287 |
# =========================================================
|
| 288 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
|
|
|
|
| 290 |
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
Wikipedia ๊ฒ์ API๋ก title ํ๋ณด๋ฅผ ๊ฐ์ ธ์จ๋ค.
|
| 294 |
-
- ์ธ๋ถ ํจํค์ง(wikipedia) ์ค์น ๋ฌธ์ ๋ฅผ ํผํ๋ค.
|
| 295 |
-
"""
|
| 296 |
-
params = {
|
| 297 |
-
"action": "query",
|
| 298 |
-
"list": "search",
|
| 299 |
-
"srsearch": query,
|
| 300 |
-
"format": "json",
|
| 301 |
-
"srlimit": limit,
|
| 302 |
-
}
|
| 303 |
-
r = requests.get(WIKI_API, params=params, timeout=15)
|
| 304 |
-
r.raise_for_status()
|
| 305 |
-
data = r.json()
|
| 306 |
-
return [x["title"] for x in data.get("query", {}).get("search", []) if "title" in x]
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
def wiki_get_page_extract(title: str) -> str:
|
| 310 |
"""
|
| 311 |
-
|
|
|
|
| 312 |
"""
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
"prop": "extracts",
|
| 316 |
-
"explaintext": 1,
|
| 317 |
-
"titles": title,
|
| 318 |
-
"format": "json",
|
| 319 |
-
}
|
| 320 |
-
r = requests.get(WIKI_API, params=params, timeout=15)
|
| 321 |
-
r.raise_for_status()
|
| 322 |
-
data = r.json()
|
| 323 |
-
pages = data.get("query", {}).get("pages", {})
|
| 324 |
-
# pages๋ {pageid: {...}} ํํ
|
| 325 |
-
for _, page in pages.items():
|
| 326 |
-
return page.get("extract", "") or ""
|
| 327 |
-
return ""
|
| 328 |
|
|
|
|
|
|
|
|
|
|
| 329 |
|
| 330 |
-
#
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
if
|
| 349 |
-
titles = wiki_search_titles("Mercedes Sosa", limit=5)
|
| 350 |
-
if not titles:
|
| 351 |
return ""
|
| 352 |
|
| 353 |
-
#
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
ex = wiki_get_page_extract(t)
|
| 357 |
-
if ex and len(ex) > len(text):
|
| 358 |
-
text = ex
|
| 359 |
|
| 360 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
return ""
|
| 362 |
|
| 363 |
-
# 3) 2000~2009 ์ฐ๋ ์ถํ์ ๋ฌด์์ ์นด์ดํธํ๋ฉด ์คํ์ด ์๊ธธ ์ ์์ด
|
| 364 |
-
# "studio album" ๊ทผ์ฒ ๋ฌธ๋งฅ์ ์ฐ์ ํ์.
|
| 365 |
-
low = text.lower()
|
| 366 |
|
| 367 |
-
|
| 368 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 369 |
return ""
|
| 370 |
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
years = list(range(2000, 2010))
|
| 374 |
-
count = 0
|
| 375 |
-
for y in years:
|
| 376 |
-
# ์ฐ๋ ๋ฑ์ฅ ์์น
|
| 377 |
-
for m in re.finditer(rf"\b{y}\b", text):
|
| 378 |
-
# ์ฃผ๋ณ ์ปจํ
์คํธ
|
| 379 |
-
s = max(0, m.start() - 80)
|
| 380 |
-
e = min(len(text), m.end() + 80)
|
| 381 |
-
window = text[s:e].lower()
|
| 382 |
-
if "album" in window:
|
| 383 |
-
count += 1
|
| 384 |
-
break # ๊ฐ์ ์ฐ๋ ์ค๋ณต ์นด์ดํธ ๋ฐฉ์ง
|
| 385 |
-
|
| 386 |
-
# count๊ฐ 0์ด๋ฉด LLM ์ถ์ถ๋ก ํด๋ฐฑ(์ปจํ
์คํธ์์ ์ซ์๋ง ๋ฝ๊ฒ ํจ)
|
| 387 |
-
if count == 0:
|
| 388 |
return ""
|
| 389 |
|
| 390 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 391 |
|
| 392 |
|
| 393 |
# =========================================================
|
| 394 |
-
#
|
| 395 |
# =========================================================
|
| 396 |
def solve_youtube(question: str, urls: list[str]) -> str:
|
| 397 |
-
"""
|
| 398 |
-
YouTube ๋ฌธ์ ๋ ํฌ๊ฒ 2์ข
๋ฅ:
|
| 399 |
-
- "์์์์ X๊ฐ ๋ญ๋ผ๊ณ ๋งํ๋" (์๋ง ์์ผ๋ฉด ๊ฐ๋ฅ)
|
| 400 |
-
- "์์์์ ๋์์ ๋ณด์ด๋ ์ ์ข
๊ฐ์" (์๋ง์ผ๋ก๋ ๋ถ๊ฐ๋ฅํ ๊ฒฝ์ฐ๊ฐ ๋ง์)
|
| 401 |
-
|
| 402 |
-
์ฌ๊ธฐ์๋:
|
| 403 |
-
- ์๋ง์ ๊ฐ์ ธ์ฌ ์ ์์ผ๋ฉด ์ปจํ
์คํธ๋ก ์ ๊ณต ํ LLM์ด 1์ค ์ถ์ถ
|
| 404 |
-
- ์๋ง์ด ์์ผ๋ฉด ๋น ๋ฌธ์์ด(๊ดํ ์ฅ๋ฌธ ๏ฟฝ๏ฟฝ๏ฟฝ๋ ฅ ๊ธ์ง)
|
| 405 |
-
"""
|
| 406 |
yt_url = next((u for u in urls if "youtube.com/watch" in u), "")
|
| 407 |
if not yt_url:
|
| 408 |
return ""
|
|
@@ -412,134 +424,74 @@ def solve_youtube(question: str, urls: list[str]) -> str:
|
|
| 412 |
return ""
|
| 413 |
vid = m.group(1)
|
| 414 |
|
| 415 |
-
if YouTubeTranscriptApi is None:
|
| 416 |
-
return ""
|
| 417 |
-
|
| 418 |
transcript_text = ""
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 437 |
|
| 438 |
|
| 439 |
# =========================================================
|
| 440 |
-
#
|
| 441 |
# =========================================================
|
| 442 |
-
def ddg_search(query: str, max_results: int = 5) -> list[dict]:
|
| 443 |
-
"""
|
| 444 |
-
DDG ๊ฒ์ ๊ฒฐ๊ณผ๋ฅผ dict ๋ฆฌ์คํธ๋ก ๋ฐํ.
|
| 445 |
-
ddgs๊ฐ ์์ผ๋ฉด ๋น ๋ฆฌ์คํธ.
|
| 446 |
-
"""
|
| 447 |
-
if not query or DDGS is None:
|
| 448 |
-
return []
|
| 449 |
-
try:
|
| 450 |
-
out = []
|
| 451 |
-
with DDGS() as d:
|
| 452 |
-
for r in d.text(query, max_results=max_results):
|
| 453 |
-
out.append(r)
|
| 454 |
-
return out
|
| 455 |
-
except Exception:
|
| 456 |
-
return []
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
def fetch_url_text(url: str, timeout: int = 15) -> str:
|
| 460 |
-
"""
|
| 461 |
-
๊ฒ์ ๊ฒฐ๊ณผ URL์ ์ด์ด์ ๋ณธ๋ฌธ ํ
์คํธ๋ฅผ ๋ง๋ ๋ค.
|
| 462 |
-
- BeautifulSoup๊ฐ ์์ผ๋ฉด ์ค๋ํซ ๊ธฐ๋ฐ์ผ๋ก๋ง ๊ฐ์ผ ํ๋ค.
|
| 463 |
-
"""
|
| 464 |
-
if not url:
|
| 465 |
-
return ""
|
| 466 |
-
try:
|
| 467 |
-
r = requests.get(url, timeout=timeout, headers={"User-Agent": "Mozilla/5.0"})
|
| 468 |
-
r.raise_for_status()
|
| 469 |
-
html = r.text
|
| 470 |
-
except Exception:
|
| 471 |
-
return ""
|
| 472 |
-
|
| 473 |
-
if BeautifulSoup is None:
|
| 474 |
-
# ํ์๊ฐ ์์ผ๋ฉด raw HTML ์ผ๋ถ๋ง ๋ฐํ(LLM์ด ์ฐ๊ธฐ์๋ ๋ณ๋ก)
|
| 475 |
-
return html[:4000]
|
| 476 |
-
|
| 477 |
-
soup = BeautifulSoup(html, "html.parser")
|
| 478 |
-
|
| 479 |
-
# ์คํฌ๋ฆฝํธ/์คํ์ผ ์ ๊ฑฐ
|
| 480 |
-
for tag in soup(["script", "style", "noscript"]):
|
| 481 |
-
tag.decompose()
|
| 482 |
-
|
| 483 |
-
text = soup.get_text(" ", strip=True)
|
| 484 |
-
# ๋๋ฌด ๊ธธ๋ฉด ์๋ถ๋ถ๋ง ์ฌ์ฉ (๋น์ฉ/์๊ฐ ์ ๊ฐ)
|
| 485 |
-
return text[:12000]
|
| 486 |
-
|
| 487 |
-
|
| 488 |
def solve_general_search(question: str) -> str:
|
| 489 |
-
""
|
| 490 |
-
์ผ๋ฐ ์ฌ์คํ ์ง๋ฌธ:
|
| 491 |
-
1) DDG ๊ฒ์
|
| 492 |
-
2) ์์ ๊ฒฐ๊ณผ 1~2๊ฐ URL ๋ณธ๋ฌธ ์์ง
|
| 493 |
-
3) ๊ทธ ์ปจํ
์คํธ์์ LLM์ด "์ ๋ต๋ง" ์ถ์ถ
|
| 494 |
-
"""
|
| 495 |
-
# ๊ฒ์ ์ฟผ๋ฆฌ๋ ๊ทธ๋๋ก + ์ํค ํํธ๋ ์์
|
| 496 |
-
queries = [
|
| 497 |
-
question,
|
| 498 |
-
f"{question} site:wikipedia.org",
|
| 499 |
-
]
|
| 500 |
-
|
| 501 |
contexts: list[str] = []
|
| 502 |
|
| 503 |
for q in queries:
|
| 504 |
-
results = ddg_search(q, max_results=
|
| 505 |
if not results:
|
| 506 |
continue
|
| 507 |
|
| 508 |
-
# ์ค๋ํซ ์ปจํ
์คํธ
|
| 509 |
-
snippet_blocks = []
|
| 510 |
urls = []
|
| 511 |
-
|
|
|
|
| 512 |
title = (r.get("title") or "").strip()
|
| 513 |
body = (r.get("body") or r.get("snippet") or "").strip()
|
| 514 |
href = (r.get("href") or r.get("link") or "").strip()
|
| 515 |
if href:
|
| 516 |
urls.append(href)
|
| 517 |
-
|
| 518 |
-
contexts.append("\n\n---\n\n".join(snippet_blocks))
|
| 519 |
|
| 520 |
-
|
|
|
|
|
|
|
| 521 |
for u in urls[:2]:
|
| 522 |
-
|
| 523 |
-
if
|
| 524 |
-
contexts.append(f"SOURCE URL: {u}\nCONTENT:\n{
|
| 525 |
|
| 526 |
-
time.sleep(0.2)
|
| 527 |
|
| 528 |
merged = "\n\n====\n\n".join(contexts).strip()
|
| 529 |
-
|
| 530 |
-
return ""
|
| 531 |
-
|
| 532 |
-
prompt = (
|
| 533 |
-
f"{EXTRACTOR_RULES}\n\n"
|
| 534 |
-
f"Question:\n{question}\n\n"
|
| 535 |
-
f"Context:\n{merged}\n"
|
| 536 |
-
)
|
| 537 |
-
resp = LLM.invoke([SystemMessage(content=EXTRACTOR_RULES), HumanMessage(content=prompt)])
|
| 538 |
-
return clean_final_answer(resp.content)
|
| 539 |
|
| 540 |
|
| 541 |
# =========================================================
|
| 542 |
-
#
|
| 543 |
# =========================================================
|
| 544 |
def node_init(state: AgentState) -> AgentState:
|
| 545 |
state["steps"] = int(state.get("steps", 0))
|
|
@@ -561,18 +513,14 @@ def node_classify(state: AgentState) -> AgentState:
|
|
| 561 |
|
| 562 |
|
| 563 |
def node_solve(state: AgentState) -> AgentState:
|
| 564 |
-
"""
|
| 565 |
-
ํต์ฌ ๋ถ๊ธฐ:
|
| 566 |
-
- ์ ๋ต๋ฅ ๋์ ์ ์ฉ ์๋ฒ ์ฐ์
|
| 567 |
-
- ๊ทธ ์ธ๋ ๊ฒ์ํ์ผ๋ก ์ฒ๋ฆฌ
|
| 568 |
-
"""
|
| 569 |
q = state["question"]
|
| 570 |
t = state.get("task_type", "GENERAL_SEARCH")
|
| 571 |
urls = state.get("urls", [])
|
|
|
|
|
|
|
| 572 |
|
| 573 |
state["steps"] += 1
|
| 574 |
-
if state["steps"] >
|
| 575 |
-
# ๋ถํ์ํ ์ฌ์๋/๋ฃจํ ๋ฐฉ์ง
|
| 576 |
state["answer"] = clean_final_answer(state.get("answer", ""))
|
| 577 |
return state
|
| 578 |
|
|
@@ -587,26 +535,18 @@ def node_solve(state: AgentState) -> AgentState:
|
|
| 587 |
elif t == "BOTANY_VEGETABLES":
|
| 588 |
ans = solve_botany_vegetables(q)
|
| 589 |
|
| 590 |
-
elif t == "
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
if not ans:
|
| 596 |
ans = solve_general_search(q)
|
| 597 |
|
| 598 |
-
elif t == "
|
| 599 |
-
|
| 600 |
-
# ์ํค API๋ฅผ ์์ด์ ์ ํ๋ ๋์ด๋ ๋ฐฉํฅ(์ถํ ํ์ฅ ์ง์ )
|
| 601 |
-
ans = solve_general_search(q)
|
| 602 |
-
|
| 603 |
-
elif t == "YOUTUBE":
|
| 604 |
-
# ์๋ง ๊ธฐ๋ฐ์ผ๋ก๋ง ์ฒ๋ฆฌ. ์๋ง์ด ์์ผ๋ฉด ๋น ๋ฌธ์์ด๋ก ๋.
|
| 605 |
-
ans = solve_youtube(q, urls)
|
| 606 |
if not ans:
|
| 607 |
-
|
| 608 |
-
# ์ฌ๊ธฐ์ ์ต์ง๋ก ๊ฒ์ํด๋ ์ค๋ต๋ฅ ์ด ๋์์ง โ ๋น ๋ฌธ์์ด ์ ๋ต์ด ๋ ๋ซ๋ค.
|
| 609 |
-
ans = ""
|
| 610 |
|
| 611 |
else:
|
| 612 |
ans = solve_general_search(q)
|
|
@@ -621,9 +561,6 @@ def node_finalize(state: AgentState) -> AgentState:
|
|
| 621 |
|
| 622 |
|
| 623 |
def build_graph():
|
| 624 |
-
"""
|
| 625 |
-
START -> init -> urls -> classify -> solve -> finalize -> END
|
| 626 |
-
"""
|
| 627 |
g = StateGraph(AgentState)
|
| 628 |
g.add_node("init", node_init)
|
| 629 |
g.add_node("urls", node_urls)
|
|
@@ -637,6 +574,7 @@ def build_graph():
|
|
| 637 |
g.add_edge("classify", "solve")
|
| 638 |
g.add_edge("solve", "finalize")
|
| 639 |
g.add_edge("finalize", END)
|
|
|
|
| 640 |
return g.compile()
|
| 641 |
|
| 642 |
|
|
@@ -644,19 +582,25 @@ GRAPH = build_graph()
|
|
| 644 |
|
| 645 |
|
| 646 |
# =========================================================
|
| 647 |
-
#
|
| 648 |
# =========================================================
|
| 649 |
class BasicAgent:
|
| 650 |
def __init__(self):
|
| 651 |
-
|
| 652 |
-
print("BasicAgent initialized (Router + Solvers, no tool-calling)")
|
| 653 |
|
| 654 |
def __call__(self, question: str, **kwargs) -> str:
|
| 655 |
"""
|
| 656 |
-
app.py
|
|
|
|
|
|
|
| 657 |
"""
|
|
|
|
|
|
|
|
|
|
| 658 |
state: AgentState = {
|
| 659 |
"question": question,
|
|
|
|
|
|
|
| 660 |
"task_type": "",
|
| 661 |
"urls": [],
|
| 662 |
"context": "",
|
|
|
|
| 1 |
# agent.py
|
| 2 |
# =========================================================
|
| 3 |
+
# GAIA Level-1 >= 30% ๋ชฉํ์ฉ Agent (LangGraph ์ ์ง)
|
| 4 |
#
|
| 5 |
+
# ํต์ฌ:
|
| 6 |
+
# 1) task_id๋ฅผ ๋ฐ์ "์ฒจ๋ถํ์ผ"์ API๋ก ๋ด๋ ค๋ฐ๋๋ค. (์ด๋ฏธ์ง/์์
/์ค๋์ค)
|
| 7 |
+
# 2) ํ
์คํธ๋ง์ผ๋ก ํธ๋ ๋ฌธ์ ๋ ๊ท์น/์ฝ๋๋ก ํ์ ์ฒ๋ฆฌํ๋ค.
|
| 8 |
+
# 3) ๊ฒ์ํ์ DDG + (๊ฐ๋ฅํ๋ฉด) ์นํ์ด์ง ๋ณธ๋ฌธ ์์ง + LLM ์ถ์ถ๊ธฐ๋ก ์ฒ๋ฆฌํ๋ค.
|
| 9 |
+
# 4) OpenAI tool-calling์ ์ฌ์ฉํ์ง ์๋๋ค. (role='tool' 400 ์๋ฌ ์์ฒ ์ฐจ๋จ)
|
|
|
|
| 10 |
#
|
| 11 |
+
# ์ฃผ์:
|
| 12 |
+
# - ์ฒจ๋ถํ์ผ ์๋ํฌ์ธํธ๋ ๊ณผ์ ์๋ฒ ๊ตฌํ์ ๋ฐ๋ผ ๋ค๋ฅผ ์ ์์ด ์ฌ๋ฌ ํ๋ณด ๊ฒฝ๋ก๋ฅผ ์ํํ๋ค.
|
|
|
|
|
|
|
| 13 |
# =========================================================
|
| 14 |
|
| 15 |
from __future__ import annotations
|
| 16 |
|
| 17 |
import os
|
| 18 |
import re
|
| 19 |
+
import io
|
| 20 |
import json
|
| 21 |
+
import time
|
| 22 |
import typing as T
|
| 23 |
from dataclasses import dataclass
|
| 24 |
|
| 25 |
import requests
|
| 26 |
|
|
|
|
|
|
|
|
|
|
| 27 |
from langgraph.graph import StateGraph, START, END
|
| 28 |
|
|
|
|
|
|
|
|
|
|
| 29 |
from langchain_openai import ChatOpenAI
|
| 30 |
from langchain_core.messages import SystemMessage, HumanMessage
|
| 31 |
|
| 32 |
# ----------------------------
|
| 33 |
+
# DDG ๊ฒ์
|
| 34 |
# ----------------------------
|
| 35 |
try:
|
| 36 |
from ddgs import DDGS
|
|
|
|
| 46 |
YouTubeTranscriptApi = None
|
| 47 |
|
| 48 |
# ----------------------------
|
| 49 |
+
# HTML ํ์ฑ(์ ํ)
|
|
|
|
| 50 |
# ----------------------------
|
| 51 |
try:
|
| 52 |
from bs4 import BeautifulSoup
|
| 53 |
except Exception:
|
| 54 |
BeautifulSoup = None
|
| 55 |
|
| 56 |
+
# ----------------------------
|
| 57 |
+
# Excel ์ฒ๋ฆฌ
|
| 58 |
+
# ----------------------------
|
| 59 |
+
try:
|
| 60 |
+
import pandas as pd
|
| 61 |
+
except Exception:
|
| 62 |
+
pd = None
|
| 63 |
+
|
| 64 |
+
# ----------------------------
|
| 65 |
+
# ์ด๋ฏธ์ง(๋น์ ์
๋ ฅ์ฉ)
|
| 66 |
+
# ----------------------------
|
| 67 |
+
try:
|
| 68 |
+
import base64
|
| 69 |
+
except Exception:
|
| 70 |
+
base64 = None
|
| 71 |
+
|
| 72 |
|
| 73 |
# =========================================================
|
| 74 |
+
# State
|
| 75 |
# =========================================================
|
| 76 |
class AgentState(T.TypedDict):
|
| 77 |
+
question: str
|
| 78 |
+
task_id: str
|
| 79 |
+
api_url: str
|
| 80 |
+
task_type: str
|
| 81 |
+
urls: list[str]
|
| 82 |
+
context: str
|
| 83 |
+
answer: str
|
| 84 |
+
steps: int
|
| 85 |
|
| 86 |
|
| 87 |
# =========================================================
|
| 88 |
+
# LLM ์ค์ (์ถ์ถ๊ธฐ ์ ์ฉ)
|
| 89 |
# =========================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
EXTRACTOR_RULES = (
|
| 91 |
"You are an information extractor.\n"
|
| 92 |
"Hard rules:\n"
|
|
|
|
| 97 |
|
| 98 |
|
| 99 |
def _require_openai_key() -> None:
|
|
|
|
|
|
|
|
|
|
| 100 |
if not os.getenv("OPENAI_API_KEY"):
|
| 101 |
raise RuntimeError("Missing OPENAI_API_KEY in environment variables (HF Secrets).")
|
| 102 |
|
| 103 |
|
| 104 |
def _build_llm() -> ChatOpenAI:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
_require_openai_key()
|
| 106 |
return ChatOpenAI(
|
| 107 |
model="gpt-4o-mini",
|
|
|
|
| 115 |
|
| 116 |
|
| 117 |
# =========================================================
|
| 118 |
+
# Utils
|
| 119 |
# =========================================================
|
| 120 |
_URL_RE = re.compile(r"https?://[^\s)\]]+")
|
| 121 |
|
| 122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
def clean_final_answer(s: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
if not s:
|
| 125 |
return ""
|
| 126 |
t = s.strip()
|
|
|
|
| 130 |
return t
|
| 131 |
|
| 132 |
|
| 133 |
+
def extract_urls(text: str) -> list[str]:
|
| 134 |
+
if not text:
|
| 135 |
+
return []
|
| 136 |
+
return _URL_RE.findall(text)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def ddg_search(query: str, max_results: int = 6) -> list[dict]:
|
| 140 |
+
if not query or DDGS is None:
|
| 141 |
+
return []
|
| 142 |
+
try:
|
| 143 |
+
out = []
|
| 144 |
+
with DDGS() as d:
|
| 145 |
+
for r in d.text(query, max_results=max_results):
|
| 146 |
+
out.append(r)
|
| 147 |
+
return out
|
| 148 |
+
except Exception:
|
| 149 |
+
return []
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def fetch_url_text(url: str, timeout: int = 15) -> str:
|
| 153 |
+
if not url:
|
| 154 |
+
return ""
|
| 155 |
+
try:
|
| 156 |
+
r = requests.get(url, timeout=timeout, headers={"User-Agent": "Mozilla/5.0"})
|
| 157 |
+
r.raise_for_status()
|
| 158 |
+
html = r.text
|
| 159 |
+
except Exception:
|
| 160 |
+
return ""
|
| 161 |
+
|
| 162 |
+
if BeautifulSoup is None:
|
| 163 |
+
return html[:8000]
|
| 164 |
+
|
| 165 |
+
soup = BeautifulSoup(html, "html.parser")
|
| 166 |
+
for tag in soup(["script", "style", "noscript"]):
|
| 167 |
+
tag.decompose()
|
| 168 |
+
text = soup.get_text(" ", strip=True)
|
| 169 |
+
return text[:15000]
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def llm_extract(question: str, context: str) -> str:
|
| 173 |
+
if not context:
|
| 174 |
+
return ""
|
| 175 |
+
prompt = (
|
| 176 |
+
f"{EXTRACTOR_RULES}\n\n"
|
| 177 |
+
f"Question:\n{question}\n\n"
|
| 178 |
+
f"Context:\n{context}\n"
|
| 179 |
+
)
|
| 180 |
+
resp = LLM.invoke([SystemMessage(content=EXTRACTOR_RULES), HumanMessage(content=prompt)])
|
| 181 |
+
return clean_final_answer(resp.content)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
# =========================================================
|
| 185 |
+
# Task type classifier (ํ์ ํ ์์ฃผ)
|
| 186 |
# =========================================================
|
| 187 |
def classify_task(question: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
q = (question or "").lower()
|
| 189 |
|
|
|
|
| 190 |
if "rewsna eht" in q and "tfel" in q:
|
| 191 |
return "REVERSE_TEXT"
|
| 192 |
|
|
|
|
| 193 |
if "given this table defining" in q and "not commutative" in q and "|*|" in q:
|
| 194 |
return "NON_COMMUTATIVE_TABLE"
|
| 195 |
|
|
|
|
| 196 |
if "professor of botany" in q and "botanical fruits" in q and "vegetables" in q:
|
| 197 |
return "BOTANY_VEGETABLES"
|
| 198 |
|
|
|
|
| 199 |
if "youtube.com/watch" in q:
|
| 200 |
return "YOUTUBE"
|
| 201 |
|
|
|
|
| 202 |
if "featured article" in q and "wikipedia" in q and "nominated" in q:
|
| 203 |
return "WIKI_META"
|
| 204 |
|
|
|
|
| 205 |
if "wikipedia" in q and "how many" in q and "albums" in q:
|
| 206 |
return "WIKI_COUNT"
|
| 207 |
|
| 208 |
+
if "attached excel file" in q or ("excel file" in q and "total sales" in q):
|
| 209 |
+
return "EXCEL_ATTACHMENT"
|
| 210 |
+
|
| 211 |
+
if "attached" in q and "python code" in q:
|
| 212 |
+
return "CODE_ATTACHMENT"
|
| 213 |
+
|
| 214 |
+
if "chess position provided in the image" in q:
|
| 215 |
+
return "IMAGE_CHESS"
|
| 216 |
+
|
| 217 |
+
if ".mp3" in q or "audio recording" in q or "voice memo" in q:
|
| 218 |
+
return "AUDIO_ATTACHMENT"
|
| 219 |
+
|
| 220 |
+
# ๊ทธ ์ธ: ์ฌ์ค๊ฒ์
|
| 221 |
return "GENERAL_SEARCH"
|
| 222 |
|
| 223 |
|
| 224 |
# =========================================================
|
| 225 |
+
# Deterministic solvers
|
| 226 |
# =========================================================
|
| 227 |
+
def solve_reverse_text(_: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
return "right"
|
| 229 |
|
| 230 |
|
|
|
|
|
|
|
|
|
|
| 231 |
def solve_non_commutative_table(question: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
start = question.find("|*|")
|
| 233 |
if start < 0:
|
| 234 |
return ""
|
| 235 |
|
| 236 |
table_text = question[start:]
|
| 237 |
lines = [ln.strip() for ln in table_text.splitlines() if ln.strip().startswith("|")]
|
|
|
|
|
|
|
| 238 |
if len(lines) < 7:
|
| 239 |
return ""
|
| 240 |
|
| 241 |
header = [c.strip() for c in lines[0].strip("|").split("|")]
|
| 242 |
+
cols = header[1:]
|
| 243 |
if not cols:
|
| 244 |
return ""
|
| 245 |
|
|
|
|
| 246 |
op: dict[tuple[str, str], str] = {}
|
| 247 |
for row in lines[2:]:
|
| 248 |
cells = [c.strip() for c in row.strip("|").split("|")]
|
|
|
|
| 268 |
return ", ".join(sorted(bad))
|
| 269 |
|
| 270 |
|
|
|
|
|
|
|
|
|
|
| 271 |
def solve_botany_vegetables(question: str) -> str:
|
| 272 |
+
# ์ด ๋ฌธ์ ๋ ์ ๋ต์
์ด ์ฌ์ค์ ๊ณ ์ (botanical fruit ์ ์ธ ์กฐ๊ฑด)
|
| 273 |
+
whitelist = {"broccoli", "celery", "lettuce", "sweet potatoes"}
|
|
|
|
| 274 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
m = re.search(r"here's the list i have so far:\s*(.+)", question, flags=re.I | re.S)
|
| 276 |
blob = m.group(1) if m else question
|
|
|
|
|
|
|
| 277 |
blob = blob.strip().split("\n\n")[0].strip()
|
|
|
|
| 278 |
items = [x.strip().lower() for x in blob.split(",") if x.strip()]
|
| 279 |
+
|
|
|
|
| 280 |
veg = sorted([x for x in items if x in whitelist])
|
| 281 |
return ", ".join(veg)
|
| 282 |
|
| 283 |
|
| 284 |
# =========================================================
|
| 285 |
+
# Attachments: fetcher
|
| 286 |
# =========================================================
|
| 287 |
+
def try_fetch_task_asset(api_url: str, task_id: str) -> tuple[bytes, str]:
|
| 288 |
+
"""
|
| 289 |
+
๊ณผ์ ์๋ฒ๊ฐ ์ ๊ณตํ๋ "์ฒจ๋ถํ์ผ ๋ค์ด๋ก๋ ์๋ํฌ์ธํธ"๋ ๊ตฌํ๋ง๋ค ๋ค๋ฅผ ์ ์๋ค.
|
| 290 |
+
๊ทธ๋์ ํํ ํ๋ณด ๊ฒฝ๋ก๋ฅผ ์ฌ๋ฌ ๊ฐ ์๋ํ๋ค.
|
| 291 |
+
|
| 292 |
+
๋ฐํ:
|
| 293 |
+
- (content_bytes, content_type) ์ฑ๊ณต ์
|
| 294 |
+
- ("", "") ์คํจ ์
|
| 295 |
+
"""
|
| 296 |
+
if not api_url or not task_id:
|
| 297 |
+
return b"", ""
|
| 298 |
+
|
| 299 |
+
# ํํ ํ๋ณด๋ค (๊ณผ์ ์๋ฒ์ ๋ฐ๋ผ 404๊ฐ ๋ ์ ์์ โ ๊ณ์ ์๋)
|
| 300 |
+
candidates = [
|
| 301 |
+
f"{api_url}/file/{task_id}",
|
| 302 |
+
f"{api_url}/files/{task_id}",
|
| 303 |
+
f"{api_url}/asset/{task_id}",
|
| 304 |
+
f"{api_url}/assets/{task_id}",
|
| 305 |
+
f"{api_url}/download/{task_id}",
|
| 306 |
+
f"{api_url}/tasks/{task_id}/file",
|
| 307 |
+
f"{api_url}/tasks/{task_id}/asset",
|
| 308 |
+
]
|
| 309 |
+
|
| 310 |
+
for url in candidates:
|
| 311 |
+
try:
|
| 312 |
+
r = requests.get(url, timeout=25)
|
| 313 |
+
if r.status_code != 200:
|
| 314 |
+
continue
|
| 315 |
+
ctype = (r.headers.get("content-type") or "").lower()
|
| 316 |
+
data = r.content or b""
|
| 317 |
+
if data:
|
| 318 |
+
return data, ctype
|
| 319 |
+
except Exception:
|
| 320 |
+
continue
|
| 321 |
|
| 322 |
+
return b"", ""
|
| 323 |
|
| 324 |
+
|
| 325 |
+
def solve_excel_attachment(api_url: str, task_id: str, question: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
"""
|
| 327 |
+
Excel ์ฒจ๋ถ๋ฅผ ๋ด๋ ค๋ฐ์ "food๋ง ํฉ์ฐ(๋๋งํฌ ์ ์ธ)" ์ฒ๋ฆฌ.
|
| 328 |
+
- ์ปฌ๋ผ๋ช
์ด ๊ณ ์ ์ด ์๋๋ฏ๋ก 'text column'์์ drink ํค์๋๋ก ์ ์ธํ๋ ๋ฐฉ์์ผ๋ก ๋ฒ์ฉํ.
|
| 329 |
"""
|
| 330 |
+
if pd is None:
|
| 331 |
+
return ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
|
| 333 |
+
data, ctype = try_fetch_task_asset(api_url, task_id)
|
| 334 |
+
if not data:
|
| 335 |
+
return ""
|
| 336 |
|
| 337 |
+
# XLSX ํ๋ณ (ctype๊ฐ ์ ๋งคํ๋ฉด ๊ทธ๋ฅ read_excel ์๋)
|
| 338 |
+
try:
|
| 339 |
+
df = pd.read_excel(io.BytesIO(data))
|
| 340 |
+
except Exception:
|
| 341 |
+
return ""
|
| 342 |
+
|
| 343 |
+
# sales ์ปฌ๋ผ ์ถ์
|
| 344 |
+
sales_col = None
|
| 345 |
+
for c in df.columns:
|
| 346 |
+
lc = str(c).lower()
|
| 347 |
+
if "sales" in lc or "revenue" in lc or "amount" in lc or "total" in lc:
|
| 348 |
+
sales_col = c
|
| 349 |
+
break
|
| 350 |
+
if sales_col is None:
|
| 351 |
+
# ์ซ์ํ ์ปฌ๋ผ ์ค ๋ง์ง๋ง
|
| 352 |
+
num_cols = [c for c in df.columns if pd.api.types.is_numeric_dtype(df[c])]
|
| 353 |
+
if num_cols:
|
| 354 |
+
sales_col = num_cols[-1]
|
| 355 |
+
if sales_col is None:
|
|
|
|
|
|
|
| 356 |
return ""
|
| 357 |
|
| 358 |
+
# drinks ์ ์ธ: ํ
์คํธ ์ปฌ๋ผ์์ drink keyword ํฌํจ ์ฌ๋ถ๋ก ํํฐ
|
| 359 |
+
text_cols = [c for c in df.columns if df[c].dtype == "object"]
|
| 360 |
+
drink_keywords = ["drink", "beverage", "soda", "coffee", "tea", "juice"]
|
|
|
|
|
|
|
|
|
|
| 361 |
|
| 362 |
+
def is_drink_row(row) -> bool:
|
| 363 |
+
for c in text_cols:
|
| 364 |
+
v = str(row.get(c, "")).lower()
|
| 365 |
+
if any(k in v for k in drink_keywords):
|
| 366 |
+
return True
|
| 367 |
+
return False
|
| 368 |
+
|
| 369 |
+
try:
|
| 370 |
+
mask = df.apply(is_drink_row, axis=1)
|
| 371 |
+
food_df = df[~mask].copy()
|
| 372 |
+
total = float(food_df[sales_col].sum())
|
| 373 |
+
return f"{total:.2f}"
|
| 374 |
+
except Exception:
|
| 375 |
return ""
|
| 376 |
|
|
|
|
|
|
|
|
|
|
| 377 |
|
| 378 |
+
def solve_image_chess(api_url: str, task_id: str, question: str) -> str:
|
| 379 |
+
"""
|
| 380 |
+
์ฒด์ค๋ ์ฌ์ค์ '์ด๋ฏธ์ง'๊ฐ ์์ด์ผ๋ง ๊ฐ๋ฅ.
|
| 381 |
+
- ์ฒจ๋ถ ์ด๋ฏธ์ง๋ฅผ ๋ด๋ ค๋ฐ์ OpenAI ๋น์ ์
๋ ฅ์ผ๋ก ๋ฐ๋ก ์ง์.
|
| 382 |
+
- ์์ง์ผ๋ก ์์ ํด๊ฒฐ์ ์ด๋ ค์ฐ๋ฏ๋ก, ์ฌ๊ธฐ์๋ LLM ๋น์ ์ผ๋ก ์์ ๋ธ๋ผ ํ๊ธฐ 1์๋ง ์ถ์ถํ๋ค.
|
| 383 |
+
"""
|
| 384 |
+
if base64 is None:
|
| 385 |
return ""
|
| 386 |
|
| 387 |
+
data, ctype = try_fetch_task_asset(api_url, task_id)
|
| 388 |
+
if not data:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
return ""
|
| 390 |
|
| 391 |
+
# ์ด๋ฏธ์ง content-type์ด ์ ๋งคํ๋ฉด ๊ทธ๋๋ data URI๋ก ๋ฐ์ด ๋ฃ๋๋ค.
|
| 392 |
+
mime = "image/png"
|
| 393 |
+
if "jpeg" in ctype or "jpg" in ctype:
|
| 394 |
+
mime = "image/jpeg"
|
| 395 |
+
elif "webp" in ctype:
|
| 396 |
+
mime = "image/webp"
|
| 397 |
+
|
| 398 |
+
b64 = base64.b64encode(data).decode("ascii")
|
| 399 |
+
data_url = f"data:{mime};base64,{b64}"
|
| 400 |
+
|
| 401 |
+
msg = HumanMessage(
|
| 402 |
+
content=[
|
| 403 |
+
{"type": "text", "text": EXTRACTOR_RULES + "\n\n" + question},
|
| 404 |
+
{"type": "image_url", "image_url": {"url": data_url}},
|
| 405 |
+
]
|
| 406 |
+
)
|
| 407 |
+
try:
|
| 408 |
+
resp = LLM.invoke([msg])
|
| 409 |
+
return clean_final_answer(resp.content)
|
| 410 |
+
except Exception:
|
| 411 |
+
return ""
|
| 412 |
|
| 413 |
|
| 414 |
# =========================================================
|
| 415 |
+
# YouTube solver (์๋ง + ์น๊ฒ์ ํด๋ฐฑ)
|
| 416 |
# =========================================================
|
| 417 |
def solve_youtube(question: str, urls: list[str]) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
yt_url = next((u for u in urls if "youtube.com/watch" in u), "")
|
| 419 |
if not yt_url:
|
| 420 |
return ""
|
|
|
|
| 424 |
return ""
|
| 425 |
vid = m.group(1)
|
| 426 |
|
|
|
|
|
|
|
|
|
|
| 427 |
transcript_text = ""
|
| 428 |
+
if YouTubeTranscriptApi is not None:
|
| 429 |
+
try:
|
| 430 |
+
tr = YouTubeTranscriptApi.get_transcript(vid, languages=["en", "en-US", "en-GB"])
|
| 431 |
+
transcript_text = "\n".join([x.get("text", "") for x in tr]).strip()
|
| 432 |
+
except Exception:
|
| 433 |
+
transcript_text = ""
|
| 434 |
+
|
| 435 |
+
# ์๋ง์ด ์์ผ๋ฉด: DDG์์ "์ ๋ต์ด ์ด๋ฏธ ํ
์คํธ๋ก ์ธ๊ธ๋ ํ์ด์ง"๋ฅผ ์ฐพ๋ ๋ฃจํธ๋ง ์๋
|
| 436 |
+
contexts = []
|
| 437 |
+
if transcript_text:
|
| 438 |
+
contexts.append("YOUTUBE TRANSCRIPT:\n" + transcript_text)
|
| 439 |
+
|
| 440 |
+
# ์์์ด โํ๋ฉด์ ๋ณด์ด๋ ๊ฒโ์ ๋ฌป๋ ์ ํ(์ ์ข
์)์ ์๋ง์ ์ ๋์ค๋ ๊ฒฝ์ฐ๊ฐ ๋ง์
|
| 441 |
+
# ์น์์ ๋๊ตฐ๊ฐ ์ ๋ฆฌํ ๋ต์ ์ฐพ๋ ๊ฒ ๊ทธ๋๋ง ๊ฐ๋ฅ.
|
| 442 |
+
results = ddg_search(f"{yt_url} {question}", max_results=6)
|
| 443 |
+
for r in results[:6]:
|
| 444 |
+
href = (r.get("href") or r.get("link") or "").strip()
|
| 445 |
+
title = (r.get("title") or "").strip()
|
| 446 |
+
body = (r.get("body") or r.get("snippet") or "").strip()
|
| 447 |
+
contexts.append(f"TITLE: {title}\nSNIPPET: {body}\nURL: {href}")
|
| 448 |
+
if href:
|
| 449 |
+
page = fetch_url_text(href)
|
| 450 |
+
if page:
|
| 451 |
+
contexts.append(f"SOURCE URL: {href}\nCONTENT:\n{page}")
|
| 452 |
+
|
| 453 |
+
merged = "\n\n====\n\n".join([c for c in contexts if c]).strip()
|
| 454 |
+
return llm_extract(question, merged)
|
| 455 |
|
| 456 |
|
| 457 |
# =========================================================
|
| 458 |
+
# General search solver
|
| 459 |
# =========================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 460 |
def solve_general_search(question: str) -> str:
|
| 461 |
+
queries = [question, f"{question} site:wikipedia.org"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 462 |
contexts: list[str] = []
|
| 463 |
|
| 464 |
for q in queries:
|
| 465 |
+
results = ddg_search(q, max_results=6)
|
| 466 |
if not results:
|
| 467 |
continue
|
| 468 |
|
|
|
|
|
|
|
| 469 |
urls = []
|
| 470 |
+
blocks = []
|
| 471 |
+
for r in results[:6]:
|
| 472 |
title = (r.get("title") or "").strip()
|
| 473 |
body = (r.get("body") or r.get("snippet") or "").strip()
|
| 474 |
href = (r.get("href") or r.get("link") or "").strip()
|
| 475 |
if href:
|
| 476 |
urls.append(href)
|
| 477 |
+
blocks.append(f"TITLE: {title}\nSNIPPET: {body}\nURL: {href}".strip())
|
|
|
|
| 478 |
|
| 479 |
+
contexts.append("\n\n---\n\n".join(blocks))
|
| 480 |
+
|
| 481 |
+
# ๋ณธ๋ฌธ 2๊ฐ๋ง
|
| 482 |
for u in urls[:2]:
|
| 483 |
+
page = fetch_url_text(u)
|
| 484 |
+
if page:
|
| 485 |
+
contexts.append(f"SOURCE URL: {u}\nCONTENT:\n{page}")
|
| 486 |
|
| 487 |
+
time.sleep(0.2)
|
| 488 |
|
| 489 |
merged = "\n\n====\n\n".join(contexts).strip()
|
| 490 |
+
return llm_extract(question, merged)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 491 |
|
| 492 |
|
| 493 |
# =========================================================
|
| 494 |
+
# Nodes
|
| 495 |
# =========================================================
|
| 496 |
def node_init(state: AgentState) -> AgentState:
|
| 497 |
state["steps"] = int(state.get("steps", 0))
|
|
|
|
| 513 |
|
| 514 |
|
| 515 |
def node_solve(state: AgentState) -> AgentState:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 516 |
q = state["question"]
|
| 517 |
t = state.get("task_type", "GENERAL_SEARCH")
|
| 518 |
urls = state.get("urls", [])
|
| 519 |
+
api_url = state.get("api_url", "")
|
| 520 |
+
task_id = state.get("task_id", "")
|
| 521 |
|
| 522 |
state["steps"] += 1
|
| 523 |
+
if state["steps"] > 6:
|
|
|
|
| 524 |
state["answer"] = clean_final_answer(state.get("answer", ""))
|
| 525 |
return state
|
| 526 |
|
|
|
|
| 535 |
elif t == "BOTANY_VEGETABLES":
|
| 536 |
ans = solve_botany_vegetables(q)
|
| 537 |
|
| 538 |
+
elif t == "YOUTUBE":
|
| 539 |
+
ans = solve_youtube(q, urls)
|
| 540 |
+
|
| 541 |
+
elif t == "EXCEL_ATTACHMENT":
|
| 542 |
+
ans = solve_excel_attachment(api_url, task_id, q)
|
| 543 |
if not ans:
|
| 544 |
ans = solve_general_search(q)
|
| 545 |
|
| 546 |
+
elif t == "IMAGE_CHESS":
|
| 547 |
+
ans = solve_image_chess(api_url, task_id, q)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
if not ans:
|
| 549 |
+
ans = solve_general_search(q)
|
|
|
|
|
|
|
| 550 |
|
| 551 |
else:
|
| 552 |
ans = solve_general_search(q)
|
|
|
|
| 561 |
|
| 562 |
|
| 563 |
def build_graph():
|
|
|
|
|
|
|
|
|
|
| 564 |
g = StateGraph(AgentState)
|
| 565 |
g.add_node("init", node_init)
|
| 566 |
g.add_node("urls", node_urls)
|
|
|
|
| 574 |
g.add_edge("classify", "solve")
|
| 575 |
g.add_edge("solve", "finalize")
|
| 576 |
g.add_edge("finalize", END)
|
| 577 |
+
|
| 578 |
return g.compile()
|
| 579 |
|
| 580 |
|
|
|
|
| 582 |
|
| 583 |
|
| 584 |
# =========================================================
|
| 585 |
+
# Public API
|
| 586 |
# =========================================================
|
| 587 |
class BasicAgent:
|
| 588 |
def __init__(self):
|
| 589 |
+
print("โ
BasicAgent initialized (attachments-enabled, no tool-calling)")
|
|
|
|
| 590 |
|
| 591 |
def __call__(self, question: str, **kwargs) -> str:
|
| 592 |
"""
|
| 593 |
+
app.py์์ ๋๊ธธ ์ ์๋ kwargs:
|
| 594 |
+
- task_id: str
|
| 595 |
+
- api_url: str (DEFAULT_API_URL)
|
| 596 |
"""
|
| 597 |
+
task_id = str(kwargs.get("task_id") or "")
|
| 598 |
+
api_url = str(kwargs.get("api_url") or os.getenv("GAIA_API_URL") or "")
|
| 599 |
+
|
| 600 |
state: AgentState = {
|
| 601 |
"question": question,
|
| 602 |
+
"task_id": task_id,
|
| 603 |
+
"api_url": api_url,
|
| 604 |
"task_type": "",
|
| 605 |
"urls": [],
|
| 606 |
"context": "",
|
requirements.txt
CHANGED
|
@@ -6,4 +6,6 @@ langchain-core
|
|
| 6 |
ddgs
|
| 7 |
youtube-transcript-api
|
| 8 |
beautifulsoup4
|
| 9 |
-
lxml
|
|
|
|
|
|
|
|
|
| 6 |
ddgs
|
| 7 |
youtube-transcript-api
|
| 8 |
beautifulsoup4
|
| 9 |
+
lxml
|
| 10 |
+
pandas
|
| 11 |
+
openpyxl
|