Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,77 +3,80 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
| 6 |
from smolagents import CodeAgent, OpenAIServerModel, DuckDuckGoSearchTool, VisitWebpageTool
|
| 7 |
|
| 8 |
-
# (Keep Constants as is)
|
| 9 |
# --- Constants ---
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# --- Basic Agent Definition ---
|
| 13 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 14 |
class BasicAgent:
|
| 15 |
def __init__(self):
|
| 16 |
print("BasicAgent initialized.")
|
| 17 |
-
#
|
| 18 |
search_tool = DuckDuckGoSearchTool()
|
| 19 |
visit_tool = VisitWebpageTool()
|
| 20 |
|
| 21 |
-
#
|
|
|
|
| 22 |
self.model = OpenAIServerModel(
|
| 23 |
-
model_id="
|
| 24 |
api_base="https://openrouter.ai/api/v1",
|
| 25 |
api_key=os.environ.get("OPENROUTER_API_KEY")
|
| 26 |
)
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
#set up CodeAgent
|
| 30 |
self.agent = CodeAgent(
|
| 31 |
-
tools
|
| 32 |
-
model
|
| 33 |
-
add_base_tools
|
| 34 |
)
|
| 35 |
|
| 36 |
-
def __call__(self, question: str) -> str:
|
| 37 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
try:
|
| 39 |
-
|
| 40 |
-
answer = self.agent.run(question)
|
| 41 |
-
|
| 42 |
print(f"Agent returning answer: {answer}")
|
| 43 |
-
return str(answer)
|
| 44 |
except Exception as e:
|
| 45 |
print(f"Agent encountered an error: {e}")
|
| 46 |
return f"Error: {e}"
|
| 47 |
|
| 48 |
-
def run_and_submit_all(
|
| 49 |
"""
|
| 50 |
-
Fetches all questions,
|
| 51 |
-
and displays the results.
|
| 52 |
"""
|
| 53 |
-
|
| 54 |
-
space_id = os.getenv("SPACE_ID", "Imnotchis/Final_Assignment_Template") # Get the SPACE_ID for sending link to the code
|
| 55 |
-
|
| 56 |
if profile:
|
| 57 |
-
username= f"{profile.username}"
|
| 58 |
print(f"User logged in: {username}")
|
| 59 |
else:
|
| 60 |
print("User not logged in.")
|
| 61 |
return "Please Login to Hugging Face with the button.", None
|
| 62 |
-
|
| 63 |
api_url = DEFAULT_API_URL
|
| 64 |
questions_url = f"{api_url}/questions"
|
| 65 |
submit_url = f"{api_url}/submit"
|
| 66 |
-
|
| 67 |
-
# 1. Instantiate Agent
|
| 68 |
try:
|
| 69 |
agent = BasicAgent()
|
| 70 |
except Exception as e:
|
| 71 |
print(f"Error instantiating agent: {e}")
|
| 72 |
return f"Error initializing agent: {e}", None
|
| 73 |
-
|
| 74 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 75 |
-
print(agent_code)
|
| 76 |
-
|
| 77 |
# 2. Fetch Questions
|
| 78 |
print(f"Fetching questions from: {questions_url}")
|
| 79 |
try:
|
|
@@ -84,17 +87,10 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 84 |
print("Fetched questions list is empty.")
|
| 85 |
return "Fetched questions list is empty or invalid format.", None
|
| 86 |
print(f"Fetched {len(questions_data)} questions.")
|
| 87 |
-
except
|
| 88 |
print(f"Error fetching questions: {e}")
|
| 89 |
return f"Error fetching questions: {e}", None
|
| 90 |
-
|
| 91 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 92 |
-
print(f"Response text: {response.text[:500]}")
|
| 93 |
-
return f"Error decoding server response for questions: {e}", None
|
| 94 |
-
except Exception as e:
|
| 95 |
-
print(f"An unexpected error occurred fetching questions: {e}")
|
| 96 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 97 |
-
|
| 98 |
# 3. Run your Agent
|
| 99 |
results_log = []
|
| 100 |
answers_payload = []
|
|
@@ -102,26 +98,58 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 102 |
for item in questions_data:
|
| 103 |
task_id = item.get("task_id")
|
| 104 |
question_text = item.get("question")
|
|
|
|
|
|
|
| 105 |
if not task_id or question_text is None:
|
| 106 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 107 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
try:
|
| 109 |
-
submitted_answer = agent(question_text)
|
| 110 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 111 |
-
results_log.append({
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
except Exception as e:
|
| 113 |
print(f"Error running agent on task {task_id}: {e}")
|
| 114 |
-
results_log.append({
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
if not answers_payload:
|
| 117 |
print("Agent did not produce any answers to submit.")
|
| 118 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 119 |
-
|
| 120 |
# 4. Prepare Submission
|
| 121 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 122 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 123 |
print(status_update)
|
| 124 |
-
|
| 125 |
# 5. Submit
|
| 126 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 127 |
try:
|
|
@@ -143,7 +171,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 143 |
try:
|
| 144 |
error_json = e.response.json()
|
| 145 |
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 146 |
-
except
|
| 147 |
error_detail += f" Response: {e.response.text[:500]}"
|
| 148 |
status_message = f"Submission Failed: {error_detail}"
|
| 149 |
print(status_message)
|
|
@@ -165,33 +193,24 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 165 |
results_df = pd.DataFrame(results_log)
|
| 166 |
return status_message, results_df
|
| 167 |
|
| 168 |
-
|
| 169 |
# --- Build Gradio Interface using Blocks ---
|
| 170 |
with gr.Blocks() as demo:
|
| 171 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 172 |
gr.Markdown(
|
| 173 |
"""
|
| 174 |
**Instructions:**
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 179 |
-
|
| 180 |
---
|
| 181 |
**Disclaimers:**
|
| 182 |
-
Once clicking on the
|
| 183 |
-
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.
|
| 184 |
"""
|
| 185 |
)
|
| 186 |
-
|
| 187 |
gr.LoginButton()
|
| 188 |
-
|
| 189 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 190 |
-
|
| 191 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 192 |
-
# Removed max_rows=10 from DataFrame constructor
|
| 193 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 194 |
-
|
| 195 |
run_button.click(
|
| 196 |
fn=run_and_submit_all,
|
| 197 |
outputs=[status_output, results_table]
|
|
@@ -199,24 +218,18 @@ with gr.Blocks() as demo:
|
|
| 199 |
|
| 200 |
if __name__ == "__main__":
|
| 201 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 202 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 203 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 204 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 205 |
-
|
| 206 |
if space_host_startup:
|
| 207 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 208 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 209 |
else:
|
| 210 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 211 |
-
|
| 212 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 213 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 214 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 215 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 216 |
else:
|
| 217 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 218 |
-
|
| 219 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 220 |
-
|
| 221 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 222 |
demo.launch(debug=True, share=True)
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
+
from pathlib import Path
|
| 7 |
from smolagents import CodeAgent, OpenAIServerModel, DuckDuckGoSearchTool, VisitWebpageTool
|
| 8 |
|
|
|
|
| 9 |
# --- Constants ---
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
+
DOWNLOADS_DIR = Path("./tmp_downloads")
|
| 12 |
+
DOWNLOADS_DIR.mkdir(parents=True, exist_ok=True)
|
| 13 |
|
| 14 |
# --- Basic Agent Definition ---
|
|
|
|
| 15 |
class BasicAgent:
|
| 16 |
def __init__(self):
|
| 17 |
print("BasicAgent initialized.")
|
| 18 |
+
# Setup tools
|
| 19 |
search_tool = DuckDuckGoSearchTool()
|
| 20 |
visit_tool = VisitWebpageTool()
|
| 21 |
|
| 22 |
+
# Setup LLM via OpenRouter
|
| 23 |
+
# Gợi ý model chuyên code & suy luận: "qwen/qwen-2.5-coder-32b-instruct" hoặc "anthropic/claude-3.5-sonnet"
|
| 24 |
self.model = OpenAIServerModel(
|
| 25 |
+
model_id="qwen/qwen-2.5-coder-32b-instruct",
|
| 26 |
api_base="https://openrouter.ai/api/v1",
|
| 27 |
api_key=os.environ.get("OPENROUTER_API_KEY")
|
| 28 |
)
|
| 29 |
+
|
| 30 |
+
# Setup CodeAgent
|
|
|
|
| 31 |
self.agent = CodeAgent(
|
| 32 |
+
tools=[search_tool, visit_tool],
|
| 33 |
+
model=self.model,
|
| 34 |
+
add_base_tools=True
|
| 35 |
)
|
| 36 |
|
| 37 |
+
def __call__(self, question: str, file_path: str | None = None) -> str:
|
| 38 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 39 |
+
|
| 40 |
+
# Bổ sung chỉ dẫn về file vào prompt để agent biết dùng Python tools xử lý file
|
| 41 |
+
prompt = question
|
| 42 |
+
if file_path and os.path.exists(file_path):
|
| 43 |
+
prompt += f"\n\n[LƯU Ý QUAN TRỌNG: Câu hỏi này có đính kèm một file dữ liệu. File đã được tải về máy tại đường dẫn: '{file_path}'. Hãy sử dụng code Python và các thư viện như pandas, openpyxl, PIL,... để đọc và phân tích file này nhằm tìm ra câu trả lời chính xác.]"
|
| 44 |
+
|
| 45 |
try:
|
| 46 |
+
answer = self.agent.run(prompt)
|
|
|
|
|
|
|
| 47 |
print(f"Agent returning answer: {answer}")
|
| 48 |
+
return str(answer).strip()
|
| 49 |
except Exception as e:
|
| 50 |
print(f"Agent encountered an error: {e}")
|
| 51 |
return f"Error: {e}"
|
| 52 |
|
| 53 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 54 |
"""
|
| 55 |
+
Fetches all questions, downloads attachments if present, runs the BasicAgent,
|
| 56 |
+
submits all answers, and displays the results.
|
| 57 |
"""
|
| 58 |
+
space_id = os.getenv("SPACE_ID", "Imnotchis/Final_Assignment_Template")
|
|
|
|
|
|
|
| 59 |
if profile:
|
| 60 |
+
username = f"{profile.username}"
|
| 61 |
print(f"User logged in: {username}")
|
| 62 |
else:
|
| 63 |
print("User not logged in.")
|
| 64 |
return "Please Login to Hugging Face with the button.", None
|
| 65 |
+
|
| 66 |
api_url = DEFAULT_API_URL
|
| 67 |
questions_url = f"{api_url}/questions"
|
| 68 |
submit_url = f"{api_url}/submit"
|
| 69 |
+
|
| 70 |
+
# 1. Instantiate Agent
|
| 71 |
try:
|
| 72 |
agent = BasicAgent()
|
| 73 |
except Exception as e:
|
| 74 |
print(f"Error instantiating agent: {e}")
|
| 75 |
return f"Error initializing agent: {e}", None
|
| 76 |
+
|
| 77 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 78 |
+
print(f"Agent code URL: {agent_code}")
|
| 79 |
+
|
| 80 |
# 2. Fetch Questions
|
| 81 |
print(f"Fetching questions from: {questions_url}")
|
| 82 |
try:
|
|
|
|
| 87 |
print("Fetched questions list is empty.")
|
| 88 |
return "Fetched questions list is empty or invalid format.", None
|
| 89 |
print(f"Fetched {len(questions_data)} questions.")
|
| 90 |
+
except Exception as e:
|
| 91 |
print(f"Error fetching questions: {e}")
|
| 92 |
return f"Error fetching questions: {e}", None
|
| 93 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
# 3. Run your Agent
|
| 95 |
results_log = []
|
| 96 |
answers_payload = []
|
|
|
|
| 98 |
for item in questions_data:
|
| 99 |
task_id = item.get("task_id")
|
| 100 |
question_text = item.get("question")
|
| 101 |
+
file_name = item.get("file_name")
|
| 102 |
+
|
| 103 |
if not task_id or question_text is None:
|
| 104 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 105 |
continue
|
| 106 |
+
|
| 107 |
+
# XỬ LÝ TẢI FILE ĐÍNH KÈM (Cải tiến giúp ăn trọn điểm các câu hỏi multimodal/Excel)
|
| 108 |
+
local_file_path = None
|
| 109 |
+
if file_name and str(file_name).strip() and str(file_name) != "None":
|
| 110 |
+
file_url = f"{api_url}/files/{task_id}"
|
| 111 |
+
local_file_path = str(DOWNLOADS_DIR / file_name)
|
| 112 |
+
print(f"Downloading attachment '{file_name}' from {file_url}...")
|
| 113 |
+
try:
|
| 114 |
+
file_resp = requests.get(file_url, timeout=30)
|
| 115 |
+
if file_resp.status_code == 200:
|
| 116 |
+
with open(local_file_path, "wb") as f:
|
| 117 |
+
f.write(file_resp.content)
|
| 118 |
+
print(f"✅ Downloaded to {local_file_path}")
|
| 119 |
+
else:
|
| 120 |
+
print(f"⚠️ Failed to download file (Status {file_resp.status_code})")
|
| 121 |
+
local_file_path = None
|
| 122 |
+
except Exception as e:
|
| 123 |
+
print(f"⚠️ Error downloading attachment: {e}")
|
| 124 |
+
local_file_path = None
|
| 125 |
+
|
| 126 |
try:
|
| 127 |
+
submitted_answer = agent(question_text, file_path=local_file_path)
|
| 128 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 129 |
+
results_log.append({
|
| 130 |
+
"Task ID": task_id,
|
| 131 |
+
"Question": question_text,
|
| 132 |
+
"Attachment": file_name if file_name else "None",
|
| 133 |
+
"Submitted Answer": submitted_answer
|
| 134 |
+
})
|
| 135 |
except Exception as e:
|
| 136 |
print(f"Error running agent on task {task_id}: {e}")
|
| 137 |
+
results_log.append({
|
| 138 |
+
"Task ID": task_id,
|
| 139 |
+
"Question": question_text,
|
| 140 |
+
"Attachment": file_name if file_name else "None",
|
| 141 |
+
"Submitted Answer": f"AGENT ERROR: {e}"
|
| 142 |
+
})
|
| 143 |
+
|
| 144 |
if not answers_payload:
|
| 145 |
print("Agent did not produce any answers to submit.")
|
| 146 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 147 |
+
|
| 148 |
# 4. Prepare Submission
|
| 149 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 150 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 151 |
print(status_update)
|
| 152 |
+
|
| 153 |
# 5. Submit
|
| 154 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 155 |
try:
|
|
|
|
| 171 |
try:
|
| 172 |
error_json = e.response.json()
|
| 173 |
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 174 |
+
except Exception:
|
| 175 |
error_detail += f" Response: {e.response.text[:500]}"
|
| 176 |
status_message = f"Submission Failed: {error_detail}"
|
| 177 |
print(status_message)
|
|
|
|
| 193 |
results_df = pd.DataFrame(results_log)
|
| 194 |
return status_message, results_df
|
| 195 |
|
|
|
|
| 196 |
# --- Build Gradio Interface using Blocks ---
|
| 197 |
with gr.Blocks() as demo:
|
| 198 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 199 |
gr.Markdown(
|
| 200 |
"""
|
| 201 |
**Instructions:**
|
| 202 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc...
|
| 203 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 204 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
|
|
|
|
|
|
| 205 |
---
|
| 206 |
**Disclaimers:**
|
| 207 |
+
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).
|
|
|
|
| 208 |
"""
|
| 209 |
)
|
|
|
|
| 210 |
gr.LoginButton()
|
|
|
|
| 211 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
|
|
|
| 212 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
|
| 213 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
|
|
|
| 214 |
run_button.click(
|
| 215 |
fn=run_and_submit_all,
|
| 216 |
outputs=[status_output, results_table]
|
|
|
|
| 218 |
|
| 219 |
if __name__ == "__main__":
|
| 220 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
|
|
|
| 221 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 222 |
+
space_id_startup = os.getenv("SPACE_ID")
|
|
|
|
| 223 |
if space_host_startup:
|
| 224 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 225 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 226 |
else:
|
| 227 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 228 |
+
if space_id_startup:
|
|
|
|
| 229 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 230 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
|
|
|
| 231 |
else:
|
| 232 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
|
|
|
| 233 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
|
|
|
| 234 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 235 |
demo.launch(debug=True, share=True)
|