diff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.py index 4167726e06e..1e97156ec94 100644 --- a/tools/code_execution_tool.py +++ b/tools/code_execution_tool.py @@ -395,6 +395,7 @@ def execute_code( tool_call_log: list = [] tool_call_counter = [0] # mutable so the RPC thread can increment exec_start = time.monotonic() + server_sock = None try: # Write the auto-generated hermes_tools module @@ -615,19 +616,17 @@ def execute_code( finally: # Cleanup temp dir and socket - try: - server_sock.close() - except Exception as e: - logger.debug("Server socket close error: %s", e, exc_info=True) - try: - import shutil - shutil.rmtree(tmpdir, ignore_errors=True) - except Exception as e: - logger.debug("Could not clean temp dir: %s", e, exc_info=True) + if server_sock is not None: + try: + server_sock.close() + except OSError as e: + logger.debug("Server socket close error: %s", e) + import shutil + shutil.rmtree(tmpdir, ignore_errors=True) try: os.unlink(sock_path) - except OSError as e: - logger.debug("Could not remove socket file: %s", e, exc_info=True) + except OSError: + pass # already cleaned up or never created def _kill_process_group(proc, escalate: bool = False):