Gemini Live on Inference: dropped connections lose the reply in progress, and drops recur every ~15 minutes
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Aptitud para principiantes
- 25/100
- Tipo de issue
- Error
- Claridad
- Bastante claro
- Estado de actividad
- Activo
- Stack tecnológico
- python
- Área
- ai-infra-agents
Línea de trabajo
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.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
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
- 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.
- Google realtime sessions are recycled before Google's limit, for example with a shorter default for
google/models, or the gateway handles Google'sGoAwaywith 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
- Lenguaje dominante
- Python
- Estrellas
- 14.6k
- Forks
- 3.9k
- Merge medio
- 3 d 1 h
- PR fusionados (30 d)
- 173
Preparar el entorno
Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de livekit/agents
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
Los mantenedores suelen responder en 1 día
-
Assistant markup is stripped from chat history when expressive mode is offPosiblemente ocupada @ShivamSharma43 la tomó hace 8 días. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
Los mantenedores suelen responder en 1 día
-
docs: openai.LLM vs openai.responses.LLM for HTTP OpenAI-compat hostsQuizá libre de nuevo @AbarnaaSree la tomó hace 47 días y no hay ningún pull request abierto. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
livekit/agents#7022 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
DuplexRealtimeAdapter: transcript fragment for audio that is never sent anchors the next burst, shifting transcripts by one utterancePosiblemente ocupada @dyyfk la tomó hoy. Abierto
Dificultad 4/5 3-5 días Aptitud para principiantes 45/100
Los mantenedores suelen responder en 1 día
-
google: support Live Avatar video output for Gemini 3.8 Live (avatar_config, VIDEO modality)Posiblemente ocupada @percusser la tomó hoy. Abierto
Dificultad 5/5 Más de una semana Aptitud para principiantes 22/100
livekit/agents#7843 · 1 comentario ·
Los mantenedores suelen responder en 1 día
Todos los issues de livekit/agents
Issues similares
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 75/100
common-workflow-language/cwl-utils#477 ·
Los mantenedores suelen responder en 1 día
-
Add dependabotAbiertofeat
Dificultad 2/5 Menos de una hora Aptitud para principiantes 72/100
open-nudge/opentemplate#204 ·
Los mantenedores suelen responder en 1 día
-
github-stale-ci-pr-closer: KV state is double-wrapped, never persists, and hits the depth-32 limitPosiblemente ocupada @VascoSch92 la tomó hoy. Abiertopriority:medium ready-for-dev
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
OpenHands/extensions#781 ·
Los mantenedores suelen responder en 1 día
-
bug good first issue
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
curriculum documentation quality
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
githubnext/gh-aw-workshop#4638 ·
Los mantenedores suelen responder en 1 día