Israelbliz commited on
Commit
e0509e3
·
verified ·
1 Parent(s): cd24eac

Changed the code

Browse files
Files changed (1) hide show
  1. app.py +108 -146
app.py CHANGED
@@ -1,222 +1,184 @@
1
  import os
2
- import openai
3
  import gradio as gr
4
  import requests
5
- import inspect
6
  import pandas as pd
 
7
  from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel
8
- # (Keep Constants as is)
9
- # --- Constants ---
 
 
 
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
12
 
13
- # --- Basic Agent Definition ---
14
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
15
- DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
16
- DEEPSEEK_API_BASE = os.getenv("DEEPSEEK_API_BASE", "https://api.deepseek.com")
17
  class BasicAgent:
18
  def __init__(self):
19
  print("BasicAgent initialized.")
20
- # Initialize the model
21
- #model = HfApiModel()
22
- if not DEEPSEEK_API_KEY: # 添加一个检查,确保密钥已设置
23
- raise ValueError("DEEPSEEK_API_KEY environment variable not set. Please set it before running.")
24
-
25
- openai.api_key = DEEPSEEK_API_KEY # <--- 步骤 2: 全局设置 API 密钥
26
-
27
- # 为 openai 库设置基础 URL
28
- openai.api_base = DEEPSEEK_API_BASE
29
-
30
  model = OpenAIServerModel(
31
- model_id="deepseek-chat",
32
- api_key=DEEPSEEK_API_KEY
33
  )
34
- # Initialize the search tool
 
35
  search_tool = DuckDuckGoSearchTool()
36
- # Initialize Agent
 
37
  self.agent = CodeAgent(
38
- model = model,
39
  tools=[search_tool]
40
  )
 
41
  def __call__(self, question: str) -> str:
42
- print(f"Agent received question (first 50 chars): {question[:50]}...")
43
- fixed_answer =self.agent.run(question)
44
- print(f"Agent returning fixed answer: {fixed_answer}")
45
- return fixed_answer
46
-
47
- def run_and_submit_all( profile: gr.OAuthProfile | None):
48
- """
49
- Fetches all questions, runs the BasicAgent on them, submits all answers,
50
- and displays the results.
51
- """
52
- # --- Determine HF Space Runtime URL and Repo URL ---
53
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
54
 
55
  if profile:
56
- username= f"{profile.username}"
57
  print(f"User logged in: {username}")
58
  else:
59
- print("User not logged in.")
60
- return "Please Login to Hugging Face with the button.", None
61
 
62
- api_url = DEFAULT_API_URL
63
- questions_url = f"{api_url}/questions"
64
- submit_url = f"{api_url}/submit"
65
 
66
- # 1. Instantiate Agent ( modify this part to create your agent)
67
  try:
68
  agent = BasicAgent()
69
  except Exception as e:
70
- print(f"Error instantiating agent: {e}")
71
  return f"Error initializing agent: {e}", None
72
- # 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)
73
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
74
- print(agent_code)
75
 
76
- # 2. Fetch Questions
77
- print(f"Fetching questions from: {questions_url}")
78
  try:
79
  response = requests.get(questions_url, timeout=15)
80
  response.raise_for_status()
81
  questions_data = response.json()
82
- if not questions_data:
83
- print("Fetched questions list is empty.")
84
- return "Fetched questions list is empty or invalid format.", None
85
- print(f"Fetched {len(questions_data)} questions.")
86
- except requests.exceptions.RequestException as e:
87
- print(f"Error fetching questions: {e}")
88
- return f"Error fetching questions: {e}", None
89
- except requests.exceptions.JSONDecodeError as e:
90
- print(f"Error decoding JSON response from questions endpoint: {e}")
91
- print(f"Response text: {response.text[:500]}")
92
- return f"Error decoding server response for questions: {e}", None
93
  except Exception as e:
94
- print(f"An unexpected error occurred fetching questions: {e}")
95
- return f"An unexpected error occurred fetching questions: {e}", None
96
 
97
- # 3. Run your Agent
98
  results_log = []
99
  answers_payload = []
100
- print(f"Running agent on {len(questions_data)} questions...")
 
101
  for item in questions_data:
102
  task_id = item.get("task_id")
103
  question_text = item.get("question")
 
104
  if not task_id or question_text is None:
105
- print(f"Skipping item with missing task_id or question: {item}")
106
  continue
 
107
  try:
108
- submitted_answer = agent(question_text)
109
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
110
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
111
  except Exception as e:
112
- print(f"Error running agent on task {task_id}: {e}")
113
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
 
 
 
 
 
114
 
115
  if not answers_payload:
