AlexDGenu commited on
Commit
0ab201b
Β·
1 Parent(s): 13118ce

Refactor SmolAgent to integrate OpenAI's API, enhancing question answering capabilities with improved instructions and error handling. Update Gradio interface for GAIA evaluation submission and results display.

Browse files
Files changed (1) hide show
  1. app.py +161 -190
app.py CHANGED
@@ -2,50 +2,60 @@ import os
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
- from smolagents import CodeAgent, InferenceClientModel, DuckDuckGoSearchTool
6
  from dotenv import load_dotenv
7
 
8
- # Load environment variables
 
 
9
  load_dotenv()
10
 
11
  # --- Constants ---
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
- HF_TOKEN = os.getenv("HF_TOKEN")
14
- INSTRUCTIONS = """Your task is to answer the user's question.
15
- Return a number OR as few words as possible OR a comma separated list of numbers and/or strings.
16
- - If you are asked for a number, don't use a comma to write your number, and don't use units like $ or % unless specified otherwise.
17
- - If you are asked for a string, don't use articles or abbreviations (e.g., for cities), and write digits in plain text unless specified otherwise.
18
- - If you are asked for a comma-separated list, apply the above rules to each element.
19
- """
 
 
 
 
 
 
 
 
20
 
21
  # --- Smol Agent Definition ---
22
  class SmolAgent:
23
- def __init__(self, hf_token: str):
24
- print("Initializing SmolAgent with smolagents...")
25
- if not hf_token:
26
- raise ValueError("Hugging Face token not found. Please set HF_TOKEN environment variable.")
27
-
28
- # Initialize the model
29
- model = InferenceClientModel(
30
- model_id="meta-llama/Meta-Llama-3-8B-Instruct",
31
- token=hf_token,
 
32
  )
33
 
34
  # Initialize the agent with tools and instructions
35
  self.agent = CodeAgent(
36
  tools=[DuckDuckGoSearchTool()],
37
- model=model,
38
  instructions=INSTRUCTIONS,
 
39
  )
40
  print("SmolAgent initialized with CodeAgent and DuckDuckGoSearchTool.")
41
 
42
  def __call__(self, question: str) -> str:
43
  print(f"\nπŸͺ Running on question:\n{question}\n")
44
  try:
45
- # The CodeAgent's run method returns the final answer directly
46
  answer = self.agent.run(question)
47
  print(f"βœ… Agent's final answer: {answer}")
48
- return str(answer) # Ensure the output is a string
49
  except Exception as e:
50
  import traceback
51
  traceback.print_exc()
@@ -53,184 +63,145 @@ class SmolAgent:
53
  print(f"❌ {error_message}")
54
  return error_message
55
 
56
-
57
- def run_and_submit_all(profile: gr.OAuthProfile | None):
58
- """
59
- Fetches all questions, runs the SmolAgent on them, submits all answers,
60
- and displays the results.
61
- """
62
- # --- Determine HF Space Runtime URL and Repo URL ---
63
- space_id = os.getenv("SPACE_ID")
64
-
65
- if profile:
66
- username = f"{profile.username}"
67
- print(f"User logged in: {username}")
68
- else:
69
- print("User not logged in.")
70
- return "Please Login to Hugging Face with the button.", None
71
-
72
- api_url = DEFAULT_API_URL
73
- questions_url = f"{api_url}/questions"
74
- submit_url = f"{api_url}/submit"
75
-
76
- # 1. Instantiate Agent
77
  try:
78
- agent = SmolAgent(hf_token=HF_TOKEN)
79
  except Exception as e:
80
- print(f"Error instantiating agent: {e}")
81
- return f"Error initializing agent: {e}", None
82
-
83
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
84
- print(f"Agent code link: {agent_code}")
85
 
86
- # 2. Fetch Questions
87
- print(f"Fetching questions from: {questions_url}")
88
  try:
89
- response = requests.get(questions_url, timeout=15)
90
- response.raise_for_status()
91
- questions_data = response.json()
92
- if not questions_data:
93
- print("Fetched questions list is empty.")
94
- return "Fetched questions list is empty or invalid format.", None
95
- print(f"Fetched {len(questions_data)} questions.")
96
- except requests.exceptions.RequestException as e:
97
- print(f"Error fetching questions: {e}")
98
- return f"Error fetching questions: {e}", None
99
- except requests.exceptions.JSONDecodeError as e:
100
- print(f"Error decoding JSON response from questions endpoint: {e}")
101
- print(f"Response text: {response.text[:500]}")
102
- return f"Error decoding server response for questions: {e}", None
103
- except Exception as e:
104
- print(f"An unexpected error occurred fetching questions: {e}")
105
- return f"An unexpected error occurred fetching questions: {e}", None
106
-
107
- # 3. Run your Agent
108
- results_log = []
109
- answers_payload = []
110
- print(f"Running agent on {len(questions_data)} questions...")
111
- for item in questions_data:
112
- task_id = item.get("task_id")
113
- question_text = item.get("question")
114
- if not task_id or question_text is None:
115
- print(f"Skipping item with missing task_id or question: {item}")
116
- continue
117
  try:
118
- submitted_answer = agent(question_text)
119
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
120
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
121
- except Exception as e:
122
- print(f"Error running agent on task {task_id}: {e}")
123
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
124
 
125
- if not answers_payload:
126
- print("Agent did not produce any answers to submit.")
127
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
128
 
129
- # 4. Prepare Submission
130
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
131
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
132
- print(status_update)
133
 
