agents icon indicating copy to clipboard operation
agents copied to clipboard

Gemini realtime: trailing audio truncated when a tool call ends the turn

Open joneriktalvio opened this issue 6 months ago • 9 comments

Gemini realtime: trailing audio truncated when a tool call ends the turn

Summary

livekit/plugins/google/realtime/realtime_api.py:_handle_tool_calls closes the current generation's audio_ch synchronously on receipt of a toolCall message. Because Gemini Live emits toolCall mid-turn (before flushing the final serverContent.modelTurn.parts audio chunks), the close is premature: the framework's speech handle resolves _done_fut, RunContext.wait_for_playout() returns as a no-op, and any tool that does "wait for playout then tear down the room" (e.g. an end_call tool) cuts the audio mid-syllable.

OpenAI's Realtime API doesn't have this shape — its plugin only closes audio on response.done, which the API guarantees is sent after the final audio delta.

PR #2439 fixed a related downstream symptom (transcript not finalised) on the now-removed beta/realtime/ path. Audio truncation is a separate symptom of the same upstream cause and is still present on main.

Reproduction

Minimal recipe (no SIP/Twilio needed — bug is at the LiveKit-room layer):

  1. Run a local LiveKit dev server (docker run livekit/livekit-server --dev).
  2. Connect two participants to the same room:
    • Agent: AgentSession(llm=google.realtime.RealtimeModel(...)) with instructions "Say 'Goodbye and have a great day.' then call the end_call tool." and a single tool:

      @function_tool()
      async def end_call(ctx: RunContext) -> str:
          await ctx.wait_for_playout()
          await lk_api.room.delete_room(api.DeleteRoomRequest(room=room_name))
          return "Call ended"
      
    • Listener: subscribes to the agent's audio track via rtc.AudioStream, writes received PCM frames to a WAV.

  3. Run the same scenario against gpt-realtime-2 and a Gemini Live model. Compare the WAVs.

The Gemini WAV ends at the last non-silent sample (zero trailing silence, i.e. mid-syllable cut). The OpenAI WAV ends with the model's natural silence pad. Same prompt, same tool, same room teardown logic; only the realtime model differs.

A fuller automated harness — with quiescence-based deferred-close patching for A/B, a macOS-say user-input fixture for audio-driven turns, and a WAV trailing-silence analyzer for verdicts — is available on request.

Comparing WAVs across runs:

Run wait_for_playout returned in WAV duration Trailing silence Effective speech end
OpenAI Realtime (gpt-realtime-2) 1.98 s 5.23 s 0.38 s 4.85 s
Gemini (gemini-3.1-flash-live-preview) 29 ms 1.37 s 0.00 s 1.37 s

Trailing silence of 0.00 s + audio published only up to 1.37 s = audio cut at a non-silent sample, i.e. mid-syllable. The 29 ms wait_for_playout return confirms _done_fut was already resolved by the time the tool called it.

The same shape is reproduced in the audio-driven path (caller mic publishes a pre-recorded request, Gemini responds, calls end_call): WAV 3.01 s, trailing silence 0.00 s.

Root cause

livekit-plugins/livekit-plugins-google/livekit/plugins/google/realtime/realtime_api.py (currently on main, around lines 1305–1321):

def _handle_tool_calls(self, tool_call: types.LiveServerToolCall) -> None:
    if not self._current_generation:
        logger.warning("received tool call but no active generation.")
        return

    gen = self._current_generation
    for fnc_call in tool_call.function_calls or []:
        arguments = json.dumps(fnc_call.args)
        gen.function_ch.send_nowait(
            llm.FunctionCall(
                call_id=fnc_call.id or utils.shortuuid("fnc-call-"),
                name=fnc_call.name,
                arguments=arguments,
            )
        )
    self._mark_current_generation_done()   # ← closes audio_ch before
                                           #   Gemini has flushed audio

_mark_current_generation_done() (lines 1246+) closes audio_ch, which makes the framework treat the speech as done.

The canonical "turn done" signal that is post-audio (server_content.turn_complete, already handled at lines ~1243–1244) is not sent by Gemini Live when the tool call is itself the turn-terminator — semantically the turn is awaiting a toolResponse. So simply removing the synchronous close hangs the tool dispatch indefinitely (see "Why the fix isn't just to remove that line" below).

Why the fix isn't just to remove that line

Removing line 1321 alone produces the right audio behaviour but no generation close ever fires: audio_ch stays open, wait_for_playout() blocks forever for tool-terminated turns. In a 30 s harness ceiling test this manifests as a 30 s WAV with 28+ s of trailing silence.

We need a deferred close that observes when audio has actually drained.

Proposed fix

Replace the synchronous _mark_current_generation_done() in _handle_tool_calls with a fire-and-forget task that closes the generation once audio_ch has been quiescent (no new audio frames pushed) for a small window — defaulting to 0.5 s. The variable is the per-chunk gap (~20 ms in Gemini Live), not total speech length, so this is robust to variable utterance durations.

