GoodLuckChuck commited on
Commit
b3c85d5
·
verified ·
1 Parent(s): 39cfefc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +195 -182
app.py CHANGED
@@ -1,16 +1,14 @@
1
  import os
2
- import gradio as gr # Make sure this import is present
3
  import requests
4
- # inspect is not used, can be removed
5
  import pandas as pd
6
  import asyncio
7
  import re
8
  import json
9
- import math
10
  import logging
11
- import operator
12
  import aiohttp
13
- from typing import Optional, Dict, Any, List, Union
14
 
15
  # Import necessary components from smolagents
16
  try:
@@ -23,48 +21,65 @@ except ImportError:
23
  class CodeAgent: pass
24
  class Tool: pass
25
  class OpenAIServerModel: pass
26
- # class AgentOutput: pass
27
-
28
 
29
  from datetime import datetime
30
 
31
- # --- Constants ---
32
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
33
- OUTPUT_DOC_PATH = "agent_answers.jsonl" # Not actively used in this script for submission
34
- SCREENSHOTS_DIR = "screenshots"
35
-
36
- # Configure logging
 
 
 
 
 
 
 
 
 
 
 
37
  logging.basicConfig(
38
  level=logging.INFO,
39
  format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
40
  logger = logging.getLogger(__name__)
41
 
42
- # Ensure screenshots directory exists
43
- os.makedirs(SCREENSHOTS_DIR, exist_ok=True)
 
 
44
 
45
- # --- Tool Definitions (Largely Unchanged, but ensure descriptions are good for the LLM) ---
 
 
46
  class ImageRetrievalTool(Tool):
47
  name = "image_retriever"
48
  description = "Retrieves and processes images from web pages. Input is a URL to an image."
49
  inputs = {"url": {"type": "string", "description": "The URL of the image to retrieve"}}
50
- output_type = "string" # Output a message or image identifier
51
 
52
  def __init__(self):
53
  super().__init__()
54
- self.image_memory = {}
55
  self.screenshot_count = 0
56
 
57
- async def forward(self, url: str) -> str: # Changed output to string for simplicity
58
  logger.info(f"ImageRetrievalTool called with URL: {url}")
59
  try:
60
  async with aiohttp.ClientSession() as session:
61
  async with session.get(url) as response:
62
  response.raise_for_status()
63
- image_data = await response.read() # In a real scenario, you might save this
64
  image_id = f"image_{self.screenshot_count}"
65
- self.image_memory[image_id] = {'data': image_data, 'url': url, 'timestamp': datetime.now().isoformat()}
 
 
 
 
66
  self.screenshot_count += 1
67
- return f"Image retrieved successfully from {url}. Stored as {image_id}."
68
  except Exception as e:
69
  logger.error(f"Error retrieving image {url}: {str(e)}")
70
  return f"Error retrieving image: {str(e)}"
@@ -84,7 +99,7 @@ class WebSearchTool(Tool):
84
 
85
  url = "https://google.serper.dev/search"
86
  headers = {'X-API-KEY': serper_api_key, 'Content-Type': 'application/json'}
87
- payload = json.dumps({'q': query, 'num': 3}) # Request fewer results for faster processing
88
 
89
  try:
90
  async with aiohttp.ClientSession() as session:
@@ -96,22 +111,22 @@ class WebSearchTool(Tool):
96
  logger.error(f"Error performing search for '{query}': {str(e)}")
97
  return f"Error performing search: {str(e)}"
98
 
99
- def _format_results(self, data: Dict) -> str:
100
  results = []
101
  if 'organic' in data and data['organic']:
102
- for result in data['organic'][:3]: # Limit to top 3
103
  title = result.get('title', 'N/A')
104
  snippet = result.get('snippet', 'N/A')
105
- # link = result.get('link', '#') # Links might not be useful for the LLM context
106
  results.append(f"Title: {title}\nSnippet: {snippet}\n---")
107
  if not results and 'knowledgeGraph' in data:
108
  kg = data['knowledgeGraph']
109
  title = kg.get('title', '')
110
  description = kg.get('description', '')
111
  if title or description:
112
- results.append(f"Knowledge Graph: {title}\n{description}\n---")
 
113
  formatted_output = "\n".join(results) if results else "No relevant search results found."
114
- return formatted_output[:3000] # Truncate to keep context manageable
115
 
116
  class CalculatorTool(Tool):
117
  name = "calculator"
@@ -126,15 +141,15 @@ class CalculatorTool(Tool):
126
  '*': operator.mul, '/': operator.truediv,
127
  '^': operator.pow
128
  }
 
