GoodLuckChuck commited on
Commit
b27fc9f
·
verified ·
1 Parent(s): d6a4f35

error fixing

Browse files
Files changed (1) hide show
  1. app.py +256 -232
app.py CHANGED
@@ -16,8 +16,12 @@ from typing import Optional, Dict, Any, List, Union
16
  try:
17
  from smolagents import CodeAgent, Tool, OpenAIServerModel
18
  except ImportError:
19
- # Handle if smolagents is not installed
20
- pass
 
 
 
 
21
 
22
  from datetime import datetime
23
 
@@ -29,8 +33,7 @@ SCREENSHOTS_DIR = "screenshots"
29
  # Configure logging
30
  logging.basicConfig(
31
  level=logging.INFO,
32
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
33
- )
34
  logger = logging.getLogger(__name__)
35
 
36
  # Ensure screenshots directory exists
@@ -39,7 +42,7 @@ os.makedirs(SCREENSHOTS_DIR, exist_ok=True)
39
  # --- Tool Definitions ---
40
  class ImageRetrievalTool(Tool):
41
  name = "image_retriever"
42
- description = "Retrieves and processes images from web pages"
43
 
44
  inputs = {
45
  "url": {
@@ -47,34 +50,37 @@ class ImageRetrievalTool(Tool):
47
  "description": "The URL of the image to retrieve"
48
  }
49
  }
50
- output_type = "object"
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) -> Dict[str, Any]:
 
58
  try:
59
  async with aiohttp.ClientSession() as session:
60
  async with session.get(url) as response:
61
- if response.status == 200:
62
- image_data = await response.read()
63
- image_id = f"image_{self.screenshot_count}"
64
- self.image_memory[image_id] = {
65
- 'data': image_data,
66
- 'url': url,
67
- 'timestamp': datetime.now().isoformat()
68
- }
69
- self.screenshot_count += 1
70
- return {"image_id": image_id, "status": "success"}
71
- return {"error": f"Failed to fetch image: {response.status}"}
 
72
  except Exception as e:
 
73
  return {"error": f"Error retrieving image: {str(e)}"}
74
 
75
  class WebSearchTool(Tool):
76
  name = "web_search"
77
- description = "Performs web searches using Serper API"
78
 
79
  inputs = {
80
  "query": {
@@ -82,80 +88,95 @@ class WebSearchTool(Tool):
82
  "description": "The search query to execute"
83
  }
84
  }
85
- output_type = "string"
86
 
87
  async def forward(self, query: str) -> str:
88
- if not os.environ.get('SERPER_API_KEY'):
89
- return "Error: Serper API key not found"
 
 
 
90
 
91
  url = "https://google.serper.dev/search"
92
  headers = {
93
- 'X-API-KEY': os.environ.get('SERPER_API_KEY'),
94
  'Content-Type': 'application/json'
95
  }
96
- payload = {
97
  'q': query,
98
- 'num': 5
99
- }
100
 
101
  try:
102
  async with aiohttp.ClientSession() as session:
103
- async with session.post(url, headers=headers, json=payload) as response:
104
- if response.status == 200:
105
- data = await response.json()
106
- return self._format_results(data)
107
- return f"Error: API returned status code {response.status}"
108
  except Exception as e:
 
109
  return f"Error performing search: {str(e)}"
110
 
111
  def _format_results(self, data: Dict) -> str:
112
  results = []
113
- if 'organic' in data:
114
- for result in data['organic']:
115
- results.append(f"Title: {result.get('title', '')}\n"
116
- f"Snippet: {result.get('snippet', '')}\n")
117
- if 'knowledgeGraph' in data:
 
 
118
  kg = data['knowledgeGraph']
119
- if 'title' in kg:
120
- results.append(f"Knowledge Graph: {kg['title']}\n"
121
- f"{kg.get('description', '')}\n")
122
- return "\n".join(results) if results else "No results found"
 
 
123
 
124
  class CalculatorTool(Tool):
125
  name = "calculator"
126
- description = "Performs mathematical calculations"
127
 
128
  inputs = {
129
  "expression": {
130
  "type": "string",
131
- "description": "The mathematical expression to evaluate"
132
  }
133
  }
134
- output_type = "number"
135
 
136
  def __init__(self):
137
  super().__init__()
 
138
  self.operations = {
139
- '+': operator.add,
140
- '-': operator.sub,
141
- '*': operator.mul,
142
- '/': operator.truediv,
143
- '^': operator.pow,
144
- 'sqrt': math.sqrt,
145
- 'abs': abs
146
  }
 
 
 
147
 
148
- async def forward(self, expression: str) -> Union[float, str]:
 
149
  try:
150
- safe_expr = self._prepare_expression(expression)
151
- result = eval(safe_expr, {"__builtins__": None}, self.operations)
152
- return float(result)
 
 
 
 
 
 
 
153
  except Exception as e:
154
- return f"Error: {str(e)}"
 
155
 
156
- def _prepare_expression(self, expression: str) -> str:
157
- safe_chars = set("0123456789+-*/^(). ")
158
- return ''.join(c for c in expression if c in safe_chars)
159
 
160
  # --- Agent Definition ---
161
  class QuestionAnsweringAgent(CodeAgent):
@@ -163,114 +184,115 @@ class QuestionAnsweringAgent(CodeAgent):
163
  tools = [
164
  WebSearchTool(),
165
  CalculatorTool(),
166
- ImageRetrievalTool()
167
  ]
168
 
169
  if model is None:
170
- model = OpenAIServerModel(model_id="gpt-4")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
  super().__init__(
173
  tools=tools,
174
  model=model,
175
- additional_authorized_imports=["PIL"],
176
- step_callbacks=[self._process_visual_memory],
177
- max_steps=20,
178
- verbosity_level=2
 
179
  )
180
 
181
- self.visual_memory = {}
182
- self.step_count = 0
183
- logger.info("QuestionAnsweringAgent initialized with all tools")
184
 
 
 
185
  async def _process_visual_memory(self, step_num: int, description: str):
186
- if hasattr(self, 'current_observation_images'):
187
- self.visual_memory[step_num] = {
188
- 'images': self.current_observation_images,
189
- 'description': description,
190
- 'timestamp': datetime.now().isoformat()
191
- }
 
 
 
 
192
 
193
  async def process_question(self, question_data: str) -> str:
194
  try:
195
- logger.info(f"Processing question: {question_data[:50]}...")
196
  self.step_count += 1
197
 
198
- plan = await self.plan_execution(question_data)
199
- logger.info(f"Execution plan: {plan}")
200
-
201
- search_results = await self.execute_tool(
202
- "web_search",
203
- {"query": question_data}
204
- )
205
-
206
- calc_result = None
207
- if any(op in question_data for op in ['+', '-', '*', '/', '^']):
208
- numbers = re.findall(r'[-+]?\d*\.?\d+', question_data)
209
- operators = re.findall(r'[\+\-\*\/\^]', question_data)
210
- if numbers and operators:
211
- expression = ''.join([f"{n}{o}" for n, o in zip(numbers, operators + [''])])
212
- calc_result = await self.execute_tool(
213
- "calculator",
214
- {"expression": expression}
215
- )
216
- logger.info(f"Calculation result: {calc_result}")
217
-
218
- context = self._prepare_context(
219
- question=question_data,
220
- search_results=search_results,
221
- calc_result=calc_result
222
- )
223
-
224
- response = self.model([
225
- {"role": "system", "content": "You are a helpful AI assistant that provides accurate and concise answers based on the given context."},
226
- {"role": "user", "content": context}
227
- ])
228
 
229
- answer_text = response.content if hasattr(response, 'content') else str(response)
230
-
231
- logger.info(f"Generated answer for question")
232
- return answer_text.strip()
233
 
234
  except Exception as e:
235
- logger.error(f"Error processing question: {str(e)}", exc_info=True)
236
  return f"Error processing question: {str(e)}"
237
 
238
- async def plan_execution(self, question: str) -> str:
239
- prompt = f"""
240
- Create a plan to answer the following question: {question}
241
- Available tools:
242
- - web_search: Search the web for information
243
- - calculator: Perform mathematical calculations
244
- """
245
-
246
- response = self.model([
247
- {"role": "system", "content": "You are a planning assistant. Create a step-by-step plan to answer the question."},
248
- {"role": "user", "content": prompt}
249
- ])
250
-
251
- result = response.content if hasattr(response, 'content') else str(response)
252
- return result.strip()
253
-
254
- def _prepare_context(
255
- self,
256
- question: str,
257
- search_results: str = "",
258
- calc_result: Optional[Union[float, str]] = None
259
- ) -> str:
260
- context = f"Question: {question}\n\n"
261
-
262
- if search_results:
263
- context += f"Search Results:\n{search_results[:2000]}...\n\n"
264
-
265
- if calc_result is not None:
266
- context += f"Calculation Result: {calc_result}\n\n"
267
-
268
- if self.visual_memory:
269
- context += "\nVisual Information:\n"
270
- for step, memory in self.visual_memory.items():
271
- context += f"Step {step}: {memory['description']}\n"
272
-
273
- return context
274
 
275
  # Adapter to fit interface with original app.py
276
  class ChuckAgent:
@@ -283,152 +305,149 @@ class ChuckAgent:
283
 
284
  missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
285
  if missing_vars:
286
- raise EnvironmentError(f"Missing required environment variables: {', '.join(missing_vars)}")
 
 
 
287
 
288
- logger.info("Agent initialization started")
289
 
