1
1
import asyncio
2
2
import json
3
+ import warnings
3
4
from collections .abc import Iterable
4
5
from functools import wraps
5
6
@@ -331,6 +332,10 @@ def __init__(self, *args, **kwargs):
331
332
if "no running event loop" not in str (e ):
332
333
raise
333
334
335
+ is_ipython , _ = self ._is_running_in_ipython_or_jupyter ()
336
+ if is_ipython :
337
+ self ._warn_about_ipython_usage ()
338
+
334
339
self ._client = GatewayClient (* args , ** kwargs )
335
340
self ._initialized = False
336
341
@@ -343,6 +348,46 @@ def __init__(self, *args, **kwargs):
343
348
else :
344
349
raise
345
350
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
+
346
391
def __del__ (self ):
347
392
if hasattr (self , "_client" ) and self ._client and getattr (self , "_initialized" , False ):
348
393
try :
0 commit comments