Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,32 +3,87 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
# (Keep Constants as is)
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
-
# ---
|
| 12 |
-
|
| 13 |
-
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
-
print("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
-
print(f"Agent received question (first
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
"""
|
| 24 |
-
Fetches all questions, runs the
|
| 25 |
and displays the results.
|
| 26 |
"""
|
| 27 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 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,15 +93,16 @@ 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 =
|
| 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 |
|
| 51 |
# 2. Fetch Questions
|
| 52 |
print(f"Fetching questions from: {questions_url}")
|
|
@@ -72,20 +128,34 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 72 |
# 3. Run your Agent
|
| 73 |
results_log = []
|
| 74 |
answers_payload = []
|
| 75 |
-
print(f"Running
|
| 76 |
-
|
|
|
|
| 77 |
task_id = item.get("task_id")
|
| 78 |
question_text = item.get("question")
|
| 79 |
if not task_id or question_text is None:
|
| 80 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 81 |
continue
|
|
|
|
|
|
|
|
|
|
| 82 |
try:
|
| 83 |
submitted_answer = agent(question_text)
|
| 84 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 85 |
-
results_log.append({
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
except Exception as e:
|
| 87 |
print(f"Error running agent on task {task_id}: {e}")
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
if not answers_payload:
|
| 91 |
print("Agent did not produce any answers to submit.")
|
|
@@ -93,13 +163,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 93 |
|
| 94 |
# 4. Prepare Submission
|
| 95 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 96 |
-
status_update = f"
|
| 97 |
print(status_update)
|
| 98 |
|
| 99 |
# 5. Submit
|
| 100 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 101 |
try:
|
| 102 |
-
response = requests.post(submit_url, json=submission_data, timeout=
|
| 103 |
response.raise_for_status()
|
| 104 |
result_data = response.json()
|
| 105 |
final_status = (
|
|
@@ -142,28 +212,29 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 142 |
|
| 143 |
# --- Build Gradio Interface using Blocks ---
|
| 144 |
with gr.Blocks() as demo:
|
| 145 |
-
gr.Markdown("#
|
| 146 |
gr.Markdown(
|
| 147 |
"""
|
| 148 |
**Instructions:**
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
---
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
| 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=
|
| 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(
|
|
@@ -172,10 +243,12 @@ with gr.Blocks() as demo:
|
|
| 172 |
)
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 176 |
-
|
|
|
|
| 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,14 +256,19 @@ 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")
|
| 190 |
else:
|
| 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
|
| 196 |
demo.launch(debug=True, share=False)
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
+
from smolagents import CodeAgent, HfApiModel
|
| 7 |
+
from smolagents.tools import PythonInterpreterTool, DuckDuckGoSearchTool
|
| 8 |
|
|
|
|
| 9 |
# --- Constants ---
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
|
| 12 |
+
# --- SmolAgents Agent Definition ---
|
| 13 |
+
class SmolAgent:
|
|
|
|
| 14 |
def __init__(self):
|
| 15 |
+
print("SmolAgent initializing...")
|
| 16 |
+
|
| 17 |
+
# 初始化模型 - 使用 HuggingFace API
|
| 18 |
+
# 你需要设置你的 HF token
|
| 19 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 20 |
+
if not hf_token:
|
| 21 |
+
print("Warning: HF_TOKEN not found. Please set your HuggingFace token.")
|
| 22 |
+
|
| 23 |
+
# 使用一个强大的模型,比如 Qwen2.5-72B-Instruct
|
| 24 |
+
self.model = HfApiModel(
|
| 25 |
+
model_id="Qwen/Qwen2.5-72B-Instruct",
|
| 26 |
+
token=hf_token
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# 初始化工具
|
| 30 |
+
self.tools = [
|
| 31 |
+
PythonInterpreterTool(),
|
| 32 |
+
DuckDuckGoSearchTool(),
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
# 创建代理
|
| 36 |
+
self.agent = CodeAgent(
|
| 37 |
+
tools=self.tools,
|
| 38 |
+
model=self.model,
|
| 39 |
+
max_steps=10,
|
| 40 |
+
verbosity_level=2
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
print("SmolAgent initialized successfully.")
|
| 44 |
+
|
| 45 |
def __call__(self, question: str) -> str:
|
| 46 |
+
print(f"Agent received question (first 100 chars): {question[:100]}...")
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
# 构建提示,强调需要精确答案
|
| 50 |
+
enhanced_prompt = f"""
|
| 51 |
+
Please answer the following question accurately and precisely.
|
| 52 |
+
Provide only the final answer without any additional text or explanation.
|
| 53 |
+
If the question requires calculations, use the Python tool to ensure accuracy.
|
| 54 |
+
If you need to search for information, use the search tool.
|
| 55 |
|
| 56 |
+
Question: {question}
|
| 57 |
+
|
| 58 |
+
Important: Your response should contain ONLY the final answer, nothing else.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
# 运行代理
|
| 62 |
+
result = self.agent.run(enhanced_prompt)
|
| 63 |
+
|
| 64 |
+
# 提取最终答案
|
| 65 |
+
if hasattr(result, 'content'):
|
| 66 |
+
answer = result.content.strip()
|
| 67 |
+
else:
|
| 68 |
+
answer = str(result).strip()
|
| 69 |
+
|
| 70 |
+
print(f"Agent returning answer: {answer}")
|
| 71 |
+
return answer
|
| 72 |
+
|
| 73 |
+
except Exception as e:
|
| 74 |
+
print(f"Error in agent execution: {e}")
|
| 75 |
+
return f"Error: {str(e)}"
|
| 76 |
+
|
| 77 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 78 |
"""
|
| 79 |
+
Fetches all questions, runs the SmolAgent on them, submits all answers,
|
| 80 |
and displays the results.
|
| 81 |
"""
|
| 82 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 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
|
| 97 |
try:
|
| 98 |
+
agent = SmolAgent()
|
| 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(f"Agent code link: {agent_code}")
|
| 106 |
|
| 107 |
# 2. Fetch Questions
|
| 108 |
print(f"Fetching questions from: {questions_url}")
|
|
|
|
| 128 |
# 3. Run your Agent
|
| 129 |
results_log = []
|
| 130 |
answers_payload = []
|
| 131 |
+
print(f"Running SmolAgent on {len(questions_data)} questions...")
|
| 132 |
+
|
| 133 |
+
for i, item in enumerate(questions_data):
|
| 134 |
task_id = item.get("task_id")
|
| 135 |
question_text = item.get("question")
|
| 136 |
if not task_id or question_text is None:
|
| 137 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 138 |
continue
|
| 139 |
+
|
| 140 |
+
print(f"Processing question {i+1}/{len(questions_data)} (Task ID: {task_id})")
|
| 141 |
+
|
| 142 |
try:
|
| 143 |
submitted_answer = agent(question_text)
|
| 144 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 145 |
+
results_log.append({
|
| 146 |
+
"Task ID": task_id,
|
| 147 |
+
"Question": question_text[:100] + "..." if len(question_text) > 100 else question_text,
|
| 148 |
+
"Submitted Answer": submitted_answer
|
| 149 |
+
})
|
| 150 |
except Exception as e:
|
| 151 |
print(f"Error running agent on task {task_id}: {e}")
|
| 152 |
+
error_answer = f"AGENT ERROR: {e}"
|
| 153 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": error_answer})
|
| 154 |
+
results_log.append({
|
| 155 |
+
"Task ID": task_id,
|
| 156 |
+
"Question": question_text[:100] + "..." if len(question_text) > 100 else question_text,
|
| 157 |
+
"Submitted Answer": error_answer
|
| 158 |
+
})
|
| 159 |
|
| 160 |
if not answers_payload:
|
| 161 |
print("Agent did not produce any answers to submit.")
|
|
|
|
| 163 |
|
| 164 |
# 4. Prepare Submission
|
| 165 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 166 |
+
status_update = f"SmolAgent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 167 |
print(status_update)
|
| 168 |
|
| 169 |
# 5. Submit
|
| 170 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 171 |
try:
|
| 172 |
+
response = requests.post(submit_url, json=submission_data, timeout=120) # 增加超时时间
|
| 173 |
response.raise_for_status()
|
| 174 |
result_data = response.json()
|
| 175 |
final_status = (
|
|
|
|
| 212 |
|
| 213 |
# --- Build Gradio Interface using Blocks ---
|
| 214 |
with gr.Blocks() as demo:
|
| 215 |
+
gr.Markdown("# SmolAgents GAIA Evaluation Runner")
|
| 216 |
gr.Markdown(
|
| 217 |
"""
|
| 218 |
**Instructions:**
|
| 219 |
+
1. Make sure you have set your HF_TOKEN environment variable in your Space settings
|
| 220 |
+
2. Log in to your Hugging Face account using the button below
|
| 221 |
+
3. Click 'Run Evaluation & Submit All Answers' to start the evaluation
|
| 222 |
+
|
| 223 |
+
**SmolAgent Features:**
|
| 224 |
+
- Uses Qwen2.5-72B-Instruct model for reasoning
|
| 225 |
+
- Python interpreter for calculations
|
| 226 |
+
- DuckDuckGo search for information retrieval
|
| 227 |
+
- Multi-step reasoning capabilities
|
| 228 |
+
|
| 229 |
+
**Note:** This process may take several minutes as the agent processes each question thoroughly.
|
| 230 |
"""
|
| 231 |
)
|
| 232 |
|
| 233 |
gr.LoginButton()
|
| 234 |
|
| 235 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
|
| 236 |
|
| 237 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=8, interactive=False)
|
|
|
|
| 238 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 239 |
|
| 240 |
run_button.click(
|
|
|
|
| 243 |
)
|
| 244 |
|
| 245 |
if __name__ == "__main__":
|
| 246 |
+
print("\n" + "-"*30 + " SmolAgent App Starting " + "-"*30)
|
| 247 |
+
|
| 248 |
+
# Check for required environment variables
|
| 249 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 250 |
+
space_id_startup = os.getenv("SPACE_ID")
|
| 251 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 252 |
|
| 253 |
if space_host_startup:
|
| 254 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 256 |
else:
|
| 257 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 258 |
|
| 259 |
+
if space_id_startup:
|
| 260 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 261 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 262 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 263 |
else:
|
| 264 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 265 |
+
|
| 266 |
+
if hf_token:
|
| 267 |
+
print("✅ HF_TOKEN found.")
|
| 268 |
+
else:
|
| 269 |
+
print("⚠️ HF_TOKEN environment variable not found. Please set it in your Space settings.")
|
| 270 |
|
| 271 |
+
print("-"*(60 + len(" SmolAgent App Starting ")) + "\n")
|
| 272 |
|
| 273 |
+
print("Launching Gradio Interface for SmolAgent GAIA Evaluation...")
|
| 274 |
demo.launch(debug=True, share=False)
|