290
- self.model = OpenAIServerModel(
291
- model_id="gpt-4",
292
- api_key=os.environ.get('OPENAI_API_KEY')
293
- )
294
 
295
- self.agent = QuestionAnsweringAgent(model=self.model)
296
  self.loop = asyncio.new_event_loop()
297
  asyncio.set_event_loop(self.loop)
298
- logger.info("Agent fully initialized")
299
 
300
  def __call__(self, question: str) -> str:
301
- print(f"Agent received question (first 50 chars): {question[:50]}...")
302
  try:
303
  # Run the async process_question function in the event loop
304
  answer = self.loop.run_until_complete(self.agent.process_question(question))
305
- print(f"Agent returning answer (first 50 chars): {answer[:50]}...")
306
- return answer
307
  except Exception as e:
308
- error_msg = f"Error running agent: {str(e)}"
309
- print(error_msg)
310
- return error_msg
311
 
312
  def run_and_submit_all(profile: gr.OAuthProfile | None):
313
  """
314
  Fetches all questions, runs the ChuckAgent on them, submits all answers,
315
  and displays the results.
316
  """
317
- # --- Determine HF Space Runtime URL and Repo URL ---
318
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
319
 
320
  if profile:
321
- username= f"{profile.username}"
322
- print(f"User logged in: {username}")
323
  else:
324
- print("User not logged in.")
325
- return "Please Login to Hugging Face with the button.", None
326
 
327
  api_url = DEFAULT_API_URL
328
  questions_url = f"{api_url}/questions"
329
  submit_url = f"{api_url}/submit"
330
 
331
- # 1. Instantiate Agent (using our new ChuckAgent)
332
  try:
333
  agent = ChuckAgent()
 
 
 
334
  except Exception as e:
335
- print(f"Error instantiating agent: {e}")
336
- return f"Error initializing agent: {e}", None
337
 
338
- # In the case of an app running as a hugging Face space, this link points toward your codebase
339
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
340
- print(agent_code)
341
 
342
- # 2. Fetch Questions
343
- print(f"Fetching questions from: {questions_url}")
344
  try:
345
- response = requests.get(questions_url, timeout=15)
346
  response.raise_for_status()
347
  questions_data = response.json()
348
- if not questions_data:
349
- print("Fetched questions list is empty.")
350
- return "Fetched questions list is empty or invalid format.", None
351
- print(f"Fetched {len(questions_data)} questions.")
352
  except requests.exceptions.RequestException as e:
353
- print(f"Error fetching questions: {e}")
354
- return f"Error fetching questions: {e}", None
355
  except requests.exceptions.JSONDecodeError as e:
356
- print(f"Error decoding JSON response from questions endpoint: {e}")
357
- print(f"Response text: {response.text[:500]}")
358
- return f"Error decoding server response for questions: {e}", None
359
- except Exception as e:
360
- print(f"An unexpected error occurred fetching questions: {e}")
361
- return f"An unexpected error occurred fetching questions: {e}", None
362
 
363
- # 3. Run your Agent
364
  results_log = []
365
  answers_payload = []
366
- print(f"Running agent on {len(questions_data)} questions...")
367
- for item in questions_data:
368
  task_id = item.get("task_id")
369
  question_text = item.get("question")
370
  if not task_id or question_text is None:
371
- print(f"Skipping item with missing task_id or question: {item}")
372
  continue
 
 
373
  try:
374
  submitted_answer = agent(question_text)
375
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
376
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
377
  except Exception as e:
378
- print(f"Error running agent on task {task_id}: {e}")
379
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
380
 
381
  if not answers_payload:
382
- print("Agent did not produce any answers to submit.")
383
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
 
 
384
 
385
- # 4. Prepare Submission
386
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
387
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
388
- print(status_update)
389
 
390
- # 5. Submit
391
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
392
  try:
393
  response = requests.post(submit_url, json=submission_data, timeout=60)
394
  response.raise_for_status()
395
  result_data = response.json()
396
  final_status = (
397
  f"Submission Successful!\n"
398
- f"User: {result_data.get('username')}\n"
399
  f"Overall Score: {result_data.get('score', 'N/A')}% "
400
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
401
  f"Message: {result_data.get('message', 'No message received.')}"
402
  )
403
- print("Submission successful.")
404
- results_df = pd.DataFrame(results_log)
405
- return final_status, results_df
406
  except requests.exceptions.HTTPError as e:
407
  error_detail = f"Server responded with status {e.response.status_code}."
408
  try:
409
  error_json = e.response.json()
410
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
411
- except requests.exceptions.JSONDecodeError:
412
- error_detail += f" Response: {e.response.text[:500]}"
413
- status_message = f"Submission Failed: {error_detail}"
414
- print(status_message)
415
- results_df = pd.DataFrame(results_log)
416
- return status_message, results_df
417
  except requests.exceptions.Timeout:
418
- status_message = "Submission Failed: The request timed out."
419
- print(status_message)
420
- results_df = pd.DataFrame(results_log)
421
- return status_message, results_df
422
  except requests.exceptions.RequestException as e:
423
- status_message = f"Submission Failed: Network error - {e}"
424
- print(status_message)
425
- results_df = pd.DataFrame(results_log)
426
- return status_message, results_df
427
  except Exception as e:
428
- status_message = f"An unexpected error occurred during submission: {e}"
429
- print(status_message)
430
- results_df = pd.DataFrame(results_log)
431
- return status_message, results_df
 
432
 
433
 
434
  # --- Build Gradio Interface using Blocks ---
@@ -440,39 +459,44 @@ with gr.Blocks() as demo:
440
  1. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
441
  2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
442
  ---
443
- **Note:** The agent uses smolagents, OpenAI, and Serper API for searches. Make sure you have all required environment variables set:
444
- - OPENAI_API_KEY
445
- - SERPER_API_KEY
446
- - HF_USERNAME
447
- - AGENT_CODE
448
  """
449
  )
450
 
451
- gr.LoginButton()
 
 
452
 
453
  run_button = gr.Button("Run Evaluation & Submit All Answers")
454
 
455
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
456
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
457
 
 
458
  run_button.click(
459
  fn=run_and_submit_all,
 
460
  outputs=[status_output, results_table]
461
  )
462
 
463
  if __name__ == "__main__":
464
  print("\n" + "-"*30 + " App Starting " + "-"*30)
465
- # Check for SPACE_HOST and SPACE_ID at startup for information
466
  space_host_startup = os.getenv("SPACE_HOST")
467
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
468
 
469
  if space_host_startup:
470
  print(f"✅ SPACE_HOST found: {space_host_startup}")
471
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
 
 
 
472
  else:
473
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
474
 
475
- if space_id_startup: # Print repo URLs if SPACE_ID is found
476
  print(f"✅ SPACE_ID found: {space_id_startup}")
477
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
478
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
@@ -482,4 +506,4 @@ if __name__ == "__main__":
482
  print("-"*(60 + len(" App Starting ")) + "\n")
483
 
484
  print("Launching Gradio Interface for Chuck Agent Evaluation...")
485
- demo.launch(debug=True, share=False)
 
16
  try:
17
  from smolagents import CodeAgent, Tool, OpenAIServerModel
18
  except ImportError:
19
+ logging.error("Failed to import smolagents. Please ensure it is installed.")
20
+ # Handle if smolagents is not installed by providing dummy classes
21
+ # so the rest of the script can be parsed, though it won't function.
22
+ class CodeAgent: pass
23
+ class Tool: pass
24
+ class OpenAIServerModel: pass
25
 
26
  from datetime import datetime
27
 
 
33
  # Configure logging
34
  logging.basicConfig(
35
  level=logging.INFO,
36
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
 
37
  logger = logging.getLogger(__name__)
38
 
39
  # Ensure screenshots directory exists
 
42
  # --- Tool Definitions ---
43
  class ImageRetrievalTool(Tool):
44
  name = "image_retriever"
45
+ description = "Retrieves and processes images from web pages. Input is a URL to an image."
46
 
47
  inputs = {
48
  "url": {
 
50
  "description": "The URL of the image to retrieve"
51
  }
52
  }
53
+ output_type = "object" # Or string if you return a path or image_id
54
 
55
  def __init__(self):
56
  super().__init__()
57
+ self.image_memory = {} # Consider if this is used or if results should be directly returned
58
+ self.screenshot_count = 0 # Manages unique IDs for images
59
 
60
  async def forward(self, url: str) -> Dict[str, Any]:
61
+ logger.info(f"ImageRetrievalTool called with URL: {url}")
62
  try:
63
  async with aiohttp.ClientSession() as session:
64
  async with session.get(url) as response:
65
+ response.raise_for_status() # Raise an exception for bad status codes
66
+ image_data = await response.read()
67
+ image_id = f"image_{self.screenshot_count}"
68
+ # Storing in memory might be for context, but agent needs an observation
69
+ self.image_memory[image_id] = {
70
+ 'data': image_data, # Raw image data
71
+ 'url': url,
72
+ 'timestamp': datetime.now().isoformat()
73
+ }
74
+ self.screenshot_count += 1
75
+ # What the agent observes. Could be the image_id, a path if saved, or a summary.
76
+ return {"image_id": image_id, "status": "success", "message": f"Image from {url} retrieved."}
77
  except Exception as e:
78
+ logger.error(f"Error retrieving image {url}: {str(e)}")
79
  return {"error": f"Error retrieving image: {str(e)}"}
80
 
81
  class WebSearchTool(Tool):
82
  name = "web_search"
83
+ description = "Performs web searches using Serper API to find information. Input is a search query."
84
 
85
  inputs = {
86
  "query": {
 
88
  "description": "The search query to execute"
89
  }
90
  }
91
+ output_type = "string" # Output is a string summarizing search results
92
 
93
  async def forward(self, query: str) -> str:
94
+ logger.info(f"WebSearchTool called with query: {query}")
95
+ serper_api_key = os.environ.get('SERPER_API_KEY')
96
+ if not serper_api_key:
97
+ logger.error("SERPER_API_KEY not found.")
98
+ return "Error: Serper API key not found in environment."
99
 
100
  url = "https://google.serper.dev/search"
101
  headers = {
102
+ 'X-API-KEY': serper_api_key,
103
  'Content-Type': 'application/json'
104
  }
105
+ payload = json.dumps({ # Ensure payload is a JSON string for older aiohttp or some servers
106
  'q': query,
107
+ 'num': 5 # Number of results
108
+ })
109
 
110
  try:
111
  async with aiohttp.ClientSession() as session:
112
+ async with session.post(url, headers=headers, data=payload) as response: # data=payload if json.dumps used
113
+ response.raise_for_status() # Raise an exception for bad status codes
114
+ data = await response.json()
115
+ return self._format_results(data)
 
116
  except Exception as e:
117
+ logger.error(f"Error performing search for '{query}': {str(e)}")
118
  return f"Error performing search: {str(e)}"
119
 
120
  def _format_results(self, data: Dict) -> str:
121
  results = []
122
+ if 'organic' in data and data['organic']:
123
+ for result in data['organic'][:3]: # Limit to top 3 for brevity
124
+ title = result.get('title', 'No title')
125
+ snippet = result.get('snippet', 'No snippet')
126
+ link = result.get('link', '#')
127
+ results.append(f"Title: {title}\nSnippet: {snippet}\nLink: {link}\n---")
128
+ if not results and 'knowledgeGraph' in data: # Fallback or supplement with knowledge graph
129
  kg = data['knowledgeGraph']
130
+ title = kg.get('title', '')
131
+ description = kg.get('description', '')
132
+ if title or description:
133
+ results.append(f"Knowledge Graph: {title}\n{description}\n---")
134
+
135
+ return "\n".join(results) if results else "No search results found."
136
 
137
  class CalculatorTool(Tool):
138
  name = "calculator"
139
+ description = "Performs mathematical calculations. Input is a mathematical expression string."
140
 
141
  inputs = {
142
  "expression": {
143
  "type": "string",
144
+ "description": "The mathematical expression to evaluate (e.g., '2+2', '10*5/2')"
145
  }
146
  }
147
+ output_type = "string" # Return result as string to avoid type issues in agent observation
148
 
149
  def __init__(self):
150
  super().__init__()
151
+ # Limited safe operations
152
  self.operations = {
153
+ '+': operator.add, '-': operator.sub,
154
+ '*': operator.mul, '/': operator.truediv,
155
+ '^': operator.pow
 
 
 
 
156
  }
157
+ # For single argument functions like sqrt, abs, they need special handling if using eval
158
+ # A more robust calculator would parse expressions or use a safer math library
159
+ # For now, focusing on basic arithmetic.
160
 
161
+ async def forward(self, expression: str) -> str:
162
+ logger.info(f"CalculatorTool called with expression: {expression}")
163
  try:
164
+ # Basic sanitization and evaluation for simple expressions
165
+ # This is a simplified and somewhat risky eval. For production, use a proper math expression parser.
166
+ expression = "".join(c for c in expression if c in "0123456789+-*/^(). ")
167
+ if not expression:
168
+ return "Error: Empty or invalid expression for calculator."
169
+
170
+ # A slightly safer eval for basic arithmetic.
171
+ # It's still not perfectly safe. A dedicated math parsing library is better.
172
+ result = eval(expression, {"__builtins__": {}}, self.operations)
173
+ return f"Calculation result: {expression} = {float(result)}"
174
  except Exception as e:
175
+ logger.error(f"Error evaluating expression '{expression}': {str(e)}")
176
+ return f"Error: Could not evaluate expression '{expression}'. Invalid format or operation. Only basic arithmetic (+,-,*,/,^) is supported."
177
 
178
+ # Original _prepare_expression was okay, but eval safety is the bigger concern.
179
+ # The above forward method simplifies this.
 
180
 
181
  # --- Agent Definition ---
182
  class QuestionAnsweringAgent(CodeAgent):
 
184
  tools = [
185
  WebSearchTool(),
186
  CalculatorTool(),
187
+ ImageRetrievalTool() # Ensure this tool is useful or remove if not actively used by the agent's plan
188
  ]
189
 
190
  if model is None:
191
+ # Ensure OPENAI_API_KEY is available for this default model
192
+ if not os.environ.get('OPENAI_API_KEY'):
193
+ raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
194
+ model = OpenAIServerModel(
195
+ model_id="gpt-4", # or a cheaper/faster model for testing like "gpt-3.5-turbo"
196
+ api_key=os.environ.get('OPENAI_API_KEY') # Pass the key here
197
+ )
198
+
199
+ # Define a system prompt that guides the CodeAgent
200
+ # This prompt tells the agent its role, how to behave, and how to use tools.
201
+ system_prompt = """You are Chuck, a helpful AI assistant. Your goal is to answer questions accurately and concisely.
202
+ You have access to the following tools:
203
+ - web_search: Use this to search the internet for information when the answer is not common knowledge or requires up-to-date details.
204
+ - calculator: Use this for mathematical calculations. Input should be a simple expression string like "10+5*2".
205
+ - image_retriever: Use this to fetch an image if a URL is provided and image content is needed.
206
+
207
+ When you receive a question:
208
+ 1. Think step-by-step to create a plan to answer the question.
209
+ 2. Decide if any tools are needed. If so, specify the tool and the exact input for it.
210
+ 3. Execute the tools if necessary and observe the results.
211
+ 4. If multiple steps or tools are needed, repeat step 2 and 3.
212
+ 5. Based on the information gathered (or if no tools were needed), formulate a final answer to the original question.
213
+ 6. Respond with only the final answer. Do not explain your plan or tool usage in the final answer unless explicitly asked.
214
+ """
215
 
216
  super().__init__(
217
  tools=tools,
218
  model=model,
219
+ system_prompt=system_prompt, # Provide the system prompt
220
+ additional_authorized_imports=["PIL"], # If PIL is used by tools or agent code
221
+ # step_callbacks=[self._process_visual_memory], # Keep if visual memory is used
222
+ max_steps=10, # Max iterations of thought-action-observation loop
223
+ verbosity_level=2 # 0 (silent), 1 (info), 2 (debug)
224
  )
225
 
226
+ # self.visual_memory = {} # If you have custom visual memory processing
227
+ self.step_count = 0 # For your custom tracking if needed
228
+ logger.info("QuestionAnsweringAgent initialized with all tools and system prompt.")
229
 
230
+ # If _process_visual_memory is a callback for CodeAgent steps, it should be compatible.
231
+ # However, its utility depends on how CodeAgent exposes observations from ImageRetrievalTool.
232
  async def _process_visual_memory(self, step_num: int, description: str):
233
+ # This callback might need adjustment based on how `smolagents.CodeAgent`
234
+ # provides image observations or if `ImageRetrievalTool` directly gives usable output.
235
+ # For now, assume `description` might contain info about image retrieval.
236
+ logger.debug(f"Step {step_num} visual memory callback: {description}")
237
+ # if hasattr(self, 'current_observation_images'): # This attribute would be set by CodeAgent
238
+ # self.visual_memory[step_num] = {
239
+ # 'images': self.current_observation_images,
240
+ # 'description': description,
241
+ # 'timestamp': datetime.now().isoformat()
242
+ # }
243
 
244
  async def process_question(self, question_data: str) -> str:
245
  try:
246
+ logger.info(f"Processing question with CodeAgent: {question_data[:100]}...")
247
  self.step_count += 1
248
 
249
+ # Let the CodeAgent's `run` method handle the entire process
250
+ # It will use its LLM, the system_prompt, and tool descriptions
251
+ # to decide how to answer the question_data.
252
+ # The `question_data` itself is the user's task/query.
253
+ answer_text = await self.run(question_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
 
255
+ logger.info(f"CodeAgent returned answer: {str(answer_text)[:100]}...")
256
+ return str(answer_text).strip() # Ensure the output is a string
 
 
257
 
258
  except Exception as e:
259
+ logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}", exc_info=True)
260
  return f"Error processing question: {str(e)}"
261
 
262
+ # The plan_execution and _prepare_context methods are likely not needed
263
+ # if self.run() handles the full agentic loop.
264
+ # They are commented out for now.
265
+ #
266
+ # async def plan_execution(self, question: str) -> str:
267
+ # prompt = f"""
268
+ # Create a plan to answer the following question: {question}
269
+ # Available tools:
270
+ # - web_search: Search the web for information
271
+ # - calculator: Perform mathematical calculations
272
+ # """
273
+ # response = self.model([ # This is a direct model call, not agent planning
274
+ # {"role": "system", "content": "You are a planning assistant. Create a step-by-step plan to answer the question."},
275
+ # {"role": "user", "content": prompt}
276
+ # ])
277
+ # result = response.content if hasattr(response, 'content') else str(response)
278
+ # return result.strip()
279
+
280
+ # def _prepare_context(
281
+ # self,
282
+ # question: str,
283
+ # search_results: str = "",
284
+ # calc_result: Optional[Union[float, str]] = None
285
+ # ) -> str:
286
+ # context = f"Question: {question}\n\n"
287
+ # if search_results:
288
+ # context += f"Search Results:\n{search_results[:2000]}...\n\n"
289
+ # if calc_result is not None:
290
+ # context += f"Calculation Result: {calc_result}\n\n"
291
+ # # if self.visual_memory: # If using custom visual_memory
292
+ # # context += "\nVisual Information:\n"
293
+ # # for step, memory in self.visual_memory.items():
294
+ # # context += f"Step {step}: {memory['description']}\n"
295
+ # return context
 
 
296
 
