mobrobro commited on
Commit
ac180a4
·
verified ·
1 Parent(s): 72b86d4

Update app.py

Browse files

Revised with everything at root level removing scripts directory

Files changed (1) hide show
  1. app.py +401 -5
app.py CHANGED
@@ -1,11 +1,407 @@
1
- from run import create_agent
 
 
 
 
 
 
2
 
3
- from smolagents.gradio_ui import GradioUI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
 
 
 
 
 
 
5
 
6
- agent = create_agent()
 
7
 
8
- demo = GradioUI(agent)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  if __name__ == "__main__":
11
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import inspect
5
+ import pandas as pd
6
+ import sys
7
+ from pathlib import Path
8
 
9
+ # Import your agent components from root level
10
+ from dotenv import load_dotenv
11
+ from huggingface_hub import login
12
+ from text_inspector_tool import TextInspectorTool
13
+ from text_web_browser import (
14
+ ArchiveSearchTool,
15
+ FinderTool,
16
+ FindNextTool,
17
+ PageDownTool,
18
+ PageUpTool,
19
+ SimpleTextBrowser,
20
+ VisitTool,
21
+ )
22
+ from visual_qa import visualizer
23
+ from reformulator import prepare_response
24
 
25
+ from smolagents import (
26
+ CodeAgent,
27
+ GoogleSearchTool,
28
+ LiteLLMModel,
29
+ ToolCallingAgent,
30
+ )
31
 
32
+ # --- Constants ---
33
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
34
 
