agents icon indicating copy to clipboard operation
agents copied to clipboard

generate_reply times out on first dialogue with gemini-3.1-flash-live-preview — works fine with gemini-2.5-flash-

Open acharan-tech-200037 opened this issue 8 months ago • 17 comments

Bug Description

When using gemini-3.1-flash-live-preview as the realtime model, the agent fails to generate the first reply immediately after joining the room. It times out waiting for the generation_created event. The exact same code with gemini-2.5-flash works without any issues.

Expected Behavior

Agent should generate and speak the first reply immediately after joining the room, same as it does with gemini-2.5-flash

Reproduction Steps

1.Create an AgentSession with google.realtime.RealtimeModel using model gemini-3.1-flash-live-preview
2.Start the session with session.start()
3.Call session.generate_reply() for the opening dialogue

Minimal Reproducible Example

from livekit import agents
from livekit.plugins import google, silero
from livekit.agents import AgentSession

@server.rtc_session(agent_name="my-agent")
async def my_agent(ctx: agents.JobContext):
    session = AgentSession(
        llm=google.realtime.RealtimeModel(
            model="gemini-3.1-flash-live-preview",  # ❌ fails
            voice="Puck",
        ),
        vad=silero.VAD.load(),
    )

    await session.start(ctx.room, participant=ctx.room.remote_participants)
    await session.generate_reply(
        instructions="Greet the user."
    )

Operating System

Windows11

Models Used

gemini-3.1-flash-live-preview

Package Versions

livekit-agents==1.5.1

Logs

ERROR… livekit.…ns.google  error in receive task: 1007 None.
                             Request contains an invalid argument.

websockets.exceptions.ConnectionClosedError:
  received 1007 (invalid frame payload data) Request contains an invalid argument.;
  then sent 1007 (invalid frame payload data) Request contains an invalid argument.

google.genai.errors.APIError: 1007 None. Request contains an invalid argument.

ERROR… livekit.agents  failed to generate a reply:
                        generate_reply timed out waiting for
                        generation_created event.

WARNI… livekit.…ns.google  received server content but no active generation.

acharan-tech-200037 avatar Mar 28 '26 19:03 acharan-tech-200037

Root cause analysis

Confirmed on livekit-plugins-google==1.5.1 + google-genai==1.68.0.

What's happening

RealtimeSession.generate_reply() (line 715-716 in realtime_api.py) uses LiveClientContent (i.e. send_client_content) to inject a placeholder "." user turn:

turns.append(types.Content(parts=[types.Part(text=".")], role="user"))
self._send_client_event(types.LiveClientContent(turns=turns, turn_complete=True))

Gemini 3.1 Flash Live rejects all send_client_content calls during a session with 1007 invalid argument. Per Google's migration guide, send_client_content is now only for seeding initial context history (with initial_history_in_client_content set). Text during conversation must use send_realtime_input.

Reproduction (minimal, no LiveKit needed)

import asyncio
from google.genai import Client, types

async def main():
    client = Client(api_key="YOUR_KEY")
    config = types.LiveConnectConfig(
        response_modalities=["AUDIO"],
        speech_config=types.SpeechConfig(
            voice_config=types.VoiceConfig(
                prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore")
            )
        ),
    )
    async with client.aio.live.connect(model="gemini-3.1-flash-live-preview", config=config) as session:
        # ❌ This fails with 1007:
        await session.send_client_content(
            turns=[types.Content(parts=[types.Part(text="Hello")], role="user")],
            turn_complete=True,
        )
        # ✅ This works:
        # await session.send_realtime_input(text="Hello")
        response = await asyncio.wait_for(session._receive(), timeout=5.0)
        print(response)

asyncio.run(main())

What needs to change in the plugin

generate_reply() should use LiveClientRealtimeInput(text=...) instead of LiveClientContent when connected to a 3.1+ model. The initial chat context seeding in _main_task (lines 820-825) may also need updating per the initial_history_in_client_content flag.

The monkey-patch in #5234 (comment by @smittie2000) works as a temporary workaround.

oEdyb avatar Mar 29 '26 13:03 oEdyb

generate_reply makes use of send_client_content to create a generation with specific model instructions.

it seems that 3.1 isn't supporting this mode very well.

davidzhao avatar Mar 30 '26 06:03 davidzhao

generate_reply() should use LiveClientRealtimeInput(text=...) instead of LiveClientContent

LiveClientRealtimeInput isn't the same thing. It represents input coming from the user, where as we need to add a piece of context that's coming from the assistant/model

davidzhao avatar Mar 30 '26 06:03 davidzhao

Additional issue: tool call cancellation + re-execution on Gemini 3.1

Beyond the send_client_content fix (see my earlier comment), there's a second incompatibility with gemini-3.1-flash-live-preview: synchronous tool calling races with audio input.

What happens

Gemini 3.1 only supports synchronous function calling — the model should block until tool responses arrive. But the plugin's _send_task continues forwarding microphone audio while tools execute. This causes:

  1. Server-side tool call cancellation: "server cancelled tool calls" warning after ~12s
  2. Duplicate tool execution: The model re-issues the same tool call after cancellation (e.g. remove_from_order with the same line_id that was already removed → ToolError)
  3. State confusion: The model loses track of what's already been executed, leading to extra turns and incorrect order state

Example from logs

13:28:04 executing tool: remove_from_order {"line_id": "00fab9b7"}
13:28:04 tools execution completed
13:28:04 executing tool: list_order {}
13:28:04 tools execution completed
        ... 12 seconds of silence while audio streams ...
13:28:16 WARN: server cancelled tool calls {"function_call_ids": ["fc_14613028103896941496"]}
13:28:18 executing tool: remove_from_order {"line_id": "00fab9b7"}  ← same ID, already removed
13:28:18 WARN: ToolError: Hittade ingen rad med ID 00fab9b7
13:28:18 executing tool: list_order {}  ← duplicate

