[Core][Frontend] Unified Full-duplex Framework (#7413)

Signed-off-by: chickeyton <ngton2014@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
chickeytonandClaude Opus 5 authored and GitHub committed 2026-09-16 15:35:36 +08:00
1 parent 9005d78903
commit 99ff4f3070
182 files changed
+26951 -34743

No files matched your search

+9 -2
View File
@@ -1,6 +1,13 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from .websocket import DuplexWebSocketActor
"""Thin websocket serving for engine-resident duplex sessions.
__all__ = ["DuplexWebSocketActor"]
The session logic lives in ``vllm_omni.engine.duplex`` and is reached through
``vllm_omni.entrypoints.duplex_omni.DuplexOmni``; this package only speaks the
OpenAI Realtime wire protocol over ``/v1/realtime?duplex=1``.
"""
from .serving import OmniDuplexSessionHandler
__all__ = ["OmniDuplexSessionHandler"]
-220
View File
@@ -1,220 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import base64
import binascii
import io
import math
import wave
import numpy as np
try:
from audioop import alaw2lin, lin2alaw, lin2ulaw, ulaw2lin
except ImportError: # pragma: no cover - audioop is removed in newer Python.
alaw2lin = lin2alaw = lin2ulaw = ulaw2lin = None
MIN_INPUT_SAMPLE_RATE_HZ = 8_000
MAX_INPUT_SAMPLE_RATE_HZ = 192_000
def validate_input_sample_rate_hz(sample_rate_hz: object) -> int:
if (
isinstance(sample_rate_hz, bool)
or not isinstance(sample_rate_hz, int | float)
or (isinstance(sample_rate_hz, float) and not math.isfinite(sample_rate_hz))
):
raise ValueError("sample_rate_hz must be a finite integer")
rate = int(sample_rate_hz)
if rate != sample_rate_hz:
raise ValueError("sample_rate_hz must be an integer")
if not MIN_INPUT_SAMPLE_RATE_HZ <= rate <= MAX_INPUT_SAMPLE_RATE_HZ:
raise ValueError(f"sample_rate_hz must be between {MIN_INPUT_SAMPLE_RATE_HZ} and {MAX_INPUT_SAMPLE_RATE_HZ}")
return rate
def resample_pcm16_mono(raw: bytes, *, source_rate_hz: int, target_rate_hz: int) -> bytes:
if source_rate_hz <= 0 or target_rate_hz <= 0 or source_rate_hz == target_rate_hz:
return raw
# Import lazily so the generic Duplex audio module does not pull in the
# OpenAI API server while the Duplex stack itself is being imported.
from vllm_omni.entrypoints.openai.audio_utils_mixin import StreamingAudioResampler
samples = np.frombuffer(raw, dtype="<i2")
rate_gcd = math.gcd(source_rate_hz, target_rate_hz)
reduced_factor = max(source_rate_hz // rate_gcd, target_rate_hz // rate_gcd)
if reduced_factor > StreamingAudioResampler._max_polyphase_factor:
# The FIR size scales with the reduced ratio. Keep unusual client
# rates bounded while common audio rates use the high-quality path.
if samples.size <= 1:
return raw
target_size = max(1, int(round(samples.size * target_rate_hz / source_rate_hz)))
source_x = np.linspace(0.0, 1.0, num=samples.size, endpoint=True)
target_x = np.linspace(0.0, 1.0, num=target_size, endpoint=True)
resampled = np.interp(target_x, source_x, samples)
return np.clip(resampled, -32_768, 32_767).astype("<i2").tobytes()
resampler = StreamingAudioResampler(source_rate_hz, target_rate_hz)
normalized = samples.astype(np.float32) * np.float32(1.0 / 32768.0)
resampled = resampler.process(normalized, final=True)
return np.clip(np.rint(resampled * 32768.0), -32768, 32767).astype("<i2").tobytes()
def decode_g711_ulaw(raw: bytes) -> bytes:
if ulaw2lin is not None:
return ulaw2lin(raw, 2)
data = np.frombuffer(raw, dtype=np.uint8)
value = np.bitwise_not(data).astype(np.int16)
sign = value & 0x80
exponent = (value >> 4) & 0x07
mantissa = value & 0x0F
sample = ((mantissa << 3) + 0x84) << exponent
return np.where(sign != 0, -(sample - 0x84), sample - 0x84).astype("<i2").tobytes()
def decode_g711_alaw(raw: bytes) -> bytes:
if alaw2lin is not None:
return alaw2lin(raw, 2)
data = np.bitwise_xor(np.frombuffer(raw, dtype=np.uint8), 0x55).astype(np.int16)
sign = data & 0x80
exponent = (data >> 4) & 0x07
mantissa = data & 0x0F
sample = np.where(exponent == 0, (mantissa << 4) + 8, ((mantissa << 4) + 0x108) << (exponent - 1))
return np.where(sign != 0, sample, -sample).astype("<i2").tobytes()
def encode_g711_ulaw(raw: bytes) -> bytes:
if lin2ulaw is not None:
return lin2ulaw(raw, 2)
pcm = np.clip(np.frombuffer(raw, dtype="<i2").astype(np.int32), -32635, 32635)
sign = np.where(pcm < 0, 0x80, 0)
magnitude = np.abs(pcm) + 0x84
exponent = np.zeros_like(magnitude)
for exp in range(7):
exponent = np.where(magnitude > (0xFF << exp), exp + 1, exponent)
mantissa = (magnitude >> (exponent + 3)) & 0x0F
return (np.bitwise_not(sign | (exponent << 4) | mantissa) & 0xFF).astype(np.uint8).tobytes()
def encode_g711_alaw(raw: bytes) -> bytes:
if lin2alaw is not None:
return lin2alaw(raw, 2)
pcm = np.frombuffer(raw, dtype="<i2").astype(np.int32)
sign = np.where(pcm >= 0, 0x80, 0x00)
magnitude = np.abs(pcm)
exponent = np.zeros_like(magnitude)
for exp in range(1, 8):
exponent = np.where(magnitude >= (1 << (exp + 7)), exp, exponent)
mantissa = np.where(
exponent == 0,
(magnitude >> 4) & 0x0F,
(magnitude >> (exponent + 3)) & 0x0F,
)
return ((sign | (exponent << 4) | mantissa) ^ 0x55).astype(np.uint8).tobytes()
def wav_payload_to_pcm16(raw: bytes) -> tuple[bytes | None, int | None]:
try:
with wave.open(io.BytesIO(raw), "rb") as wav_file:
channels = wav_file.getnchannels()
sample_width = wav_file.getsampwidth()
sample_rate_hz = wav_file.getframerate()
frames = wav_file.readframes(wav_file.getnframes())
if sample_width != 2:
return None, sample_rate_hz
if channels <= 1:
return frames, sample_rate_hz
pcm = np.frombuffer(frames, dtype="<i2").reshape(-1, channels)
mono = np.mean(pcm.astype(np.float32), axis=1)
return np.clip(mono, -32768, 32767).astype("<i2").tobytes(), sample_rate_hz
except (EOFError, ValueError, wave.Error):
return None, None
def encode_float32_mono_wav_base64(
samples: np.ndarray,
*,
sample_rate_hz: int,
) -> str:
"""Package normalized mono float32 samples as a PCM16 WAV data payload."""
rate = validate_input_sample_rate_hz(sample_rate_hz)
normalized = np.ascontiguousarray(samples, dtype=np.float32).reshape(-1)
pcm16 = np.clip(np.rint(normalized * 32768.0), -32768, 32767).astype("<i2")
with io.BytesIO() as buffer:
with wave.open(buffer, "wb") as wav_file:
wav_file.setnchannels(1)
wav_file.setsampwidth(2)
wav_file.setframerate(rate)
wav_file.writeframes(pcm16.tobytes())
return base64.b64encode(buffer.getvalue()).decode("ascii")
def convert_input_audio_with_rate(
audio: object,
fmt: object,
*,
sample_rate_hz: int | float | None = None,
target_sample_rate_hz: int = 16_000,
) -> tuple[object, object, int | float | None]:
if not isinstance(audio, str) or not isinstance(fmt, str):
return audio, fmt, sample_rate_hz
normalized = fmt.lower()
if normalized not in {"pcm16", "pcm_s16le", "s16le", "g711_ulaw", "g711_alaw"}:
return audio, fmt, sample_rate_hz
if isinstance(sample_rate_hz, int | float):
sample_rate_hz = validate_input_sample_rate_hz(sample_rate_hz)
try:
raw = base64.b64decode(audio.strip(), validate=False)
except (binascii.Error, ValueError):
return audio, fmt, sample_rate_hz
if normalized == "g711_ulaw":
raw = decode_g711_ulaw(raw)
sample_rate_hz = sample_rate_hz if isinstance(sample_rate_hz, int | float) else 8_000
elif normalized == "g711_alaw":
raw = decode_g711_alaw(raw)
sample_rate_hz = sample_rate_hz if isinstance(sample_rate_hz, int | float) else 8_000
elif len(raw) % 2:
return audio, fmt, sample_rate_hz
if isinstance(sample_rate_hz, int | float) and int(sample_rate_hz) != target_sample_rate_hz:
raw = resample_pcm16_mono(
raw,
source_rate_hz=int(sample_rate_hz),
target_rate_hz=target_sample_rate_hz,
)
sample_rate_hz = target_sample_rate_hz
pcm = np.frombuffer(raw, dtype="<i2").astype(np.float32) / 32768.0
encoded = base64.b64encode(np.ascontiguousarray(pcm, dtype="<f4").tobytes()).decode("ascii")
return encoded, "pcm_f32le", sample_rate_hz
def convert_output_audio(
audio: str,
*,
source_fmt: str,
target_fmt: str,
source_sample_rate_hz: int | None = None,
target_sample_rate_hz: int | None = None,
) -> tuple[str, str, int | None]:
target = target_fmt.lower()
if target not in {"g711_ulaw", "g711_alaw"}:
return audio, source_fmt, source_sample_rate_hz
try:
raw = base64.b64decode(audio, validate=False)
except (binascii.Error, ValueError):
return audio, source_fmt, source_sample_rate_hz
source = source_fmt.lower()
if source == "wav":
pcm_raw, wav_rate = wav_payload_to_pcm16(raw)
if pcm_raw is None:
return audio, source_fmt, source_sample_rate_hz
raw = pcm_raw
source_sample_rate_hz = source_sample_rate_hz or wav_rate
elif source not in {"pcm", "pcm16", "pcm_s16le", "s16le"} or len(raw) % 2:
return audio, source_fmt, source_sample_rate_hz
target_rate = target_sample_rate_hz or 8_000
if source_sample_rate_hz is not None:
raw = resample_pcm16_mono(raw, source_rate_hz=source_sample_rate_hz, target_rate_hz=target_rate)
encoded = encode_g711_ulaw(raw) if target == "g711_ulaw" else encode_g711_alaw(raw)
return base64.b64encode(encoded).decode("ascii"), target, target_rate
@@ -0,0 +1,55 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Audio encoding for duplex model output (entrypoint layer, injected into ``DuplexOmniEngine``)."""
from __future__ import annotations
import numpy as np
from vllm.logger import init_logger
logger = init_logger(__name__)
def encode_audio(
audio_data: object,
sample_rate_hz: int,
response_format: str,
speed: float | None,
) -> str | None:
"""Encode a model audio tensor/array into base64 in ``response_format``.
Moved from the serving runtime bridge; uses the shared ``AudioMixin``
encoder directly instead of going through the chat service.
"""
if audio_data is None:
return None
try:
import torch
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin
from vllm_omni.entrypoints.openai.protocol.audio import CreateAudio
if isinstance(audio_data, torch.Tensor):
audio_tensor = audio_data.detach().cpu().float().numpy()
else:
audio_tensor = np.asarray(audio_data, dtype=np.float32)
if audio_tensor.ndim > 1:
audio_tensor = audio_tensor.reshape(-1)
audio_response = AudioMixin().create_audio(
CreateAudio(
audio_tensor=audio_tensor,
sample_rate=sample_rate_hz,
response_format=response_format,
speed=float(speed) if isinstance(speed, int | float) and speed > 0 else 1.0,
stream_format="audio",
base64_encode=True,
)
)
return str(audio_response.audio_data)
except Exception:
logger.exception("Failed to encode duplex data-plane audio output")
return None
__all__ = ["encode_audio"]
@@ -1,34 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from vllm.logger import init_logger
logger = init_logger(__name__)
def should_enable_duplex_endpoint(
stage_configs: list | None,
*,
config_path: str | None = None,
) -> bool:
"""Enable the realtime session handler for explicitly configured deployments."""
if stage_configs:
for stage in stage_configs:
session_mode = (
stage.get("session_mode") if isinstance(stage, dict) else getattr(stage, "session_mode", None)
)
if session_mode == "duplex":
return True
if config_path:
try:
from vllm_omni.config.stage_config import resolve_deploy_yaml
raw_config = resolve_deploy_yaml(config_path)
if raw_config.get("session_mode") == "duplex" or isinstance(raw_config.get("duplex_session"), dict):
return True
except Exception as exc:
logger.warning("Failed to inspect realtime session configuration from %s: %s", config_path, exc)
return False
__all__ = ["should_enable_duplex_endpoint"]
@@ -1,302 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
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
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
from vllm.logger import init_logger
from vllm_omni.entrypoints.duplex.protocol import DuplexSession
logger = init_logger(__name__)
class ChatFallbackProjectorMixin:
"""Project generic chat completion output into duplex response events."""
async def _run_response(self, session: DuplexSession, send_json) -> None:
response_id = session.begin_response()
epoch = session.epoch
request_id = f"duplex-{session.session_id}-{epoch}-{session.input_commit_seq}"
session.bind_request(f"chatcmpl-{request_id}")
await send_json(
self._response_created_payload(
session,
response_id,
epoch=epoch,
request_id=session.active_request_id,
)
)
try:
request = self._build_chat_request(session, request_id)
result = await self._chat_service.create_chat_completion(request, raw_request=None)
if isinstance(result, ErrorResponse):
error = result.error
await send_json(
{
"type": "error",
"error": error.message if error else "Chat request failed",
"code": error.type if error else "chat_error",
}
)
session.end_response(commit_text=False)
return
if hasattr(result, "__aiter__"):
await self._drain_streaming_response(session, result, epoch, response_id, send_json)
else:
await self._emit_full_response(session, result, epoch, response_id, send_json)
if session.epoch == epoch:
final_stage_metrics = session.accumulate_response_stage_metrics(None)
should_commit = self._should_commit_response_to_history(session, response_id)
committed_message = session.end_response(commit_text=should_commit)
if should_commit:
session.register_history_item(f"item_{response_id}", committed_message)
done_payload: dict[str, object] = {
"type": "response.done",
"session_id": session.session_id,
"response_id": response_id,
"epoch": epoch,
"committed": committed_message is not None,
"playback": session.playback.as_dict(),
}
if final_stage_metrics:
done_payload["vllm_omni"] = {"stage_metrics": final_stage_metrics}
await send_json(done_payload)
except asyncio.CancelledError:
raise
except Exception as exc:
logger.exception("Duplex response failed: %s", exc)
session.end_response(commit_text=False)
await send_json(
{
"type": "error",
"session_id": session.session_id,
"response_id": response_id,
"error": str(exc),
"code": "response_error",
}
)
def _build_chat_request(self, session: DuplexSession, request_id: str) -> ChatCompletionRequest:
response_config = session.response_config
messages: list[dict[str, object]] = []
if response_config.instructions:
messages.append({"role": "system", "content": response_config.instructions})
messages.extend(session.history)
kwargs: dict[str, Any] = {
"model": response_config.model or self._chat_service.model_config.model,
"messages": messages,
"stream": True,
}
if response_config.temperature is not None:
kwargs["temperature"] = response_config.temperature
if response_config.max_tokens is not None:
kwargs["max_tokens"] = response_config.max_tokens
model_extra = dict(response_config.extra_body)
model_extra.pop("native_duplex", None)
model_extra.pop("minicpmo45_native_duplex", None)
tools = model_extra.pop("realtime_response_tools", model_extra.pop("realtime_tools", None))
tool_choice = model_extra.pop(
"realtime_response_tool_choice",
model_extra.pop("realtime_tool_choice", None),
)
for protocol_key in (
"realtime_response_conversation",
"realtime_response_metadata",
"realtime_response_prompt",
):
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):
kwargs["tool_choice"] = tool_choice
request = ChatCompletionRequest(**kwargs)
object.__setattr__(request, "modalities", response_config.modalities)
object.__setattr__(request, "request_id", request_id)
object.__setattr__(
request,
"chat_template_kwargs",
{"use_tts_template": response_config.use_tts_template},
)
return request
async def _drain_streaming_response(
self,
session: DuplexSession,
result: AsyncGenerator[str, None],
epoch: int,
response_id: str,
send_json,
) -> None:
async for raw_chunk in result:
if session.epoch != epoch:
return
for payload in self._parse_sse_payloads(raw_chunk):
if payload == "[DONE]":
continue
if isinstance(payload, dict):
await self._emit_chat_payload(session, payload, epoch, response_id, send_json)
async def _emit_full_response(
self,
session: DuplexSession,
result: Any,
epoch: int,
response_id: str,
send_json,
) -> None:
if hasattr(result, "model_dump"):
payload = result.model_dump(mode="json", exclude_unset=True)
else:
payload = {"response": str(result)}
await self._emit_chat_payload(session, payload, epoch, response_id, send_json)
def _parse_sse_payloads(self, raw_chunk: str) -> list[dict[str, object] | str]:
payloads: list[dict[str, object] | str] = []
for line in raw_chunk.splitlines():
line = line.strip()
if not line.startswith("data:"):
continue
data = line[5:].strip()
if not data:
continue
if data == "[DONE]":
payloads.append(data)
continue
try:
parsed = json.loads(data)
except json.JSONDecodeError:
logger.debug("Skipping non-JSON duplex stream payload: %s", data)
continue
if isinstance(parsed, dict):
payloads.append(parsed)
return payloads
async def _emit_chat_payload(
self,
session: DuplexSession,
payload: dict[str, object],
epoch: int,
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):
session.replace_response_stage_metric_snapshots(stage_metrics)
modality = payload.get("modality")
if modality not in {None, "text", "audio"}:
await send_json(
{
"type": "error",
"session_id": session.session_id,
"response_id": response_id,
"epoch": epoch,
"code": "unsupported_response_modality",
"error": f"Unsupported chat response modality: {modality}",
}
)
return
choices = payload.get("choices")
if not isinstance(choices, list):
await send_json(
{
"type": "response.message",
"session_id": session.session_id,
"response_id": response_id,
"epoch": epoch,
"payload": payload,
}
)
return
for choice in choices:
if not isinstance(choice, dict):
continue
delta = choice.get("delta")
message = choice.get("message")
content = None
if isinstance(delta, dict):
content = delta.get("content")
elif isinstance(message, dict):
content = message.get("content")
if isinstance(content, str) and content:
if modality != "audio":
session.append_assistant_text(content)
await send_json(
{
"type": "response.text.delta",
"session_id": session.session_id,
"response_id": response_id,
"epoch": epoch,
"delta": content,
}
)
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(
{
"type": "response.output_item.done",
"session_id": session.session_id,
"response_id": response_id,
"epoch": epoch,
"finish_reason": finish_reason,
"modality": modality,
}
)
@@ -1,41 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
class CommitAction(str, Enum):
"""How one native audio commit participates in response scheduling."""
START_AUTO_RESPONSE = "start_auto_response"
DEFER_ACTIVE_RESPONSE = "defer_active_response"
COMMIT_ONLY = "commit_only"
@dataclass(frozen=True, slots=True)
class CommitSnapshot:
auto_responds: bool
speech_since_commit: bool
active_response_id: str | None
overlap_speech_ms: int
native_response_in_progress: bool
playback_active: bool
def decide_commit_action(snapshot: CommitSnapshot) -> CommitAction:
"""Choose response scheduling from an immutable session snapshot."""
if snapshot.auto_responds:
if snapshot.speech_since_commit:
return CommitAction.START_AUTO_RESPONSE
return CommitAction.COMMIT_ONLY
if snapshot.native_response_in_progress and snapshot.overlap_speech_ms > 0:
return CommitAction.DEFER_ACTIVE_RESPONSE
if snapshot.playback_active and snapshot.overlap_speech_ms > 0:
return CommitAction.DEFER_ACTIVE_RESPONSE
return CommitAction.COMMIT_ONLY
__all__ = ["CommitAction", "CommitSnapshot", "decide_commit_action"]
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,147 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import json
from typing import Any
from uuid import uuid4
from fastapi import WebSocket
from vllm_omni.entrypoints.duplex import realtime_state as _state
from vllm_omni.entrypoints.duplex.realtime_input import (
RealtimeInputTranslator,
)
from vllm_omni.entrypoints.duplex.realtime_output import (
RealtimeOutputProjector,
)
REALTIME_ERROR_TYPES_BY_CODE = _state.REALTIME_ERROR_TYPES_BY_CODE
REALTIME_INPUT_AUDIO_FORMATS = _state.REALTIME_INPUT_AUDIO_FORMATS
REALTIME_OUTPUT_AUDIO_FORMATS = _state.REALTIME_OUTPUT_AUDIO_FORMATS
RealtimeSessionState = _state.RealtimeSessionState
_RealtimeResponseState = _state._RealtimeResponseState
class NativeRealtimeSessionProtocol(
RealtimeInputTranslator,
RealtimeOutputProjector,
_state.RealtimeStateOwner,
):
"""Compatibility facade for one native Realtime protocol session.
Input translation, output projection, and mutable state have separate
owners. The facade retains the established import path and private helper
surface used by serving and protocol contract tests.
"""
def __init__(self, query_params: Any) -> None:
self._state = RealtimeSessionState.from_query_params(query_params)
def bind_sender(self, send_realtime_json) -> None:
self._send_realtime_json = send_realtime_json
def bind_native_input_append(self, enabled: bool) -> None:
"""Use the serving-selected input path, independent of interruption policy."""
self._native_input_append = enabled
def _default_session_payload(self) -> dict[str, object]:
payload: dict[str, object] = {
"model": self._default_model,
"session_id": self._default_session_id,
}
if self._default_extra_body:
payload["extra_body"] = dict(self._default_extra_body)
return payload
async def receive_internal_event_text(self, websocket: WebSocket) -> str:
if not self._pending_outbound.empty():
return json.dumps(await self._pending_outbound.get())
if not self._opened and not self._resume_only and not self._autostarted_default_session and self._default_model:
self._opened = True
self._autostarted_default_session = True
return json.dumps(self._session_create_from_realtime(self._default_session_payload()))
while True:
if not self._pending_outbound.empty():
return json.dumps(await self._pending_outbound.get())
await self.wait_for_realtime_turn_detection_update()
raw = await websocket.receive_text()
try:
event = json.loads(raw)
except json.JSONDecodeError:
return raw
if not isinstance(event, dict):
return raw
if not self._opened and event.get("type") == "session.resume":
self._opened = True
translated = await self._to_duplex_event(event)
if translated is None:
if not self._pending_outbound.empty():
return json.dumps(await self._pending_outbound.get())
continue
return json.dumps(translated)
if not self._opened and self._resume_only:
translated = await self._to_duplex_event(event)
if translated is None:
if not self._pending_outbound.empty():
return json.dumps(await self._pending_outbound.get())
continue
return json.dumps(translated)
if not self._opened and event.get("type") != "session.update":
self._opened = True
await self._pending_outbound.put(self._session_create_from_realtime(self._default_session_payload()))
translated = await self._to_duplex_event(event)
if translated is not None:
await self._send_realtime_input_ack(event)
await self._pending_outbound.put(translated)
return json.dumps(await self._pending_outbound.get())
translated = await self._to_duplex_event(event)
if translated is None:
if not self._pending_outbound.empty():
return json.dumps(await self._pending_outbound.get())
continue
await self._send_realtime_input_ack(event)
return json.dumps(translated)
def encode_outbound_event(self, data: dict[str, Any]) -> list[dict[str, object]]:
payloads = self._from_duplex_event(data)
for payload in payloads:
self._attach_event_id(payload)
return payloads
@staticmethod
def _attach_event_id(payload: dict[str, object]) -> None:
payload.setdefault("event_id", f"event_{uuid4().hex}")
async def _send_realtime_payload(self, payload: dict[str, object]) -> None:
self._attach_event_id(payload)
if (
self._hold_realtime_output_until_session_created
and payload.get("type") != "error"
and payload.get("type") != "session.created"
):
self._held_realtime_payloads.append(payload)
return
if self._send_realtime_json is None:
raise RuntimeError("Native Realtime sender is not bound")
await self._send_realtime_json(payload)
@staticmethod
def _realtime_error_payload(
code: str,
message: str,
*,
event_id: object | None = None,
param: object | None = None,
) -> dict[str, object]:
error: dict[str, object] = {
"type": REALTIME_ERROR_TYPES_BY_CODE.get(code, "invalid_request_error"),
"code": code,
"message": message,
}
if isinstance(event_id, str) and event_id:
error["event_id"] = event_id
if isinstance(param, str) and param:
error["param"] = param
return {"type": "error", "error": error}
@@ -1,245 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
from typing import Any, Generic, TypeVar
REALTIME_INPUT_AUDIO_FORMATS = {
"pcm16",
"pcm_s16le",
"s16le",
"pcm_f32le",
"g711_ulaw",
"g711_alaw",
}
REALTIME_OUTPUT_AUDIO_FORMATS = {
"pcm16",
"pcm_s16le",
"s16le",
"wav",
"pcm",
"g711_ulaw",
"g711_alaw",
}
REALTIME_PCM_DEFAULT_SAMPLE_RATE_HZ = 24_000
REALTIME_PCM_F32_DEFAULT_SAMPLE_RATE_HZ = 16_000
REALTIME_G711_DEFAULT_SAMPLE_RATE_HZ = 8_000
_RealtimeProtocolConfig = tuple[str, int, str, int | None, float]
_PendingTurnDetectionUpdate = tuple[
bool,
dict[str, object] | None,
asyncio.Event,
_RealtimeProtocolConfig,
]
def realtime_default_sample_rate_hz(fmt: object) -> int | None:
if not isinstance(fmt, str):
return None
normalized = fmt.lower()
if normalized in {"pcm16", "pcm_s16le", "s16le", "pcm", "audio/pcm"}:
return REALTIME_PCM_DEFAULT_SAMPLE_RATE_HZ
if normalized in {"pcm_f32le", "audio/pcm_f32le"}:
return REALTIME_PCM_F32_DEFAULT_SAMPLE_RATE_HZ
if normalized in {"g711_ulaw", "g711_alaw", "audio/g711_ulaw", "audio/g711_alaw"}:
return REALTIME_G711_DEFAULT_SAMPLE_RATE_HZ
return None
REALTIME_ERROR_TYPES_BY_CODE = {
"bad_event": "invalid_request_error",
"bad_audio": "invalid_request_error",
"config_timeout": "invalid_request_error",
"invalid_json": "invalid_request_error",
"event_too_large": "invalid_request_error",
"unknown_event": "invalid_request_error",
"internal_error": "server_error",
"runtime_open_failed": "server_error",
"runtime_open_unsupported": "server_error",
"runtime_append_failed": "server_error",
"runtime_append_task_failed": "server_error",
"runtime_signal_failed": "server_error",
"runtime_close_failed": "server_error",
"runtime_abort_failed": "server_error",
"runtime_data_plane_stream_failed": "server_error",
"runtime_data_plane_text_without_audio": "server_error",
"response_error": "server_error",
"chat_error": "server_error",
"server_vad_initialization_failed": "server_error",
"server_vad_inference_failed": "server_error",
"duplex_session_busy": "rate_limit_error",
"resource_exhausted": "rate_limit_error",
"input_backpressure": "rate_limit_error",
"response_already_active": "invalid_request_error",
"response_not_active": "invalid_request_error",
"response_create_without_input": "invalid_request_error",
"input_audio_buffer_empty": "invalid_request_error",
"server_vad_manual_commit_unsupported": "invalid_request_error",
"missing_item_id": "invalid_request_error",
"item_not_found": "invalid_request_error",
"playback_item_mismatch": "invalid_request_error",
"playback_item_not_found": "invalid_request_error",
"playback_ack_too_late": "invalid_request_error",
"unsupported_audio_format": "invalid_request_error",
"unsupported_ref_audio_path": "invalid_request_error",
"ref_audio_required": "invalid_request_error",
"model_update_unsupported": "invalid_request_error",
"voice_update_after_audio_unsupported": "invalid_request_error",
"ref_audio_update_unsupported": "invalid_request_error",
"native_text_append_unsupported": "invalid_request_error",
"runtime_native_stage_role_required": "server_error",
"runtime_native_runner_kv_required": "server_error",
}
@dataclass(slots=True)
class _RealtimeResponseState:
item_id: str
transcript_parts: list[str] = field(default_factory=list)
text_parts: list[str] = field(default_factory=list)
audio_duration_ms: int | None = None
audio_text_marks: list[dict[str, int]] = field(default_factory=list)
audio_delta_emitted: bool = False
audio_done_emitted: bool = False
audio_part_added: bool = False
audio_part_done: bool = False
text_part_added: bool = False
text_part_done: bool = False
output_text_done: bool = False
output_item_done: bool = False
conversation_item_done: bool = False
speak_emitted: bool = False
done_emitted: bool = False
@property
def transcript(self) -> str:
return "".join(self.transcript_parts)
@property
def text(self) -> str:
return "".join(self.text_parts)
@dataclass(slots=True)
class RealtimeSessionState:
"""Single mutable authority for one Realtime protocol session."""
_opened: bool = False
_autostarted_default_session: bool = False
_resume_only: bool = False
_pending_outbound: asyncio.Queue[dict[str, object]] = field(default_factory=asyncio.Queue)
_held_realtime_payloads: list[dict[str, object]] = field(default_factory=list)
_hold_realtime_output_until_session_created: bool = True
_default_model: object | None = None
_default_session_id: object | None = None
_default_extra_body: dict[str, object] = field(default_factory=dict)
_input_audio_format: str = "pcm16"
_input_sample_rate_hz: int = REALTIME_PCM_DEFAULT_SAMPLE_RATE_HZ
_output_audio_format: str = "pcm16"
_overlap_silence_rms: float = 0.003
_turn_detection: dict[str, object] | None = None
_native_input_append: bool = False
_pending_turn_detection_update: _PendingTurnDetectionUpdate | None = None
_send_realtime_json: Any = None
_initial_session_update: bool = False
_input_speech_started: bool = False
_response_states: dict[str | int, _RealtimeResponseState] = field(default_factory=dict)
_item_truncation_cursors: dict[str, tuple[int, int]] = field(default_factory=dict)
_active_response_id: str | None = None
_last_response_id: str | None = None
_conversation_items: dict[str, dict[str, object]] = field(default_factory=dict)
_last_conversation_item_id: str | None = None
_output_sample_rate_hz: int | None = None
_active_input_item_id: str | None = None
_input_audio_buffer_has_audio: bool = False
_input_audio_buffer_had_non_speech: bool = False
_input_audio_buffer_transcript_parts: list[str] = field(default_factory=list)
_turn_detection_configured: bool = False
@classmethod
def from_query_params(cls, query_params: Any) -> RealtimeSessionState:
if hasattr(query_params, "query_params"):
query_params = query_params.query_params
getter = query_params.get if hasattr(query_params, "get") else None
# Canonical query param plus the deprecated model-prefixed alias;
# both seed the canonical extra_body key.
native_duplex = None
if getter is not None:
native_duplex = getter("native_duplex")
if native_duplex is None:
native_duplex = getter("minicpmo45_native_duplex")
resume_only = getter("resume") if getter is not None else None
autostart = getter("autostart") if getter is not None else None
default_extra_body = {}
if str(native_duplex).strip().lower() in {"1", "true", "yes", "on"}:
default_extra_body["native_duplex"] = True
return cls(
_resume_only=(
str(resume_only).strip().lower() in {"1", "true", "yes", "on"}
or str(autostart).strip().lower() in {"0", "false", "no", "off"}
),
_default_model=getter("model") if getter is not None else None,
_default_session_id=(getter("session_id") if getter is not None else None),
_default_extra_body=default_extra_body,
)
_StateValue = TypeVar("_StateValue")
class _RealtimeStateField(Generic[_StateValue]):
"""Explicit descriptor binding one protocol attribute to session state."""
def __set_name__(self, owner: type, name: str) -> None:
del owner
self._name = name
def __get__(self, instance: Any, owner: type | None = None) -> _StateValue | _RealtimeStateField[_StateValue]:
del owner
if instance is None:
return self
return getattr(instance._state, self._name)
def __set__(self, instance: Any, value: _StateValue) -> None:
setattr(instance._state, self._name, value)
class RealtimeStateOwner:
"""Declare the mutable state surface shared by input/output projectors."""
_state: RealtimeSessionState
_opened: bool = _RealtimeStateField()
_autostarted_default_session: bool = _RealtimeStateField()
_resume_only: bool = _RealtimeStateField()
_pending_outbound: asyncio.Queue[dict[str, object]] = _RealtimeStateField()
_held_realtime_payloads: list[dict[str, object]] = _RealtimeStateField()
_hold_realtime_output_until_session_created: bool = _RealtimeStateField()
_default_model: object | None = _RealtimeStateField()
_default_session_id: object | None = _RealtimeStateField()
_default_extra_body: dict[str, object] = _RealtimeStateField()
_input_audio_format: str = _RealtimeStateField()
_input_sample_rate_hz: int = _RealtimeStateField()
_output_audio_format: str = _RealtimeStateField()
_overlap_silence_rms: float = _RealtimeStateField()
_turn_detection: dict[str, object] | None = _RealtimeStateField()
_native_input_append: bool = _RealtimeStateField()
_pending_turn_detection_update: _PendingTurnDetectionUpdate | None = _RealtimeStateField()
_send_realtime_json: Any = _RealtimeStateField()
_initial_session_update: bool = _RealtimeStateField()
_input_speech_started: bool = _RealtimeStateField()
_response_states: dict[str | int, _RealtimeResponseState] = _RealtimeStateField()
_item_truncation_cursors: dict[str, tuple[int, int]] = _RealtimeStateField()
_active_response_id: str | None = _RealtimeStateField()
_last_response_id: str | None = _RealtimeStateField()
_conversation_items: dict[str, dict[str, object]] = _RealtimeStateField()
_last_conversation_item_id: str | None = _RealtimeStateField()
_output_sample_rate_hz: int | None = _RealtimeStateField()
_active_input_item_id: str | None = _RealtimeStateField()
_input_audio_buffer_has_audio: bool = _RealtimeStateField()
_input_audio_buffer_had_non_speech: bool = _RealtimeStateField()
_input_audio_buffer_transcript_parts: list[str] = _RealtimeStateField()
_turn_detection_configured: bool = _RealtimeStateField()
@@ -1,331 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable, Iterable, Mapping, MutableMapping
from dataclasses import dataclass, field
from importlib import import_module
from typing import Any, Protocol
class ServingRuntimeConfigError(ValueError):
"""A model serving plugin rejected client-visible runtime configuration."""
def __init__(self, message: str, *, code: str = "invalid_duplex_runtime_config") -> None:
super().__init__(message)
self.code = code
def reject_changed_runtime_value(
new_value: object,
current_value: object,
*,
message: str,
code: str,
error_cls: type[ServingRuntimeConfigError] = ServingRuntimeConfigError,
) -> None:
if new_value != current_value:
raise error_cls(message, code=code)
class PcmAppendReservation(Protocol):
operation_id: str
payload: dict[str, object] | None
@property
def active(self) -> bool: ...
@property
def byte_count(self) -> int: ...
def commit(self) -> None: ...
def rollback(self) -> None: ...
class PcmAppendBuffer(Protocol):
@property
def pending_byte_count(self) -> int: ...
def clear(self) -> None: ...
def clear_force_listen(self) -> None: ...
def has_pending(self) -> bool: ...
def has_reserved(self) -> bool: ...
def prepare_append(
self,
payload: dict[str, object],
*,
operation_id: str,
chunk_period_ms: int,
allow_emit: bool,
) -> PcmAppendReservation | None: ...
def prepare_commit(
self,
*,
operation_id: str,
chunk_period_ms: int,
) -> PcmAppendReservation: ...
def flush(self, *, chunk_period_ms: int) -> dict[str, object] | None: ...
class ServingRuntimeSessionState(Protocol):
audio_buffer: PcmAppendBuffer
input_since_commit: bool
speech_since_commit: bool
native_context_locked: bool
committed_audio_payload: dict[str, object] | None
committed_audio_operation_id: str | None
committed_audio_reserved_bytes: int
deferred_response_create: bool
deferred_precreate_response: bool
data_plane_task: asyncio.Task[None] | None
data_plane_restart_requested: bool
continuation_owner_id: str | None
continuation_units: int
pending_silence_task: asyncio.Task[bool] | None
pending_silence_owner_id: str | None
silence_continuation_scheduler: Callable[..., Awaitable[bool]] | None
def retain_committed_audio(
self,
payload: dict[str, object],
*,
operation_id: str | None,
reserved_bytes: int = 0,
) -> None: ...
def clear_committed_audio(self) -> int: ...
def clear_continuation(self) -> None: ...
class _TurnBasedPcmAppendBuffer:
"""Empty native-audio buffer for chat-fallback sessions.
Turn-based sessions keep input audio in ``DuplexSession`` and never use
the model-native append path. The runner still shares lifecycle and
cancellation code with native sessions, so it needs an inert buffer for
those common operations.
"""
@property
def pending_byte_count(self) -> int:
return 0
def clear(self) -> None:
return None
def clear_force_listen(self) -> None:
return None
def has_pending(self) -> bool:
return False
def has_reserved(self) -> bool:
return False
def prepare_append(
self,
payload: dict[str, object],
*,
operation_id: str,
chunk_period_ms: int,
allow_emit: bool,
) -> PcmAppendReservation | None:
del payload, operation_id, chunk_period_ms, allow_emit
raise RuntimeError("Model-native audio append is not enabled for this session")
def prepare_commit(
self,
*,
operation_id: str,
chunk_period_ms: int,
) -> PcmAppendReservation:
del operation_id, chunk_period_ms
raise RuntimeError("Model-native audio append is not enabled for this session")
def flush(self, *, chunk_period_ms: int) -> dict[str, object] | None:
del chunk_period_ms
return None
@dataclass(slots=True)
class TurnBasedServingSessionState:
"""Runner-local state for sessions served through chat fallback."""
audio_buffer: PcmAppendBuffer = field(default_factory=_TurnBasedPcmAppendBuffer)
input_since_commit: bool = False
speech_since_commit: bool = False
native_context_locked: bool = False
committed_audio_payload: dict[str, object] | None = None
committed_audio_operation_id: str | None = None
committed_audio_reserved_bytes: int = 0
deferred_response_create: bool = False
deferred_precreate_response: bool = False
data_plane_task: asyncio.Task[None] | None = None
data_plane_restart_requested: bool = False
continuation_owner_id: str | None = None
continuation_units: int = 0
pending_silence_task: asyncio.Task[bool] | None = None
pending_silence_owner_id: str | None = None
silence_continuation_scheduler: Callable[..., Awaitable[bool]] | None = None
def retain_committed_audio(
self,
payload: dict[str, object],
*,
operation_id: str | None,
reserved_bytes: int = 0,
) -> None:
self.committed_audio_payload = payload
self.committed_audio_operation_id = operation_id
self.committed_audio_reserved_bytes += max(0, int(reserved_bytes))
def clear_committed_audio(self) -> int:
reserved_bytes = self.committed_audio_reserved_bytes
self.committed_audio_payload = None
self.committed_audio_operation_id = None
self.committed_audio_reserved_bytes = 0
self.deferred_response_create = False
self.deferred_precreate_response = False
return reserved_bytes
def clear_continuation(self) -> None:
self.continuation_owner_id = None
self.continuation_units = 0
self.pending_silence_task = None
self.pending_silence_owner_id = None
class RuntimeDataPlane(Protocol):
def begin_request(self, request_id: str) -> None: ...
def is_terminal(self, request_id: str | None) -> bool: ...
def mark_terminal(self, request_id: str) -> None: ...
def close_stream(self, request_id: str) -> None: ...
def close_session(self, session_id: str, *, active_request_id: str | None = None) -> None: ...
def project(self, result: object, *, context: object | None = None) -> Iterable[dict[str, object]]: ...
class ServingRuntimeAdapter(Protocol):
adapter_id: str
session_states: MutableMapping[str, ServingRuntimeSessionState]
data_plane: RuntimeDataPlane
clean_response_done_prefix: str
interrupted_tts_prefix: str
private_runtime_config_keys: frozenset[str]
collect_outputs_on_append: bool
def create_session_state(self) -> ServingRuntimeSessionState: ...
def session_state(self, session_id: str) -> ServingRuntimeSessionState: ...
def remove_session_state(self, session_id: str) -> None: ...
def is_enabled(self, config: object) -> bool: ...
def capabilities(self, *, max_sessions: int) -> object: ...
def validate_client_extra_body(self, extra_body: object) -> None: ...
async def prepare_runtime_config(self, config: object, *, model_config: Any) -> dict[str, object]: ...
def runtime_config_for_update(
self,
config: object,
current: Mapping[str, object],
) -> dict[str, object]: ...
def data_plane_context(
self,
*,
epoch: int,
turn_id: int,
active_response_turn_id: int | None,
active_response_id: str | None,
auto_responds: bool,
response_format: str,
speed: float | None,
modalities: tuple[str, ...],
) -> object: ...
def load_serving_runtime_adapter(
path: str,
encode_audio,
) -> ServingRuntimeAdapter:
module_name, separator, attribute_name = path.rpartition(".")
if not separator:
raise ValueError(f"Invalid duplex serving runtime adapter path: {path!r}")
adapter_type = getattr(import_module(module_name), attribute_name)
return validate_serving_runtime_adapter(adapter_type(encode_audio))
def validate_serving_runtime_adapter(adapter: object) -> ServingRuntimeAdapter:
required_methods = (
"create_session_state",
"session_state",
"remove_session_state",
"is_enabled",
"capabilities",
"validate_client_extra_body",
"prepare_runtime_config",
"runtime_config_for_update",
"data_plane_context",
)
missing = [name for name in required_methods if not callable(getattr(adapter, name, None))]
if missing:
raise TypeError(f"Duplex serving runtime adapter is missing callable method(s): {', '.join(missing)}")
if not isinstance(getattr(adapter, "adapter_id", None), str) or not adapter.adapter_id:
raise TypeError("Duplex serving runtime adapter must declare adapter_id")
if not isinstance(getattr(adapter, "session_states", None), MutableMapping):
raise TypeError("Duplex serving runtime adapter must declare mutable session_states")
for prefix_name in ("clean_response_done_prefix", "interrupted_tts_prefix"):
if not isinstance(getattr(adapter, prefix_name, None), str):
raise TypeError(f"Duplex serving runtime adapter must declare {prefix_name}")
private_keys = getattr(adapter, "private_runtime_config_keys", None)
if not isinstance(private_keys, frozenset) or any(not isinstance(key, str) for key in private_keys):
raise TypeError("Duplex serving runtime adapter must declare private_runtime_config_keys as frozenset[str]")
data_plane = getattr(adapter, "data_plane", None)
if data_plane is None:
raise TypeError("Duplex serving runtime adapter must declare data_plane")
data_plane_methods = (
"begin_request",
"is_terminal",
"mark_terminal",
"close_stream",
"close_session",
"project",
)
missing_data_plane_methods = [name for name in data_plane_methods if not callable(getattr(data_plane, name, None))]
if missing_data_plane_methods:
raise TypeError(
"Duplex serving runtime adapter data_plane is missing callable method(s): "
+ ", ".join(missing_data_plane_methods)
)
return adapter # type: ignore[return-value]
def payload_turn_id(payload: object) -> int | None:
if not isinstance(payload, Mapping):
return None
return coerce_int(payload.get("duplex_turn_id", payload.get("model_turn_id")))
def coerce_int(value: object) -> int | None:
try:
return int(value) if value is not None else None
except (TypeError, ValueError):
return None
File diff suppressed because it is too large. Load diff
-528
View File
@@ -1,528 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import asyncio
import hashlib
import threading
import time
from collections.abc import Mapping
from dataclasses import dataclass, replace
from pathlib import Path
from typing import TYPE_CHECKING, Literal, Protocol
import numpy as np
from vllm.transformers_utils.repo_utils import try_get_local_file
if TYPE_CHECKING:
from vllm_omni.entrypoints.openai.audio_utils_mixin import StreamingAudioResampler
SILERO_VAD_REPO_ID = "istupakov/silero-vad-onnx"
SILERO_VAD_REVISION = "8b14476858ef240c50b3884bb38cc67290c1cc70"
SILERO_VAD_FILENAME = "silero_vad.onnx"
SILERO_VAD_SHA256 = "1a153a22f4509e292a94e67d6f9b85e8deb25b4988682b7e174c65279d8788e3"
SILERO_VAD_MIN_THRESHOLD = 0.15
SILERO_VAD_DEFAULT_MIN_SPEECH_DURATION_MS = 96
_SERVER_VAD_FIELDS = {
"type",
"threshold",
"prefix_padding_ms",
"silence_duration_ms",
"create_response",
"interrupt_response",
"min_speech_duration_ms",
}
@dataclass(frozen=True, slots=True)
class ServerVADConfig:
"""Validated OpenAI-compatible ``server_vad`` session configuration."""
type: Literal["server_vad"] = "server_vad"
threshold: float = 0.5
prefix_padding_ms: int = 300
silence_duration_ms: int = 500
create_response: bool = True
# Omission is resolved from runtime capabilities before the session is opened.
interrupt_response: bool | None = None
min_speech_duration_ms: int | None = None
@classmethod
def from_value(cls, value: object) -> ServerVADConfig:
if not isinstance(value, dict):
raise ValueError("turn_detection must be null or an object")
unknown = sorted(set(value) - _SERVER_VAD_FIELDS)
if unknown:
raise ValueError(f"Unknown server_vad field(s): {', '.join(unknown)}")
vad_type = value.get("type")
if vad_type != "server_vad":
raise ValueError("turn_detection.type must be 'server_vad'")
threshold = value.get("threshold", 0.5)
if isinstance(threshold, bool) or not isinstance(threshold, int | float) or not 0 <= threshold <= 1:
raise ValueError("server_vad.threshold must be a number between 0 and 1")
prefix_padding_ms = value.get("prefix_padding_ms", 300)
if isinstance(prefix_padding_ms, bool) or not isinstance(prefix_padding_ms, int) or prefix_padding_ms < 0:
raise ValueError("server_vad.prefix_padding_ms must be a non-negative integer")
silence_duration_ms = value.get("silence_duration_ms", 500)
if (
isinstance(silence_duration_ms, bool)
or not isinstance(silence_duration_ms, int)
or silence_duration_ms <= 0
):
raise ValueError("server_vad.silence_duration_ms must be a positive integer")
create_response = value.get("create_response", True)
if not isinstance(create_response, bool):
raise ValueError("server_vad.create_response must be a boolean")
interrupt_response = value.get("interrupt_response")
if "interrupt_response" in value and not isinstance(interrupt_response, bool):
raise ValueError("server_vad.interrupt_response must be a boolean")
min_speech_duration_ms = value.get("min_speech_duration_ms")
if min_speech_duration_ms is not None and (
isinstance(min_speech_duration_ms, bool)
or not isinstance(min_speech_duration_ms, int | float)
or not np.isfinite(float(min_speech_duration_ms))
or min_speech_duration_ms < 0
):
raise ValueError("server_vad.min_speech_duration_ms must be a non-negative number")
return cls(
type=vad_type,
threshold=float(threshold),
prefix_padding_ms=prefix_padding_ms,
silence_duration_ms=silence_duration_ms,
create_response=create_response,
interrupt_response=interrupt_response,
min_speech_duration_ms=(int(min_speech_duration_ms) if min_speech_duration_ms is not None else None),
)
def as_dict(self) -> dict[str, object]:
result: dict[str, object] = {
"type": self.type,
"threshold": self.threshold,
"prefix_padding_ms": self.prefix_padding_ms,
"silence_duration_ms": self.silence_duration_ms,
"create_response": self.create_response,
}
if self.interrupt_response is not None:
result["interrupt_response"] = self.interrupt_response
if self.min_speech_duration_ms is not None:
result["min_speech_duration_ms"] = self.min_speech_duration_ms
return result
def parse_session_turn_detection(
payload: Mapping[str, object],
) -> tuple[bool, ServerVADConfig | None]:
"""Extract and validate OpenAI-compatible turn detection aliases."""
configured_values: list[tuple[str, object]] = []
if "turn_detection" in payload:
configured_values.append(("turn_detection", payload["turn_detection"]))
audio = payload.get("audio")
if isinstance(audio, Mapping):
audio_input = audio.get("input")
if isinstance(audio_input, Mapping) and "turn_detection" in audio_input:
configured_values.append(("audio.input.turn_detection", audio_input["turn_detection"]))
if not configured_values:
return False, None
first_path, first_value = configured_values[0]
first_config = None if first_value is None else ServerVADConfig.from_value(first_value)
for field_path, value in configured_values[1:]:
config = None if value is None else ServerVADConfig.from_value(value)
if first_config is not None and config is not None:
# An omitted option must not conflict with an explicit alias value.
if first_config.interrupt_response is None:
first_config = replace(first_config, interrupt_response=config.interrupt_response)
if config.interrupt_response is None:
config = replace(config, interrupt_response=first_config.interrupt_response)
if config != first_config:
raise ValueError(f"{first_path} and {field_path} must not specify conflicting values")
return True, first_config
class SpeechDetectorBackend(Protocol):
"""Detector contract; per-stream state is owned by the pipeline."""
frame_samples: int
def new_state(self) -> object: ...
def infer(self, frame: np.ndarray, state: object) -> tuple[float, object]: ...
class SpeechDetectorBackendProvider(Protocol):
def get(self) -> SpeechDetectorBackend: ...
@dataclass(frozen=True, slots=True)
class SpeechEndpointDecision:
speech_started: bool = False
speech_stopped: bool = False
audio_start_ms: int | None = None
audio_end_ms: int | None = None
endpoint_delay_ms: int | None = None
class SpeechEndpointPolicy(Protocol):
@property
def speech_active(self) -> bool: ...
def update(
self,
probability: float,
*,
frame_start_sample: int,
frame_samples: int,
) -> SpeechEndpointDecision: ...
def reset(self) -> None: ...
class ThresholdEndpointPolicy:
"""Apply threshold and trailing-silence endpoint rules."""
def __init__(self, config: ServerVADConfig, *, sample_rate_hz: int) -> None:
self.config = config
self.sample_rate_hz = sample_rate_hz
self._speech_active = False
self._candidate_samples = 0
self._candidate_start_sample: int | None = None
self._silence_samples = 0
@property
def speech_active(self) -> bool:
return self._speech_active
def update(
self,
probability: float,
*,
frame_start_sample: int,
frame_samples: int,
) -> SpeechEndpointDecision:
if probability >= self.config.threshold:
self._silence_samples = 0
if not self._speech_active:
if self._candidate_samples == 0:
self._candidate_start_sample = frame_start_sample
self._candidate_samples += frame_samples
min_speech_duration_ms = self.config.min_speech_duration_ms or 0
min_speech_samples = max(1, round(min_speech_duration_ms * self.sample_rate_hz / 1000))
if self._candidate_samples < min_speech_samples:
return SpeechEndpointDecision()
self._speech_active = True
detected_start_sample = (
self._candidate_start_sample if self._candidate_start_sample is not None else frame_start_sample
)
detected_start_ms = round(detected_start_sample * 1000 / self.sample_rate_hz)
self._candidate_samples = 0
self._candidate_start_sample = None
return SpeechEndpointDecision(
speech_started=True,
audio_start_ms=max(0, detected_start_ms - self.config.prefix_padding_ms),
)
return SpeechEndpointDecision()
if not self._speech_active:
self._candidate_samples = 0
self._candidate_start_sample = None
return SpeechEndpointDecision()
# Match Silero v6.2's streaming VAD hysteresis: activation uses the
# configured threshold, while potential speech end starts only below
# ``max(threshold - 0.15, 0.01)``. Once a silence candidate exists,
# intermediate frames keep elapsed time moving but cannot themselves
# close the turn.
negative_threshold = max(self.config.threshold - SILERO_VAD_MIN_THRESHOLD, 0.01)
below_negative_threshold = probability < negative_threshold
if not below_negative_threshold and self._silence_samples == 0:
return SpeechEndpointDecision()
self._silence_samples += frame_samples
if not below_negative_threshold:
return SpeechEndpointDecision()
silence_limit = max(1, round(self.config.silence_duration_ms * self.sample_rate_hz / 1000))
if self._silence_samples < silence_limit:
return SpeechEndpointDecision()
# OpenAI defines ``audio_end_ms`` as the end of the audio sent to the
# model, including the trailing silence used for endpoint detection.
audio_end_sample = frame_start_sample + frame_samples
endpoint_delay_ms = round(self._silence_samples * 1000 / self.sample_rate_hz)
self.reset()
return SpeechEndpointDecision(
speech_stopped=True,
audio_end_ms=max(0, round(audio_end_sample * 1000 / self.sample_rate_hz)),
endpoint_delay_ms=endpoint_delay_ms,
)
def reset(self) -> None:
self._speech_active = False
self._candidate_samples = 0
self._candidate_start_sample = None
self._silence_samples = 0
@dataclass(frozen=True, slots=True)
class ServerVADFrame:
samples: np.ndarray
decision: SpeechEndpointDecision
@dataclass(frozen=True, slots=True)
class ServerVADBatch:
frames: tuple[ServerVADFrame, ...]
inference_ms: float
class ServerVADPipeline:
"""Frame continuous 16 kHz audio and apply acoustic endpointing.
The pipeline retains only input-resampling residuals, a partial frame,
detector state, and timing counters. Commit-eligible prefix and utterance
audio remain session-owned.
"""
sample_rate_hz = 16_000
def __init__(
self,
backend: SpeechDetectorBackend,
config: ServerVADConfig,
*,
endpoint_policy: SpeechEndpointPolicy | None = None,
) -> None:
self.backend = backend
self.config = config
self.endpoint_policy = endpoint_policy or ThresholdEndpointPolicy(
config,
sample_rate_hz=self.sample_rate_hz,
)
self._input_resampler: StreamingAudioResampler | None = None
self._source_sample_rate_hz: int | None = None
self._scratch = np.empty(0, dtype=np.float32)
self._detector_state = backend.new_state()
self._processed_samples = 0
self._stream_start_ms = 0
@property
def speech_active(self) -> bool:
return self.endpoint_policy.speech_active
@property
def source_sample_rate_hz(self) -> int | None:
return self._source_sample_rate_hz
@property
def scratch_bytes(self) -> int:
resampler_bytes = self._input_resampler.scratch_bytes if self._input_resampler is not None else 0
return int(self._scratch.nbytes) + resampler_bytes
async def push_pcm16(
self,
samples: bytes,
*,
source_sample_rate_hz: int,
) -> ServerVADBatch:
"""Normalize chunked mono PCM16 input and run endpoint detection."""
if isinstance(source_sample_rate_hz, bool) or source_sample_rate_hz not in {16_000, 24_000}:
raise ValueError("server_vad PCM16 input sample rate must be 16000 or 24000 Hz")
if len(samples) % np.dtype("<i2").itemsize:
raise ValueError("server_vad PCM16 input contains an incomplete sample")
pcm16 = np.frombuffer(samples, dtype="<i2")
if self._source_sample_rate_hz is not None and source_sample_rate_hz != self._source_sample_rate_hz:
raise ValueError("server_vad input sample rate cannot change within a continuous audio stream")
if pcm16.size and self._source_sample_rate_hz is None:
from vllm_omni.entrypoints.openai.audio_utils_mixin import StreamingAudioResampler
self._input_resampler = (
None
if source_sample_rate_hz == self.sample_rate_hz
else StreamingAudioResampler(source_sample_rate_hz, self.sample_rate_hz)
)
self._source_sample_rate_hz = source_sample_rate_hz
normalized = np.ascontiguousarray(pcm16, dtype=np.float32) * np.float32(1.0 / 32768.0)
if self._input_resampler is not None:
normalized = self._input_resampler.process(normalized)
return await self.push(normalized)
async def push(self, samples: np.ndarray) -> ServerVADBatch:
normalized = np.ascontiguousarray(samples, dtype=np.float32).reshape(-1)
return await asyncio.to_thread(self._push_sync, normalized)
def _push_sync(self, samples: np.ndarray) -> ServerVADBatch:
started_at = time.perf_counter()
if self._scratch.size:
samples = np.concatenate((self._scratch, samples))
frame_samples = int(self.backend.frame_samples)
complete_samples = samples.size - samples.size % frame_samples
# Retained state must not keep the whole input chunk alive through a view.
self._scratch = samples[complete_samples:].copy()
results: list[ServerVADFrame] = []
for offset in range(0, complete_samples, frame_samples):
frame = np.ascontiguousarray(samples[offset : offset + frame_samples], dtype=np.float32)
frame_start = self._processed_samples
probability, self._detector_state = self.backend.infer(frame, self._detector_state)
probability = min(1.0, max(0.0, float(probability)))
decision = self.endpoint_policy.update(
probability,
frame_start_sample=frame_start,
frame_samples=frame_samples,
)
if decision.speech_started and decision.audio_start_ms is not None:
# Prefix audio before the most recent reset is no longer available.
decision = replace(decision, audio_start_ms=max(self._stream_start_ms, decision.audio_start_ms))
self._processed_samples += frame_samples
results.append(
ServerVADFrame(
samples=frame,
decision=decision,
)
)
return ServerVADBatch(
frames=tuple(results),
inference_ms=(time.perf_counter() - started_at) * 1000,
)
def reset(self) -> None:
"""Discard stream state while preserving the session-relative audio clock."""
self._stream_start_ms = round(self._processed_samples * 1000 / self.sample_rate_hz)
self._input_resampler = None
self._source_sample_rate_hz = None
self._scratch = np.empty(0, dtype=np.float32)
self._detector_state = self.backend.new_state()
self.endpoint_policy.reset()
@dataclass(frozen=True, slots=True)
class _SileroVADState:
model_state: np.ndarray
context: np.ndarray
class SileroVADBackend:
"""Shared ONNX Runtime Silero v6.2 detector running on CPU."""
sample_rate_hz = 16_000
frame_samples = 512
context_samples = 64
model_state_shape = (2, 1, 128)
def __init__(self, model_path: str | Path) -> None:
try:
import onnxruntime as ort
except ImportError as exc: # pragma: no cover - platform packaging supplies ORT.
raise RuntimeError("server_vad requires ONNX Runtime") from exc
session_options = ort.SessionOptions()
session_options.inter_op_num_threads = 1
session_options.intra_op_num_threads = 1
self.model_path = Path(model_path)
self._session = ort.InferenceSession(
str(self.model_path),
providers=["CPUExecutionProvider"],
sess_options=session_options,
)
input_names = {item.name for item in self._session.get_inputs()}
if "input" not in input_names or "sr" not in input_names or "state" not in input_names:
raise RuntimeError(f"Unsupported Silero ONNX input contract: {sorted(input_names)}")
self._warm_up()
def _warm_up(self) -> None:
self.infer(np.zeros(self.frame_samples, dtype=np.float32), self.new_state())
def new_state(self) -> _SileroVADState:
return _SileroVADState(
model_state=np.zeros(self.model_state_shape, dtype=np.float32),
context=np.zeros((1, self.context_samples), dtype=np.float32),
)
def infer(self, frame: np.ndarray, state: object) -> tuple[float, object]:
if not isinstance(state, _SileroVADState):
raise TypeError("Silero detector state must be created by SileroVADBackend.new_state()")
model_state = np.ascontiguousarray(state.model_state, dtype=np.float32)
context = np.ascontiguousarray(state.context, dtype=np.float32)
if model_state.shape != self.model_state_shape:
raise ValueError(f"Silero model state must have shape {self.model_state_shape}, got {model_state.shape}")
expected_context_shape = (1, self.context_samples)
if context.shape != expected_context_shape:
raise ValueError(f"Silero context must have shape {expected_context_shape}, got {context.shape}")
audio = np.ascontiguousarray(frame, dtype=np.float32).reshape(1, -1)
if audio.shape[1] != self.frame_samples:
raise ValueError(
f"Silero detector frame must contain exactly {self.frame_samples} samples, got {audio.shape[1]}"
)
model_input = np.concatenate((context, audio), axis=1)
inputs = {
"input": model_input,
"state": model_state,
"sr": np.asarray(self.sample_rate_hz, dtype=np.int64),
}
# ONNX Runtime permits concurrent Run calls on one CPU session. Stream
# state is explicit, so independent pipelines can safely share the session.
output = self._session.run(None, inputs)
if len(output) < 2:
raise RuntimeError("Silero ONNX model did not return probability and model state")
probability = float(np.asarray(output[0]).reshape(-1)[0])
next_state = _SileroVADState(
model_state=np.ascontiguousarray(output[1], dtype=np.float32),
context=np.ascontiguousarray(model_input[:, -self.context_samples :], dtype=np.float32),
)
return probability, next_state
class SileroVADBackendProvider:
"""Resolve, verify, and load one Silero model instance per process."""
def __init__(self, *, model_path: str | None = None) -> None:
self.model_path = model_path
self._backend: SileroVADBackend | None = None
self._lock = threading.Lock()
def get(self) -> SileroVADBackend:
if self._backend is not None:
return self._backend
with self._lock:
if self._backend is None:
path = self._resolve_local_artifact()
self._verify_checksum(path)
self._backend = SileroVADBackend(path)
return self._backend
def _resolve_local_artifact(self) -> Path:
if self.model_path:
path = Path(self.model_path).expanduser()
if path.is_file():
return path
raise RuntimeError(f"Configured Silero VAD model does not exist: {path}")
cached = try_get_local_file(
model=SILERO_VAD_REPO_ID,
file_name=SILERO_VAD_FILENAME,
revision=SILERO_VAD_REVISION,
)
if isinstance(cached, Path) and cached.is_file():
return cached
raise RuntimeError(
"Silero VAD artifact is not available locally. Pre-download the pinned artifact "
"or configure duplex_session.server_vad_model_path."
)
def _verify_checksum(self, path: Path) -> None:
digest = hashlib.sha256(path.read_bytes()).hexdigest()
if digest != SILERO_VAD_SHA256:
raise RuntimeError(f"Silero VAD checksum mismatch for {path}: expected {SILERO_VAD_SHA256}, got {digest}")
File diff suppressed because it is too large. Load diff
@@ -180,7 +180,6 @@ class DuplexEventJournal:
@dataclass(frozen=True)
class DuplexSessionAttachmentCreated:
session_id: str
incarnation: int
attachment_generation: int
resume_token: ResumeToken = field(repr=False)
@@ -188,7 +187,6 @@ class DuplexSessionAttachmentCreated:
@dataclass(frozen=True)
class DuplexSessionResumeResult:
session_id: str
incarnation: int
attachment_generation: int
resume_token: ResumeToken = field(repr=False)
replay_entries: tuple[JournalEntry, ...] = ()
@@ -198,14 +196,12 @@ class DuplexSessionResumeResult:
@dataclass
class _DuplexSessionAttachmentState:
session_id: str
incarnation: int
credential: DuplexResumeCredential
journal: DuplexEventJournal
attachment: DuplexTransportAttachment | None
attachment_generation: int
outbound_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
recovery_token_digest: bytes | None = field(default=None, repr=False)
grace_task: asyncio.Task[None] | None = field(default=None, repr=False)
class DuplexSessionAttachmentRegistry:
@@ -214,18 +210,14 @@ class DuplexSessionAttachmentRegistry:
*,
replay_ttl_s: float,
replay_max_bytes_per_session: int,
disconnect_grace_s: float = 30.0,
clock: Callable[[], float] | None = None,
) -> None:
if replay_ttl_s <= 0:
raise ValueError("replay_ttl_s must be positive")
if replay_max_bytes_per_session <= 0:
raise ValueError("replay_max_bytes_per_session must be positive")
if disconnect_grace_s <= 0:
raise ValueError("disconnect_grace_s must be positive")
self._replay_ttl_s = replay_ttl_s
self._replay_max_bytes_per_session = replay_max_bytes_per_session
self._disconnect_grace_s = disconnect_grace_s
self._clock = clock or time.monotonic
self._sessions: dict[str, _DuplexSessionAttachmentState] = {}
self._lock = asyncio.Lock()
@@ -237,7 +229,6 @@ class DuplexSessionAttachmentRegistry:
self,
session_id: str,
*,
incarnation: int,
send: Callable[[dict[str, object]], Awaitable[None]],
close: Callable[[str], Awaitable[None]],
) -> DuplexSessionAttachmentCreated:
@@ -248,7 +239,6 @@ class DuplexSessionAttachmentRegistry:
generation = 1
self._sessions[session_id] = _DuplexSessionAttachmentState(
session_id=session_id,
incarnation=incarnation,
credential=DuplexResumeCredential.from_token(token),
journal=DuplexEventJournal(
max_bytes=self._replay_max_bytes_per_session,
@@ -264,7 +254,6 @@ class DuplexSessionAttachmentRegistry:
)
return DuplexSessionAttachmentCreated(
session_id=session_id,
incarnation=incarnation,
attachment_generation=generation,
resume_token=token,
)
@@ -309,33 +298,39 @@ class DuplexSessionAttachmentRegistry:
async with self._lock:
return self._require(session_id).journal.acknowledge(sequence)
async def detach(
self,
session_id: str,
*,
attachment_generation: int,
on_grace_expired: Callable[[], Awaitable[None]] | None = None,
) -> bool:
async def detach(self, session_id: str, *, attachment_generation: int | None = None) -> bool:
"""Drop the current transport; the engine lease owns the disconnect grace.
``attachment_generation`` names the connection asking to detach, so a
socket that already lost a takeover cannot detach the winner. ``None``
means "whichever connection is attached right now" and is for callers
that only know the session (the outbound pump, whose send just failed).
Returns whether this call is the one that detached: an already-detached
session answers ``False`` so a second disconnect signal for the same
socket cannot restart the engine's disconnect grace window.
"""
async with self._lock:
state = self._sessions.get(session_id)
if state is None or state.attachment_generation != attachment_generation:
if state is None or state.attachment is None:
return False
if attachment_generation is not None and state.attachment_generation != attachment_generation:
return False
state.attachment = None
if state.grace_task is not None:
state.grace_task.cancel()
state.grace_task = (
asyncio.create_task(
self._run_disconnect_grace(
state,
attachment_generation=attachment_generation,
callback=on_grace_expired,
)
)
if on_grace_expired is not None
else None
)
return True
async def has_attachment(self, session_id: str) -> bool:
"""Whether some connection is attached right now, whoever it is.
A resume that failed to activate has no generation of its own, so it
cannot ask ``is_current_attachment``. What it needs to know before
rolling the engine lease back into its disconnect grace is only whether
it would be rolling back somebody else's live attachment.
"""
async with self._lock:
state = self._sessions.get(session_id)
return state is not None and state.attachment is not None
async def is_current_attachment(self, session_id: str, attachment_generation: int) -> bool:
async with self._lock:
state = self._sessions.get(session_id)
@@ -349,25 +344,19 @@ class DuplexSessionAttachmentRegistry:
self,
session_id: str,
*,
incarnation: int,
resume_token: str,
last_received_server_event_seq: int,
) -> None:
"""Validate transport credentials before any engine resume control."""
async with self._lock:
state = self._require(session_id)
self._validate_resume_identity(
state,
incarnation=incarnation,
resume_token=resume_token,
)
self._validate_resume_identity(state, resume_token=resume_token)
state.journal.replay_after(last_received_server_event_seq)
async def resume(
self,
session_id: str,
*,
incarnation: int,
resume_token: str,
last_received_server_event_seq: int,
send: Callable[[dict[str, object]], Awaitable[None]],
@@ -380,18 +369,11 @@ class DuplexSessionAttachmentRegistry:
async with self._lock:
if self._sessions.get(session_id) is not state:
raise KeyError(f"unknown duplex attachment session: {session_id}")
used_recovery = self._validate_resume_identity(
state,
incarnation=incarnation,
resume_token=resume_token,
)
used_recovery = self._validate_resume_identity(state, resume_token=resume_token)
replay_entries = state.journal.replay_after(last_received_server_event_seq)
accepted_token_digest = (
state.recovery_token_digest if used_recovery else bytes(state.credential.token_digest)
)
if state.grace_task is not None:
state.grace_task.cancel()
state.grace_task = None
state.recovery_token_digest = None
rotated_token = state.credential.rotate()
replaced = state.attachment
@@ -407,53 +389,53 @@ class DuplexSessionAttachmentRegistry:
await send(dict(activation_payload_factory(rotated_token, attachment_generation)))
for entry in replay_entries:
await send(dict(entry.payload))
except Exception:
async with self._lock:
if (
self._sessions.get(session_id) is state
and state.attachment_generation == attachment_generation
):
state.attachment = None
state.recovery_token_digest = accepted_token_digest
except (Exception, asyncio.CancelledError):
# CancelledError derives from BaseException, so an
# ``except Exception`` here would let a cancellation during
# activation or replay skip the rollback: the dead
# attachment would stay current while the token it rotated
# past is gone, leaving the session attached to an unusable
# transport with no way back. Both failures take the same
# path deliberately, so they cannot drift apart.
await self._rollback_resume(
session_id,
state=state,
attachment_generation=attachment_generation,
accepted_token_digest=accepted_token_digest,
)
raise
return DuplexSessionResumeResult(
session_id=session_id,
incarnation=incarnation,
attachment_generation=attachment_generation,
resume_token=rotated_token,
replay_entries=replay_entries,
replaced_attachment=replaced,
)
async def _rollback_resume(
self,
session_id: str,
*,
state: _DuplexSessionAttachmentState,
attachment_generation: int,
accepted_token_digest: bytes,
) -> None:
"""Undo a resume whose activation never reached the client.
Generation-checked: a later resume that already took over must keep its
attachment. Restoring ``recovery_token_digest`` is what lets the caller
retry with the token it presented, which ``resume`` had rotated past.
"""
async with self._lock:
if self._sessions.get(session_id) is state and state.attachment_generation == attachment_generation:
state.attachment = None
state.recovery_token_digest = accepted_token_digest
async def close(self, session_id: str) -> DuplexTransportAttachment | None:
async with self._lock:
state = self._sessions.pop(session_id, None)
if state is not None and state.grace_task is not None:
state.grace_task.cancel()
return state.attachment if state is not None else None
async def _run_disconnect_grace(
self,
state: _DuplexSessionAttachmentState,
*,
attachment_generation: int,
callback: Callable[[], Awaitable[None]] | None,
) -> None:
try:
await asyncio.sleep(self._disconnect_grace_s)
except asyncio.CancelledError:
return
async with self._lock:
if (
self._sessions.get(state.session_id) is not state
or state.attachment is not None
or state.attachment_generation != attachment_generation
):
return
state.grace_task = None
if callback is not None:
await callback()
def _require(self, session_id: str) -> _DuplexSessionAttachmentState:
state = self._sessions.get(session_id)
if state is None:
@@ -461,14 +443,7 @@ class DuplexSessionAttachmentRegistry:
return state
@staticmethod
def _validate_resume_identity(
state: _DuplexSessionAttachmentState,
*,
incarnation: int,
resume_token: str,
) -> bool:
if incarnation != state.incarnation:
raise ValueError(f"duplex attachment incarnation mismatch: expected {state.incarnation}, got {incarnation}")
def _validate_resume_identity(state: _DuplexSessionAttachmentState, *, resume_token: str) -> bool:
if state.credential.verify(resume_token):
return False
recovery_digest = state.recovery_token_digest
File diff suppressed because it is too large. Load diff
+4 -3
View File
@@ -43,10 +43,11 @@ async def _warmup_duplex_realtime(app, args, warmup_frames: int) -> None:
model_name = served
else:
model_name = args.model
adapter = getattr(getattr(app.state, "openai_serving_duplex", None), "_serving_runtime_adapter", None)
frame_samples = int(getattr(adapter, "silence_continuation_samples", 16000))
# One silence unit as the engine-side plugin defines it (DuplexOmniEngine.plugin).
plugin = getattr(getattr(app.state.engine_client, "engine", None), "plugin", None)
frame_samples = int(getattr(plugin, "silence_continuation_samples", 16000))
silence = base64.b64encode(bytes(frame_samples * 4)).decode("ascii")
from vllm_omni.experimental.fullduplex.client import build_realtime_url
from vllm_omni.clients.duplex import build_realtime_url
url = (
build_realtime_url(f"ws://127.0.0.1:{args.port}/v1/realtime", model_name, autostart=False)
+42 -248
View File
@@ -1,266 +1,60 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""WebSocket transport helpers for the duplex Realtime handler.
The ordered session mailbox and the per-session task handles that used to be
defined here now live engine-side (``vllm_omni.engine.duplex.session.runner``).
"""
from __future__ import annotations
import asyncio
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any
from collections.abc import Awaitable, Callable
from contextlib import suppress
from fastapi import WebSocketDisconnect
from fastapi import WebSocket, WebSocketDisconnect
INPUT_EVENTS = frozenset(
{
"input.text.append",
"input_audio_buffer.append",
"input.commit",
"input_audio_buffer.commit",
"response.create",
}
)
#: Largest client frame accepted before it is parsed (base64 audio + video frames).
MAX_EVENT_BYTES = 15 * 1024 * 1024
_INPUT_EVENT_ALIASES = {
"signal_turn": "turn.signal",
"close_session": "session.close",
"audio.playback_ack": "playback.ack",
"input_text.append": "input.text.append",
"push_text": "input.text.append",
"input.audio.append": "input_audio_buffer.append",
"push_chunk": "input_audio_buffer.append",
}
_WAV_AUDIO_ALIASES = frozenset({"input.audio.append", "push_chunk"})
SendJson = Callable[[dict[str, object]], Awaitable[None]]
CloseFn = Callable[[str], Awaitable[None]]
def normalize_duplex_input_event(event: dict[str, object]) -> dict[str, object]:
"""Normalize compatibility aliases before an event enters the mailbox."""
event_type = event.get("type")
if not isinstance(event_type, str):
return event
canonical_type = _INPUT_EVENT_ALIASES.get(event_type)
if canonical_type is None:
return event
normalized = dict(event)
normalized["type"] = canonical_type
if event_type in _WAV_AUDIO_ALIASES:
normalized.setdefault("format", "wav")
return normalized
async def receive_text_with_timeout(websocket: WebSocket, timeout_s: float | None) -> str | None:
"""Receive one text frame; ``None`` on idle timeout. Disconnects propagate."""
if timeout_s is None or timeout_s <= 0:
return await websocket.receive_text()
try:
return await asyncio.wait_for(websocket.receive_text(), timeout=timeout_s)
except TimeoutError:
return None
MODEL_OUTPUT_EVENTS = frozenset(
{
"response.created",
"response.listen",
"response.speak",
"response.output_item.added",
"response.content_part.added",
"response.output_audio.delta",
"response.output_audio.done",
"response.output_text.delta",
"response.output_text.done",
"response.text.delta",
"response.text.done",
"response.message",
"response.output_item.done",
"response.content_part.done",
"response.done",
"runtime.control",
}
)
DOMAIN_TERMINAL_EVENTS = frozenset(
{
"response.done",
"response.listen",
"audio.cancelled",
"input.cancelled",
"session.closed",
}
)
def attachment_callbacks(websocket: WebSocket) -> tuple[SendJson, CloseFn]:
"""``send`` / ``close`` callables for a ``DuplexSessionAttachmentRegistry`` attachment.
A send on a socket that already closed surfaces as ``WebSocketDisconnect``
so the caller's disconnect path runs instead of a generic failure.
"""
def is_input_event(event_type: object) -> bool:
return isinstance(event_type, str) and event_type in INPUT_EVENTS
@dataclass(frozen=True, slots=True)
class DuplexAppendTaskMeta:
epoch: int
mode: str
final: bool
response_bound: bool
@dataclass
class DuplexSessionTasks:
"""Connection-independent task handles for one resumable session."""
native_append_tasks: dict[asyncio.Task[bool], DuplexAppendTaskMeta] = field(default_factory=dict)
native_append_tail: asyncio.Task[bool] | None = None
active_response_task: asyncio.Task[None] | None = None
def track_append_task(
self,
task: asyncio.Task[bool],
*,
epoch: int,
mode: str,
final: bool,
response_bound: bool,
) -> None:
self.native_append_tasks[task] = DuplexAppendTaskMeta(epoch, mode, final, response_bound)
task.add_done_callback(self.native_append_tasks.pop)
def has_response_bound_append_tasks(self) -> bool:
return any(meta.response_bound for meta in self.native_append_tasks.values())
async def cancel_append_tasks(self, timeout_s: float = 0.25, *, response_bound_only: bool = False) -> bool:
tasks = [
task for task, meta in self.native_append_tasks.items() if not response_bound_only or meta.response_bound
]
if not tasks:
return False
cancelled_tail = self.native_append_tail if self.native_append_tail in tasks else None
for task in tasks:
task.cancel()
async def attachment_send(payload: dict[str, object]) -> None:
try:
await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), timeout=timeout_s)
except TimeoutError:
pass
if cancelled_tail is not None and self.native_append_tail is cancelled_tail:
self.native_append_tail = None
return True
await websocket.send_json(payload)
except RuntimeError as exc:
message = str(exc)
if "after sending 'websocket.close'" in message or "response already completed" in message:
raise WebSocketDisconnect(code=1006) from exc
raise
async def attachment_close(reason: str) -> None:
close = getattr(websocket, "close", None)
if callable(close):
with suppress(Exception):
await close(code=1000, reason=reason)
return attachment_send, attachment_close
@dataclass
class DuplexWebSocketActor:
"""Own ordered WebSocket I/O queues, but no domain identity."""
websocket: Any
current_epoch: Callable[[], int | None] | None = None
session_closed: Callable[[], bool] | None = None
output_queue: asyncio.Queue[dict[str, object] | None] = field(default_factory=asyncio.Queue)
mailbox: asyncio.Queue[dict[str, object]] = field(default_factory=asyncio.Queue)
outbound_protocol: Any | None = None
tasks: DuplexSessionTasks = field(default_factory=DuplexSessionTasks)
closing: bool = False
close_reason: str | None = None
stale_output_dropped: int = 0
_queued_input_events: int = 0
@property
def native_append_tasks(self) -> dict[asyncio.Task[bool], DuplexAppendTaskMeta]:
return self.tasks.native_append_tasks
@property
def active_response_task(self) -> asyncio.Task[None] | None:
return self.tasks.active_response_task
@active_response_task.setter
def active_response_task(self, task: asyncio.Task[None] | None) -> None:
self.tasks.active_response_task = task
@property
def native_append_tail(self) -> asyncio.Task[bool] | None:
return self.tasks.native_append_tail
@native_append_tail.setter
def native_append_tail(self, task: asyncio.Task[bool] | None) -> None:
self.tasks.native_append_tail = task
async def enqueue_event(self, event: dict[str, object]) -> None:
if is_input_event(event.get("type")):
self._queued_input_events += 1
await self.mailbox.put(event)
async def next_event(self) -> dict[str, object]:
event = await self.mailbox.get()
if is_input_event(event.get("type")):
self._queued_input_events = max(0, self._queued_input_events - 1)
self.mailbox.task_done()
return event
def has_queued_input_events(self) -> bool:
return self._queued_input_events > 0
async def send_json(self, payload: dict[str, object]) -> None:
await self.output_queue.put(payload)
async def close_writer(self) -> None:
await self.output_queue.put(None)
async def writer_loop(self) -> None:
while True:
payload = await self.output_queue.get()
try:
if payload is None:
return
raw_realtime = payload.pop("_realtime_raw", False) is True
if not raw_realtime and self._is_stale_model_output(payload):
self.stale_output_dropped += 1
continue
try:
if raw_realtime:
await self.websocket.send_json(payload)
elif self.outbound_protocol is not None:
for projected in self.outbound_protocol.encode_outbound_event(payload):
await self.websocket.send_json(projected)
else:
await self.websocket.send_json(payload)
except (WebSocketDisconnect, RuntimeError):
return
finally:
self.output_queue.task_done()
def _is_stale_model_output(self, payload: dict[str, object]) -> bool:
event_type = payload.get("type")
if event_type in DOMAIN_TERMINAL_EVENTS:
return False
if event_type not in MODEL_OUTPUT_EVENTS:
return False
if self.closing and event_type not in {"response.listen", "runtime.control"}:
return True
expected_epoch = self.current_epoch() if self.current_epoch is not None else None
if (
self.session_closed is not None
and self.session_closed()
and event_type
not in {
"response.listen",
"runtime.control",
}
):
return True
epoch = payload.get("epoch")
return isinstance(epoch, int) and isinstance(expected_epoch, int) and epoch != expected_epoch
def track_append_task(
self,
task: asyncio.Task[bool],
*,
epoch: int,
mode: str,
final: bool,
response_bound: bool,
) -> None:
self.tasks.track_append_task(
task,
epoch=epoch,
mode=mode,
final=final,
response_bound=response_bound,
)
def has_response_bound_append_tasks(self) -> bool:
return self.tasks.has_response_bound_append_tasks()
async def cancel_append_tasks(self, timeout_s: float = 0.25, *, response_bound_only: bool = False) -> bool:
return await self.tasks.cancel_append_tasks(timeout_s, response_bound_only=response_bound_only)
__all__ = [
"DOMAIN_TERMINAL_EVENTS",
"DuplexAppendTaskMeta",
"DuplexSessionTasks",
"DuplexWebSocketActor",
"is_input_event",
]
__all__ = ["MAX_EVENT_BYTES", "CloseFn", "SendJson", "attachment_callbacks", "receive_text_with_timeout"]