yooke commited on
Commit
d267ada
·
verified ·
1 Parent(s): 69b82a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -140
app.py CHANGED
@@ -2,202 +2,181 @@ import os
2
  import traceback
3
  import gradio as gr
4
  import requests
5
- import inspect
6
  import pandas as pd
7
  from smolagents import CodeAgent, DuckDuckGoSearchTool, PythonInterpreterTool, HfApiModel, LiteLLMModel, WikipediaSearchTool
8
  from huggingface_hub import login
9
  import time
10
 
11
- # (Keep Constants as is)
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
- #HF_TOKEN = os.getenv("HF_TOKEN")
15
- #login(HF_TOKEN)
16
  HF_TOKEN = os.getenv("HF_TOKEN")
17
- #login(HF_TOKEN)
 
18
  model = LiteLLMModel(model_id="deepseek/deepseek-chat",
19
  api_key=os.getenv("DEEPSEEK_API_KEY"),
20
  base_url="https://api.deepseek.com")
21
 
22
  # --- Basic Agent Definition ---
23
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
24
  class BasicAgent:
25
  def __init__(self):
26
- print("BasicAgent initialized.")
27
- # Set up model
28
  self.model = model
29
-
30
- # Initialize custom tools
31
  self.tools = [
32
  PythonInterpreterTool(),
33
  DuckDuckGoSearchTool(),
34
  WikipediaSearchTool(),
35
  ]
36
-
37
- # Create agent
38
  self.agent = CodeAgent(
39
  model=self.model,
40
  tools=self.tools,
41
  add_base_tools=True
42
  )
43
-
44
- def answer_question(self, question: str) -> str:
45
- """Process a question and return the answer"""
46
- print(f"Processing question: {question[:50]}..." if len(question) > 50 else question)
47
 
 
 
48
  try:
49
  result = self.agent.run(question)
50
- # Ensure result is always a string
51
  if not isinstance(result, str):
52
  result = str(result)
53
- # 提取最终答案 - 如果结果包含"Final answer:"格式
54
  if "Final answer:" in result:
55
- # 只提取最终答案部分
56
- final_answer_part = result.split("Final answer:")[1].strip()
57
  return final_answer_part
58
  return result
59
- except Exception as e:
60
- print(traceback.format_exc())
61
- error_msg = f"Error running agent: {str(e)}"
62
- return f"I encountered an issue while processing your question: {str(e)}"
63
 
64
 
 
 
 
65
 
66
- # 添加全局变量来存储已经处理过的问题和答案
67
- processed_questions = {}
68
- submission_completed = False
69
- def run_and_submit_all( profile: gr.OAuthProfile | None):
70
- """
71
- Fetches all questions, runs the BasicAgent on them, submits all answers,
72
- and displays the results.
73
- """
74
 
75
- global processed_questions, submission_completed
76
-
77
- # 如果已经完成提交,直接返回之前的结果
78
- if submission_completed and processed_questions:
79
- results_log = []
80
- for task_id, data in processed_questions.items():
81
- results_log.append({"Task ID": task_id, "Question": data["question"], "Submitted Answer": data["answer"]})
82
- return "已经完成提交,请刷新页面重新开始。", pd.DataFrame(results_log)
83
 
84
- # --- Determine HF Space Runtime URL and Repo URL ---
85
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
 
 
 
 
86
 
87
- if profile:
88
- username= f"{profile.username}"
89
- print(f"User logged in: {username}")
90
- else:
91
- print("User not logged in.")
92
- return "Please Login to Hugging Face with the button.", None
93
 
94
  api_url = DEFAULT_API_URL
95
  questions_url = f"{api_url}/questions"
96
  submit_url = f"{api_url}/submit"
 
 
97
 
98
- # 1. Instantiate Agent ( modify this part to create your agent)
99
  try:
100
  agent = BasicAgent()
101
  except Exception as e:
102
- print(f"Error instantiating agent: {e}")
103
- return f"Error initializing agent: {e}", None
104
- # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
105
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
106
- print(agent_code)
107
 
108
- # 2. Fetch Questions
109
- # print(f"Fetching questions from: {questions_url}")
110
  try:
111
- response = requests.get(questions_url, timeout=15)
112
  response.raise_for_status()
113
  questions_data = response.json()
114
  if not questions_data:
115
- print("Fetched questions list is empty.")
116
- return "Fetched questions list is empty or invalid format.", None
117
- # print(f"Fetched {len(questions_data)} questions.")
118
  except requests.exceptions.RequestException as e:
119
- print(f"Error fetching questions: {e}")
120
- return f"Error fetching questions: {e}", None
121
  except requests.exceptions.JSONDecodeError as e:
