ShigatoraShuz commited on
Commit
ede29af
·
verified ·
1 Parent(s): 97795a7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +7 -189
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import os
2
  import re
 
3
  import tempfile
4
  import gradio as gr
5
  import requests
@@ -8,7 +9,7 @@ import spaces
8
  from smolagents import (
9
  CodeAgent,
10
  DuckDuckGoSearchTool,
11
- InferenceClientModel,
12
  VisitWebpageTool,
13
  tool,
14
  )
@@ -43,10 +44,9 @@ def download_task_file(task_id: str) -> str:
43
  # --- Basic Agent Definition ---
44
  class BasicAgent:
45
  def __init__(self):
46
- model = InferenceClientModel(
47
- model_id="Qwen/Qwen2.5-72B-Instruct",
48
- provider="auto",
49
- token=os.getenv("HF_TOKEN"),
50
  )
51
  self.agent = CodeAgent(
52
  tools=[DuckDuckGoSearchTool(), VisitWebpageTool(), download_task_file],
@@ -81,190 +81,8 @@ class BasicAgent:
81
  try:
82
  raw = str(self.agent.run(prompt)).strip()
83
  cleaned = re.sub(r"^(final answer\s*:?\s*)", "", raw, flags=re.IGNORECASE).strip()
 
84
  return cleaned.rstrip(".")
85
  except Exception as e:
86
  print(f"Agent error: {e}")
87
- return f"Error: {e}"
88
-
89
-
90
- def run_and_submit_all(profile: gr.OAuthProfile | None):
91
- """
92
- Fetches all questions, runs the BasicAgent on them, submits all answers,
93
- and displays the results.
94
- """
95
- space_id = os.getenv("SPACE_ID")
96
-
97
- if profile:
98
- username = f"{profile.username}"
99
- print(f"User logged in: {username}")
100
- else:
101
- print("User not logged in.")
102
- return "Please Login to Hugging Face with the button.", None
103
-
104
- api_url = DEFAULT_API_URL
105
- questions_url = f"{api_url}/questions"
106
- submit_url = f"{api_url}/submit"
107
-
108
- # 1. Instantiate Agent
109
- try:
110
- agent = BasicAgent()
111
- except Exception as e:
112
- print(f"Error instantiating agent: {e}")
113
- return f"Error initializing agent: {e}", None
114
-
115
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
116
- print(agent_code)
117
-
118
- # 2. Fetch Questions
119
- print(f"Fetching questions from: {questions_url}")
120
- try:
121
- response = requests.get(questions_url, timeout=15)
122
- response.raise_for_status()
123
- questions_data = response.json()
124
- if not questions_data:
125
- print("Fetched questions list is empty.")
126
- return "Fetched questions list is empty or invalid format.", None
127
- print(f"Fetched {len(questions_data)} questions.")
128
- except requests.exceptions.RequestException as e:
129
- print(f"Error fetching questions: {e}")
130
- return f"Error fetching questions: {e}", None
131
- except requests.exceptions.JSONDecodeError as e:
132
- print(f"Error decoding JSON response from questions endpoint: {e}")
133
- return f"Error decoding server response for questions: {e}", None
134
- except Exception as e:
135
- print(f"An unexpected error occurred fetching questions: {e}")
136
- return f"An unexpected error occurred fetching questions: {e}", None
137
-
138
- # 3. Run your Agent
139
- results_log = []
140
- answers_payload = []
141
- print(f"Running agent on {len(questions_data)} questions...")
142
- for item in questions_data:
143
- task_id = item.get("task_id")
144
- question_text = item.get("question")
145
- if not task_id or question_text is None:
146
- print(f"Skipping item with missing task_id or question: {item}")
147
- continue
148
- try:
149
- submitted_answer = agent(question_text, task_id)
150
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
151
- results_log.append(
152
- {
153
- "Task ID": task_id,
154
- "Question": question_text,
155
- "Submitted Answer": submitted_answer,
156
- }
157
- )
158
- except Exception as e:
159
- print(f"Error running agent on task {task_id}: {e}")
160
- results_log.append(
161
- {
162
- "Task ID": task_id,
163
- "Question": question_text,
164
- "Submitted Answer": f"AGENT ERROR: {e}",
165
- }
166
- )
167
-
168
- if not answers_payload:
169
- print("Agent did not produce any answers to submit.")
170
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
171
-
172
- # 4. Prepare Submission
173
- submission_data = {
174
- "username": username.strip(),
175
- "agent_code": agent_code,
176
- "answers": answers_payload,
177
- }
178
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
179
- print(status_update)
180
-
181
- # 5. Submit
182
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
183
- try:
184
- response = requests.post(submit_url, json=submission_data, timeout=60)
185
- response.raise_for_status()
186
- result_data = response.json()
187
- final_status = (
188
- f"Submission Successful!\n"
189
- f"User: {result_data.get('username')}\n"
190
- f"Overall Score: {result_data.get('score', 'N/A')}% "
191
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
192
- f"Message: {result_data.get('message', 'No message received.')}"
193
- )
194
- print("Submission successful.")
195
- results_df = pd.DataFrame(results_log)
196
- return final_status, results_df
197
- except requests.exceptions.HTTPError as e:
198
- error_detail = f"Server responded with status {e.response.status_code}."
199
- try:
200
- error_json = e.response.json()
201
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
202
- except requests.exceptions.JSONDecodeError:
203
- error_detail += f" Response: {e.response.text[:500]}"
204
- status_message = f"Submission Failed: {error_detail}"
205
- print(status_message)
206
- results_df = pd.DataFrame(results_log)
207
- return status_message, results_df
208
- except requests.exceptions.Timeout:
209
- status_message = "Submission Failed: The request timed out. Please try again."
210
- print(status_message)
211
- results_df = pd.DataFrame(results_log)
212
- return status_message, results_df
213
- except requests.exceptions.RequestException as e:
214
- status_message = f"Submission Failed: Network error - {e}"
215
- print(status_message)
216
- results_df = pd.DataFrame(results_log)
217
- return status_message, results_df
218
- except Exception as e:
219
- status_message = f"An unexpected error occurred during submission: {e}"
220
- print(status_message)
221
- results_df = pd.DataFrame(results_log)
222
- return status_message, results_df
223
-
224
-
225
- # --- Build Gradio Interface using Blocks ---
226
- with gr.Blocks() as demo:
227
- gr.Markdown("# Basic Agent Evaluation Runner")
228
- gr.Markdown(
229
- """
230
- **Instructions:**
231
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
232
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
233
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
234
- """
235
- )
236
-
237
- gr.LoginButton()
238
-
239
- run_button = gr.Button("Run Evaluation & Submit All Answers")
240
-
241
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
242
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
243
-
244
- run_button.click(
245
- fn=run_and_submit_all,
246
- outputs=[status_output, results_table],
247
- )
248
-
249
- if __name__ == "__main__":
250
- print("\n" + "-" * 30 + " App Starting " + "-" * 30)
251
- space_host_startup = os.getenv("SPACE_HOST")
252
- space_id_startup = os.getenv("SPACE_ID")
253
-
254
- if space_host_startup:
255
- print(f"✅ SPACE_HOST found: {space_host_startup}")
256
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
257
- else:
258
- print("ℹ️ SPACE_HOST environment variable not found (running locally).")
259
-
260
- if space_id_startup:
261
- print(f"✅ SPACE_ID found: {space_id_startup}")
262
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
263
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
264
- else:
265
- print("ℹ️ SPACE_ID environment variable not found (running locally). Repo URL cannot be determined.")
266
-
267
- print("-" * (60 + len(" App Starting ")) + "\n")
268
-
269
- print("Launching Gradio Interface for Basic Agent Evaluation...")
270
- demo.launch(debug=True, share=False)
 
1
  import os
2
  import re
3
+ import time
4
  import tempfile
5
  import gradio as gr
6
  import requests
 
9
  from smolagents import (
10
  CodeAgent,
11
  DuckDuckGoSearchTool,
12
+ LiteLLMModel,
13
  VisitWebpageTool,
14
  tool,
15
  )
 
44
  # --- Basic Agent Definition ---
45
  class BasicAgent:
46
  def __init__(self):
47
+ model = LiteLLMModel(
48
+ model_id="gemini/gemini-2.5-flash",
49
+ api_key=os.getenv("GEMINI_API_KEY"),
 
50
  )
51
  self.agent = CodeAgent(
52
  tools=[DuckDuckGoSearchTool(), VisitWebpageTool(), download_task_file],
 
81
  try:
82
  raw = str(self.agent.run(prompt)).strip()
83
  cleaned = re.sub(r"^(final answer\s*:?\s*)", "", raw, flags=re.IGNORECASE).strip()
84
+ time.sleep(2)
85
  return cleaned.rstrip(".")
86
  except Exception as e:
87
  print(f"Agent error: {e}")
88
+ return f"Error: {e}"