Team Ai
Apppublic

openenv/echo_env

sourceHugging Faceupdated 1d agoView on Hugging Face
6likes
utils.py56 linesDownload Raw Back to core
1# SPDX-License-Identifier: BSD-3-Clause2 3"""Utility functions for OpenEnv core."""4 5import asyncio6import concurrent.futures7 8 9def run_async_safely(coro):10    """11    Run an async coroutine safely from any context.12 13    This handles the case where we may already be inside an async event loop14    (e.g., when called from an async framework). In that case, asyncio.run()15    would fail, so we use a ThreadPoolExecutor to run in a separate thread.16 17    Args:18        coro: The coroutine to run19 20    Returns:21        The result of the coroutine22    """23    try:24        loop = asyncio.get_running_loop()25    except RuntimeError:26        loop = None27 28    if loop is not None:29        # Already in async context - run in a thread pool30        with concurrent.futures.ThreadPoolExecutor() as pool:31            future = pool.submit(asyncio.run, coro)32            return future.result()33    else:34        # No async context - use asyncio.run() directly35        return asyncio.run(coro)36 37 38def convert_to_ws_url(url: str) -> str:39    """40    Convert an HTTP/HTTPS URL to a WS/WSS URL.41 42    Args:43        url: The URL to convert.44 45    Returns:46        The converted WebSocket URL.47    """48    ws_url = url.rstrip("/")49    if ws_url.startswith("http://"):50        ws_url = "ws://" + ws_url[7:]51    elif ws_url.startswith("https://"):52        ws_url = "wss://" + ws_url[8:]53    elif not ws_url.startswith("ws://") and not ws_url.startswith("wss://"):54        ws_url = "ws://" + ws_url55    return ws_url56