GoodLuckChuck commited on
Commit
9cf4e3c
·
verified ·
1 Parent(s): 82a4281

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -68
app.py CHANGED
@@ -27,9 +27,7 @@ class AppConfig:
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
@@ -51,24 +49,16 @@ def ensure_dir_exists(directory_path: str):
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()
@@ -82,22 +72,19 @@ class ImageRetrievalTool(Tool):
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,
@@ -121,9 +108,9 @@ 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}")
@@ -137,7 +124,6 @@ class WebSearchTool(Tool):
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()
@@ -174,7 +160,7 @@ class CalculatorTool(Tool):
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,
@@ -197,12 +183,10 @@ class CalculatorTool(Tool):
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
 
@@ -214,7 +198,6 @@ class QuestionAnsweringAgent(CodeAgent):
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__(
@@ -271,7 +254,6 @@ class ChuckAgent:
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")
@@ -279,7 +261,6 @@ class ChuckAgent:
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
 
@@ -294,17 +275,11 @@ class ChuckAgent:
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)"
@@ -314,7 +289,6 @@ 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()
@@ -380,8 +354,11 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answer
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:
@@ -395,7 +372,6 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answer
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]:
@@ -414,7 +390,6 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile]) -> Tuple[s
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
@@ -439,10 +414,11 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile]) -> Tuple[s
439
  return submission_status, results_df
440
 
441
  # --- Build Gradio Interface ---
 
442
  with gr.Blocks() as demo:
443
- gr.Markdown("# Basic Agent Evaluation Runner") # MODIFIED TITLE to match screenshot
444
 
445
- gr.Markdown( # INSTRUCTIONS BLOCK
446
  """
447
  **Instructions:**
448
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
@@ -451,16 +427,12 @@ with gr.Blocks() as demo:
451
  """
452
  )
453
 
454
- gr.Markdown( # ADDED DISCLAIMER BLOCK
455
  """
456
  **Disclaimers:** Once clicking on the "submit" button, it can take quite some time ( this is the time for the agent to go through all the questions). This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a separate action or even to answer the questions in async.
457
  """
458
  )
459
- # NOTE: The original script's "Note:" section about API keys is important and was part of its instructions.
460
- # You might want to integrate it back into the instructions or as a separate note if it's not covered by the screenshot's intent.
461
- # For now, I'm prioritizing matching the screenshot's distinct "Instructions" and "Disclaimers".
462
- # Let's add the technical notes below the disclaimers or combine logically.
463
-
464
  gr.Markdown(
465
  f"""
466
  ---
@@ -468,15 +440,13 @@ with gr.Blocks() as demo:
468
  * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
469
  * Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
470
  * `requirements.txt` should specify `gradio>=4.19.2` or newer.
471
- * Consider trying `OPENAI_MODEL_ID = "gpt-3.5-turbo"` in the script for faster evaluation if it's currently set to `gpt-4`.
472
  """
473
  )
474
 
475
- login_button = gr.LoginButton() # "Sign In with Hugging Face"
476
  run_button = gr.Button("Run Evaluation & Submit All Answers")
477
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
478
- # The DataFrame will initially be empty. When populated, its headers will be:
479
- # "Task ID", "Question", "Submitted Answer", "Reasoning Trace"
480
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True, max_rows=20)
481
 
482
  run_button.click(
@@ -488,7 +458,6 @@ with gr.Blocks() as demo:
488
  # --- Application Startup & Shutdown Handling ---
489
  if __name__ == "__main__":
490
  print("\n" + "-"*30 + " App Starting " + "-"*30)
491
- # ... (startup print messages remain the same)
492
  space_host_startup = os.getenv("SPACE_HOST")
493
  space_id_startup, agent_url_startup = get_space_id_agent_code_url()
494
 
@@ -506,27 +475,37 @@ if __name__ == "__main__":
506
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
507
 
508
  print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
509
- print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}")
510
  print("-"*(60 + len(" App Starting ")) + "\n")
511
  print("Launching Gradio Interface for Chuck Agent Evaluation...")
512
 
513
- # For proper shutdown of shared resources like aiohttp session
514
- # Gradio's .launch() is blocking. A more complex setup might be needed for perfect
515
- # lifecycle management in a continuously running server environment.
516
- # For this script, we'll rely on Python's exit handlers or manual interruption
517
- # to eventually clean up if not explicitly closed.
518
  try:
519
  demo.launch(debug=True, share=False)
520
  finally:
