GeminiLiveLLMService: connection failures never mark the service unusable, and a session that fails to open is only logged
pipecat version
1.11.0 (also reproduced on 1.12.0 and on main at 49dea682f)
Python version
3.14.7 (google-genai 2.25.0, websockets 16.0)
Operating System
Debian 13 (Docker, aarch64)
Issue description
GeminiLiveLLMService reports connection failures in ways the pipeline cannot act on.
GeminiLiveVertexLLMService inherits the same methods.
A session that fails to open is only logged.
_connection_task_handleropens the session withasync with self._client.aio.live.connect(...)outside itstry, which only wraps the receive loop. When the server rejects the setup (google-genai raisesAPIError, for example 1008 when the model is not available forbidiGenerateContent, as in the log in #3348) or the socket cannot be opened, the exception escapes the connection task and the task manager logs_connection_task_handler unexpected exception. NoErrorFrameis pushed,_handle_connection_errornever runs, nothing retries, andis_usablestays True, soon_pipeline_errornever fires andProcessorUnusablePolicynever applies. The bot is silent for the whole session.Giving up after
MAX_CONSECUTIVE_FAILURESleaves the service usable._handle_connection_errorlogs "Max consecutive failures (3) reached, treating as fatal error" and callspush_error(error_msg=error_msg, exception=error). google-genai'sAPIErrorhas no HTTP status the classifier reads, so the category isUNKNOWN, the service stays usable, and the pipeline keeps running with no session and no further reconnect.A send-side error is not fatal either.
_handle_send_errorsays "let's just treat a send-side error as fatal", but callspush_error(error_msg=f"Send error: {error}")with no exception, category orforce_treat_as_permanent. It passedfatal=Trueuntil the error-handling rework in #3084 dropped the flag.A connection that drops mid-reply never ends that reply.
_disconnect(), which_reconnect()calls, resets most session state but not_bot_is_responding, and noTTSStoppedFrameis pushed for the cut-off reply, whether or not the reconnect succeeds. AnEndFramethat arrives before the model completes another turn is then deferred for the full_END_FRAME_DEFERRAL_TIMEOUT_SECS(30 s). This may be the case behind the hang that #4125 added that timeout for.
For comparison, OpenAILiveLLMService reports its connect, send and connection-closed failures with force_treat_as_permanent=True.
Related but different: #5465 (input dropped while reconnecting) and #4366 (Gemini 3.x needs a realtime-input nudge after a tool result).
OpenAIRealtimeLLMService has the same family of problems; reported separately in #5998.
Reproduction steps
- Run
GeminiLiveLLMServicein aPipelineWorkerwithprocessor_unusable_policy=ProcessorUnusablePolicy.ENDand anon_pipeline_errorhandler. - Make the Live session fail to open (1008), drop on every connection (1011), fail a send, or drop mid-reply and then reconnect.
- Check what reaches
on_pipeline_error,is_usable, whether the pipeline ends, and how long a laterEndFrametakes.
Minimal reproducible example
Fakes stand in for google-genai's live client (the exceptions are the ones google-genai and websockets raise); no network or API key.
import asyncio
import contextlib
import time
from google.genai import errors
from google.genai.types import Blob, Content, LiveServerContent, LiveServerMessage, Part
from websockets.exceptions import ConnectionClosedError
from websockets.frames import Close
from pipecat.frames.frames import EndFrame, InputAudioRawFrame, TTSStartedFrame, TTSStoppedFrame
from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.worker import PipelineParams, PipelineWorker, ProcessorUnusablePolicy
from pipecat.processors.frame_processor import FrameProcessor
from pipecat.services.google.gemini_live.llm import GeminiLiveLLMService
from pipecat.workers.runner import WorkerRunner
def api_error(code, reason):
"""What google-genai raises when the Live socket closes with `code`."""
try:
errors.APIError.raise_error(code, reason, None)
except errors.APIError as e:
return e
AUDIO = LiveServerMessage(
server_content=LiveServerContent(
model_turn=Content(parts=[Part(inline_data=Blob(data=b"\0\0" * 2400, mime_type="audio/pcm;rate=24000"))])
)
)
class FakeSession:
def __init__(self, messages=(), drop=None):
self.messages, self.drop = list(messages), drop
async def receive(self):
for m in self.messages:
yield m
if self.drop:
raise self.drop
await asyncio.Event().wait()
async def send_realtime_input(self, **kwargs):
# google-genai sends with websocket.send(), which raises this once the socket is gone.
raise ConnectionClosedError(Close(1011, "internal error"), None)
async def close(self):
pass
class FakeLive:
"""Stands in for client.aio.live; `script(attempt)` returns a session or an exception."""
def __init__(self, script):
self.script, self.attempts = script, 0
@contextlib.asynccontextmanager
async def connect(self, *, model, config=None):
self.attempts += 1
step = self.script(self.attempts)
if isinstance(step, Exception):
raise step
yield step
class Collect(FrameProcessor):
def __init__(self):
super().__init__()
self.frames = []
async def process_frame(self, frame, direction):
await super().process_frame(frame, direction)
self.frames.append(frame)
await self.push_frame(frame, direction)
async def run(title, script, action=None):
llm = GeminiLiveLLMService(api_key="test")
llm._client = type("C", (), {"aio": type("A", (), {"live": FakeLive(script)})()})()
collect = Collect()
worker = PipelineWorker(
Pipeline([llm, collect]),
params=PipelineParams(),
idle_timeout_secs=None,
enable_rtvi=False,
processor_unusable_policy=ProcessorUnusablePolicy.END,
)
errors_seen = []
@worker.event_handler("on_pipeline_error")
async def on_pipeline_error(worker, frame):
errors_seen.append(frame)
runner = WorkerRunner(handle_sigint=False)
await runner.add_workers(worker)
task = asyncio.create_task(runner.run())
await asyncio.sleep(1)
if action:
await action(llm, worker)
await asyncio.sleep(1)
print(f"\n{title}")
print(" errors:", [(e.error[:70], e.category.name) for e in errors_seen])
print(" is_usable:", llm.is_usable, "| pipeline still running:", not task.done())
started = sum(isinstance(f, TTSStartedFrame) for f in collect.frames)
stopped = sum(isinstance(f, TTSStoppedFrame) for f in collect.frames)
print(f" TTSStartedFrame={started} TTSStoppedFrame={stopped}")
t0 = time.monotonic()
await worker.queue_frame(EndFrame())
await task
print(f" EndFrame took {time.monotonic() - t0:.1f} s")
async def send_audio(llm, worker):
llm._ready_for_realtime_input = True # as after the initial response
await worker.queue_frame(InputAudioRawFrame(audio=b"\0\0" * 160, sample_rate=16000, num_channels=1))
async def main():
drop = api_error(1011, "Internal error encountered.")
await run(
"1. session fails to open",
lambda n: api_error(1008, "models/x is not found for API version v1beta"),
)
await run("2. session drops, reconnects exhausted", lambda n: FakeSession(drop=drop))
await run("3. send fails on a live session", lambda n: FakeSession(), action=send_audio)
await run(
"4. session drops mid-reply, reconnect succeeds",
lambda n: FakeSession([AUDIO], drop=drop) if n == 1 else FakeSession(),
)
asyncio.run(main())Expected behavior
- A session that cannot be opened reaches the application as an
ErrorFrameand goes through the same handling as a dropped connection; a setup the server rejects (1007, 1008) is permanent at once. - When the reconnect ladder gives up, and on a send-side error, the service is marked unusable (
force_treat_as_permanent=True), soProcessorUnusablePolicy.ENDends the pipeline. - A connection loss ends a reply in progress, as an interruption does (clear
_bot_is_responding, pushTTSStoppedFrame), so a laterEndFrameis not held for 30 s.
Actual behavior
1. session fails to open
errors: []
is_usable: True | pipeline still running: True
TTSStartedFrame=0 TTSStoppedFrame=0
EndFrame took 0.0 s
2. session drops, reconnects exhausted
errors: [('Max consecutive failures (3) reached, treating as fatal error', 'UNKNOWN')]
is_usable: True | pipeline still running: True
TTSStartedFrame=0 TTSStoppedFrame=0
EndFrame took 0.0 s
3. send fails on a live session
errors: [('Send error: received 1011 (internal error) internal error; no close fr', 'UNKNOWN')]
is_usable: True | pipeline still running: True
TTSStartedFrame=0 TTSStoppedFrame=0
EndFrame took 0.0 s
4. session drops mid-reply, reconnect succeeds
errors: []
is_usable: True | pipeline still running: True
TTSStartedFrame=1 TTSStoppedFrame=0
EndFrame took 30.0 sLogs
ERROR | pipecat.utils.asyncio.task_manager:run_coroutine:199 - GeminiLiveLLMService#0::_connection_task_handler unexpected exception (.../google/genai/errors.py:206): 1008 None. models/x is not found for API version v1beta
ERROR | pipecat.processors.frame_processor:push_error_frame:1000 - GeminiLiveLLMService#1 exception (.../google/genai/errors.py:206): Max consecutive failures (3) reached, treating as fatal error
WARNING | pipecat.pipeline.worker:_source_push_frame:1482 - PipelineWorker#1: Something went wrong: ErrorFrame#0(error: Max consecutive failures (3) reached, treating as fatal error, fatal: False)
ERROR | pipecat.processors.frame_processor:push_error_frame:1000 - GeminiLiveLLMService#2 error: Send error: received 1011 (internal error) internal error; no close frame sent
WARNING | pipecat.services.google.gemini_live.llm:_timeout:1272 - EndFrame deferral timed out after 30.0s without receiving turn_completeProposed fix
- Bring the
async with self._client.aio.live.connect(...)into the failure handling, so an exception raised while opening goes through_handle_connection_errorlike a dropped connection. - Override
_classify_errorfor google-genaiAPIErrorclose codes, so a rejected setup (1007, 1008) isINVALID_REQUESTand permanent without three retries. - Pass
force_treat_as_permanent=True(andexception=errorfor the send case) where the ladder gives up and in_handle_send_error, asOpenAILiveLLMServicedoes. - On connection loss, end an in-flight reply the way
_handle_interruptiondoes, for example in_disconnect().
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