116
- print("Agent did not produce any answers to submit.")
117
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
118
 
119
- # 4. Prepare Submission
120
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
121
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
122
- print(status_update)
 
123
 
124
- # 5. Submit
125
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
126
  try:
127
  response = requests.post(submit_url, json=submission_data, timeout=60)
128
  response.raise_for_status()
129
- result_data = response.json()
 
130
  final_status = (
131
  f"Submission Successful!\n"
132
- f"User: {result_data.get('username')}\n"
133
- f"Overall Score: {result_data.get('score', 'N/A')}% "
134
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
135
- f"Message: {result_data.get('message', 'No message received.')}"
 
136
  )
137
- print("Submission successful.")
138
- results_df = pd.DataFrame(results_log)
139
- return final_status, results_df
140
- except requests.exceptions.HTTPError as e:
141
- error_detail = f"Server responded with status {e.response.status_code}."
142
- try:
143
- error_json = e.response.json()
144
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
145
- except requests.exceptions.JSONDecodeError:
146
- error_detail += f" Response: {e.response.text[:500]}"
147
- status_message = f"Submission Failed: {error_detail}"
148
- print(status_message)
149
- results_df = pd.DataFrame(results_log)
150
- return status_message, results_df
151
- except requests.exceptions.Timeout:
152
- status_message = "Submission Failed: The request timed out."
153
- print(status_message)
154
- results_df = pd.DataFrame(results_log)
155
- return status_message, results_df
156
- except requests.exceptions.RequestException as e:
157
- status_message = f"Submission Failed: Network error - {e}"
158
- print(status_message)
159
- results_df = pd.DataFrame(results_log)
160
- return status_message, results_df
161
  except Exception as e:
162
- status_message = f"An unexpected error occurred during submission: {e}"
163
- print(status_message)
164
- results_df = pd.DataFrame(results_log)
165
- return status_message, results_df
166
 
167
 
168
- # --- Build Gradio Interface using Blocks ---
 
 
169
  with gr.Blocks() as demo:
170
- gr.Markdown("# Basic Agent Evaluation Runner")
 
171
  gr.Markdown(
172
  """
173
- **Instructions:**
174
-
175
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
176
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
177
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
178
 
179
  ---
180
- **Disclaimers:**
181
- 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).
182
- 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.
183
- Please note that this version requires an OpenAI Key to run.
184
  """
185
  )
186
 
187
  gr.LoginButton()
188
-
189
  run_button = gr.Button("Run Evaluation & Submit All Answers")
190
 
191
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
192
- # Removed max_rows=10 from DataFrame constructor
193
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
 
 
 
 
 
 
 
194
 
195
  run_button.click(
196
  fn=run_and_submit_all,
197
  outputs=[status_output, results_table]
198
  )
199
 
200
- if __name__ == "__main__":
201
- print("\n" + "-"*30 + " App Starting " + "-"*30)
202
- # Check for SPACE_HOST and SPACE_ID at startup for information
203
- space_host_startup = os.getenv("SPACE_HOST")
204
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
205
-
206
- if space_host_startup:
207
- print(f"✅ SPACE_HOST found: {space_host_startup}")
208
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
209
- else:
210
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
211
 
212
- if space_id_startup: # Print repo URLs if SPACE_ID is found
213
- print(f"✅ SPACE_ID found: {space_id_startup}")
214
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
215
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
216
- else:
217
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
218
-
219
- print("-"*(60 + len(" App Starting ")) + "\n")
220
-
221
- print("Launching Gradio Interface for Basic Agent Evaluation...")
222
- demo.launch(debug=True, share=False)
 
1
  import os
 
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
+
6
  from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel
7
+
8
+
9
+ # =========================
10
+ # Constants
11
+ # =========================
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
 
14
 
15
+ # =========================
16
+ # Basic Agent Definition
17
+ # =========================
 
18
  class BasicAgent:
19
  def __init__(self):
20
  print("BasicAgent initialized.")
21
+
22
+ # Get OpenAI API key from environment (HF Secrets)
23
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
24
+ if not OPENAI_API_KEY:
25
+ raise ValueError(
26
+ "OPENAI_API_KEY environment variable not set. "
27
+ "Add it in Hugging Face → Settings → Secrets."
28
+ )
29
+
30
+ # Initialize OpenAI model
31
  model = OpenAIServerModel(
32
+ model_id="gpt-4o-mini", # You can switch to "gpt-4o" if you want
33
+ api_key=OPENAI_API_KEY
34
  )
35
+
36
+ # Initialize tools
37
  search_tool = DuckDuckGoSearchTool()