def _handle_tool_calls(self, tool_call: types.LiveServerToolCall) -> None:
    if not self._current_generation:
        logger.warning("received tool call but no active generation.")
        return

    gen = self._current_generation
    for fnc_call in tool_call.function_calls or []:
        arguments = json.dumps(fnc_call.args)
        gen.function_ch.send_nowait(
            llm.FunctionCall(
                call_id=fnc_call.id or utils.shortuuid("fnc-call-"),
                name=fnc_call.name,
                arguments=arguments,
            )
        )
    asyncio.create_task(self._close_after_audio_drain(gen))


async def _close_after_audio_drain(
    self,
    gen,
    quiescence_s: float = 0.5,
    max_drain_s: float = 5.0,
) -> None:
    started = time.monotonic()
    last_seen = getattr(gen, "_last_audio_frame_at", time.monotonic())
    while True:
        if getattr(gen, "_done", False):
            return
        if time.monotonic() - started > max_drain_s:
            break
        await asyncio.sleep(quiescence_s)
        current = getattr(gen, "_last_audio_frame_at", last_seen)
        if current == last_seen:
            break
        last_seen = current
    self._mark_current_generation_done()

This requires the audio-push site (around line 1189, inside _handle_server_content) to stamp gen._last_audio_frame_at = time.monotonic() whenever it pushes a frame.

_mark_current_generation_done() is already idempotent (line 1226-1227 short-circuits when gen._done is True), so the deferred close composes safely with the other call sites (session teardown at line ~1053, turn_complete at ~1243).

Validation

Harness numbers with the fix applied (same setup as the table above):

Run wait_for_playout returned in WAV duration Trailing silence Effective speech end
Gemini patched (text-driven) 1.47 s 2.99 s 0.26 s 2.73 s
Gemini patched (audio-driven, q=0.5) 2.01 s ~4.6 s ~0.3 s 4.28 s
Gemini patched (audio-driven, q=1.0) 2.01 s 5.48 s 1.20 s 4.28 s

Effective speech end is invariant under different quiescence values (4.24–4.28 s) — confirming the recovered audio is real, not an artefact of the wait. Trailing silence scales with quiescence_s as expected.

Environment

  • livekit-agents==1.5.8
  • livekit-plugins-google==1.5.8
  • Bug also confirmed by code inspection on main (file path livekit-plugins/livekit-plugins-google/livekit/plugins/google/realtime/realtime_api.py, lines 1305–1321).
  • Model: gemini-3.1-flash-live-preview (Gemini API key, not Vertex).
  • Plugin warning seen in trace: received server content but no active generation. (line ~1166), consistent with audio frames arriving after audio_ch was closed.

Related

  • #2432 / #2439 — transcript-not-finalised, fixed via a different code path on the now-removed beta/realtime/. Audio truncation is a separate symptom of the same upstream close site and remains unfixed.

joneriktalvio avatar May 15 '26 09:05 joneriktalvio

can you share a reproducible example? I tested with gemini realtime in this example and the goodbye audio was played out correctly.

I saw something similar that the goodbye message was missing when using gemini, but it was the model didn't generate audio back after the tool call at that time, https://github.com/livekit/agents/pull/4563#issuecomment-3784152373

longcw avatar May 15 '26 09:05 longcw

can you share a reproducible example? I tested with gemini realtime in this example and the goodbye audio was played out correctly.

I saw something similar that the goodbye message was missing when using gemini, but it was the model didn't generate audio back after the tool call at that time, #4563 (comment)

I think that example avoids the failing path: EndCallTool tells the model not to speak when calling the tool, then plays a separate tool-reply goodbye before shutdown.

The repro here is audio chunks -> toolCall -> trailing audio chunks. Current _handle_tool_calls() closes audio_ch at toolCall, so trailing Gemini audio can be dropped.

I have a small regression test for that ordering and can open a PR.

Anrahya avatar Jul 01 '26 15:07 Anrahya

@Anrahya do you see the case from gemini realtime it emits a tool call with audio in the same turn? self._mark_current_generation_done() is called once it's a tool call because we expect this generation only contains a tool call.

longcw avatar Jul 03 '26 09:07 longcw

@longcw Ye, i reran this against gemini-3.1-flash-live-preview with response_modalities=["AUDIO"] and an end_call tool.

I can reproduce same-turn mixed output on 3.1: audio chunks are emitted before toolCall=end_call in the same turn. I could not reproduce the stricter audio -> toolCall -> audio ordering on 3.1 in fresh runs.

For completeness, I did reproduce audio -> toolCall -> audio on the Gemini Live 2.5 native-audio model, but I think the 3.1 evidence should be the main point here.

Anrahya avatar Jul 03 '26 15:07 Anrahya

@Anrahya can you share an example or logs, and are you sure it's the same generation instead of multiple generation and one is the tool call the others are audio?

longcw avatar Jul 04 '26 03:07 longcw

@longcw mb, I should have included the logs earlier.

Here is a sanitized log from a direct Live API probe.

Config:

  • model: gemini-3.1-flash-live-preview
  • response_modalities=["AUDIO"]
  • one tool: end_call
  • one send_realtime_input(...), then one session.receive() stream

