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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -86
app.py CHANGED
@@ -8,16 +8,13 @@ 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:
15
  from smolagents import CodeAgent, Tool, OpenAIServerModel
16
- # If CodeAgent has a specific return type for run that includes reasoning
17
- # from smolagents.types import AgentOutput # Or similar, check smolagents docs
18
  except ImportError:
19
  logging.error("Failed to import smolagents. Please ensure it is installed.")
20
- # Dummy classes for script parsing if smolagents is not installed
21
  class CodeAgent: pass
22
  class Tool: pass
23
  class OpenAIServerModel: pass
@@ -30,12 +27,13 @@ class AppConfig:
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()
@@ -48,40 +46,73 @@ 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)}"
86
 
87
  class WebSearchTool(Tool):
@@ -90,6 +121,10 @@ class WebSearchTool(Tool):
90
  inputs = {"query": {"type": "string", "description": "The search query to execute"}}
91
  output_type = "string"
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')
@@ -102,13 +137,19 @@ class WebSearchTool(Tool):
102
  payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
103
 
104
  try:
105
- async with aiohttp.ClientSession() as session:
106
- async with session.post(url, headers=headers, data=payload) as response:
107
- response.raise_for_status()
108
- data = await response.json()
109
- return self._format_results(data)
 
 
 
 
 
 
110
  except Exception as e:
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:
@@ -124,7 +165,6 @@ class WebSearchTool(Tool):
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
 
@@ -134,7 +174,7 @@ class CalculatorTool(Tool):
134
  inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate"}}
135
  output_type = "string"
136
 
137
- def __init__(self):
138
  super().__init__()
139
  self.operations = {
140
  '+': operator.add, '-': operator.sub,
@@ -149,8 +189,6 @@ class CalculatorTool(Tool):
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)}"
156
  except Exception as e:
@@ -159,8 +197,14 @@ class CalculatorTool(Tool):
159
 
160
  # --- Agent Definition ---
161
  class QuestionAnsweringAgent(CodeAgent):
162
- def __init__(self, model: Optional[OpenAIServerModel] = None):
163
- tools = [WebSearchTool(), CalculatorTool(), ImageRetrievalTool()]
 
 
 
 
 
 
164
 
165
  effective_model = model
166
  if effective_model is None:
@@ -170,28 +214,27 @@ class QuestionAnsweringAgent(CodeAgent):
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)
@@ -199,18 +242,16 @@ class QuestionAnsweringAgent(CodeAgent):
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)}"
212
  reasoning_trace += f"\nError encountered: {str(e)}"
213
-
214
  return final_answer_for_submission, reasoning_trace
215
 
216
  # --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
@@ -224,18 +265,24 @@ class ChuckAgent:
224
  raise EnvironmentError(error_msg)
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
  )
