this seems to fix CTRL+C issues and litellm warnin...
# proj-sdk
w
this seems to fix CTRL+C issues and litellm warnings https://github.com/All-Hands-AI/agent-sdk/pull/492/files Rohit, curious if this will interfere with your CTRL+C handling in the CLI
q
I'll verify in a bit
👍 1
c
Copy code
# OpenHands CLI Slow Exit Profiling Results

## Problem Identified

The OpenHands CLI was experiencing extremely slow exit behavior after displaying "Goodbye!" - taking 240+ seconds to fully exit.

## Root Cause Analysis

Through profiling, we identified that the issue was caused by **LiteLLM's async client cleanup mechanism**:

1. **Import Time**: The initial import of `openhands_cli.simple_main` takes ~1.8 seconds
2. **Main Issue**: LiteLLM registers an `atexit` handler that attempts to clean up async HTTP clients
3. **Problematic Code**: The cleanup function in `/lib/python3.12/site-packages/litellm/llms/custom_httpx/async_client_cleanup.py` line 78 has this warning:
RuntimeWarning: coroutine 'close_litellm_async_clients' was never awaited
Copy code
4. **Delay Cause**: When the program exits, Python waits for these unawaited coroutines to be cleaned up by the garbage collector, causing the 240+ second delay.

## Solution Implemented

We implemented a comprehensive fix in two parts:

### 1. Prevention of Problematic Registration
In `simple_main.py`, we prevent LiteLLM from registering its problematic atexit handler:

```python
def _prevent_litellm_atexit_registration():
    """Prevent LiteLLM from registering its problematic atexit handler."""
    try:
        import litellm
        
        # Override the register_async_client_cleanup function to do nothing
        def dummy_register_cleanup():
            pass
        
        # Replace the problematic function
        if hasattr(litellm, 'register_async_client_cleanup'):
            litellm.register_async_client_cleanup = dummy_register_cleanup
            
    except ImportError:
        pass
### 2. Proper Async Client Cleanup We added our own cleanup function that properly handles async clients:
Copy code
python
def cleanup_async_clients() -> None:
    """Clean up async HTTP clients to prevent delays during exit."""
    try:
        import litellm
        
        async def async_cleanup():
            await litellm.close_litellm_async_clients()
        
        # Try multiple approaches to run the cleanup properly
        try:
            loop = asyncio.get_event_loop()
            if loop.is_closed():
                raise RuntimeError("Loop is closed")
            
            if loop.is_running():
                loop.create_task(async_cleanup())
            else:
                loop.run_until_complete(async_cleanup())
                
        except RuntimeError:
            # Create new event loop if needed
            new_loop = asyncio.new_event_loop()
            asyncio.set_event_loop(new_loop)
            new_loop.run_until_complete(async_cleanup())
            new_loop.close()
            
    except ImportError:
        pass
### 3. Integration with Exit Points We call the cleanup function before showing "Goodbye!" in both exit scenarios: - In `simple_main.py`: Before KeyboardInterrupt and EOFError handling - In `agent_chat.py`: Before "/exit" command and KeyboardInterrupt handling ## Results ### Before Fix: - Total execution time: 240.186 seconds - RuntimeWarning about unawaited coroutines - Significant delay after "Goodbye!" message ### After Fix: - Total execution time: ~1.8 seconds - No more RuntimeWarning about unawaited coroutines - Immediate exit after "Goodbye!" message - 99.2% improvement in exit speed ## Files Modified 1.
openhands_cli/simple_main.py
- Added prevention mechanism and cleanup function 2.
openhands_cli/agent_chat.py
- Added cleanup calls before exit points ## Testing Created comprehensive test suite that verifies: - ✅ Cleanup function executes quickly (< 0.1s) - ✅ Import time is reasonable (< 2s) - ✅ No RuntimeWarnings about unawaited coroutines - ✅ Total exit time is fast (< 2s vs 240s+) ## Conclusion The slow exit issue has been successfully resolved by: 1. Preventing LiteLLM's problematic atexit registration 2. Implementing proper async client cleanup 3. Calling cleanup at appropriate exit points The fix reduces exit time from 240+ seconds to ~1.8 seconds, providing a much better user experience.``` Interestingly, OH seems to think this is the source of issue for "CLI slow to shutdown": https://github.com/All-Hands-AI/OpenHands/issues/11103
and i did notice CLI gets slower and slower to shutdown as i chat more with it..
so it could be this litellm bug
w
I noticed some imports get pulled in at runtime (when a tool is called maybe?)--that could be a culprit
c
actually i just try to reproduce, it is very slow to shut it down (after "Goodbye!", you'd wait for a full seconds for it to send you back to your terminal)
nod 1