Nuriza01 commited on
Commit
269081f
·
verified ·
1 Parent(s): f1145f8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +277 -24
app.py CHANGED
@@ -1,34 +1,163 @@
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.")
@@ -54,25 +183,149 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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")
@@ -84,16 +337,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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
@@ -172,10 +425,10 @@ with gr.Blocks() as demo:
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}")
@@ -183,14 +436,14 @@ if __name__ == "__main__":
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 json
5
  import pandas as pd
6
+ import spacy
7
+ from openai import OpenAI
8
+ from agent_tools import duckduckgo_search, langsearch_search, TOOLS_MAPPING, TOOLS_DEFINITION
9
+
10
 
 
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
+
17
+
18
  class BasicAgent:
19
  def __init__(self):
20
  print("BasicAgent initialized.")
21
+ self.client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.getenv("OR_TOKEN"))
22
+
23
  def __call__(self, question: str) -> str:
24
+ print(f"Agent received question: {question}")
25
+
26
+ try:
27
+ count = 0
28
+
29
+ content = "You are taking a quiz. Follow the description in the question. Do do not report your thoughts, explanations, reasoning, or conclusion. Give only YOUR FINAL ANSWER. YOUR FINAL ANSWER should be a number (write the number using digits) OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string. Remove any quotation marks surrounding the answer."
30
+
31
+ llm_api_url = "http://localhost:8004/ask"
32
+ headers = {"Content-Type": "application/json"}
33
+ payload = {"question": f"Question: {question}\n\n1. Derive the sub-questions to above question\n2. Provide answers to each sub-questions.\n3. Provide final exact answer."}
34
+
35
+ print(f"Sending question to LLM API: {llm_api_url}")
36
+ response = requests.post(llm_api_url, headers=headers, json=payload, timeout=60)
37
+ response.raise_for_status() # Raise an exception for bad status codes
38
+
39
+ response_data = response.json()
40
+ search_results = response_data.get("answer", "No answer found in LLM response.")
41
+ print(f"LLM API response received: {search_results}")
42
+
43
+ content += f"\n\nThe following are the results from LLM, use it as reference along with your own knowledge base to provide the most accurate answer: {search_results}"
44
+
45
+ # nlp = spacy.load("en_core_web_sm")
46
+ # doc = nlp(question)
47
+ # # Extract keywords: Nouns, Proper Nouns, Adjectives, and Verbs might be useful
48
+ # keywords = [token.lemma_ for token in doc if token.pos_ in ['NOUN', 'PROPN', 'ADJ', 'VERB'] and not token.is_stop]
49
+ # # Extract all recognized entities
50
+ # entities = [ent.text for ent in doc.ents]
51
+ # print("Keywords:", keywords)
52
+ # print("Entities:", entities)
53
 
54
+ # keywords.extend(entities) # Combine keywords and entities for search
55
+
56
+ # # Call langsearch_search function
57
+ # search_query = ""
58
+ # if keywords:
59
+ # search_query = " ".join(keywords)
60
+ # # print(f"No entities found, using keywords for search query: '{search_query}'")
61
+ # else:
62
+ # search_query = question
63
+ # # print("No entities or keywords found, using original question for search query.")
64
+ # search_results = langsearch_search(query=search_query, count=5)
65
+ # if len(search_results) > 0:
66
+ # # Convert search results to a readable text format
67
+ # search_results_text = ""
68
+ # for i, result in enumerate(search_results, 1):
69
+ # count += 1
70
+ # search_results_text += f"\n\n---SEARCH RESULT #{count}---\n"
71
+ # search_results_text += f"{search_results[i - 1]}"
72
+ # content += f"\n\nThe following are the results from NLP + LangSearch, use it as reference along with your own knowledge base to provide the most accurate answer: {search_results_text}"
73
+
74
+ # search_results = langsearch_search(query=question, count=5)
75
+ # content += f"\n\nThe following are the results from the LangSearch, use it as reference along with your own knowledge base to provide the most accurate answer: {search_results}"
76
+
77
+ # print(f"Content for system message: {content}")
78
+
79
+ messages = [
80
+ {
81
+ "role": "system",
82
+ "content": content
83
+ },
84
+ {
85
+ "role": "user",
86
+ "content": [
87
+ {
88
+ "type": "text",
89
+ "text": question
90
+ },
91
+ # {
92
+ # "type": "image_url",
93
+ # "image_url": {
94
+ # "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
95
+ # }
96
+ # }
97
+ ]
98
+ }
99
+ ]
100
+
101
+ for _ in range(3):
102
+ # Generate response
103
+ print("Using Inference API for generation...")
104
+ completion = self.client.chat.completions.create(
105
+ extra_headers={
106
+ "HTTP-Referer": "<YOUR_SITE_URL>", # Optional. Site URL for rankings on openrouter.ai.
107
+ "X-Title": "<YOUR_SITE_NAME>", # Optional. Site title for rankings on openrouter.ai.
108
+ },
109
+ extra_body={},
110
+ # model="deepseek/deepseek-chat-v3-0324:free",
111
+ # model="deepseek/deepseek-r1",
112
+ # model="tngtech/deepseek-r1t-chimera:free",
113
+ model="microsoft/mai-ds-r1:free",
114
+ # tools=TOOLS_DEFINITION, # Use imported tools definition
115
+ messages=messages,
116
+ temperature=0.0,
117
+ max_tokens=2048,
118
+ )
119
+ print(f"Completion: {completion}")
120
+ messages.append(completion.choices[0].message)
121
+
122
+ if completion.choices[0].message.tool_calls is None:
123
+ answer = completion.choices[0].message.content
124
+ if answer is None or answer == "":
125
+ if completion.choices[0].message.reasoning is not None:
126
+ answer = completion.choices[0].message.reasoning
127
+ else:
128
+ answer = "I apologize, but I encountered an error when trying to answer your question."
129
+ print(f"Agent generated response: {answer}")
130
+ return answer
131
+
132
+ for tool_call in completion.choices[0].message.tool_calls:
133
+ tool_name = tool_call.function.name
134
+ tool_args = json.loads(tool_call.function.arguments)
135
+ tool_response = TOOLS_MAPPING[tool_name](**tool_args) # Use imported tools mapping
136
+ message = {
137
+ "role": "tool",
138
+ "tool_call_id": tool_call.id,
139
+ "name": tool_name,
140
+ "content": json.dumps(tool_response),
141
+ }
142
+ messages.append(message)
143
+ print(f"Tool call: {message}")
144
+ except Exception as e:
145
+ print(f"Error generating response: {e}")
146
+ fallback_answer = "I apologize, but I encountered an error when trying to answer your question."
147
+ print(f"Agent returning fallback answer: {fallback_answer}")
148
+ return fallback_answer
149
+
150
+
151
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
152
  """
153
  Fetches all questions, runs the BasicAgent on them, submits all answers,
154
  and displays the results.
155
  """