297
  # Adapter to fit interface with original app.py
298
  class ChuckAgent:
 
305
 
306
  missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
307
  if missing_vars:
308
+ # Log and raise error if critical API keys are missing
309
+ error_msg = f"Missing required environment variables: {', '.join(missing_vars)}"
310
+ logger.critical(error_msg) # Use critical for startup failures
311
+ raise EnvironmentError(error_msg)
312
 
313
+ logger.info("ChuckAgent initialization started")
314
 
315
+ # Model is now initialized within QuestionAnsweringAgent if not provided
316
+ # This means QuestionAnsweringAgent is self-contained regarding model creation
317
+ self.agent = QuestionAnsweringAgent() # Let it use its default model
 
318
 
 
319
  self.loop = asyncio.new_event_loop()
320
  asyncio.set_event_loop(self.loop)
321
+ logger.info("ChuckAgent fully initialized")
322
 
323
  def __call__(self, question: str) -> str:
324
+ logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
325
  try:
326
  # Run the async process_question function in the event loop
327
  answer = self.loop.run_until_complete(self.agent.process_question(question))
328
+ logger.info(f"ChuckAgent returning answer (first 50 chars): {str(answer)[:50]}...")
329
+ return str(answer) # Ensure it's a string
330
  except Exception as e:
331
+ error_msg = f"Error running ChuckAgent: {str(e)}"
332
+ logger.error(error_msg, exc_info=True)
333
+ return error_msg # Return the error message to be displayed
334
 
335
  def run_and_submit_all(profile: gr.OAuthProfile | None):
336
  """
337
  Fetches all questions, runs the ChuckAgent on them, submits all answers,
338
  and displays the results.
339
  """
340
+ space_id = os.getenv("SPACE_ID")
 
341
 
342
  if profile:
343
+ username = f"{profile.username}"
344
+ logger.info(f"User logged in: {username}")
345
  else:
346
+ logger.warning("User not logged in for run_and_submit_all.")
347
+ return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
348
 
349
  api_url = DEFAULT_API_URL
350
  questions_url = f"{api_url}/questions"
351
  submit_url = f"{api_url}/submit"
352
 
 
353
  try:
354
  agent = ChuckAgent()
355
+ except EnvironmentError as e: # Catch specific error for missing keys
356
+ logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
357
+ return f"Agent Initialization Error: {e}. Please ensure API keys are set in Space Secrets.", pd.DataFrame()
358
  except Exception as e:
359
+ logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
360
+ return f"Error initializing agent: {e}", pd.DataFrame() # Use pd.DataFrame() for empty table
361
 
