ghanemfaouri commited on
Commit
c45a8b7
·
verified ·
1 Parent(s): 26a1714

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -101
app.py CHANGED
@@ -1,91 +1,49 @@
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
- import re
6
- from openai import OpenAI
7
- from duckduckgo_search import DDGS
8
 
 
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
- GAIA_SYSTEM_PROMPT = """
12
- You are an expert at solving GAIA benchmark questions. Follow these rules:
13
- 1. Think step-by-step before answering
14
- 2. Format answers EXACTLY as required
15
- 3. Use web search when needed
16
- 4. ALWAYS end with: FINAL ANSWER: [Your Answer]
17
- """
18
-
19
- class GaiaAgent:
20
- def __init__(self):
21
- print("Initializing GAIA Agent")
22
- self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
23
- self.answer_patterns = [
24
- r"FINAL ANSWER:\s*(.+)",
25
- r"Final Answer:\s*(.+)",
26
- r"Answer:\s*(.+)"
27
- ]
28
-
29
- def web_search(self, query: str) -> str:
30
- """Simple web search implementation"""
31
- try:
32
- with DDGS() as ddgs:
33
- results = [r for r in ddgs.text(query, max_results=3)]
34
- return "\n".join([f"{i+1}. {res['title']}: {res['body']}" for i, res in enumerate(results)])
35
- except Exception as e:
36
- print(f"Search error: {str(e)}")
37
- return ""
38
 
39
- def __call__(self, question: str) -> str:
40
- """Handle question answering"""
41
- print(f"Processing: {question[:60]}...")
42
-
43
- # Determine if we need web search
44
- needs_search = any(word in question.lower() for word in
45
- ["current", "recent", "today", "latest", "who is", "what is"])
46
-
47
- context = self.web_search(question) if needs_search else ""
48
-
49
- messages = [
50
- {"role": "system", "content": GAIA_SYSTEM_PROMPT},
51
- {"role": "user", "content": question}
52
- ]
53
-
54
- if context:
55
- messages.insert(1, {"role": "system", "content": f"Search Results:\n{context}"})
56
-
57
- try:
58
- response = self.client.chat.completions.create(
59
- model="gpt-4-turbo",
60
- messages=messages,
61
- temperature=0.1,
62
- max_tokens=500
63
- )
64
- return self.extract_final_answer(response.choices[0].message.content)
65
- except Exception as e:
66
- print(f"GPT error: {str(e)}")
67
- return "Error: Could not generate answer"
68
-
69
- def extract_final_answer(self, response: str) -> str:
70
- """Extract the final answer from the response"""
71
- for pattern in self.answer_patterns:
72
- match = re.search(pattern, response, re.IGNORECASE)
73
- if match:
74
- answer = match.group(1).strip()
75
- # Clean up the answer
76
- answer = re.sub(r"[^a-zA-Z0-9,. ]", "", answer)
77
- return answer[:200] # Limit length
78
 
79
- # Fallback: return the last line
80
- lines = response.strip().split('\n')
81
- return lines[-1].strip() if lines else "No answer found"
82
-
83
- def run_and_submit_all(profile: gr.OAuthProfile | None):
84
- """Handle the full submission process"""
85
- space_id = os.getenv("SPACE_ID")
 
 
 
 
 
 
86
 
87
  if profile:
88
- username = f"{profile.username}"
89
  print(f"User logged in: {username}")
90
  else:
91
  print("User not logged in.")
@@ -95,74 +53,150 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
95
  questions_url = f"{api_url}/questions"
96
  submit_url = f"{api_url}/submit"
97
 
 
98
  try:
99
- agent = GaiaAgent()
100
  except Exception as e:
101
  print(f"Error instantiating agent: {e}")
102
  return f"Error initializing agent: {e}", None
103
-
104
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
105
 
 
 
106
  try:
107
  response = requests.get(questions_url, timeout=15)
108
  response.raise_for_status()
109
  questions_data = response.json()
110
  if not questions_data:
111
- return "Fetched questions list is empty.", None
 
112
  print(f"Fetched {len(questions_data)} questions.")
113
- except Exception as e:
 
114
  return f"Error fetching questions: {e}", None
 
 
 
 
 
 
 
115
 
 
116
  results_log = []
117
  answers_payload = []
 
