Update app.py
Browse files
app.py
CHANGED
|
@@ -2,40 +2,91 @@ import os
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
-
from smolagents import HfApiModel
|
|
|
|
|
|
|
| 6 |
|
| 7 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
class BasicAgent:
|
| 10 |
def __init__(self):
|
| 11 |
-
print("π Loading model...")
|
| 12 |
self.model = HfApiModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
def __call__(self, question: str) -> str:
|
| 15 |
try:
|
| 16 |
-
|
| 17 |
-
Do not write any explanation, no reasoning, no "Final Answer", no extra text.
|
| 18 |
-
Just give the direct answer.
|
| 19 |
-
|
| 20 |
-
Question: {question}
|
| 21 |
-
|
| 22 |
-
Answer:"""
|
| 23 |
-
|
| 24 |
-
output = self.model.generate(prompt, max_new_tokens=200)
|
| 25 |
answer = str(output).strip()
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
if "Answer:" in answer:
|
|
|
|
|
|
|
| 29 |
answer = answer.split("Answer:")[-1].strip()
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
except Exception as e:
|
| 33 |
-
return f"Error: {str(e)[:
|
| 34 |
|
| 35 |
|
|
|
|
| 36 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 37 |
if not profile:
|
| 38 |
-
return "Please login
|
| 39 |
|
| 40 |
username = profile.username.strip()
|
| 41 |
api_url = DEFAULT_API_URL
|
|
@@ -61,32 +112,25 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 61 |
|
| 62 |
answer = agent(question)
|
| 63 |
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
| 64 |
-
results_log.append({
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
"Answer": answer[:150] + "..." if len(answer) > 150 else answer
|
| 68 |
-
})
|
| 69 |
-
|
| 70 |
-
submission_data = {
|
| 71 |
-
"username": username,
|
| 72 |
-
"agent_code": agent_code,
|
| 73 |
-
"answers": answers_payload
|
| 74 |
-
}
|
| 75 |
|
| 76 |
try:
|
| 77 |
response = requests.post(submit_url, json=submission_data, timeout=90)
|
| 78 |
response.raise_for_status()
|
| 79 |
result = response.json()
|
| 80 |
score = result.get("score", 0)
|
| 81 |
-
status = f"β
|
| 82 |
return status, pd.DataFrame(results_log)
|
| 83 |
except Exception as e:
|
| 84 |
return f"Submission failed: {str(e)}", pd.DataFrame(results_log)
|
| 85 |
|
| 86 |
|
|
|
|
| 87 |
with gr.Blocks() as demo:
|
| 88 |
-
gr.Markdown("# Unit 4 - GAIA Agent (
|
| 89 |
-
gr.Markdown("Login β Click
|
| 90 |
|
| 91 |
gr.LoginButton()
|
| 92 |
btn = gr.Button("π Run Evaluation & Submit All Answers", variant="primary", size="large")
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
+
from smolagents import CodeAgent, HfApiModel, tool
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import io
|
| 8 |
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
+
# ====================== TOOLS ======================
|
| 12 |
+
@tool
|
| 13 |
+
def web_search(query: str) -> str:
|
| 14 |
+
"""Search the web for information."""
|
| 15 |
+
try:
|
| 16 |
+
from duckduckgo_search import DDGS
|
| 17 |
+
with DDGS() as ddgs:
|
| 18 |
+
results = list(ddgs.text(query, max_results=3))
|
| 19 |
+
return "\n".join([f"{r.get('title')}: {r.get('body') or r.get('snippet')}" for r in results])
|
| 20 |
+
except:
|
| 21 |
+
return "Search failed."
|
| 22 |
+
|
| 23 |
+
@tool
|
| 24 |
+
def calculate(expression: str) -> str:
|
| 25 |
+
"""Calculate simple math."""
|
| 26 |
+
try:
|
| 27 |
+
import math
|
| 28 |
+
return str(eval(expression, {"__builtins__": {}}, {"math": math}))
|
| 29 |
+
except:
|
| 30 |
+
return "Calc failed."
|
| 31 |
+
|
| 32 |
+
@tool
|
| 33 |
+
def download_file(task_id: str) -> str:
|
| 34 |
+
"""Download the file (image, csv, audio, etc.) attached to a question."""
|
| 35 |
+
url = f"{DEFAULT_API_URL}/files/{task_id}"
|
| 36 |
+
try:
|
| 37 |
+
r = requests.get(url, timeout=20)
|
| 38 |
+
r.raise_for_status()
|
| 39 |
+
content_type = r.headers.get("content-type", "")
|
| 40 |
+
|
| 41 |
+
if "image" in content_type:
|
| 42 |
+
img = Image.open(io.BytesIO(r.content))
|
| 43 |
+
return f"Downloaded image: {img.size} {img.format}"
|
| 44 |
+
else:
|
| 45 |
+
text = r.text[:1500]
|
| 46 |
+
return f"Downloaded file content:\n{text}"
|
| 47 |
+
except Exception as e:
|
| 48 |
+
return f"File download failed: {str(e)}"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# ====================== AGENT ======================
|
| 52 |
class BasicAgent:
|
| 53 |
def __init__(self):
|
|
|
|
| 54 |
self.model = HfApiModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")
|
| 55 |
+
|
| 56 |
+
self.agent = CodeAgent(
|
| 57 |
+
model=self.model,
|
| 58 |
+
tools=[web_search, calculate, download_file],
|
| 59 |
+
add_base_tools=True,
|
| 60 |
+
verbosity_level=0,
|
| 61 |
+
max_steps=10,
|
| 62 |
+
planning_interval=3
|
| 63 |
+
)
|
| 64 |
|
| 65 |
def __call__(self, question: str) -> str:
|
| 66 |
try:
|
| 67 |
+
output = self.agent.run(question)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
answer = str(output).strip()
|
| 69 |
|
| 70 |
+
# Force clean final answer (this fixes 0%)
|
| 71 |
+
if "Final Answer:" in answer:
|
| 72 |
+
answer = answer.split("Final Answer:")[-1].strip()
|
| 73 |
+
elif "Answer:" in answer:
|
| 74 |
answer = answer.split("Answer:")[-1].strip()
|
| 75 |
+
|
| 76 |
+
# Take last line if too long
|
| 77 |
+
if len(answer) > 400:
|
| 78 |
+
answer = answer.split("\n")[-1].strip()
|
| 79 |
+
|
| 80 |
+
return answer[:700].strip()
|
| 81 |
+
|
| 82 |
except Exception as e:
|
| 83 |
+
return f"Error: {str(e)[:150]}"
|
| 84 |
|
| 85 |
|
| 86 |
+
# ====================== SUBMISSION ======================
|
| 87 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 88 |
if not profile:
|
| 89 |
+
return "Please login first.", None
|
| 90 |
|
| 91 |
username = profile.username.strip()
|
| 92 |
api_url = DEFAULT_API_URL
|
|
|
|
| 112 |
|
| 113 |
answer = agent(question)
|
| 114 |
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
| 115 |
+
results_log.append({"Task ID": task_id, "Question": question[:100]+"...", "Answer": answer[:150]+"..."})
|
| 116 |
+
|
| 117 |
+
submission_data = {"username": username, "agent_code": agent_code, "answers": answers_payload}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
try:
|
| 120 |
response = requests.post(submit_url, json=submission_data, timeout=90)
|
| 121 |
response.raise_for_status()
|
| 122 |
result = response.json()
|
| 123 |
score = result.get("score", 0)
|
| 124 |
+
status = f"β
Done!\nScore: {score}% ({result.get('correct_count',0)}/20)\n{result.get('message','')}"
|
| 125 |
return status, pd.DataFrame(results_log)
|
| 126 |
except Exception as e:
|
| 127 |
return f"Submission failed: {str(e)}", pd.DataFrame(results_log)
|
| 128 |
|
| 129 |
|
| 130 |
+
# ====================== UI ======================
|
| 131 |
with gr.Blocks() as demo:
|
| 132 |
+
gr.Markdown("# Unit 4 - Final GAIA Agent (with file support)")
|
| 133 |
+
gr.Markdown("Login β Click button (takes 8-15 min)")
|
| 134 |
|
| 135 |
gr.LoginButton()
|
| 136 |
btn = gr.Button("π Run Evaluation & Submit All Answers", variant="primary", size="large")
|