362
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Agent code URL not determinable (SPACE_ID not set)"
363
+ logger.info(f"Agent code URL: {agent_code}")
 
364
 
365
+ logger.info(f"Fetching questions from: {questions_url}")
 
366
  try:
367
+ response = requests.get(questions_url, timeout=30) # Increased timeout
368
  response.raise_for_status()
369
  questions_data = response.json()
370
+ if not questions_data or not isinstance(questions_data, list): # Basic validation
371
+ logger.warning(f"Fetched questions list is empty or invalid format: {questions_data}")
372
+ return "Fetched questions list is empty or not a list.", pd.DataFrame()
373
+ logger.info(f"Fetched {len(questions_data)} questions.")
374
  except requests.exceptions.RequestException as e:
375
+ logger.error(f"Error fetching questions: {e}", exc_info=True)
376
+ return f"Error fetching questions: {e}", pd.DataFrame()
377
  except requests.exceptions.JSONDecodeError as e:
378
+ logger.error(f"Error decoding JSON response from questions endpoint: {e}. Response text: {response.text[:500]}", exc_info=True)
379
+ return f"Error decoding server response for questions: {e}", pd.DataFrame()
380
+ except Exception as e: # Catch any other unexpected error
381
+ logger.error(f"An unexpected error occurred fetching questions: {e}", exc_info=True)
382
+ return f"An unexpected error occurred fetching questions: {e}", pd.DataFrame()
 
383
 
 
384
  results_log = []
385
  answers_payload = []
