[Bugfix][Frontend] Preserve duplex chat audio format and duration (#7316)
Signed-off-by: Nolen Liang <nliang@nvidia.com>
This commit is contained in:
1 parent
1b6cd282f0
commit
e0c4f97f32
13 files changed
+684
-40
No files matched your search
@@ -6,6 +6,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import json
|
||||
from collections.abc import AsyncGenerator
|
||||
from functools import partial
|
||||
from typing import Any
|
||||
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
|
||||
@@ -115,6 +116,13 @@ class ChatFallbackProjectorMixin:
|
||||
):
|
||||
model_extra.pop(protocol_key, None)
|
||||
kwargs.update(model_extra)
|
||||
if "audio" in response_config.modalities:
|
||||
audio_options = kwargs.get("audio")
|
||||
audio_options = dict(audio_options) if isinstance(audio_options, dict) else {}
|
||||
# Chat defaults to WAV. Request the session's internal output format
|
||||
# explicitly rather than relabeling the returned bytes as PCM.
|
||||
audio_options["format"] = response_config.response_format
|
||||
kwargs["audio"] = audio_options
|
||||
if isinstance(tools, list):
|
||||
kwargs["tools"] = tools
|
||||
if isinstance(tool_choice, str | dict):
|
||||
@@ -190,6 +198,8 @@ class ChatFallbackProjectorMixin:
|
||||
response_id: str,
|
||||
send_json,
|
||||
) -> None:
|
||||
if session.epoch != epoch or session.active_response_id != response_id:
|
||||
return
|
||||
metrics = payload.get("metrics")
|
||||
stage_metrics = metrics.get("stage_metrics") if isinstance(metrics, dict) else None
|
||||
if isinstance(stage_metrics, dict):
|
||||
@@ -233,19 +243,7 @@ class ChatFallbackProjectorMixin:
|
||||
content = message.get("content")
|
||||
|
||||
if isinstance(content, str) and content:
|
||||
if modality == "audio":
|
||||
session.mark_audio_sent()
|
||||
await send_json(
|
||||
{
|
||||
"type": "response.output_audio.delta",
|
||||
"session_id": session.session_id,
|
||||
"response_id": response_id,
|
||||
"epoch": epoch,
|
||||
"audio": content,
|
||||
"format": session.response_config.response_format,
|
||||
}
|
||||
)
|
||||
else:
|
||||
if modality != "audio":
|
||||
session.append_assistant_text(content)
|
||||
await send_json(
|
||||
{
|
||||
@@ -257,6 +255,39 @@ class ChatFallbackProjectorMixin:
|
||||
}
|
||||
)
|
||||
|
||||
audio_content = content if modality == "audio" else None
|
||||
if isinstance(message, dict):
|
||||
message_audio = message.get("audio")
|
||||
if isinstance(message_audio, dict):
|
||||
audio_content = message_audio.get("data")
|
||||
if isinstance(audio_content, str) and audio_content:
|
||||
# The OpenAI package imports duplex serving during initialization.
|
||||
# Defer this import until chat fallback has finished loading.
|
||||
from vllm_omni.entrypoints.openai.protocol.audio import AudioChunkMetadata
|
||||
|
||||
audio_metadata = AudioChunkMetadata.model_validate(choice.get("audio_metadata"))
|
||||
duration_ms = session.record_generated_audio(
|
||||
response_id,
|
||||
frame_count=audio_metadata.frame_count,
|
||||
sample_rate_hz=audio_metadata.sample_rate_hz,
|
||||
)
|
||||
if duration_ms is None:
|
||||
return
|
||||
await send_json(
|
||||
{
|
||||
"type": "response.output_audio.delta",
|
||||
"session_id": session.session_id,
|
||||
"response_id": response_id,
|
||||
"epoch": epoch,
|
||||
"audio": audio_content,
|
||||
"format": audio_metadata.format,
|
||||
"sample_rate_hz": audio_metadata.sample_rate_hz,
|
||||
"channels": audio_metadata.channels,
|
||||
"audio_duration_ms": duration_ms,
|
||||
},
|
||||
on_accepted=partial(session.mark_audio_sent, duration_ms, response_id=response_id),
|
||||
)
|
||||
|
||||
finish_reason = choice.get("finish_reason")
|
||||
if finish_reason is not None and modality != "audio":
|
||||
await send_json(
|
||||
|
||||
@@ -178,6 +178,8 @@ class DuplexPlaybackCursor:
|
||||
sent_ms: int = 0
|
||||
played_ms: int = 0
|
||||
committed_ms: int = 0
|
||||
generated_frames: int = 0
|
||||
sample_rate_hz: int | None = None
|
||||
|
||||
def acknowledge(self, played_ms: int, committed_ms: int | None = None) -> None:
|
||||
self.played_ms = max(self.played_ms, max(0, int(played_ms)))
|
||||
@@ -1103,25 +1105,54 @@ class DuplexSession:
|
||||
if text:
|
||||
self._response.assistant_text_buffer.append(text)
|
||||
|
||||
def record_generated_audio(self, response_id: str, *, frame_count: int, sample_rate_hz: int) -> int | None:
|
||||
"""Accumulate source frames, rounding only the cumulative duration.
|
||||
|
||||
A late chunk cannot change a different response's playback cursor.
|
||||
This records encoded audio, not transport delivery or client playback.
|
||||
"""
|
||||
if response_id != self.active_response_id:
|
||||
return None
|
||||
if type(frame_count) is not int or frame_count < 0:
|
||||
raise ValueError("Audio frame_count must be a non-negative integer")
|
||||
if type(sample_rate_hz) is not int or sample_rate_hz <= 0:
|
||||
raise ValueError("Audio sample_rate_hz must be a positive integer")
|
||||
playback = self._playback.current
|
||||
if playback.sample_rate_hz is not None and playback.sample_rate_hz != sample_rate_hz:
|
||||
raise ValueError("Audio sample rate changed within a response")
|
||||
playback.sample_rate_hz = sample_rate_hz
|
||||
playback.generated_frames += frame_count
|
||||
playback.generated_ms = playback.generated_frames * 1000 // sample_rate_hz
|
||||
return playback.generated_ms
|
||||
|
||||
def mark_audio_sent(
|
||||
self,
|
||||
duration_ms: int | None = None,
|
||||
*,
|
||||
response_id: str | None = None,
|
||||
text_chars: int | None = None,
|
||||
audio_text_marks: list[dict[str, object]] | None = None,
|
||||
) -> None:
|
||||
playback = self._playback.current
|
||||
"""Record cumulative audio accepted by the output path.
|
||||
|
||||
``sent_ms`` includes queued/journaled output; only client acknowledgements
|
||||
establish ``played_ms``. It is not confirmation of socket delivery.
|
||||
"""
|
||||
playback = self._playback.current if response_id is None else self._playback.by_response.get(response_id)
|
||||
if playback is None:
|
||||
return
|
||||
is_current = response_id is None or response_id == self.active_response_id
|
||||
if duration_ms is not None:
|
||||
playback.generated_ms = max(playback.generated_ms, duration_ms)
|
||||
playback.sent_ms = max(playback.sent_ms, duration_ms)
|
||||
if text_chars is not None and text_chars >= 0:
|
||||
if is_current and text_chars is not None and text_chars >= 0:
|
||||
self._response.assistant_audio_text_marks.append(
|
||||
DuplexAssistantAudioTextMark(
|
||||
text_chars=int(text_chars),
|
||||
audio_end_ms=max(0, int(duration_ms)),
|
||||
)
|
||||
)
|
||||
if audio_text_marks:
|
||||
if is_current and audio_text_marks:
|
||||
for raw_mark in audio_text_marks:
|
||||
if not isinstance(raw_mark, dict):
|
||||
continue
|
||||
@@ -1135,7 +1166,8 @@ class DuplexSession:
|
||||
audio_end_ms=max(0, int(raw_audio_end_ms)),
|
||||
)
|
||||
)
|
||||
self.turn_state = DuplexTurnState.ASSISTANT_PLAYING
|
||||
if is_current:
|
||||
self.turn_state = DuplexTurnState.ASSISTANT_PLAYING
|
||||
|
||||
def _playback_cursor_for_response(self, response_id: str | None = None) -> DuplexPlaybackCursor:
|
||||
if response_id is None:
|
||||
|
||||
@@ -275,12 +275,18 @@ class DuplexSessionAttachmentRegistry:
|
||||
payload: Mapping[str, object],
|
||||
*,
|
||||
journal: bool = True,
|
||||
on_accepted: Callable[[], None] | None = None,
|
||||
) -> JournalEntry | None:
|
||||
"""Sequence and dispatch one event to the current attachment.
|
||||
|
||||
The per-session lock keeps wire order equal to journal order without
|
||||
serializing unrelated sessions. A detached session still records
|
||||
replayable events, but has no transport side effect.
|
||||
|
||||
``on_accepted`` runs synchronously once the event is journaled, or
|
||||
after a successful transport send when journaling is disabled. A later
|
||||
send failure cannot undo acceptance into the journal. Detached,
|
||||
non-journaled events do not invoke it. The callback must not raise.
|
||||
"""
|
||||
async with self._lock:
|
||||
state = self._require(session_id)
|
||||
@@ -291,8 +297,12 @@ class DuplexSessionAttachmentRegistry:
|
||||
entry = state.journal.record(payload) if journal else None
|
||||
attachment = state.attachment
|
||||
wire_payload = dict(entry.payload) if entry is not None else dict(payload)
|
||||
if entry is not None and on_accepted is not None:
|
||||
on_accepted()
|
||||
if attachment is not None:
|
||||
await attachment.send(wire_payload)
|
||||
if entry is None and on_accepted is not None:
|
||||
on_accepted()
|
||||
return entry
|
||||
|
||||
async def acknowledge(self, session_id: str, sequence: int) -> int:
|
||||
|
||||
@@ -7,6 +7,7 @@ import asyncio
|
||||
import binascii
|
||||
import json
|
||||
import uuid
|
||||
from collections.abc import Callable
|
||||
from contextlib import suppress
|
||||
from copy import deepcopy
|
||||
|
||||
@@ -99,7 +100,9 @@ class DuplexSessionRunnerMixin:
|
||||
if callable(close):
|
||||
await close(code=1000, reason=reason)
|
||||
|
||||
async def send_attachment_payload(payload: dict[str, object], *, journal: bool) -> None:
|
||||
async def send_attachment_payload(
|
||||
payload: dict[str, object], *, journal: bool, on_accepted: Callable[[], None] | None = None
|
||||
) -> None:
|
||||
assert session is not None
|
||||
session_id = session.session_id
|
||||
should_journal = journal and session_id not in self._resync_required_sessions
|
||||
@@ -108,6 +111,7 @@ class DuplexSessionRunnerMixin:
|
||||
session_id,
|
||||
payload,
|
||||
journal=should_journal,
|
||||
on_accepted=on_accepted,
|
||||
)
|
||||
except DuplexJournalOverflowError:
|
||||
first_overflow = session_id not in self._resync_required_sessions
|
||||
@@ -129,6 +133,7 @@ class DuplexSessionRunnerMixin:
|
||||
session_id,
|
||||
payload,
|
||||
journal=False,
|
||||
on_accepted=on_accepted,
|
||||
)
|
||||
|
||||
if realtime_protocol is not None:
|
||||
@@ -155,23 +160,29 @@ class DuplexSessionRunnerMixin:
|
||||
|
||||
event_emit_lock = asyncio.Lock()
|
||||
|
||||
async def send_outbound(payload: dict[str, object]) -> None:
|
||||
async def send_outbound(payload: dict[str, object], *, on_accepted: Callable[[], None] | None = None) -> None:
|
||||
if not attachment_ready or session is None:
|
||||
await actor.send_json(dict(payload))
|
||||
if on_accepted is not None:
|
||||
on_accepted()
|
||||
return
|
||||
if realtime_protocol is None:
|
||||
await send_attachment_payload(
|
||||
payload,
|
||||
journal=payload.get("type") not in {"session.created", "session.resumed"},
|
||||
on_accepted=on_accepted,
|
||||
)
|
||||
return
|
||||
for projected in realtime_protocol.encode_outbound_event(payload):
|
||||
await send_attachment_payload(
|
||||
projected,
|
||||
journal=projected.get("type") not in {"session.created", "session.resumed"},
|
||||
# Item/part announcements may precede the audio. Only the
|
||||
# actual audio event establishes acceptance of this chunk.
|
||||
on_accepted=on_accepted if projected.get("type") == "response.audio.delta" else None,
|
||||
)
|
||||
|
||||
async def emit_event(payload: dict[str, object]) -> None:
|
||||
async def emit_event(payload: dict[str, object], *, on_accepted: Callable[[], None] | None = None) -> None:
|
||||
deferred_precreate_response = False
|
||||
async with event_emit_lock:
|
||||
accepted, deferred_overlap_payload = await self._apply_outbound_session_event(
|
||||
@@ -183,7 +194,7 @@ class DuplexSessionRunnerMixin:
|
||||
)
|
||||
if not accepted:
|
||||
return
|
||||
await send_outbound(payload)
|
||||
await send_outbound(payload, on_accepted=on_accepted)
|
||||
if deferred_overlap_payload is not None:
|
||||
deferred_precreate_response = native.deferred_precreate_response
|
||||
native.deferred_precreate_response = False
|
||||
|
||||
Reference in new issue
Block a user