Hacktoberfest 2026: le issue che i maintainer hanno segnato per ottobre, aperte e adatte ai principianti. Sfoglia le issue Hacktoberfest

Gemini Live on Inference: dropped connections lose the reply in progress, and drops recur every ~15 minutes

Aperta
#7,867 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
25/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
python

Direzione di ricerca

Start with the reconnect path in RealtimeSession, where the replay is built from self.chat_ctx and the in-progress generation is dropped, then with DEFAULT_MAX_SESSION_DURATION in the inference.RealtimeModel setup. The issue's reproduction script shows the failure: after the websocket closes mid-reply, the replay has no assistant item and the next answer repeats the count. Done means that script's next answer matches the expected reply, and the recycle default for google/ models is settled. Both changes touch shared realtime code, so ask a maintainer about the intended design before writing a patch.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Bug Description

Two problems combine to derail Gemini Live sessions on LiveKit Inference about every 15 minutes.

1. A dropped connection loses the reply in progress, and the next turn answers the wrong thing. When the realtime websocket closes mid-reply, RealtimeSession reconnects and replays self.chat_ctx. The reply in progress is discarded and never added to the chat context, so the replay ends on the user's request with no answer. On the next turn the model answers that earlier request again instead of the new one. The user hears the agent stop mid-sentence, then answer the question before last.

2. The default recycle interval is longer than Google's session limit. inference.RealtimeModel defaults max_session_duration to 20 minutes (DEFAULT_MAX_SESSION_DURATION) for every provider. Gemini Live caps audio sessions at 15 minutes without context window compression (docs). In two 65-minute sessions on google/gemini-3.8-live, the gateway returned server_error / provider_error ("Internal error encountered.") roughly 15 minutes after each (re)connection, so the client hits problem 1 several times an hour:

  • Audio only: errors at 18.0, 33.4, and 48.8 minutes.
  • Audio and video: routine recycles at 20.0 and 54.3 minutes, and one error at 34.2 minutes (14 minutes after the recycle).

A routine recycle is clean, because it waits for the current generation to finish. Only the error path loses the reply.

Expected Behavior
  1. After an unexpected reconnect, the replayed context includes what the agent already said, as a truncated assistant message (like an interruption), so the conversation continues correctly.
  2. Google realtime sessions are recycled before Google's limit, for example with a shorter default for google/ models, or the gateway handles Google's GoAway with session resumption, so the limit never surfaces as an error.
Reproduction Steps
1. Set LIVEKIT_API_KEY and LIVEKIT_API_SECRET and run the script below. No room is needed.
2. The script closes the websocket after a few chunks of a long reply, as a provider error would, then asks a new question.

import asyncio, aiohttp
from livekit.agents import inference, llm

class Tracking(aiohttp.ClientSession):
    sockets = []
    async def _ws_connect(self, *a, **kw):
        ws = await super()._ws_connect(*a, **kw); Tracking.sockets.append(ws); return ws

async def reply(sess, text, drop_after=None):
    ctx = sess.chat_ctx.copy(); ctx.add_message(role="user", content=text)
    await sess.update_chat_ctx(ctx)
    gen, out = await sess.generate_reply(), []
    async for msg in gen.message_stream:
        async for d in msg.text_stream:
            out.append(str(d))
            if len(out) == drop_after:
                await Tracking.sockets[-1].close()
        async for _ in msg.audio_stream: pass
    print(f"> {text[:40]!r}\n< {''.join(out)[:70]!r}")

async def main():
    async with Tracking() as http:
        model = inference.RealtimeModel("google/gemini-3.8-live", modalities=["text"], http_session=http)
        sess = model.session()
        sent = []
        sess.on("openai_client_event_queued", lambda ev: sent.append(ev.get("item")) if isinstance(ev, dict)
                and ev.get("type") == "conversation.item.create" else None)
        sess.on("session_reconnected", lambda _: print("RECONNECTED, replaying:",
            [(i["role"], " ".join(c.get("text") or "" for c in i["content"])[:30]) for i in sent[2:]]))
        await sess.update_instructions("Follow the user's formatting requests exactly.")
        await reply(sess, "My dog is Biscuit, a 7 year old beagle. Say hi in one sentence.")
        await reply(sess, "Count from one to forty in words, one per line, then ask me a question.", drop_after=3)
        await asyncio.sleep(2)
        await reply(sess, "What is my dog's name, breed and age?")
        await sess.aclose(); await model.aclose()

asyncio.run(main())

Output (the same in every run):

> 'My dog is Biscuit, a 7 year old beagle. '
< 'Hello Biscuit, you lovely seven-year-old beagle!'
RECONNECTED, replaying: [('user', 'My dog is Biscuit, a 7 year ol'), ('assistant', 'Hello Biscuit, you lovely seve'), ('user', 'Count from one to forty in wor')]
> 'Count from one to forty in words, one pe'
< 'One\nTwo\nThree\nFour\nFive\nSix\nSeven\nEight\nNine\nTen\nEleven\nTwelve\nThirtee'
> "What is my dog's name, breed and age?"
< 'One\nTwo\nThree\nFour\nFive\nSix\nSeven\nEight\nNine\nTen\nEleven\nTwelve\nThirtee'

The replay has no assistant item for the cut-off reply, and the next question gets the count again instead of an answer.

For comparison, with max_session_duration=20 and the long reply spanning the recycle, the client waits for the reply to finish, reconnects, and the next answer is correct ("Your dog's name is Biscuit, he is a beagle, and he is 7 years old.").

Operating System

macOS 15

Models Used

LiveKit Inference: google/gemini-3.8-live (realtime, modalities=["text"])

Package Versions
livekit-agents==1.8.8
# also present on main (597e6b49)
Session/Room/Call IDs

No response

Proposed Solution
# 1. When a reconnect closes a generation that already produced text, add that text to the
#    chat context as a truncated assistant message before replaying, the same way an
#    interrupted reply is kept.
#
# 2. Default max_session_duration below Google's limit for google/ realtime models, e.g.:
#    max_session_duration = 12 * 60 if model.startswith("google/") else DEFAULT_MAX_SESSION_DURATION
#    or have the gateway handle Gemini's GoAway with session resumption.
Additional Context

The error reconnect itself is fast (about 0.1–0.4s), and memory of earlier turns survives it. The damage comes from the missing partial reply. Related: #7866.

Screenshots and Recordings

No response

Lingua principale
Python
Stelle
14.6k
Fork
3.9k
Merge medio
3g 1h
PR unite (30g)
173

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di livekit/agents

Tutte le issue di livekit/agents

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.