GoodLuckChuck commited on
Commit
8ab0ff1
·
verified ·
1 Parent(s): 74c8d73

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +438 -123
app.py CHANGED
@@ -1,196 +1,511 @@
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 asyncio
6
+ import re
7
+ import json
8
+ import logging
9
+ import operator # Used by CalculatorTool
10
+ import aiohttp
11
+ from typing import Optional, Dict, Any, List, Tuple
12
 
13
+ # Import necessary components from smolagents
14
+ try:
15
+ from smolagents import CodeAgent, Tool, OpenAIServerModel
16
+ except ImportError:
17
+ logging.error("Failed to import smolagents. Please ensure it is installed.")
18
+ class CodeAgent: pass
19
+ class Tool: pass
20
+ class OpenAIServerModel: pass
21
+
22
+ from datetime import datetime
23
+
24
+ # --- Configuration ---
25
+ class AppConfig:
26
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
27
+ QUESTIONS_URL_PATH = "/questions"
28
+ SUBMIT_URL_PATH = "/submit"
29
+ SCREENSHOTS_DIR = "screenshots"
30
+ OPENAI_MODEL_ID = "gpt-3.5-turbo" # Defaulting to faster/cheaper model
31
+ SERPER_API_NUM_RESULTS = 3
32
+ WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
33
+ AGENT_MAX_STEPS = 10
34
+ AGENT_VERBOSITY_LEVEL = 2
35
+ AGENT_SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number 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."""
36
+
37
+ CONFIG = AppConfig()
38
+
39
+ # --- Logging Setup ---
40
+ logging.basicConfig(
41
+ level=logging.INFO,
42
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
43
+ logger = logging.getLogger(__name__)
44
+
45
+ # --- Utility Functions ---
46
+ def ensure_dir_exists(directory_path: str):
47
+ os.makedirs(directory_path, exist_ok=True)
48
+
49
+ ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)
50
+
51
+ # --- HTTP Client Session Management ---
52
+ SHARED_HTTP_SESSION: Optional[aiohttp.ClientSession] = None
53
+
54
+ async def get_shared_http_session() -> aiohttp.ClientSession:
55
+ global SHARED_HTTP_SESSION
56
+ if SHARED_HTTP_SESSION is None or SHARED_HTTP_SESSION.closed:
57
+ SHARED_HTTP_SESSION = aiohttp.ClientSession()
58
+ logger.info("Created shared aiohttp.ClientSession.")
59
+ return SHARED_HTTP_SESSION
60
+
61
+ async def close_shared_http_session():
62
+ global SHARED_HTTP_SESSION
63
+ if SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed:
64
+ await SHARED_HTTP_SESSION.close()
65
+ SHARED_HTTP_SESSION = None
66
+ logger.info("Closed shared aiohttp.ClientSession.")
67
+
68
+ # --- Tool Definitions ---
69
+ class ImageRetrievalTool(Tool):
70
+ name = "image_retriever"
71
+ description = "Retrieves images from web pages. Input is a URL to an image. Returns a success/error message."
72
+ inputs = {"url": {"type": "string", "description": "The URL of the image to retrieve"}}
73
+ output_type = "string"
74
+
75
+ def __init__(self, session: aiohttp.ClientSession):
76
+ super().__init__()
77
+ self.image_memory: Dict[str, Dict[str, Any]] = {}
78
+ self.screenshot_count = 0
79
+ self._session = session
80
+
81
+ async def forward(self, url: str) -> str:
82
+ logger.info(f"ImageRetrievalTool called with URL: {url}")
83
+ try:
84
+ async with self._session.get(url, timeout=aiohttp.ClientTimeout(total=20)) as response:
85
+ response.raise_for_status()
86
+ image_data = await response.read()
87
+ image_id = f"image_{self.screenshot_count}"
88
+ self.image_memory[image_id] = {
89
+ 'data': image_data,
90
+ 'url': url,
91
+ 'timestamp': datetime.now().isoformat()
92
+ }
93
+ self.screenshot_count += 1
94
+ return f"Image retrieved successfully from {url}. Stored in memory as {image_id}."
95
+ except asyncio.TimeoutError:
96
+ logger.error(f"Timeout retrieving image {url}")
97
+ return f"Error: Timeout retrieving image {url}."
98
+ except aiohttp.ClientError as e:
99
+ logger.error(f"ClientError retrieving image {url}: {type(e).__name__} - {str(e)}")
100
+ return f"Error retrieving image (client error): {str(e)}"
101
+ except Exception as e:
102
+ logger.error(f"Unexpected error retrieving image {url}: {type(e).__name__} - {str(e)}")
103
+ return f"Error retrieving image: {str(e)}"
104
+
105
+ class WebSearchTool(Tool):
106
+ name = "web_search"
107
+ description = "Performs web searches using Serper API to find information. Input is a search query."
108
+ inputs = {"query": {"type": "string", "description": "The search query to execute"}}
109
+ output_type = "string"
110
+
111
+ def __init__(self, session: aiohttp.ClientSession):
112
+ super().__init__()
113
+ self._session = session
114
+
115
+ async def forward(self, query: str) -> str:
116
+ logger.info(f"WebSearchTool called with query: {query}")
117
+ serper_api_key = os.environ.get('SERPER_API_KEY')
118
+ if not serper_api_key:
119
+ logger.error("SERPER_API_KEY not found.")
120
+ return "Error: Serper API key not found in environment."
121
+
122
+ url = "https://google.serper.dev/search"
123
+ headers = {'X-API-KEY': serper_api_key, 'Content-Type': 'application/json'}
124
+ payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
125
+
126
+ try:
127
+ async with self._session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
128
+ response.raise_for_status()
129
+ data = await response.json()
130
+ return self._format_results(data)
131
+ except asyncio.TimeoutError:
132
+ logger.error(f"Timeout performing search for '{query}'")
133
+ return f"Error: Timeout during web search for '{query}'."
134
+ except aiohttp.ClientError as e:
135
+ logger.error(f"ClientError performing search for '{query}': {type(e).__name__} - {str(e)}")
136
+ return f"Error performing search (client error): {str(e)}"
137
+ except Exception as e:
138
+ logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}")
139
+ return f"Error performing search: {str(e)}"
140
+
141
+ def _format_results(self, data: Dict[str, Any]) -> str:
142
+ results = []
143
+ if 'organic' in data and data['organic']:
144
+ for result in data['organic'][:CONFIG.SERPER_API_NUM_RESULTS]:
145
+ title = result.get('title', 'N/A')
146
+ snippet = result.get('snippet', 'N/A')
147
+ results.append(f"Title: {title}\nSnippet: {snippet}\n---")
148
+ if not results and 'knowledgeGraph' in data:
149
+ kg = data['knowledgeGraph']
150
+ title = kg.get('title', '')
151
+ description = kg.get('description', '')
152
+ if title or description:
153
+ results.append(f"Knowledge Graph: {title}\n{description}\n---")
154
+ formatted_output = "\n".join(results) if results else "No relevant search results found."
155
+ return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
156
+
157
+ class CalculatorTool(Tool):
158
+ name = "calculator"
159
+ description = "Performs mathematical calculations. Input is a mathematical expression string (e.g., '2+2*5')."
160
+ inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate"}}
161
+ output_type = "string"
162
 
 
 
 
163
  def __init__(self):
164
+ super().__init__()
165
+ self.operations = {
166
+ '+': operator.add, '-': operator.sub,
167
+ '*': operator.mul, '/': operator.truediv,
168
+ '^': operator.pow
169
+ }
170
+ self.allowed_chars = "0123456789+-*/^(). "
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
+ async def forward(self, expression: str) -> str:
173
+ logger.info(f"CalculatorTool called with expression: {expression}")
174
+ try:
175
+ safe_expr = "".join(c for c in expression if c in self.allowed_chars)
176
+ if not safe_expr:
177
+ return "Error: Empty or invalid expression for calculator."
178
+ result = eval(safe_expr, {"__builtins__": {}}, self.operations) # type: ignore
179
+ return f"Calculation result: {safe_expr} = {float(result)}"
180
+ except Exception as e:
181
+ logger.error(f"Error evaluating expression '{expression}': {str(e)}")
182
+ return f"Error: Could not evaluate expression '{expression}'. Ensure it's a simple arithmetic expression."
183
 
184
+ # --- Agent Definition ---
185
+ class QuestionAnsweringAgent(CodeAgent):
186
+ def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
187
+ tools = [
188
+ WebSearchTool(session=http_session),
189
+ CalculatorTool(),
190
+ ImageRetrievalTool(session=http_session)
191
+ ]
192
+
193
+ effective_model = model
194
+ if effective_model is None:
195
+ openai_api_key = os.environ.get('OPENAI_API_KEY')
196
+ if not openai_api_key:
197
+ raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
198
+ effective_model = OpenAIServerModel(
199
+ model_id=CONFIG.OPENAI_MODEL_ID,
200
+ api_key=openai_api_key
201
+ )
202
+
203
+ super().__init__(
204
+ tools=tools,
205
+ model=effective_model,
206
+ system_prompt=CONFIG.AGENT_SYSTEM_PROMPT,
207
+ additional_authorized_imports=["PIL"],
208
+ max_steps=CONFIG.AGENT_MAX_STEPS,
209
+ verbosity_level=CONFIG.AGENT_VERBOSITY_LEVEL
210
+ )
211
+ logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID}.")
212
+
213
+ async def process_question(self, question_text: str) -> Tuple[str, str]:
214
+ reasoning_trace = "Agent execution started."
215
+ final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
216
+ try:
217
+ logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
218
+ raw_output = await self.run(question_text)
219
+ full_agent_response = str(raw_output)
220
+ reasoning_trace = full_agent_response
221
+ logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
222
+
223
+ match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
224
+ if match:
225
+ final_answer_for_submission = match.group(1).strip()
226
+ logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
227
+ else:
228
+ logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
229
+ final_answer_for_submission = full_agent_response.strip()
230
+
231
+ if not final_answer_for_submission:
232
+ logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
233
+ final_answer_for_submission = "Could not determine answer."
234
+ except Exception as e:
235
+ logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}", exc_info=True)
236
+ final_answer_for_submission = f"Error in agent processing: {str(e)}"
237
+ reasoning_trace += f"\nError encountered: {str(e)}"
238
+ return final_answer_for_submission, reasoning_trace
239
+
240
+ # --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
241
+ class ChuckAgent:
242
+ def __init__(self):
243
+ required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
244
+ missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
245
+ if missing_vars:
246
+ error_msg = f"Missing required environment variables: {', '.join(missing_vars)}"
247
+ logger.critical(error_msg)
248
+ raise EnvironmentError(error_msg)
249
+
250
+ logger.info("ChuckAgent initialization started")
251
+ try:
252
+ self.loop = asyncio.get_running_loop()
253
+ except RuntimeError:
254
+ self.loop = asyncio.new_event_loop()
255
+ asyncio.set_event_loop(self.loop)
256
+
257
+ self.http_session = self.loop.run_until_complete(get_shared_http_session())
258
+ self.agent = QuestionAnsweringAgent(http_session=self.http_session)
259
+ logger.info("ChuckAgent fully initialized")
260
+
261
+ def __call__(self, question: str) -> Tuple[str, str]:
262
+ logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
263
+ try:
264
+ if asyncio.get_event_loop() is not self.loop:
265
+ asyncio.set_event_loop(self.loop)
266
+
267
+ final_answer, reasoning_trace = self.loop.run_until_complete(
268
+ self.agent.process_question(question)
269
+ )
270
+ logger.info(f"ChuckAgent returning answer (first 50 chars): {final_answer[:50]}...")
271
+ return final_answer, reasoning_trace
272
+ except Exception as e:
273
+ error_msg = f"Error running ChuckAgent: {str(e)}"
274
+ logger.error(error_msg, exc_info=True)
275
+ return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
276
+
277
+ async def shutdown(self):
278
+ logger.info("ChuckAgent shutting down...")
279
+ await close_shared_http_session()
280
+ logger.info("ChuckAgent shutdown complete.")
281
+
282
+ # --- Core Evaluation Logic ---
283
+ def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
284
+ space_id = os.getenv("SPACE_ID")
285
+ agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Agent code URL not found (SPACE_ID not set)"
286
+ return space_id, agent_code_url
287
+
288
+ def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
289
+ questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
290
+ logger.info(f"Fetching questions from: {questions_url}")
291
  try:
292
+ response = requests.get(questions_url, timeout=30)
293
  response.raise_for_status()
294
  questions_data = response.json()
295
+ if not questions_data or not isinstance(questions_data, list):
296
+ logger.warning(f"Fetched questions empty or invalid: {questions_data}")
297
+ raise ValueError("Fetched questions list is empty or not a list.")
298
+ logger.info(f"Fetched {len(questions_data)} questions.")
299
+ return questions_data
300
  except requests.exceptions.RequestException as e:
301
+ logger.error(f"Error fetching questions: {e}", exc_info=True)
302
+ raise ConnectionError(f"Error fetching questions: {e}") from e
303
+ except (requests.exceptions.JSONDecodeError, ValueError) as e:
304
+ logger.error(f"Error decoding questions JSON or invalid data: {e}. Response text: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
305
+ raise ValueError(f"Error decoding server response for questions: {e}") from e
 
 
 
 
306
 
307
+ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
 
308
  answers_payload = []
309
+ results_log = []
310
+ logger.info(f"Running agent on {len(questions_data)} questions...")
311
+ for i, item in enumerate(questions_data):
312
  task_id = item.get("task_id")
313
  question_text = item.get("question")
314
  if not task_id or question_text is None:
315
+ logger.warning(f"Skipping item {i+1} with missing data: {item}")
316
  continue
317
+ logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
318
+ model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
319
  try:
320
+ model_ans, reasoning = agent(question_text)
 
 
321
  except Exception as e:
322
+ logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
323
+ model_ans = f"AGENT_CALL_ERROR: {e}"
324
+ reasoning = str(e)
325
+
326
+ payload_item = {"task_id": task_id, "model_answer": model_ans}
327
+ if reasoning:
328
+ payload_item["reasoning_trace"] = reasoning
329
+ answers_payload.append(payload_item)
330
+
331
+ results_log.append({
332
+ "Task ID": task_id, "Question": question_text,
333
+ "Submitted Answer": model_ans, "Reasoning Trace": reasoning
334
+ })
335
+ return answers_payload, results_log
336
 
337
+ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answers_payload: List[Dict[str, Any]]) -> str:
338
  if not answers_payload:
339
+ logger.warning("Agent did not produce any answers to submit.")
340
+ return "Agent did not produce any answers to submit."
 
 
 
 
 
341
 
342
+ submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
343
+ submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
344
+ logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...")
345
  try:
346
  response = requests.post(submit_url, json=submission_data, timeout=60)
347
  response.raise_for_status()
348
  result_data = response.json()
349
+ return (
350
+ f"Submission Successful!\nUser: {result_data.get('username', 'N/A')}\n"
 
351
  f"Overall Score: {result_data.get('score', 'N/A')}% "
352
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
353
  f"Message: {result_data.get('message', 'No message received.')}"
354
  )
 
 
 
355
  except requests.exceptions.HTTPError as e:
356
+ error_detail = f"Server responded with {e.response.status_code}."
357
  try:
358
  error_json = e.response.json()
359
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
360
  except requests.exceptions.JSONDecodeError:
361
+ error_detail += f" Raw Response: {e.response.text[:500]}"
362
+ logger.error(f"Submission Failed: {error_detail}")
363
+ return f"Submission Failed: {error_detail}"
 
 
364
  except requests.exceptions.Timeout:
365
+ logger.error("Submission Failed: The request timed out.")
366
+ return "Submission Failed: The request timed out."
 
 
367
  except requests.exceptions.RequestException as e:
368
+ logger.error(f"Submission Failed: Network error - {e}", exc_info=True)
369
+ return f"Submission Failed: Network error - {e}"
370
+ except Exception as e:
371
+ logger.error(f"An unexpected error occurred during submission: {e}", exc_info=True)
372
+ return f"An unexpected error occurred during submission: {e}"
373
+
374
+ # --- Gradio Interface Main Function ---
375
+ GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
376
+
377
+ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile]) -> Tuple[str, pd.DataFrame]:
378
+ global GLOBAL_CHUCK_AGENT
379
+ logger.info(f"run_and_submit_all_evaluation called. Profile: {profile.username if profile else 'None'}")
380
+
381
+ if not profile:
382
+ logger.warning("User not logged in for evaluation.")
383
+ return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
384
+
385
+ username = profile.username
386
+ logger.info(f"User logged in: {username}")
387
+
388
+ _, agent_code_url = get_space_id_agent_code_url()
389
+ logger.info(f"Agent code URL: {agent_code_url}")
390
+ results_log_data: List[Dict[str, Any]] = []
391
+
392
+ try:
393
+ if GLOBAL_CHUCK_AGENT is None:
394
+ GLOBAL_CHUCK_AGENT = ChuckAgent()
395
+ agent = GLOBAL_CHUCK_AGENT
396
+ except EnvironmentError as e:
397
+ logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
398
+ return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
399
  except Exception as e:
400
+ logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
401
+ return f"Error initializing agent: {e}", pd.DataFrame()
 
 
402
 
403
+ try:
404
+ questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
405
+ answers_payload, results_log_data = process_all_questions(agent, questions_data)
406
+ submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
407
+ except (ConnectionError, ValueError) as e:
408
+ submission_status = str(e)
409
+ except Exception as e:
410
+ logger.error(f"An unexpected error occurred during evaluation pipeline: {e}", exc_info=True)
411
+ submission_status = f"An unexpected error occurred: {e}"
412
+
413
+ results_df = pd.DataFrame(results_log_data if results_log_data else [])
414
+ return submission_status, results_df
415
 
416
+ # --- Build Gradio Interface ---
417
+ # This is the UI part that was adjusted to look more like the screenshot
418
  with gr.Blocks() as demo:
419
  gr.Markdown("# Basic Agent Evaluation Runner")
420
+
421
  gr.Markdown(
422
  """
