{"record":{"id":"fe23077ff756bba4","repo":"xtekky/gpt4free","slug":"install-nest-asyncio2-package-pip-install-u-n","errorCode":null,"errorMessage":"Install \"nest-asyncio2\" package | pip install -U nest-asyncio2","messagePattern":"Install \"nest-asyncio2\" package \\| pip install -U nest-asyncio2","errorType":"exception","errorClass":"NestAsyncioError","httpStatus":null,"severity":"error","filePath":"g4f/providers/asyncio.py","lineNumber":34,"sourceCode":"    import uvloop\n\n    has_uvloop = True\nexcept ImportError:\n    has_uvloop = False\n\n\ndef get_running_loop(check_nested: bool) -> Optional[AbstractEventLoop]:\n    try:\n        loop = asyncio.get_running_loop()\n        # Do not patch uvloop loop because its incompatible.\n        if has_uvloop:\n            if isinstance(loop, uvloop.Loop):\n                return loop\n        if not hasattr(loop.__class__, \"_nest_patched\"):\n            if has_nest_asyncio:\n                nest_asyncio.apply(loop)\n            elif check_nested:\n                raise NestAsyncioError(\n                    'Install \"nest-asyncio2\" package | pip install -U nest-asyncio2'\n                )\n        return loop\n    except RuntimeError:\n        pass\n\n\n# Fix for RuntimeError: async generator ignored GeneratorExit\nasync def await_callback(callback: Callable, timeout: Optional[int] = None) -> any:\n    try:\n        return (\n            await asyncio.wait_for(callback(), timeout)\n            if timeout is not None\n            else await callback()\n        )\n    except TimeoutError as e:\n        raise TimeoutError(\n            \"The operation timed out after {} seconds\".format(timeout)","sourceCodeStart":16,"sourceCodeEnd":52,"githubUrl":"https://github.com/xtekky/gpt4free/blob/973504e1770928ed5fb82f43da528f441ad9ddc3/g4f/providers/asyncio.py#L16-L52","documentation":"Raised by get_running_loop(check_nested=True): the caller is inside a running asyncio event loop that is not nest-asyncio-patched, and the nest_asyncio2 package is not installed. g4f's sync-style APIs need to run coroutines on an already-running loop, which plain asyncio forbids; nest-asyncio2 patches the loop (adding _nest_patched) to allow re-entrant run_until_complete. uvloop loops are exempt because they cannot be patched, so the loop is returned unpatched.","triggerScenarios":"Calling g4f's synchronous completion APIs (which use get_running_loop) from inside async code — e.g. provider.create_completion inside a Jupyter cell, a FastAPI handler, or any async def — while nest_asyncio2 is absent and the current loop lacks _nest_patched.","commonSituations":"Jupyter/IPython users (there is always a running loop); calling g4f inside Discord bots or web servers; fresh installs where the optional nest-asyncio2 dependency was not installed.","solutions":["pip install -U nest-asyncio2","Prefer the async API (create_async_generator / async completion) instead of the sync wrapper inside event loops","Run the sync call in a worker thread so it gets its own loop: asyncio.to_thread(...)"],"exampleFix":"# before (inside async def / Jupyter)\nresponse = g4f.ChatCompletion.create(...)\n\n# after\nresponse = await asyncio.to_thread(g4f.ChatCompletion.create, ...)\n# or: pip install -U nest-asyncio2","handlingStrategy":"fallback","validationCode":"import asyncio\ndef in_running_loop() -> bool:\n    try:\n        asyncio.get_running_loop(); return True\n    except RuntimeError:\n        return False","typeGuard":null,"tryCatchPattern":"try:\n    result = g4f.ChatCompletion.create(...)  # sync API\nexcept NestAsyncioError:\n    result = asyncio.get_event_loop().run_until_complete(\n        asyncio.to_thread(g4f.ChatCompletion.create, ...)\n    )","preventionTips":["Install nest-asyncio2 alongside g4f when embedding in Jupyter or async servers","Prefer the async API whenever a loop is already running","Guard sync calls with asyncio.to_thread in async hosts"],"tags":["asyncio","event-loop","dependency","jupyter"],"backgroundTag":null,"analyzedSha":"973504e1770928ed5fb82f43da528f441ad9ddc3","analyzedAt":"2026-08-14T23:45:32.408Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}