122
- print(f"Error decoding JSON response from questions endpoint: {e}")
123
- print(f"Response text: {response.text[:500]}")
124
- return f"Error decoding server response for questions: {e}", None
125
- except Exception as e:
126
- print(f"An unexpected error occurred fetching questions: {e}")
127
- return f"An unexpected error occurred fetching questions: {e}", None
128
 
129
- # 3. Run your Agent
130
  results_log = []
131
  answers_payload = []
132
- # print(f"Running agent on {len(questions_data)} questions...")
133
- for item in questions_data:
 
 
134
  task_id = item.get("task_id")
135
  question_text = item.get("question")
 
136
  if not task_id or question_text is None:
137
- # print(f"Skipping item with missing task_id or question: {item}")
138
  continue
 
 
 
139
  try:
140
  submitted_answer = agent.answer_question(question_text)
 
141
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
142
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
143
  except Exception as e:
144
- print(f"Error running agent on task {task_id}: {e}")
145
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
146
 
147
-
 
 
148
 
149
  if not answers_payload:
150
- # print("Agent did not produce any answers to submit.")
151
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
152
 
153
- # 4. Prepare Submission
154
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
155
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
156
- # print(status_update)
157
 
158
- # 5. Submit
159
- # print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
160
  try:
161
  response = requests.post(submit_url, json=submission_data, timeout=60)
162
  response.raise_for_status()
163
  result_data = response.json()
164
  final_status = (
165
- f"Submission Successful!\n"
166
- f"User: {result_data.get('username')}\n"
167
- f"Overall Score: {result_data.get('score', 'N/A')}% "
168
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
169
- f"Message: {result_data.get('message', 'No message received.')}"
170
  )
171
- # print("Submission successful.")
172
- submission_completed = True
 
 
 
 
 
173
  results_df = pd.DataFrame(results_log)
174
  return final_status, results_df
175
  except requests.exceptions.HTTPError as e:
176
- error_detail = f"Server responded with status {e.response.status_code}."
177
  try:
178
  error_json = e.response.json()
179
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
180
  except requests.exceptions.JSONDecodeError:
181
- error_detail += f" Response: {e.response.text[:500]}"
182
- status_message = f"Submission Failed: {error_detail}"
183
- # print(status_message)
184
- results_df = pd.DataFrame(results_log)
185
- return status_message, results_df
186
  except requests.exceptions.Timeout:
187
- status_message = "Submission Failed: The request timed out."
188
- # print(status_message)
189
- results_df = pd.DataFrame(results_log)
190
- return status_message, results_df
191
  except requests.exceptions.RequestException as e:
192
- status_message = f"Submission Failed: Network error - {e}"
193
- # print(status_message)
194
- results_df = pd.DataFrame(results_log)
195
- return status_message, results_df
196
  except Exception as e:
197
- status_message = f"An unexpected error occurred during submission: {e}"
198
- # print(status_message)
199
- results_df = pd.DataFrame(results_log)
200
- return status_message, results_df
 
201
 
202
 
203
  # --- Build Gradio Interface using Blocks ---
@@ -206,51 +185,29 @@ with gr.Blocks() as demo:
206
  gr.Markdown(
207
  """
208
  **Instructions:**
209
-
210
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
211
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
212
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
213
-
214
  ---
215
  **Disclaimers:**
216
- 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).
217
- 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.
 
218
  """
219
  )
220
 
221
  gr.LoginButton()
222
-
223
  run_button = gr.Button("Run Evaluation & Submit All Answers")
224
-
225
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
226
- # Removed max_rows=10 from DataFrame constructor
227
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
228
 
229
  run_button.click(
230
  fn=run_and_submit_all,
231
- outputs=[status_output, results_table]
232
  )
233
 
234
  if __name__ == "__main__":
235
  print("\n" + "-"*30 + " App Starting " + "-"*30)
236
- # Check for SPACE_HOST and SPACE_ID at startup for information
237
- space_host_startup = os.getenv("SPACE_HOST")
238
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
239
-
240
- if space_host_startup:
241
- print(f"✅ SPACE_HOST found: {space_host_startup}")
242
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
243
- else:
244
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
245
-
246
- if space_id_startup: # Print repo URLs if SPACE_ID is found
247
- print(f"✅ SPACE_ID found: {space_id_startup}")
248
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
249
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
250
- else:
251
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
252
-
253
- print("-"*(60 + len(" App Starting ")) + "\n")
254
-
255
  print("Launching Gradio Interface for Basic Agent Evaluation...")
256
- demo.launch(debug=True, share=True)
 
2
  import traceback
3
  import gradio as gr
4
  import requests
 
5
  import pandas as pd
6
  from smolagents import CodeAgent, DuckDuckGoSearchTool, PythonInterpreterTool, HfApiModel, LiteLLMModel, WikipediaSearchTool
7
  from huggingface_hub import login
8
  import time
