ghanemfaouri commited on
Commit
ce2ebf0
·
verified ·
1 Parent(s): c86d0ef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -140
app.py CHANGED
@@ -4,119 +4,88 @@ import requests
4
  import pandas as pd
5
  import re
6
  from openai import OpenAI
7
- from langchain_community.tools import DuckDuckGoSearchRun
8
- from langchain.agents import Tool, AgentExecutor, create_react_agent
9
- from langchain import hub
10
- from langchain.chains import LLMMathChain
11
- from langchain_community.utilities import WikipediaAPIWrapper
12
- from langchain_community.chat_models import ChatOpenAI
13
- from langchain.memory import ConversationBufferMemory
14
- from langchain.prompts import PromptTemplate
15
 
16
  # --- Constants ---
17
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  # --- Enhanced Agent Definition ---
20
- class AdvancedAgent:
21
  def __init__(self):
22
- print("AdvancedAgent initialized with enhanced capabilities")
23
-
24
- # Initialize OpenAI client with API key
25
  self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
26
-
27
- # Create tools for the agent
28
- self.tools = self.create_tools()
29
-
30
- # Create the agent executor
31
- self.agent_executor = self.create_agent_executor()
32
-
33
- # Set up answer extraction patterns
34
  self.answer_patterns = [
35
  r"FINAL ANSWER:\s*(.+)",
36
  r"Final Answer:\s*(.+)",
37
- r"Answer:\s*(.+)",
38
- r"\[ANSWER\]:\s*(.+)"
39
- ]
40
-
41
- def create_tools(self):
42
- """Create a comprehensive set of tools for the agent"""
43
- llm = ChatOpenAI(temperature=0, model="gpt-4-turbo")
44
-
45
- # Create tools
46
- search = DuckDuckGoSearchRun()
47
- calculator = LLMMathChain.from_llm(llm=llm)
48
- wikipedia = WikipediaAPIWrapper()
49
-
50
- return [
51
- Tool(
52
- name="Web Search",
53
- func=search.run,
54
- description="Useful for finding current information online"
55
- ),
56
- Tool(
57
- name="Calculator",
58
- func=calculator.run,
59
- description="Useful for solving math problems and calculations"
60
- ),
61
- Tool(
62
- name="Wikipedia",
63
- func=wikipedia.run,
64
- description="Useful for factual information about people, places, and historical events"
65
- )
66
  ]
67
 
68
- def create_agent_executor(self):
69
- """Create a ReAct agent with enhanced reasoning capabilities"""
70
- llm = ChatOpenAI(temperature=0, model="gpt-4-turbo")
71
-
72
- # Custom prompt template for GAIA benchmark
73
- prompt_template = """
74
- You are an expert AI solving GAIA benchmark questions. Follow these rules:
75
-
76
- 1. ALWAYS think step-by-step
77
- 2. Use tools for factual verification
78
- 3. Format final answers EXACTLY as required:
79
- - Numbers: Plain digits without commas/units (e.g., 1500000)
80
- - Strings: Minimal words, no articles/abbreviations
81
- - Lists: Comma-separated values without spaces (e.g., red,blue,green)
82
-
83
- 4. For multiple-choice: Select the letter (e.g., A, B, C)
84
- 5. Verify units and formats match question requirements
85
- 6. When uncertain, research using tools
86
- 7. End with: FINAL ANSWER: [Your Answer]
87
-
88
- Current conversation:
89
- {chat_history}
90
-
91
- Question: {input}
92
- {agent_scratchpad}"""
93
-
94
- prompt = PromptTemplate.from_template(prompt_template)
95
- memory = ConversationBufferMemory(memory_key="chat_history")
96
-
97
- agent = create_react_agent(llm, self.tools, prompt)
98
- return AgentExecutor(agent=agent, tools=self.tools,
99
- memory=memory, verbose=True,
100
- handle_parsing_errors=True,
101
- max_iterations=5)
102
 
103
  def __call__(self, question: str) -> str:
104
  """Process a question and return formatted answer"""
