kamorou commited on
Commit
8962abd
·
verified ·
1 Parent(s): 9590080

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +315 -78
app.py CHANGED
@@ -1,29 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
 
@@ -38,13 +336,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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
 
@@ -58,13 +356,6 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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
@@ -80,6 +371,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | 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})
@@ -112,27 +404,6 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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)
@@ -142,55 +413,21 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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 inspect
5
+ # import pandas as pd
6
+
7
+ # # Add this line with the other imports
8
+ # from agent import BasicAgent
9
+
10
+ # # (Keep Constants as is)
11
+ # # --- Constants ---
12
+ # DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
+
14
+ # # --- Basic Agent Definition ---
15
+ # # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
16
+ # class BasicAgent:
17
+ # def __init__(self):
18
+ # print("BasicAgent initialized.")
19
+ # def __call__(self, question: str) -> str:
20
+ # print(f"Agent received question (first 50 chars): {question[:50]}...")
21
+ # fixed_answer = "This is a default answer."
22
+ # print(f"Agent returning fixed answer: {fixed_answer}")
23
+ # return fixed_answer
24
+
25
+ # def run_and_submit_all( profile: gr.OAuthProfile | None):
26
+ # """
27
+ # Fetches all questions, runs the BasicAgent on them, submits all answers,
28
+ # and displays the results.
29
+ # """
30
+ # # --- Determine HF Space Runtime URL and Repo URL ---
31
+ # space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
32
+
33
+ # if profile:
34
+ # username= f"{profile.username}"
35
+ # print(f"User logged in: {username}")
36
+ # else:
37
+ # print("User not logged in.")
38
+ # return "Please Login to Hugging Face with the button.", None
39
+
40
+ # api_url = DEFAULT_API_URL
41
+ # questions_url = f"{api_url}/questions"
42
+ # submit_url = f"{api_url}/submit"
43
+
44
+ # # 1. Instantiate Agent ( modify this part to create your agent)
45
+ # try:
46
+ # agent = BasicAgent()
47
+ # except Exception as e:
48
+ # print(f"Error instantiating agent: {e}")
49
+ # return f"Error initializing agent: {e}", None
50
+ # # 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)
51
+ # agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
52
+ # print(agent_code)
53
+
54
+ # # 2. Fetch Questions
55
+ # print(f"Fetching questions from: {questions_url}")
56
+ # try:
57
+ # response = requests.get(questions_url, timeout=15)
58
+ # response.raise_for_status()
59
+ # questions_data = response.json()
60
+ # if not questions_data:
61
+ # print("Fetched questions list is empty.")
62
+ # return "Fetched questions list is empty or invalid format.", None
63
+ # print(f"Fetched {len(questions_data)} questions.")
64
+ # except requests.exceptions.RequestException as e:
65
+ # print(f"Error fetching questions: {e}")
66
+ # return f"Error fetching questions: {e}", None
67
+ # except requests.exceptions.JSONDecodeError as e:
68
+ # print(f"Error decoding JSON response from questions endpoint: {e}")
69
+ # print(f"Response text: {response.text[:500]}")
70
+ # return f"Error decoding server response for questions: {e}", None
71
+ # except Exception as e:
72
+ # print(f"An unexpected error occurred fetching questions: {e}")
73
+ # return f"An unexpected error occurred fetching questions: {e}", None
74
+
75
+ # # 3. Run your Agent
76
+ # results_log = []
77
+ # answers_payload = []
78
+ # print(f"Running agent on {len(questions_data)} questions...")
79
+ # for item in questions_data:
80
+ # task_id = item.get("task_id")
81
+ # question_text = item.get("question")
82
+ # if not task_id or question_text is None:
83
+ # print(f"Skipping item with missing task_id or question: {item}")
84
+ # continue
85
+ # try:
86
+ # submitted_answer = agent(question_text)
87
+ # answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
88
+ # results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
89
+ # except Exception as e:
90
+ # print(f"Error running agent on task {task_id}: {e}")
91
+ # results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
92
+
93
+ # if not answers_payload:
94
+ # print("Agent did not produce any answers to submit.")
95
+ # return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
96
+
97
+ # # 4. Prepare Submission
98
+ # submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
99
+ # status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
100
+ # print(status_update)
101
+
102
+ # # 5. Submit
103
+ # print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
104
+ # try:
105
+ # response = requests.post(submit_url, json=submission_data, timeout=60)
106
+ # response.raise_for_status()
107
+ # result_data = response.json()
108
+ # final_status = (
109
+ # f"Submission Successful!\n"
110
+ # f"User: {result_data.get('username')}\n"
111
+ # f"Overall Score: {result_data.get('score', 'N/A')}% "
112
+ # f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
113
+ # f"Message: {result_data.get('message', 'No message received.')}"
114
+ # )
115
+ # print("Submission successful.")
116
+ # results_df = pd.DataFrame(results_log)
117
+ # return final_status, results_df
118
+ # except requests.exceptions.HTTPError as e:
119
+ # error_detail = f"Server responded with status {e.response.status_code}."
120
+ # try:
121
+ # error_json = e.response.json()
122
+ # error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
123
+ # except requests.exceptions.JSONDecodeError:
124
+ # error_detail += f" Response: {e.response.text[:500]}"
125
+ # status_message = f"Submission Failed: {error_detail}"
126
+ # print(status_message)
127
+ # results_df = pd.DataFrame(results_log)
128
+ # return status_message, results_df
129
+ # except requests.exceptions.Timeout:
130
+ # status_message = "Submission Failed: The request timed out."
131
+ # print(status_message)
132
+ # results_df = pd.DataFrame(results_log)
133
+ # return status_message, results_df
134
+ # except requests.exceptions.RequestException as e:
135
+ # status_message = f"Submission Failed: Network error - {e}"
136
+ # print(status_message)
137
+ # results_df = pd.DataFrame(results_log)
138
+ # return status_message, results_df
139
+ # except Exception as e:
140
+ # status_message = f"An unexpected error occurred during submission: {e}"
141
+ # print(status_message)
142
+ # results_df = pd.DataFrame(results_log)
143
+ # return status_message, results_df
144
+
145
+
146
+ # # --- Build Gradio Interface using Blocks ---
147
+ # with gr.Blocks() as demo:
148
+ # gr.Markdown("# Basic Agent Evaluation Runner")
149
+ # gr.Markdown(
150
+ # """
151
+ # **Instructions:**
152
+
153
+ # 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
154
+ # 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
155
+ # 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
156
+
157
+ # ---
158
+ # **Disclaimers:**
159
+ # 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).
160
+ # 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.
161
+ # """
162
+ # )
163
+
164
+ # gr.LoginButton()
165
+
166
+ # run_button = gr.Button("Run Evaluation & Submit All Answers")
167
+
168
+ # status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
169
+ # # Removed max_rows=10 from DataFrame constructor
170
+ # results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
171
+
172
+ # run_button.click(
173
+ # fn=run_and_submit_all,
174
+ # outputs=[status_output, results_table]
175
+ # )
176
+
177
+ # if __name__ == "__main__":
178
+ # print("\n" + "-"*30 + " App Starting " + "-"*30)
179
+ # # Check for SPACE_HOST and SPACE_ID at startup for information
180
+ # space_host_startup = os.getenv("SPACE_HOST")
181
+ # space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
182
+
183
+ # if space_host_startup:
184
+ # print(f"✅ SPACE_HOST found: {space_host_startup}")
185
+ # print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
186
+ # else:
187
+ # print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
188
+
189
+ # if space_id_startup: # Print repo URLs if SPACE_ID is found
190
+ # print(f"✅ SPACE_ID found: {space_id_startup}")
191
+ # print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
192
+ # print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
193
+ # else:
194
+ # print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
195
+
196
+ # print("-"*(60 + len(" App Starting ")) + "\n")
197
+
198
+ # print("Launching Gradio Interface for Basic Agent Evaluation...")
199
+ # demo.launch(debug=True, share=False)
200
+
201
+
202
+
203
  import os