521
- if GLOBAL_CHUCK_AGENT and GLOBAL_CHUCK_AGENT.http_session.loop.is_running():
522
- logger.info("Attempting to shutdown ChuckAgent and close HTTP session...")
523
- # Ensure we run the async shutdown in the correct loop
524
- if asyncio.get_event_loop() is not GLOBAL_CHUCK_AGENT.http_session.loop:
525
- asyncio.set_event_loop(GLOBAL_CHUCK_AGENT.http_session.loop)
526
- GLOBAL_CHUCK_AGENT.http_session.loop.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
527
- elif SHARED_HTTP_SESSION and SHARED_HTTP_SESSION.loop.is_running() and not SHARED_HTTP_SESSION.closed:
528
- # Fallback if agent wasn't fully init but session was made
529
- logger.info("Attempting to close shared HTTP session directly...")
530
- if asyncio.get_event_loop() is not SHARED_HTTP_SESSION.loop:
531
- asyncio.set_event_loop(SHARED_HTTP_SESSION.loop)
532
- SHARED_HTTP_SESSION.loop.run_until_complete(close_shared_http_session())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  QUESTIONS_URL_PATH = "/questions"
28
  SUBMIT_URL_PATH = "/submit"
29
  SCREENSHOTS_DIR = "screenshots"
30
+ OPENAI_MODEL_ID = "gpt-3.5-turbo" # Defaulting to faster/cheaper model
 
 
31
  SERPER_API_NUM_RESULTS = 3
32
  WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
33
  AGENT_MAX_STEPS = 10
 
49
  ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)
50
 
51
  # --- HTTP Client Session Management ---
 
 
 
52
  SHARED_HTTP_SESSION: Optional[aiohttp.ClientSession] = None
53
 
54
  async def get_shared_http_session() -> aiohttp.ClientSession:
 
55
  global SHARED_HTTP_SESSION
56
  if SHARED_HTTP_SESSION is None or SHARED_HTTP_SESSION.closed:
 
 
 
57
  SHARED_HTTP_SESSION = aiohttp.ClientSession()
58
  logger.info("Created shared aiohttp.ClientSession.")
59
  return SHARED_HTTP_SESSION
60
 
61
  async def close_shared_http_session():
 
62
  global SHARED_HTTP_SESSION
63
  if SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed:
64
  await SHARED_HTTP_SESSION.close()
 
72
  inputs = {"url": {"type": "string", "description": "The URL of the image to retrieve"}}
73
  output_type = "string"
74
 
75
+ def __init__(self, session: aiohttp.ClientSession):
76
  super().__init__()
77
  self.image_memory: Dict[str, Dict[str, Any]] = {}
78
  self.screenshot_count = 0
79
+ self._session = session
80
 
81
  async def forward(self, url: str) -> str:
82
  logger.info(f"ImageRetrievalTool called with URL: {url}")
83
  try:
 
84
  async with self._session.get(url, timeout=aiohttp.ClientTimeout(total=20)) as response:
85
  response.raise_for_status()
86
  image_data = await response.read()
87
  image_id = f"image_{self.screenshot_count}"
 
 
88
  self.image_memory[image_id] = {
89
  'data': image_data,
90
  'url': url,
 
108
  inputs = {"query": {"type": "string", "description": "The search query to execute"}}
109
  output_type = "string"
110
 
111
+ def __init__(self, session: aiohttp.ClientSession):
112
  super().__init__()
113
+ self._session = session
114
 
115
  async def forward(self, query: str) -> str:
116
  logger.info(f"WebSearchTool called with query: {query}")
 
124
  payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
125
 
126
  try:
 
127
  async with self._session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
128
  response.raise_for_status()
129
  data = await response.json()
 
160
  inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate"}}
161
  output_type = "string"
162
 
163
+ def __init__(self):
164
  super().__init__()
165
  self.operations = {
166
  '+': operator.add, '-': operator.sub,
 
183
 
184
  # --- Agent Definition ---
185
  class QuestionAnsweringAgent(CodeAgent):
 
186
  def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
 
187
  tools = [
188
  WebSearchTool(session=http_session),
189
+ CalculatorTool(),
190
  ImageRetrievalTool(session=http_session)
191
  ]
192
 
 
198
  effective_model = OpenAIServerModel(
199
  model_id=CONFIG.OPENAI_MODEL_ID,
200
  api_key=openai_api_key
 
201
  )
202
 
203
  super().__init__(
 
254
  self.loop = asyncio.new_event_loop()
255
  asyncio.set_event_loop(self.loop)
256
 
 
257
  self.http_session = self.loop.run_until_complete(get_shared_http_session())
258
  self.agent = QuestionAnsweringAgent(http_session=self.http_session)
259
  logger.info("ChuckAgent fully initialized")
 
261
  def __call__(self, question: str) -> Tuple[str, str]:
262
  logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
263
  try:
 
264
  if asyncio.get_event_loop() is not self.loop:
265
  asyncio.set_event_loop(self.loop)
266
 
 
275
  return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
276
 
277
  async def shutdown(self):
 
278
  logger.info("ChuckAgent shutting down...")
279
  await close_shared_http_session()
280
  logger.info("ChuckAgent shutdown complete.")
281
 
 
282
  # --- Core Evaluation Logic ---
 
 
 
 
283
  def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
284
  space_id = os.getenv("SPACE_ID")
285
  agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Agent code URL not found (SPACE_ID not set)"
 
289
  questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
290
  logger.info(f"Fetching questions from: {questions_url}")
291
  try:
 
292
  response = requests.get(questions_url, timeout=30)
293
  response.raise_for_status()
294
  questions_data = response.json()
 
354
  )
355
  except requests.exceptions.HTTPError as e:
356
  error_detail = f"Server responded with {e.response.status_code}."
357
+ try:
358
+ error_json = e.response.json()
359
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
360
+ except requests.exceptions.JSONDecodeError:
361
+ error_detail += f" Raw Response: {e.response.text[:500]}"
362
  logger.error(f"Submission Failed: {error_detail}")
363
  return f"Submission Failed: {error_detail}"
364
  except requests.exceptions.Timeout:
 
372
  return f"An unexpected error occurred during submission: {e}"
373
 
374
  # --- Gradio Interface Main Function ---
 
375
  GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
376
 
377
  def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile]) -> Tuple[str, pd.DataFrame]:
 
