severin15 commited on
Commit
c24e09d
·
verified ·
1 Parent(s): 1b544db

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +6 -217
app.py CHANGED
@@ -1,226 +1,15 @@
1
  import os
2
  import gradio as gr
3
- import requests
4
- import inspect
5
- import pandas as pd
6
 
7
- # (Keep Constants as is)
8
- # --- Constants ---
9
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Basic Agent Definition ---
12
- from smolagents import CodeAgent, InferenceClientModel, DuckDuckGoSearchTool
13
-
14
- class BasicAgent:
15
- def __init__(self):
16
- print("Initialisation de l'agent intelligent avec smolagents...")
17
- # On utilise le nouveau nom de la classe : InferenceClientModel
18
- self.model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")
19
-
20
- # On donne à l'agent un outil pour chercher sur le web
21
- self.tools = [DuckDuckGoSearchTool()]
22
-
23
- # On crée le CodeAgent
24
- self.agent = CodeAgent(tools=self.tools, model=self.model, add_base_tools=True)
25
-
26
- def __call__(self, question: str) -> str:
27
- print(f"Agent received question: {question[:100]}...")
28
-
29
- # On force l'agent à respecter le format strict de GAIA
30
- prompt = f"""
31
- Tu es un agent IA expert chargé de répondre à une question du benchmark GAIA.
32
- Voici la question :
33
- {question}
34
-
35
- Utilise tes outils pour trouver la réponse exacte.
36
- ATTENTION : Tu dois formuler ta réponse finale pour qu'elle corresponde EXACTEMENT à la solution (Exact Match).
37
- - Si c'est un nombre, renvoie juste le nombre (sans unités, sans virgules).
38
- - Si c'est un nom propre, renvoie juste le nom (sans articles).
39
- - Ne fais pas de phrases. Ne mets pas de ponctuation à la fin.
40
- Retourne UNIQUEMENT la valeur demandée.
41
- """
42
-
43
- try:
44
- # L'agent réfléchit et exécute ses actions
45
- result = self.agent.run(prompt)
46
- print(f"Agent returning answer: {result}")
47
- return str(result)
48
- except Exception as e:
49
- print(f"Agent error: {e}")
50
- return "Error"
51
-
52
- def run_and_submit_all( profile: gr.OAuthProfile | None):
53
- """
54
- Fetches all questions, runs the BasicAgent on them, submits all answers,
55
- and displays the results.
56
- """
57
- # --- Determine HF Space Runtime URL and Repo URL ---
58
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
59
-
60
- if profile:
61
- username= f"{profile.username}"
62
- print(f"User logged in: {username}")
63
- else:
64
- print("User not logged in.")
65
- return "Please Login to Hugging Face with the button.", None
66
-
67
- api_url = DEFAULT_API_URL
68
- questions_url = f"{api_url}/questions"
69
- submit_url = f"{api_url}/submit"
70
-
71
- # 1. Instantiate Agent ( modify this part to create your agent)
72
- try:
73
- agent = BasicAgent()
74
- except Exception as e:
75
- print(f"Error instantiating agent: {e}")
76
- return f"Error initializing agent: {e}", None
77
- # 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)
78
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
79
- print(agent_code)
80
-
81
- # 2. Fetch Questions
82
- print(f"Fetching questions from: {questions_url}")
83
- try:
84
- response = requests.get(questions_url, timeout=15)
85
- response.raise_for_status()
86
- questions_data = response.json()
87
- if not questions_data:
88
- print("Fetched questions list is empty.")
89
- return "Fetched questions list is empty or invalid format.", None
90
- print(f"Fetched {len(questions_data)} questions.")
91
- except requests.exceptions.RequestException as e:
92
- print(f"Error fetching questions: {e}")
93
- return f"Error fetching questions: {e}", None
94
- except requests.exceptions.JSONDecodeError as e:
95
- print(f"Error decoding JSON response from questions endpoint: {e}")
96
- print(f"Response text: {response.text[:500]}")
97
- return f"Error decoding server response for questions: {e}", None
98
- except Exception as e:
99
- print(f"An unexpected error occurred fetching questions: {e}")
100
- return f"An unexpected error occurred fetching questions: {e}", None
101
-
102
- # 3. Run your Agent
103
- results_log = []
104
- answers_payload = []
105
- print(f"Running agent on {len(questions_data)} questions...")
106
- for item in questions_data:
107
- task_id = item.get("task_id")
108
- question_text = item.get("question")
109
- if not task_id or question_text is None:
110
- print(f"Skipping item with missing task_id or question: {item}")
111
- continue
112
- try:
113
- submitted_answer = agent(question_text)
114
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
115
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
116
- except Exception as e:
117
- print(f"Error running agent on task {task_id}: {e}")
118
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
119
-
120
- if not answers_payload:
121
- print("Agent did not produce any answers to submit.")
122
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
123
-
124
- # 4. Prepare Submission
125
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
126
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
127
- print(status_update)
128
-
129
- # 5. Submit
130
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
131
- try:
132
- response = requests.post(submit_url, json=submission_data, timeout=60)
133
- response.raise_for_status()
134
- result_data = response.json()
135
- final_status = (
136
- f"Submission Successful!\n"
137
- f"User: {result_data.get('username')}\n"
138
- f"Overall Score: {result_data.get('score', 'N/A')}% "
139
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
140
- f"Message: {result_data.get('message', 'No message received.')}"
141
- )
142
- print("Submission successful.")
143
- results_df = pd.DataFrame(results_log)
144
- return final_status, results_df
145
- except requests.exceptions.HTTPError as e:
146
- error_detail = f"Server responded with status {e.response.status_code}."
147
- try:
148
- error_json = e.response.json()
149
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
150
- except requests.exceptions.JSONDecodeError:
151
- error_detail += f" Response: {e.response.text[:500]}"
152
- status_message = f"Submission Failed: {error_detail}"
153
- print(status_message)
154
- results_df = pd.DataFrame(results_log)
155
- return status_message, results_df
156
- except requests.exceptions.Timeout:
157
- status_message = "Submission Failed: The request timed out."
158
- print(status_message)
159
- results_df = pd.DataFrame(results_log)
160
- return status_message, results_df
161
- except requests.exceptions.RequestException as e:
162
- status_message = f"Submission Failed: Network error - {e}"
163
- print(status_message)
164
- results_df = pd.DataFrame(results_log)
165
- return status_message, results_df
166
- except Exception as e:
167
- status_message = f"An unexpected error occurred during submission: {e}"
168
- print(status_message)
169
- results_df = pd.DataFrame(results_log)
170
- return status_message, results_df
171
-
172
-
173
- # --- Build Gradio Interface using Blocks ---
174
  with gr.Blocks() as demo:
