Add SSE stream_format support for audio speech streaming (#4490)
Signed-off-by: syd520zy <529477025@qq.com> Signed-off-by: faceless void <100186390+syd520zy@users.noreply.github.com> Signed-off-by: Nick Cao <ncao@redhat.com> Signed-off-by: Chendi Xue <chendi.xue@intel.com> Signed-off-by: kTorp <Kristoffer.Torp@amd.com> Signed-off-by: Junhong Liu <98734602+LJH-LBJ@users.noreply.github.com> Signed-off-by: Hongsheng Liu <liuhongsheng4@huawei.com> Signed-off-by: Hyoseop Song <crad_on25@naver.com> Signed-off-by: Hyoseop Song <crad_on25@naver.com> Signed-off-by: amy-why-3459 <wuhaiyan17@huawei.com> Co-authored-by: Nick Cao <ncao@redhat.com> Co-authored-by: Chendi.Xue <chendi.xue@intel.com> Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com> Co-authored-by: Kristoffer <kristoffer.torp@amd.com> Co-authored-by: Junhong Liu <ljh_lbj@163.com> Co-authored-by: lishunyang <lishunyang12@163.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Co-authored-by: Hyoseop Song <crad_on25@naver.com> Co-authored-by: Zhou Taichang <tzhouam@connect.ust.hk> Co-authored-by: Alicia <115451386+congw729@users.noreply.github.com> Co-authored-by: amy-why-3459 <wuhaiyan17@huawei.com>
This commit is contained in:
9 files changed
+320
-51
No files matched your search
@@ -2659,7 +2659,6 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
sample_rate=sample_rate_val,
|
||||
response_format="pcm",
|
||||
speed=1.0,
|
||||
stream_format="audio",
|
||||
base64_encode=False,
|
||||
)
|
||||
if first_audio_chunk_s is None:
|
||||
@@ -2728,6 +2727,53 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
if not artifact_ready:
|
||||
self._discard_ref_audio_artifact_warmup(request_id)
|
||||
|
||||
async def _generate_audio_sse_events(
|
||||
self,
|
||||
generator,
|
||||
request_id: str,
|
||||
response_format: str = "pcm",
|
||||
raw_request: Request | None = None,
|
||||
request_start_s: float | None = None,
|
||||
):
|
||||
"""Generate OpenAI-style SSE events with base64 audio deltas.
|
||||
|
||||
Field naming follows the OpenAI ``speech.audio.delta`` schema, which
|
||||
carries the base64 chunk in ``audio`` (not ``delta`` — that is the
|
||||
Realtime API ``response.audio.delta`` convention, a different event).
|
||||
See https://platform.openai.com/docs/api-reference/audio-streaming.
|
||||
"""
|
||||
try:
|
||||
async for chunk in self._generate_audio_chunks(
|
||||
generator,
|
||||
request_id,
|
||||
response_format,
|
||||
raw_request=raw_request,
|
||||
request_start_s=request_start_s,
|
||||
):
|
||||
payload = {
|
||||
"type": "speech.audio.delta",
|
||||
"audio": base64.b64encode(chunk).decode("ascii"),
|
||||
"response_format": response_format,
|
||||
}
|
||||
data = json.dumps(payload, separators=(",", ":"))
|
||||
yield f"event: speech.audio.delta\ndata: {data}\n\n"
|
||||
done = json.dumps({"type": "speech.audio.done"}, separators=(",", ":"))
|
||||
yield f"event: speech.audio.done\ndata: {done}\n\n"
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e:
|
||||
payload = {
|
||||
"type": "speech.audio.error",
|
||||
"error": {
|
||||
"message": str(e),
|
||||
"type": "server_error",
|
||||
"param": None,
|
||||
"code": HTTPStatus.INTERNAL_SERVER_ERROR.value,
|
||||
},
|
||||
}
|
||||
data = json.dumps(payload, separators=(",", ":"))
|
||||
yield f"event: speech.audio.error\ndata: {data}\n\n"
|
||||
|
||||
@staticmethod
|
||||
def _extract_audio_output(res) -> tuple[dict | None, str | None]:
|
||||
"""Return (audio_output dict, audio key) or (None, None).
|
||||
@@ -3305,7 +3351,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
# we don't emit redundant MM data & drain after emitting.
|
||||
# list() makes a copy to avoid mutating the params.
|
||||
sampling_params_list = list(self.engine_client.default_sampling_params_list)
|
||||
sampling_params_list = coerce_param_message_types(sampling_params_list, request.stream)
|
||||
is_streaming_request = request.is_streaming()
|
||||
sampling_params_list = coerce_param_message_types(sampling_params_list, is_streaming_request)
|
||||
|
||||
# Build prompt + tts_params via the per-model adapter (RFC #4327). Every
|
||||
# dedicated TTS model resolves to an adapter that owns its validation,
|
||||
@@ -3636,7 +3683,6 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
sample_rate=sample_rate,
|
||||
response_format=request.response_format or "wav",
|
||||
speed=request.speed or 1.0,
|
||||
stream_format=request.stream_format,
|
||||
base64_encode=base64_encode,
|
||||
)
|
||||
audio_response: AudioResponse = self.create_audio(audio_obj)
|
||||
@@ -3749,7 +3795,6 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
sample_rate=sample_rate,
|
||||
response_format=request.response_format or "wav",
|
||||
speed=request.speed or 1.0,
|
||||
stream_format=request.stream_format,
|
||||
base64_encode=False,
|
||||
)
|
||||
audio_response: AudioResponse = self.create_audio(audio_obj)
|
||||
@@ -3779,6 +3824,25 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
error_body = json.dumps({"error": {"message": message, "type": err_type, "param": None, "code": status_code}})
|
||||
return Response(content=error_body, media_type="application/json", status_code=status_code)
|
||||
|
||||
def _validate_speech_streaming_request(
|
||||
self,
|
||||
request: OpenAICreateSpeechRequest,
|
||||
*,
|
||||
mode_label: str,
|
||||
) -> tuple[str, Response | None]:
|
||||
"""Validate pcm/wav + speed constraints for streaming speech responses."""
|
||||
response_format = (request.response_format or "wav").lower()
|
||||
if response_format not in ("pcm", "wav"):
|
||||
return response_format, self.create_error_response(
|
||||
f"{mode_label} is only supported for 'pcm' and 'wav' formats. Got '{response_format}'."
|
||||
)
|
||||
if request.speed is not None and request.speed != 1.0:
|
||||
return response_format, self.create_error_response(
|
||||
f"{mode_label} is not supported with speed adjustment. "
|
||||
"Use a non-streaming request or remove the speed parameter."
|
||||
)
|
||||
return response_format, None
|
||||
|
||||
async def create_speech(
|
||||
self,
|
||||
request: OpenAICreateSpeechRequest,
|
||||
@@ -3800,7 +3864,9 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
- ref_text: Transcript of reference audio (Base task)
|
||||
- x_vector_only_mode: Use speaker embedding only (Base task)
|
||||
|
||||
Streaming is supported via stream=True with response_format='pcm' or 'wav'.
|
||||
Streaming is supported via ``stream_format='audio'`` or the legacy
|
||||
``stream=True`` switch, with ``response_format='pcm'`` or ``'wav'``.
|
||||
``stream_format='sse'`` returns OpenAI ``speech.audio.*`` SSE events instead.
|
||||
Each Code2Wav chunk is yielded as raw audio bytes as soon as it is decoded.
|
||||
For WAV format, a header with placeholder size values is emitted first.
|
||||
"""
|
||||
@@ -3820,7 +3886,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
)
|
||||
|
||||
try:
|
||||
if request.stream:
|
||||
if request.is_raw_audio_stream():
|
||||
if request.word_timestamps:
|
||||
return self.create_error_response(
|
||||
"word_timestamps=true is currently supported by the WebSocket "
|
||||
@@ -3828,22 +3894,12 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
"stream_audio=true and response_format='pcm'."
|
||||
)
|
||||
|
||||
# Determine response format and media type for streaming
|
||||
response_format = (request.response_format or "wav").lower()
|
||||
|
||||
# Only pcm and wav support streaming without post-processing
|
||||
if response_format not in ["pcm", "wav"]:
|
||||
return self.create_error_response(
|
||||
f"Streaming is only supported for 'pcm' and 'wav' formats. "
|
||||
f"Got '{response_format}'. For other formats, use stream=False."
|
||||
)
|
||||
|
||||
# Check if speed adjustment is requested (not compatible with streaming)
|
||||
if request.speed is not None and request.speed != 1.0:
|
||||
return self.create_error_response(
|
||||
"Streaming is not supported with speed adjustment. "
|
||||
"Use stream=False or remove the speed parameter."
|
||||
)
|
||||
response_format, error = self._validate_speech_streaming_request(
|
||||
request,
|
||||
mode_label="Streaming",
|
||||
)
|
||||
if error is not None:
|
||||
return error
|
||||
|
||||
media_type = "audio/wav" if response_format == "wav" else "audio/pcm"
|
||||
_, generator, _ = await self._prepare_speech_generation(request, request_id=request_id)
|
||||
@@ -3858,6 +3914,26 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
media_type=media_type,
|
||||
)
|
||||
|
||||
if request.is_sse_stream():
|
||||
response_format, error = self._validate_speech_streaming_request(
|
||||
request,
|
||||
mode_label="SSE streaming",
|
||||
)
|
||||
if error is not None:
|
||||
return error
|
||||
|
||||
_, generator, _ = await self._prepare_speech_generation(request, request_id=request_id)
|
||||
return StreamingResponse(
|
||||
self._generate_audio_sse_events(
|
||||
generator,
|
||||
request_id,
|
||||
response_format,
|
||||
raw_request=raw_request,
|
||||
request_start_s=request_start_s,
|
||||
),
|
||||
media_type="text/event-stream",
|
||||
)
|
||||
|
||||
audio_bytes, media_type = await self._generate_audio_bytes(request, request_id=request_id)
|
||||
total_ms = (time.perf_counter() - request_start_s) * 1000.0
|
||||
logger.info(
|
||||
|
||||
Reference in new issue
Block a user