Skip to content

No current event loop in thread #3

Open
@RegisGraptin

Description

@RegisGraptin

When using the SDK in a thread mode, by using with FastAPI or Streamlit (in my case), I encounter the following issue:

   ...
  File "/.../secret-ai-getting-started/src/secret/secret_chat_server.py", line 29, in __init__
    secret_client = Secret(
                    ^^^^^^^
  File "/.../secret-ai-getting-started/.venv/lib/python3.12/site-packages/secret_ai_sdk/secret.py", line 35, in __init__
    self.secret_client = LCDClient(chain_id=self.chain_id, url=self.node_url)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/.../secret-ai-getting-started/.venv/lib/python3.12/site-packages/secret_sdk/client/lcd/lcdclient.py", line 289, in __init__
    loop=nest_asyncio.apply(get_event_loop()),
                            ^^^^^^^^^^^^^^^^
  File "/.../.pyenv/versions/3.12.7/lib/python3.12/asyncio/events.py", line 702, in get_event_loop
    raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'ScriptRunner.scriptThread'.

The fix I used was to modify the lcdclient.py file with:

+from asyncio import AbstractEventLoop, get_event_loop, TimeoutError, new_event_loop, set_event_loop

...

def __init__(
        self,
        url: str,
        chain_id: str = None,
        gas_prices: Optional[Coins.Input] = default_gas_prices,
        gas_adjustment: Optional[Numeric.Input] = default_gas_adjustment,
        custom_fees: Optional[dict] = default_fees,
        _request_config: Optional[dict] = REQUEST_CONFIG
    ):
        self.lock = Lock()

+         try:
+            loop = get_event_loop()
+        except RuntimeError:
+            loop = new_event_loop()
+            set_event_loop(loop)
        
+        loop = nest_asyncio.apply(loop)

        super().__init__(
            url,
            chain_id,
            gas_prices,
            gas_adjustment,
            custom_fees,
            _create_session=False,
+            loop=loop,
            _request_config=_request_config
        )

Not fully familiar on how the SDK should handle the co-routine. May missed some stuff here, but wanted to highlight the issue when using it with FastAPI for instance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions