s1144662 commited on
Commit
9e0b740
·
verified ·
1 Parent(s): 5ba52a4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -37
app.py CHANGED
@@ -2,92 +2,167 @@ import os
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
- # 這裡只導入最基本的組件,避開 HfApiModel 導入錯誤
6
- from smolagents import CodeAgent, DuckDuckGoSearchTool
 
 
 
 
 
 
 
7
 
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
  class BasicAgent:
12
  def __init__(self):
13
- # 使用字串定義模型讓 smolagents 內部去處理載入,避開導入報錯
14
  self.model_id = "Qwen/Qwen2.5-Coder-32B-Instruct"
15
- search_tool = DuckDuckGoSearchTool()
16
 
17
- self.agent = CodeAgent(
18
- tools=[search_tool],
19
- model=self.model_id, # 直接傳入模型 ID 字串
20
- add_base_tools=True,
21
- )
22
- print("Agent initialized successfully.")
 
 
 
 
 
 
 
 
 
 
 
 
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
- print(f"Error: {e}")
 
31
  return "I am sorry, I cannot answer this right now."
32
 
33
- def run_and_submit_all(profile: gr.OAuthProfile | None):
34
- space_id = os.getenv("SPACE_ID")
35
- if profile:
36
- username = f"{profile.username}"
37
- else:
 
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=15)
 
53
  questions_data = response.json()
54
- except Exception as e:
55
- return f"Error fetching questions: {e}", None
 
 
56
 
57
  answers_payload = []
58
  results_log = []
59
 
60
- for item in questions_data:
 
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({"task_id": task_id, "submitted_answer": submitted_answer})
66
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
 
67
  except Exception as e:
68
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"Error: {e}"})
 
 
 
 
 
 
 
 
 
69
 
70
- submission_data = {"username": username, "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
 
 
71
  try:
72
- response = requests.post(submit_url, json=submission_data, timeout=60)
 
73
  result_data = response.json()
74
- status_msg = f"Score: {result_data.get('score')}% ({result_data.get('correct_count')}/{result_data.get('total_attempted')} correct)"
75
- except Exception as e:
76
- status_msg = f"Submission Failed: {e}"
 
 
 
 
 
 
77
 
78
  return status_msg, pd.DataFrame(results_log)
79
 
80
- with gr.Blocks() as demo:
 
 
81
  gr.Markdown("# Unit 4 Final Project: AI Agent")
82
- gr.LoginButton()
83
- run_button = gr.Button("Run Evaluation & Submit All Answers")
84
- status_output = gr.Textbox(label="Result")
85
- results_table = gr.DataFrame(label="Details")
 
 
 
 
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)