Files changed (1) hide show
  1. app.py +265 -168
app.py CHANGED
@@ -1,196 +1,293 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
 
 
6
 
7
- # (Keep Constants as is)
8
- # --- Constants ---
9
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
- class BasicAgent:
14
  def __init__(self):
15
- print("BasicAgent initialized.")
 
 
 
 
 
 
 
 
 
 
 
16
  def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
21
-
22
- def run_and_submit_all( profile: gr.OAuthProfile | None):
23
- """
24
- Fetches all questions, runs the BasicAgent on them, submits all answers,
25
- and displays the results.
26
- """
27
- # --- Determine HF Space Runtime URL and Repo URL ---
28
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- if profile:
31
- username= f"{profile.username}"
32
- print(f"User logged in: {username}")
33
- else:
34
- print("User not logged in.")
35
- return "Please Login to Hugging Face with the button.", None
36
 
37
- api_url = DEFAULT_API_URL
38
- questions_url = f"{api_url}/questions"
39
- submit_url = f"{api_url}/submit"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- # 1. Instantiate Agent ( modify this part to create your agent)
42
- try:
43
- agent = BasicAgent()
44
- except Exception as e:
45
- print(f"Error instantiating agent: {e}")
46
- return f"Error initializing agent: {e}", None
47
- # 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)
48
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
- print(agent_code)
50
 
