Idealcom commited on
Commit
5cab61d
·
verified ·
1 Parent(s): e68d0c2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +228 -73
app.py CHANGED
@@ -1,105 +1,260 @@
 
1
  import gradio as gr
2
  import requests
 
3
  import time
4
  from smolagents import (
5
  CodeAgent,
 
6
  DuckDuckGoSearchTool,
7
- InferenceClientModel,
8
- Tool
 
9
  )
10
 
11
- from smolagents import VisitWebpageTool
12
 
13
- USERNAME = "Idealcom"
14
- SPACE_URL = "https://huggingface.co/spaces/Idealcom/Final_Assignment_Template"
 
15
 
16
- class FinalAnswerTool(Tool):
17
- name = "final_answer"
18
- description = "Provides a final answer to the given problem."
19
- inputs = {"answer": {"type": "string", "description": "The final answer"}}
20
- output_type = "string"
21
- def forward(self, answer: str) -> str:
22
- return answer
23
 
24
- final_answer = FinalAnswerTool()
 
 
 
 
25
 
26
- model = InferenceClientModel(
27
- model_id='meta-llama/Llama-3.1-70B-Instruct',
28
- temperature=0.1,
29
- )
 
 
30
 
 
 
 
 
 
 
31
 
32
- web_search = DuckDuckGoSearchTool()
33
- visit_webpage = VisitWebpageTool()
34
 
