sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[FEATURE] BidiAgent: improve speech continuity during connection restarts

Open pgrayy opened this issue 2 months ago • 1 comments

SDK Language

Python

Problem Statement

A connection restart can split a spoken utterance. For example, a user starts speaking just before the assistant finishes, but the interruption signal has not arrived when the agent decides to reconnect. Audio already sent to the old connection may be absent from the restored conversation, leaving the new connection with only the rest of the sentence.

Track improved speech continuity as a follow-up to the existing reconnect support. The current response-boundary and transcript-history work will preserve existing restart behavior.

Proposed Solution

Evaluate a bounded microphone replay buffer and an explicit cutoff policy. The design and buffer sizes below are candidates, not established guarantees:

  • While reconnect is pending, continue forwarding input and retain a rolling lookback, initially testing two to three seconds. Allow interruptions to postpone the cutoff until a clean assistant completion, with a deadline for repeated interruptions.
  • At cutoff, block new sends and freeze the lookback. Preserve audio captured during reconnect after that prefix, rather than allowing the rolling buffer to overwrite it. Deliver retained audio in capture order before new sends can overtake it.
  • Explore shrinking the replay window for short exchanges to avoid replaying the completed question. One candidate is retaining only audio captured since the first observed assistant output, capped by the maximum lookback. Delayed events make this a heuristic that needs testing.
  • Account for sends already in progress, buffer overflow, and the difference between opening a fresh connection and resuming retained server-side state.

A replay window trades possible repetition for possible truncation. Measure capture-to-interruption-event delay rather than assuming a fixed provider cutoff or inferring timing from transcript length or generated audio duration.

Use Case

Maintain a natural voice conversation when the user speaks near a scheduled reconnect, including brief exchanges such as “yes” followed by “okay.” Avoid losing the beginning of the next utterance or making the model answer an already-completed question again.

Alternatives Solutions

An explicit reconnect announcement could make a forced pause understandable. However, sending text does not universally cancel active generation or finalize pending audio. The next completion may belong to previously submitted speech, and generation completion does not necessarily mean transcription or speaker playback has finished. Evaluate announcements or application-level notifications separately from any continuity guarantee.

Validation

  • [ ] Exercise speech immediately before and after assistant completion, delayed interruption signals, and overlapping input.
  • [ ] Check short exchanges for duplicate questions or responses after replay.
  • [ ] Cover reconnects longer than the replay window, input backpressure, and repeated interruptions requiring a hard cutoff.
  • [ ] Validate fresh connections and session resumption across Nova, Gemini Live, and OpenAI Realtime.
  • [ ] Document the selected policy and its remaining loss/repetition limitations.

Tool-use/result delivery across restart boundaries is separate work.

Additional Context

Parent epic: #1722. Related reconnect support: #3721. Related session segmentation: #3760.

The Nova session-continuation sample prepares another session and transfers history plus buffered microphone audio. Its three-second rolling buffer excludes audio before buffering begins and drops older chunks on overflow. An isolated test confirmed those behaviors and that the old session's user transcripts during transition are excluded from transferred history. This is a useful reference, not a guarantee of lossless handoff. We have not run a live handoff test of that sample or validated the proposed replay sizes.

pgrayy avatar Sep 22 '26 17:09 pgrayy

@pgrayy I'd like to work on this and wanted to check the shape with you first, since it touches the loop.

Reading loop.py, audio sent during a restart isn't lost: _restart_connection clears _send_gate, so send() waits and delivers to the new connection. What goes missing is audio already delivered to the old connection that hadn't been committed as a user turn when the swap happened. So the buffer would cover that window:

  • _BidiAgentLoop keeps a rolling lookback of audio deltas passed to send(), bounded by duration (default 2.5 s, configurable) and hard-capped in bytes.
  • It's cleared at a committed user-turn boundary: a user BidiTranscriptStopEvent, or BidiResponseStartEvent. Audio the provider has already turned into a user turn is never replayed.
  • After _swap_connection succeeds and before _send_gate.set(), the retained audio is replayed to the new connection, then live audio resumes behind the gate as today. Replay runs once per accepted swap, keyed to _generation, so a declined or superseded restart can't replay twice.
  • Cutoff: if the old connection already committed the turn (the buffer is empty), nothing is replayed. If the retained audio is older than the window, only the tail is sent.

Two questions: does this belong in the loop, or would you rather each provider own it (Nova Sonic, OpenAI, and Gemini may treat a replayed prefix differently)? And should it default on, or be opt-in behind a connection-config flag until it's been exercised against each provider?

sidxh avatar Sep 26 '26 20:09 sidxh