Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,92 +2,167 @@ import os
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
class BasicAgent:
|
| 12 |
def __init__(self):
|
| 13 |
-
|
| 14 |
self.model_id = "Qwen/Qwen2.5-Coder-32B-Instruct"
|
| 15 |
-
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
def __call__(self, question: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
try:
|
| 26 |
-
# 執行 Agent 並確保回傳結果是字串
|
| 27 |
result = self.agent.run(question)
|
| 28 |
-
return str(result)
|
| 29 |
except Exception as e:
|
| 30 |
-
|
|
|
|
| 31 |
return "I am sorry, I cannot answer this right now."
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
| 38 |
return "Please Login to Hugging Face with the button.", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
api_url = DEFAULT_API_URL
|
| 41 |
questions_url = f"{api_url}/questions"
|
| 42 |
submit_url = f"{api_url}/submit"
|
| 43 |
|
|
|
|
| 44 |
try:
|
| 45 |
agent = BasicAgent()
|
| 46 |
except Exception as e:
|
| 47 |
-
return f"Error initializing agent: {e}", None
|
| 48 |
|
| 49 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 50 |
|
|
|
|
| 51 |
try:
|
| 52 |
-
response = requests.get(questions_url, timeout=
|
|
|
|
| 53 |
questions_data = response.json()
|
| 54 |
-
except
|
| 55 |
-
return f"Error fetching questions: {e}", None
|
|
|
|
|
|
|
| 56 |
|
| 57 |
answers_payload = []
|
| 58 |
results_log = []
|
| 59 |
|
| 60 |
-
|
|
|
|
| 61 |
task_id = item.get("task_id")
|
| 62 |
question_text = item.get("question")
|
|
|
|
|
|
|
|
|
|
| 63 |
try:
|
| 64 |
submitted_answer = agent(question_text)
|
| 65 |
-
answers_payload.append({
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
except Exception as e:
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
try:
|
| 72 |
-
response = requests.post(submit_url, json=submission_data, timeout=
|
|
|
|
| 73 |
result_data = response.json()
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
return status_msg, pd.DataFrame(results_log)
|
| 79 |
|
| 80 |
-
|
|
|
|
|
|
|
| 81 |
gr.Markdown("# Unit 4 Final Project: AI Agent")
|
| 82 |
-
gr.
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
run_button.click(
|
| 88 |
fn=run_and_submit_all,
|
|
|
|
| 89 |
outputs=[status_output, results_table]
|
| 90 |
)
|
| 91 |
|
| 92 |
if __name__ == "__main__":
|
| 93 |
-
demo.launch()
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
# 導入 smolagents 組件
|
| 8 |
+
try:
|
| 9 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool
|
| 10 |
+
except ImportError as e:
|
| 11 |
+
print(f"Warning: smolagents import failed: {e}")
|
| 12 |
+
DuckDuckGoSearchTool = None
|
| 13 |
+
CodeAgent = None
|
| 14 |
|
| 15 |
# --- Constants ---
|
| 16 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 17 |
|
| 18 |
class BasicAgent:
|
| 19 |
def __init__(self):
|
| 20 |
+
"""初始化 Agent,帶有完整的錯誤處理"""
|
| 21 |
self.model_id = "Qwen/Qwen2.5-Coder-32B-Instruct"
|
| 22 |
+
self.agent = None
|
| 23 |
|
| 24 |
+
try:
|
| 25 |
+
if CodeAgent is None or DuckDuckGoSearchTool is None:
|
| 26 |
+
raise ImportError("smolagents not properly installed")
|
| 27 |
+
|
| 28 |
+
# 初始化搜尋工具
|
| 29 |
+
search_tool = DuckDuckGoSearchTool()
|
| 30 |
+
|
| 31 |
+
# 初始化 Agent
|
| 32 |
+
self.agent = CodeAgent(
|
| 33 |
+
tools=[search_tool],
|
| 34 |
+
model=self.model_id,
|
| 35 |
+
add_base_tools=True,
|
| 36 |
+
verbose=False,
|
| 37 |
+
)
|
| 38 |
+
print("✓ Agent initialized successfully.")
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print(f"✗ Agent initialization error: {e}")
|
| 41 |
+
self.agent = None
|
| 42 |
|
| 43 |
def __call__(self, question: str) -> str:
|
| 44 |
+
"""執行 Agent 查詢"""
|
| 45 |
+
if self.agent is None:
|
| 46 |
+
return "Agent not initialized. Please check model loading."
|
| 47 |
+
|
| 48 |
try:
|
|
|
|
| 49 |
result = self.agent.run(question)
|
| 50 |
+
return str(result).strip()
|
| 51 |
except Exception as e:
|
| 52 |
+
error_msg = f"Agent error: {str(e)[:200]}"
|
| 53 |
+
print(error_msg)
|
| 54 |
return "I am sorry, I cannot answer this right now."
|
| 55 |
|
| 56 |
+
|
| 57 |
+
def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
| 58 |
+
"""主要評估和提交函數"""
|
| 59 |
+
|
| 60 |
+
# 檢查登入狀態
|
| 61 |
+
if profile is None:
|
| 62 |
return "Please Login to Hugging Face with the button.", None
|
| 63 |
+
|
| 64 |
+
username = profile.username
|
| 65 |
+
space_id = os.getenv("SPACE_ID")
|
| 66 |
+
|
| 67 |
+
if not space_id:
|
| 68 |
+
return "Error: SPACE_ID environment variable not set.", None
|
| 69 |
|
| 70 |
api_url = DEFAULT_API_URL
|
| 71 |
questions_url = f"{api_url}/questions"
|
| 72 |
submit_url = f"{api_url}/submit"
|
| 73 |
|
| 74 |
+
# 初始化 Agent
|
| 75 |
try:
|
| 76 |
agent = BasicAgent()
|
| 77 |
except Exception as e:
|
| 78 |
+
return f"Error initializing agent: {str(e)[:200]}", None
|
| 79 |
|
| 80 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 81 |
|
| 82 |
+
# 獲取問題
|
| 83 |
try:
|
| 84 |
+
response = requests.get(questions_url, timeout=30)
|
| 85 |
+
response.raise_for_status()
|
| 86 |
questions_data = response.json()
|
| 87 |
+
except requests.exceptions.RequestException as e:
|
| 88 |
+
return f"Error fetching questions: {str(e)[:200]}", None
|
| 89 |
+
except ValueError as e:
|
| 90 |
+
return f"Error parsing questions response: {str(e)[:200]}", None
|
| 91 |
|
| 92 |
answers_payload = []
|
| 93 |
results_log = []
|
| 94 |
|
| 95 |
+
# 逐個回答問題
|
| 96 |
+
for idx, item in enumerate(questions_data):
|
| 97 |
task_id = item.get("task_id")
|
| 98 |
question_text = item.get("question")
|
| 99 |
+
|
| 100 |
+
print(f"Processing question {idx+1}/{len(questions_data)}: {task_id}")
|
| 101 |
+
|
| 102 |
try:
|
| 103 |
submitted_answer = agent(question_text)
|
| 104 |
+
answers_payload.append({
|
| 105 |
+
"task_id": task_id,
|
| 106 |
+
"submitted_answer": submitted_answer
|
| 107 |
+
})
|
| 108 |
+
results_log.append({
|
| 109 |
+
"Task ID": task_id,
|
| 110 |
+
"Question": question_text[:100],
|
| 111 |
+
"Submitted Answer": submitted_answer[:200]
|
| 112 |
+
})
|
| 113 |
except Exception as e:
|
| 114 |
+
error_answer = f"Error: {str(e)[:100]}"
|
| 115 |
+
answers_payload.append({
|
| 116 |
+
"task_id": task_id,
|
| 117 |
+
"submitted_answer": error_answer
|
| 118 |
+
})
|
| 119 |
+
results_log.append({
|
| 120 |
+
"Task ID": task_id,
|
| 121 |
+
"Question": question_text[:100],
|
| 122 |
+
"Submitted Answer": error_answer
|
| 123 |
+
})
|
| 124 |
|
| 125 |
+
# 提交答案
|
| 126 |
+
submission_data = {
|
| 127 |
+
"username": username,
|
| 128 |
+
"agent_code": agent_code,
|
| 129 |
+
"answers": answers_payload
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
try:
|
| 133 |
+
response = requests.post(submit_url, json=submission_data, timeout=120)
|
| 134 |
+
response.raise_for_status()
|
| 135 |
result_data = response.json()
|
| 136 |
+
|
| 137 |
+
score = result_data.get('score', 'N/A')
|
| 138 |
+
correct = result_data.get('correct_count', 0)
|
| 139 |
+
total = result_data.get('total_attempted', 0)
|
| 140 |
+
status_msg = f"Score: {score}% ({correct}/{total} correct)"
|
| 141 |
+
except requests.exceptions.RequestException as e:
|
| 142 |
+
status_msg = f"Submission Failed: {str(e)[:200]}"
|
| 143 |
+
except ValueError as e:
|
| 144 |
+
status_msg = f"Submission response parsing error: {str(e)[:200]}"
|
| 145 |
|
| 146 |
return status_msg, pd.DataFrame(results_log)
|
| 147 |
|
| 148 |
+
|
| 149 |
+
# Gradio UI
|
| 150 |
+
with gr.Blocks(title="Unit 4 Final Assignment") as demo:
|
| 151 |
gr.Markdown("# Unit 4 Final Project: AI Agent")
|
| 152 |
+
gr.Markdown("_Click 'Login with Hugging Face' first, then click 'Run Evaluation & Submit All Answers'_")
|
| 153 |
+
|
| 154 |
+
with gr.Row():
|
| 155 |
+
gr.LoginButton(scale=1)
|
| 156 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers", scale=2, variant="primary")
|
| 157 |
+
|
| 158 |
+
status_output = gr.Textbox(label="Result", lines=3, interactive=False)
|
| 159 |
+
results_table = gr.DataFrame(label="Details", interactive=False)
|
| 160 |
|
| 161 |
run_button.click(
|
| 162 |
fn=run_and_submit_all,
|
| 163 |
+
inputs=[], # 自動取得 profile
|
| 164 |
outputs=[status_output, results_table]
|
| 165 |
)
|
| 166 |
|
| 167 |
if __name__ == "__main__":
|
| 168 |
+
demo.launch(debug=True)
|