Update app.py
Browse files
app.py
CHANGED
|
@@ -7,7 +7,7 @@ import gradio as gr
|
|
| 7 |
|
| 8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
|
| 10 |
-
# ββ Imports
|
| 11 |
from smolagents import (
|
| 12 |
CodeAgent,
|
| 13 |
InferenceClientModel,
|
|
@@ -16,7 +16,47 @@ from smolagents import (
|
|
| 16 |
tool,
|
| 17 |
)
|
| 18 |
|
| 19 |
-
# ββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
@tool
|
| 22 |
def wikipedia_search(query: str) -> str:
|
|
@@ -26,17 +66,17 @@ def wikipedia_search(query: str) -> str:
|
|
| 26 |
"""
|
| 27 |
try:
|
| 28 |
base = "https://en.wikipedia.org/w/api.php"
|
| 29 |
-
|
| 30 |
"action": "query", "list": "search",
|
| 31 |
"srsearch": query, "format": "json", "srlimit": 1,
|
| 32 |
}, timeout=15).json()
|
| 33 |
-
title =
|
| 34 |
-
|
| 35 |
"action": "query", "prop": "extracts",
|
| 36 |
"exintro": True, "explaintext": True,
|
| 37 |
"titles": title, "format": "json",
|
| 38 |
}, timeout=15).json()
|
| 39 |
-
pages =
|
| 40 |
text = next(iter(pages.values())).get("extract", "")[:4000]
|
| 41 |
return f"# {title}\n{text}"
|
| 42 |
except Exception as e:
|
|
@@ -73,8 +113,7 @@ def download_file_for_task(task_id: str) -> str:
|
|
| 73 |
for _ in range(3):
|
| 74 |
resp = requests.post(url, headers={"Authorization": f"Bearer {token}"}, data=data, timeout=120)
|
| 75 |
if resp.status_code == 503:
|
| 76 |
-
time.sleep(20)
|
| 77 |
-
continue
|
| 78 |
if resp.status_code == 200:
|
| 79 |
return resp.json().get("text", "")
|
| 80 |
return "Audio transcription failed."
|
|
@@ -102,15 +141,14 @@ def download_file_for_task(task_id: str) -> str:
|
|
| 102 |
"model": "meta-llama/Llama-3.2-11B-Vision-Instruct",
|
| 103 |
"messages": [{"role": "user", "content": [
|
| 104 |
{"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}},
|
| 105 |
-
{"type": "text", "text": "Describe everything in
|
| 106 |
]}],
|
| 107 |
"max_tokens": 1024,
|
| 108 |
}
|
| 109 |
for _ in range(3):
|
| 110 |
resp = requests.post(url, headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"}, json=payload, timeout=120)
|
| 111 |
if resp.status_code == 503:
|
| 112 |
-
time.sleep(20)
|
| 113 |
-
continue
|
| 114 |
if resp.status_code == 200:
|
| 115 |
return resp.json()["choices"][0]["message"]["content"]
|
| 116 |
return "Image analysis failed."
|
|
@@ -126,7 +164,7 @@ def download_file_for_task(task_id: str) -> str:
|
|
| 126 |
def get_youtube_transcript(video_url: str) -> str:
|
| 127 |
"""Fetch the transcript/captions from a YouTube video URL.
|
| 128 |
Args:
|
| 129 |
-
video_url: The full YouTube URL
|
| 130 |
"""
|
| 131 |
try:
|
| 132 |
from youtube_transcript_api import YouTubeTranscriptApi
|
|
@@ -141,7 +179,7 @@ def get_youtube_transcript(video_url: str) -> str:
|
|
| 141 |
|
| 142 |
@tool
|
| 143 |
def run_python_code(code: str) -> str:
|
| 144 |
-
"""Execute Python code and return stdout. Use for math, logic, string
|
| 145 |
Args:
|
| 146 |
code: Valid Python code to execute.
|
| 147 |
"""
|
|
@@ -155,11 +193,10 @@ def run_python_code(code: str) -> str:
|
|
| 155 |
return f"Execution error: {e}"
|
| 156 |
|
| 157 |
|
| 158 |
-
# ββ Agent βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 159 |
|
| 160 |
class GAIAAgent:
|
| 161 |
def __init__(self):
|
| 162 |
-
# Exactement comme dans la doc officielle smolagents
|
| 163 |
model = InferenceClientModel(
|
| 164 |
model_id="meta-llama/Llama-3.3-70B-Instruct",
|
| 165 |
token=os.environ.get("HF_TOKEN", ""),
|
|
@@ -174,11 +211,13 @@ class GAIAAgent:
|
|
| 174 |
run_python_code,
|
| 175 |
],
|
| 176 |
model=model,
|
|
|
|
| 177 |
max_steps=10,
|
| 178 |
verbosity_level=1,
|
| 179 |
additional_authorized_imports=[
|
| 180 |
"re", "json", "math", "unicodedata",
|
| 181 |
"datetime", "collections", "itertools",
|
|
|
|
| 182 |
],
|
| 183 |
)
|
| 184 |
print("GAIAAgent ready β
")
|
|
@@ -186,34 +225,25 @@ class GAIAAgent:
|
|
| 186 |
def __call__(self, question: str, task_id: str = "") -> str:
|
| 187 |
print(f"\n{'='*60}\nQ: {question[:120]}")
|
| 188 |
|
| 189 |
-
# DΓ©tection de fichier joint ou YouTube dans la question
|
| 190 |
-
has_yt = bool(re.search(r"youtube\.com|youtu\.be", question))
|
| 191 |
-
has_file_hint = any(w in question.lower() for w in ["attached", "file", "image", "audio", "excel", "spreadsheet", "pdf", "code"])
|
| 192 |
-
|
| 193 |
task_hint = ""
|
| 194 |
-
if task_id
|
| 195 |
-
task_hint = f"\n\
|
| 196 |
-
elif task_id:
|
| 197 |
-
task_hint = f"\n\n[task_id: '{task_id}' β use download_file_for_task if a file is mentioned]"
|
| 198 |
|
| 199 |
prompt = (
|
| 200 |
-
"Solve this GAIA benchmark question
|
| 201 |
-
"- Use tools to
|
| 202 |
-
"-
|
| 203 |
-
"-
|
| 204 |
-
"-
|
| 205 |
-
"-
|
| 206 |
-
"-
|
| 207 |
-
"-
|
| 208 |
-
"- For counts: give only the number.\n"
|
| 209 |
-
"- For lists: comma-separated values only.\n\n"
|
| 210 |
f"Question: {question}{task_hint}"
|
| 211 |
)
|
| 212 |
|
| 213 |
try:
|
| 214 |
result = self.agent.run(prompt)
|
| 215 |
answer = str(result).strip()
|
| 216 |
-
# Nettoyer les prΓ©fixes verbeux du LLM
|
| 217 |
for prefix in ["the answer is", "answer:", "final answer:", "result:"]:
|
| 218 |
if answer.lower().startswith(prefix):
|
| 219 |
answer = answer[len(prefix):].strip().lstrip(":").strip()
|
|
@@ -224,7 +254,7 @@ class GAIAAgent:
|
|
| 224 |
return "Unable to determine answer."
|
| 225 |
|
| 226 |
|
| 227 |
-
# ββ Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 228 |
|
| 229 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 230 |
if not profile:
|
|
@@ -257,7 +287,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 257 |
answer = agent(question_text, task_id=task_id)
|
| 258 |
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
| 259 |
results_log.append({"Task ID": task_id, "Question": question_text[:80], "Submitted Answer": answer})
|
| 260 |
-
time.sleep(
|
| 261 |
|
| 262 |
if not answers_payload:
|
| 263 |
return "No answers produced.", pd.DataFrame(results_log)
|
|
@@ -287,8 +317,8 @@ with gr.Blocks() as demo:
|
|
| 287 |
gr.Markdown("# π€ GAIA Agent β smolagents + HF Inference")
|
| 288 |
gr.Markdown("""
|
| 289 |
**Models:** Llama-3.3-70B Β· Llama-3.2-11B-Vision Β· Whisper large-v3
|
| 290 |
-
**Tools:** DuckDuckGo Β· Wikipedia Β· VisitWebpage Β· YouTube transcript Β· Python Β· File reader
|
| 291 |
-
**Setup:** Ajoute `HF_TOKEN` dans les secrets de ton Space.
|
| 292 |
""")
|
| 293 |
gr.LoginButton()
|
| 294 |
run_btn = gr.Button("π Run Evaluation & Submit All Answers", variant="primary")
|
|
|
|
| 7 |
|
| 8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
|
| 10 |
+
# ββ Imports officiels smolagents ββββββββββββββββββββββββββββββββββββββ
|
| 11 |
from smolagents import (
|
| 12 |
CodeAgent,
|
| 13 |
InferenceClientModel,
|
|
|
|
| 16 |
tool,
|
| 17 |
)
|
| 18 |
|
| 19 |
+
# ββ Prompt templates COMPLETS (obligatoires pour CodeAgent) βββββββββββ
|
| 20 |
+
def get_prompt_templates():
|
| 21 |
+
return {
|
| 22 |
+
"system_prompt": """You are an expert AI assistant solving GAIA benchmark tasks.
|
| 23 |
+
You have access to tools and must use them to find accurate answers.
|
| 24 |
+
|
| 25 |
+
RULES:
|
| 26 |
+
- Always use Thought: then Code: sequences
|
| 27 |
+
- Return ONLY the exact answer - no explanation
|
| 28 |
+
- For reversed text: reverse it back then answer
|
| 29 |
+
- For math/logic: write Python code to compute
|
| 30 |
+
- For files: use the download tools
|
| 31 |
+
- Answers are exact-match graded
|
| 32 |
+
|
| 33 |
+
{{authorized_imports}}
|
| 34 |
+
""",
|
| 35 |
+
"planning": """
|
| 36 |
+
Facts given in the task:
|
| 37 |
+
<<facts_given_in_task>>
|
| 38 |
+
|
| 39 |
+
Facts needed:
|
| 40 |
+
<<facts_needed>>
|
| 41 |
+
|
| 42 |
+
Plan:
|
| 43 |
+
<<plan>>
|
| 44 |
+
|
| 45 |
+
<end_plan>
|
| 46 |
+
""",
|
| 47 |
+
"managed_agent": """
|
| 48 |
+
You are a managed agent. Return your result via final_answer().
|
| 49 |
+
Task: {{task}}
|
| 50 |
+
""",
|
| 51 |
+
"final_answer": """
|
| 52 |
+
Return ONLY the final answer. No explanation. No punctuation unless required.
|
| 53 |
+
- Numbers: digits only (e.g. 42)
|
| 54 |
+
- Lists: comma-separated (e.g. apple, banana)
|
| 55 |
+
- Names: as-is
|
| 56 |
+
"""
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
# ββ Tools custom ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 60 |
|
| 61 |
@tool
|
| 62 |
def wikipedia_search(query: str) -> str:
|
|
|
|
| 66 |
"""
|
| 67 |
try:
|
| 68 |
base = "https://en.wikipedia.org/w/api.php"
|
| 69 |
+
r = requests.get(base, params={
|
| 70 |
"action": "query", "list": "search",
|
| 71 |
"srsearch": query, "format": "json", "srlimit": 1,
|
| 72 |
}, timeout=15).json()
|
| 73 |
+
title = r["query"]["search"][0]["title"]
|
| 74 |
+
ex = requests.get(base, params={
|
| 75 |
"action": "query", "prop": "extracts",
|
| 76 |
"exintro": True, "explaintext": True,
|
| 77 |
"titles": title, "format": "json",
|
| 78 |
}, timeout=15).json()
|
| 79 |
+
pages = ex["query"]["pages"]
|
| 80 |
text = next(iter(pages.values())).get("extract", "")[:4000]
|
| 81 |
return f"# {title}\n{text}"
|
| 82 |
except Exception as e:
|
|
|
|
| 113 |
for _ in range(3):
|
| 114 |
resp = requests.post(url, headers={"Authorization": f"Bearer {token}"}, data=data, timeout=120)
|
| 115 |
if resp.status_code == 503:
|
| 116 |
+
time.sleep(20); continue
|
|
|
|
| 117 |
if resp.status_code == 200:
|
| 118 |
return resp.json().get("text", "")
|
| 119 |
return "Audio transcription failed."
|
|
|
|
| 141 |
"model": "meta-llama/Llama-3.2-11B-Vision-Instruct",
|
| 142 |
"messages": [{"role": "user", "content": [
|
| 143 |
{"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}},
|
| 144 |
+
{"type": "text", "text": "Describe everything in detail. If chess: name every piece and square. Transcribe any text/numbers exactly."},
|
| 145 |
]}],
|
| 146 |
"max_tokens": 1024,
|
| 147 |
}
|
| 148 |
for _ in range(3):
|
| 149 |
resp = requests.post(url, headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"}, json=payload, timeout=120)
|
| 150 |
if resp.status_code == 503:
|
| 151 |
+
time.sleep(20); continue
|
|
|
|
| 152 |
if resp.status_code == 200:
|
| 153 |
return resp.json()["choices"][0]["message"]["content"]
|
| 154 |
return "Image analysis failed."
|
|
|
|
| 164 |
def get_youtube_transcript(video_url: str) -> str:
|
| 165 |
"""Fetch the transcript/captions from a YouTube video URL.
|
| 166 |
Args:
|
| 167 |
+
video_url: The full YouTube URL e.g. https://www.youtube.com/watch?v=XXXXX
|
| 168 |
"""
|
| 169 |
try:
|
| 170 |
from youtube_transcript_api import YouTubeTranscriptApi
|
|
|
|
| 179 |
|
| 180 |
@tool
|
| 181 |
def run_python_code(code: str) -> str:
|
| 182 |
+
"""Execute Python code and return stdout. Use for math, logic, string ops, data processing.
|
| 183 |
Args:
|
| 184 |
code: Valid Python code to execute.
|
| 185 |
"""
|
|
|
|
| 193 |
return f"Execution error: {e}"
|
| 194 |
|
| 195 |
|
| 196 |
+
# ββ Agent βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 197 |
|
| 198 |
class GAIAAgent:
|
| 199 |
def __init__(self):
|
|
|
|
| 200 |
model = InferenceClientModel(
|
| 201 |
model_id="meta-llama/Llama-3.3-70B-Instruct",
|
| 202 |
token=os.environ.get("HF_TOKEN", ""),
|
|
|
|
| 211 |
run_python_code,
|
| 212 |
],
|
| 213 |
model=model,
|
| 214 |
+
add_base_tools=True,
|
| 215 |
max_steps=10,
|
| 216 |
verbosity_level=1,
|
| 217 |
additional_authorized_imports=[
|
| 218 |
"re", "json", "math", "unicodedata",
|
| 219 |
"datetime", "collections", "itertools",
|
| 220 |
+
"pandas", "requests", "os", "time",
|
| 221 |
],
|
| 222 |
)
|
| 223 |
print("GAIAAgent ready β
")
|
|
|
|
| 225 |
def __call__(self, question: str, task_id: str = "") -> str:
|
| 226 |
print(f"\n{'='*60}\nQ: {question[:120]}")
|
| 227 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
task_hint = ""
|
| 229 |
+
if task_id:
|
| 230 |
+
task_hint = f"\n\n[task_id='{task_id}' β call download_file_for_task('{task_id}') if a file/image/audio is needed]"
|
|
|
|
|
|
|
| 231 |
|
| 232 |
prompt = (
|
| 233 |
+
"Solve this GAIA benchmark question precisely.\n"
|
| 234 |
+
"- Use tools to verify facts. Do NOT guess.\n"
|
| 235 |
+
"- YouTube URL β call get_youtube_transcript\n"
|
| 236 |
+
"- File/image/audio/excel/pdf β call download_file_for_task\n"
|
| 237 |
+
"- Math/logic/strings β call run_python_code\n"
|
| 238 |
+
"- Facts β wikipedia_search or DuckDuckGoSearchTool\n"
|
| 239 |
+
"- Reversed text β decode first, then answer\n"
|
| 240 |
+
"- Return ONLY the exact answer. No explanation.\n\n"
|
|
|
|
|
|
|
| 241 |
f"Question: {question}{task_hint}"
|
| 242 |
)
|
| 243 |
|
| 244 |
try:
|
| 245 |
result = self.agent.run(prompt)
|
| 246 |
answer = str(result).strip()
|
|
|
|
| 247 |
for prefix in ["the answer is", "answer:", "final answer:", "result:"]:
|
| 248 |
if answer.lower().startswith(prefix):
|
| 249 |
answer = answer[len(prefix):].strip().lstrip(":").strip()
|
|
|
|
| 254 |
return "Unable to determine answer."
|
| 255 |
|
| 256 |
|
| 257 |
+
# ββ Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 258 |
|
| 259 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 260 |
if not profile:
|
|
|
|
| 287 |
answer = agent(question_text, task_id=task_id)
|
| 288 |
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
| 289 |
results_log.append({"Task ID": task_id, "Question": question_text[:80], "Submitted Answer": answer})
|
| 290 |
+
time.sleep(2)
|
| 291 |
|
| 292 |
if not answers_payload:
|
| 293 |
return "No answers produced.", pd.DataFrame(results_log)
|
|
|
|
| 317 |
gr.Markdown("# π€ GAIA Agent β smolagents + HF Inference")
|
| 318 |
gr.Markdown("""
|
| 319 |
**Models:** Llama-3.3-70B Β· Llama-3.2-11B-Vision Β· Whisper large-v3
|
| 320 |
+
**Tools:** DuckDuckGo Β· Wikipedia Β· VisitWebpage Β· YouTube transcript Β· Python Β· File reader
|
| 321 |
+
**Setup:** Ajoute `HF_TOKEN` dans les secrets de ton Space HF.
|
| 322 |
""")
|
| 323 |
gr.LoginButton()
|
| 324 |
run_btn = gr.Button("π Run Evaluation & Submit All Answers", variant="primary")
|