raise APIConnectionError( f"failed to gene...
# ask-ai
r
raise APIConnectionError( f"failed to generate LLM completion after {self._conn_options.max_retry + 1} attempts", # noqa: E501 ) from e livekit.agents._exceptions.APIConnectionError: failed to generate LLM completion after 4 attempts (body=None, retryable=True) {"pid": 64112, "job_id": "AJ_huBBaBN7T2M8"} 2025-08-05 100023,646 - INFO livekit.agents - closing agent session due to participant disconnect (disable via
RoomInputOptions.close_on_disconnect=False
) {"participant": "identity-CrYS", "reason": "CLIENT_INITIATED", "pid": 64112, "job how to capture this error in our code as there erros are raised by external libraries
t
Thanks for reaching out, Riddhi. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To capture and handle errors raised by external libraries in LiveKit, such as
APIConnectionError
, you can follow these steps: 1. Use Try-Except Blocks: Wrap the code that might raise an error in a try-except block to handle specific exceptions.
Copy code
try:
    # Code that might raise an error
except APIConnectionError as e:
    print(f"Connection error: {e.message}")
except Exception as e:
    print(f"Unexpected error: {str(e)}")
2. Implement Retry Logic: For transient errors, include retry logic. For example:
Copy code
for i in range(self._conn_options.max_retry):
    try:
        # API request
    except Exception as e:
        if i < self._conn_options.max_retry - 1:
            await asyncio.sleep(self._conn_options.retry_interval)
        else:
            raise APIConnectionError("Failed after all retries") from e
3. Log Errors: Use logging to capture error details for debugging.
Copy code
except Exception as e:
    logger.exception("Failed to call API")
    raise APIConnectionError() from e
4. Inspect Error Attributes: For example, check the
retryable
attribute of
APIConnectionError
or the
status_code
of
APIStatusError
to determine the error type and handle it accordingly. These practices will help you effectively capture and manage errors in your code.
r
can we capture using error event? @session.on_error async def handle_error(event: ErrorEvent): if event.error.recoverable: logger.warning(f"[Recoverable Error] Source: {event.source}, Error: {event.error}") else: logger.error(f"[Non-Recoverable Error] Source: {event.source}, Error: {event.error}") await session.say("Something went wrong while processing. Please try again in a moment.")
t
Absolutely! You can catch errors in LiveKit by using an error event handler like
@session.on_error
. The
AgentSession
will emit an
ErrorEvent
whenever something goes wrong, and here’s a friendly way to handle it: 1. Error Event Emission: The
AgentSession
sends out an
ErrorEvent
for things like STT, TTS, or LLM hiccups. 2. Recoverable vs. Unrecoverable Errors: - If
event.error.recoverable
is
True
, the session will try the operation again. - If it’s
False
, that’s your cue to step in—maybe notify the user or log what happened. 3. Example Implementation:
Copy code
@session.on_error
async def handle_error(event: ErrorEvent):
    if event.error.recoverable:
        logger.warning(f"[Recoverable Error] Source: {event.source}, Error: {event.error}")
    else:
        logger.error(f"[Non-Recoverable Error] Source: {event.source}, Error: {event.error}")
        await session.say("Something went wrong while processing. Please try again in a moment.")
4. Custom Handling: You can also get creative—like playing a custom audio message or transferring calls when errors can’t be fixed automatically. This way, you’re handling errors smoothly and keeping the experience as seamless as possible for your users. Sources: livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/experimental/realti... | Events and error handling | LiveKit Docs
r
any import?
t
Hey there! To get started with
@session.on_error
and handle the
ErrorEvent
in LiveKit, you'll want to import these:
Copy code
from livekit.agents.voice import AgentSession
from livekit.agents.voice.events import ErrorEvent
These imports make it easy to create your session and smoothly handle any errors right inside your callback function. Let me know if you need a hand with anything else!