Update app.py
#426
by ahmedreyanniazi - opened
app.py
CHANGED
|
@@ -4,22 +4,77 @@ import requests
|
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
|
| 7 |
-
#
|
|
|
|
|
|
|
|
|
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
-
# ---
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
def run_and_submit_all(
|
| 23 |
"""
|
| 24 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 25 |
and displays the results.
|
|
@@ -28,7 +83,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 28 |
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 29 |
|
| 30 |
if profile:
|
| 31 |
-
username= f"{profile.username}"
|
| 32 |
print(f"User logged in: {username}")
|
| 33 |
else:
|
| 34 |
print("User not logged in.")
|
|
@@ -38,13 +93,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 38 |
questions_url = f"{api_url}/questions"
|
| 39 |
submit_url = f"{api_url}/submit"
|
| 40 |
|
| 41 |
-
# 1. Instantiate Agent (
|
| 42 |
try:
|
| 43 |
agent = BasicAgent()
|
| 44 |
except Exception as e:
|
| 45 |
print(f"Error instantiating agent: {e}")
|
| 46 |
return f"Error initializing agent: {e}", None
|
| 47 |
-
|
|
|
|
| 48 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 49 |
print(agent_code)
|
| 50 |
|
|
@@ -146,24 +202,18 @@ with gr.Blocks() as demo:
|
|
| 146 |
gr.Markdown(
|
| 147 |
"""
|
| 148 |
**Instructions:**
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 153 |
-
|
| 154 |
---
|
| 155 |
**Disclaimers:**
|
| 156 |
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|
| 157 |
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
|
| 158 |
"""
|
| 159 |
)
|
| 160 |
-
|
| 161 |
gr.LoginButton()
|
| 162 |
-
|
| 163 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 164 |
-
|
| 165 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 166 |
-
# Removed max_rows=10 from DataFrame constructor
|
| 167 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 168 |
|
| 169 |
run_button.click(
|
|
@@ -173,17 +223,15 @@ with gr.Blocks() as demo:
|
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 176 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 177 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 178 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 179 |
-
|
| 180 |
if space_host_startup:
|
| 181 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 182 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 183 |
else:
|
| 184 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 185 |
|
| 186 |
-
if space_id_startup:
|
| 187 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 188 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 189 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
|
@@ -191,6 +239,5 @@ if __name__ == "__main__":
|
|
| 191 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 192 |
|
| 193 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 194 |
-
|
| 195 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 196 |
demo.launch(debug=True, share=False)
|
|
|
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
|
| 7 |
+
# --- Import Smart Agent Libraries ---
|
| 8 |
+
from smolagents import CodeAgent, HfModel, tool
|
| 9 |
+
from duckduckgo_search import DDGS
|
| 10 |
+
|
| 11 |
# --- Constants ---
|
| 12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 13 |
|
| 14 |
+
# --- Custom Secure Search Tool ---
|
| 15 |
+
@tool
|
| 16 |
+
def web_search(query: str) -> str:
|
| 17 |
+
"""Executes a live DuckDuckGo web search to find current information on a topic.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
query: The search query string to look up.
|
| 21 |
+
|
| 22 |
+
Returns:
|
| 23 |
+
A text string summarizing the top web snippets found.
|
| 24 |
+
"""
|
| 25 |
+
try:
|
| 26 |
+
with DDGS() as ddgs:
|
| 27 |
+
results = [r for r in ddgs.text(query, max_results=5)]
|
| 28 |
+
if not results:
|
| 29 |
+
return f"No web search results found for query: '{query}'"
|
| 30 |
+
|
| 31 |
+
summary = []
|
| 32 |
+
for i, result in enumerate(results):
|
| 33 |
+
summary.append(f"[{i+1}] Source: {result.get('href')}\nSnippet: {result.get('body')}\n")
|
| 34 |
+
return "\n".join(summary)
|
| 35 |
+
except Exception as e:
|
| 36 |
+
return f"Search temporary error occurred: {str(e)}"
|
| 37 |
+
|
| 38 |
+
# --- Upgraded Agent Definition ---
|
| 39 |
class BasicAgent:
|
| 40 |
def __init__(self):
|
| 41 |
+
# Using HfModel standard serverless configuration
|
| 42 |
+
self.model = HfModel(
|
| 43 |
+
model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
|
| 44 |
+
timeout=60
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
# Pass the reliable custom web_search tool directly to the loop
|
| 48 |
+
tools_list = [web_search]
|
| 49 |
+
|
| 50 |
+
# Initialize the dynamic code-executing agent engine
|
| 51 |
+
self.agent = CodeAgent(
|
| 52 |
+
model=self.model,
|
| 53 |
+
tools=tools_list,
|
| 54 |
+
max_steps=10,
|
| 55 |
+
verbosity_level=1
|
| 56 |
+
)
|
| 57 |
+
print("Smart Agent customized framework initialized successfully.")
|
| 58 |
+
|
| 59 |
def __call__(self, question: str) -> str:
|
| 60 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 61 |
+
|
| 62 |
+
# Strict prompting forcing exact match short answers for the GAIA benchmark
|
| 63 |
+
system_instruction = (
|
| 64 |
+
f"{question}\n\n"
|
| 65 |
+
"CRITICAL: Utilize the web_search tool if any factual lookup or verification is required. "
|
| 66 |
+
"Provide ONLY the definitive, final answer matching the expected value or data type. "
|
| 67 |
+
"Do not include conversational preamble, markdown formatting labels, or phrases like 'FINAL ANSWER:'."
|
| 68 |
+
)
|
| 69 |
+
try:
|
| 70 |
+
output = self.agent.run(system_instruction)
|
| 71 |
+
return str(output).strip()
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print(f"Processing error: {e}")
|
| 74 |
+
return f"Error processing task: {str(e)}"
|
| 75 |
+
|
| 76 |
|
| 77 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 78 |
"""
|
| 79 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 80 |
and displays the results.
|
|
|
|
| 83 |
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 84 |
|
| 85 |
if profile:
|
| 86 |
+
username = f"{profile.username}"
|
| 87 |
print(f"User logged in: {username}")
|
| 88 |
else:
|
| 89 |
print("User not logged in.")
|
|
|
|
| 93 |
questions_url = f"{api_url}/questions"
|
| 94 |
submit_url = f"{api_url}/submit"
|
| 95 |
|
| 96 |
+
# 1. Instantiate Agent (modified to use your smart agent implementation)
|
| 97 |
try:
|
| 98 |
agent = BasicAgent()
|
| 99 |
except Exception as e:
|
| 100 |
print(f"Error instantiating agent: {e}")
|
| 101 |
return f"Error initializing agent: {e}", None
|
| 102 |
+
|
| 103 |
+
# In the case of an app running as a hugging Face space, this link points toward your codebase
|
| 104 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 105 |
print(agent_code)
|
| 106 |
|
|
|
|
| 202 |
gr.Markdown(
|
| 203 |
"""
|
| 204 |
**Instructions:**
|
| 205 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 206 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 207 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
|
|
|
|
|
|
| 208 |
---
|
| 209 |
**Disclaimers:**
|
| 210 |
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|
| 211 |
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
|
| 212 |
"""
|
| 213 |
)
|
|
|
|
| 214 |
gr.LoginButton()
|
|
|
|
| 215 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
|
|
|
| 216 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
|
| 217 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 218 |
|
| 219 |
run_button.click(
|
|
|
|
| 223 |
|
| 224 |
if __name__ == "__main__":
|
| 225 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
|
|
|
| 226 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 227 |
+
space_id_startup = os.getenv("SPACE_ID")
|
|
|
|
| 228 |
if space_host_startup:
|
| 229 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 230 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 231 |
else:
|
| 232 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 233 |
|
| 234 |
+
if space_id_startup:
|
| 235 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 236 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 237 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
|
|
|
| 239 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 240 |
|
| 241 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
|
|
|
| 242 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 243 |
demo.launch(debug=True, share=False)
|