386
+ logger.info(f"Running agent on {len(questions_data)} questions...")
387
+ for i, item in enumerate(questions_data):
388
  task_id = item.get("task_id")
389
  question_text = item.get("question")
390
  if not task_id or question_text is None:
391
+ logger.warning(f"Skipping item with missing task_id or question: {item}")
392
  continue
393
+
394
+ logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
395
  try:
396
  submitted_answer = agent(question_text)
397
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
398
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
399
  except Exception as e:
400
+ logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
401
+ # Still add to results log to show an attempt was made
402
+ submitted_answer_error = f"AGENT EXECUTION ERROR: {e}"
403
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer_error})
404
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer_error})
405
+
406
 
407
  if not answers_payload:
408
+ logger.warning("Agent did not produce any answers to submit.")
409
+ # Return empty DataFrame if results_log is also empty or structure as needed
410
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log if results_log else [])
411
+
412
 
 
413
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
414
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
415
+ logger.info(status_update)
416
 
417
+ logger.info(f"Submitting {len(answers_payload)} answers to: {submit_url}")
 
418
  try:
419
  response = requests.post(submit_url, json=submission_data, timeout=60)
420
  response.raise_for_status()
421
  result_data = response.json()
422
  final_status = (
423
  f"Submission Successful!\n"
424
+ f"User: {result_data.get('username', 'N/A')}\n"
425
  f"Overall Score: {result_data.get('score', 'N/A')}% "
426
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
427
  f"Message: {result_data.get('message', 'No message received.')}"
428
  )
429
+ logger.info("Submission successful.")
 
 
430
  except requests.exceptions.HTTPError as e:
431
  error_detail = f"Server responded with status {e.response.status_code}."
432
  try:
433
  error_json = e.response.json()
434
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
435
+ except requests.exceptions.JSONDecodeError: # Renamed for clarity
436
+ error_detail += f" Raw Response: {e.response.text[:500]}" # Show raw response if not JSON
437
+ final_status = f"Submission Failed: {error_detail}"
438
+ logger.error(final_status)
 
 
439
  except requests.exceptions.Timeout:
440
+ final_status = "Submission Failed: The request timed out."
441
+ logger.error(final_status)
 
 
442
  except requests.exceptions.RequestException as e:
443
+ final_status = f"Submission Failed: Network error - {e}"
444
+ logger.error(final_status, exc_info=True)
 
 
445
  except Exception as e:
446
+ final_status = f"An unexpected error occurred during submission: {e}"
447
+ logger.error(final_status, exc_info=True)
448
+
449
+ results_df = pd.DataFrame(results_log if results_log else []) # Ensure DataFrame is always created
450
+ return final_status, results_df
451
 
452
 
453
  # --- Build Gradio Interface using Blocks ---
 
459
  1. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
460
  2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
461
  ---
462
+ **Note:** The agent uses `smolagents`, OpenAI, and Serper API for searches.
463
+ Make sure you have the following **Secrets** correctly set in your Hugging Face Space settings:
464
+ - `OPENAI_API_KEY` (Your OpenAI API key)
465
+ - `SERPER_API_KEY` (Your Serper API key)
 
466
  """
467
  )
468
 
469
+ # The Gradio LoginButton will use OAuth details if `hf_oauth: true` is in README.md
470
+ # It provides the `profile` object to the click function.
471
+ login_button = gr.LoginButton()
472
 
473
  run_button = gr.Button("Run Evaluation & Submit All Answers")
474
 
475
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
476
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
477
 
478
+ # Pass login_button (which resolves to the profile) as an input to run_and_submit_all
479
  run_button.click(
480
  fn=run_and_submit_all,
481
+ inputs=[login_button], # Pass the profile from the login button
482
  outputs=[status_output, results_table]
483
  )
484
 
485
  if __name__ == "__main__":
486
  print("\n" + "-"*30 + " App Starting " + "-"*30)
 
487
  space_host_startup = os.getenv("SPACE_HOST")
488
+ space_id_startup = os.getenv("SPACE_ID")
489
 
490
  if space_host_startup:
491
  print(f"✅ SPACE_HOST found: {space_host_startup}")
492
+ # Corrected the runtime URL construction slightly.
493
+ # Typically, it's just https://{SPACE_ID_WITH_DASHES}.hf.space or similar.
494
+ # The SPACE_HOST itself is often the full hostname.
495
+ print(f" Runtime URL might be: https://{space_host_startup}")
496
  else:
497
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
498
 
499
+ if space_id_startup:
500
  print(f"✅ SPACE_ID found: {space_id_startup}")
501
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
502
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
 
506
  print("-"*(60 + len(" App Starting ")) + "\n")
507
 
508
  print("Launching Gradio Interface for Chuck Agent Evaluation...")
509
+ demo.launch(debug=True, share=False) # share=False is safer for spaces unless public link needed