9
 
 
10
  # --- Constants ---
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
12
  HF_TOKEN = os.getenv("HF_TOKEN")
13
+ # login(HF_TOKEN) # Recommended via Space secrets
14
+
15
  model = LiteLLMModel(model_id="deepseek/deepseek-chat",
16
  api_key=os.getenv("DEEPSEEK_API_KEY"),
17
  base_url="https://api.deepseek.com")
18
 
19
  # --- Basic Agent Definition ---
 
20
  class BasicAgent:
21
  def __init__(self):
22
+ # print("BasicAgent initialized.") # Removed
 
23
  self.model = model
 
 
24
  self.tools = [
25
  PythonInterpreterTool(),
26
  DuckDuckGoSearchTool(),
27
  WikipediaSearchTool(),
28
  ]
 
 
29
  self.agent = CodeAgent(
30
  model=self.model,
31
  tools=self.tools,
32
  add_base_tools=True
33
  )
 
 
 
 
34
 
35
+ def answer_question(self, question: str) -> str:
36
+ # print(f"Processing question (first 50 chars): {question[:50]}...") # Removed
37
  try:
38
  result = self.agent.run(question)
 
39
  if not isinstance(result, str):
40
  result = str(result)
 
41
  if "Final answer:" in result:
42
+ final_answer_part = result.split("Final answer:", 1)[1].strip()
 
43
  return final_answer_part
44
  return result
45
+ except Exception as e: # Capture exception object
46
+ print(f"Error in agent.run for question '{question[:50]}...':\n{traceback.format_exc()}")
47
+ return f"I encountered an issue processing your question: {str(e)}"
 
48
 
49
 
50
+ # Global variables
51
+ processed_questions_cache = {}
52
+ submission_has_been_completed = False
53
 
54
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
55
+ global processed_questions_cache, submission_has_been_completed
 
 
 
 
 
 
56
 
57
+ # print(f"--- run_and_submit_all triggered. Submission completed: {submission_has_been_completed} ---") # Removed
 
 
 
 
 
 
 
58
 
59
+ if submission_has_been_completed and processed_questions_cache:
60
+ # print("--- Submission previously completed. Displaying cached results. ---") # Removed
61
+ results_log_display = []
62
+ for task_id, data in processed_questions_cache.items():
63
+ results_log_display.append({"Task ID": task_id, "Question": data["question"], "Submitted Answer": data["answer"]})
64
+ return "评估已完成并提交。如果需要重新运行,请刷新页面。", pd.DataFrame(results_log_display if results_log_display else [{}])
65
 
66
+ if not profile:
67
+ # print("--- User not logged in. ---") # Removed
68
+ return "请先使用 Hugging Face 账号登录。", None
69
+
70
+ username = profile.username
71
+ print(f"--- User: {username}. Starting new submission process. ---") # Kept for context
72
 
73
  api_url = DEFAULT_API_URL
74
  questions_url = f"{api_url}/questions"
75
  submit_url = f"{api_url}/submit"
76
+ space_id = os.getenv("SPACE_ID")
77
+ agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "N/A (SPACE_ID not set)"
78
 
 
79
  try:
80
  agent = BasicAgent()
81
  except Exception as e:
82
+ print(f"Fatal: Error instantiating agent: {e}\n{traceback.format_exc()}")
83
+ return f"初始化 Agent 失败: {e}", None
 
 
 
84
 
85
+ # 1. Fetch Questions
86
+ # print(f"Fetching questions from: {questions_url}") # Removed
87
  try:
88
+ response = requests.get(questions_url, timeout=20)
89
  response.raise_for_status()
90
  questions_data = response.json()
91
  if not questions_data:
92
+ print("Warning: Fetched questions list is empty.")
93
+ return "获取到的问题列表为空。", None
94
+ # print(f"Fetched {len(questions_data)} questions.") # Removed
95
  except requests.exceptions.RequestException as e:
96
+ print(f"Fatal: Error fetching questions: {e}\n{traceback.format_exc()}")
97
+ return f"获取问题失败: {e}", None
98
  except requests.exceptions.JSONDecodeError as e:
99
+ print(f"Fatal: Error decoding JSON from questions: {e}\nResponse text: {response.text[:500]}")
100
+ return f"解析问题数据失败: {e}", None
 
 
 
 
101
 
 
102
  results_log = []
103
  answers_payload = []
104
+
105
+ # 2. Run Agent on Questions
106
+ print(f"--- Running agent on {len(questions_data)} questions... ---")
107
+ for i, item in enumerate(questions_data):
108
  task_id = item.get("task_id")
109
  question_text = item.get("question")
110
+
111
  if not task_id or question_text is None:
112
+ print(f"Warning: Skipping item with missing task_id or question: {item}")
113
  continue
