updatedapp.py
#313
by meghkaa - opened
app.py
CHANGED
|
@@ -3,6 +3,9 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# (Keep Constants as is)
|
| 8 |
# --- Constants ---
|
|
@@ -12,12 +15,64 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
| 12 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
-
print("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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( profile: gr.OAuthProfile | None):
|
| 23 |
"""
|
|
@@ -146,11 +201,9 @@ with gr.Blocks() as demo:
|
|
| 146 |
gr.Markdown(
|
| 147 |
"""
|
| 148 |
**Instructions:**
|
| 149 |
-
|
| 150 |
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 151 |
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 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).
|
|
@@ -163,7 +216,6 @@ with gr.Blocks() as demo:
|
|
| 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,9 +225,8 @@ 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}")
|
|
@@ -183,7 +234,7 @@ if __name__ == "__main__":
|
|
| 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")
|
|
@@ -193,4 +244,4 @@ if __name__ == "__main__":
|
|
| 193 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 194 |
|
| 195 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 196 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
+
import re
|
| 7 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, tool
|
| 8 |
+
from tools.final_answer import FinalAnswerTool
|
| 9 |
|
| 10 |
# (Keep Constants as is)
|
| 11 |
# --- Constants ---
|
|
|
|
| 15 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 16 |
class BasicAgent:
|
| 17 |
def __init__(self):
|
| 18 |
+
print("Smart Agent initialized.")
|
| 19 |
+
|
| 20 |
+
self.final_answer = FinalAnswerTool()
|
| 21 |
+
|
| 22 |
+
self.model = HfApiModel(
|
| 23 |
+
model_id="Qwen/Qwen2.5-7B-Instruct",
|
| 24 |
+
temperature=0,
|
| 25 |
+
max_tokens=2048,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
@tool
|
| 29 |
+
def fetch_file(url: str) -> str:
|
| 30 |
+
"""Download and return text content from a URL."""
|
| 31 |
+
response = requests.get(url, timeout=20)
|
| 32 |
+
response.raise_for_status()
|
| 33 |
+
return response.text
|
| 34 |
+
|
| 35 |
+
@tool
|
| 36 |
+
def calculate(expression: str) -> str:
|
| 37 |
+
"""Safely evaluate a mathematical expression."""
|
| 38 |
+
allowed_chars = "0123456789+-*/(). "
|
| 39 |
+
if not all(c in allowed_chars for c in expression):
|
| 40 |
+
return "Invalid expression"
|
| 41 |
+
try:
|
| 42 |
+
return str(eval(expression))
|
| 43 |
+
except Exception:
|
| 44 |
+
return "Calculation error"
|
| 45 |
+
|
| 46 |
+
self.agent = CodeAgent(
|
| 47 |
+
model=self.model,
|
| 48 |
+
tools=[
|
| 49 |
+
self.final_answer,
|
| 50 |
+
DuckDuckGoSearchTool(),
|
| 51 |
+
fetch_file,
|
| 52 |
+
calculate,
|
| 53 |
+
],
|
| 54 |
+
max_steps=8,
|
| 55 |
+
verbosity_level=0,
|
| 56 |
+
description="You are a precise problem-solving agent. Return ONLY the final answer."
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
def clean_output(self, text: str) -> str:
|
| 60 |
+
text = str(text).strip()
|
| 61 |
+
text = re.sub(r"^Final Answer:\s*", "", text, flags=re.IGNORECASE)
|
| 62 |
+
text = re.sub(r"^Answer:\s*", "", text, flags=re.IGNORECASE)
|
| 63 |
+
text = text.rstrip(".")
|
| 64 |
+
return text.strip()
|
| 65 |
+
|
| 66 |
def __call__(self, question: str) -> str:
|
| 67 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 68 |
+
try:
|
| 69 |
+
result = self.agent.run(question)
|
| 70 |
+
cleaned = self.clean_output(result)
|
| 71 |
+
print(f"Agent returning answer: {cleaned}")
|
| 72 |
+
return cleaned
|
| 73 |
+
except Exception as e:
|
| 74 |
+
print(f"Agent error: {e}")
|
| 75 |
+
return "Error"
|
| 76 |
|
| 77 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 78 |
"""
|
|
|
|
| 201 |
gr.Markdown(
|
| 202 |
"""
|
| 203 |
**Instructions:**
|
|
|
|
| 204 |
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 205 |
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 206 |
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
|
|
|
| 207 |
---
|
| 208 |
**Disclaimers:**
|
| 209 |
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).
|
|
|
|
| 216 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 217 |
|
| 218 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
|
| 219 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 220 |
|
| 221 |
run_button.click(
|
|
|
|
| 225 |
|
| 226 |
if __name__ == "__main__":
|
| 227 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
|
|
|
| 228 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 229 |
+
space_id_startup = os.getenv("SPACE_ID")
|
| 230 |
|
| 231 |
if space_host_startup:
|
| 232 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 234 |
else:
|
| 235 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 236 |
|
| 237 |
+
if space_id_startup:
|
| 238 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 239 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 240 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
|
|
|
| 244 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 245 |
|
| 246 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 247 |
+
demo.launch(debug=True, share=False)
|