129
 
130
  async def forward(self, expression: str) -> str:
131
  logger.info(f"CalculatorTool called with expression: {expression}")
132
  try:
133
- # More robust sanitization
134
- safe_expr = "".join(c for c in expression if c in "0123456789+-*/^(). ")
135
  if not safe_expr:
136
  return "Error: Empty or invalid expression for calculator."
137
- # Using a safer eval approach is complex; this remains a simplified version.
138
  # For production, a proper math expression parser is crucial.
139
  result = eval(safe_expr, {"__builtins__": {}}, self.operations) # type: ignore
140
  return f"Calculation result: {safe_expr} = {float(result)}"
@@ -147,66 +162,50 @@ class QuestionAnsweringAgent(CodeAgent):
147
  def __init__(self, model: Optional[OpenAIServerModel] = None):
148
  tools = [WebSearchTool(), CalculatorTool(), ImageRetrievalTool()]
149
 
150
- if model is None:
151
- if not os.environ.get('OPENAI_API_KEY'):
 
 
152
  raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
153
- model = OpenAIServerModel(
154
- model_id="gpt-4", # Consider "gpt-3.5-turbo" for faster/cheaper testing
155
- api_key=os.environ.get('OPENAI_API_KEY')
156
  )
157
 
158
- # MODIFICATION 2: Use the specified system prompt
159
- 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."""
160
-
161
  super().__init__(
162
  tools=tools,
163
- model=model,
164
- system_prompt=system_prompt,
165
- additional_authorized_imports=["PIL"],
166
- max_steps=10,
167
- verbosity_level=2
168
  )
169
- self.step_count = 0
170
- logger.info("QuestionAnsweringAgent initialized with tools and new system prompt.")
171
 
172
- async def process_question(self, question_data: str) -> tuple[str, str]: # Return (final_answer, reasoning_trace)
173
- full_agent_response = ""
174
- final_answer_for_submission = ""
175
  reasoning_trace = "Agent execution started."
 
176
  try:
177
- logger.info(f"Processing question with CodeAgent: {question_data[:100]}...")
178
- self.step_count += 1
179
-
180
- # self.run() is the method from CodeAgent to execute the task
181
- # It should return the full text output from the LLM, including thoughts and FINAL ANSWER
182
- # The exact return type of self.run() might need checking in smolagents docs
183
- # It could be a string, or an object with more details.
184
- raw_output = await self.run(question_data)
185
- full_agent_response = str(raw_output) # Assuming it's a string or can be stringified
186
- reasoning_trace = full_agent_response # Use the full response as the trace for now
187
-
188
- logger.info(f"CodeAgent full response: {full_agent_response[:500]}...")
189
-
190
- # MODIFICATION 2 (continued): Extract the final answer
191
  match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
192
  if match:
193
  final_answer_for_submission = match.group(1).strip()
194
- # Further clean up if necessary, e.g., removing trailing thoughts
195
- # For now, this takes everything after "FINAL ANSWER:"
196
  logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
197
  else:
198
- logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response.")
199
- # As per instructions, if "FINAL ANSWER" is not found, this might be an issue.
200
- # However, the scoring server note says "don't include the text 'FINAL ANSWER' in your submission"
201
- # This implies the agent *should* be producing it, and we extract the content.
202
- # If it's not producing it, then the raw_output might be the best guess, but it's not ideal.
203
- final_answer_for_submission = full_agent_response.strip() # Fallback, might be incorrect for submission
204
-
205
- if not final_answer_for_submission: # If empty after stripping
206
  logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
207
  final_answer_for_submission = "Could not determine answer."
208
 
209
-
210
  except Exception as e:
211
  logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}", exc_info=True)
212
  final_answer_for_submission = f"Error in agent processing: {str(e)}"
@@ -214,7 +213,7 @@ class QuestionAnsweringAgent(CodeAgent):
214
 
215
  return final_answer_for_submission, reasoning_trace
216
 
217
- # Adapter to fit interface with original app.py
218
  class ChuckAgent:
219
  def __init__(self):
220
  required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
@@ -226,138 +225,113 @@ class ChuckAgent:
226
 
227
  logger.info("ChuckAgent initialization started")
228
  self.agent = QuestionAnsweringAgent()
229
- self.loop = asyncio.new_event_loop()
230
- asyncio.set_event_loop(self.loop)
 
 
 
 
231
  logger.info("ChuckAgent fully initialized")
232
 
233
- # MODIFICATION 3: __call__ should now return a tuple (answer, reasoning_trace)
234
- def __call__(self, question: str) -> tuple[str, str]:
235
  logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
236
- final_answer_for_submission = "Error: Agent call failed"
237
- reasoning_trace = "No reasoning trace generated due to an error."
238
  try:
239
- # process_question now returns a tuple
240
- final_answer_for_submission, reasoning_trace = self.loop.run_until_complete(
241
  self.agent.process_question(question)
242
  )
243
- logger.info(f"ChuckAgent returning answer (first 50 chars): {final_answer_for_submission[:50]}...")
244
- return final_answer_for_submission, reasoning_trace
245
  except Exception as e:
246
  error_msg = f"Error running ChuckAgent: {str(e)}"
247
  logger.error(error_msg, exc_info=True)
248
- # Ensure tuple is returned even in case of error before process_question
249
  return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
250
 
 
 
 
 
 
 
251
 
252
- # MODIFICATION for Gradio `ClickData` AttributeError:
253
- # Reverting to simpler signature for `run_and_submit_all` temporarily.
254
- # The AttributeError: module 'gradio' has no attribute 'ClickData'
255
- # needs to be solved by ensuring the correct Gradio version in requirements.txt.
256
- # For now, this signature will accept the profile and use *args for others.
257
- def run_and_submit_all(profile: gr.OAuthProfile | None, *args): # Using *args
258
- logger.info(f"run_and_submit_all called. Profile: {profile.username if profile else 'None'}")
259
- if args:
260
- logger.info(f"Additional args received by run_and_submit_all: {args}")
261
-
262
-
263
- space_id = os.getenv("SPACE_ID")
264
-
265
- if not profile:
266
- logger.warning("User not logged in for run_and_submit_all.")
267
- return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
268
-
269
- username = profile.username
270
- logger.info(f"User logged in: {username}")
271
-
272
- api_url = DEFAULT_API_URL
273
- questions_url = f"{api_url}/questions"
274
- submit_url = f"{api_url}/submit"
275
-
276
- try:
277
- agent = ChuckAgent()
278
- except EnvironmentError as e:
279
- logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
280
- return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
281
- except Exception as e:
282
- logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
283
- return f"Error initializing agent: {e}", pd.DataFrame()
284
-
285
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Agent code URL not found"
286
- logger.info(f"Agent code URL: {agent_code}")
287
-
288
  logger.info(f"Fetching questions from: {questions_url}")
289
  try:
290
  response = requests.get(questions_url, timeout=30)
291
  response.raise_for_status()
292
  questions_data = response.json()
293
  if not questions_data or not isinstance(questions_data, list):
294
- logger.warning(f"Fetched questions empty or invalid: {questions_data}")
295
- return "Fetched questions list is empty or not a list.", pd.DataFrame()
296
  logger.info(f"Fetched {len(questions_data)} questions.")
 
297
  except requests.exceptions.RequestException as e:
298
  logger.error(f"Error fetching questions: {e}", exc_info=True)
299
- return f"Error fetching questions: {e}", pd.DataFrame()
300
- except requests.exceptions.JSONDecodeError as e:
301
- logger.error(f"Error decoding questions JSON: {e}. Response: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
302
- return f"Error decoding server response for questions: {e}", pd.DataFrame()
303
- except Exception as e:
304
- logger.error(f"Unexpected error fetching questions: {e}", exc_info=True)
305
- return f"An unexpected error occurred fetching questions: {e}", pd.DataFrame()
306
 
307
- results_log = []
 
308
  answers_payload = []
 
309
  logger.info(f"Running agent on {len(questions_data)} questions...")
 
310
  for i, item in enumerate(questions_data):
311
  task_id = item.get("task_id")
312
  question_text = item.get("question")
 
313
  if not task_id or question_text is None:
314
- logger.warning(f"Skipping item with missing data: {item}")
315
  continue
316
 
317
  logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
 
318
  try:
319
- # MODIFICATION 3: Agent now returns a tuple (answer, reasoning_trace)
320
  model_ans, reasoning = agent(question_text)
321
-
322
- # Prepare payload item
323
- payload_item = {"task_id": task_id, "model_answer": model_ans}
324
- if reasoning: # Add reasoning_trace if it's available and not empty
325
- payload_item["reasoning_trace"] = reasoning
326
- answers_payload.append(payload_item)
327
-
328
- results_log.append({
329
- "Task ID": task_id,
330
- "Question": question_text,
331
- "Submitted Answer": model_ans,
332
- "Reasoning Trace": reasoning
333
- })
334
  except Exception as e:
335
- logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
336
- error_answer = f"AGENT_CALL_ERROR: {e}"
337
- answers_payload.append({"task_id": task_id, "model_answer": error_answer, "reasoning_trace": str(e)})
338
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": error_answer, "Reasoning Trace": str(e)})
339
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340
  if not answers_payload:
341
- logger.warning("Agent did not produce any answers.")
342
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log if results_log else [])
343
 
344
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
 
345
  logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...")
346
  # logger.debug(f"Submission payload: {json.dumps(submission_data, indent=2)}")
347
 
348
-
349
  try:
350
  response = requests.post(submit_url, json=submission_data, timeout=60)
351
  response.raise_for_status()
352
  result_data = response.json()
353
- final_status = (
354
  f"Submission Successful!\n"
355
  f"User: {result_data.get('username', 'N/A')}\n"
356
  f"Overall Score: {result_data.get('score', 'N/A')}% "
357
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
358
  f"Message: {result_data.get('message', 'No message received.')}"
359
  )
360
- logger.info("Submission successful.")
361
  except requests.exceptions.HTTPError as e:
362
  error_detail = f"Server responded with {e.response.status_code}."
363
  try:
@@ -365,54 +339,92 @@ def run_and_submit_all(profile: gr.OAuthProfile | None, *args): # Using *args
365
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
366
  except requests.exceptions.JSONDecodeError:
367
  error_detail += f" Raw Response: {e.response.text[:500]}"
368
- final_status = f"Submission Failed: {error_detail}"
369
- logger.error(final_status)
370
  except requests.exceptions.Timeout:
371
- final_status = "Submission Failed: The request timed out."
372
- logger.error(final_status)
373
  except requests.exceptions.RequestException as e:
374
- final_status = f"Submission Failed: Network error - {e}"
375
- logger.error(final_status, exc_info=True)
376
- except Exception as e:
377
- final_status = f"An unexpected error occurred during submission: {e}"
378
- logger.error(final_status, exc_info=True)
379
-
380
- results_df = pd.DataFrame(results_log if results_log else [])
381
- return final_status, results_df
382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383
 
384
- # --- Build Gradio Interface using Blocks ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
385
  with gr.Blocks() as demo:
386
  gr.Markdown("# Chuck Agent Evaluation Runner")
387
  gr.Markdown(
388
- """
389
  **Instructions:**
