How do I automatically retry APIConnectionError er...
# ask-ai
r
How do I automatically retry APIConnectionError errors
t
Thanks for reaching out, Trevor. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To automatically retry
APIConnectionError
errors, you can implement a retry mechanism similar to the one used in the
_main_task()
method of the ChunkedStream class. Here's how it works: 1. Attempt to run the desired operation (e.g.,
_run()
) within a loop that iterates based on the
max_retry
value from your connection options. 2. If an
APIError
occurs, calculate a retry interval using a method like
_interval_for_retry(i)
. 3. If
max_retry
is 0, raise the exception immediately. 4. If the current attempt is the last one allowed, raise an
APIConnectionError
with a message indicating the failure after all attempts. 5. Otherwise, log a warning message and wait for the calculated retry interval before trying again. Here is an example implementation:
Copy code
async def _main_task(self):
    for i in range(self._conn_options.max_retry + 1):
        try:
            return await self._run()
        except APIError as e:
            retry_interval = self._conn_options._interval_for_retry(i)
            if self._conn_options.max_retry == 0:
                raise
            elif i == self._conn_options.max_retry:
                raise APIConnectionError(
                    f"failed to synthesize speech after {self._conn_options.max_retry + 1} attempts",
                ) from e
            else:
                logger.warning(
                    f"failed to synthesize speech, retrying in {retry_interval}s",
                    exc_info=e,
                    extra={
                        "tts": self._tts._label,
                        "attempt": i + 1,
                        "streamed": False,
                    },
                )

            await asyncio.sleep(retry_interval)
This approach ensures that the operation is retried a specified number of times with appropriate intervals between attempts. Sources: livekit.agents.tts API documentation