114
+
115
+ print(f"--- Processing question {i+1}/{len(questions_data)} (ID: {task_id}): \"{question_text[:70]}...\" ---")
116
+ submitted_answer = "AGENT_ERROR: Did not run or failed" # Default in case of early exit
117
  try:
118
  submitted_answer = agent.answer_question(question_text)
119
+ print(f"--- Answer for Q{i+1} (ID: {task_id}): \"{submitted_answer[:70]}...\" ---") # Print the answer
120
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
121
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
122
  except Exception as e:
123
+ # This specific exception handling might be redundant if agent.answer_question handles its own exceptions and returns a string
124
+ # However, keeping it as a fallback.
125
+ print(f"Error running agent on task {task_id} (Question: \"{question_text[:50]}...\"):\n{traceback.format_exc()}")
126
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT_ERROR: {e}"})
127
 
128
+ # CRITICAL: This sleep is likely causing timeouts.
129
+ # print(f"--- Waiting before next question... ---") # Removed
130
+ time.sleep(1) # MINIMAL SLEEP - ADJUST OR REMOVE FOR TESTING / BASED ON API LIMITS
131
 
132
  if not answers_payload:
133
+ print("Warning: Agent did not produce any answers to submit.")
134
+ return "Agent 未能生成任何答案用于提交。", pd.DataFrame(results_log)
135
 
136
+ # 3. Prepare and Submit
137
+ submission_data = {"username": username, "agent_code": agent_code_url, "answers": answers_payload}
138
+ # status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..." # Removed
139
+ # print(status_update) # Removed
140
 
141
+ print(f"--- Submitting {len(answers_payload)} answers for user '{username}'... ---")
 
142
  try:
143
  response = requests.post(submit_url, json=submission_data, timeout=60)
144
  response.raise_for_status()
145
  result_data = response.json()
146
  final_status = (
147
+ f"提交成功!\n"
148
+ f"用户: {result_data.get('username')}\n"
149
+ f"总分: {result_data.get('score', 'N/A')}% "
150
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} 正确)\n"
151
+ f"消息: {result_data.get('message', '无消息.')}"
152
  )
153
+ print(f"--- Submission successful for {username}! Score: {result_data.get('score', 'N/A')}% ---")
154
+ submission_has_been_completed = True
155
+ for item_log in results_log:
156
+ processed_questions_cache[item_log["Task ID"]] = {
157
+ "question": item_log["Question"],
158
+ "answer": item_log["Submitted Answer"]
159
+ }
160
  results_df = pd.DataFrame(results_log)
161
  return final_status, results_df
162
  except requests.exceptions.HTTPError as e:
163
+ error_detail = f"服务器响应状态 {e.response.status_code}."
164
  try:
165
  error_json = e.response.json()
166
+ error_detail += f" 详情: {error_json.get('detail', e.response.text)}"
167
  except requests.exceptions.JSONDecodeError:
168
+ error_detail += f" 响应内容: {e.response.text[:500]}"
169
+ status_message = f"提交失败: {error_detail}"
 
 
 
170
  except requests.exceptions.Timeout:
171
+ status_message = "提交失败: 请求超时."
 
 
 
172
  except requests.exceptions.RequestException as e:
173
+ status_message = f"提交失败: 网络错误 - {e}"
 
 
 
174
  except Exception as e:
175
+ status_message = f"提交过程中发生未知错误: {e}\n{traceback.format_exc()}"
176
+
177
+ print(f"--- Submission failed or an error occurred for {username}: {status_message} ---")
178
+ results_df = pd.DataFrame(results_log)
179
+ return status_message, results_df
180
 
181
 
182
  # --- Build Gradio Interface using Blocks ---
 
185
  gr.Markdown(
186
  """
187
  **Instructions:**
188
+ 1. Modify the code (if needed) to define your agent's logic.
189
+ 2. Log in to your Hugging Face account using the button below.
190
+ 3. Click 'Run Evaluation & Submit All Answers'.
 
 
191
  ---
192
  **Disclaimers:**
193
+ This process can take a significant amount of time.
194
+ If the process seems to restart, it might be due to platform timeouts.
195
+ Check the application logs on Hugging Face Spaces for more details.
196
  """
197
  )
198
 
199
  gr.LoginButton()
 
200
  run_button = gr.Button("Run Evaluation & Submit All Answers")
 
201
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
202
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
203
 
204
  run_button.click(
205
  fn=run_and_submit_all,
206
+ outputs=[status_output, results_table],
207
  )
208
 
209
  if __name__ == "__main__":
210
  print("\n" + "-"*30 + " App Starting " + "-"*30)
211
+ # Minimal startup logs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  print("Launching Gradio Interface for Basic Agent Evaluation...")
213
+ demo.launch(debug=False, share=True) # debug=False for cleaner logs in production, True for local dev