390
  1. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
391
  2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
392
  ---
393
- **Note:** The agent uses `smolagents`, OpenAI, and Serper API for searches.
394
  Make sure you have the following **Secrets** correctly set in your Hugging Face Space settings:
395
  - `OPENAI_API_KEY` (Your OpenAI API key)
396
  - `SERPER_API_KEY` (Your Serper API key)
397
- Ensure your `requirements.txt` specifies `gradio>=4.19.2` or newer.
398
  """
399
  )
400
 
401
- login_button = gr.LoginButton()
402
  run_button = gr.Button("Run Evaluation & Submit All Answers")
403
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False) # Increased lines
404
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) # Show more rows
405
 
 
 
406
  run_button.click(
407
- fn=run_and_submit_all,
408
  inputs=[login_button],
409
  outputs=[status_output, results_table]
410
  )
411
 
 
412
  if __name__ == "__main__":
413
  print("\n" + "-"*30 + " App Starting " + "-"*30)
414
  space_host_startup = os.getenv("SPACE_HOST")
415
- space_id_startup = os.getenv("SPACE_ID")
416
 
417
  if space_host_startup:
418
  print(f"✅ SPACE_HOST found: {space_host_startup}")
@@ -420,13 +432,14 @@ if __name__ == "__main__":
420
  else:
421
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
422
 
423
- if space_id_startup:
424
  print(f"✅ SPACE_ID found: {space_id_startup}")
425
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
426
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
427
  else:
428
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
429
-
 
430
  print("-"*(60 + len(" App Starting ")) + "\n")
431
 
432
  print("Launching Gradio Interface for Chuck Agent Evaluation...")
 
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 # Changed Union to Tuple for return types
12
 
13
  # Import necessary components from smolagents
14
  try:
 
21
  class CodeAgent: pass
22
  class Tool: pass
23
  class OpenAIServerModel: pass
 
 
24
 
25
  from datetime import datetime
26
 
27
+ # --- Configuration ---
28
+ class AppConfig:
29
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
30
+ QUESTIONS_URL_PATH = "/questions"
31
+ SUBMIT_URL_PATH = "/submit"
32
+ SCREENSHOTS_DIR = "screenshots"
33
+ OPENAI_MODEL_ID = "gpt-4" # Consider "gpt-3.5-turbo" for faster/cheaper testing
34
+ SERPER_API_NUM_RESULTS = 3 # Number of search results to request and process
35
+ WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000 # Max characters for web search output
36
+ AGENT_MAX_STEPS = 10
37
+ AGENT_VERBOSITY_LEVEL = 2
38
+ # System prompt for the agent
39
+ 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."""
40
+
41
+ CONFIG = AppConfig()
42
+
43
+ # --- Logging Setup ---
44
  logging.basicConfig(
45
  level=logging.INFO,
46
  format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
47
  logger = logging.getLogger(__name__)
48
 
49
+ # --- Utility Functions ---
50
+ def ensure_dir_exists(directory_path: str):
51
+ """Creates a directory if it doesn't already exist."""
52
+ os.makedirs(directory_path, exist_ok=True)
53
 
54
+ ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)
55
+
56
+ # --- Tool Definitions ---
57
  class ImageRetrievalTool(Tool):
