Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,60 +4,72 @@ 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 |
-
"""
|
| 21 |
-
self.
|
| 22 |
-
self.
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 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 |
-
"""
|
| 45 |
if self.agent is None:
|
| 46 |
-
return "
|
| 47 |
|
| 48 |
try:
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
except Exception as e:
|
| 52 |
-
|
| 53 |
-
|
| 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 |
|
|
@@ -65,13 +77,12 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
| 65 |
space_id = os.getenv("SPACE_ID")
|
| 66 |
|
| 67 |
if not space_id:
|
| 68 |
-
return "Error: SPACE_ID
|
| 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:
|
|
@@ -79,25 +90,21 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = 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
|
| 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"
|
| 101 |
|
| 102 |
try:
|
| 103 |
submitted_answer = agent(question_text)
|
|
@@ -107,8 +114,8 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
| 107 |
})
|
| 108 |
results_log.append({
|
| 109 |
"Task ID": task_id,
|
| 110 |
-
"Question": question_text[:
|
| 111 |
-
"
|
| 112 |
})
|
| 113 |
except Exception as e:
|
| 114 |
error_answer = f"Error: {str(e)[:100]}"
|
|
@@ -118,11 +125,10 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
| 118 |
})
|
| 119 |
results_log.append({
|
| 120 |
"Task ID": task_id,
|
| 121 |
-
"Question": question_text[:
|
| 122 |
-
"
|
| 123 |
})
|
| 124 |
|
| 125 |
-
# 提交答案
|
| 126 |
submission_data = {
|
| 127 |
"username": username,
|
| 128 |
"agent_code": agent_code,
|
|
@@ -138,10 +144,8 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
| 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
|
| 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 |
|
|
@@ -149,7 +153,7 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
| 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
|
| 153 |
|
| 154 |
with gr.Row():
|
| 155 |
gr.LoginButton(scale=1)
|
|
@@ -160,7 +164,7 @@ with gr.Blocks(title="Unit 4 Final Assignment") as demo:
|
|
| 160 |
|
| 161 |
run_button.click(
|
| 162 |
fn=run_and_submit_all,
|
| 163 |
-
inputs=[],
|
| 164 |
outputs=[status_output, results_table]
|
| 165 |
)
|
| 166 |
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
from typing import Optional
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
# --- Constants ---
|
| 8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
+
HF_API_URL = "https://api-inference.huggingface.co/models"
|
| 10 |
|
| 11 |
class BasicAgent:
|
| 12 |
def __init__(self):
|
| 13 |
+
"""用 HuggingFace Inference API(不佔用本地記憶體)"""
|
| 14 |
+
self.hf_token = os.getenv("HF_TOKEN")
|
| 15 |
+
self.model_name = "mistralai/Mistral-7B-Instruct-v0.1"
|
| 16 |
|
| 17 |
+
if not self.hf_token:
|
| 18 |
+
print("✗ HF_TOKEN not found in Secrets")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
self.agent = None
|
| 20 |
+
return
|
| 21 |
+
|
| 22 |
+
self.agent_url = f"{HF_API_URL}/{self.model_name}"
|
| 23 |
+
print("✓ Agent initialized (using HF Inference API)")
|
| 24 |
|
| 25 |
def __call__(self, question: str) -> str:
|
| 26 |
+
"""透過 API 呼叫模型"""
|
| 27 |
if self.agent is None:
|
| 28 |
+
return "HF_TOKEN not configured. Add it to Secrets."
|
| 29 |
|
| 30 |
try:
|
| 31 |
+
headers = {"Authorization": f"Bearer {self.hf_token}"}
|
| 32 |
+
|
| 33 |
+
payload = {
|
| 34 |
+
"inputs": question,
|
| 35 |
+
"parameters": {
|
| 36 |
+
"max_new_tokens": 256,
|
| 37 |
+
"temperature": 0.7,
|
| 38 |
+
"top_p": 0.9
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
response = requests.post(
|
| 43 |
+
self.agent_url,
|
| 44 |
+
headers=headers,
|
| 45 |
+
json=payload,
|
| 46 |
+
timeout=60
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
if response.status_code != 200:
|
| 50 |
+
return f"API error: {response.status_code}"
|
| 51 |
+
|
| 52 |
+
result = response.json()
|
| 53 |
+
|
| 54 |
+
# 解析回應
|
| 55 |
+
if isinstance(result, list) and len(result) > 0:
|
| 56 |
+
answer = result[0].get("generated_text", "")
|
| 57 |
+
# 去除問題部分
|
| 58 |
+
answer = answer.replace(question, "").strip()
|
| 59 |
+
return answer[:1000] if answer else "No answer"
|
| 60 |
+
|
| 61 |
+
return "Invalid API response"
|
| 62 |
+
|
| 63 |
+
except requests.exceptions.Timeout:
|
| 64 |
+
return "API request timeout"
|
| 65 |
except Exception as e:
|
| 66 |
+
print(f"Error: {e}")
|
| 67 |
+
return f"Error: {str(e)[:200]}"
|
|
|
|
| 68 |
|
| 69 |
|
| 70 |
def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
| 71 |
"""主要評估和提交函數"""
|
| 72 |
|
|
|
|
| 73 |
if profile is None:
|
| 74 |
return "Please Login to Hugging Face with the button.", None
|
| 75 |
|
|
|
|
| 77 |
space_id = os.getenv("SPACE_ID")
|
| 78 |
|
| 79 |
if not space_id:
|
| 80 |
+
return "Error: SPACE_ID not set.", None
|
| 81 |
|
| 82 |
api_url = DEFAULT_API_URL
|
| 83 |
questions_url = f"{api_url}/questions"
|
| 84 |
submit_url = f"{api_url}/submit"
|
| 85 |
|
|
|
|
| 86 |
try:
|
| 87 |
agent = BasicAgent()
|
| 88 |
except Exception as e:
|
|
|
|
| 90 |
|
| 91 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 92 |
|
|
|
|
| 93 |
try:
|
| 94 |
response = requests.get(questions_url, timeout=30)
|
| 95 |
response.raise_for_status()
|
| 96 |
questions_data = response.json()
|
| 97 |
+
except Exception as e:
|
| 98 |
return f"Error fetching questions: {str(e)[:200]}", None
|
|
|
|
|
|
|
| 99 |
|
| 100 |
answers_payload = []
|
| 101 |
results_log = []
|
| 102 |
|
|
|
|
| 103 |
for idx, item in enumerate(questions_data):
|
| 104 |
task_id = item.get("task_id")
|
| 105 |
question_text = item.get("question")
|
| 106 |
|
| 107 |
+
print(f"[{idx+1}/{len(questions_data)}] Processing: {task_id}")
|
| 108 |
|
| 109 |
try:
|
| 110 |
submitted_answer = agent(question_text)
|
|
|
|
| 114 |
})
|
| 115 |
results_log.append({
|
| 116 |
"Task ID": task_id,
|
| 117 |
+
"Question": question_text[:80],
|
| 118 |
+
"Answer": submitted_answer[:150]
|
| 119 |
})
|
| 120 |
except Exception as e:
|
| 121 |
error_answer = f"Error: {str(e)[:100]}"
|
|
|
|
| 125 |
})
|
| 126 |
results_log.append({
|
| 127 |
"Task ID": task_id,
|
| 128 |
+
"Question": question_text[:80],
|
| 129 |
+
"Answer": error_answer
|
| 130 |
})
|
| 131 |
|
|
|
|
| 132 |
submission_data = {
|
| 133 |
"username": username,
|
| 134 |
"agent_code": agent_code,
|
|
|
|
| 144 |
correct = result_data.get('correct_count', 0)
|
| 145 |
total = result_data.get('total_attempted', 0)
|
| 146 |
status_msg = f"Score: {score}% ({correct}/{total} correct)"
|
| 147 |
+
except Exception as e:
|
| 148 |
status_msg = f"Submission Failed: {str(e)[:200]}"
|
|
|
|
|
|
|
| 149 |
|
| 150 |
return status_msg, pd.DataFrame(results_log)
|
| 151 |
|
|
|
|
| 153 |
# Gradio UI
|
| 154 |
with gr.Blocks(title="Unit 4 Final Assignment") as demo:
|
| 155 |
gr.Markdown("# Unit 4 Final Project: AI Agent")
|
| 156 |
+
gr.Markdown("_Click 'Login with Hugging Face' first, then 'Run Evaluation & Submit All Answers'_")
|
| 157 |
|
| 158 |
with gr.Row():
|
| 159 |
gr.LoginButton(scale=1)
|
|
|
|
| 164 |
|
| 165 |
run_button.click(
|
| 166 |
fn=run_and_submit_all,
|
| 167 |
+
inputs=[],
|
| 168 |
outputs=[status_output, results_table]
|
| 169 |
)
|
| 170 |
|