xtekky/gpt4free · error · NestAsyncioError

Install "nest-asyncio2" package | pip install -U nest-asynci

Error message

Install "nest-asyncio2" package | pip install -U nest-asyncio2

What it means

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.

Source

Thrown at g4f/providers/asyncio.py:34

    import uvloop

    has_uvloop = True
except ImportError:
    has_uvloop = False


def get_running_loop(check_nested: bool) -> Optional[AbstractEventLoop]:
    try:
        loop = asyncio.get_running_loop()
        # Do not patch uvloop loop because its incompatible.
        if has_uvloop:
            if isinstance(loop, uvloop.Loop):
                return loop
        if not hasattr(loop.__class__, "_nest_patched"):
            if has_nest_asyncio:
                nest_asyncio.apply(loop)
            elif check_nested:
                raise NestAsyncioError(
                    'Install "nest-asyncio2" package | pip install -U nest-asyncio2'
                )
        return loop
    except RuntimeError:
        pass


# Fix for RuntimeError: async generator ignored GeneratorExit
async def await_callback(callback: Callable, timeout: Optional[int] = None) -> any:
    try:
        return (
            await asyncio.wait_for(callback(), timeout)
            if timeout is not None
            else await callback()
        )
    except TimeoutError as e:
        raise TimeoutError(
            "The operation timed out after {} seconds".format(timeout)

View on GitHub (pinned to 973504e177)

Solutions

  1. pip install -U nest-asyncio2
  2. Prefer the async API (create_async_generator / async completion) instead of the sync wrapper inside event loops
  3. Run the sync call in a worker thread so it gets its own loop: asyncio.to_thread(...)

Example fix

# before (inside async def / Jupyter)
response = g4f.ChatCompletion.create(...)

# after
response = await asyncio.to_thread(g4f.ChatCompletion.create, ...)
# or: pip install -U nest-asyncio2
Defensive patterns

Strategy: fallback

Validate before calling

import asyncio
def in_running_loop() -> bool:
    try:
        asyncio.get_running_loop(); return True
    except RuntimeError:
        return False

Try / catch

try:
    result = g4f.ChatCompletion.create(...)  # sync API
except NestAsyncioError:
    result = asyncio.get_event_loop().run_until_complete(
        asyncio.to_thread(g4f.ChatCompletion.create, ...)
    )

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14). Data as JSON: /api/errors/fe23077ff756bba4. Report an issue: GitHub.