390
  results_log_data: List[Dict[str, Any]] = []
391
 
392
  try:
 
393
  if GLOBAL_CHUCK_AGENT is None:
394
  GLOBAL_CHUCK_AGENT = ChuckAgent()
395
  agent = GLOBAL_CHUCK_AGENT
 
414
  return submission_status, results_df
415
 
416
  # --- Build Gradio Interface ---
417
+ # This is the UI part that was adjusted to look more like the screenshot
418
  with gr.Blocks() as demo:
419
+ gr.Markdown("# Basic Agent Evaluation Runner")
420
 
421
+ gr.Markdown(
422
  """
423
  **Instructions:**
424
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
 
427
  """
428
  )
429
 
430
+ gr.Markdown(
431
  """
432
  **Disclaimers:** Once clicking on the "submit" button, it can take quite some time ( this is the time for the agent to go through all the questions). This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a separate action or even to answer the questions in async.
433
  """
434
  )
435
+
 
 
 
 
436
  gr.Markdown(
437
  f"""
438
  ---
 
440
  * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
441
  * Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
442
  * `requirements.txt` should specify `gradio>=4.19.2` or newer.
443
+ * Consider trying `OPENAI_MODEL_ID = "gpt-3.5-turbo"` (current default) or `"gpt-4"` in the script for different performance/capability.
444
  """
445
  )
446
 
447
+ login_button = gr.LoginButton()
448
  run_button = gr.Button("Run Evaluation & Submit All Answers")
449
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
 
 
450
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True, max_rows=20)
451
 
452
  run_button.click(
 
458
  # --- Application Startup & Shutdown Handling ---
459
  if __name__ == "__main__":
460
  print("\n" + "-"*30 + " App Starting " + "-"*30)
 
461
  space_host_startup = os.getenv("SPACE_HOST")
462
  space_id_startup, agent_url_startup = get_space_id_agent_code_url()
463
 
 
475
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
476
 
477
  print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
478
+ print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}") # For visibility
479
  print("-"*(60 + len(" App Starting ")) + "\n")
480
  print("Launching Gradio Interface for Chuck Agent Evaluation...")
481
 
 
 
 
 
 
482
  try:
483
  demo.launch(debug=True, share=False)
484
  finally:
485
+ # Attempt to gracefully close the aiohttp session on exit
486
+ # This part is a bit tricky with how Gradio's launch() blocks
487
+ # and how different environments handle script termination.
488
+ loop_to_use = None
489
+ if GLOBAL_CHUCK_AGENT and hasattr(GLOBAL_CHUCK_AGENT, 'http_session') and GLOBAL_CHUCK_AGENT.http_session:
490
+ loop_to_use = GLOBAL_CHUCK_AGENT.http_session.loop
491
+ elif SHARED_HTTP_SESSION:
492
+ loop_to_use = SHARED_HTTP_SESSION.loop
493
+
494
+ if loop_to_use and loop_to_use.is_running():
495
+ logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
496
+ # Ensure we are using the correct event loop that the session was created with.
497
+ # This can be complex if multiple loops were involved or if the main loop closed.
498
+ try:
499
+ current_loop = asyncio.get_event_loop()
500
+ if current_loop is not loop_to_use:
501
+ asyncio.set_event_loop(loop_to_use)
502
+
503
+ if GLOBAL_CHUCK_AGENT:
504
+ loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
505
+ elif SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed: # Fallback
506
+ loop_to_use.run_until_complete(close_shared_http_session())
507
+
508
+ except Exception as e:
509
+ logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
510
+ else:
511
+ logger.info("No active HTTP session or loop to close in finally block.")