Repository navigation
fix(realtime)!: send the Gemini Live setup at the first content so session.update settings apply - #39864
Conversation
…o session.update modalities apply Gemini and Vertex AI Live accept exactly one setup per session, and the proxy sent its default audio setup at connect, so a client's session.update (GA output_modalities or beta modalities) was dropped and every answer came back as audio. The setup now goes out on the client's first message: a session.update becomes that setup, anything else gets the model default. Bedrock Nova Sonic keeps its connect-time setup through a provider hook. Text setups label deltas response.output_text.delta, and downgrading TEXT to AUDIO on an audio-only model logs a warning
[High impact] The current changes appear safe to merge, with no outstanding correctness or repository-rule finding identified. SummaryThis PR delays Gemini and Vertex Live setup until initial content so preceding
Reviews (14) · Last reviewed commit: "fix(realtime): take the lazy setup clock..." · Reviewed by Greptile |
Merging this PR will not alter performance
Performance Changes
Comparing |
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
…nf" token limit in the setup
…nt frame into the Gemini Live setup Gemini and Vertex Live accept one setup per connection, so the bridge used to turn only the first session.update into that setup and drop the rest without telling the client. Now every session.update that arrives before the first content frame is held, deep-merged (later values win per field), acknowledged with a session.updated built from the setup it would produce, and the merged session becomes the one setup sent with the first conversation item, audio frame, or tool result. The session events also surface the systemInstruction text as instructions, which the old string check never matched because the setup carries it as a Content object.
…tector accepts it _merge_session_fields recurses once per nested mapping level, so CI's recursive_detector flagged it. Bound the descent at eight levels (the OpenAI session object nests four deep at most), replace anything deeper wholesale with the later session.update's value, and list the helper with the other depth-capped functions the detector allows.
…e cannot produce A bare string output_modalities is read as a one-element list and modality values Gemini Live cannot produce are dropped with a warning instead of reaching the backend, so a malformed session.update no longer costs the session. Transcription guardrails now fold their VAD disable into the first held session.update only, so the merged setup carries it exactly once.
…/litellm into litellm_lit_6974_gemini_live_lazy_setup
|
bugbot run |
|
Thanks for this fix — I believe we're hitting the behaviour it describes, and would like to confirm which release contains it. Reproduced on gemini/gemini-3.8-live, gemini/gemini-3.1-flash-live-preview and vertex_ai/gemini-live-2.5-flash-native-audio. Repro: connect to /v1/realtime?model=gemini/gemini-3.1-flash-live-preview, send session.update with instructions: "You are a pirate. Always begin with ARRR." as the client's first message, then conversation.item.create + response.create. Gemini replies as a generic assistant; the same sequence on gpt-realtime-mini replies "ARRR…". Same result via raw websockets and the OpenAI SDK. Questions:
Separately: would you accept a PR adding context_window_compression to the Gemini realtime supported params? It's currently dropped silently. Happy to submit it in the same shape as #41408. |
…ni_live_lazy_setup # Conflicts: # litellm/litellm_core_utils/realtime_streaming.py # litellm/llms/custom_httpx/llm_http_handler.py
…p outage spend rows, share the playground session config The Live voice gate now judges the Gemini voice an OpenAI TTS name maps to, so fable and onyx reach Vertex as Umbriel and Orus again. An upstream close before the held setup was sent is logged as a session, not a refusal. The playground sends one server_vad session config for typed and voice turns, and the e2e, integration, and dashboard tests follow lazy setup.
… run on a stepped clock The deadline and grace tests waited on real 50 ms timers, and the merge cost check compared wall-clock runs. The session now reads an injected clock, time.monotonic by default, the two tests step it, and the merge cost check moves to the CodSpeed benchmarks. The Nova Sonic style handler test passes the backend through wrap_backend, which main added after the test was written
|
bugbot run |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 9eb50c9. Configure here.
BerriAI#39864 holds client content until the first setup and sends it right after the setup; Gemini Live still drops what reaches it before setupComplete, so that content now waits with the other pending frames. The barge-in speech_started is emitted once per open response, ahead of the close events BerriAI#39864 added, and the manual-activity activityEnd counts as the generation request.
… covers Since BerriAI#39864 the Gemini Live setup goes out with the first content, and a client that sends session.update, an item and response.create back to back is answered 20 times out of 20 against Vertex eu (gemini-3.8-live) on main. The explicit response.create of the transcription-guardrail test now hands the floor to the model, per the response.create fix of this branch.
…etes Since BerriAI#39864 the setup goes out with the first content and the content follows right away. An audio setup completes fast enough, but a Live Avatar (video) setup does not: Gemini answers the first item with the text "Error: Session is not set up yet" and drops it. Every client frame except the session.update that triggers the setup, held content included, now waits for setupComplete.
Gemini and Vertex Live sessions on
/v1/realtimedropped the client'ssession.update, since the proxy sent its own audio setup at connect and Gemini takes only one. Text clients got audio, and instructions and tools never reached the modelNow the setup goes out with the first content, built from every
session.updatebefore it. What Gemini can't apply gets anerrorevent unlessdrop_paramsis onOriginal
TLDR
Problem this solves:
session.updatenever reach the modelHow it solves it:
session.updateframes merge in and get ackederroreventFull TLDR
Problem this solves:
session.updateis dropped with only a debug logoutput_modalitiesand betamodalitiesshapes are lost, along with instructions, tools, and VAD settingsturn_detectionwithcreate_response: false, orturn_detection: null) never gets an answer, since Gemini needs explicit activity markers when automatic detection is offHow it solves it:
session.updatesent before it, each acknowledged withsession.updatedsession.updateis held, the first messages and input audio wait forresponse.create, any other event, or 1 second, so an update sent between them, like the one Pipecat sends before its firstresponse.create, joins the setupconversation.item.create,response.create, and input audio) sends the setup, so a control event likeresponse.cancelsent first leaves it open for the nextsession.updatepre_callguardrail that blocks the first typed message sends the setup first, so the session stays openactivityStartandactivityEndmessages, andresponse.createcloses an open turn.turn_detection: nullturns Gemini's automatic activity detection off on AI Studio and Vertexrealtime_input_transcriptionguardrail on, Gemini audio input gets anaudio_input_not_screenableerror and is not sent, since Gemini only transcribes a turn after it starts answering it, so the guardrail could not check it first. Text turns still go through the guardrailsession.updateafter the first content getssession.updatedwhen it leaves the setup unchanged, like the resend Pipecat sends with each response. A changed one answers asession_update_not_appliederror unlessdrop_paramsis set, which drops itinvalid_request_errorevent unlessdrop_paramsis set, in which case the value is dropped. A text and audio pair collapses to the one the model can produceinvalid_valueerror event, or is dropped withdrop_params, on Vertex and AI Studio's native-audio models, since those close the socket with 1007 on a voice they do not know. AI Studio's 3.x Live models take any name, so it is forwarded therefabletoUmbrielandonyxtoOrus, pass the Live voice check as their Gemini voice{"type": "function", "name": ...}shape go through Gemini's schema conversion, so$defs,$ref, and nullable types workmax_output_tokens: "inf"is not forwarded, since Gemini closes the socket with 1007 on each of thosesession.updateframes past 10 MB answersession_update_too_largesession.update, with server VAD, at connect and when recording starts, so Gemini acks the second onegemini_live_defer_setup) merges held updates the same way, sends the default setup before content that comes first, and sends asession.updatethat follows buffered audio as the setup at oncebuilds_setup_from_session_update()returns False keep the connect-time setup, and Bedrock reuses the same rejection typeUser Flow
Before: a Vertex Gemini Live app asks for text answers with instructions, and both are ignored
wss://litellm-domain/v1/realtime?model=vertex_ai/gemini-live-2.5-flashand getsession.createdsession.updatewithoutput_modalities: ["text"], instructions, and tools, and get nosession.updatedconversation.item.createandresponse.create, or push-to-talk audio and a commitresponse.output_audio.deltawithout the instructions, and push-to-talk audio gets no answerAfter: the same session acks the update, answers in text, and follows the instructions
wss://litellm-domain/v1/realtime?model=vertex_ai/gemini-live-2.5-flashand getsession.createdsession.updategetssession.updatedwithoutput_modalities: ["text"]conversation.item.createandresponse.create, or push-to-talk audio and a commitresponse.output_text.deltawith the instructions applied, and push-to-talk audio gets answeredRelevant issues
Fixes #46685
Related: #44825
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Last updated: 9eb50c9. QA ran on 6b58477. Changes since QA: an injectable lazy setup clock that defaults to
time.monotonic, plus tests. Proof and /live-pr-risk remain valid because no caller passes the clock. Verification: realtime unit tests,make check, affected unit testsBoth legs ran a
websocketsclient through/v1/realtimeon a 2-worker proxy against real Vertex AI, Gemini, and OpenAIaudio_input_not_screenableerrorinvalid_valueerrorinvalid_valueerrorsession_update_not_appliederrorinvalid_valueerror, answersinvalid_valueerrorsession_update_not_appliederrorinvalid_valueerror, answersAdmin UI playground cases
Each leg replays its own tree's
RealtimePlayground.tsxframes, a typed turn and then a recorded one, through this clientinvalid_valueerror, both answerShared setup
Both legs booted from this config.
gemini-live-2.5-flashis only served atglobaland the native-audio model only regionally, so the config pins eachEach case runs
rt_client.pywith these flags, and a case without--textasks "What color is the sky on a clear day? One word."The client connects to
/v1/realtime?model=...and sendssession.updatewith{"type": "realtime", "<field>": [...], "instructions": "Answer in at most five words."}, thenconversation.item.createwith the text andresponse.create. It prints the event types with repeat counts, everysession.*event's modalities, anyerrorevent, the transcript, and theresponse.doneusage.--fieldpicks the GAoutput_modalitiesor betamodalitieskey,--out bothasks for text and audio,--out text-stringsends the bare string"text",--out videoasks for a modality Gemini Live cannot produce,--extrasadds the SDK-style audio, tool, and token-limit fields,--max-tokens infsends the OpenAI SDK default,--order twosends an instructions-onlysession.updatebefore the full one,--order instrsends only the instructions,--order latesends the update after the message,--voicesets the output voice, and--wait-before-text Nwaits N seconds before the message.--ptt no-auto-responsesetsturn_detectionto server VAD withcreate_response: falseand the weather tool, streams--audio(a 24 kHz PCM clip of "What is the weather in Paris right now?" made with OpenAIgpt-4o-mini-tts) throughinput_audio_buffer.append, then sendsinput_audio_buffer.commitandresponse.create, and answers the tool call with a fixed forecastThe
defer*cases ran on a proxy booted withLITELLM_GEMINI_LIVE_DEFER_SETUP=true, and the rest without it.--order resendsendssession.update, then the item, the samesession.updateagain, andresponse.create, like Pipecat.--ptt manualsendsturn_detection: null, and--ptt autosends server VAD with the default auto-response.--order controlsendsresponse.cancelbeforesession.update,--order audiofirststreams the audio and commits beforesession.update, and--beta-headeraddsOpenAI-Beta: realtime=v1.--order pipecatsendssession.updatewithout the instructions and tools, then the item, the fullsession.update, andresponse.create, like Pipecat's first turn when its context comes aftersession.created.--order audiomidstreams the audio between the two updates and commits after the second.--ref-toolsends aget_weathertool whose parameters use$defs,$ref, and"type": ["string", "null"].pttGuardVertex's key carries thert-content-filterguardrailThe client, config, case table, and runner are in this gist
Before (c98641f)
gaText
output_modalities: ["text"]Spend log
Other cases
pttAudioVertex
pttGuardVertex
betaHeaderText
controlFirstVertex
pirate38AiStudio
pirateNativeVertex
guardBlockFirst
openaiGaText
betaText
nativeGaText
nativeDropParams
aiStudio38GaText
twoUpdates
guardTwoUpdates
lateUpdate
badVoiceVertex
gaBothExtras
gaInfTokens
gaTextString
gaVideo
idle70Vertex
idle310Vertex
pipecatResendVertex
pipecatResendNative
vNovaDropParams
pttManualVertex
deferTwoUpdates
deferResend
deferLateUpdate
deferControlFirst
deferAudioFirst
flatRefToolVertex
flatRefTool38AiStudio
pipecatFirstTurnVertex
pipecatFirstTurnNative
audioMidUpdateVertex
deferPipecatFirstTurn
badVoiceAiStudio
aiStudioNovaDropParams
nova38AiStudio
pgTextVoiceVertex
pgVoiceVertex
pgTextVoiceStudio
pgFableNativeVertex
pgOnyxNativeVertex
pgNovaNativeStudio
pgTextVoiceOpenAI
After (6b58477)
gaText
Spend log
Other cases
pttAudioVertex
pttGuardVertex
betaHeaderText
controlFirstVertex
pirate38AiStudio
pirateNativeVertex
guardBlockFirst
openaiGaText
betaText
nativeGaText
nativeDropParams
aiStudio38GaText
twoUpdates
guardTwoUpdates
lateUpdate
badVoiceVertex
gaBothExtras
gaInfTokens
gaTextString
gaVideo
idle70Vertex
idle310Vertex
pipecatResendVertex
pipecatResendNative
vNovaDropParams
pttManualVertex
deferTwoUpdates
deferResend
deferLateUpdate
deferControlFirst
deferAudioFirst
flatRefToolVertex
flatRefTool38AiStudio
pipecatFirstTurnVertex
pipecatFirstTurnNative
audioMidUpdateVertex
deferPipecatFirstTurn
badVoiceAiStudio
aiStudioNovaDropParams
nova38AiStudio
pgTextVoiceVertex
pgVoiceVertex
pgTextVoiceStudio
pgFableNativeVertex
pgOnyxNativeVertex
pgNovaNativeStudio
pgTextVoiceOpenAI
gemini-live-2.5-flashspend reads 0.0 on both legs, pre-existing/live-pr-risk at 6b58477
Breaking
Each was found at e9644a0 and fixed in 6b58477
session.updatewhen recording started, so on AI Studiogemini-3.8-livethe recorded turn gotsession_update_not_appliedand no answer (e9644a018c). It now sends one config for both turns, and both answer (pgTextVoiceStudio)fablegotinvalid_valueon Vertex native audio, though Gemini TTS maps it toUmbriel(e9644a018c), andonyxhit the same check. The Live voice check now maps OpenAI's TTS names first, and both are acked (pgFableNativeVertex,pgOnyxNativeVertex)Backward incompatible
session.updategetssession_update_not_applied, a modality the model cannot produce getsinvalid_value(f34e5aa), and an undocumented voice getsinvalid_value(58089df, ef52e61).drop_paramsdrops each one instead, per litellm's convention for a param the provider cannot take (mateo-berri)realtime_input_transcriptionguardrail refuses Gemini audio withaudio_input_not_screenable, where the session used to close with 1007. Fixed in ef52e61Regression risk
?intent=transcriptionon Gemini with a transcription guardrail now holds its setup too. No test or case drives it, and it needs a Gemini transcription clientinput_audio_buffer.clearwhile audio is held, and a held setup whose send fails, have no test. Each needs a client that sends that event, or an upstream that drops the socket mid-sendsession.updatehave no assertion. A logging callback on alateUpdaterun would show itlitellm_settings.drop_paramswas traced but not run. The cases set it on the deploymentDependency graph
pre_calland transcription guardrailsgemini_live_defer_setupmodelitellm._arealtimeintent=transcriptioninput_audio_buffer.clearwhile heldNot verified
Type
🐛 Bug Fix
Caveats (if any)
Medium
session.updateafter the setup errors withoutdrop_params, which Pipecat apps needdrop_params, text on a native-audio model rejects the whole updateLow
Low caveats
session.updatedechoes only the modalities, instructions, and model, under the betamodalitieskeysetupCompletenova, which Gemini native audio refuses withoutdrop_paramssession.updateis held reaches Gemini up to 1 s latersession.updateis ignored until a docs follow-upbuildkite/e2e-testsfails on every PR because its Buildkite queue is missing, and it is not requiredCaveat details
response.create(pipecatFirstTurnVertex,pipecatFirstTurnNative). A change after that, like Pipecat'sLLMSetToolsFrameadding tools mid-call or a context that arrives after the user's audio already sent the setup, getssession_update_not_applied. An unchanged resend getssession.updated(pipecatResendVertex). Withdrop_params: truethe change is dropped and the session keeps its setup. Pipecat 1.15.0 ends the session on anyerrorevent other than a cancel, so this error and theinvalid_valueerrors below stop a Pipecat call unlessdrop_paramsis onsession.update(nativeGaText), and it does the same for an unknown voice. Withdrop_params: trueonly the modality is dropped and the rest applies (nativeDropParams)realtime_input_transcriptionguardrail cannot check audio before the model answers it. Before this PR that audio closed the session with 1007 (pttGuardVertex). Text turns still go through the guardrailsession.updateis acked before Gemini has seen it. A wrong model name on Vertex now getssession.updatedand then anerrorwith a 1008 close at the first message, where before this PR it closed about 1 s after connect. Checking it at connect would mean sending the setup there, which is what dropped the client'ssession.updatesession.updatecomes after 4 minutes gets the default setup, then the late-update error. Vertex closes a socket with no setup at 300 s (idle310Vertex). A new env var needs its docs row first, and nobody asked for onesession.updatedbuilder that every provider shares, so widening it is a separate changeinvalid_valueerror. Withdrop_params: truethe voice is dropped (badVoiceVertex,vNovaDropParams,badVoiceAiStudio,aiStudioNovaDropParams). AI Studio'sgemini-3.8-liveaccepts any name, a made-up one included, so the voice is forwarded there unchecked (nova38AiStudio)novahas no Gemini match, so a native-audio model withoutdrop_paramsrefuses the update and runs on its default voice (pgNovaNativeStudio). Filtering the list per provider is a separate UI changesession.updateis held, the first content waits up to 1 s for a following update, andresponse.createor any other event sends it at once. In default mode input audio waits too, so an update that arrives while the user speaks joins the setup (audioMidUpdateVertex). Deferred mode sends the setup at once when audio is bufferedQueue 'litellm-e2e' does not exist, the same failure as another PR's build, before any test runsFinal Attestation
Bugbot summary