204
  import gradio as gr
205
  import requests
206
  import inspect
207
  import pandas as pd
208
+ from dotenv import load_dotenv
209
+ from typing import TypedDict, Annotated, List
210
 
211
+ # ==============================================================================
212
+ # PART 1: YOUR AGENT'S LOGIC AND DEFINITION
213
+ # All of this is new. It replaces the old placeholder.
214
+ # ==============================================================================
215
+
216
+ # LangChain and LangGraph imports
217
+ from langchain_huggingface import HuggingFaceEndpoint
218
+ from langchain_community.tools.tavily_search import TavilySearchResults
219
+ from langchain_experimental.tools import PythonREPLTool
220
+ from langchain_core.messages import BaseMessage, HumanMessage
221
+ from langgraph.graph import StateGraph, END
222
+ from langgraph.prebuilt import ToolNode
223
+
224
+ # Load API keys from .env file or Space secrets
225
+ load_dotenv()
226
+ hf_token = os.getenv("HF_TOKEN")
227
+ tavily_api_key = os.getenv("TAVILY_API_KEY")
228
+
229
+ # Set the Tavily API key for the tool to use
230
+ if tavily_api_key:
231
+ os.environ["TAVILY_API_KEY"] = tavily_api_key
232
+ else:
233
+ print("Warning: TAVILY_API_KEY not found. Web search tool will not work.")
234
+
235
+ # --- Define Agent Tools ---
236
+ tools = [
237
+ TavilySearchResults(max_results=3, description="A search engine for finding up-to-date information on the web."),
238
+ PythonREPLTool()
239
+ ]
240
+ tool_node = ToolNode(tools)
241
+
242
+ # --- Configure the LLM "Brain" ---
243
+ repo_id = "meta-llama/Meta-Llama-3-8B-Instruct"
244
+ SYSTEM_PROMPT = """You are a highly capable AI agent. Your mission is to accurately answer complex questions.
245
+ **Instructions:**
246
+ 1. **Analyze:** Read the question to understand what is being asked.
247
+ 2. **Plan:** Think step-by-step. Break the problem into smaller tasks. Decide which tool is best for each task.
248
+ 3. **Execute:** Call ONE tool at a time.
249
+ 4. **Observe & Reason:** After getting a tool's result, observe it. Decide if you have the final answer or if you need to use another tool.
250
+ 5. **Final Answer:** Once confident, provide a clear, direct, and concise final answer."""
251
 