Observed event order:

TRIAL 3: tool=True real_audio_before_tool=True generation_or_turn_complete_before_tool=False

1.175s response_fields server_content
1.412s audio bytes=2
1.413s audio bytes=2400
1.471s audio bytes=7680
1.531s audio bytes=9600
...
5.843s audio bytes=15360
5.929s audio bytes=15360
5.968s tool_call end_call
5.968s response_fields tool_call
8.170s receive_timeout

There was no generation_complete or turn_complete before the tool_call.

The timeout after the tool call is expected here because the probe intentionally did not send a tool response; I was only checking event ordering before/at the tool call.

In LiveKit terms, _is_new_generation(response) would start the generation on the first server content/audio event, and since the generation is not complete before the tool call, the tool call belongs to that same generation. The old code then marks that generation done synchronously at the tool call.

Anrahya avatar Jul 04 '26 17:07 Anrahya

This is a classic expected-vs-actual + fan-out failure in a realtime control plane.

Closing audio_ch on toolCall assumes the tool message is a hard turn boundary. Gemini Live can emit toolCall before the final serverContent.modelTurn audio chunks, so the speech handle resolves _done_fut while audio is still in flight — wait_for_playout() becomes a no-op and trailing audio is dropped.

Reliability checklist for this shape:

  1. Fan-out control — treat tool-call and model-audio as concurrent legs of one generation, not serial phases; cap/await both before terminal close.
  2. Observable long jobs — generation state machine should expose audio_open | tool_pending | flushing | terminal so premature close is visible in metrics.
  3. Expected vs actual — only mark speech done after durable "no more audio for generation_id=X" (or explicit flush sentinel), not on toolCall alone.
  4. Policy before action — gate channel close on a provider-specific completion contract, not a generic "tool arrived" event.

Invalidation: if Gemini documents toolCall as strictly end-of-audio, this is a provider bug; if not, the premature close is local.

Architecture only — no product pitch.

IgorGanapolsky avatar Jul 24 '26 17:07 IgorGanapolsky

Linking #7151 here, which has a detailed root-cause write-up for this issue.

davidzhao avatar Oct 10 '26 21:10 davidzhao

I opened #8376 for the crash in #7151, which @davidzhao linked above as the root cause.

  • The problem: when one Gemini message carries both turn_complete and a tool_call, the generation's function_ch closes before the call is delivered. The receive task then raises ChanClosed and the session reconnects, so the call is lost.
  • The fix: it follows @longcw's suggestion on #7164. The receive loop finalizes the generation once, after both handlers.
  • Credit: #7164 (@noooooooookro) and #6285 (@Anrahya).

real _recv_task with a fake Gemini stream: main vs #8376, plus mutation runs

Version end_call reaches function_stream Receive task
main no, the call is lost ChanClosed, then a reconnect
#8376 yes no error

Still open: audio that Gemini sends in a later message after a tool call. I left this alone on purpose. The framework sends tool output only after the generation closes. If Gemini waits for that output before it ends the turn with BLOCKING tools, which #6285's timed drain suggests but I haven't confirmed live, keeping the generation open would stall every tool call. @joneriktalvio, if you still see trailing audio cut off after a tool call, a LK_GOOGLE_DEBUG=1 log of that turn would show whether the audio arrives in the same message as the tool call or after it.

flowchart TD
    A[LiveServerMessage] --> B{response.server_content present?}
    B -->|yes| C[_handle_server_content - no self-finalize]
    B -->|no| D
    C --> D{response.tool_call present?}
    D -->|yes| E[_handle_tool_calls - no self-finalize]
    D -->|no| F
    E --> F{server_content.turn_complete OR tool_call present?}
    F -->|yes| G[_mark_current_generation_done - exactly once]
    F -->|no| H[generation stays open]
    G --> I[function_ch / message_ch / text_ch / audio_ch closed]
sequenceDiagram
    participant Gemini
    participant RecvTask as _recv_task
    participant SC as _handle_server_content
    participant TC as _handle_tool_calls
    participant Gen as generation channels
    participant AA as AgentActivity

    Gemini->>RecvTask: LiveServerMessage(server_content(turn_complete=True), tool_call)
    alt base c2b2f5cbd6 (bug #7151)
        RecvTask->>SC: handle server_content
        SC->>Gen: _mark_current_generation_done() closes function_ch
        RecvTask->>TC: handle tool_call
        TC->>Gen: function_ch.send_nowait(call)
        Gen-->>TC: ChanClosed - recv task crashes, call lost, reconnect forced
    else R1 fix (this commit)
        RecvTask->>SC: handle server_content, no finalize
        RecvTask->>TC: handle tool_call, no finalize
        TC->>Gen: function_ch.send_nowait(call) - ok, channel still open
        RecvTask->>Gen: _mark_current_generation_done() once, after both handlers
        Gen->>AA: all 4 channels close cleanly; call delivered; AgentActivity awaits exe_task, sends tool output via update_chat_ctx
    end

himanshumehta avatar Nov 04 '26 09:11 himanshumehta