134
- # 5. Submit
135
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  try:
137
- response = requests.post(submit_url, json=submission_data, timeout=60)
138
- response.raise_for_status()
139
- result_data = response.json()
140
- final_status = (
141
- f"Submission Successful!\n"
142
- f"User: {result_data.get('username')}\n"
143
- f"Overall Score: {result_data.get('score', 'N/A')}% "
144
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
145
- f"Message: {result_data.get('message', 'No message received.')}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  )
147
- print("Submission successful.")
148
- results_df = pd.DataFrame(results_log)
149
- return final_status, results_df
150
- except requests.exceptions.HTTPError as e:
151
- error_detail = f"Server responded with status {e.response.status_code}."
152
- try:
153
- error_json = e.response.json()
154
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
155
- except requests.exceptions.JSONDecodeError:
156
- error_detail += f" Response: {e.response.text[:500]}"
157
- status_message = f"Submission Failed: {error_detail}"
158
- print(status_message)
159
- results_df = pd.DataFrame(results_log)
160
- return status_message, results_df
161
- except requests.exceptions.Timeout:
162
- status_message = "Submission Failed: The request timed out."
163
- print(status_message)
164
- results_df = pd.DataFrame(results_log)
165
- return status_message, results_df
166
- except requests.exceptions.RequestException as e:
167
- status_message = f"Submission Failed: Network error - {e}"
168
- print(status_message)
169
- results_df = pd.DataFrame(results_log)
170
- return status_message, results_df
171
- except Exception as e:
172
- status_message = f"An unexpected error occurred during submission: {e}"
173
- print(status_message)
174
- results_df = pd.DataFrame(results_log)
175
- return status_message, results_df
176
-
177
-
178
- # --- Build Gradio Interface using Blocks ---
179
- with gr.Blocks() as demo:
180
- gr.Markdown("# SmolLM Agent Evaluation Runner")
181
- gr.Markdown(
182
- """
183
- **Instructions:**
184
-
185
- 1. This space uses a `smolagents.CodeAgent` with the `meta-llama/Meta-Llama-3-8B-Instruct` model.
186
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
187
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
188
-
189
- ---
190
- **Model Information:**
191
- - Agent: `smolagents.CodeAgent`
192
- - Model: `meta-llama/Meta-Llama-3-8B-Instruct`
193
- - Tools: `DuckDuckGoSearchTool`
194
-
195
- **Disclaimers:**
196
- 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).
197
- 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.
198
- """
199
- )
200
-
201
- gr.LoginButton()
202
-
203
- run_button = gr.Button("Run Evaluation & Submit All Answers")
204
-
205
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
206
- # Removed max_rows=10 from DataFrame constructor
207
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
208
-
209
- run_button.click(
210
- fn=run_and_submit_all,
211
- outputs=[status_output, results_table]
212
- )
213
 
 
214
  if __name__ == "__main__":
215
- print("\n" + "-"*30 + " App Starting " + "-"*30)
216
- # Check for SPACE_HOST and SPACE_ID at startup for information
217
- space_host_startup = os.getenv("SPACE_HOST")
218
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
219
-
220
- if space_host_startup:
221
- print(f"βœ… SPACE_HOST found: {space_host_startup}")
222
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
223
- else:
224
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
225
-
226
- if space_id_startup: # Print repo URLs if SPACE_ID is found
227
- print(f"βœ… SPACE_ID found: {space_id_startup}")
228
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
229
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
230
- else:
231
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
232
-
233
- print("-"*(60 + len(" App Starting ")) + "\n")
234
-
235
- print("Launching Gradio Interface for Smol Agent Evaluation...")
236
- demo.launch(debug=True, share=False)
 
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
 
5
  from dotenv import load_dotenv
6
 
7
+ from smolagents import CodeAgent, OpenAIServerModel, DuckDuckGoSearchTool
8
+
9
+ # Load environment variables (including OPENAI_API_KEY)
10
  load_dotenv()
11
 
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
15
+
16
+ INSTRUCTIONS = """You are a general AI assistant. I will ask you a question. Report your thoughts, and then provide your final answer.
17
+
18
+ CRITICAL FORMATTING RULES:
19
+ - Your final answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings
20
+ - 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
21
+ - 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
22
+ - 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
23
+ - Be extremely precise with spelling and formatting - the evaluation uses exact matching
24
+ - For strings: no extra spaces, no punctuation unless part of the answer, lowercase
25
+ - For numbers: just the number, no units, no commas, no currency symbols
26
+ - Provide ONLY the answer as your final response, nothing else
27
+
28
+ You have access to a web search tool to help you find accurate information. Use it when you need to look up facts."""
29
 
30
  # --- Smol Agent Definition ---
31
  class SmolAgent:
32
+ def __init__(self):
33
+ print("Initializing SmolAgent with OpenAI model...")
34
+ if not OPENAI_API_KEY:
35
+ raise ValueError("OPENAI_API_KEY not found. Please set it in your environment.")
36
+
37
+ # Initialize the OpenAI-backed model
38
+ self.model = OpenAIServerModel(
39
+ model_id="gpt-4o-mini", # or "gpt-4", "gpt-3.5-turbo", etc.
40
+ api_base="https://api.openai.com/v1",
41
+ api_key=OPENAI_API_KEY,
42
  )
43
 
44
  # Initialize the agent with tools and instructions
45
  self.agent = CodeAgent(
46
  tools=[DuckDuckGoSearchTool()],
47
+ model=self.model,
48
  instructions=INSTRUCTIONS,
49
+ max_steps=7,
50
  )
51
  print("SmolAgent initialized with CodeAgent and DuckDuckGoSearchTool.")
52
 
53
  def __call__(self, question: str) -> str:
54
  print(f"\nπŸͺ Running on question:\n{question}\n")
55
  try:
 
56
  answer = self.agent.run(question)
57
  print(f"βœ… Agent's final answer: {answer}")
58
+ return str(answer)
59
  except Exception as e:
60
  import traceback
61
  traceback.print_exc()
 
63
  print(f"❌ {error_message}")
64
  return error_message
65
 
66
+ def run_gaia_evaluation(username: str):
67
+ """Run the complete GAIA evaluation and submit results"""
68
+ print("πŸš€ GAIA Benchmark Evaluation with ChatGPT")
69
+ print("=" * 60)
70
+
71
+ if not username:
72
+ return "❌ Please provide a username"
73
+
74
+ print(f"πŸ‘€ User: {username}")
75
+
76
+ # Initialize the agent
 
 
 
 
 
 
 
 
 
 
77
  try:
78
+ agent = SmolAgent()
79
  except Exception as e:
80
+ return f"❌ Failed to initialize agent: {e}"
 
 
 
 
81
 
82
+ # Fetch questions
 
83
  try:
84
+ resp = requests.get(f"{DEFAULT_API_URL}/questions", timeout=30)
85
+ resp.raise_for_status()
86
+ data = resp.json()
87
+ questions = data if isinstance(data, list) else data.get("questions", [])
88
+ print(f"πŸ“‹ Loaded {len(questions)} questions")
89
+ except requests.RequestException as e:
90
+ return f"❌ Error fetching questions: {e}"
91
+
92
+ # Process questions
93
+ results = []
94
+ progress_log = []
95
+
96
+ for i, q in enumerate(questions):
97
+ task_id = q["task_id"]
98
+ text = q["question"]
99
+ progress_log.append(f"❓ Question {i+1}: {text}")
100
+ print(f"\n❓ Question {i+1}: {text}")
101
+
 
 
 
 
 
 
 
 
 
 
102
  try:
103
+ result = agent(text)
104
+ result_str = str(result).strip()
 
 
 
 
105
 
106
+ # Take the last line as the answer
107
+ out = result_str.splitlines()[-1] if result_str else "AGENT ERROR: No response."
 
108
 
109
+ if out.startswith("{"):
110
+ out = "AGENT ERROR: No final answer."
 
 
111
 
112
+ out = out.strip().rstrip(".")
113
+ results.append({"task_id": task_id, "submitted_answer": out})
114
+
115
+ progress_log.append(f"βœ… Answer: '{out}'")
116
+ print(f"βœ… Answer: '{out}'")
117
+
118
+ except Exception as e:
119
+ error_msg = f"AGENT ERROR: {e}"
120
+ results.append({"task_id": task_id, "submitted_answer": error_msg})
121
+ progress_log.append(f"❌ Error: {error_msg}")
122
+ print(f"❌ Error: {error_msg}")
123
+
124
+ # Submit results
125
+ payload = {
126
+ "username": username,
127
+ "agent_code": "chatgpt-gpt4o-mini-with-tools",
128
+ "answers": results,
129
+ }
130
+
131
  try:
132
+ print("πŸ“€ Submitting to GAIA leaderboard...")
133
+ post = requests.post(f"{DEFAULT_API_URL}/submit", json=payload, timeout=60)
134
+ post.raise_for_status()
135
+ res = post.json()
136
+
137
+ # Format results for display
138
+ result_summary = f"""
139
+ πŸ† GAIA BENCHMARK RESULTS
140
+ {'=' * 60}
141
+ πŸ‘€ User: {res.get('username', username)}
142
+ πŸ“Š Overall Score: {res.get('score', res.get('overall_score', 'N/A'))}%
143
+ βœ… Correct: {res.get('correct_count', res.get('num_correct', 'N/A'))}/{len(results)}
144
+ πŸ’¬ Message: {res.get('message', 'N/A')}
145
+ {'=' * 60}
146
+ """
147
+
148
+ # Combine progress log with final results
149
+ full_log = "\n".join(progress_log) + "\n" + result_summary
150
+ return full_log
151
+
152
+ except requests.RequestException as e:
153
+ error_msg = f"❌ Error submitting: {e}"
154
+ done = sum(1 for r in results if not r["submitted_answer"].startswith("AGENT ERROR"))
155
+ local_summary = f"πŸ“‹ Completed locally: {done}/{len(results)}"
156
+ return "\n".join(progress_log) + "\n" + error_msg + "\n" + local_summary
157
+
158
+ # --- Gradio Interface ---
159
+ def create_interface():
160
+ with gr.Blocks(title="GAIA Benchmark with ChatGPT", theme=gr.themes.Soft()) as demo:
161
+ gr.Markdown("# πŸš€ GAIA Benchmark Evaluation with ChatGPT")
162
+ gr.Markdown("This app runs the GAIA benchmark using ChatGPT (GPT-4o-mini) with web search capabilities.")
163
+
164
+ with gr.Row():
165
+ with gr.Column(scale=1):
166
+ username_input = gr.Textbox(
167
+ label="Hugging Face Username",
168
+ placeholder="Enter your HF username",
169
+ info="This will be used for the GAIA leaderboard submission"
170
+ )
171
+
172
+ run_button = gr.Button("πŸš€ Run GAIA Evaluation", variant="primary", size="lg")
173
+
174
+ with gr.Column(scale=2):
175
+ output_area = gr.Textbox(
176
+ label="Results & Progress",
177
+ lines=20,
178
+ max_lines=50,
179
+ interactive=False
180
+ )
181
+
182
+ # Event handler
183
+ run_button.click(
184
+ fn=run_gaia_evaluation,
185
+ inputs=[username_input],
186
+ outputs=[output_area]
187
  )
188
+
189
+ gr.Markdown("""
190
+ ### How it works:
191
+ 1. Enter your Hugging Face username
192
+ 2. Click "Run GAIA Evaluation"
193
+ 3. The agent will process all 20 GAIA questions using ChatGPT + web search
194
+ 4. Results will be automatically submitted to the GAIA leaderboard
195
+ 5. Your score will be displayed here
196
+
197
+ ### Requirements:
198
+ - Set `OPENAI_API_KEY` in your environment variables
199
+ - Valid Hugging Face username for leaderboard submission
200
+ """)
201
+
202
+ return demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
204
+ # --- Main execution ---
205
  if __name__ == "__main__":
206
+ demo = create_interface()
207
+ demo.launch()