105
  print(f"Processing: {question[:60]}...")
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  try:
108
- # Run through agent executor
109
- response = self.agent_executor.invoke({"input": question})
110
- raw_answer = response["output"]
 
 
 
 
111
 
112
- # Extract final answer
113
  final_answer = self.extract_final_answer(raw_answer)
114
  print(f"Final answer: {final_answer}")
115
  return final_answer
116
  except Exception as e:
117
- print(f"Agent error: {str(e)}")
118
- # Fallback to direct GPT-4-turbo call
119
- return self.fallback_gpt_call(question)
120
 
121
  def extract_final_answer(self, response: str) -> str:
122
  """Robust extraction of final answer from response"""
@@ -132,34 +101,17 @@ class AdvancedAgent:
132
  return lines[-1].strip()
133
  return response.strip()
134
 
135
- def fallback_gpt_call(self, question: str) -> str:
136
- """Direct GPT-4 call when agent fails"""
137
- try:
138
- response = self.client.chat.completions.create(
139
- model="gpt-4-turbo",
140
- messages=[
141
- {"role": "system", "content": "Answer concisely in GAIA format. End with FINAL ANSWER: [Your Answer]"},
142
- {"role": "user", "content": question}
143
- ],
144
- temperature=0.1,
145
- max_tokens=300
146
- )
147
- return self.extract_final_answer(response.choices[0].message.content)
148
- except Exception as e:
149
- print(f"Fallback GPT error: {str(e)}")
150
- return "Error: Could not generate answer"
151
-
152
  # --- Updated Submission Function ---
153
  def run_and_submit_all(profile: gr.OAuthProfile | None):
154
  """
155
- Fetches all questions, runs the AdvancedAgent on them, submits all answers,
156
  and displays the results.
157
  """
158
  # --- Determine HF Space Runtime URL and Repo URL ---
159
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
160
 
161
  if profile:
162
- username= f"{profile.username}"
163
  print(f"User logged in: {username}")
164
  else:
165
  print("User not logged in.")
@@ -171,11 +123,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
171
 
172
  # 1. Instantiate Agent
173
  try:
174
- agent = AdvancedAgent()
175
  except Exception as e:
176
  print(f"Error instantiating agent: {e}")
177
  return f"Error initializing agent: {e}", None
178
- # 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)
179
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
180
  print(agent_code)
181
 
@@ -186,16 +138,12 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
186
  response.raise_for_status()
187
  questions_data = response.json()
188
  if not questions_data:
189
- print("Fetched questions list is empty.")
190
- return "Fetched questions list is empty or invalid format.", None
191
  print(f"Fetched {len(questions_data)} questions.")
192
  except requests.exceptions.RequestException as e:
193
  print(f"Error fetching questions: {e}")
194
  return f"Error fetching questions: {e}", None
195
- except requests.exceptions.JSONDecodeError as e:
196
- print(f"Error decoding JSON response from questions endpoint: {e}")
197
- print(f"Response text: {response.text[:500]}")
198
- return f"Error decoding server response for questions: {e}", None
199
  except Exception as e:
200
  print(f"An unexpected error occurred fetching questions: {e}")
201
  return f"An unexpected error occurred fetching questions: {e}", None
@@ -215,8 +163,8 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
215
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
216
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
217
  except Exception as e:
218
- print(f"Error running agent on task {task_id}: {e}")
219
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
220
 
221
  if not answers_payload:
222
  print("Agent did not produce any answers to submit.")
@@ -248,29 +196,18 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
248
  try:
249
  error_json = e.response.json()
250
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
251
- except requests.exceptions.JSONDecodeError:
252
  error_detail += f" Response: {e.response.text[:500]}"
253
  status_message = f"Submission Failed: {error_detail}"
254
  print(status_message)
255
  results_df = pd.DataFrame(results_log)
256
  return status_message, results_df
257
- except requests.exceptions.Timeout:
258
- status_message = "Submission Failed: The request timed out."
259
- print(status_message)
260
- results_df = pd.DataFrame(results_log)
261
- return status_message, results_df
262
- except requests.exceptions.RequestException as e:
263
- status_message = f"Submission Failed: Network error - {e}"
264
- print(status_message)
265
- results_df = pd.DataFrame(results_log)
266
- return status_message, results_df
267
  except Exception as e:
