Team Ai
Apppublic

openenv/coding_env

sourceHugging Faceupdated 3mo agoView on Hugging Face
21likes
utils.py60 linesDownload Raw Back to core
1# Copyright (c) Meta Platforms, Inc. and affiliates.2# All rights reserved.3#4# This source code is licensed under the BSD-style license found in the5# LICENSE file in the root directory of this source tree.6 7"""Utility functions for OpenEnv core."""8 9import asyncio10import concurrent.futures11 12 13def run_async_safely(coro):14    """15    Run an async coroutine safely from any context.16 17    This handles the case where we may already be inside an async event loop18    (e.g., when called from an async framework). In that case, asyncio.run()19    would fail, so we use a ThreadPoolExecutor to run in a separate thread.20 21    Args:22        coro: The coroutine to run23 24    Returns:25        The result of the coroutine26    """27    try:28        loop = asyncio.get_running_loop()29    except RuntimeError:30        loop = None31 32    if loop is not None:33        # Already in async context - run in a thread pool34        with concurrent.futures.ThreadPoolExecutor() as pool:35            future = pool.submit(asyncio.run, coro)36            return future.result()37    else:38        # No async context - use asyncio.run() directly39        return asyncio.run(coro)40 41 42def convert_to_ws_url(url: str) -> str:43    """44    Convert an HTTP/HTTPS URL to a WS/WSS URL.45 46    Args:47        url: The URL to convert.48 49    Returns:50        The converted WebSocket URL.51    """52    ws_url = url.rstrip("/")53    if ws_url.startswith("http://"):54        ws_url = "ws://" + ws_url[7:]55    elif ws_url.startswith("https://"):56        ws_url = "wss://" + ws_url[8:]57    elif not ws_url.startswith("ws://") and not ws_url.startswith("wss://"):58        ws_url = "ws://" + ws_url59    return ws_url60