58
  name = "image_retriever"
59
  description = "Retrieves and processes images from web pages. Input is a URL to an image."
60
  inputs = {"url": {"type": "string", "description": "The URL of the image to retrieve"}}
61
+ output_type = "string"
62
 
63
  def __init__(self):
64
  super().__init__()
65
+ self.image_memory: Dict[str, Dict[str, Any]] = {}
66
  self.screenshot_count = 0
67
 
68
+ async def forward(self, url: str) -> str:
69
  logger.info(f"ImageRetrievalTool called with URL: {url}")
70
  try:
71
  async with aiohttp.ClientSession() as session:
72
  async with session.get(url) as response:
73
  response.raise_for_status()
74
+ image_data = await response.read()
75
  image_id = f"image_{self.screenshot_count}"
76
+ self.image_memory[image_id] = {
77
+ 'data': image_data, # In a real app, you might save this to SCREENSHOTS_DIR
78
+ 'url': url,
79
+ 'timestamp': datetime.now().isoformat()
80
+ }
81
  self.screenshot_count += 1
82
+ return f"Image retrieved successfully from {url}. Stored in memory as {image_id}."
83
  except Exception as e:
84
  logger.error(f"Error retrieving image {url}: {str(e)}")
85
  return f"Error retrieving image: {str(e)}"
 