423
  **Instructions:**
424
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
425
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
426
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
427
+ """
428
+ )
429
 
430
+ gr.Markdown(
431
+ """
432
+ **Disclaimers:** 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). 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 separate action or even to answer the questions in async.
433
+ """
434
+ )
435
+
436
+ gr.Markdown(
437
+ f"""
438
  ---
439
+ **Technical Notes:**
440
+ * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
441
+ * Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
442
+ * `requirements.txt` should specify `gradio>=4.19.2` or newer.
443
+ * Consider trying `OPENAI_MODEL_ID = "gpt-3.5-turbo"` (current default) or `"gpt-4"` in the script for different performance/capability.
444
  """
445
  )
446
 
447
+ login_button = gr.LoginButton()
 
448
  run_button = gr.Button("Run Evaluation & Submit All Answers")
449
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
450
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True, max_rows=20)
 
 
451
 
452
  run_button.click(
453
+ fn=run_and_submit_all_evaluation,
454
+ inputs=[login_button],
455
  outputs=[status_output, results_table]
456
  )
457
 
458
+ # --- Application Startup & Shutdown Handling ---
459
  if __name__ == "__main__":
460
  print("\n" + "-"*30 + " App Starting " + "-"*30)
 
461
  space_host_startup = os.getenv("SPACE_HOST")
462
+ space_id_startup, agent_url_startup = get_space_id_agent_code_url()
463
 
464
  if space_host_startup:
465
  print(f"✅ SPACE_HOST found: {space_host_startup}")
466
+ print(f" Runtime URL might be: https://{space_host_startup}")
467
  else:
468
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
469
 
470
+ if space_id_startup:
471
  print(f"✅ SPACE_ID found: {space_id_startup}")
472
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
473
+ print(f" Agent Code URL reported to server: {agent_url_startup}")
474
  else:
475
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
476
+
477
+ print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
478
+ print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}") # For visibility
479
  print("-"*(60 + len(" App Starting ")) + "\n")
480
+ print("Launching Gradio Interface for Chuck Agent Evaluation...")
481
+
482
+ try:
483
+ demo.launch(debug=True, share=False)
484
+ finally:
485
+ # Attempt to gracefully close the aiohttp session on exit
486
+ # This part is a bit tricky with how Gradio's launch() blocks
487
+ # and how different environments handle script termination.
488
+ loop_to_use = None
489
+ if GLOBAL_CHUCK_AGENT and hasattr(GLOBAL_CHUCK_AGENT, 'http_session') and GLOBAL_CHUCK_AGENT.http_session:
490
+ loop_to_use = GLOBAL_CHUCK_AGENT.http_session.loop
491
+ elif SHARED_HTTP_SESSION:
492
+ loop_to_use = SHARED_HTTP_SESSION.loop
493
+
494
+ if loop_to_use and loop_to_use.is_running():
495
+ logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
496
+ # Ensure we are using the correct event loop that the session was created with.
497
+ # This can be complex if multiple loops were involved or if the main loop closed.
498
+ try:
499
+ current_loop = asyncio.get_event_loop()
500
+ if current_loop is not loop_to_use:
501
+ asyncio.set_event_loop(loop_to_use)
502
+
503
+ if GLOBAL_CHUCK_AGENT:
504
+ loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
505
+ elif SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed: # Fallback
506
+ loop_to_use.run_until_complete(close_shared_http_session())
507
 
508
+ except Exception as e:
509
+ logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
510
+ else:
511
+ logger.info("No active HTTP session or loop to close in finally block.")