118
  for item in questions_data:
119
  task_id = item.get("task_id")
120
  question_text = item.get("question")
121
  if not task_id or question_text is None:
 
122
  continue
123
  try:
124
  submitted_answer = agent(question_text)
125
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
126
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
127
  except Exception as e:
128
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
129
 
130
  if not answers_payload:
131
- return "Agent did not produce any answers.", pd.DataFrame(results_log)
 
132
 
133
- submission_data = {
134
- "username": username.strip(),
135
- "agent_code": agent_code,
136
- "answers": answers_payload
137
- }
138
 
 
 
139
  try:
140
  response = requests.post(submit_url, json=submission_data, timeout=60)
141
  response.raise_for_status()
142
  result_data = response.json()
143
  final_status = (
144
  f"Submission Successful!\n"
145
- f"Score: {result_data.get('score', 'N/A')}% "
146
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)"
 
 
147
  )
148
- return final_status, pd.DataFrame(results_log)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  except Exception as e:
150
- return f"Submission Failed: {str(e)}", pd.DataFrame(results_log)
 
 
 
 
151
 
 
152
  with gr.Blocks() as demo:
153
- gr.Markdown("# GAIA Benchmark Agent")
154
- gr.Markdown("Run the agent to answer GAIA benchmark questions")
155
-
 
 
 
 
156
  gr.LoginButton()
157
- run_button = gr.Button("Run Evaluation")
158
- status_output = gr.Textbox(label="Status", lines=3)
159
- results_table = gr.DataFrame(label="Results")
160
-
 
 
 
161
  run_button.click(
162
  fn=run_and_submit_all,
163
  outputs=[status_output, results_table]
164
  )
165
 
166
  if __name__ == "__main__":
167
- print("Starting GAIA Agent...")
168
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import gradio as gr
3
  import requests
4
+ import inspect
5
  import pandas as pd
6
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
 
 
7
 
