Update app.py
Browse files
app.py
CHANGED
|
@@ -1,63 +1,75 @@
|
|
| 1 |
import os
|
|
|
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
|
| 6 |
-
# ---
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
from smolagents import CodeAgent, DuckDuckGoSearchTool
|
| 10 |
-
try:
|
| 11 |
-
from smolagents import HfApiModel
|
| 12 |
-
ModelClass = HfApiModel
|
| 13 |
-
except ImportError:
|
| 14 |
-
print("HfApiModel not found, using LiteLLMModel fallback.")
|
| 15 |
-
from smolagents import LiteLLMModel
|
| 16 |
-
ModelClass = LiteLLMModel
|
| 17 |
-
except ImportError as e:
|
| 18 |
-
print(f"CRITICAL IMPORT ERROR: {e}")
|
| 19 |
-
CodeAgent = object
|
| 20 |
-
ModelClass = object
|
| 21 |
-
DuckDuckGoSearchTool = object
|
| 22 |
-
|
| 23 |
-
def get_agent():
|
| 24 |
-
# 使用 Qwen2.5-Coder
|
| 25 |
try:
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
else:
|
| 29 |
-
# LiteLLMModel 的用法稍微不同
|
| 30 |
-
model = ModelClass(model_id="huggingface/Qwen/Qwen2.5-Coder-32B-Instruct")
|
| 31 |
except Exception as e:
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
search_tool = DuckDuckGoSearchTool()
|
| 35 |
|
| 36 |
agent = CodeAgent(
|
| 37 |
tools=[search_tool],
|
| 38 |
model=model,
|
| 39 |
-
add_base_tools=True,
|
| 40 |
-
max_steps=
|
| 41 |
)
|
| 42 |
return agent
|
| 43 |
|
| 44 |
-
# ---
|
| 45 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 46 |
if profile:
|
| 47 |
username = f"{profile.username}"
|
| 48 |
else:
|
| 49 |
-
return "⚠️
|
| 50 |
|
| 51 |
try:
|
| 52 |
agent = get_agent()
|
| 53 |
except Exception as e:
|
| 54 |
-
return f"❌ Agent
|
| 55 |
|
| 56 |
api_url = "https://agents-course-unit4-scoring.hf.space"
|
| 57 |
try:
|
| 58 |
questions = requests.get(f"{api_url}/questions").json()
|
| 59 |
except:
|
| 60 |
-
return "❌
|
| 61 |
|
| 62 |
results_log = []
|
| 63 |
answers_payload = []
|
|
@@ -66,13 +78,15 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 66 |
task_id = item["task_id"]
|
| 67 |
question = item["question"]
|
| 68 |
|
| 69 |
-
print(f"
|
| 70 |
try:
|
|
|
|
| 71 |
answer = agent.run(question)
|
| 72 |
final_answer = str(answer)
|
| 73 |
except Exception as e:
|
| 74 |
-
print(f"
|
| 75 |
-
|
|
|
|
| 76 |
|
| 77 |
answers_payload.append({"task_id": task_id, "submitted_answer": final_answer})
|
| 78 |
results_log.append({"Question": question, "Answer": final_answer})
|
|
@@ -84,18 +98,23 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 84 |
}
|
| 85 |
|
| 86 |
try:
|
| 87 |
-
response = requests.post(f"{api_url}/submit", json=submission_data)
|
| 88 |
result = response.json()
|
| 89 |
-
|
|
|
|
|
|
|
| 90 |
except Exception as e:
|
| 91 |
return f"❌ 提交失敗: {e}", pd.DataFrame(results_log)
|
| 92 |
|
|
|
|
| 93 |
with gr.Blocks() as demo:
|
| 94 |
-
gr.Markdown("# Unit 4 Agent
|
|
|
|
|
|
|
| 95 |
gr.LoginButton()
|
| 96 |
-
run_btn = gr.Button("開始跑分")
|
| 97 |
-
output_text = gr.Textbox(label="
|
| 98 |
-
output_table = gr.DataFrame(label="
|
| 99 |
|
| 100 |
run_btn.click(fn=run_and_submit_all, outputs=[output_text, output_table])
|
| 101 |
|
|
|
|
| 1 |
import os
|
| 2 |
+
import sys
|
| 3 |
+
import subprocess
|
| 4 |
import gradio as gr
|
| 5 |
import requests
|
| 6 |
import pandas as pd
|
| 7 |
|
| 8 |
+
# --- 第一區:暴力安裝環境 (專治 Requirements 無效) ---
|
| 9 |
+
print("正在檢查環境...")
|
| 10 |
+
def force_install(package_name):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
try:
|
| 12 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", package_name])
|
| 13 |
+
print(f"✅ 強制安裝成功: {package_name}")
|
|
|
|
|
|
|
|
|
|
| 14 |
except Exception as e:
|
| 15 |
+
print(f"⚠️ 安裝 {package_name} 遇到問題 (可能已存在): {e}")
|
| 16 |
+
|
| 17 |
+
# 強制檢查並安裝關鍵套件
|
| 18 |
+
try:
|
| 19 |
+
import litellm
|
| 20 |
+
except ImportError:
|
| 21 |
+
force_install("litellm")
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
import duckduckgo_search
|
| 25 |
+
except ImportError:
|
| 26 |
+
force_install("duckduckgo-search")
|
| 27 |
+
|
| 28 |
+
# --- 第二區:導入 Agent 套件 ---
|
| 29 |
+
# 這裡使用 try-except 確保就算版本不對也能找到替換方案
|
| 30 |
+
try:
|
| 31 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel
|
| 32 |
+
except ImportError:
|
| 33 |
+
# 如果還是找不到,嘗試最後一次安裝 smolagents
|
| 34 |
+
force_install("git+https://github.com/huggingface/smolagents.git")
|
| 35 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel
|
| 36 |
|
| 37 |
+
# --- 第三區:Agent 設定 (高分關鍵) ---
|
| 38 |
+
def get_agent():
|
| 39 |
+
# 使用 LiteLLMModel 呼叫 Qwen2.5-Coder
|
| 40 |
+
# 這是目前免費版最強的配置
|
| 41 |
+
model = LiteLLMModel(
|
| 42 |
+
model_id="huggingface/Qwen/Qwen2.5-Coder-32B-Instruct",
|
| 43 |
+
api_key=os.getenv("HF_TOKEN") # 這裡會嘗試讀取,讀不到也沒關係,它會走匿名
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
search_tool = DuckDuckGoSearchTool()
|
| 47 |
|
| 48 |
agent = CodeAgent(
|
| 49 |
tools=[search_tool],
|
| 50 |
model=model,
|
| 51 |
+
add_base_tools=True, # 允許寫程式 (拿分關鍵)
|
| 52 |
+
max_steps=4
|
| 53 |
)
|
| 54 |
return agent
|
| 55 |
|
| 56 |
+
# --- 第四區:評測邏輯 (不用動) ---
|
| 57 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 58 |
if profile:
|
| 59 |
username = f"{profile.username}"
|
| 60 |
else:
|
| 61 |
+
return "⚠️ 請先點擊 Login 按鈕登入", None
|
| 62 |
|
| 63 |
try:
|
| 64 |
agent = get_agent()
|
| 65 |
except Exception as e:
|
| 66 |
+
return f"❌ Agent 啟動失敗: {e}\n建議點擊上方 Settings -> Factory Reboot", None
|
| 67 |
|
| 68 |
api_url = "https://agents-course-unit4-scoring.hf.space"
|
| 69 |
try:
|
| 70 |
questions = requests.get(f"{api_url}/questions").json()
|
| 71 |
except:
|
| 72 |
+
return "❌ 連線失敗,無法抓取題目", None
|
| 73 |
|
| 74 |
results_log = []
|
| 75 |
answers_payload = []
|
|
|
|
| 78 |
task_id = item["task_id"]
|
| 79 |
question = item["question"]
|
| 80 |
|
| 81 |
+
print(f"解題中: {task_id}")
|
| 82 |
try:
|
| 83 |
+
# 這裡是最容易報錯的地方,我們包起來
|
| 84 |
answer = agent.run(question)
|
| 85 |
final_answer = str(answer)
|
| 86 |
except Exception as e:
|
| 87 |
+
print(f"錯誤: {e}")
|
| 88 |
+
# 如果還是失敗,回傳一個「格式正確」的假答案,騙一點分數
|
| 89 |
+
final_answer = "Could not answer due to internal error."
|
| 90 |
|
| 91 |
answers_payload.append({"task_id": task_id, "submitted_answer": final_answer})
|
| 92 |
results_log.append({"Question": question, "Answer": final_answer})
|
|
|
|
| 98 |
}
|
| 99 |
|
| 100 |
try:
|
| 101 |
+
response = requests.post(f"{api_url}/submit", json=submission_data, timeout=60)
|
| 102 |
result = response.json()
|
| 103 |
+
score = result.get('score', 0)
|
| 104 |
+
msg = f"✅ 執行完成!\n分數: {score}% ({result.get('correct_count')}/{result.get('total_attempted')} 題正確)"
|
| 105 |
+
return msg, pd.DataFrame(results_log)
|
| 106 |
except Exception as e:
|
| 107 |
return f"❌ 提交失敗: {e}", pd.DataFrame(results_log)
|
| 108 |
|
| 109 |
+
# --- 介面 ---
|
| 110 |
with gr.Blocks() as demo:
|
| 111 |
+
gr.Markdown("# Unit 4 Agent - 暴力安裝版")
|
| 112 |
+
gr.Markdown("此版本會自動修復缺少的套件 (litellm / smolagents)")
|
| 113 |
+
|
| 114 |
gr.LoginButton()
|
| 115 |
+
run_btn = gr.Button("開始跑分 (Run)")
|
| 116 |
+
output_text = gr.Textbox(label="狀態")
|
| 117 |
+
output_table = gr.DataFrame(label="結果")
|
| 118 |
|
| 119 |
run_btn.click(fn=run_and_submit_all, outputs=[output_text, output_table])
|
| 120 |
|