99
 
100
  url = "https://google.serper.dev/search"
101
  headers = {'X-API-KEY': serper_api_key, 'Content-Type': 'application/json'}
102
+ payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
103
 
104
  try:
105
  async with aiohttp.ClientSession() as session:
 
111
  logger.error(f"Error performing search for '{query}': {str(e)}")
112
  return f"Error performing search: {str(e)}"
113
 
114
+ def _format_results(self, data: Dict[str, Any]) -> str:
115
  results = []
116
  if 'organic' in data and data['organic']:
117
+ for result in data['organic'][:CONFIG.SERPER_API_NUM_RESULTS]:
118
  title = result.get('title', 'N/A')
119
  snippet = result.get('snippet', 'N/A')
 
120
  results.append(f"Title: {title}\nSnippet: {snippet}\n---")
121
  if not results and 'knowledgeGraph' in data:
122
  kg = data['knowledgeGraph']
123
  title = kg.get('title', '')
124
  description = kg.get('description', '')
125
  if title or description:
126
+ results.append(f"Knowledge Graph: {title}\n{description}\n---")
127
+
128
  formatted_output = "\n".join(results) if results else "No relevant search results found."
129
+ return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
130
 
131
  class CalculatorTool(Tool):
132
  name = "calculator"
 
141
  '*': operator.mul, '/': operator.truediv,