@@ -246,18 +293,28 @@ class ChuckAgent:
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()
@@ -269,24 +326,20 @@ def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
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:
@@ -297,48 +350,38 @@ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]
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:
338
- error_json = e.response.json()
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:
@@ -347,12 +390,16 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answer
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:
@@ -364,15 +411,17 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile]) -> Tuple[s
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
 
@@ -380,10 +429,9 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile]) -> Tuple[s
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
 
@@ -404,6 +452,7 @@ with gr.Blocks() as demo:
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
 
@@ -412,17 +461,16 @@ with gr.Blocks() as demo:
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
 
@@ -440,7 +488,27 @@ if __name__ == "__main__":
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...")
446
- demo.launch(debug=True, share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
 
27
  QUESTIONS_URL_PATH = "/questions"
28
  SUBMIT_URL_PATH = "/submit"
29
  SCREENSHOTS_DIR = "screenshots"
30
+ # RECOMMENDATION: Changed to gpt-3.5-turbo for potentially faster and cheaper responses.
31
+ # Switch back to "gpt-4" if higher reasoning capabilities are strictly necessary.
32
+ OPENAI_MODEL_ID = "gpt-3.5-turbo"
33
+ SERPER_API_NUM_RESULTS = 3
34
+ WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
35
  AGENT_MAX_STEPS = 10
36
  AGENT_VERBOSITY_LEVEL = 2
 
37
  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."""
38
 
39
  CONFIG = AppConfig()
 
46
 
47
  # --- Utility Functions ---
48
  def ensure_dir_exists(directory_path: str):
 
49
  os.makedirs(directory_path, exist_ok=True)
50
 
51
  ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)
52
 
53
+ # --- HTTP Client Session Management ---
54
+ # Global session for ChuckAgent to reuse for all its tools
55
+ # This will be initialized in ChuckAgent and passed down.
56
+ # This avoids creating a new session for every single HTTP request made by tools.
57
+ SHARED_HTTP_SESSION: Optional[aiohttp.ClientSession] = None
58
+
59
+ async def get_shared_http_session() -> aiohttp.ClientSession:
60
+ """Gets or creates the shared aiohttp ClientSession."""
61
+ global SHARED_HTTP_SESSION
62
+ if SHARED_HTTP_SESSION is None or SHARED_HTTP_SESSION.closed:
63
+ # You might want to configure connector limits here if making many concurrent requests
64
+ # connector = aiohttp.TCPConnector(limit_per_host=10)
65
+ # SHARED_HTTP_SESSION = aiohttp.ClientSession(connector=connector)
66
+ SHARED_HTTP_SESSION = aiohttp.ClientSession()
67
+ logger.info("Created shared aiohttp.ClientSession.")
68
+ return SHARED_HTTP_SESSION
69
+
70
+ async def close_shared_http_session():
71
+ """Closes the shared aiohttp ClientSession if it exists and is open."""
72
+ global SHARED_HTTP_SESSION
73
+ if SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed:
74
+ await SHARED_HTTP_SESSION.close()
75
+ SHARED_HTTP_SESSION = None
76
+ logger.info("Closed shared aiohttp.ClientSession.")
77
+
78
  # --- Tool Definitions ---
79
  class ImageRetrievalTool(Tool):
80
  name = "image_retriever"
81
+ description = "Retrieves images from web pages. Input is a URL to an image. Returns a success/error message."
82
  inputs = {"url": {"type": "string", "description": "The URL of the image to retrieve"}}
83
  output_type = "string"
84
 
85
+ def __init__(self, session: aiohttp.ClientSession): # MODIFIED: Accept session
86
  super().__init__()
87
  self.image_memory: Dict[str, Dict[str, Any]] = {}
88
  self.screenshot_count = 0
89
+ self._session = session # MODIFIED: Store session
90
 
91
  async def forward(self, url: str) -> str:
92
  logger.info(f"ImageRetrievalTool called with URL: {url}")
93
  try:
94
+ # MODIFIED: Use the passed-in session
95
+ async with self._session.get(url, timeout=aiohttp.ClientTimeout(total=20)) as response:
96
+ response.raise_for_status()
97
+ image_data = await response.read()
98
+ image_id = f"image_{self.screenshot_count}"
99
+ # Consider saving to disk if memory becomes an issue (e.g., in CONFIG.SCREENSHOTS_DIR)
100
+ # For now, keeping in memory for simplicity as per original script.
101
+ self.image_memory[image_id] = {
102
+ 'data': image_data,
103
+ 'url': url,
104
+ 'timestamp': datetime.now().isoformat()
105
+ }
106
+ self.screenshot_count += 1
107
+ return f"Image retrieved successfully from {url}. Stored in memory as {image_id}."
108
+ except asyncio.TimeoutError:
109
+ logger.error(f"Timeout retrieving image {url}")
110
+ return f"Error: Timeout retrieving image {url}."
111
+ except aiohttp.ClientError as e:
112
+ logger.error(f"ClientError retrieving image {url}: {type(e).__name__} - {str(e)}")
113
+ return f"Error retrieving image (client error): {str(e)}"
114
  except Exception as e:
115
+ logger.error(f"Unexpected error retrieving image {url}: {type(e).__name__} - {str(e)}")
116
  return f"Error retrieving image: {str(e)}"
117
 
118
  class WebSearchTool(Tool):
 
121
  inputs = {"query": {"type": "string", "description": "The search query to execute"}}
122
  output_type = "string"
123
 
124
+ def __init__(self, session: aiohttp.ClientSession): # MODIFIED: Accept session
125
+ super().__init__()
126
+ self._session = session # MODIFIED: Store session
127
+
128
  async def forward(self, query: str) -> str:
129
  logger.info(f"WebSearchTool called with query: {query}")
130
  serper_api_key = os.environ.get('SERPER_API_KEY')
 
137
  payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
138
 
139
  try:
140
+ # MODIFIED: Use the passed-in session
141
+ async with self._session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
142
+ response.raise_for_status()
143
+ data = await response.json()
144
+ return self._format_results(data)
145
+ except asyncio.TimeoutError:
146
+ logger.error(f"Timeout performing search for '{query}'")
147
+ return f"Error: Timeout during web search for '{query}'."
148
+ except aiohttp.ClientError as e:
149
+ logger.error(f"ClientError performing search for '{query}': {type(e).__name__} - {str(e)}")
150
+ return f"Error performing search (client error): {str(e)}"
151
  except Exception as e:
152
+ logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}")
153
  return f"Error performing search: {str(e)}"
154
 
155
  def _format_results(self, data: Dict[str, Any]) -> str:
 
165
  description = kg.get('description', '')
166
  if title or description:
167
  results.append(f"Knowledge Graph: {title}\n{description}\n---")
 
168
  formatted_output = "\n".join(results) if results else "No relevant search results found."
169
  return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
170
 
 
174
  inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate"}}
175
  output_type = "string"
176
 
177
+ def __init__(self): # Does not use aiohttp, so no session needed
178
  super().__init__()
179
  self.operations = {
180
  '+': operator.add, '-': operator.sub,
 
189
  safe_expr = "".join(c for c in expression if c in self.allowed_chars)
190
  if not safe_expr:
191
  return "Error: Empty or invalid expression for calculator."
 
 
192
  result = eval(safe_expr, {"__builtins__": {}}, self.operations) # type: ignore
193
  return f"Calculation result: {safe_expr} = {float(result)}"
194
  except Exception as e:
 
197
 
198
  # --- Agent Definition ---
199
  class QuestionAnsweringAgent(CodeAgent):
200
+ # MODIFIED: Accept http_session to pass to tools
201
+ def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
202
+ # MODIFIED: Instantiate tools with the shared session
203
+ tools = [
204
+ WebSearchTool(session=http_session),
205
+ CalculatorTool(), # No session needed for CalculatorTool
206
+ ImageRetrievalTool(session=http_session)
207
+ ]
208
 
209
  effective_model = model
210
  if effective_model is None:
 
214
  effective_model = OpenAIServerModel(
215
  model_id=CONFIG.OPENAI_MODEL_ID,
216
  api_key=openai_api_key
217
+ # Consider adding timeout configurations for OpenAIServerModel if available
218
  )
219
 
220
  super().__init__(
221
  tools=tools,
222
  model=effective_model,
223
  system_prompt=CONFIG.AGENT_SYSTEM_PROMPT,
224
+ additional_authorized_imports=["PIL"],
225
  max_steps=CONFIG.AGENT_MAX_STEPS,
226
  verbosity_level=CONFIG.AGENT_VERBOSITY_LEVEL
227
  )
228
+ logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID}.")
229
 
230
  async def process_question(self, question_text: str) -> Tuple[str, str]:
 
231
  reasoning_trace = "Agent execution started."
232
  final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
233
  try:
234
  logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
235
+ raw_output = await self.run(question_text)
236
  full_agent_response = str(raw_output)
237
+ reasoning_trace = full_agent_response
 
238
  logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
239
 
240
  match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
 
242
  final_answer_for_submission = match.group(1).strip()
243
  logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
244
  else:
245
+ logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
246
  final_answer_for_submission = full_agent_response.strip()
247
 
248
  if not final_answer_for_submission:
249
  logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
250
  final_answer_for_submission = "Could not determine answer."
 
251
  except Exception as e:
252
  logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}", exc_info=True)
253
  final_answer_for_submission = f"Error in agent processing: {str(e)}"
254
  reasoning_trace += f"\nError encountered: {str(e)}"
 
255
  return final_answer_for_submission, reasoning_trace
256
 
257
  # --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
 
265
  raise EnvironmentError(error_msg)
266
 
267
  logger.info("ChuckAgent initialization started")
 
 
268
  try:
269
  self.loop = asyncio.get_running_loop()
270
+ except RuntimeError:
271
  self.loop = asyncio.new_event_loop()
272
  asyncio.set_event_loop(self.loop)
273
+
274
+ # MODIFIED: Create shared HTTP session managed by ChuckAgent's loop
275
+ self.http_session = self.loop.run_until_complete(get_shared_http_session())
276
+ self.agent = QuestionAnsweringAgent(http_session=self.http_session)
277
  logger.info("ChuckAgent fully initialized")
278
 
279
  def __call__(self, question: str) -> Tuple[str, str]:
280
  logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
281
  try:
282
+ # Ensure the loop associated with http_session is used for agent processing
283
+ if asyncio.get_event_loop() is not self.loop:
284
+ asyncio.set_event_loop(self.loop)
285
+
286
  final_answer, reasoning_trace = self.loop.run_until_complete(
287
  self.agent.process_question(question)
288
  )
 
293
  logger.error(error_msg, exc_info=True)
294
  return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
295
 
296
+ async def shutdown(self):
297
+ """Gracefully shutdowns the agent, closing the shared HTTP session."""
298
+ logger.info("ChuckAgent shutting down...")
299
+ await close_shared_http_session()
300
+ logger.info("ChuckAgent shutdown complete.")
301
+
302
+
303
  # --- Core Evaluation Logic ---
304
+ # These functions (fetch_questions, etc.) remain largely synchronous as they were.
305
+ # If we wanted to make the entire pipeline async, these would need to use self.http_session too.
306
+ # For now, `requests` (sync) is used for evaluation server communication.
307
+
308
  def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
 
309
  space_id = os.getenv("SPACE_ID")
310
  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)"
311
  return space_id, agent_code_url
312
 
313
  def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
 
314
  questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
315
  logger.info(f"Fetching questions from: {questions_url}")
316
  try:
317
+ # Using synchronous requests for this part, as it's outside the async agent tools
318
  response = requests.get(questions_url, timeout=30)
319
  response.raise_for_status()
320
  questions_data = response.json()
 
326
  except requests.exceptions.RequestException as e:
327
  logger.error(f"Error fetching questions: {e}", exc_info=True)
328
  raise ConnectionError(f"Error fetching questions: {e}") from e
329
+ except (requests.exceptions.JSONDecodeError, ValueError) as e:
330
+ logger.error(f"Error decoding questions JSON or invalid data: {e}. Response text: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
331
  raise ValueError(f"Error decoding server response for questions: {e}") from e
332
 
333
  def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
 
334
  answers_payload = []
335
  results_log = []
336
  logger.info(f"Running agent on {len(questions_data)} questions...")
 
337
  for i, item in enumerate(questions_data):
338
  task_id = item.get("task_id")
339
  question_text = item.get("question")
 
340
  if not task_id or question_text is None:
341
  logger.warning(f"Skipping item {i+1} with missing data: {item}")
342
  continue
 
343
  logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
344
  model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
345
  try:
 
350
  reasoning = str(e)
351
 
352
  payload_item = {"task_id": task_id, "model_answer": model_ans}
353
+ if reasoning:
354
  payload_item["reasoning_trace"] = reasoning
355
  answers_payload.append(payload_item)
356
 
357
  results_log.append({
358
+ "Task ID": task_id, "Question": question_text,
359
+ "Submitted Answer": model_ans, "Reasoning Trace": reasoning
 
 
360
  })
361
  return answers_payload, results_log
362
 
363
  def submit_answers(base_api_url: str, username: str, agent_code_url: str, answers_payload: List[Dict[str, Any]]) -> str:
 
364
  if not answers_payload:
365
  logger.warning("Agent did not produce any answers to submit.")
366
  return "Agent did not produce any answers to submit."
367
 
368
  submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
369
  submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
 
370
  logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...")
 
 
371
  try:
372
  response = requests.post(submit_url, json=submission_data, timeout=60)
373
  response.raise_for_status()
374
  result_data = response.json()
375
  return (
376
+ f"Submission Successful!\nUser: {result_data.get('username', 'N/A')}\n"
 
377
  f"Overall Score: {result_data.get('score', 'N/A')}% "
378
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
379
  f"Message: {result_data.get('message', 'No message received.')}"
380
  )
381
  except requests.exceptions.HTTPError as e:
382
  error_detail = f"Server responded with {e.response.status_code}."
383
+ try: error_json = e.response.json(); error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
384
+ except requests.exceptions.JSONDecodeError: error_detail += f" Raw Response: {e.response.text[:500]}"
 
 
 
385
  logger.error(f"Submission Failed: {error_detail}")
386
  return f"Submission Failed: {error_detail}"
387
  except requests.exceptions.Timeout:
 
390
  except requests.exceptions.RequestException as e:
391
  logger.error(f"Submission Failed: Network error - {e}", exc_info=True)
392
  return f"Submission Failed: Network error - {e}"
393
+ except Exception as e:
394
  logger.error(f"An unexpected error occurred during submission: {e}", exc_info=True)
395
  return f"An unexpected error occurred during submission: {e}"
396
 
397
  # --- Gradio Interface Main Function ---
398
+ # Global agent instance to manage its lifecycle (e.g. for session closing)
399
+ GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
400
+
401
  def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile]) -> Tuple[str, pd.DataFrame]:
402
+ global GLOBAL_CHUCK_AGENT
403
  logger.info(f"run_and_submit_all_evaluation called. Profile: {profile.username if profile else 'None'}")
404
 
405
  if not profile:
 
411
 
412
  _, agent_code_url = get_space_id_agent_code_url()
413
  logger.info(f"Agent code URL: {agent_code_url}")
414
+ results_log_data: List[Dict[str, Any]] = []
 
415
 
416
  try:
417
+ # Use or create the global agent instance
418
+ if GLOBAL_CHUCK_AGENT is None:
419
+ GLOBAL_CHUCK_AGENT = ChuckAgent()
420
+ agent = GLOBAL_CHUCK_AGENT
421
  except EnvironmentError as e:
422
  logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
423
  return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
424
+ except Exception as e:
425
  logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
426
  return f"Error initializing agent: {e}", pd.DataFrame()
427
 
 
429
  questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
430
  answers_payload, results_log_data = process_all_questions(agent, questions_data)
431
  submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
432
+ except (ConnectionError, ValueError) as e:
433
+ submission_status = str(e)
434
+ except Exception as e:
 
435
  logger.error(f"An unexpected error occurred during evaluation pipeline: {e}", exc_info=True)
436
  submission_status = f"An unexpected error occurred: {e}"
437
 
 
452
  - `OPENAI_API_KEY` (Your OpenAI API key)
453
  - `SERPER_API_KEY` (Your Serper API key)
454
  Ensure your `requirements.txt` specifies `gradio>=4.19.2` or newer for `gr.LoginButton()`.
455
+ Consider trying `OPENAI_MODEL_ID = "gpt-3.5-turbo"` in the script for faster evaluation.
456
  """
457
  )
458
 
 
461
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
462
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True, max_rows=20)
463
 
 
 
