agents icon indicating copy to clipboard operation
agents copied to clipboard

Gemini Realtime EndCallTool not working

Open b4stien opened this issue 8 months ago • 8 comments

Bug Description

Hi,

I'm using Gemini Live Flash (exact model on Vertex AI: gemini-live-2.5-flash-native-audio) and trying to have the agent hang up when the call is finished. It works ~70% of the time but the process seems unreliable. It quasi-systematically (95% of the times) triggers the tool reply timed out, shutting down session warning, and some _SegmentSynchronizerImpl.playback_finished called before text/audio input is done (I'd say ~20% of the times, and in those cases the final audio message is truncated).

Expected Behavior

The agent says its Goodbye message, ends the call immediately, and there is no warning.

Reproduction Steps

import structlog
from livekit.agents import Agent, AgentServer, AgentSession
from livekit.agents.beta.tools import EndCallTool
from livekit.agents.job import JobContext
from livekit.plugins.google.realtime import RealtimeModel

from xxx import settings
from xxx import SYSTEM_INSTRUCTION, VOICE_NAME

logger = structlog.get_logger()

server = AgentServer()


class TheAgent(Agent):
    def __init__(self):
        super().__init__(
            instructions=SYSTEM_INSTRUCTION,
            tools=[
                EndCallTool(
                    extra_description="A utiliser UNIQUEMENT après avoir dit au revoir.",
                    delete_room=True,
                    end_instructions="Dis au revoir Ă  l'appelant.",
                ),
            ],
        )

    async def on_enter(self):
        await self.session.generate_reply()


@server.rtc_session(agent_name="the-agent")
async def entrypoint(ctx: JobContext):
    agent = TheAgent()
    session = AgentSession(
        llm=RealtimeModel(
            model="gemini-live-2.5-flash-native-audio",
            voice=VOICE_NAME,
            vertexai=True,
            project=settings.gcp_project_id,
            location=settings.gcp_location,
        ),
    )
    await session.start(agent=agent, room=ctx.room)


if __name__ == "__main__":
    from livekit.agents.cli import run_app

    run_app(server)

Operating System

macOS

Models Used

No response

Package Versions

↪ uv pip freeze | grep livekit
Using Python 3.13.9 environment at: XXX
livekit==1.1.2
livekit-agents==1.4.5
livekit-api==1.1.0
livekit-blingfire==1.1.0
livekit-plugins-google==1.4.5
livekit-protocol==1.1.2

Session/Room/Call IDs

No response

Proposed Solution


Additional Context

No response

