Update app.py
Browse files
app.py
CHANGED
|
@@ -10,7 +10,6 @@ import re
|
|
| 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 |
|
|
@@ -44,7 +43,7 @@ def calculator(expr: str) -> str:
|
|
| 44 |
Safely evaluate a mathematical expression.
|
| 45 |
|
| 46 |
Args:
|
| 47 |
-
expr (str):
|
| 48 |
|
| 49 |
Returns:
|
| 50 |
str: JSON string with {"expression": expr, "result": value} or {"error": "..."} on failure.
|
|
@@ -55,6 +54,7 @@ def calculator(expr: str) -> str:
|
|
| 55 |
except Exception as e:
|
| 56 |
return json.dumps({"error": f"Calc error: {e}"})
|
| 57 |
|
|
|
|
| 58 |
@tool
|
| 59 |
def get_current_time_in_timezone(timezone: str) -> str:
|
| 60 |
"""
|
|
@@ -73,26 +73,28 @@ 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 |
# Load prompts.yaml if exists
|
| 78 |
# -------------------------
|
| 79 |
prompt_templates = None
|
| 80 |
try:
|
|
|
|
| 81 |
with open("prompts.yaml", "r") as fh:
|
| 82 |
prompt_templates = yaml.safe_load(fh)
|
| 83 |
except Exception:
|
| 84 |
prompt_templates = None
|
| 85 |
|
|
|
|
| 86 |
# -------------------------
|
| 87 |
-
# HfApiModel + CodeAgent
|
| 88 |
# -------------------------
|
| 89 |
-
hf_token = os.getenv("HF_API_TOKEN") # token
|
| 90 |
|
| 91 |
model = HfApiModel(
|
| 92 |
model_id="HuggingFaceTB/SmolLM-135M-Instruct",
|
| 93 |
max_tokens=1024,
|
| 94 |
temperature=0.5,
|
| 95 |
-
api_key=hf_token
|
| 96 |
)
|
| 97 |
|
| 98 |
code_agent = CodeAgent(
|
|
@@ -103,6 +105,7 @@ code_agent = CodeAgent(
|
|
| 103 |
prompt_templates=prompt_templates
|
| 104 |
)
|
| 105 |
|
|
|
|
| 106 |
# -------------------------
|
| 107 |
# GAIA Agent wrapper
|
| 108 |
# -------------------------
|
|
@@ -120,13 +123,22 @@ class GaiaAgentMinimal:
|
|
| 120 |
def run(self, question: str) -> str:
|
| 121 |
try:
|
| 122 |
q = question.strip()
|
|
|
|
|
|
|
| 123 |
if self._is_calc(q):
|
| 124 |
m = re.search(r'([0-9\.\s\+\-\*\/\^\%\(\)]+)', q)
|
| 125 |
expr = m.group(1) if m else q
|
| 126 |
return calculator(expr)
|
|
|
|
|
|
|
| 127 |
if self._is_time(q):
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
| 129 |
return get_current_time_in_timezone(tz)
|
|
|
|
|
|
|
| 130 |
resp = self.code_agent.run(q)
|
| 131 |
if isinstance(resp, dict):
|
| 132 |
for key in ("final_answer", "answer", "result", "output"):
|
|
@@ -137,8 +149,10 @@ class GaiaAgentMinimal:
|
|
| 137 |
except Exception as e:
|
| 138 |
return json.dumps({"error": f"Agent internal error: {e}"})
|
| 139 |
|
|
|
|
| 140 |
gaia_agent = GaiaAgentMinimal(code_agent)
|
| 141 |
|
|
|
|
| 142 |
# -------------------------
|
| 143 |
# GAIA runner
|
| 144 |
# -------------------------
|
|
@@ -146,11 +160,16 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
| 146 |
|
| 147 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 148 |
space_id = os.getenv("SPACE_ID")
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
| 150 |
return "Please Login to Hugging Face with the button.", None
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
| 154 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "unknown"
|
| 155 |
|
| 156 |
# Fetch questions
|
|
@@ -163,6 +182,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 163 |
except Exception as e:
|
| 164 |
return f"Error fetching questions: {e}", None
|
| 165 |
|
|
|
|
| 166 |
results_log = []
|
| 167 |
answers_payload = []
|
| 168 |
for item in questions_data:
|
|
@@ -180,7 +200,9 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 180 |
if not answers_payload:
|
| 181 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 182 |
|
| 183 |
-
submission_data = {"username": username, "agent_code": agent_code, "answers": answers_payload}
|
|
|
|
|
|
|
| 184 |
try:
|
| 185 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 186 |
response.raise_for_status()
|
|
@@ -192,20 +214,26 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 192 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 193 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 194 |
)
|
| 195 |
-
|
|
|
|
| 196 |
except Exception as e:
|
| 197 |
-
|
|
|
|
|
|
|
| 198 |
|
| 199 |
# -------------------------
|
| 200 |
# Gradio UI
|
| 201 |
# -------------------------
|
| 202 |
with gr.Blocks() as demo:
|
| 203 |
gr.Markdown("# Minimal GAIA Agent Runner")
|
| 204 |
-
gr.Markdown(
|
|
|
|
|
|
|
| 205 |
gr.LoginButton()
|
| 206 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 207 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 208 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
|
|
|
| 209 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 210 |
|
| 211 |
if __name__ == "__main__":
|
|
|
|
| 10 |
import requests
|
| 11 |
import pandas as pd
|
| 12 |
import gradio as gr
|
|
|
|
| 13 |
|
| 14 |
from smolagents import CodeAgent, HfApiModel, tool
|
| 15 |
|
|
|
|
| 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.
|
|
|
|
| 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 |
"""
|
|
|
|
| 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 |
+
# HfApiModel + CodeAgent
|
| 91 |
# -------------------------
|
| 92 |
+
hf_token = os.getenv("HF_API_TOKEN") # Assurez-vous que votre token HF est défini
|
| 93 |
|
| 94 |
model = HfApiModel(
|
| 95 |
model_id="HuggingFaceTB/SmolLM-135M-Instruct",
|
| 96 |
max_tokens=1024,
|
| 97 |
temperature=0.5,
|
|
|
|
| 98 |
)
|
| 99 |
|
| 100 |
code_agent = CodeAgent(
|
|
|
|
| 105 |
prompt_templates=prompt_templates
|
| 106 |
)
|
| 107 |
|
| 108 |
+
|
| 109 |
# -------------------------
|
| 110 |
# GAIA Agent wrapper
|
| 111 |
# -------------------------
|
|
|
|
| 123 |
def run(self, question: str) -> str:
|
| 124 |
try:
|
| 125 |
q = question.strip()
|
| 126 |
+
|
| 127 |
+
# Calculator queries
|
| 128 |
if self._is_calc(q):
|
| 129 |
m = re.search(r'([0-9\.\s\+\-\*\/\^\%\(\)]+)', q)
|
| 130 |
expr = m.group(1) if m else q
|
| 131 |
return calculator(expr)
|
| 132 |
+
|
| 133 |
+
# Time queries
|
| 134 |
if self._is_time(q):
|
| 135 |
+
if "paris" in q.lower() or "france" in q.lower():
|
| 136 |
+
tz = "Europe/Paris"
|
| 137 |
+
else:
|
| 138 |
+
tz = "UTC"
|
| 139 |
return get_current_time_in_timezone(tz)
|
| 140 |
+
|
| 141 |
+
# fallback LLM
|
| 142 |
resp = self.code_agent.run(q)
|
| 143 |
if isinstance(resp, dict):
|
| 144 |
for key in ("final_answer", "answer", "result", "output"):
|
|
|
|
| 149 |
except Exception as e:
|
| 150 |
return json.dumps({"error": f"Agent internal error: {e}"})
|
| 151 |
|
| 152 |
+
|
| 153 |
gaia_agent = GaiaAgentMinimal(code_agent)
|
| 154 |
|
| 155 |
+
|
| 156 |
# -------------------------
|
| 157 |
# GAIA runner
|
| 158 |
# -------------------------
|
|
|
|
| 160 |
|
| 161 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 162 |
space_id = os.getenv("SPACE_ID")
|
| 163 |
+
|
| 164 |
+
if profile:
|
| 165 |
+
username = f"{profile.username}"
|
| 166 |
+
else:
|
| 167 |
return "Please Login to Hugging Face with the button.", None
|
| 168 |
+
|
| 169 |
+
api_url = DEFAULT_API_URL
|
| 170 |
+
questions_url = f"{api_url}/questions"
|
| 171 |
+
submit_url = f"{api_url}/submit"
|
| 172 |
+
|
| 173 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "unknown"
|
| 174 |
|
| 175 |
# Fetch questions
|
|
|
|
| 182 |
except Exception as e:
|
| 183 |
return f"Error fetching questions: {e}", None
|
| 184 |
|
| 185 |
+
# Run agent
|
| 186 |
results_log = []
|
| 187 |
answers_payload = []
|
| 188 |
for item in questions_data:
|
|
|
|
| 200 |
if not answers_payload:
|
| 201 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 202 |
|
| 203 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 204 |
+
|
| 205 |
+
# Submit
|
| 206 |
try:
|
| 207 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 208 |
response.raise_for_status()
|
|
|
|
| 214 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 215 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 216 |
)
|
| 217 |
+
results_df = pd.DataFrame(results_log)
|
| 218 |
+
return final_status, results_df
|
| 219 |
except Exception as e:
|
| 220 |
+
results_df = pd.DataFrame(results_log)
|
| 221 |
+
return f"Submission failed: {e}", results_df
|
| 222 |
+
|
| 223 |
|
| 224 |
# -------------------------
|
| 225 |
# Gradio UI
|
| 226 |
# -------------------------
|
| 227 |
with gr.Blocks() as demo:
|
| 228 |
gr.Markdown("# Minimal GAIA Agent Runner")
|
| 229 |
+
gr.Markdown(
|
| 230 |
+
"Log in to Hugging Face, click 'Run Evaluation & Submit All Answers' to fetch questions, run the agent, and submit answers."
|
| 231 |
+
)
|
| 232 |
gr.LoginButton()
|
| 233 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 234 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 235 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 236 |
+
|
| 237 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 238 |
|
| 239 |
if __name__ == "__main__":
|