Update app.py
Browse files
app.py
CHANGED
|
@@ -10,8 +10,9 @@ import re
|
|
| 10 |
import requests
|
| 11 |
import pandas as pd
|
| 12 |
import gradio as gr
|
|
|
|
| 13 |
|
| 14 |
-
from smolagents import CodeAgent,
|
| 15 |
|
| 16 |
# -------------------------
|
| 17 |
# Minimal tools
|
|
@@ -39,33 +40,16 @@ def safe_calc(expr: str):
|
|
| 39 |
|
| 40 |
@tool
|
| 41 |
def calculator(expr: str) -> str:
|
| 42 |
-
"""
|
| 43 |
-
Safely evaluate a mathematical expression.
|
| 44 |
-
|
| 45 |
-
Args:
|
| 46 |
-
expr (str): A string containing a math expression like "2 + 2 * 3".
|
| 47 |
-
|
| 48 |
-
Returns:
|
| 49 |
-
str: JSON string with {"expression": expr, "result": value} or {"error": "..."} on failure.
|
| 50 |
-
"""
|
| 51 |
try:
|
| 52 |
val = safe_calc(expr)
|
| 53 |
return json.dumps({"expression": expr, "result": float(val)})
|
| 54 |
except Exception as e:
|
| 55 |
return json.dumps({"error": f"Calc error: {e}"})
|
| 56 |
|
| 57 |
-
|
| 58 |
@tool
|
| 59 |
def get_current_time_in_timezone(timezone: str) -> str:
|
| 60 |
-
"""
|
| 61 |
-
Get the current local time in a specified timezone.
|
| 62 |
-
|
| 63 |
-
Args:
|
| 64 |
-
timezone (str): A valid timezone string (e.g., "Europe/Paris").
|
| 65 |
-
|
| 66 |
-
Returns:
|
| 67 |
-
str: JSON string with {"timezone": timezone, "local_time": "..."} or {"error": "..."} on failure.
|
| 68 |
-
"""
|
| 69 |
try:
|
| 70 |
tz = pytz.timezone(timezone)
|
| 71 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
|
@@ -73,22 +57,24 @@ def get_current_time_in_timezone(timezone: str) -> str:
|
|
| 73 |
except Exception as e:
|
| 74 |
return json.dumps({"error": f"Timezone error: {e}"})
|
| 75 |
|
| 76 |
-
|
| 77 |
# -------------------------
|
| 78 |
# Load prompts.yaml if exists
|
| 79 |
# -------------------------
|
| 80 |
prompt_templates = None
|
| 81 |
try:
|
| 82 |
-
import yaml
|
| 83 |
with open("prompts.yaml", "r") as fh:
|
| 84 |
prompt_templates = yaml.safe_load(fh)
|
| 85 |
except Exception:
|
| 86 |
prompt_templates = None
|
| 87 |
|
| 88 |
# -------------------------
|
| 89 |
-
#
|
| 90 |
# -------------------------
|
| 91 |
-
model =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
code_agent = CodeAgent(
|
| 94 |
model=model,
|
|
@@ -124,10 +110,7 @@ class GaiaAgentMinimal:
|
|
| 124 |
|
| 125 |
# Time queries
|
| 126 |
if self._is_time(q):
|
| 127 |
-
if "paris" in q.lower() or "france" in q.lower()
|
| 128 |
-
tz = "Europe/Paris"
|
| 129 |
-
else:
|
| 130 |
-
tz = "UTC"
|
| 131 |
return get_current_time_in_timezone(tz)
|
| 132 |
|
| 133 |
# fallback LLM
|
|
@@ -141,7 +124,6 @@ class GaiaAgentMinimal:
|
|
| 141 |
except Exception as e:
|
| 142 |
return json.dumps({"error": f"Agent internal error: {e}"})
|
| 143 |
|
| 144 |
-
# instantiate GAIA agent
|
| 145 |
gaia_agent = GaiaAgentMinimal(code_agent)
|
| 146 |
|
| 147 |
# -------------------------
|
|
@@ -151,16 +133,13 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
| 151 |
|
| 152 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 153 |
space_id = os.getenv("SPACE_ID")
|
| 154 |
-
|
| 155 |
if profile:
|
| 156 |
-
username =
|
| 157 |
else:
|
| 158 |
return "Please Login to Hugging Face with the button.", None
|
| 159 |
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
submit_url = f"{api_url}/submit"
|
| 163 |
-
|
| 164 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "unknown"
|
| 165 |
|
| 166 |
# Fetch questions
|
|
@@ -174,8 +153,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 174 |
return f"Error fetching questions: {e}", None
|
| 175 |
|
| 176 |
# Run agent
|
| 177 |
-
results_log = []
|
| 178 |
-
answers_payload = []
|
| 179 |
for item in questions_data:
|
| 180 |
task_id = item.get("task_id")
|
| 181 |
question_text = item.get("question")
|
|
@@ -193,7 +171,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 193 |
|
| 194 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 195 |
|
| 196 |
-
# Submit
|
| 197 |
try:
|
| 198 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 199 |
response.raise_for_status()
|
|
@@ -205,25 +182,20 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 205 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 206 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 207 |
)
|
| 208 |
-
|
| 209 |
-
return final_status, results_df
|
| 210 |
except Exception as e:
|
| 211 |
-
|
| 212 |
-
return f"Submission failed: {e}", results_df
|
| 213 |
|
| 214 |
# -------------------------
|
| 215 |
# Gradio UI
|
| 216 |
# -------------------------
|
| 217 |
with gr.Blocks() as demo:
|
| 218 |
gr.Markdown("# Minimal GAIA Agent Runner")
|
| 219 |
-
gr.Markdown(
|
| 220 |
-
"Log in to Hugging Face, click 'Run Evaluation & Submit All Answers' to fetch questions, run the agent, and submit answers."
|
| 221 |
-
)
|
| 222 |
gr.LoginButton()
|
| 223 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 224 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 225 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 226 |
-
|
| 227 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 228 |
|
| 229 |
if __name__ == "__main__":
|
|
|
|
| 10 |
import requests
|
| 11 |
import pandas as pd
|
| 12 |
import gradio as gr
|
| 13 |
+
import yaml
|
| 14 |
|
| 15 |
+
from smolagents import CodeAgent, HfApiModel, tool
|
| 16 |
|
| 17 |
# -------------------------
|
| 18 |
# Minimal tools
|
|
|
|
| 40 |
|
| 41 |
@tool
|
| 42 |
def calculator(expr: str) -> str:
|
| 43 |
+
"""Safely evaluate a math expression."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
try:
|
| 45 |
val = safe_calc(expr)
|
| 46 |
return json.dumps({"expression": expr, "result": float(val)})
|
| 47 |
except Exception as e:
|
| 48 |
return json.dumps({"error": f"Calc error: {e}"})
|
| 49 |
|
|
|
|
| 50 |
@tool
|
| 51 |
def get_current_time_in_timezone(timezone: str) -> str:
|
| 52 |
+
"""Get the current local time in a timezone."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
try:
|
| 54 |
tz = pytz.timezone(timezone)
|
| 55 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
| 57 |
except Exception as e:
|
| 58 |
return json.dumps({"error": f"Timezone error: {e}"})
|
| 59 |
|
|
|
|
| 60 |
# -------------------------
|
| 61 |
# Load prompts.yaml if exists
|
| 62 |
# -------------------------
|
| 63 |
prompt_templates = None
|
| 64 |
try:
|
|
|
|
| 65 |
with open("prompts.yaml", "r") as fh:
|
| 66 |
prompt_templates = yaml.safe_load(fh)
|
| 67 |
except Exception:
|
| 68 |
prompt_templates = None
|
| 69 |
|
| 70 |
# -------------------------
|
| 71 |
+
# HfApiModel + CodeAgent
|
| 72 |
# -------------------------
|
| 73 |
+
model = HfApiModel(
|
| 74 |
+
model_id="HuggingFaceTB/SmolLM-135M-Instruct",
|
| 75 |
+
max_tokens=1024,
|
| 76 |
+
temperature=0.5
|
| 77 |
+
)
|
| 78 |
|
| 79 |
code_agent = CodeAgent(
|
| 80 |
model=model,
|
|
|
|
| 110 |
|
| 111 |
# Time queries
|
| 112 |
if self._is_time(q):
|
| 113 |
+
tz = "Europe/Paris" if "paris" in q.lower() or "france" in q.lower() else "UTC"
|
|
|
|
|
|
|
|
|
|
| 114 |
return get_current_time_in_timezone(tz)
|
| 115 |
|
| 116 |
# fallback LLM
|
|
|
|
| 124 |
except Exception as e:
|
| 125 |
return json.dumps({"error": f"Agent internal error: {e}"})
|
| 126 |
|
|
|
|
| 127 |
gaia_agent = GaiaAgentMinimal(code_agent)
|
| 128 |
|
| 129 |
# -------------------------
|
|
|
|
| 133 |
|
| 134 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 135 |
space_id = os.getenv("SPACE_ID")
|
|
|
|
| 136 |
if profile:
|
| 137 |
+
username = profile.username
|
| 138 |
else:
|
| 139 |
return "Please Login to Hugging Face with the button.", None
|
| 140 |
|
| 141 |
+
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 142 |
+
submit_url = f"{DEFAULT_API_URL}/submit"
|
|
|
|
|
|
|
| 143 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "unknown"
|
| 144 |
|
| 145 |
# Fetch questions
|
|
|
|
| 153 |
return f"Error fetching questions: {e}", None
|
| 154 |
|
| 155 |
# Run agent
|
| 156 |
+
results_log, answers_payload = [], []
|
|
|
|
| 157 |
for item in questions_data:
|
| 158 |
task_id = item.get("task_id")
|
| 159 |
question_text = item.get("question")
|
|
|
|
| 171 |
|
| 172 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 173 |
|
|
|
|
| 174 |
try:
|
| 175 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 176 |
response.raise_for_status()
|
|
|
|
| 182 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 183 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 184 |
)
|
| 185 |
+
return final_status, pd.DataFrame(results_log)
|
|
|
|
| 186 |
except Exception as e:
|
| 187 |
+
return f"Submission failed: {e}", pd.DataFrame(results_log)
|
|
|
|
| 188 |
|
| 189 |
# -------------------------
|
| 190 |
# Gradio UI
|
| 191 |
# -------------------------
|
| 192 |
with gr.Blocks() as demo:
|
| 193 |
gr.Markdown("# Minimal GAIA Agent Runner")
|
| 194 |
+
gr.Markdown("Log in to Hugging Face, click 'Run Evaluation & Submit All Answers' to fetch questions, run the agent, and submit answers.")
|
|
|
|
|
|
|
| 195 |
gr.LoginButton()
|
| 196 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 197 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 198 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
|
|
|
| 199 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 200 |
|
| 201 |
if __name__ == "__main__":
|