Root cause

The plugin doesn't pause audio input during synchronous tool execution. On Gemini 2.5 (async tool calling), this was fine — the model could process audio and tool responses concurrently. On 3.1 (sync only), the incoming audio confuses the model into thinking the turn changed, which triggers tool cancellation and retry.

Suggested fix

When the model is gemini-3.1-* (sync tool calling), the plugin should:

  1. Stop forwarding LiveClientRealtimeInput(audio=...) while tool calls are pending
  2. Buffer audio frames and flush them after send_tool_response
  3. Handle tool_call_cancellation gracefully — don't re-execute already-completed tools

Workaround

Using the google.genai SDK directly (bypassing the plugin) with send_realtime_input(text=...) instead of audio works correctly — the model blocks on tool responses as expected. This is how we run our benchmarks (100% accuracy on ordering scenarios). The issue is specific to the plugin's concurrent audio + tool dispatch architecture.

Environment: livekit-plugins-google==1.5.1, google-genai==1.68.0, gemini-3.1-flash-live-preview

oEdyb avatar Mar 30 '26 11:03 oEdyb

I tried doing the (Workaround Using the google.genai SDK directly (bypassing the plugin) with send_realtime_input(text=...) instead of audio works correctly — the model blocks on tool responses as expected. This is how we run our benchmarks (100% accuracy on ordering scenarios). The issue is specific to the plugin's concurrent audio + tool dispatch architecture.

Environment: livekit-plugins-google==1.5.1, google-genai==1.68.0, gemini-3.1-flash-live-preview)

But couldnt figure it out

Incredible we have to read issues to make it work from the get-go

mauricio9657 avatar Mar 30 '26 15:03 mauricio9657

confirmed with gemini team that this is a temporary limitation with the model. they are working on improving the behavior on their side. in the next version we'll raise an explicit error in generate_reply to make the issue more clear

davidzhao avatar Mar 31 '26 06:03 davidzhao

Confirming same issue in production (voice agent use case)

Running into the exact same 1007 Request contains an invalid argument error with livekit-plugins-google==1.5.1 and gemini-3.1-flash-live-preview.

Our scenario: We use generate_reply() in the agent's on_enter() to deliver an opening greeting when the agent joins the LiveKit room. With Gemini 3.1, this consistently fails with the 1007 error and generate_reply timed out waiting for generation_created event.

Workaround observation: If the human participant speaks first (sending audio via the normal realtime input path), Gemini 3.1 responds correctly. Only generate_reply() is broken — the rest of the conversation works fine once initiated by the user.

Impact: For outbound-call use cases where the agent must speak first (e.g. appointment confirmations, proactive outreach), this is a blocker. We're keeping gemini-3.1-flash-live-preview and accepting the missing auto-greeting as a temporary degradation until this is resolved.

Environment:

  • livekit-agents==1.5.1
  • livekit-plugins-google==1.5.1
  • google-genai (latest)
  • Python 3.11, Debian 13 (container)

stavarc avatar Apr 04 '26 13:04 stavarc

Any updates on this issue? This is a big blocker for using this model with livekit

emulicus avatar May 02 '26 00:05 emulicus

any updates?

giacomoarienti avatar May 07 '26 14:05 giacomoarienti

any updates guys?

codaisa avatar May 15 '26 18:05 codaisa

Any update? This is a big blocker for using this model with livekit

Lol I forgot about livekit Is still not working???

On Thu, May 21, 2026, 3:15 AM Abhijeet Patki @.***> wrote:

patkiabhijeetapollohealthaxis left a comment (livekit/agents#5260) https://github.com/livekit/agents/issues/5260#issuecomment-4506151871

Any update? This is a big blocker for using this model with livekit

— Reply to this email directly, view it on GitHub https://github.com/livekit/agents/issues/5260#issuecomment-4506151871, or unsubscribe https://github.com/notifications/unsubscribe-auth/A3NBXHEW2IBCLPRPUHN2JPL4323LNAVCNFSM6AAAAACXDOQUFOVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHM2DKMBWGE2TCOBXGE . You are receiving this because you commented.Message ID: @.***>

mauricio9657 avatar May 21 '26 12:05 mauricio9657

this bug is not solved yet , still gemini 3.1 is not in sync with live kit even with update, i dont know how much time will they take before user finally migrating to different platform

gauthamiitj avatar May 28 '26 17:05 gauthamiitj

Hi @davidzhao, any estimate for timing of the Gemini-side fix (this month / quarter / no ETA)? Trying to decide whether to wait for 3.1 or ship a workaround. Pointer to an upstream Gemini issue works too if you can't share dates.

frankfarzan avatar Jun 04 '26 20:06 frankfarzan

Any update? This is a big blocker for using this model with livekit

git+https://github.com/charan632-dev/agents.git#subdirectory=livekit-plugins/livekit-plugins-google

while installing the google plugins , install from this , where changes were made in site-livekit/plugins/google/realtime/realtime_api.py

acharan-tech-200037 avatar Jun 08 '26 10:06 acharan-tech-200037

any updates guys?

git+https://github.com/charan632-dev/agents.git#subdirectory=livekit-plugins/livekit-plugins-google

while installing the google plugins , install from this , where changes were made in site-livekit/plugins/google/realtime/realtime_api.py

acharan-tech-200037 avatar Jun 08 '26 10:06 acharan-tech-200037

hi everyone, generate_reply now works with gemini-3.1 live in 1.8.2! please feel free to try it out and let us know any feedback you may have 🎉

tinalenguyen avatar Sep 16 '26 19:09 tinalenguyen