142
  '^': operator.pow
143
  }
144
+ self.allowed_chars = "0123456789+-*/^(). "
145
 
146
  async def forward(self, expression: str) -> str:
147
  logger.info(f"CalculatorTool called with expression: {expression}")
148
  try:
149
+ safe_expr = "".join(c for c in expression if c in self.allowed_chars)
 
150
  if not safe_expr:
151
  return "Error: Empty or invalid expression for calculator."
152
+ # WARNING: eval() is dangerous. This is a simplified, non-production-safe version.
153
  # For production, a proper math expression parser is crucial.
154
  result = eval(safe_expr, {"__builtins__": {}}, self.operations) # type: ignore
155
  return f"Calculation result: {safe_expr} = {float(result)}"
 
162
  def __init__(self, model: Optional[OpenAIServerModel] = None):
163
  tools = [WebSearchTool(), CalculatorTool(), ImageRetrievalTool()]
164
 
165
+ effective_model = model
166
+ if effective_model is None:
167
+ openai_api_key = os.environ.get('OPENAI_API_KEY')
168
+ if not openai_api_key:
169
  raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
170
+ effective_model = OpenAIServerModel(
171
+ model_id=CONFIG.OPENAI_MODEL_ID,
172
+ api_key=openai_api_key
173
  )
174
 
 
 
 
175
  super().__init__(
176
  tools=tools,
177
+ model=effective_model,
178
+ system_prompt=CONFIG.AGENT_SYSTEM_PROMPT,
179
+ additional_authorized_imports=["PIL"], # If PIL is needed by agent-generated code
180
+ max_steps=CONFIG.AGENT_MAX_STEPS,
181
+ verbosity_level=CONFIG.AGENT_VERBOSITY_LEVEL
182
  )
183
+ logger.info("QuestionAnsweringAgent initialized.")
 
184
 
185
+ async def process_question(self, question_text: str) -> Tuple[str, str]:
186
+ """Processes a question and returns the final answer and reasoning trace."""
 
187
  reasoning_trace = "Agent execution started."
188
+ final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
189
  try:
190
+ logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
191
+ raw_output = await self.run(question_text) # self.run() is from CodeAgent
192
+ full_agent_response = str(raw_output)
193
+ reasoning_trace = full_agent_response # Use the full response as the trace
194
+
195
+ logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
196
+
 
 
 
 
 
 
 
197
  match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
198
  if match:
199
  final_answer_for_submission = match.group(1).strip()
 
 
200
  logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
201
  else:
202
+ logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback (may be incorrect for submission).")
203
+ final_answer_for_submission = full_agent_response.strip()
204
+
205
+ if not final_answer_for_submission:
 
 
 
 
206
  logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
207
  final_answer_for_submission = "Could not determine answer."
208
 
 
209
  except Exception as e:
210
  logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}", exc_info=True)
211
  final_answer_for_submission = f"Error in agent processing: {str(e)}"
 
213
 
214
  return final_answer_for_submission, reasoning_trace
215
 
216
+ # --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
217
  class ChuckAgent:
218
  def __init__(self):
219
  required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
 
225
 
226
  logger.info("ChuckAgent initialization started")
227
  self.agent = QuestionAnsweringAgent()
228
+ # Get or create an event loop for the current context if needed
229
+ try:
230
+ self.loop = asyncio.get_running_loop()
231
+ except RuntimeError: # No running event loop
232
+ self.loop = asyncio.new_event_loop()
233
+ asyncio.set_event_loop(self.loop)
234
  logger.info("ChuckAgent fully initialized")
235
 
236
+ def __call__(self, question: str) -> Tuple[str, str]:
 
237
  logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
 
 
238
  try:
239
+ final_answer, reasoning_trace = self.loop.run_until_complete(
 
240
  self.agent.process_question(question)
241
  )