35
+ # GAIA system prompt for exact answer format
36
+ GAIA_SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."""
37
+
38
+ # --- Smolagent Implementation ---
39
+ load_dotenv(override=True)
40
+
41
+ # Try to login with HF token from env or secrets
42
+ try:
43
+ hf_token = os.getenv("HF_TOKEN")
44
+ if hf_token:
45
+ login(hf_token)
46
+ print("Successfully logged in to Hugging Face")
47
+ else:
48
+ print("No HF_TOKEN found in environment")
49
+ except Exception as e:
50
+ print(f"Error logging in to Hugging Face: {e}")
51
+
52
+ # Custom settings for your agent
53
+ custom_role_conversions = {"tool-call": "assistant", "tool-response": "user"}
54
+ user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"
55
+
56
+ BROWSER_CONFIG = {
57
+ "viewport_size": 1024 * 5,
58
+ "downloads_folder": "downloads_folder",
59
+ "request_kwargs": {
60
+ "headers": {"User-Agent": user_agent},
61
+ "timeout": 300,
62
+ },
63
+ "serpapi_key": os.getenv("SERPAPI_API_KEY"),
64
+ }
65
+
66
+ # Create downloads folder if it doesn't exist
67
+ os.makedirs(f"./{BROWSER_CONFIG['downloads_folder']}", exist_ok=True)
68
+
69
+ class SmolaAgent:
70
+ def __init__(self):
71
+ print("Initializing SmolaAgent...")
72
+
73
+ # Initialize model
74
+ model_id = "o1" # You can adjust this or make it configurable
75
+ model_params = {
76
+ "model_id": model_id,
77
+ "custom_role_conversions": custom_role_conversions,
78
+ "max_completion_tokens": 8192,
79
+ }
80
+ if model_id == "o1":
81
+ model_params["reasoning_effort"] = "high"
82
+
83
+ self.model = LiteLLMModel(**model_params)
84
+
85
+ # Create agent with tools
86
+ text_limit = 100000
87
+ browser = SimpleTextBrowser(**BROWSER_CONFIG)
88
+ WEB_TOOLS = [
89
+ GoogleSearchTool(provider="serper"),
90
+ VisitTool(browser),
91
+ PageUpTool(browser),
92
+ PageDownTool(browser),
93
+ FinderTool(browser),
94
+ FindNextTool(browser),
95
+ ArchiveSearchTool(browser),
96
+ TextInspectorTool(self.model, text_limit),
97
+ ]
98
+
99
+ # Create text webbrowser agent
100
+ self.text_webbrowser_agent = ToolCallingAgent(
101
+ model=self.model,
102
+ tools=WEB_TOOLS,
103
+ max_steps=20,
104
+ verbosity_level=2,
105
+ planning_interval=4,
106
+ name="search_agent",
107
+ description="""A team member that will search the internet to answer your question.
108
+ Ask him for all your questions that require browsing the web.
109
+ Provide him as much context as possible, in particular if you need to search on a specific timeframe!
110
+ And don't hesitate to provide him with a complex search task, like finding a difference between two webpages.
111
+ Your request must be a real sentence, not a google search! Like "Find me this information (...)" rather than a few keywords.
112
+ """,
113
+ provide_run_summary=True,
114
+ )
115
+
116
+ self.text_webbrowser_agent.prompt_templates["managed_agent"]["task"] += """You can navigate to .txt online files.
117
+ If a non-html page is in another format, especially .pdf or a Youtube video, use tool 'inspect_file_as_text' to inspect it.
118
+ Additionally, if after some searching you find out that you need more information to answer the question, you can use `final_answer` with your request for clarification as argument to request for more information."""
119
+
120
+ # Create manager agent
121
+ self.manager_agent = CodeAgent(
122
+ model=self.model,
123
+ tools=[visualizer, TextInspectorTool(self.model, text_limit)],
124
+ max_steps=12,
125
+ verbosity_level=2,
126
+ additional_authorized_imports=["*"],
127
+ planning_interval=4,
128
+ managed_agents=[self.text_webbrowser_agent],
129
+ )
130
+
131
+ print("SmolaAgent initialized successfully.")
132
+
133
+ def __call__(self, question: str) -> str:
134
+ print(f"Agent received question: {question[:50]}...")
135
+
136
+ # Include the GAIA system prompt in the question to ensure proper answer format
137
+ augmented_question = f"""You have one question to answer. It is paramount that you provide a correct answer.
138
+ Give it all you can: I know for a fact that you have access to all the relevant tools to solve it and find the correct answer (the answer does exist). Failure or 'I cannot answer' or 'None found' will not be tolerated, success will be rewarded.
139
+ Run verification steps if that's needed, you must make sure you find the correct answer!
140
+
141
+ {GAIA_SYSTEM_PROMPT}
142
+
143
+ Here is the task:
144
+ {question}"""
145
+
146
+ try:
147
+ # Run the agent
148
+ result = self.manager_agent.run(augmented_question)
149
+
150
+ # Use reformulator to get properly formatted final answer
151
+ agent_memory = self.manager_agent.write_memory_to_messages()
152
+
153
+ # Add the GAIA system prompt to the reformulation to ensure correct format
154
+ for message in agent_memory:
155
+ if message.get("role") == "system" and message.get("content"):
156
+ if isinstance(message["content"], list):
157
+ for content_item in message["content"]:
158
+ if content_item.get("type") == "text":
159
+ content_item["text"] = GAIA_SYSTEM_PROMPT + "\n\n" + content_item["text"]
160
+ else:
161
+ message["content"] = GAIA_SYSTEM_PROMPT + "\n\n" + message["content"]
162
+ break
163
+
164
+ final_answer = prepare_response(augmented_question, agent_memory, self.model)
165
+
166
+ print(f"Agent returning answer: {final_answer}")
167
+ return final_answer
168
+
169
+ except Exception as e:
170
+ print(f"Error running agent: {e}")
171
+ return "FINAL ANSWER: Unable to determine"
172
+
173
+ # Function to extract the exact answer from agent response
174
+ def extract_final_answer(agent_response):
175
+ if "FINAL ANSWER:" in agent_response:
176
+ answer = agent_response.split("FINAL ANSWER:")[1].strip()
177
+
178
+ # Additional cleaning to ensure exact match
179
+ # Remove any trailing punctuation
180
+ answer = answer.rstrip('.,!?;:')
181
+
182
+ # Clean numbers (remove commas and units)
183
+ # This is a simple example - you might need more sophisticated cleaning
184
+ words = answer.split()
185
+ for i, word in enumerate(words):
186
+ # Try to convert to a number to remove commas and format correctly
187
+ try:
188
+ num = float(word.replace(',', '').replace('$', '').replace('%', ''))
189
+ # Convert to int if it's a whole number
190
+ words[i] = str(int(num)) if num.is_integer() else str(num)
191
+ except (ValueError, AttributeError):
192
+ # Not a number, leave as is
193
+ pass
194
+
195
+ return ' '.join(words)
196
+
197
+ return "Unable to determine"
198
+
199
+ # Replace BasicAgent with your SmolaAgent in the run_and_submit_all function
200
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
201
+ """
202
+ Fetches all questions, runs the SmolaAgent on them, submits all answers,
203
+ and displays the results.
204
+ """
205
+ # --- Determine HF Space Runtime URL and Repo URL ---
206
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
207
+
208
+ if profile:
209
+ username= f"{profile.username}"
210
+ print(f"User logged in: {username}")
211
+ else:
212
+ print("User not logged in.")
213
+ return "Please Login to Hugging Face with the button.", None
214
+
215
+ api_url = DEFAULT_API_URL
216
+ questions_url = f"{api_url}/questions"
217
+ submit_url = f"{api_url}/submit"
218
+
219
+ # 1. Instantiate Agent
220
+ try:
221
+ agent = SmolaAgent()
222
+ except Exception as e:
223
+ print(f"Error instantiating agent: {e}")
224
+ return f"Error initializing agent: {e}", None
225
+
226
+ # In the case of an app running as a hugging Face space, this link points toward your codebase
227
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
228
+ print(agent_code)
229
+
230
+ # 2. Fetch Questions
231
+ print(f"Fetching questions from: {questions_url}")
232
+ try:
233
+ response = requests.get(questions_url, timeout=15)
234
+ response.raise_for_status()
235
+ questions_data = response.json()
236
+ if not questions_data:
237
+ print("Fetched questions list is empty.")
238
+ return "Fetched questions list is empty or invalid format.", None
239
+ print(f"Fetched {len(questions_data)} questions.")
240
+ except requests.exceptions.RequestException as e:
241
+ print(f"Error fetching questions: {e}")
242
+ return f"Error fetching questions: {e}", None
243
+ except requests.exceptions.JSONDecodeError as e:
244
+ print(f"Error decoding JSON response from questions endpoint: {e}")
245
+ print(f"Response text: {response.text[:500]}")
246
+ return f"Error decoding server response for questions: {e}", None
247
+ except Exception as e:
248
+ print(f"An unexpected error occurred fetching questions: {e}")
249
+ return f"An unexpected error occurred fetching questions: {e}", None
250
+
251
+ # 3. Run your Agent
252
+ results_log = []
253
+ answers_payload = []
254
+ print(f"Running agent on {len(questions_data)} questions...")
255
+ for item in questions_data:
256
+ task_id = item.get("task_id")
257
+ question_text = item.get("question")
258
+
259
+ # Check if there are files associated with this task
260
+ try:
261
+ files_url = f"{api_url}/files/{task_id}"
262
+ files_response = requests.get(files_url, timeout=15)
263
+ if files_response.status_code == 200:
264
+ # Save the file and provide its path to the agent
265
+ # This depends on what format the files are returned in
266
+ print(f"Task {task_id} has associated files")
267
+ # Handle files if needed
268
+ except Exception as e:
269
+ print(f"Error checking for files for task {task_id}: {e}")
270
+ # Continue even if file check fails
271
+
272
+ if not task_id or question_text is None:
273
+ print(f"Skipping item with missing task_id or question: {item}")
274
+ continue
275
+
276
+ try:
277
+ # Get full agent response
278
+ full_response = agent(question_text)
279
+
280
+ # Extract just the final answer part for submission
281
+ submitted_answer = extract_final_answer(full_response)
282
+
283
+ # Add to submission payload
284
+ answers_payload.append({
285
+ "task_id": task_id,
286
+ "submitted_answer": submitted_answer,
287
+ "reasoning_trace": full_response # Optional: include full reasoning
288
+ })
289
+
290
+ # Log for display
291
+ results_log.append({
292
+ "Task ID": task_id,
293
+ "Question": question_text,
294
+ "Submitted Answer": submitted_answer,
295
+ "Full Response": full_response
296
+ })
297
+
298
+ print(f"Processed task {task_id}, answer: {submitted_answer}")
299
+
300
+ except Exception as e:
301
+ print(f"Error running agent on task {task_id}: {e}")
302
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
303
+
304
+ if not answers_payload:
305
+ print("Agent did not produce any answers to submit.")
306
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
307
+
308
+ # 4. Prepare Submission
309
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
310
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
311
+ print(status_update)
312
+
313
+ # 5. Submit
314
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
315
+ try:
316
+ response = requests.post(submit_url, json=submission_data, timeout=60)
317
+ response.raise_for_status()
318
+ result_data = response.json()
319
+ final_status = (
320
+ f"Submission Successful!\n"
321
+ f"User: {result_data.get('username')}\n"
322
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
323
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
324
+ f"Message: {result_data.get('message', 'No message received.')}"
325
+ )
326
+ print("Submission successful.")
327
+ results_df = pd.DataFrame(results_log)
328
+ return final_status, results_df
329
+ except requests.exceptions.HTTPError as e:
330
+ error_detail = f"Server responded with status {e.response.status_code}."
331
+ try:
332
+ error_json = e.response.json()
333
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
334
+ except requests.exceptions.JSONDecodeError:
335
+ error_detail += f" Response: {e.response.text[:500]}"
336
+ status_message = f"Submission Failed: {error_detail}"
337
+ print(status_message)
338
+ results_df = pd.DataFrame(results_log)
339
+ return status_message, results_df
340
+ except requests.exceptions.Timeout:
341
+ status_message = "Submission Failed: The request timed out."
342
+ print(status_message)
343
+ results_df = pd.DataFrame(results_log)
344
+ return status_message, results_df
345
+ except requests.exceptions.RequestException as e:
346
+ status_message = f"Submission Failed: Network error - {e}"
347
+ print(status_message)
348
+ results_df = pd.DataFrame(results_log)
349
+ return status_message, results_df
350
+ except Exception as e:
351
+ status_message = f"An unexpected error occurred during submission: {e}"
352
+ print(status_message)
353
+ results_df = pd.DataFrame(results_log)
354
+ return status_message, results_df
355
+
356
+ # --- Build Gradio Interface using Blocks ---
357
+ with gr.Blocks() as demo:
358
+ gr.Markdown("# Smolagent GAIA Evaluation Runner")
359
+ gr.Markdown(
360
+ """
361
+ **Instructions:**
362
+ 1. Log in to your Hugging Face account using the button below.
363
+ 2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
364
+ ---
365
+ **Note:** This process will take some time as the agent processes each question. The agent is specifically configured to
366
+ format answers according to the GAIA benchmark requirements:
367
+ - Numbers: No commas, no units
368
+ - Strings: No articles, no abbreviations
369
+ - Lists: Comma-separated values following the above rules
370
+ """
371
+ )
372
+
373
+ gr.LoginButton()
374
+
375
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
376
+
377
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
378
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
379
+
380
+ run_button.click(
381
+ fn=run_and_submit_all,
382
+ outputs=[status_output, results_table]
383
+ )
384
 
385
  if __name__ == "__main__":
386
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
387
+ # Check for SPACE_HOST and SPACE_ID at startup for information
388
+ space_host_startup = os.getenv("SPACE_HOST")
389
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
390
+
391
+ if space_host_startup:
392
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
393
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
394
+ else:
395
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
396
+
397
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
398
+ print(f"✅ SPACE_ID found: {space_id_startup}")
399
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
400
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
401
+ else:
402
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
403
+
404
+ print("-"*(60 + len(" App Starting ")) + "\n")
405
+
406
+ print("Launching Gradio Interface for Smolagent GAIA Evaluation...")
407
+ demo.launch(debug=True, share=False)