35
- agent = CodeAgent(
36
- model=model,
37
- tools=[web_search, visit_webpage, final_answer],
38
- max_steps=6,
39
- verbosity_level=1,
40
- name="Agent_GAIA_Student",
41
- description="Agent capable of solving complex tasks using web search",
42
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
 
 
 
45
 
46
- def run_evaluation_and_submit():
47
- logs = "🚀 DÉBUT DE L'EXAMEN...\n"
48
- yield logs
 
 
 
49
 
 
 
 
 
 
50
  try:
51
- logs += "📚 Récupération des questions...\n"
52
- yield logs
53
- questions = requests.get(f"{API_URL}/questions").json()
54
- logs += f"✅ {len(questions)} questions reçues.\n\n"
55
- yield logs
56
  except Exception as e:
57
- yield f"❌ Erreur : {e}"
58
- return
 
 
 
59
 
60
- answers = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- for i, q in enumerate(questions, 1):
63
- logs += f"[{i}/{len(questions)}] {q['question'][:60]}...\n"
64
- yield logs
65
-
66
  try:
67
- result = agent.run(q["question"])
68
- ans = str(result).replace("FINAL ANSWER:", "").strip()
69
- answers.append({"task_id": q["task_id"], "submitted_answer": ans})
70
- logs += f"✅ {ans}\n\n"
71
  except Exception as e:
72
- logs += f"⚠️ Erreur: {e}\n\n"
73
- answers.append({"task_id": q["task_id"], "submitted_answer": "Error"})
74
 
75
- yield logs
76
- time.sleep(0.2)
77
 
78
- logs += "📤 Envoi au serveur...\n"
79
- yield logs
80
-
 
 
 
 
 
 
 
 
 
81
  try:
82
- res = requests.post(
83
- f"{API_URL}/submit",
84
- json={"username": USERNAME, "agent_code": SPACE_URL, "answers": answers}
85
- ).json()
86
-
87
- logs += f"\n🎉 SCORE: {res.get('score', '?')}/{res.get('total', 20)}\n"
88
- logs += f"📊 {res.get('percentage', '?')}%\n"
89
-
90
- if res.get('percentage', 0) >= 30:
91
- logs += "\n✅ BRAVO! ≥ 30%!\n"
92
- logs += "Certificat: https://huggingface.co/spaces/agents-course/Unit4-Final-Certificate"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  except Exception as e:
94
- logs += f"\n❌ Erreur envoi: {e}"
95
-
96
- yield logs
 
 
97
 
 
98
  with gr.Blocks() as demo:
99
- gr.Markdown("# 🎓 GAIA Agent - Examen Final")
100
- btn = gr.Button("🚀 LANCER L'EXAMEN", variant="primary", size="lg")
101
- logs = gr.Textbox(label="Logs", lines=30, interactive=False)
102
- btn.click(run_evaluation_and_submit, outputs=logs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
  if __name__ == "__main__":
105
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
  import gradio as gr
3
  import requests
4
+ import pandas as pd
5
  import time
6
  from smolagents import (
7
  CodeAgent,
8
+ LiteLLMModel,
9
  DuckDuckGoSearchTool,
10
+ VisitWebpageTool,
11
+ PythonInterpreterTool,
12
+ tool
13
  )
14
 
 
15
 
16
+ # (Keep Constants as is)
17
+ # --- Constants ---
18
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
19
 
20
+ # Mes outils
 
 
 
 
 
 
21
 
22
+ @tool
23
+ def reverse_text_tool(text: str) -> str:
24
+ """Reverse text and word order"""
25
+ words = text.split(" ")[::-1]
26
+ return " ".join([word[::-1] for word in words])
27
 
28
+ @tool
29
+ def clean_answer_tool(answer: str) -> str:
30
+ """Clean answer"""
31
+ if answer.endswith('.'):
32
+ answer = answer[:-1]
33
+ return answer.replace("St.", "Saint").strip()
34
 
35
+ @tool
36
+ def extract_numbers_tool(text: str) -> str:
37
+ """Extract numbers from text"""
38
+ import re
39
+ numbers = re.findall(r'\d+\.?\d*', text)
40
+ return ', '.join(numbers)
41
 
 
 
42
 
43
+ # ----- THIS IS WHERE YOU CAN BUILD WHAT YOU WANT ------
44
+
45
+ class BasicAgent:
46
+ def __init__(self):
47
+ api_key = os.getenv("GOOGLE_API_KEY")
48
+
49
+ self.model = LiteLLMModel(
50
+ model_id="gemini/gemini-2.0-flash",
51
+ api_key=api_key
52
+ )
53
+
54
+ self.agent = CodeAgent(
55
+ model=self.model,
56
+ tools=[
57
+ DuckDuckGoSearchTool(),
58
+ VisitWebpageTool(),
59
+ PythonInterpreterTool(),
60
+ reverse_text_tool,
61
+ clean_answer_tool,
62
+ extract_numbers_tool,
63
+ ],
64
+ max_steps=15,
65
+ verbosity_level=1,
66
+ )
67
+ print("✅ BasicAgent initialized with Gemini 2.0 Flash")
68
+
69
+ def __call__(self, question: str) -> str:
70
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
71
+ try:
72
+ answer = self.agent.run(question)
73
+ result = str(answer).strip()
74
+ print(f"Agent returning: {result[:100]}...")
75
+ return result
76
+ except Exception as e:
77
+ print(f"Error: {e}")
78
+ return f"Error: {e}"
79
+
80
 
81
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
82
+ """
83
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
84
+ and displays the results.
85
+ """
86
+ # --- Determine HF Space Runtime URL and Repo URL ---
87
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
88
 
89
+ if profile:
90
+ username= f"{profile.username}"
91
+ print(f"User logged in: {username}")
92
+ else:
93
+ print("User not logged in.")
94
+ return "Please Login to Hugging Face with the button.", None
95
 
96
+ api_url = DEFAULT_API_URL
97
+ questions_url = f"{api_url}/questions"
98
+ submit_url = f"{api_url}/submit"
99
+
100
+ # 1. Instantiate Agent ( modify this part to create your agent)
101
  try:
102
+ agent = BasicAgent()
 
 
 
 
103
  except Exception as e:
104
+ print(f"Error instantiating agent: {e}")
105
+ return f"Error initializing agent: {e}", None
106
+ # 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)
107
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
108
+ print(agent_code)
109
 
110
+ # 2. Fetch Questions
111
+ print(f"Fetching questions from: {questions_url}")
112
+ try:
113
+ response = requests.get(questions_url, timeout=15)
114
+ response.raise_for_status()
115
+ questions_data = response.json()
116
+ if not questions_data:
117
+ print("Fetched questions list is empty.")
118
+ return "Fetched questions list is empty or invalid format.", None
119
+ print(f"Fetched {len(questions_data)} questions.")
120
+ except requests.exceptions.RequestException as e:
121
+ print(f"Error fetching questions: {e}")
122
+ return f"Error fetching questions: {e}", None
123
+ except requests.exceptions.JSONDecodeError as e:
124
+ print(f"Error decoding JSON response from questions endpoint: {e}")
125
+ print(f"Response text: {response.text[:500]}")
126
+ return f"Error decoding server response for questions: {e}", None
127
+ except Exception as e:
128
+ print(f"An unexpected error occurred fetching questions: {e}")
129
+ return f"An unexpected error occurred fetching questions: {e}", None
130
+
131
+ # 3. Run your Agent
132
+ results_log = []
133
+ answers_payload = []
134
+ print(f"Running agent on {len(questions_data)} questions...")
135
+
136
+ for item in questions_data:
137
+ task_id = item.get("task_id")
138
+ question_text = item.get("question")
139
+
140
+ if not task_id or question_text is None:
141
+ print(f"Skipping item with missing task_id or question: {item}")
142
+ continue
143
 
 
 
 
 
144
  try:
145
+ # Attention : avec smolagents, utilise souvent agent.run() au lieu de agent() direct
146
+ submitted_answer = agent.run(question_text)
147
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
148
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
149
  except Exception as e:
150
+ print(f"Error running agent on task {task_id}: {e}")
151
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
152
 
153
+ time.sleep(0.3)
 
154
 
155
+ if not answers_payload:
156
+ print("Agent did not produce any answers to submit.")
157
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
158
+
159
+
160
+ # 4. Prepare Submission
161
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
162
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
163
+ print(status_update)
164
+
165
+ # 5. Submit
166
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
167
  try:
168
+ response = requests.post(submit_url, json=submission_data, timeout=60)
169
+ response.raise_for_status()
170
+ result_data = response.json()
171
+ final_status = (
172
+ f"Submission Successful!\n"
173
+ f"User: {result_data.get('username')}\n"
174
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
175
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
176
+ f"Message: {result_data.get('message', 'No message received.')}"
177
+ )
178
+ print("Submission successful.")
179
+ results_df = pd.DataFrame(results_log)
180
+ return final_status, results_df
181
+ except requests.exceptions.HTTPError as e:
182
+ error_detail = f"Server responded with status {e.response.status_code}."
183
+ try:
184
+ error_json = e.response.json()
185
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
186
+ except requests.exceptions.JSONDecodeError:
187
+ error_detail += f" Response: {e.response.text[:500]}"
188
+ status_message = f"Submission Failed: {error_detail}"
189
+ print(status_message)
190
+ results_df = pd.DataFrame(results_log)
191
+ return status_message, results_df
192
+ except requests.exceptions.Timeout:
193
+ status_message = "Submission Failed: The request timed out."
194
+ print(status_message)
195
+ results_df = pd.DataFrame(results_log)
196
+ return status_message, results_df
197
+ except requests.exceptions.RequestException as e:
198
+ status_message = f"Submission Failed: Network error - {e}"
199
+ print(status_message)
200
+ results_df = pd.DataFrame(results_log)
201
+ return status_message, results_df
202
  except Exception as e:
203
+ status_message = f"An unexpected error occurred during submission: {e}"
204
+ print(status_message)
205
+ results_df = pd.DataFrame(results_log)
206
+ return status_message, results_df
207
+
208
 
209
+ # --- Build Gradio Interface using Blocks ---
210
  with gr.Blocks() as demo:
211
+ gr.Markdown("# Basic Agent Evaluation Runner")
212
+ gr.Markdown(
213
+ """
214
+ **Instructions:**
215
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
216
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
217
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
218
+ ---
219
+ **Disclaimers:**
220
+ 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).
221
+ 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.
222
+ """
223
+ )
224
+
225
+ gr.LoginButton()
226
+
227
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
228
+
229
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
230
+ # Removed max_rows=10 from DataFrame constructor
231
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
232
+
233
+ run_button.click(
234
+ fn=run_and_submit_all,
235
+ outputs=[status_output, results_table]
236
+ )
237
 
238
  if __name__ == "__main__":
239
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
240
+ # Check for SPACE_HOST and SPACE_ID at startup for information
241
+ space_host_startup = os.getenv("SPACE_HOST")
242
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
243
+
244
+ if space_host_startup:
245
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
246
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
247
+ else:
248
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
249
+
250
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
251
+ print(f"✅ SPACE_ID found: {space_id_startup}")
252
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
253
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
254
+ else:
255
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
256
+
257
+ print("-"*(60 + len(" App Starting ")) + "\n")
258
+
259
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
260
+ demo.launch(debug=True, share=False)