Screenshots and Recordings

    16:41:16.671 INFO … livekit.agents     received job request
                                         {"job_id": "AJ_mux5Zsfnc5YM", "dispatch_id": "AD_TmUdoCVCBubq", "room": "call-_+3368863XXXX_DCar3yX6ZJhu", "room_id": "RM_ctw3iLophAHV", "agent_name": "onkol-agent",
"resuming": false, "enable_recording": false}
    16:41:16.701 DEBUG… livekit.agents     received assignment
                                         {"agent_name": "onkol-agent", "room_id": "RM_ctw3iLophAHV", "room": "call-_+3368863XXXX_DCar3yX6ZJhu", "job_id": "AJ_mux5Zsfnc5YM", "dispatch_id": "AD_TmUdoCVCBubq",
"enable_recording": false}
    16:41:16.703 WARNI… livekit.agents     no warmed process available for job, waiting for one to be created {"job_id": "AJ_mux5Zsfnc5YM"}
    16:41:16.710 INFO … livekit.agents     initializing process {"pid": 62808}
    16:41:17.587 INFO … livekit.agents     process initialized {"pid": 62808, "elapsed_time": 0.88}
                 DEBUG… asyncio            Using selector: KqueueSelector {"pid": 62808}
    16:41:17.594 DEBUG… livekit.agents     input stream attached
                                         {"participant": null, "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"], "pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:17.604 DEBUG… livekit.…ns.google connecting to Gemini Realtime API... {"pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
                 DEBUG… google.a…._default Checking '' for explicit credentials as part of auth process... {"pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
                 DEBUG… google.a…._default Checking Cloud SDK credentials as part of auth process... {"pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:18.146 DEBUG… livekit.agents     using audio io: `RoomIO` -> `AgentSession` -> `TranscriptSynchronizer` -> `RoomIO` {"pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
                 DEBUG… livekit.agents     using transcript io: `AgentSession` -> `TranscriptSynchronizer` -> `RoomIO` {"pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:18.148 DEBUG… livekit.agents     start reading stream {"participant": "sip_+3368863XXXX", "source": "SOURCE_MICROPHONE", "pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:18.814 DEBUG… livekit.agents     aec warmup active, disabling interruptions for 3.00s {"pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:21.814 DEBUG… livekit.agents     aec warmup expired, re-enabling interruptions {"pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:28.696 DEBUG… livekit.agents     executing tool
                                         {"function": "end_call", "arguments": "{}", "speech_id": "speech_153b2a5961d2", "pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:28.698 DEBUG… livekit.agents     end_call tool called {"pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:28.699 DEBUG… livekit.agents     tools execution completed {"speech_id": "speech_153b2a5961d2", "pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:28.808 WARNI… livekit.agents     _SegmentSynchronizerImpl.playback_finished called before text/audio input is done
                                         {"text_done": false, "audio_done": true, "pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:33.727 WARNI… livekit.agents     tool reply timed out, shutting down session {"pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:33.728 DEBUG… livekit.agents     input stream detached
                                         {"participant": "sip_+3368863XXXX", "source": "SOURCE_MICROPHONE", "accepted_sources": ["SOURCE_MICROPHONE"], "pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id":
"RM_ctw3iLophAHV"}
                 DEBUG… livekit.…ns.google send task finished. {"pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:33.753 DEBUG… livekit.agents     stream closed {"participant": "sip_+3368863XXXX", "source": "SOURCE_MICROPHONE", "pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:33.754 DEBUG… livekit.agents     session closed {"reason": "user_initiated", "error": null, "pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:33.756 INFO … livekit.agents     process exiting {"reason": "user_initiated", "pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
                 DEBUG… livekit.agents     shutting down job task {"reason": "user_initiated", "user_initiated": true, "pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:33.786 INFO … livekit.agents     deleting the room because the user ended the call {"pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
                 DEBUG… livekit.agents     http_session(): creating a new httpclient ctx {"pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}
    16:41:34.401 DEBUG… livekit.agents     http_session(): closing the httpclient ctx {"pid": 62808, "job_id": "AJ_mux5Zsfnc5YM", "room_id": "RM_ctw3iLophAHV"}

b4stien avatar Mar 12 '26 15:03 b4stien

it looks like an issue of the model, that it didn't generate a response to the tool output. It works as expected when testing with gemini-2.5-flash-native-audio-preview-12-2025 without Vertex.

if you want to use vertex model with this tool, maybe use session.say to generate a goodbye message with an tts

        async def on_tool_completed(ev):
            ev.ctx.session.say("Thank you for calling, goodbye!")

        EndCallTool(
            on_tool_completed=on_tool_completed,
            end_instructions=None,
            ...
        )

longcw avatar Mar 13 '26 02:03 longcw

it looks like an issue of the model, that it didn't generate a response to the tool output.

Do you know how I can diagnose this further?

(In the meantime I'll try to log more things to analyze the model output, and compare it with the one without Vertex)

b4stien avatar Mar 13 '26 08:03 b4stien

you can enable the debugging logs for the google realtime plugin with LK_GOOGLE_DEBUG=1 python agent.py dev, it logs the raw events between the api.

longcw avatar Mar 13 '26 08:03 longcw

After further investigation: yes it might be an issue with the model, especially around following instructions, but it's pretty hard (and unreliable) to have it respect them 100%.

Gist of the issue is that, for the LiveKit EndCallTool to work properly, the model should follow those exact steps:

  • Call the tool without saying anything.
  • Receive the tool output with instruction about what to say.
  • Say the words.
  • (And LiveKit detect end of the audio following the tool call, thus end of the "goodbye" audio, and closes the call)

The problem is that the model might want to say something before/while calling the tool:

  1. If it speaks before and call the tool at the end we have the full audio but have to wait 5s for the tool's timeout.
  2. If it interleaves the tool call with the audio (like [audio, audio, audio, tool_call, audio, done]) it generates a glitch where the audio is truncated (and we have the _SegmentSynchronizerImpl.playback_finished warning) and then the tool timeout (with the other warning).

Do you have an idea of how to progress? Iter on the prompt until it better follows the instructions?

b4stien avatar Mar 13 '26 09:03 b4stien

Any Suggested fix?? , because this issue still exist , in my case while calling the tool it is emitting audio and when tool response arrives it gets blank.

namanlegitbytes avatar Jun 16 '26 11:06 namanlegitbytes

also having the same issue. it seems a problem with the model as it tries to take the shorter path by saying the message at the same time while doing the tool call ( even if instructed to not do this at the system prompt), but is there a way to make it work ?

AyoubSelmi avatar Jun 19 '26 02:06 AyoubSelmi

Adding a related finding in the same function, since the discussion so far has focused on the 5s wait_for timing out — there is a second await in _delayed_session_shutdown that has no timeout at all, and it fails worse when it triggers.

livekit-agents/livekit/agents/beta/tools/end_call.py (unchanged on main as of today, verified against 1.7.1):

try:
    speech_handle = await asyncio.wait_for(speech_created_fut, timeout=5.0)   # guarded
    await speech_handle                                                       # unguarded
except asyncio.TimeoutError:
    logger.warning("tool reply timed out, shutting down session")
finally:
    ctx.session.off("speech_created", _on_speech_created)
    ctx.session.shutdown()

The 5s timeout guards only waiting for speech_created to fire. Once it fires, await speech_handle waits indefinitely for that speech to complete. except asyncio.TimeoutError cannot catch anything from that second await, so if the handle never resolves the coroutine parks there forever and the finally never runs — meaning ctx.session.shutdown() is never called.

The knock-on matters for anyone using delete_room=True: room deletion is registered in _on_session_close, which only runs on session close. No session shutdown means no job_ctx.shutdown(), no shutdown callback, and the room survives to the server's empty timeout with the SIP leg still connected and billing.

So the two paths through this function are asymmetric:

  • speech_created never fires → warn after 5s, shut down cleanly (what this thread has been seeing)
  • speech_created fires but the handle never completes → hang silently, never shut down

The asymmetry between the two awaits reads like an oversight rather than intent, given the first one was explicitly bounded. A wait_for around the second, with the except widened to cover both, would make the failure mode uniform.

Two caveats on the above, stated plainly. I found this by reading the code, not by observing a hang in production — we run OpenAI realtime, which reports auto_tool_reply_generation=False and takes the direct ctx.session.shutdown() branch in _on_speech_done, so _delayed_session_shutdown never executes for us. This path is reachable only for models reporting True, which today is the Google realtime plugin (plugins/google/realtime/realtime_api.py). That matches the fact that every report in this thread is Gemini.

Second, a question rather than a claim, aimed at @b4stien's interleaved case ([audio, audio, audio, tool_call, audio, done]): _on_speech_created resolves on the first speech_created after registration, with nothing checking that it is the tool reply. If a generation in that shape emits a speech_created for audio that is not the farewell, the shutdown would be waiting on the wrong handle — which would produce both a truncated goodbye and a spurious timeout, i.e. exactly the pair of symptoms described. I have not verified that Gemini emits a second speech_created in that case, so treat it as a hypothesis worth checking rather than a diagnosis.

killerminion96 avatar Sep 02 '26 06:09 killerminion96

Hi — following up on the _delayed_session_shutdown analysis in this thread.

I’d like to take a focused fix for the unguarded second await only:

  • today speech_created is bounded with asyncio.wait_for(..., timeout=5.0), but await speech_handle is not
  • if that handle never completes, finally never runs and ctx.session.shutdown() is skipped (bad for delete_room=True / SIP cleanup)

Proposed change: wrap the speech-handle await in the same timeout (or one shared wait_for), keep the existing warning + shutdown path, and add a regression test for the hang case.

I would not try to “fix” Gemini model behavior or EndCallTool instruction following in this PR — just the timeout asymmetry so shutdown always happens.

If that scope looks right to maintainers, I’ll open a PR against current main. Happy to adjust if you’d rather see a different timeout shape first.

usmamalik345 avatar Sep 07 '26 13:09 usmamalik345