268
  status_message = f"An unexpected error occurred during submission: {e}"
269
  print(status_message)
270
  results_df = pd.DataFrame(results_log)
271
  return status_message, results_df
272
 
273
-
274
  # --- Build Gradio Interface using Blocks ---
275
  with gr.Blocks() as demo:
276
  gr.Markdown("# GAIA Benchmark Agent")
@@ -291,27 +228,23 @@ with gr.Blocks() as demo:
291
  outputs=[status_output, results_table]
292
  )
293
 
294
-
295
  if __name__ == "__main__":
296
  print("\n" + "-"*30 + " GAIA Agent Starting " + "-"*30)
297
- # Check for SPACE_HOST and SPACE_ID at startup for information
298
  space_host_startup = os.getenv("SPACE_HOST")
299
  space_id_startup = os.getenv("SPACE_ID")
300
 
301
  if space_host_startup:
302
  print(f"✅ SPACE_HOST found: {space_host_startup}")
303
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
304
  else:
305
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
306
 
307
  if space_id_startup:
308
  print(f"✅ SPACE_ID found: {space_id_startup}")
309
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
310
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
311
  else:
312
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
313
 
314
  print("-"*(60 + len(" GAIA Agent Starting ")) + "\n")
315
-
316
- print("Launching Gradio Interface for GAIA Benchmark Agent...")
317
  demo.launch(debug=True, share=False)
 
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
+ - Numbers: Plain digits without commas/units (e.g., 1500000)
16
+ - Strings: Minimal words, no articles/abbreviations
17
+ - Lists: Comma-separated values without spaces
18
+ - Multiple choice: Single uppercase letter (e.g., A)
19
+ 3. For calculations, show your work then box the final answer
20
+ 4. When uncertain, search online for verification
21
+ 5. ALWAYS end with: FINAL ANSWER: [Your Answer]
22
+ """
23
 
24
  # --- Enhanced Agent Definition ---
25
+ class GaiaAgent:
26
  def __init__(self):
27
+ print("GaiaAgent initialized")
 
 
28
  self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
 
 
 
 
 
 
 
 
29
  self.answer_patterns = [
30
  r"FINAL ANSWER:\s*(.+)",
31
  r"Final Answer:\s*(.+)",
32
+ r"\[ANSWER\]:\s*(.+)",
33
+ r"Answer:\s*(.+)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  ]
35
 
36
+ def web_search(self, query: str, max_results: int = 3) -> str:
37
+ """Perform web search and return results as string"""
38
+ try:
39
+ with DDGS() as ddgs:
40
+ results = [r for r in ddgs.text(query, max_results=max_results)]
41
+ return "\n".join([f"{i+1}. {res['title']}: {res['body']}" for i, res in enumerate(results)])
42
+ except Exception as e:
43
+ print(f"Search error: {str(e)}")
44
+ return ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  def __call__(self, question: str) -> str:
47
  """Process a question and return formatted answer"""
48
  print(f"Processing: {question[:60]}...")
49
 
50
+ # Step 1: Perform web search if needed
51
+ needs_search = any(word in question.lower() for word in
52
+ ["current", "recent", "today", "latest", "who is", "what is"])
53
+ search_results = ""
54
+ if needs_search:
55
+ search_query = f"{question} -site:reddit.com -site:quora.com"
56
+ search_results = self.web_search(search_query)
57
+ if search_results:
58
+ print(f"Found {len(search_results.splitlines())} search results")
59
+
60
+ # Step 2: Generate prompt
61
+ messages = [
62
+ {"role": "system", "content": GAIA_SYSTEM_PROMPT},
63
+ {"role": "user", "content": question}
64
+ ]
65
+
66
+ if search_results:
67
+ messages.insert(1, {
68
+ "role": "system",
69
+ "content": f"Search Results:\n{search_results}"
70
+ })
71
+
72
+ # Step 3: Get model response
73
  try:
74
+ response = self.client.chat.completions.create(
75
+ model="gpt-4-turbo",
76
+ messages=messages,
77
+ temperature=0.1,
78
+ max_tokens=500
79
+ )
80
+ raw_answer = response.choices[0].message.content
81
 
82
+ # Step 4: Extract final answer
83
  final_answer = self.extract_final_answer(raw_answer)
84
  print(f"Final answer: {final_answer}")
85
  return final_answer
86
  except Exception as e:
87
+ print(f"GPT error: {str(e)}")
88
+ return "Error: Could not generate answer"
 
89
 
90
  def extract_final_answer(self, response: str) -> str:
91
  """Robust extraction of final answer from response"""
 
101
  return lines[-1].strip()
102
  return response.strip()
103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  # --- Updated Submission Function ---
105
  def run_and_submit_all(profile: gr.OAuthProfile | None):
106
  """
