Update app.py
Browse files
app.py
CHANGED
|
@@ -2,35 +2,72 @@ import os
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
-
from smolagents import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
class BasicAgent:
|
| 10 |
-
def __init__(self):
|
| 11 |
print("BasicAgent initialized.")
|
|
|
|
| 12 |
model = InferenceClientModel(
|
| 13 |
-
model_id="
|
| 14 |
token=os.environ.get("HF_TOKEN"),
|
| 15 |
-
provider="nebius"
|
| 16 |
)
|
| 17 |
self.agent = CodeAgent(
|
| 18 |
-
tools=[VisitWebpageTool()],
|
| 19 |
model=model,
|
| 20 |
max_steps=10,
|
| 21 |
-
additional_authorized_imports=["time", "numpy", "pandas", "json", "re"]
|
| 22 |
)
|
| 23 |
|
| 24 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
try:
|
| 30 |
answer = self.agent.run(prompt)
|
| 31 |
return str(answer).strip()
|
| 32 |
except Exception as e:
|
| 33 |
-
|
|
|
|
|
|
|
| 34 |
|
| 35 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 36 |
space_id = os.getenv("SPACE_ID")
|
|
@@ -47,7 +84,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 47 |
submit_url = f"{api_url}/submit"
|
| 48 |
|
| 49 |
try:
|
| 50 |
-
agent = BasicAgent()
|
| 51 |
except Exception as e:
|
| 52 |
print(f"Error instantiating agent: {e}")
|
| 53 |
return f"Error initializing agent: {e}", None
|
|
@@ -81,7 +118,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 81 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 82 |
continue
|
| 83 |
try:
|
| 84 |
-
submitted_answer = agent(question_text)
|
| 85 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 86 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 87 |
except Exception as e:
|
|
@@ -95,7 +132,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 95 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 96 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 97 |
try:
|
| 98 |
-
response = requests.post(submit_url, json=submission_data, timeout=
|
| 99 |
response.raise_for_status()
|
| 100 |
result_data = response.json()
|
| 101 |
final_status = (
|
|
@@ -112,14 +149,15 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 112 |
print(status_message)
|
| 113 |
return status_message, pd.DataFrame(results_log)
|
| 114 |
|
|
|
|
| 115 |
with gr.Blocks() as demo:
|
| 116 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 117 |
gr.Markdown(
|
| 118 |
"""
|
| 119 |
**Instructions:**
|
| 120 |
-
1.
|
| 121 |
2. Log in to your Hugging Face account using the button below.
|
| 122 |
-
3. Click 'Run Evaluation & Submit All Answers'
|
| 123 |
"""
|
| 124 |
)
|
| 125 |
gr.LoginButton()
|
|
@@ -129,5 +167,5 @@ with gr.Blocks() as demo:
|
|
| 129 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 130 |
|
| 131 |
if __name__ == "__main__":
|
| 132 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 133 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
+
from smolagents import (
|
| 6 |
+
CodeAgent,
|
| 7 |
+
InferenceClientModel,
|
| 8 |
+
VisitWebpageTool,
|
| 9 |
+
DuckDuckGoSearchTool,
|
| 10 |
+
)
|
| 11 |
|
| 12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 13 |
|
| 14 |
+
GAIA_SYSTEM_PROMPT = """You are a precise research agent answering benchmark questions.
|
| 15 |
+
Use the search and webpage tools to find facts before answering.
|
| 16 |
+
Your FINAL answer must be EXACT and minimal — a number, a word, or a short phrase.
|
| 17 |
+
Rules for the final answer:
|
| 18 |
+
- No explanations, no full sentences, no trailing period.
|
| 19 |
+
- Numbers: digits only, no thousands separators, no units unless explicitly asked.
|
| 20 |
+
- Strings: no leading articles (a/an/the), no abbreviations unless asked.
|
| 21 |
+
- If asked for a comma-separated list, output "a, b, c" with single spaces.
|
| 22 |
+
Return the answer via final_answer()."""
|
| 23 |
+
|
| 24 |
+
|
| 25 |
class BasicAgent:
|
| 26 |
+
def __init__(self, api_url: str):
|
| 27 |
print("BasicAgent initialized.")
|
| 28 |
+
self.api_url = api_url
|
| 29 |
model = InferenceClientModel(
|
| 30 |
+
model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
|
| 31 |
token=os.environ.get("HF_TOKEN"),
|
| 32 |
+
provider="nebius",
|
| 33 |
)
|
| 34 |
self.agent = CodeAgent(
|
| 35 |
+
tools=[DuckDuckGoSearchTool(), VisitWebpageTool()],
|
| 36 |
model=model,
|
| 37 |
max_steps=10,
|
| 38 |
+
additional_authorized_imports=["time", "numpy", "pandas", "json", "re", "math"],
|
| 39 |
)
|
| 40 |
|
| 41 |
+
def _fetch_file(self, task_id: str) -> str:
|
| 42 |
+
"""Download an attached file for the task, if any. Returns a local path or ''."""
|
| 43 |
+
try:
|
| 44 |
+
r = requests.get(f"{self.api_url}/files/{task_id}", timeout=30)
|
| 45 |
+
if r.status_code != 200 or not r.content:
|
| 46 |
+
return ""
|
| 47 |
+
path = f"/tmp/{task_id}"
|
| 48 |
+
with open(path, "wb") as f:
|
| 49 |
+
f.write(r.content)
|
| 50 |
+
return path
|
| 51 |
+
except requests.exceptions.RequestException:
|
| 52 |
+
return ""
|
| 53 |
+
|
| 54 |
+
def __call__(self, question: str, task_id: str = "") -> str:
|
| 55 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 56 |
+
file_path = self._fetch_file(task_id) if task_id else ""
|
| 57 |
+
file_note = (
|
| 58 |
+
f"\nAn attached file for this task is saved locally at: {file_path}\n"
|
| 59 |
+
f"Read it from disk if the question refers to it."
|
| 60 |
+
if file_path
|
| 61 |
+
else ""
|
| 62 |
+
)
|
| 63 |
+
prompt = f"{GAIA_SYSTEM_PROMPT}\n\nQuestion: {question}{file_note}"
|
| 64 |
try:
|
| 65 |
answer = self.agent.run(prompt)
|
| 66 |
return str(answer).strip()
|
| 67 |
except Exception as e:
|
| 68 |
+
print(f"Agent error: {e}")
|
| 69 |
+
return "" # submit empty rather than the error text
|
| 70 |
+
|
| 71 |
|
| 72 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 73 |
space_id = os.getenv("SPACE_ID")
|
|
|
|
| 84 |
submit_url = f"{api_url}/submit"
|
| 85 |
|
| 86 |
try:
|
| 87 |
+
agent = BasicAgent(api_url)
|
| 88 |
except Exception as e:
|
| 89 |
print(f"Error instantiating agent: {e}")
|
| 90 |
return f"Error initializing agent: {e}", None
|
|
|
|
| 118 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 119 |
continue
|
| 120 |
try:
|
| 121 |
+
submitted_answer = agent(question_text, task_id)
|
| 122 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 123 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 124 |
except Exception as e:
|
|
|
|
| 132 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 133 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 134 |
try:
|
| 135 |
+
response = requests.post(submit_url, json=submission_data, timeout=120)
|
| 136 |
response.raise_for_status()
|
| 137 |
result_data = response.json()
|
| 138 |
final_status = (
|
|
|
|
| 149 |
print(status_message)
|
| 150 |
return status_message, pd.DataFrame(results_log)
|
| 151 |
|
| 152 |
+
|
| 153 |
with gr.Blocks() as demo:
|
| 154 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 155 |
gr.Markdown(
|
| 156 |
"""
|
| 157 |
**Instructions:**
|
| 158 |
+
1. Clone this space and modify the agent logic / tools as needed.
|
| 159 |
2. Log in to your Hugging Face account using the button below.
|
| 160 |
+
3. Click 'Run Evaluation & Submit All Answers'.
|
| 161 |
"""
|
| 162 |
)
|
| 163 |
gr.LoginButton()
|
|
|
|
| 167 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 168 |
|
| 169 |
if __name__ == "__main__":
|
| 170 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
| 171 |
+
demo.launch(debug=True, share=False)
|