175
- gr.Markdown("# Basic Agent Evaluation Runner")
176
- gr.Markdown(
177
- """
178
- **Instructions:**
179
-
180
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
181
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
182
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
183
-
184
- ---
185
- **Disclaimers:**
186
- 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).
187
- 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.
188
- """
189
- )
190
-
191
  gr.LoginButton()
192
-
193
- run_button = gr.Button("Run Evaluation & Submit All Answers")
194
-
195
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
196
- # Removed max_rows=10 from DataFrame constructor
197
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
198
-
199
- run_button.click(
200
- fn=run_and_submit_all,
201
- outputs=[status_output, results_table]
202
- )
203
 
204
  if __name__ == "__main__":
205
- print("\n" + "-"*30 + " App Starting " + "-"*30)
206
- # Check for SPACE_HOST and SPACE_ID at startup for information
207
- space_host_startup = os.getenv("SPACE_HOST")
208
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
209
-
210
- if space_host_startup:
211
- print(f"✅ SPACE_HOST found: {space_host_startup}")
212
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
213
- else:
214
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
215
-
216
- if space_id_startup: # Print repo URLs if SPACE_ID is found
217
- print(f"✅ SPACE_ID found: {space_id_startup}")
218
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
219
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
220
- else:
221
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
222
-
223
- print("-"*(60 + len(" App Starting ")) + "\n")
224
-
225
- print("Launching Gradio Interface for Basic Agent Evaluation...")
226
  demo.launch(debug=True, share=False, ssr_mode=False)
 
1
  import os
2
  import gradio as gr
 
 
 
3
 
4
+ def dummy_evaluation(profile: gr.OAuthProfile | None):
5
+ return "Test réussi !", None
 
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  with gr.Blocks() as demo:
8
+ gr.Markdown("# Test Minimal")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  gr.LoginButton()
10
+ run_button = gr.Button("Tester")
11
+ status_output = gr.Textbox(label="Statut")
12
+ run_button.click(fn=dummy_evaluation, outputs=[status_output, gr.Number()])
 
 
 
 
 
 
 
 
13
 
14
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  demo.launch(debug=True, share=False, ssr_mode=False)