464
  run_button.click(
465
  fn=run_and_submit_all_evaluation,
466
  inputs=[login_button],
467
  outputs=[status_output, results_table]
468
  )
469
 
470
+ # --- Application Startup & Shutdown Handling ---
471
  if __name__ == "__main__":
472
  print("\n" + "-"*30 + " App Starting " + "-"*30)
473
+ # ... (startup print messages remain the same)
474
  space_host_startup = os.getenv("SPACE_HOST")
475
  space_id_startup, agent_url_startup = get_space_id_agent_code_url()
476
 
 
488
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
489
 
490
  print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
491
+ print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}")
492
  print("-"*(60 + len(" App Starting ")) + "\n")
 
493
  print("Launching Gradio Interface for Chuck Agent Evaluation...")
494
+
495
+ # For proper shutdown of shared resources like aiohttp session
496
+ # Gradio's .launch() is blocking. A more complex setup might be needed for perfect
497
+ # lifecycle management in a continuously running server environment.
498
+ # For this script, we'll rely on Python's exit handlers or manual interruption
499
+ # to eventually clean up if not explicitly closed.
500
+ try:
501
+ demo.launch(debug=True, share=False)
502
+ finally:
503
+ if GLOBAL_CHUCK_AGENT and GLOBAL_CHUCK_AGENT.http_session.loop.is_running():
504
+ logger.info("Attempting to shutdown ChuckAgent and close HTTP session...")
505
+ # Ensure we run the async shutdown in the correct loop
506
+ if asyncio.get_event_loop() is not GLOBAL_CHUCK_AGENT.http_session.loop:
507
+ asyncio.set_event_loop(GLOBAL_CHUCK_AGENT.http_session.loop)
508
+ GLOBAL_CHUCK_AGENT.http_session.loop.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
509
+ elif SHARED_HTTP_SESSION and SHARED_HTTP_SESSION.loop.is_running() and not SHARED_HTTP_SESSION.closed:
510
+ # Fallback if agent wasn't fully init but session was made
511
+ logger.info("Attempting to close shared HTTP session directly...")
512
+ if asyncio.get_event_loop() is not SHARED_HTTP_SESSION.loop:
513
+ asyncio.set_event_loop(SHARED_HTTP_SESSION.loop)
514
+ SHARED_HTTP_SESSION.loop.run_until_complete(close_shared_http_session())