Repository navigation
fix(realtime): keep the reply in progress when the session reconnects #7907
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Rehansanjay
wants to merge
2
commits into
livekit:main
Choose a base branch
from
Rehansanjay:fix/realtime-reconnect-loses-partial-reply
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| """The reconnection replay has to carry what the model already said. | ||
|
|
||
| A response that finishes writes each message's transcript into its mirror item in | ||
| `_handle_response_done`. A connection that drops mid-reply never delivers that event, | ||
| so without a flush the item stays empty, the replay drops it, and the replayed | ||
| conversation ends on the user's request with nothing answering it. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
|
|
||
| import pytest | ||
|
|
||
| from livekit import rtc | ||
| from livekit.agents import llm, utils | ||
| from livekit.agents.llm import remote_chat_context | ||
| from livekit.agents.llm._realtime.openai import ( | ||
| RealtimeSession, | ||
| _MessageGeneration, | ||
| _ResponseGeneration, | ||
| ) | ||
|
|
||
| pytestmark = [pytest.mark.unit, pytest.mark.concurrent] | ||
|
|
||
| _PARTIAL = "The capital of France is Pa" | ||
|
|
||
|
|
||
| def _session_mid_reply(transcript: str = _PARTIAL) -> tuple[RealtimeSession, str]: | ||
| """A session whose model is part-way through a reply, as a dropped socket leaves it. | ||
|
|
||
| The user's request is in the mirror, and so is the assistant item the response | ||
| created -- with empty content, because only `response.done` fills it in. | ||
| """ | ||
| session = RealtimeSession.__new__(RealtimeSession) | ||
| session._remote_chat_ctx = remote_chat_context.RemoteChatContext() | ||
|
|
||
| user = llm.ChatMessage(role="user", content=["What is the capital of France?"]) | ||
| session._remote_chat_ctx.insert(None, user) | ||
| assistant = llm.ChatMessage(role="assistant", content=[]) | ||
| session._remote_chat_ctx.insert(user.id, assistant) | ||
|
|
||
| session._current_generation = _ResponseGeneration( | ||
| message_ch=utils.aio.Chan[llm.MessageGeneration](), | ||
| function_ch=utils.aio.Chan[llm.FunctionCall](), | ||
| messages={ | ||
| assistant.id: _MessageGeneration( | ||
| message_id=assistant.id, | ||
| text_ch=utils.aio.Chan[str](), | ||
| audio_ch=utils.aio.Chan[rtc.AudioFrame](), | ||
| modalities=asyncio.Future(), | ||
| audio_transcript=transcript, | ||
| ) | ||
| }, | ||
| _done_fut=asyncio.Future(), | ||
| _created_timestamp=0.0, | ||
| ) | ||
| return session, assistant.id | ||
|
|
||
|
|
||
| def _replayed(session: RealtimeSession) -> llm.ChatContext: | ||
| """Exactly the context _reconnect replays.""" | ||
| return session.chat_ctx.copy( | ||
| exclude_instructions=True, | ||
| exclude_empty_message=True, | ||
| exclude_handoff=True, | ||
| exclude_config_update=True, | ||
| ) | ||
|
|
||
|
|
||
| def test_replay_keeps_what_the_agent_already_said() -> None: | ||
| session, assistant_id = _session_mid_reply() | ||
|
|
||
| session._flush_generation_transcripts() | ||
|
|
||
| replayed = _replayed(session) | ||
| assert [item.id for item in replayed.items] == [replayed.items[0].id, assistant_id] | ||
| assert replayed.items[-1].role == "assistant" | ||
| assert replayed.items[-1].content == [_PARTIAL] | ||
|
|
||
|
|
||
| def test_a_retried_reconnection_does_not_duplicate_the_transcript() -> None: | ||
| """A reconnection whose sends fail restores the mirror and is retried. | ||
|
|
||
| The transcript is still on the generation, so a second flush must be a no-op | ||
| rather than appending the same text again. | ||
| """ | ||
| session, assistant_id = _session_mid_reply() | ||
|
|
||
| session._flush_generation_transcripts() | ||
| session._flush_generation_transcripts() | ||
|
|
||
| assert _replayed(session).items[-1].content == [_PARTIAL] |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Replayed reply includes unspoken words
If transcript deltas precede audio at disconnect,
_flush_generation_transcriptsreplays words the caller never heard. The next reply treats those words as already spoken.Learn more
Transcript deltas and audio deltas arrive in separate server events; audio handling buffers each independently. On a dropped connection, the last received transcript can describe audio that never arrived or played. The replay serializes that transcript as an assistant answer, although realtime playout has no corresponding audio to forward. The reverse ordering also leaves spoken audio with an empty transcript, which this flush skips entirely.
Example: The server sends transcript
The code is 1234but only sends audio forThe code isbefore disconnecting. The replay claims the assistant already said1234, so a follow-up can proceed without giving the caller the code.Recommended fix: Reconcile the replayed transcript with audio actually forwarded by the voice generation task, or preserve only the portion whose audio was confirmed delivered. Account for audio received before any transcript as well; do not treat the full accumulated transcript as proof of speech.
Was this helpful? React with 👍 or 👎 to provide feedback.