Imnotchis commited on
Commit
ba04a28
·
verified ·
1 Parent(s): ca9aa47

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -20
app.py CHANGED
@@ -12,7 +12,8 @@ from smolagents import (
12
  OpenAIModel,
13
  WebSearchTool,
14
  VisitWebpageTool,
15
- WikipediaSearchTool
 
16
  )
17
 
18
 
@@ -84,6 +85,9 @@ class BasicAgent:
84
  # Tools
85
  self.tools = [
86
  WebSearchTool(),
 
 
 
87
  WikipediaSearchTool()
88
  ]
89
 
@@ -94,23 +98,57 @@ class BasicAgent:
94
  max_steps=5,
95
  verbosity_level=2,
96
  instructions="""
97
- You are a general-purpose assistant designed to solve GAIA benchmark questions.
98
-
99
- Solve each question carefully and use the available tools when necessary.
100
-
101
- Important rules:
102
- - Carefully follow the exact instructions in the question.
103
- - Use web search and webpage tools when external information is needed.
104
- - Verify information when possible.
105
- - Perform calculations carefully.
106
- - Do not guess when information can be verified.
107
- - Your final answer must be concise and directly answer the question.
108
- - Do not include explanations, reasoning, citations, tables, or extra text in the final answer unless explicitly requested.
109
- - If the answer is a number, return only the number.
110
- - If the answer is a name, return only the name.
111
- - If the question requests a specific format, follow that format exactly.
112
- """
113
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
  def __call__(self, question: str) -> str:
116
 
@@ -122,14 +160,29 @@ class BasicAgent:
122
  try:
123
  answer = self.agent.run(question)
124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  print(
126
  f"Agent answer: {answer}"
127
  )
 
 
 
128
  except Exception as e:
129
  print(f"Agent error: {e}")
130
  raise
131
-
132
- return str(answer)
133
  def run_and_submit_all( profile: gr.OAuthProfile | None):
134
  """
135
  Fetches all questions, runs the BasicAgent on them, submits all answers,
@@ -195,6 +248,10 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
195
  continue
196
  try:
197
  submitted_answer = agent(question_text)
 
 
 
 
198
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
199
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
200
  except Exception as e:
@@ -205,6 +262,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
205
  print("Agent did not produce any answers to submit.")
206
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
207
 
 
 
 
 
 
 
 
208
  # 4. Prepare Submission
209
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
210
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
 
12
  OpenAIModel,
13
  WebSearchTool,
14
  VisitWebpageTool,
15
+ WikipediaSearchTool,
16
+ PythonInterpreterTool
17
  )
18
 
19
 
 
85
  # Tools
86
  self.tools = [
87
  WebSearchTool(),
88
+ PythonInterpreterTool(
89
+ authorized_imports=["math", "re", "datetime", "collections"]
90
+ ),
91
  WikipediaSearchTool()
92
  ]
93
 
 
98
  max_steps=5,
99
  verbosity_level=2,
100
  instructions="""
101
+ You are an intelligent AI agent designed to solve GAIA benchmark questions accurately and efficiently.
102
+
103
+ Your goal is to produce the correct final answer while minimizing unnecessary tool calls and token usage.
104
+
105
+ GENERAL RULES:
106
+ - Read the entire question carefully before taking any action.
107
+ - Follow all constraints and output formatting requirements.
108
+ - Reason carefully and verify uncertain information.
109
+ - Never fabricate facts, sources, or tool results.
110
+ - Use only information available to you and your tools.
111
+ - Do not assume missing attachments or inaccessible content have been examined.
112
+
113
+ TOOL SELECTION:
114
+ - Before using a tool, determine what information is actually needed.
115
+ - Select the most appropriate tool for the question.
116
+ - For questions explicitly referencing Wikipedia, prefer wikipedia_search.
117
+ - Use web_search when external information must be discovered.
118
+ - Do not use tools for simple questions that can be answered reliably without them.
119
+ - Avoid repeatedly switching between tools without a clear reason.
120
+ - Do not repeat the same search query if it has already failed.
121
+ - If a search fails, try a shorter or broader query.
122
+ - Use additional tools only when necessary to obtain missing evidence.
123
+
124
+ TOKEN EFFICIENCY:
125
+ - Minimize unnecessary model calls and tool invocations.
126
+ - Do not repeat information already available in tool observations.
127
+ - Avoid redundant searches and excessive verification.
128
+ - If the available evidence is sufficient, stop searching.
129
+ - Prefer focused search queries over long keyword lists.
130
+ - Do not spend additional steps researching an already resolved question.
131
+
132
+ ERROR HANDLING:
133
+ - If a tool returns no results, reconsider the search strategy.
134
+ - If a website returns HTTP 403, consider another accessible source.
135
+ - Do not repeatedly call a tool that is consistently failing.
136
+ - Do not invent an answer to compensate for failed tools.
137
+
138
+ FINAL ANSWER:
139
+ - When the answer is determined, invoke the final_answer tool.
140
+ - Use the native tool calling mechanism to invoke final_answer.
141
+ - Do not output a textual JSON representation of a tool call.
142
+ - The final answer must directly answer the question.
143
+ - Return only the requested answer without explanations, citations, or extra commentary.
144
+ - If the answer is a number, return only the number.
145
+ - If the answer is a city, return its full city name.
146
+ - If the answer is a person, return only the person's name.
147
+ - If the question requires a specific format, follow it exactly.
148
+ - Do not include markdown formatting unless requested.
149
+ - Do not call additional tools after obtaining sufficient evidence.
150
+ """
151
+ )
152
 
153
  def __call__(self, question: str) -> str:
154
 
 
160
  try:
161
  answer = self.agent.run(question)
162
 
163
+ if answer is None:
164
+ raise ValueError("Agent returned None")
165
+
166
+ if isinstance(answer, list):
167
+ raise ValueError(f"Invalid agent output: {answer}")
168
+
169
+ if not isinstance(answer, (str, int, float)):
170
+ raise TypeError(f"Invalid answer type: {type(answer).__name__}")
171
+
172
+ answer = str(answer).strip()
173
+
174
+ if not answer or "Error in generating final LLM output" in answer or "tool_use_failed" in answer:
175
+ raise ValueError(f"Invalid agent answer: {answer}")
176
+
177
  print(
178
  f"Agent answer: {answer}"
179
  )
180
+
181
+ return answer
182
+
183
  except Exception as e:
184
  print(f"Agent error: {e}")
185
  raise
 
 
186
  def run_and_submit_all( profile: gr.OAuthProfile | None):
187
  """
188
  Fetches all questions, runs the BasicAgent on them, submits all answers,
 
248
  continue
249
  try:
250
  submitted_answer = agent(question_text)
251
+ if submitted_answer is None:
252
+ raise ValueError("Submitted answer is None")
253
+ if not isinstance(submitted_answer, (str, int, float)):
254
+ raise TypeError("Submitted answer has invalid type")
255
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
256
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
257
  except Exception as e:
 
262
  print("Agent did not produce any answers to submit.")
263
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
264
 
265
+ if len(answers_payload) != len(questions_data):
266
+ print(f"Only {len(answers_payload)}/{len(questions_data)} valid answers.")
267
+ return (
268
+ f"Evaluation incomplete: {len(answers_payload)}/{len(questions_data)} valid answers. Submission cancelled.",
269
+ pd.DataFrame(results_log)
270
+ )
271
+
272
  # 4. Prepare Submission
273
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
274
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."