From 74280829fcf5e03754ba5263162ff70eaabcdc4a Mon Sep 17 00:00:00 2001 From: Filipi Fuchter Date: Mon, 23 Jun 2025 18:48:03 -0300 Subject: [PATCH] Fixed an issue with the FastAPIWebsocketClient to disconnect in case the websocket is already closed. --- .../transports/network/fastapi_websocket.py | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/pipecat/transports/network/fastapi_websocket.py b/src/pipecat/transports/network/fastapi_websocket.py index 97ff8e03a..e2cf65dbe 100644 --- a/src/pipecat/transports/network/fastapi_websocket.py +++ b/src/pipecat/transports/network/fastapi_websocket.py @@ -70,11 +70,22 @@ class FastAPIWebsocketClient: return self._websocket.iter_bytes() if self._is_binary else self._websocket.iter_text() async def send(self, data: str | bytes): - if self._can_send(): - if self._is_binary: - await self._websocket.send_bytes(data) - else: - await self._websocket.send_text(data) + try: + if self._can_send(): + if self._is_binary: + await self._websocket.send_bytes(data) + else: + await self._websocket.send_text(data) + except Exception as e: + logger.error( + f"{self} exception sending data: {e.__class__.__name__} ({e}), application_state: {self._websocket.application_state}" + ) + # For some reason the websocket is disconnected, and we are not able to send data + # So let's properly handle it and disconnect the transport + if self._websocket.application_state == WebSocketState.DISCONNECTED: + logger.warning("Closing already disconnected websocket!") + self._closing = True + await self.trigger_client_disconnected() async def disconnect(self): self._leave_counter -= 1