252
+ llm = HuggingFaceEndpoint(
253
+ repo_id=repo_id,
254
+ huggingfacehub_api_token=hf_token,
255
+ temperature=0,
256
+ max_new_tokens=2048,
257
+ )
258
+ llm_with_tools = llm.bind_tools(tools)
259
+
260
+ # --- Build the LangGraph Agent ---
261
+ class AgentState(TypedDict):
262
+ messages: Annotated[List[BaseMessage], lambda x, y: x + y]
263
+
264
+ def agent_node(state):
265
+ last_message = state['messages'][-1]
266
+ prompt_with_system = [HumanMessage(content=SYSTEM_PROMPT, name="system_prompt"), last_message]
267
+ response = llm_with_tools.invoke(prompt_with_system)
268
+ return {"messages": [response]}
269
+
270
+ def should_continue(state):
271
+ if state["messages"][-1].tool_calls:
272
+ return "tools"
273
+ return END
274
+
275
+ workflow = StateGraph(AgentState)
276
+ workflow.add_node("agent", agent_node)
277
+ workflow.add_node("tools", tool_node)
278
+ workflow.set_entry_point("agent")
279
+ workflow.add_conditional_edges("agent", should_continue, {"tools": "tools", "end": END})
280
+ workflow.add_edge("tools", "agent")
281
+
282
+ # Compile the graph into a runnable app
283
+ compiled_agent_app = workflow.compile()
284
+
285
+ # --- THIS IS THE NEW BasicAgent CLASS THAT REPLACES THE PLACEHOLDER ---
286
  class BasicAgent:
