Update app.py
Browse files
app.py
CHANGED
|
@@ -2,10 +2,9 @@ import os
|
|
| 2 |
import re
|
| 3 |
import gradio as gr
|
| 4 |
import requests
|
| 5 |
-
import inspect
|
| 6 |
import pandas as pd
|
| 7 |
|
| 8 |
-
from smolagents import
|
| 9 |
|
| 10 |
# --- Constants ---
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
@@ -17,33 +16,45 @@ class BasicAgent:
|
|
| 17 |
|
| 18 |
groq_key = os.getenv("GROQ_API_KEY")
|
| 19 |
if not groq_key:
|
| 20 |
-
raise ValueError(
|
|
|
|
|
|
|
| 21 |
|
| 22 |
model = LiteLLMModel(
|
| 23 |
-
model_id="groq/llama-3.
|
| 24 |
-
api_key=groq_key
|
| 25 |
)
|
| 26 |
|
| 27 |
-
self.agent =
|
| 28 |
-
tools=[DuckDuckGoSearchTool()],
|
| 29 |
model=model,
|
| 30 |
-
max_steps=
|
|
|
|
|
|
|
| 31 |
)
|
| 32 |
|
| 33 |
def clean_answer(self, answer: str) -> str:
|
| 34 |
answer = str(answer).strip()
|
| 35 |
|
|
|
|
| 36 |
answer = re.sub(r"(?i)^final answer\s*:\s*", "", answer).strip()
|
| 37 |
answer = re.sub(r"(?i)^answer\s*:\s*", "", answer).strip()
|
| 38 |
answer = re.sub(r"(?i)^the answer is\s*", "", answer).strip()
|
| 39 |
|
|
|
|
|
|
|
| 40 |
answer = answer.strip("`")
|
| 41 |
answer = answer.strip('"')
|
| 42 |
answer = answer.strip("'")
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
lines = [line.strip() for line in answer.splitlines() if line.strip()]
|
| 45 |
if lines:
|
| 46 |
-
|
|
|
|
| 47 |
|
| 48 |
return answer.strip()
|
| 49 |
|
|
@@ -63,7 +74,9 @@ Rules:
|
|
| 63 |
- If the answer is a name, return only the name.
|
| 64 |
- If the answer is a number, return only the number and unit if required.
|
| 65 |
- If the answer is a date, use the clearest standard date format.
|
| 66 |
-
-
|
|
|
|
|
|
|
| 67 |
|
| 68 |
Question:
|
| 69 |
{question}
|
|
@@ -85,8 +98,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 85 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 86 |
and displays the results.
|
| 87 |
"""
|
| 88 |
-
|
| 89 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 90 |
|
| 91 |
if profile:
|
| 92 |
username = f"{profile.username}"
|
|
@@ -106,8 +118,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 106 |
print(f"Error instantiating agent: {e}")
|
| 107 |
return f"Error initializing agent: {e}", None
|
| 108 |
|
| 109 |
-
# In the case of an app running as a Hugging Face Space,
|
| 110 |
-
# this link points toward your codebase.
|
| 111 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 112 |
print(agent_code)
|
| 113 |
|
|
@@ -117,22 +127,27 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 117 |
response = requests.get(questions_url, timeout=15)
|
| 118 |
response.raise_for_status()
|
| 119 |
questions_data = response.json()
|
|
|
|
| 120 |
if not questions_data:
|
| 121 |
print("Fetched questions list is empty.")
|
| 122 |
return "Fetched questions list is empty or invalid format.", None
|
|
|
|
| 123 |
print(f"Fetched {len(questions_data)} questions.")
|
|
|
|
| 124 |
except requests.exceptions.RequestException as e:
|
| 125 |
print(f"Error fetching questions: {e}")
|
| 126 |
return f"Error fetching questions: {e}", None
|
|
|
|
| 127 |
except requests.exceptions.JSONDecodeError as e:
|
| 128 |
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 129 |
print(f"Response text: {response.text[:500]}")
|
| 130 |
return f"Error decoding server response for questions: {e}", None
|
|
|
|
| 131 |
except Exception as e:
|
| 132 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 133 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 134 |
|
| 135 |
-
# 3. Run
|
| 136 |
results_log = []
|
| 137 |
answers_payload = []
|
| 138 |
print(f"Running agent on {len(questions_data)} questions...")
|
|
@@ -147,12 +162,14 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 147 |
|
| 148 |
try:
|
| 149 |
submitted_answer = agent(question_text)
|
|
|
|
| 150 |
answers_payload.append(
|
| 151 |
{
|
| 152 |
"task_id": task_id,
|
| 153 |
"submitted_answer": submitted_answer,
|
| 154 |
}
|
| 155 |
)
|
|
|
|
| 156 |
results_log.append(
|
| 157 |
{
|
| 158 |
"Task ID": task_id,
|
|
@@ -160,6 +177,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 160 |
"Submitted Answer": submitted_answer,
|
| 161 |
}
|
| 162 |
)
|
|
|
|
| 163 |
except Exception as e:
|
| 164 |
print(f"Error running agent on task {task_id}: {e}")
|
| 165 |
results_log.append(
|
|
@@ -181,7 +199,9 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 181 |
"answers": answers_payload,
|
| 182 |
}
|
| 183 |
|
| 184 |
-
status_update =
|
|
|
|
|
|
|
| 185 |
print(status_update)
|
| 186 |
|
| 187 |
# 5. Submit
|
|
@@ -205,6 +225,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 205 |
|
| 206 |
except requests.exceptions.HTTPError as e:
|
| 207 |
error_detail = f"Server responded with status {e.response.status_code}."
|
|
|
|
| 208 |
try:
|
| 209 |
error_json = e.response.json()
|
| 210 |
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
|
@@ -213,24 +234,28 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 213 |
|
| 214 |
status_message = f"Submission Failed: {error_detail}"
|
| 215 |
print(status_message)
|
|
|
|
| 216 |
results_df = pd.DataFrame(results_log)
|
| 217 |
return status_message, results_df
|
| 218 |
|
| 219 |
except requests.exceptions.Timeout:
|
| 220 |
status_message = "Submission Failed: The request timed out."
|
| 221 |
print(status_message)
|
|
|
|
| 222 |
results_df = pd.DataFrame(results_log)
|
| 223 |
return status_message, results_df
|
| 224 |
|
| 225 |
except requests.exceptions.RequestException as e:
|
| 226 |
status_message = f"Submission Failed: Network error - {e}"
|
| 227 |
print(status_message)
|
|
|
|
| 228 |
results_df = pd.DataFrame(results_log)
|
| 229 |
return status_message, results_df
|
| 230 |
|
| 231 |
except Exception as e:
|
| 232 |
status_message = f"An unexpected error occurred during submission: {e}"
|
| 233 |
print(status_message)
|
|
|
|
| 234 |
results_df = pd.DataFrame(results_log)
|
| 235 |
return status_message, results_df
|
| 236 |
|
|
@@ -291,7 +316,9 @@ if __name__ == "__main__":
|
|
| 291 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 292 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 293 |
else:
|
| 294 |
-
print(
|
|
|
|
|
|
|
| 295 |
|
| 296 |
print("-" * (60 + len(" App Starting ")) + "\n")
|
| 297 |
|
|
|
|
| 2 |
import re
|
| 3 |
import gradio as gr
|
| 4 |
import requests
|
|
|
|
| 5 |
import pandas as pd
|
| 6 |
|
| 7 |
+
from smolagents import ToolCallingAgent, DuckDuckGoSearchTool, LiteLLMModel
|
| 8 |
|
| 9 |
# --- Constants ---
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
| 16 |
|
| 17 |
groq_key = os.getenv("GROQ_API_KEY")
|
| 18 |
if not groq_key:
|
| 19 |
+
raise ValueError(
|
| 20 |
+
"GROQ_API_KEY is missing. Add it in Space Settings → Variables and secrets."
|
| 21 |
+
)
|
| 22 |
|
| 23 |
model = LiteLLMModel(
|
| 24 |
+
model_id="groq/llama-3.3-70b-versatile",
|
| 25 |
+
api_key=groq_key,
|
| 26 |
)
|
| 27 |
|
| 28 |
+
self.agent = ToolCallingAgent(
|
| 29 |
+
tools=[DuckDuckGoSearchTool(max_results=8)],
|
| 30 |
model=model,
|
| 31 |
+
max_steps=6,
|
| 32 |
+
name="search_agent",
|
| 33 |
+
description="Searches the web and returns short exact answers.",
|
| 34 |
)
|
| 35 |
|
| 36 |
def clean_answer(self, answer: str) -> str:
|
| 37 |
answer = str(answer).strip()
|
| 38 |
|
| 39 |
+
# Remove common unwanted prefixes.
|
| 40 |
answer = re.sub(r"(?i)^final answer\s*:\s*", "", answer).strip()
|
| 41 |
answer = re.sub(r"(?i)^answer\s*:\s*", "", answer).strip()
|
| 42 |
answer = re.sub(r"(?i)^the answer is\s*", "", answer).strip()
|
| 43 |
|
| 44 |
+
# Remove markdown/code wrapping.
|
| 45 |
+
answer = answer.replace("```", "").strip()
|
| 46 |
answer = answer.strip("`")
|
| 47 |
answer = answer.strip('"')
|
| 48 |
answer = answer.strip("'")
|
| 49 |
|
| 50 |
+
# Remove common final-answer phrasing if it appears later.
|
| 51 |
+
answer = re.sub(r"(?i)final answer\s*:\s*", "", answer).strip()
|
| 52 |
+
|
| 53 |
+
# If the model gives multiple lines, prefer the shortest useful final-looking line.
|
| 54 |
lines = [line.strip() for line in answer.splitlines() if line.strip()]
|
| 55 |
if lines:
|
| 56 |
+
short_lines = [line for line in lines if len(line) <= 120]
|
| 57 |
+
answer = short_lines[-1] if short_lines else lines[-1]
|
| 58 |
|
| 59 |
return answer.strip()
|
| 60 |
|
|
|
|
| 74 |
- If the answer is a name, return only the name.
|
| 75 |
- If the answer is a number, return only the number and unit if required.
|
| 76 |
- If the answer is a date, use the clearest standard date format.
|
| 77 |
+
- Use the search tool when the answer requires factual lookup.
|
| 78 |
+
- If the question can be solved directly by reasoning, solve it directly without search.
|
| 79 |
+
- For comma-separated answers, use exactly this style: item 1, item 2, item 3
|
| 80 |
|
| 81 |
Question:
|
| 82 |
{question}
|
|
|
|
| 98 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 99 |
and displays the results.
|
| 100 |
"""
|
| 101 |
+
space_id = os.getenv("SPACE_ID")
|
|
|
|
| 102 |
|
| 103 |
if profile:
|
| 104 |
username = f"{profile.username}"
|
|
|
|
| 118 |
print(f"Error instantiating agent: {e}")
|
| 119 |
return f"Error initializing agent: {e}", None
|
| 120 |
|
|
|
|
|
|
|
| 121 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 122 |
print(agent_code)
|
| 123 |
|
|
|
|
| 127 |
response = requests.get(questions_url, timeout=15)
|
| 128 |
response.raise_for_status()
|
| 129 |
questions_data = response.json()
|
| 130 |
+
|
| 131 |
if not questions_data:
|
| 132 |
print("Fetched questions list is empty.")
|
| 133 |
return "Fetched questions list is empty or invalid format.", None
|
| 134 |
+
|
| 135 |
print(f"Fetched {len(questions_data)} questions.")
|
| 136 |
+
|
| 137 |
except requests.exceptions.RequestException as e:
|
| 138 |
print(f"Error fetching questions: {e}")
|
| 139 |
return f"Error fetching questions: {e}", None
|
| 140 |
+
|
| 141 |
except requests.exceptions.JSONDecodeError as e:
|
| 142 |
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 143 |
print(f"Response text: {response.text[:500]}")
|
| 144 |
return f"Error decoding server response for questions: {e}", None
|
| 145 |
+
|
| 146 |
except Exception as e:
|
| 147 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 148 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 149 |
|
| 150 |
+
# 3. Run Agent
|
| 151 |
results_log = []
|
| 152 |
answers_payload = []
|
| 153 |
print(f"Running agent on {len(questions_data)} questions...")
|
|
|
|
| 162 |
|
| 163 |
try:
|
| 164 |
submitted_answer = agent(question_text)
|
| 165 |
+
|
| 166 |
answers_payload.append(
|
| 167 |
{
|
| 168 |
"task_id": task_id,
|
| 169 |
"submitted_answer": submitted_answer,
|
| 170 |
}
|
| 171 |
)
|
| 172 |
+
|
| 173 |
results_log.append(
|
| 174 |
{
|
| 175 |
"Task ID": task_id,
|
|
|
|
| 177 |
"Submitted Answer": submitted_answer,
|
| 178 |
}
|
| 179 |
)
|
| 180 |
+
|
| 181 |
except Exception as e:
|
| 182 |
print(f"Error running agent on task {task_id}: {e}")
|
| 183 |
results_log.append(
|
|
|
|
| 199 |
"answers": answers_payload,
|
| 200 |
}
|
| 201 |
|
| 202 |
+
status_update = (
|
| 203 |
+
f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 204 |
+
)
|
| 205 |
print(status_update)
|
| 206 |
|
| 207 |
# 5. Submit
|
|
|
|
| 225 |
|
| 226 |
except requests.exceptions.HTTPError as e:
|
| 227 |
error_detail = f"Server responded with status {e.response.status_code}."
|
| 228 |
+
|
| 229 |
try:
|
| 230 |
error_json = e.response.json()
|
| 231 |
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
|
|
|
| 234 |
|
| 235 |
status_message = f"Submission Failed: {error_detail}"
|
| 236 |
print(status_message)
|
| 237 |
+
|
| 238 |
results_df = pd.DataFrame(results_log)
|
| 239 |
return status_message, results_df
|
| 240 |
|
| 241 |
except requests.exceptions.Timeout:
|
| 242 |
status_message = "Submission Failed: The request timed out."
|
| 243 |
print(status_message)
|
| 244 |
+
|
| 245 |
results_df = pd.DataFrame(results_log)
|
| 246 |
return status_message, results_df
|
| 247 |
|
| 248 |
except requests.exceptions.RequestException as e:
|
| 249 |
status_message = f"Submission Failed: Network error - {e}"
|
| 250 |
print(status_message)
|
| 251 |
+
|
| 252 |
results_df = pd.DataFrame(results_log)
|
| 253 |
return status_message, results_df
|
| 254 |
|
| 255 |
except Exception as e:
|
| 256 |
status_message = f"An unexpected error occurred during submission: {e}"
|
| 257 |
print(status_message)
|
| 258 |
+
|
| 259 |
results_df = pd.DataFrame(results_log)
|
| 260 |
return status_message, results_df
|
| 261 |
|
|
|
|
| 316 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 317 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 318 |
else:
|
| 319 |
+
print(
|
| 320 |
+
"ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
|
| 321 |
+
)
|
| 322 |
|
| 323 |
print("-" * (60 + len(" App Starting ")) + "\n")
|
| 324 |
|