242
+ logger.info(f"ChuckAgent returning answer (first 50 chars): {final_answer[:50]}...")
243
+ return final_answer, reasoning_trace
244
  except Exception as e:
245
  error_msg = f"Error running ChuckAgent: {str(e)}"
246
  logger.error(error_msg, exc_info=True)
 
247
  return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
248
 
249
+ # --- Core Evaluation Logic ---
250
+ def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
251
+ """Retrieves Space ID and constructs the agent code URL."""
252
+ space_id = os.getenv("SPACE_ID")
253
+ 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)"
254
+ return space_id, agent_code_url
255
 
256
+ def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
257
+ """Fetches questions from the evaluation server."""
258
+ questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  logger.info(f"Fetching questions from: {questions_url}")
260
  try:
261
  response = requests.get(questions_url, timeout=30)
262
  response.raise_for_status()
263
  questions_data = response.json()
264
  if not questions_data or not isinstance(questions_data, list):
265
+ logger.warning(f"Fetched questions empty or invalid: {questions_data}")
266
+ raise ValueError("Fetched questions list is empty or not a list.")
267
  logger.info(f"Fetched {len(questions_data)} questions.")
268
+ return questions_data
269
  except requests.exceptions.RequestException as e:
270
  logger.error(f"Error fetching questions: {e}", exc_info=True)
271
+ raise ConnectionError(f"Error fetching questions: {e}") from e
272
+ except (requests.exceptions.JSONDecodeError, ValueError) as e: # Catch ValueError from our check
273
+ logger.error(f"Error decoding questions JSON or invalid data: {e}. Response: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
274
+ raise ValueError(f"Error decoding server response for questions: {e}") from e
 
 
 
275
 
276
+ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
277
+ """Runs the agent on all questions and logs results."""
278
  answers_payload = []
279
+ results_log = []
280
  logger.info(f"Running agent on {len(questions_data)} questions...")
281
+
282
  for i, item in enumerate(questions_data):
283
  task_id = item.get("task_id")
284
  question_text = item.get("question")
285
+
286
  if not task_id or question_text is None:
287
+ logger.warning(f"Skipping item {i+1} with missing data: {item}")
288
  continue
289
 
290
  logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
291
+ model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
292
  try:
 
293
  model_ans, reasoning = agent(question_text)
 
 
 
 
 
 
 
 
 
 
 
 
 
294
  except Exception as e:
295
+ logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
296
+ model_ans = f"AGENT_CALL_ERROR: {e}"
297
+ reasoning = str(e)
298
+
299
+ payload_item = {"task_id": task_id, "model_answer": model_ans}
300
+ if reasoning: # Add reasoning_trace if it's available and not empty
301
+ payload_item["reasoning_trace"] = reasoning
302
+ answers_payload.append(payload_item)
303
+
304
+ results_log.append({
305
+ "Task ID": task_id,
306
+ "Question": question_text,
307
+ "Submitted Answer": model_ans,
308
+ "Reasoning Trace": reasoning
309
+ })
310
+ return answers_payload, results_log
311
+
312
+ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answers_payload: List[Dict[str, Any]]) -> str:
313
+ """Submits answers to the evaluation server."""
314
  if not answers_payload:
315
+ logger.warning("Agent did not produce any answers to submit.")
316
+ return "Agent did not produce any answers to submit."
317
 
318
+ submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
319
+ submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
320
+
321
  logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...")
322
  # logger.debug(f"Submission payload: {json.dumps(submission_data, indent=2)}")
323
 
 
324
  try:
325
  response = requests.post(submit_url, json=submission_data, timeout=60)
326
  response.raise_for_status()
327
  result_data = response.json()
328
+ return (
329
  f"Submission Successful!\n"
330
  f"User: {result_data.get('username', 'N/A')}\n"
331
  f"Overall Score: {result_data.get('score', 'N/A')}% "
332
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
333
  f"Message: {result_data.get('message', 'No message received.')}"
334
  )
 
335
  except requests.exceptions.HTTPError as e:
336
  error_detail = f"Server responded with {e.response.status_code}."
337
  try:
 
339
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
340
  except requests.exceptions.JSONDecodeError:
341
  error_detail += f" Raw Response: {e.response.text[:500]}"
342
+ logger.error(f"Submission Failed: {error_detail}")
343
+ return f"Submission Failed: {error_detail}"
344
  except requests.exceptions.Timeout:
345
+ logger.error("Submission Failed: The request timed out.")
346
+ return "Submission Failed: The request timed out."
347
  except requests.exceptions.RequestException as e:
348
+ logger.error(f"Submission Failed: Network error - {e}", exc_info=True)
349
+ return f"Submission Failed: Network error - {e}"
350
+ except Exception as e: # Catch any other unexpected error during submission
351
+ logger.error(f"An unexpected error occurred during submission: {e}", exc_info=True)
352
+ return f"An unexpected error occurred during submission: {e}"
 
 
 
353
 
354
+ # --- Gradio Interface Main Function ---
355
+ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile]) -> Tuple[str, pd.DataFrame]:
356
+ logger.info(f"run_and_submit_all_evaluation called. Profile: {profile.username if profile else 'None'}")
357
+
358
+ if not profile:
359
+ logger.warning("User not logged in for evaluation.")
360
+ return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
361
+
362
+ username = profile.username
363
+ logger.info(f"User logged in: {username}")
364
+
365
+ _, agent_code_url = get_space_id_agent_code_url()
366
+ logger.info(f"Agent code URL: {agent_code_url}")
367
+
368
+ results_log_data: List[Dict[str, Any]] = [] # Ensure it's always defined
369
 
370
+ try:
371
+ agent = ChuckAgent()
372
+ except EnvironmentError as e:
373
+ logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
374
+ return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
375
+ except Exception as e: # Catch any other agent instantiation error
376
+ logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
377
+ return f"Error initializing agent: {e}", pd.DataFrame()
378
+
379
+ try:
380
+ questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
381
+ answers_payload, results_log_data = process_all_questions(agent, questions_data)
382
+ submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
383
+
384
+ except (ConnectionError, ValueError) as e: # Errors from fetch_questions
385
+ submission_status = str(e) # Already logged by fetch_questions
386
+ except Exception as e: # Catch-all for other unexpected issues in the flow
387
+ logger.error(f"An unexpected error occurred during evaluation pipeline: {e}", exc_info=True)
388
+ submission_status = f"An unexpected error occurred: {e}"
389
+
390
+ results_df = pd.DataFrame(results_log_data if results_log_data else [])
391
+ return submission_status, results_df
392
+
393
+ # --- Build Gradio Interface ---
394
  with gr.Blocks() as demo:
395
  gr.Markdown("# Chuck Agent Evaluation Runner")
396
  gr.Markdown(
397
+ f"""
398
  **Instructions:**
399
  1. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
400
  2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
401
  ---
402
+ **Note:** The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
403
  Make sure you have the following **Secrets** correctly set in your Hugging Face Space settings:
404
  - `OPENAI_API_KEY` (Your OpenAI API key)
405
  - `SERPER_API_KEY` (Your Serper API key)
406
+ Ensure your `requirements.txt` specifies `gradio>=4.19.2` or newer for `gr.LoginButton()`.
407
  """
408
  )
409
 
410
+ login_button = gr.LoginButton()
411
  run_button = gr.Button("Run Evaluation & Submit All Answers")
412
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
413
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True, max_rows=20)
414
 
415
+ # Removed *args from run_and_submit_all_evaluation as it only needs profile
416
+ # Gradio passes inputs based on the list provided.
417
  run_button.click(
418
+ fn=run_and_submit_all_evaluation,
419
  inputs=[login_button],
420
  outputs=[status_output, results_table]
421
  )
422
 
423
+ # --- Application Startup ---
424
  if __name__ == "__main__":
425
  print("\n" + "-"*30 + " App Starting " + "-"*30)
426
  space_host_startup = os.getenv("SPACE_HOST")
427
+ space_id_startup, agent_url_startup = get_space_id_agent_code_url()
428
 
429
  if space_host_startup:
430
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
432
  else:
433
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
434
 
435
+ if space_id_startup:
436
  print(f"✅ SPACE_ID found: {space_id_startup}")
437
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
438
+ print(f" Agent Code URL reported to server: {agent_url_startup}")
439
  else:
440
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
441
+
442
+ print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
443
  print("-"*(60 + len(" App Starting ")) + "\n")
444
 
445
  print("Launching Gradio Interface for Chuck Agent Evaluation...")