OpenAIRealtimeLLMService: an error event or a dropped socket stops the receive loop while the service stays usable
pipecat version
1.11.0 (also reproduced on 1.12.0 and on main at 49dea682f)
Python version
3.14.7 (websockets 16.0)
Operating System
Debian 13 (Docker, aarch64)
Issue description
OpenAIRealtimeLLMService can stop reading its websocket for the rest of a session while reporting nothing the pipeline can act on.
AzureRealtimeLLMService inherits the same code.
- Any error event ends the receive loop.
For every error event except
response_cancel_not_activeandconversation_already_has_active_response,_receive_task_handlercalls_handle_evt_errorand returns ("errors are fatal, so exit the receive loop")._handle_evt_errorcallspush_error(error_msg=f"Error: {evt}"), which is not permanent, so the service stays usable while no later server event (audio, transcripts, tool calls,response.done) is ever read. OpenAI documents most error events as recoverable with the session left open, which is why they stopped being fatal after #1781, but the loop exit stayed.
#5968 (closed without merging) targeted a neighbouring case: an unrecognized server event type ending the same loop.
A socket the server closes mid-session is only logged.
async for message in self._websocketraisesConnectionClosedError(for example 1011), nothing in_receive_task_handlercatches it, and the task manager logs_receive_task_handler unexpected exception. NoErrorFrameis pushed.After that, every send pushes another recoverable error.
_ws_sendfails for each client event, one per user audio chunk, and pushes "Error sending client event" with categoryUNKNOWN, although the comment above it says to "treat a send-side error as fatal". The service never becomes unusable.A socket that cannot be opened is reported as recoverable, but nothing retries it.
_connectpushes the exception's category, so a refused or timed-out connect isCONNECTIVITY(not permanent),_websocketstaysNone, and nothing reconnects later.
OpenAILiveLLMService already handles all four: its receive loop keeps going after an error event, catches ConnectionClosed and reports it with force_treat_as_permanent=True, and its connect and send failures are permanent too.
GeminiLiveLLMService has the same family of problems; reported separately in #5997.
Reproduction steps
- Run
OpenAIRealtimeLLMServicein aPipelineWorkerwithprocessor_unusable_policy=ProcessorUnusablePolicy.ENDand anon_pipeline_errorhandler. - Have the server send one error event followed by a normal event, or close the socket with 1011, or refuse the connection.
- Send a few user audio chunks and check what reaches
on_pipeline_error,is_usable, and whether the second event is read.
Minimal reproducible example
A fake socket replaces websocket_connect; no network or API key.
import asyncio
import json
from unittest.mock import patch
from websockets.exceptions import ConnectionClosedError
from websockets.frames import Close
from pipecat.frames.frames import EndFrame, InputAudioRawFrame
from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.worker import PipelineParams, PipelineWorker, ProcessorUnusablePolicy
from pipecat.services.openai.realtime import llm as realtime_llm
from pipecat.services.openai.realtime.llm import OpenAIRealtimeLLMService
from pipecat.workers.runner import WorkerRunner
ERROR_EVENT = {
"type": "error",
"event_id": "event_1",
"error": {"type": "invalid_request_error", "code": "invalid_value", "message": "Invalid value."},
}
NEXT_EVENT = {
"type": "input_audio_buffer.speech_started",
"event_id": "event_2",
"audio_start_ms": 1000,
"item_id": "item_1",
}
CLOSED = ConnectionClosedError(Close(1011, "internal error"), None)
class FakeSocket:
"""Plays `events`, then either stays open or raises `drop`."""
def __init__(self, events=(), drop=None):
self.events, self.drop, self.read = [json.dumps(e) for e in events], drop, 0
def __aiter__(self):
return self
async def __anext__(self):
if self.events:
self.read += 1
return self.events.pop(0)
if self.drop:
raise self.drop
await asyncio.Event().wait()
async def send(self, data):
if self.drop:
raise self.drop
async def close(self):
pass
async def run(title, connect):
with patch.object(realtime_llm, "websocket_connect", connect):
llm = OpenAIRealtimeLLMService(api_key="test")
worker = PipelineWorker(
Pipeline([llm]),
params=PipelineParams(),
idle_timeout_secs=None,
enable_rtvi=False,
processor_unusable_policy=ProcessorUnusablePolicy.END,
)
errors = []
@worker.event_handler("on_pipeline_error")
async def on_pipeline_error(worker, frame):
errors.append(frame)
runner = WorkerRunner(handle_sigint=False)
await runner.add_workers(worker)
task = asyncio.create_task(runner.run())
await asyncio.sleep(1)
for _ in range(3): # user audio keeps arriving
await worker.queue_frame(
InputAudioRawFrame(audio=b"\0\0" * 240, sample_rate=24000, num_channels=1)
)
await asyncio.sleep(0.5)
print(f"\n{title}")
print(f" errors: {[(e.error[:60], e.category.name) for e in errors]}")
print(f" is_usable: {llm.is_usable} | receive task done: {llm._receive_task is None or llm._receive_task.done()}")
print(f" pipeline still running: {not task.done()}")
await worker.queue_frame(EndFrame())
await task
async def main():
socket = FakeSocket([ERROR_EVENT, NEXT_EVENT])
async def connect_error_event(**kwargs):
return socket
await run("1. one recoverable error event, then a normal event", connect_error_event)
print(f" server events read: {socket.read} of 2")
async def connect_dropped(**kwargs):
return FakeSocket(drop=CLOSED)
await run("2. the server closes the socket mid-session (1011)", connect_dropped)
async def connect_refused(**kwargs):
raise ConnectionRefusedError(111, "Connection refused")
await run("3. the socket cannot be opened", connect_refused)
asyncio.run(main())Expected behavior
- An error event is reported and the service keeps reading the socket, as
OpenAILiveLLMServicedoes. - A socket the server closes, a failed send on a live session, and a failed connect are reported once with
force_treat_as_permanent=True, soProcessorUnusablePolicyapplies instead of the service sitting deaf.
Actual behavior
1. one recoverable error event, then a normal event
errors: [("Error: event_id='event_1' type='error' error=RealtimeError(t", 'UNKNOWN')]
is_usable: True | receive task done: True
pipeline still running: True
server events read: 1 of 2
2. the server closes the socket mid-session (1011)
errors: [('Error sending client event: received 1011 (internal error) i', 'UNKNOWN'), ('Error sending client event: received 1011 (internal error) i', 'UNKNOWN'), ('Error sending client event: received 1011 (internal error) i', 'UNKNOWN')]
is_usable: True | receive task done: True
pipeline still running: True
3. the socket cannot be opened
errors: [('Error connecting: [Errno 111] Connection refused', 'CONNECTIVITY')]
is_usable: True | receive task done: True
pipeline still running: TrueIn case 2 the drop itself only appears in the task manager's log:
ERROR | pipecat.utils.asyncio.task_manager:run_coroutine:199 - OpenAIRealtimeLLMService#1::_receive_task_handler unexpected exception (...): received 1011 (internal error) internal error; no close frame sentProposed fix
Mirror OpenAILiveLLMService:
- In
_receive_task_handler, drop thereturnafter_handle_evt_error, and catchConnectionClosedaround the loop, pushing it withforce_treat_as_permanent=Trueunless_disconnecting. - In
_ws_sendand_connect, push withforce_treat_as_permanent=True.
Before you submit
- I have personally reproduced this issue on the latest Pipecat release (or
main). - I have searched existing issues for this bug.
- If AI tools helped write this report, I have verified the behavior myself and will personally answer follow-up questions.
Source: pipecat-ai/pipecat