11import asyncio
22import json
3+ import warnings
34from collections .abc import Iterable
45from functools import wraps
56
@@ -331,6 +332,10 @@ def __init__(self, *args, **kwargs):
331332 if "no running event loop" not in str (e ):
332333 raise
333334
335+ is_ipython , _ = self ._is_running_in_ipython_or_jupyter ()
336+ if is_ipython :
337+ self ._warn_about_ipython_usage ()
338+
334339 self ._client = GatewayClient (* args , ** kwargs )
335340 self ._initialized = False
336341
@@ -343,6 +348,46 @@ def __init__(self, *args, **kwargs):
343348 else :
344349 raise
345350
351+ def _is_running_in_ipython_or_jupyter (self ):
352+ """Detect if client is running inside an IPython or Jupyter environment."""
353+ try :
354+ import IPython
355+
356+ ipython_instance = IPython .get_ipython ()
357+ if ipython_instance is not None :
358+ if hasattr (ipython_instance , "kernel" ):
359+ return True , "Jupyter"
360+ else :
361+ return True , "IPython"
362+ except ImportError :
363+ pass
364+
365+ try :
366+ import sys
367+
368+ if "ipykernel" in sys .modules :
369+ return True , "Jupyter"
370+ except ImportError :
371+ pass
372+
373+ return False , None
374+
375+ def _warn_about_ipython_usage (self ):
376+ """Issue a warning about using GatewayClientSync in IPython/Jupyter environments."""
377+ warnings .warn (
378+ "You are using GatewayClientSync in an IPython/Jupyter environment."
379+ " This may cause 'RuntimeError: Event loop is closed' on subsequent calls."
380+ " Consider using the async GatewayClient with 'await' syntax instead:\n \n "
381+ " async with GatewayClient(...) as client:\n "
382+ " result = await client.process(text)\n \n "
383+ "Or use nest_asyncio to allow nested event loops:\n \n "
384+ " import nest_asyncio\n "
385+ " nest_asyncio.apply()\n "
386+ " client = GatewayClientSync(...)\n " ,
387+ UserWarning ,
388+ stacklevel = 3 ,
389+ )
390+
346391 def __del__ (self ):
347392 if hasattr (self , "_client" ) and self ._client and getattr (self , "_initialized" , False ):
348393 try :
0 commit comments