38
+
39
+ # Initialize agent
40
  self.agent = CodeAgent(
41
+ model=model,
42
  tools=[search_tool]
43
  )
44
+
45
  def __call__(self, question: str) -> str:
46
+ print(f"Agent received question: {question[:50]}...")
47
+ return self.agent.run(question)
48
+
49
+
50
+ # =========================
51
+ # Run + Submit Logic
52
+ # =========================
53
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
54
+ space_id = os.getenv("SPACE_ID")
 
 
 
55
 
56
  if profile:
57
+ username = profile.username
58
  print(f"User logged in: {username}")
59
  else:
60
+ return "Please login to Hugging Face first.", None
 
61
 
62
+ questions_url = f"{DEFAULT_API_URL}/questions"
63
+ submit_url = f"{DEFAULT_API_URL}/submit"
 
64
 
65
+ # Instantiate agent
66
  try:
67
  agent = BasicAgent()
68
  except Exception as e:
 
69
  return f"Error initializing agent: {e}", None
70
+
71
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
72
 
73
+ # Fetch questions
 
74
  try:
75
  response = requests.get(questions_url, timeout=15)
76
  response.raise_for_status()
77
  questions_data = response.json()
 
 
 
 
 
 
 
 
 
 
 
78
  except Exception as e:
79
+ return f"Error fetching questions: {e}", None
 
80
 
 
81
  results_log = []
82
  answers_payload = []
83
+
84
+ # Run agent
85
  for item in questions_data:
86
  task_id = item.get("task_id")
87
  question_text = item.get("question")
88
+
89
  if not task_id or question_text is None:
 
90
  continue
91
+
92
  try:
93
+ answer = agent(question_text)
 
 
94
  except Exception as e:
95
+ answer = f"AGENT ERROR: {e}"
96
+
97
+ answers_payload.append(
98
+ {"task_id": task_id, "submitted_answer": answer}
99
+ )
100
+
101
+ results_log.append(
102
+ {
103
+ "Task ID": task_id,
104
+ "Question": question_text,
105
+ "Submitted Answer": answer
106
+ }
107
+ )
108
 
109
  if not answers_payload:
110
+ return "No answers generated.", pd.DataFrame(results_log)
 
111
 
112
+ submission_data = {
113
+ "username": username.strip(),
114
+ "agent_code": agent_code,
115
+ "answers": answers_payload
116
+ }
117
 
118
+ # Submit answers
 
119
  try:
120
  response = requests.post(submit_url, json=submission_data, timeout=60)
121
  response.raise_for_status()
122
+ result = response.json()
123
+
124
  final_status = (
125
  f"Submission Successful!\n"
126
+ f"User: {result.get('username')}\n"
127
+ f"Score: {result.get('score', 'N/A')}% "
128
+ f"({result.get('correct_count', '?')}/"
129
+ f"{result.get('total_attempted', '?')})\n"
130
+ f"Message: {result.get('message', '')}"
131
  )
132
+
133
+ return final_status, pd.DataFrame(results_log)
134
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  except Exception as e:
136
+ return f"Submission failed: {e}", pd.DataFrame(results_log)
 
 
 
137
 
138
 
139
+ # =========================
140
+ # Gradio UI
141
+ # =========================
142
  with gr.Blocks() as demo:
143
+ gr.Markdown("# 🤖 Basic Agent Evaluation Runner")
144
+
145
  gr.Markdown(
146
  """
147
+ **Instructions**
148
+ 1. Login with your Hugging Face account.
149
+ 2. Click **Run Evaluation & Submit All Answers**.
150
+ 3. Wait while the agent answers and submits.
 
151
 
152
  ---
153
+ **Note:**
154
+ This app uses **OpenAI (gpt-4o-mini)** and requires an `OPENAI_API_KEY`
155
+ set in **Hugging Face Settings Secrets**.
 
156
  """
157
  )
158
 
159
  gr.LoginButton()
 
160
  run_button = gr.Button("Run Evaluation & Submit All Answers")
161
 
162
+ status_output = gr.Textbox(
163
+ label="Run Status / Submission Result",
164
+ lines=6,
165
+ interactive=False
166
+ )
167
+
168
+ results_table = gr.DataFrame(
169
+ label="Questions and Agent Answers",
170
+ wrap=True
171
+ )
172
 
173
  run_button.click(
174
  fn=run_and_submit_all,
175
  outputs=[status_output, results_table]
176
  )
177
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
+ # =========================
180
+ # App Entry Point
181
+ # =========================
182
+ if __name__ == "__main__":
183
+ print("Launching Gradio app...")
184
+ demo.launch(debug=True, share=False)