287
  def __init__(self):
288
+ # Check for API keys during initialization
289
+ if not hf_token or not tavily_api_key:
290
+ raise ValueError("HF_TOKEN or TAVILY_API_KEY not set. Please add them to your Space secrets.")
291
+ print("LangGraph Agent initialized successfully.")
292
+
293
  def __call__(self, question: str) -> str:
294
+ print(f"Agent received question (first 80 chars): {question[:80]}...")
295
+ try:
296
+ inputs = {"messages": [HumanMessage(content=question)]}
297
+ final_response = ""
298
+ for s in compiled_agent_app.stream(inputs, {"recursion_limit": 15}):
299
+ if "agent" in s and s["agent"]["messages"][-1].content:
300
+ final_response = s["agent"]["messages"][-1].content
301
+
302
+ if not final_response:
303
+ final_response = "Agent finished but did not produce a clear final answer."
304
+
305
+ print(f"Agent returning final answer (first 80 chars): {final_response[:80]}...")
306
+ return final_response
307
+ except Exception as e:
308
+ print(f"An error occurred in agent execution: {e}")
309
+ return f"Error: {e}"
310
+
311
+ # ==============================================================================
312
+ # PART 2: THE GRADIO TEST HARNESS UI
313
+ # The rest of this file remains exactly as it was provided in the template.
314
+ # ==============================================================================
315
+
316
+ # --- Constants ---
317
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
318
 
319
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
320
  """
321
  Fetches all questions, runs the BasicAgent on them, submits all answers,
322
  and displays the results.
323
  """
324
+ # (The rest of this function remains unchanged)
325
  # --- Determine HF Space Runtime URL and Repo URL ---
326
  space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
327
 
 
336
  questions_url = f"{api_url}/questions"
337
  submit_url = f"{api_url}/submit"
338
 
339
+ # 1. Instantiate Agent (this now calls YOUR agent class from above)
340
  try:
341
  agent = BasicAgent()
342
  except Exception as e:
343
  print(f"Error instantiating agent: {e}")
344
  return f"Error initializing agent: {e}", None
345
+
346
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
347
  print(agent_code)
348
 
 
356
  print("Fetched questions list is empty.")
357
  return "Fetched questions list is empty or invalid format.", None
358
  print(f"Fetched {len(questions_data)} questions.")
 
 
 
 
 
 
 
359
  except Exception as e:
360
  print(f"An unexpected error occurred fetching questions: {e}")
361
  return f"An unexpected error occurred fetching questions: {e}", None
 
371
  print(f"Skipping item with missing task_id or question: {item}")
372
  continue
373
  try:
374
+ # This line now calls your __call__ method in your new BasicAgent
375
  submitted_answer = agent(question_text)
376
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
377
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
404
  print("Submission successful.")
405
  results_df = pd.DataFrame(results_log)
406
  return final_status, results_df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
407
  except Exception as e:
408
  status_message = f"An unexpected error occurred during submission: {e}"
409
  print(status_message)
 
413
 
414
  # --- Build Gradio Interface using Blocks ---
415
  with gr.Blocks() as demo:
416
+ gr.Markdown("# GAIA Agent Evaluation Runner")
417
  gr.Markdown(
418
  """
419
+ 1. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
420
+ 2. Click 'Run Evaluation & Submit All Answers' to run your custom agent and see the score.
 
 
 
 
 
 
 
 
421
  """
422
  )
 
423
  gr.LoginButton()
 
424
  run_button = gr.Button("Run Evaluation & Submit All Answers")
 
425
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
426
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
 
427
  run_button.click(
428
  fn=run_and_submit_all,
429
  outputs=[status_output, results_table]
430
  )
431
 
432
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
433
  demo.launch(debug=True, share=False)