Add better exception handling

The OpikLogger can be used with both `completion` and `acompletion`. Currently
when using it with `completion`, it display the following warnings:

```
17:03:24 - LiteLLM:ERROR: opik.py:71 - OpikLogger - Asynchronous processing not initialized as we are not running in an async context no running event loop
Traceback (most recent call last):
  File ".../litellm/litellm/integrations/opik/opik.py", line 68, in __init__
    asyncio.create_task(self.periodic_flush())
  File ".../asyncio/tasks.py", line 336, in create_task
    loop = events.get_running_loop()
RuntimeError: no running event loop
.../litellm/litellm/integrations/opik/opik.py:74: RuntimeWarning: coroutine 'CustomBatchLogger.periodic_flush' was never awaited
  self.flush_lock = None
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
```

Added code to detect when running in synchronous mode and do not create
asyncio resources in that case.
This commit is contained in:
Boris Feld 2025-02-11 17:45:00 +01:00
parent ce3ead6f91
commit 2a2e01e77b

View file

@ -65,8 +65,12 @@ class OpikLogger(CustomBatchLogger):
self.opik_workspace = opik_workspace
self.opik_api_key = opik_api_key
try:
loop = asyncio.get_running_loop()
asyncio.create_task(self.periodic_flush())
self.flush_lock = asyncio.Lock()
except RuntimeError:
# OpikLogger can be used both synchronously and asynchronously
self.flush_lock = None
except Exception as e:
verbose_logger.exception(
f"OpikLogger - Asynchronous processing not initialized as we are not running in an async context {str(e)}"