107
+ Fetches all questions, runs the GaiaAgent on them, submits all answers,
108
  and displays the results.
109
  """
110
  # --- Determine HF Space Runtime URL and Repo URL ---
111
+ space_id = os.getenv("SPACE_ID")
112
 
113
  if profile:
114
+ username = f"{profile.username}"
115
  print(f"User logged in: {username}")
116
  else:
117
  print("User not logged in.")
 
123
 
124
  # 1. Instantiate Agent
125
  try:
126
+ agent = GaiaAgent()
127
  except Exception as e:
128
  print(f"Error instantiating agent: {e}")
129
  return f"Error initializing agent: {e}", None
130
+
131
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
132
  print(agent_code)
133
 
 
138
  response.raise_for_status()
139
  questions_data = response.json()
140
  if not questions_data:
141
+ print("Fetched questions list is empty.")
142
+ return "Fetched questions list is empty or invalid format.", None
143
  print(f"Fetched {len(questions_data)} questions.")
144
  except requests.exceptions.RequestException as e:
145
  print(f"Error fetching questions: {e}")
146
  return f"Error fetching questions: {e}", None
 
 
 
 
147
  except Exception as e:
148
  print(f"An unexpected error occurred fetching questions: {e}")
149
  return f"An unexpected error occurred fetching questions: {e}", None
 
163
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
164
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
165
  except Exception as e:
166
+ print(f"Error running agent on task {task_id}: {e}")
167
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
168
 
169
  if not answers_payload:
170
  print("Agent did not produce any answers to submit.")
 
196
  try:
197
  error_json = e.response.json()
198
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
199
+ except:
200
  error_detail += f" Response: {e.response.text[:500]}"
201
  status_message = f"Submission Failed: {error_detail}"
202
  print(status_message)
203
  results_df = pd.DataFrame(results_log)
204
  return status_message, results_df
 
 
 
 
 
 
 
 
 
 
205
  except Exception as e:
206
  status_message = f"An unexpected error occurred during submission: {e}"
207
  print(status_message)
208
  results_df = pd.DataFrame(results_log)
209
  return status_message, results_df
210
 
 
211
  # --- Build Gradio Interface using Blocks ---
212
  with gr.Blocks() as demo:
213
  gr.Markdown("# GAIA Benchmark Agent")
 
228
  outputs=[status_output, results_table]
229
  )
230
 
 
231
  if __name__ == "__main__":
232
  print("\n" + "-"*30 + " GAIA Agent Starting " + "-"*30)
 
233
  space_host_startup = os.getenv("SPACE_HOST")
234
  space_id_startup = os.getenv("SPACE_ID")
235
 
236
  if space_host_startup:
237
  print(f"✅ SPACE_HOST found: {space_host_startup}")
238
+ print(f" Runtime URL: https://{space_host_startup}.hf.space")
239
  else:
240
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?)")
241
 
242
  if space_id_startup:
243
  print(f"✅ SPACE_ID found: {space_id_startup}")
244
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
 
245
  else:
246
+ print("ℹ️ SPACE_ID environment variable not found (running locally?)")
247
 
248
  print("-"*(60 + len(" GAIA Agent Starting ")) + "\n")
249
+ print("Launching Gradio Interface...")
 
250
  demo.launch(debug=True, share=False)