8
+ # (Keep Constants and BasicAgent class as is)
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ # --- Basic Agent Definition ---
13
+ class BasicAgent:
14
+ def __init__(self):
15
+ print("BasicAgent initialized.")
16
+ self.agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=HfApiModel())
17
+
18
+ SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and
19
+ finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
20
+ YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated
21
+ list of numbers and/or strings.
22
+ If you are asked for a number, don't use comma to write your number neither use units such as $ or
23
+ percent sign unless specified otherwise.
24
+ If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the
25
+ digits in plain text unless specified otherwise.
26
+ If you are asked for a comma separated list, apply the above rules depending of whether the element
27
+ to be put in the list is a number or a string.
28
+ """
29
+ self.agent.prompt_templates["system_prompt"] = self.agent.prompt_templates["system_prompt"] + SYSTEM_PROMPT
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ def __call__(self, question: str) -> str:
32
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
33
+ final_answer = self.agent.run(question)
34
+ print(f"Agent returning final answer: {final_answer}")
35
+ return final_answer
36
+
37
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
38
+ """
39
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
40
+ and displays the results.
41
+ """
42
+ # --- Determine HF Space Runtime URL and Repo URL ---
43
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
44
 
45
  if profile:
46
+ username= f"{profile.username}"
47
  print(f"User logged in: {username}")
48
  else:
49
  print("User not logged in.")
 
53
  questions_url = f"{api_url}/questions"
54
  submit_url = f"{api_url}/submit"
55
 
56
+ # 1. Instantiate Agent ( modify this part to create your agent)
57
  try:
58
+ agent = BasicAgent()
59
  except Exception as e:
60
  print(f"Error instantiating agent: {e}")
61
  return f"Error initializing agent: {e}", None
62
+ # 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)
63
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
64
+ print(agent_code)
65
 
66
+ # 2. Fetch Questions
67
+ print(f"Fetching questions from: {questions_url}")
68
  try:
69
  response = requests.get(questions_url, timeout=15)
70
  response.raise_for_status()
71
  questions_data = response.json()
72
  if not questions_data:
73
+ print("Fetched questions list is empty.")
74
+ return "Fetched questions list is empty or invalid format.", None
75
  print(f"Fetched {len(questions_data)} questions.")
76
+ except requests.exceptions.RequestException as e:
77
+ print(f"Error fetching questions: {e}")
78
  return f"Error fetching questions: {e}", None
79
+ except requests.exceptions.JSONDecodeError as e:
80
+ print(f"Error decoding JSON response from questions endpoint: {e}")
81
+ print(f"Response text: {response.text[:500]}")
82
+ return f"Error decoding server response for questions: {e}", None
83
+ except Exception as e:
84
+ print(f"An unexpected error occurred fetching questions: {e}")
85
+ return f"An unexpected error occurred fetching questions: {e}", None
86
 
87
+ # 3. Run your Agent
88
  results_log = []
89
  answers_payload = []
90
+ print(f"Running agent on {len(questions_data)} questions...")
91
  for item in questions_data:
92
  task_id = item.get("task_id")
93
  question_text = item.get("question")
94
  if not task_id or question_text is None:
95
+ print(f"Skipping item with missing task_id or question: {item}")
96
  continue
97
  try:
98
  submitted_answer = agent(question_text)
99
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
100
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
101
  except Exception as e:
102
+ print(f"Error running agent on task {task_id}: {e}")
103
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
104
 
105
  if not answers_payload:
106
+ print("Agent did not produce any answers to submit.")
107
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
108
 
109
+ # 4. Prepare Submission
110
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
111
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
112
+ print(status_update)
 
113
 
114
+ # 5. Submit
115
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
116
  try:
117
  response = requests.post(submit_url, json=submission_data, timeout=60)
118
  response.raise_for_status()
119
  result_data = response.json()
120
  final_status = (
121
  f"Submission Successful!\n"
122
+ f"User: {result_data.get('username')}\n"
123
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
124
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
125
+ f"Message: {result_data.get('message', 'No message received.')}"
126
  )
127
+ print("Submission successful.")
128
+ results_df = pd.DataFrame(results_log)
129
+ return final_status, results_df
130
+ except requests.exceptions.HTTPError as e:
131
+ error_detail = f"Server responded with status {e.response.status_code}."
132
+ try:
133
+ error_json = e.response.json()
134
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
135
+ except requests.exceptions.JSONDecodeError:
136
+ error_detail += f" Response: {e.response.text[:500]}"
137
+ status_message = f"Submission Failed: {error_detail}"
138
+ print(status_message)
139
+ results_df = pd.DataFrame(results_log)
140
+ return status_message, results_df
141
+ except requests.exceptions.Timeout:
142
+ status_message = "Submission Failed: The request timed out."
143
+ print(status_message)
144
+ results_df = pd.DataFrame(results_log)
145
+ return status_message, results_df
146
+ except requests.exceptions.RequestException as e:
147
+ status_message = f"Submission Failed: Network error - {e}"
148
+ print(status_message)
149
+ results_df = pd.DataFrame(results_log)
150
+ return status_message, results_df
151
  except Exception as e:
152
+ status_message = f"An unexpected error occurred during submission: {e}"
153
+ print(status_message)
154
+ results_df = pd.DataFrame(results_log)
155
+ return status_message, results_df
156
+
157
 
158
+ # --- Build Gradio Interface using Blocks ---
159
  with gr.Blocks() as demo:
160
+ gr.Markdown("# Basic Agent Evaluation Runner")
161
+ gr.Markdown(
162
+ "Please clone this space, then modify the code to define your agent's logic within the BasicAgent class. "
163
+ "Log in to your Hugging Face account using the button below. This uses your HF username for submission. "
164
+ "Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score."
165
+ )
166
+
167
  gr.LoginButton()
168
+
169
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
170
+
171
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
172
+ # Removed max_rows=10 from DataFrame constructor
173
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
174
+
175
  run_button.click(
176
  fn=run_and_submit_all,
177
  outputs=[status_output, results_table]
178
  )
179
 
180
  if __name__ == "__main__":
181
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
182
+ # Check for SPACE_HOST and SPACE_ID at startup for information
183
+ space_host_startup = os.getenv("SPACE_HOST")
184
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
185
+
186
+ if space_host_startup:
187
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
188
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
189
+ else:
190
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
191
+
192
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
193
+ print(f"✅ SPACE_ID found: {space_id_startup}")
194
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
195
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
196
+ else:
197
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
198
+
199
+ print("-"*(60 + len(" App Starting ")) + "\n")
200
+
201
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
202
+ demo.launch(debug=True, share=False)