156
  # --- Determine HF Space Runtime URL and Repo URL ---
157
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
158
 
159
  if profile:
160
+ username = f"{profile.username}"
161
  print(f"User logged in: {username}")
162
  else:
163
  print("User not logged in.")
 
183
  response = requests.get(questions_url, timeout=15)
184
  response.raise_for_status()
185
  questions_data = response.json()
186
+ print(f"Questions: {questions_data}")
187
  if not questions_data:
188
+ print("Fetched questions list is empty.")
189
+ return "Fetched questions list is empty or invalid format.", None
190
  print(f"Fetched {len(questions_data)} questions.")
191
  except requests.exceptions.RequestException as e:
192
  print(f"Error fetching questions: {e}")
193
  return f"Error fetching questions: {e}", None
194
  except requests.exceptions.JSONDecodeError as e:
195
+ print(f"Error decoding JSON response from questions endpoint: {e}")
196
+ print(f"Response text: {response.text[:500]}")
197
+ return f"Error decoding server response for questions: {e}", None
198
  except Exception as e:
199
  print(f"An unexpected error occurred fetching questions: {e}")
200
  return f"An unexpected error occurred fetching questions: {e}", None
201
 
202
+ # questions_data = [
203
+ # {
204
+ # 'task_id': '8e867cd7-cff9-4e6c-867a-ff5ddc2550be',
205
+ # 'question': 'How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.',
206
+ # 'Level': '1',
207
+ # 'file_name': ''
208
+ # },
209
+ # {
210
+ # 'task_id': 'a1e91b78-d3d8-4675-bb8d-62741b4b68a6',
211
+ # 'question': 'In the video https:\\/\\/www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?',
212
+ # 'Level': '1',
213
+ # 'file_name': ''
214
+ # },
215
+ # {
216
+ # 'task_id': '2d83110e-a098-4ebb-9987-066c06fa42d0',
217
+ # 'question': '.rewsna eht sa "tfel" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI',
218
+ # 'Level': '1',
219
+ # 'file_name': ''
220
+ # },
221
+ # {
222
+ # 'task_id': 'cca530fc-4052-43b2-b130-b30968d8aa44',
223
+ # 'question': "Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.",
224
+ # 'Level': '1',
225
+ # 'file_name': 'cca530fc-4052-43b2-b130-b30968d8aa44.png'
226
+ # },
227
+ # {
228
+ # 'task_id': '4fc2f1ae-8625-45b5-ab34-ad4433bc21f8',
229
+ # 'question': 'Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?',
230
+ # 'Level': '1',
231
+ # 'file_name': ''
232
+ # },
233
+ # {
234
+ # 'task_id': '6f37996b-2ac7-44b0-8e68-6d28256631b4',
235
+ # 'question': 'Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.',
236
+ # 'Level': '1',
237
+ # 'file_name': ''
238
+ # },
239
+ # {
240
+ # 'task_id': '9d191bce-651d-4746-be2d-7ef8ecadb9c2',
241
+ # 'question': 'Examine the video at https:\\/\\/www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal\'c say in response to the question "Isn\'t that hot?"',
242
+ # 'Level': '1',
243
+ # 'file_name': ''
244
+ # },
245
+ # {
246
+ # 'task_id': 'cabe07ed-9eca-40ea-8ead-410ef5e83f91',
247
+ # 'question': "What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?",
248
+ # 'Level': '1',
249
+ # 'file_name': ''
250
+ # },
251
+ # {
252
+ # 'task_id': '3cef3a44-215e-4aed-8e3b-b1e3f08063b7',
253
+ # 'question': "I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:\n\nmilk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts\n\nI need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.",
254
+ # 'Level': '1',
255
+ # 'file_name': ''
256
+ # },
257
+ # {
258
+ # 'task_id': '99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3',
259
+ # 'question': 'Hi, I\'m making a pie but I could use some help with my shopping list. I have everything I need for the crust, but I\'m not sure about the filling. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can\'t quite make out what she\'s saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I\'ve attached the recipe as Strawberry pie.mp3.\n\nIn your response, please only list the ingredients, not any measurements. So if the recipe calls for "a pinch of salt" or "two cups of ripe strawberries" the ingredients on the list would be "salt" and "ripe strawberries".\n\nPlease format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.",
260
+ # 'Level': '1',
261
+ # 'file_name': '99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3'
262
+ # },
263
+ # {
264
+ # 'task_id': '305ac316-eef6-4446-960a-92d80d542f82',
265
+ # 'question': 'Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.',
266
+ # 'Level': '1',
267
+ # 'file_name': ''
268
+ # },
269
+ # {
270
+ # 'task_id': 'f918266a-b3e0-4914-865d-4faa564f1aef',
271
+ # 'question': 'What is the final numeric output from the attached Python code?',
272
+ # 'Level': '1',
273
+ # 'file_name': 'f918266a-b3e0-4914-865d-4faa564f1aef.py'
274
+ # },
275
+ # {
276
+ # 'task_id': '3f57289b-8c60-48be-bd80-01f8099ca449',
277
+ # 'question': 'How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?',
278
+ # 'Level': '1',
279
+ # 'file_name': ''
280
+ # },
281
+ # {
282
+ # 'task_id': '1f975693-876d-457b-a649-393859e79bf3',
283
+ # 'question': "Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(\n\nCould you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.",
284
+ # 'Level': '1',
285
+ # 'file_name': '1f975693-876d-457b-a649-393859e79bf3.mp3'
286
+ # },
287
+ # {
288
+ # 'task_id': '840bfca7-4f7b-481a-8794-c560c340185d',
289
+ # 'question': 'On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?',
290
+ # 'Level': '1',
291
+ # 'file_name': ''
292
+ # },
293
+ # {
294
+ # 'task_id': 'bda648d7-d618-4883-88f4-3466eabd860e',
295
+ # 'question': "Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.",
296
+ # 'Level': '1',
297
+ # 'file_name': ''
298
+ # },
299
+ # {
300
+ # 'task_id': 'cf106601-ab4f-4af9-b045-5295fe67b37d',
301
+ # 'question': "What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.",
302
+ # 'Level': '1',
303
+ # 'file_name': ''
304
+ # },
305
+ # {
306
+ # 'task_id': 'a0c07678-e491-4bbc-8f0b-07405144218f',
307
+ # 'question': "Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.",
308
+ # 'Level': '1',
309
+ # 'file_name': ''
310
+ # },
311
+ # {
312
+ # 'task_id': '7bd855d8-463d-4ed5-93ca-5fe35145f733',
313
+ # 'question': 'The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.',
314
+ # 'Level': '1',
315
+ # 'file_name': '7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx'
316
+ # },
317
+ # {
318
+ # 'task_id': '5a0c1adf-205e-4841-a666-7c3ef95def9d',
319
+ # 'question': 'What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?',
320
+ # 'Level': '1',
321
+ # 'file_name': ''
322
+ # },
323
+ # ]
324
+
325
  # 3. Run your Agent
326
  results_log = []
327
  answers_payload = []
328
+ print(f"Running agent on {len(questions_data)} questions")
329
  for item in questions_data:
330
  task_id = item.get("task_id")
331
  question_text = item.get("question")
 
337
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
338
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
339
  except Exception as e:
340
+ print(f"Error running agent on task {task_id}: {e}")
341
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
342
 
343
  if not answers_payload:
344
  print("Agent did not produce any answers to submit.")
345
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
346
 
347
+ # 4. Prepare Submission
348
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
349
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'"
350
  print(status_update)
351
 
352
  # 5. Submit
 
425
  )
426
 
427
  if __name__ == "__main__":
428
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
429
  # Check for SPACE_HOST and SPACE_ID at startup for information
430
  space_host_startup = os.getenv("SPACE_HOST")
431
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
432
 
433
  if space_host_startup:
434
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
436
  else:
437
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
438
 
439
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
440
  print(f"✅ SPACE_ID found: {space_id_startup}")
441
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
442
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
443
  else:
444
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
445
 
446
+ print("-" * (60 + len(" App Starting ")) + "\n")
447
 
448
  print("Launching Gradio Interface for Basic Agent Evaluation...")
449
+ demo.launch(debug=True, share=False)