51
- # 2. Fetch Questions
52
- print(f"Fetching questions from: {questions_url}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  try:
54
- response = requests.get(questions_url, timeout=15)
 
55
  response.raise_for_status()
56
- questions_data = response.json()
57
- if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
- print(f"Fetched {len(questions_data)} questions.")
61
- except requests.exceptions.RequestException as e:
62
- print(f"Error fetching questions: {e}")
63
- return f"Error fetching questions: {e}", None
64
- except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
  except Exception as e:
69
- print(f"An unexpected error occurred fetching questions: {e}")
70
- return f"An unexpected error occurred fetching questions: {e}", None
71
-
72
- # 3. Run your Agent
73
- results_log = []
74
- answers_payload = []
75
- print(f"Running agent on {len(questions_data)} questions...")
76
- for item in questions_data:
77
  task_id = item.get("task_id")
78
- question_text = item.get("question")
79
- if not task_id or question_text is None:
80
- print(f"Skipping item with missing task_id or question: {item}")
81
  continue
 
 
 
 
82
  try:
83
- submitted_answer = agent(question_text)
84
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
86
  except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
89
-
90
- if not answers_payload:
91
- print("Agent did not produce any answers to submit.")
92
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
-
94
- # 4. Prepare Submission
95
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
- print(status_update)
98
-
99
- # 5. Submit
100
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
 
 
 
101
  try:
102
- response = requests.post(submit_url, json=submission_data, timeout=60)
103
  response.raise_for_status()
104
- result_data = response.json()
105
- final_status = (
106
- f"Submission Successful!\n"
107
- f"User: {result_data.get('username')}\n"
108
- f"Overall Score: {result_data.get('score', 'N/A')}% "
109
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
110
- f"Message: {result_data.get('message', 'No message received.')}"
111
- )
112
- print("Submission successful.")
113
- results_df = pd.DataFrame(results_log)
114
- return final_status, results_df
115
- except requests.exceptions.HTTPError as e:
116
- error_detail = f"Server responded with status {e.response.status_code}."
117
- try:
118
- error_json = e.response.json()
119
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
120
- except requests.exceptions.JSONDecodeError:
121
- error_detail += f" Response: {e.response.text[:500]}"
122
- status_message = f"Submission Failed: {error_detail}"
123
- print(status_message)
124
- results_df = pd.DataFrame(results_log)
125
- return status_message, results_df
126
- except requests.exceptions.Timeout:
127
- status_message = "Submission Failed: The request timed out."
128
- print(status_message)
129
- results_df = pd.DataFrame(results_log)
130
- return status_message, results_df
131
- except requests.exceptions.RequestException as e:
132
- status_message = f"Submission Failed: Network error - {e}"
133
- print(status_message)
134
- results_df = pd.DataFrame(results_log)
135
- return status_message, results_df
136
- except Exception as e:
137
- status_message = f"An unexpected error occurred during submission: {e}"
138
- print(status_message)
139
- results_df = pd.DataFrame(results_log)
140
- return status_message, results_df
141
-
142
-
143
- # --- Build Gradio Interface using Blocks ---
144
- with gr.Blocks() as demo:
145
- gr.Markdown("# Basic Agent Evaluation Runner")
146
- gr.Markdown(
147
- """
148
- **Instructions:**
149
-
150
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
-
154
- ---
155
- **Disclaimers:**
156
- 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).
157
- 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.
158
- """
159
- )
160
 
161
- gr.LoginButton()
162
-
163
- run_button = gr.Button("Run Evaluation & Submit All Answers")
 
 
 
 
 
 
164
 
165
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
- # Removed max_rows=10 from DataFrame constructor
167
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
168
 
169
- run_button.click(
170
- fn=run_and_submit_all,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  outputs=[status_output, results_table]
172
  )
173
 
174
  if __name__ == "__main__":
175
- print("\n" + "-"*30 + " App Starting " + "-"*30)
176
- # Check for SPACE_HOST and SPACE_ID at startup for information
177
- space_host_startup = os.getenv("SPACE_HOST")
178
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
179
-
180
- if space_host_startup:
181
- print(f"✅ SPACE_HOST found: {space_host_startup}")
182
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
183
- else:
184
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
185
-
186
- if space_id_startup: # Print repo URLs if SPACE_ID is found
187
- print(f"✅ SPACE_ID found: {space_id_startup}")
188
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
190
- else:
191
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
192
-
193
- print("-"*(60 + len(" App Starting ")) + "\n")
194
-
195
- print("Launching Gradio Interface for Basic Agent Evaluation...")
196
- demo.launch(debug=True, share=False)
 
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
+ import google.generativeai as genai
6
+ from typing import Optional
7
 
8
+ API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
9
 
10
+ class ImprovedGAIAgent:
11
+ """Agente melhorado para o GAIA com Chain of Thought."""
12
+
13
  def __init__(self):
14
+ print("🚀 Inicializando agente melhorado...")
15
+
16
+ # Configura Gemini
17
+ api_key = os.getenv("GOOGLE_API_KEY")
18
+ if api_key:
19
+ genai.configure(api_key=api_key)
20
+ self.model = genai.GenerativeModel("gemini-3.1-flash-lite")
21
+ print("✅ Gemini configurado")
22
+ else:
23
+ self.model = None
24
+ print("⚠️ GOOGLE_API_KEY não encontrada")
25
+
26
  def __call__(self, question: str) -> str:
27
+ """Responde à pergunta com Chain of Thought."""
28
+
29
+ # Se não tiver modelo, retorna N/A
30
+ if not self.model:
31
+ return "N/A"
32
+
33
+ # Prompt melhorado com instruções claras
34
+ prompt = f"""
35
+ You are an AI assistant solving GAIA benchmark questions.
36
+
37
+ Question: {question}
38
+
39
+ Instructions:
40
+ 1. THINK STEP BY STEP about the problem.
41
+ 2. Show your reasoning briefly.
42
+ 3. END with the final answer in the format: FINAL ANSWER: [answer]
43
+
44
+ Important rules:
45
+ - If it's a number, just output the number
46
+ - If it's a string, output just the string
47
+ - If it's a date, output in YYYY-MM-DD format
48
+ - No markdown, no extra text after FINAL ANSWER
49
+
50
+ Let me solve this step by step:
51
+ """
52
+
53
+ try:
54
+ response = self.model.generate_content(prompt)
55
+ text = response.text.strip()
56
+
57
+ # Extrai a resposta final
58
+ if "FINAL ANSWER:" in text:
59
+ answer = text.split("FINAL ANSWER:")[-1].strip()
60
+ else:
61
+ # Fallback: pega a última linha
62
+ lines = [l.strip() for l in text.split('\n') if l.strip()]
63
+ answer = lines[-1] if lines else text
64
+
65
+ # Remove markdown e aspas extras
66
+ answer = answer.strip('"').strip("'").strip()
67
+ answer = answer.replace("```", "").strip()
68
+
69
+ print(f"✅ Resposta: {answer}")
70
+ return answer if answer else "N/A"
71
+
72
+ except Exception as e:
73
+ print(f"❌ Erro no modelo: {e}")
74
+ return "N/A"
75
 
 
 
 
 
 
 
76
 
77
+ class SearchEnhancedAgent:
78
+ """Agente com ferramenta de busca (se disponível)."""
79
+
80
+ def __init__(self):
81
+ print("🚀 Inicializando agente com busca...")
82
+
83
+ # Configura Gemini
84
+ api_key = os.getenv("GOOGLE_API_KEY")
85
+ if api_key:
86
+ genai.configure(api_key=api_key)
87
+ self.model = genai.GenerativeModel("gemini-3.1-flash-lite")
88
+ print("✅ Gemini configurado")
89
+ else:
90
+ self.model = None
91
+ print("⚠️ GOOGLE_API_KEY não encontrada")
92
+
93
+ # Tenta importar ferramentas de busca
94
+ self.search_tool = None
95
+ try:
96
+ from duckduckgo_search import DDGS
97
+ self.search_tool = DDGS()
98
+ print("✅ DuckDuckGo configurado")
99
+ except ImportError:
100
+ print("⚠️ DuckDuckGo não disponível")
101
+
102
+ def search(self, query: str) -> str:
103
+ """Faz busca na web."""
104
+ if not self.search_tool:
105
+ return ""
106
+ try:
107
+ results = self.search_tool.text(query, max_results=3)
108
+ return "\n".join([f"- {r['body']}" for r in results])
109
+ except Exception as e:
110
+ print(f"⚠️ Erro na busca: {e}")
111
+ return ""
112
+
113
+ def __call__(self, question: str) -> str:
114
+ """Responde à pergunta com busca se necessário."""
115
+
116
+ if not self.model:
117
+ return "N/A"
118
+
119
+ # Verifica se precisa de busca
120
+ search_terms = ["who", "what", "when", "where", "which", "how"]
121
+ needs_search = any(term in question.lower() for term in search_terms)
122
+
123
+ search_results = ""
124
+ if needs_search and self.search_tool:
125
+ print("🔍 Buscando informações...")
126
+ search_results = self.search(question)
127
+
128
+ prompt = f"""
129
+ You are an AI assistant solving GAIA benchmark questions.
130
+
131
+ Question: {question}
132
+
133
+ {f"Search results:\n{search_results}\n" if search_results else ""}
134
+
135
+ Instructions:
136
+ 1. Use the search results if available.
137
+ 2. Think step by step.
138
+ 3. END with FINAL ANSWER: [answer]
139
+
140
+ Rules:
141
+ - Numbers: just the number
142
+ - Strings: just the text
143
+ - Dates: YYYY-MM-DD
144
+ - No markdown after FINAL ANSWER
145
+
146
+ Let me solve this:
147
+ """
148
+
149
+ try:
150
+ response = self.model.generate_content(prompt)
151
+ text = response.text.strip()
152
+
153
+ if "FINAL ANSWER:" in text:
154
+ answer = text.split("FINAL ANSWER:")[-1].strip()
155
+ else:
156
+ lines = [l.strip() for l in text.split('\n') if l.strip()]
157
+ answer = lines[-1] if lines else text
158
+
159
+ answer = answer.strip('"').strip("'").strip()
160
+ answer = answer.replace("```", "").strip()
161
+
162
+ print(f"✅ Resposta: {answer}")
163
+ return answer if answer else "N/A"
164
+
165
+ except Exception as e:
166
+ print(f"❌ Erro: {e}")
167
+ return "N/A"
168
 
 
 
 
 
 
 
 
 
 
169
 
170
+ # ===== FUNÇÃO PRINCIPAL =====
171
+ def run_and_submit(username: str, use_search: bool = True):
172
+ """Executa o agente e submete as respostas."""
173
+
174
+ if not username or not username.strip():
175
+ return "❌ Digite seu username do Hugging Face.", None
176
+
177
+ username = username.strip()
178
+ print(f"\n👤 Usuário: {username}")
179
+
180
+ # Escolhe o agente
181
+ if use_search:
182
+ agent = SearchEnhancedAgent()
183
+ else:
184
+ agent = ImprovedGAIAgent()
185
+
186
+ # Busca perguntas
187
  try:
188
+ print("📥 Buscando perguntas...")
189
+ response = requests.get(f"{API_URL}/questions", timeout=15)
190
  response.raise_for_status()
191
+ questions = response.json()
192
+ print(f"✅ {len(questions)} perguntas carregadas")
 
 
 
 
 
 
 
 
 
 
193
  except Exception as e:
194
+ return f" Erro ao buscar perguntas: {e}", None
195
+
196
+ # Processa perguntas
197
+ results = []
198
+ answers = []
199
+ correct = 0
200
+
201
+ for i, item in enumerate(questions, 1):
202
  task_id = item.get("task_id")
203
+ question = item.get("question")
204
+
205
+ if not task_id:
206
  continue
207
+
208
+ print(f"\n[{i}/{len(questions)}] Task {task_id[:8]}...")
209
+ print(f" Pergunta: {question[:100]}...")
210
+
211
  try:
212
+ answer = agent(question)
213
+ answers.append({"task_id": task_id, "submitted_answer": answer})
214
+ results.append({"Task ID": task_id, "Resposta": answer})
215
+ print(f" ✅ Resposta: {answer}")
216
  except Exception as e:
217
+ error_msg = f"ERRO: {e}"
218
+ results.append({"Task ID": task_id, "Resposta": error_msg})
219
+ print(f" ❌ {error_msg}")
220
+
221
+ if not answers:
222
+ return " Nenhuma resposta gerada.", pd.DataFrame(results)
223
+
224
+ # Submete
225
+ space_id = os.getenv("SPACE_ID", "seu-usuario/seu-space")
226
+ payload = {
227
+ "username": username,
228
+ "agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
229
+ "answers": answers
230
+ }
231
+
232
+ print(f"\n📤 Submetendo {len(answers)} respostas...")
233
+
234
  try:
235
+ response = requests.post(f"{API_URL}/submit", json=payload, timeout=120)
236
  response.raise_for_status()
237
+ data = response.json()
238
+
239
+ status = f"""
240
+ SUBMISSÃO CONCLUÍDA!
241
+ 👤 Usuário: {data.get('username', username)}
242
+ 📊 Score: {data.get('score', 'N/A')}%
243
+ ✅ Acertos: {data.get('correct_count', '?')}/{data.get('total_attempted', '?')}
244
+ 📝 Mensagem: {data.get('message', '')}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
+ 📋 Detalhes:
247
+ - Total perguntas: {len(questions)}
248
+ - Respostas submetidas: {len(answers)}
249
+ - Agente: {'com busca' if use_search else 'sem busca'}
250
+ """
251
+ return status, pd.DataFrame(results)
252
+
253
+ except Exception as e:
254
+ return f"❌ Erro na submissão: {e}", pd.DataFrame(results)
255
 
 
 
 
256
 
257
+ # ===== INTERFACE GRADIO =====
258
+ with gr.Blocks(title="GAIA Agent - Busca+CoT") as demo:
259
+ gr.Markdown("""
260
+ # 🎯 GAIA Agent - Versão Melhorada
261
+
262
+ **Agente com Chain of Thought e busca na web!**
263
+
264
+ Instruções:
265
+ 1. Digite seu username do Hugging Face
266
+ 2. Selecione se quer usar busca na web
267
+ 3. Clique em Executar
268
+ 4. Veja seu score!
269
+ """)
270
+
271
+ with gr.Row():
272
+ username_input = gr.Textbox(
273
+ label="Seu username do Hugging Face",
274
+ placeholder="ex: nayaracardoso",
275
+ scale=2
276
+ )
277
+ search_checkbox = gr.Checkbox(
278
+ label="🔍 Usar busca na web",
279
+ value=True
280
+ )
281
+ run_btn = gr.Button("🚀 Executar", variant="primary", scale=1)
282
+
283
+ status_output = gr.Textbox(label="Status", lines=15)
284
+ results_table = gr.DataFrame(label="Resultados")
285
+
286
+ run_btn.click(
287
+ fn=run_and_submit,
288
+ inputs=[username_input, search_checkbox],
289
  outputs=[status_output, results_table]
290
  )
291
 
292
  if __name__ == "__main__":
293
+ demo.launch()