Merge main and preserve event-driven defaults in shared engine bases
Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
commit
d2bb944863
371 files changed
+43235
-38379
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Engine-side helpers for the full-duplex runtime."""
|
||||
"""Engine-resident full-duplex sessions: typed commands/events, the merged session
|
||||
state, the per-session runner, the session manager and the model plugin contract."""
|
||||
@@ -0,0 +1,218 @@
|
||||
# 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
|
||||
|
||||
from vllm_omni.utils.audio_resample import StreamingAudioResampler
|
||||
|
||||
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
|
||||
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,324 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Typed commands accepted by a duplex session.
|
||||
|
||||
``DuplexSessionHandle.submit()`` takes one of these; the websocket handler and
|
||||
``InlineDuplexClient`` build them with :func:`command_from_realtime` from the
|
||||
OpenAI Realtime client event vocabulary. Every command can also render the
|
||||
session-internal mailbox payload (``payload()``), which is the dictionary
|
||||
vocabulary the session runner bodies were written against.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field, fields
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.engine.duplex.realtime_commands import RealtimeInputDefaults
|
||||
|
||||
|
||||
class DuplexCommandError(ValueError):
|
||||
"""A client payload could not be turned into a command."""
|
||||
|
||||
def __init__(self, message: str, *, code: str = "bad_event", event_id: str | None = None) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.event_id = event_id
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class DuplexCommand:
|
||||
#: Mailbox event type this command renders to (see ``payload()``).
|
||||
type: ClassVar[str] = ""
|
||||
#: Client correlation id (OpenAI ``event_id``), echoed on error events.
|
||||
event_id: str | None = None
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
"""Render the session-internal mailbox dictionary."""
|
||||
data: dict[str, object] = {"type": self.type}
|
||||
for f in fields(self):
|
||||
if f.name == "event_id":
|
||||
if self.event_id is not None:
|
||||
data["realtime_event_id"] = self.event_id
|
||||
continue
|
||||
value = getattr(self, f.name)
|
||||
if value is None:
|
||||
continue
|
||||
if isinstance(value, tuple):
|
||||
value = list(value)
|
||||
elif isinstance(value, Mapping):
|
||||
value = dict(value)
|
||||
data[f.name] = value
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class AppendAudio(DuplexCommand):
|
||||
type: ClassVar[str] = "input_audio_buffer.append"
|
||||
#: Raw audio bytes in ``format`` at ``sample_rate_hz`` (base64 only on the wire).
|
||||
audio: bytes
|
||||
format: str = "pcm16"
|
||||
sample_rate_hz: int | None = None
|
||||
is_speech: bool | None = None
|
||||
video_frames: tuple[str, ...] = ()
|
||||
duration_ms: int | None = None
|
||||
audio_end_ms: int | None = None
|
||||
#: Model-neutral hints carried through from the wire (rms, vad, transcript hints ...).
|
||||
hints: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
hints = data.pop("hints", None)
|
||||
if isinstance(hints, Mapping):
|
||||
# Hints are raw wire values; the typed fields went through
|
||||
# ``build_append_audio``'s normalization, so they have to win. An
|
||||
# unset typed field is simply absent here (``payload`` skips None),
|
||||
# which is what lets a hint still carry it. Merging the other way
|
||||
# round let a client's ``"is_speech": 0`` override the computed
|
||||
# ``bool | None`` and silently miss the runner's silent-commit path.
|
||||
merged: dict[str, object] = dict(hints)
|
||||
merged.update(data)
|
||||
data = merged
|
||||
data["audio"] = base64.b64encode(self.audio).decode("ascii")
|
||||
if not data.get("video_frames"):
|
||||
data.pop("video_frames", None)
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class AppendText(DuplexCommand):
|
||||
type: ClassVar[str] = "input.text.append"
|
||||
text: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class Commit(DuplexCommand):
|
||||
type: ClassVar[str] = "input_audio_buffer.commit"
|
||||
final: bool = True
|
||||
#: ``None`` means "no explicit request": the runner decides on commit (auto-response
|
||||
#: sessions answer on their own); ``True`` / ``False`` force it.
|
||||
create_response: bool | None = None
|
||||
is_speech: bool | None = None
|
||||
#: Realtime conversation item created for this commit (wire correlation only).
|
||||
realtime_item_id: str | None = None
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
if self.create_response is not None:
|
||||
data["response_create"] = data.pop("create_response")
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class CreateResponse(DuplexCommand):
|
||||
type: ClassVar[str] = "response.create"
|
||||
#: Raw Realtime ``response`` object (instructions, voice, modalities, ...).
|
||||
options: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
options = data.pop("options", None)
|
||||
if isinstance(options, Mapping):
|
||||
data["response"] = dict(options)
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ClearInput(DuplexCommand):
|
||||
type: ClassVar[str] = "input_audio_buffer.clear"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class CancelInput(DuplexCommand):
|
||||
type: ClassVar[str] = "input.cancel"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class CancelResponse(DuplexCommand):
|
||||
type: ClassVar[str] = "response.cancel"
|
||||
response_id: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class BargeIn(DuplexCommand):
|
||||
type: ClassVar[str] = "barge_in"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ClearOutputAudio(DuplexCommand):
|
||||
type: ClassVar[str] = "output_audio_buffer.clear"
|
||||
#: Explicit response to clear; ``None`` targets the active/last response.
|
||||
response_id: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SignalTurn(DuplexCommand):
|
||||
"""Generic ``turn.signal`` (local turn transitions such as ``user_started``)."""
|
||||
|
||||
type: ClassVar[str] = "turn.signal"
|
||||
event: str
|
||||
signal_payload: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
signal_payload = data.pop("signal_payload", None)
|
||||
if isinstance(signal_payload, Mapping) and signal_payload:
|
||||
data["payload"] = dict(signal_payload)
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class UpdateSession(DuplexCommand):
|
||||
"""``session.update``: a Realtime ``session`` object patch."""
|
||||
|
||||
type: ClassVar[str] = "turn.signal"
|
||||
patch: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
data["event"] = "session.update"
|
||||
data["payload"] = dict(data.pop("patch", {}) or {})
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class AckPlayback(DuplexCommand):
|
||||
type: ClassVar[str] = "playback.ack"
|
||||
played_ms: int
|
||||
committed_ms: int | None = None
|
||||
response_id: str | None = None
|
||||
item_id: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class Heartbeat(DuplexCommand):
|
||||
type: ClassVar[str] = "session.heartbeat"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class CreateItem(DuplexCommand):
|
||||
"""``conversation.item.create`` (history injection or function-call output)."""
|
||||
|
||||
type: ClassVar[str] = "turn.signal"
|
||||
item: Mapping[str, object]
|
||||
previous_item_id: str | None = None
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
data["event"] = "conversation.item.create"
|
||||
payload: dict[str, object] = {"item": dict(data.pop("item"))}
|
||||
previous = data.pop("previous_item_id", None)
|
||||
if previous is not None:
|
||||
payload["previous_item_id"] = previous
|
||||
data["payload"] = payload
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class DeleteItem(DuplexCommand):
|
||||
type: ClassVar[str] = "turn.signal"
|
||||
item_id: str
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
data["event"] = "conversation.item.delete"
|
||||
data["payload"] = {"item_id": data.pop("item_id")}
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TruncateItem(DuplexCommand):
|
||||
type: ClassVar[str] = "turn.signal"
|
||||
item_id: str
|
||||
audio_end_ms: int
|
||||
content_index: int = 0
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
data["event"] = "conversation.item.truncate"
|
||||
data["payload"] = {
|
||||
"item_id": data.pop("item_id"),
|
||||
"audio_end_ms": data.pop("audio_end_ms"),
|
||||
"content_index": data.pop("content_index", 0),
|
||||
}
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class CloseSession(DuplexCommand):
|
||||
"""Graceful close requested through the command stream (``session.close``)."""
|
||||
|
||||
type: ClassVar[str] = "session.close"
|
||||
reason: str = "client_close"
|
||||
|
||||
|
||||
#: Realtime client event types that map onto commands (wire vocabulary).
|
||||
REALTIME_COMMAND_TYPES: frozenset[str] = frozenset(
|
||||
{
|
||||
"input_audio_buffer.append",
|
||||
"input_audio_buffer.commit",
|
||||
"input_audio_buffer.clear",
|
||||
"output_audio_buffer.clear",
|
||||
"response.create",
|
||||
"response.cancel",
|
||||
"conversation.item.create",
|
||||
"conversation.item.delete",
|
||||
"conversation.item.truncate",
|
||||
"session.update",
|
||||
"playback.ack",
|
||||
"session.heartbeat",
|
||||
"session.close",
|
||||
"turn.signal",
|
||||
"input.text.append",
|
||||
"input.cancel",
|
||||
"barge_in",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def command_from_realtime(
|
||||
payload: Mapping[str, object],
|
||||
*,
|
||||
defaults: RealtimeInputDefaults | None = None,
|
||||
) -> DuplexCommand:
|
||||
"""Translate one OpenAI Realtime client event into a command.
|
||||
|
||||
Envelope concerns (``event_id`` acknowledgements, resume bookkeeping) are
|
||||
handled by the transport; this function only validates and maps the
|
||||
payload shape. ``defaults`` carries the audio format / sample rate / VAD
|
||||
defaults the session declared, so every transport decodes an append the
|
||||
same way. Raises :class:`DuplexCommandError` for malformed or unsupported
|
||||
payloads.
|
||||
"""
|
||||
from vllm_omni.engine.duplex.realtime_commands import translate_realtime_command
|
||||
|
||||
return translate_realtime_command(payload, defaults=defaults)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"REALTIME_COMMAND_TYPES",
|
||||
"AckPlayback",
|
||||
"AppendAudio",
|
||||
"AppendText",
|
||||
"BargeIn",
|
||||
"CancelInput",
|
||||
"CancelResponse",
|
||||
"ClearInput",
|
||||
"ClearOutputAudio",
|
||||
"CloseSession",
|
||||
"Commit",
|
||||
"CreateItem",
|
||||
"CreateResponse",
|
||||
"DeleteItem",
|
||||
"DuplexCommand",
|
||||
"DuplexCommandError",
|
||||
"Heartbeat",
|
||||
"SignalTurn",
|
||||
"TruncateItem",
|
||||
"UpdateSession",
|
||||
"command_from_realtime",
|
||||
]
|
||||
@@ -0,0 +1,815 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Session configuration, capabilities and value types of the duplex session model.
|
||||
|
||||
These classes are the typed half of the public contract: ``DuplexOmni``
|
||||
accepts a ``DuplexSessionConfig`` (or the equivalent OpenAI Realtime
|
||||
``session`` object via :meth:`DuplexSessionConfig.from_realtime`) and reports
|
||||
``DuplexCapabilities``. They used to live in ``entrypoints/duplex/protocol.py``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
from typing import Any, cast
|
||||
|
||||
|
||||
class DuplexConfigError(ValueError):
|
||||
"""A Realtime session/response object was rejected while mapping it onto the duplex config."""
|
||||
|
||||
def __init__(self, message: str, *, code: str = "bad_event", param: str | None = None) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.param = param
|
||||
|
||||
|
||||
class DuplexOverlapPolicy(str, Enum):
|
||||
LISTEN_ONLY = "listen_only"
|
||||
BARGE_IN_ON_SPEECH = "barge_in_on_speech"
|
||||
|
||||
|
||||
class DuplexPlaybackCommitPolicy(str, Enum):
|
||||
COMMIT_ALL_ON_DONE = "commit_all_on_done"
|
||||
ACK_ONLY = "ack_only"
|
||||
|
||||
|
||||
class DuplexSessionState(str, Enum):
|
||||
OPEN = "open"
|
||||
CLOSING = "closing"
|
||||
CLOSED = "closed"
|
||||
|
||||
|
||||
class DuplexTurnState(str, Enum):
|
||||
IDLE = "idle"
|
||||
USER_SPEAKING = "user_speaking"
|
||||
USER_COMMITTED = "user_committed"
|
||||
ASSISTANT_GENERATING = "assistant_generating"
|
||||
ASSISTANT_PLAYING = "assistant_playing"
|
||||
BARGE_IN = "barge_in"
|
||||
|
||||
|
||||
class DuplexTurnEventType(str, Enum):
|
||||
USER_STARTED = "user_started"
|
||||
USER_COMMITTED = "user_committed"
|
||||
ASSISTANT_STARTED = "assistant_started"
|
||||
ASSISTANT_DONE = "assistant_done"
|
||||
BARGE_IN = "barge_in"
|
||||
PLAYBACK_ACK = "playback_ack"
|
||||
TIMEOUT = "timeout"
|
||||
CLOSE = "close"
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplexCapabilities:
|
||||
"""Runtime/model capabilities exposed by the duplex serving protocol.
|
||||
|
||||
These are intentionally explicit so the serving layer does not assume all
|
||||
duplex models support the same input append, rollback, or turn policy.
|
||||
``supports_core_kv_lease`` is reserved for scheduler-owned KV lifecycle;
|
||||
model-owned decoder/TTS state must use ``supports_model_internal_state``.
|
||||
``supports_core_resumable_request`` means the scheduler can resume the
|
||||
same request id across streaming updates, but it is not a KV lease by
|
||||
itself. Realtime support means this endpoint can speak the native Realtime
|
||||
event schema for the supported audio duplex paths while keeping model- or
|
||||
scheduler-specific limits explicit in the capability payload.
|
||||
"""
|
||||
|
||||
supports_session_adapter: bool = True
|
||||
supports_model_native_turn_policy: bool = False
|
||||
supports_external_turn_signal: bool = True
|
||||
supports_client_commit: bool = True
|
||||
supports_barge_in: bool = True
|
||||
supports_playback_ack: bool = True
|
||||
supports_input_append: bool = False
|
||||
supports_replace_latest_chunk: bool = True
|
||||
supports_reencode_context: bool = True
|
||||
supports_rollback_to_checkpoint: bool = False
|
||||
supports_turn_commit_only: bool = True
|
||||
supports_kv_lease: bool = False
|
||||
supports_core_kv_lease: bool = False
|
||||
supports_model_internal_state: bool = False
|
||||
supports_stage_resumption: bool = False
|
||||
supports_scheduler_native_append: bool = False
|
||||
supports_core_resumable_request: bool = False
|
||||
supports_stage_connector_handoff: bool = False
|
||||
supports_independent_io_streams: bool = False
|
||||
supports_realtime_endpoint: bool = False
|
||||
supports_multi_session: bool = False
|
||||
supports_multi_session_same_replica: bool = False
|
||||
supports_session_lease: bool = False
|
||||
supports_session_resume: bool = False
|
||||
session_admission_mode: str = "serving_managed"
|
||||
supports_audio_truncate: bool = False
|
||||
#: Whether this model can serve ``/v1/chat/completions`` on a duplex
|
||||
#: session. That needs one thing the protocol cannot assume: the model
|
||||
#: honours ``DuplexSessionConfig.initial_user_text``, so a turn can be
|
||||
#: seeded from text. A model-native model decides to speak from the audio
|
||||
#: it hears, and silence is its signal *not* to take a turn, so without
|
||||
#: seeding a text prompt has no representation and the turn never
|
||||
#: completes. ``text_turn_priming_units`` is how many silence units such a
|
||||
#: seeded turn must be given to generate on -- it still speaks per unit.
|
||||
supports_chat_completions: bool = False
|
||||
text_turn_priming_units: int = 0
|
||||
requires_model_runner_kv: bool = False
|
||||
requires_native_stage_role: bool = False
|
||||
adapter_patterns: list[str] = field(default_factory=lambda: ["chunk_group_append"])
|
||||
signal_sources: list[str] = field(default_factory=lambda: ["client_event", "server_policy", "model_native"])
|
||||
stage_handoff_transport: str | None = None
|
||||
chunk_period_ms: int | None = 1000
|
||||
target_barge_in_latency_ms: int | None = 1000
|
||||
|
||||
def as_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"supports_session_adapter": self.supports_session_adapter,
|
||||
"supports_model_native_turn_policy": self.supports_model_native_turn_policy,
|
||||
"supports_external_turn_signal": self.supports_external_turn_signal,
|
||||
"supports_client_commit": self.supports_client_commit,
|
||||
"supports_barge_in": self.supports_barge_in,
|
||||
"supports_playback_ack": self.supports_playback_ack,
|
||||
"supports_input_append": self.supports_input_append,
|
||||
"supports_replace_latest_chunk": self.supports_replace_latest_chunk,
|
||||
"supports_reencode_context": self.supports_reencode_context,
|
||||
"supports_rollback_to_checkpoint": self.supports_rollback_to_checkpoint,
|
||||
"supports_turn_commit_only": self.supports_turn_commit_only,
|
||||
"supports_kv_lease": self.supports_kv_lease,
|
||||
"supports_core_kv_lease": self.supports_core_kv_lease,
|
||||
"supports_model_internal_state": self.supports_model_internal_state,
|
||||
"supports_stage_resumption": self.supports_stage_resumption,
|
||||
"supports_scheduler_native_append": self.supports_scheduler_native_append,
|
||||
"supports_core_resumable_request": self.supports_core_resumable_request,
|
||||
"supports_stage_connector_handoff": self.supports_stage_connector_handoff,
|
||||
"supports_independent_io_streams": self.supports_independent_io_streams,
|
||||
"supports_realtime_endpoint": self.supports_realtime_endpoint,
|
||||
"supports_multi_session": self.supports_multi_session,
|
||||
"supports_multi_session_same_replica": self.supports_multi_session_same_replica,
|
||||
"supports_session_lease": self.supports_session_lease,
|
||||
"supports_session_resume": self.supports_session_resume,
|
||||
"session_admission_mode": self.session_admission_mode,
|
||||
"supports_audio_truncate": self.supports_audio_truncate,
|
||||
"requires_model_runner_kv": self.requires_model_runner_kv,
|
||||
"requires_native_stage_role": self.requires_native_stage_role,
|
||||
# Every duplex model is model-native and appends audio chunks (§7 D4);
|
||||
# kept on the wire as constants for clients that still read them.
|
||||
"implementation_level": "model_native_duplex",
|
||||
"adapter_patterns": self.adapter_patterns,
|
||||
"input_modes": ["append_audio_chunk"],
|
||||
"signal_sources": self.signal_sources,
|
||||
"stage_handoff_transport": self.stage_handoff_transport,
|
||||
"chunk_period_ms": self.chunk_period_ms,
|
||||
"target_barge_in_latency_ms": self.target_barge_in_latency_ms,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplexPlaybackCursor:
|
||||
generated_ms: int = 0
|
||||
sent_ms: int = 0
|
||||
played_ms: int = 0
|
||||
committed_ms: int = 0
|
||||
|
||||
def acknowledge(self, played_ms: int, committed_ms: int | None = None) -> None:
|
||||
self.played_ms = max(self.played_ms, max(0, int(played_ms)))
|
||||
if committed_ms is None:
|
||||
committed_ms = self.played_ms
|
||||
self.committed_ms = max(self.committed_ms, max(0, int(committed_ms)))
|
||||
|
||||
def truncate_committed(self, committed_ms: int) -> None:
|
||||
self.committed_ms = max(0, min(max(self.sent_ms, self.generated_ms), int(committed_ms)))
|
||||
|
||||
def as_dict(self) -> dict[str, int]:
|
||||
return {
|
||||
"generated_ms": self.generated_ms,
|
||||
"sent_ms": self.sent_ms,
|
||||
"played_ms": self.played_ms,
|
||||
"committed_ms": self.committed_ms,
|
||||
}
|
||||
|
||||
def snapshot(self) -> DuplexPlaybackView:
|
||||
return DuplexPlaybackView(**self.as_dict())
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DuplexPlaybackView:
|
||||
generated_ms: int = 0
|
||||
sent_ms: int = 0
|
||||
played_ms: int = 0
|
||||
committed_ms: int = 0
|
||||
|
||||
def as_dict(self) -> dict[str, int]:
|
||||
return {
|
||||
"generated_ms": self.generated_ms,
|
||||
"sent_ms": self.sent_ms,
|
||||
"played_ms": self.played_ms,
|
||||
"committed_ms": self.committed_ms,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplexAudioChunk:
|
||||
data: str
|
||||
format: str = "wav"
|
||||
sample_rate_hz: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplexSessionConfig:
|
||||
model: str | None = None
|
||||
modalities: list[str] = field(default_factory=lambda: ["text", "audio"])
|
||||
instructions: str | None = None
|
||||
#: Text the session treats as the user's opening turn. A caller that cannot
|
||||
#: reach the model by speech (an HTTP request, a batch job) puts its prompt
|
||||
#: here; ``supports_text_only_turn`` says whether the model can answer it.
|
||||
initial_user_text: str | None = None
|
||||
voice: str | None = None
|
||||
ref_audio: str | None = None
|
||||
response_format: str = "wav"
|
||||
temperature: float | None = None
|
||||
max_tokens: int | None = None
|
||||
speed: float | None = None
|
||||
use_tts_template: bool = True
|
||||
idle_timeout_s: float = 300.0
|
||||
overlap_policy: str = DuplexOverlapPolicy.LISTEN_ONLY.value
|
||||
overlap_short_ack_ms: int = 700
|
||||
overlap_barge_in_ms: int = 1200
|
||||
overlap_silence_rms: float = 0.003
|
||||
playback_commit_policy: str = DuplexPlaybackCommitPolicy.COMMIT_ALL_ON_DONE.value
|
||||
extra_body: dict[str, object] = field(default_factory=dict)
|
||||
|
||||
def as_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"model": self.model,
|
||||
"modalities": list(self.modalities),
|
||||
"instructions": self.instructions,
|
||||
"initial_user_text": self.initial_user_text,
|
||||
"voice": self.voice,
|
||||
"ref_audio": self.ref_audio,
|
||||
"response_format": self.response_format,
|
||||
"temperature": self.temperature,
|
||||
"max_tokens": self.max_tokens,
|
||||
"speed": self.speed,
|
||||
"use_tts_template": self.use_tts_template,
|
||||
"idle_timeout_s": self.idle_timeout_s,
|
||||
"overlap_policy": self.overlap_policy,
|
||||
"overlap_short_ack_ms": self.overlap_short_ack_ms,
|
||||
"overlap_barge_in_ms": self.overlap_barge_in_ms,
|
||||
"overlap_silence_rms": self.overlap_silence_rms,
|
||||
"playback_commit_policy": self.playback_commit_policy,
|
||||
"extra_body": dict(self.extra_body),
|
||||
}
|
||||
|
||||
def normalized(self) -> DuplexSessionConfig:
|
||||
"""Apply the clamps / defaults ``from_event`` applies to a wire object (typed configs skip them)."""
|
||||
return DuplexSessionConfig.from_event({"session": self.as_dict()})
|
||||
|
||||
@classmethod
|
||||
def from_event(cls, event: dict[str, object]) -> DuplexSessionConfig:
|
||||
payload = event.get("session")
|
||||
if isinstance(payload, dict):
|
||||
source = payload
|
||||
else:
|
||||
source = event
|
||||
|
||||
config = cls()
|
||||
if isinstance(source.get("model"), str):
|
||||
config.model = source["model"]
|
||||
if isinstance(source.get("instructions"), str):
|
||||
config.instructions = source["instructions"]
|
||||
if isinstance(source.get("initial_user_text"), str):
|
||||
config.initial_user_text = source["initial_user_text"]
|
||||
if isinstance(source.get("voice"), str):
|
||||
config.voice = source["voice"]
|
||||
if isinstance(source.get("ref_audio"), str):
|
||||
config.ref_audio = source["ref_audio"]
|
||||
if isinstance(source.get("response_format"), str):
|
||||
config.response_format = source["response_format"]
|
||||
if isinstance(source.get("use_tts_template"), bool):
|
||||
config.use_tts_template = bool(source["use_tts_template"])
|
||||
if isinstance(source.get("temperature"), int | float):
|
||||
config.temperature = float(source["temperature"])
|
||||
if isinstance(source.get("max_tokens"), int):
|
||||
config.max_tokens = int(source["max_tokens"])
|
||||
if isinstance(source.get("speed"), int | float):
|
||||
config.speed = float(source["speed"])
|
||||
if isinstance(source.get("idle_timeout_s"), int | float):
|
||||
config.idle_timeout_s = float(source["idle_timeout_s"])
|
||||
if isinstance(source.get("overlap_policy"), str):
|
||||
config.overlap_policy = cls._normalize_overlap_policy(source["overlap_policy"])
|
||||
if isinstance(source.get("overlap_short_ack_ms"), int | float):
|
||||
config.overlap_short_ack_ms = max(0, int(source["overlap_short_ack_ms"]))
|
||||
if isinstance(source.get("overlap_barge_in_ms"), int | float):
|
||||
config.overlap_barge_in_ms = max(0, int(source["overlap_barge_in_ms"]))
|
||||
if isinstance(source.get("overlap_silence_rms"), int | float):
|
||||
config.overlap_silence_rms = max(0.0, float(source["overlap_silence_rms"]))
|
||||
if isinstance(source.get("playback_commit_policy"), str):
|
||||
config.playback_commit_policy = cls._normalize_playback_commit_policy(source["playback_commit_policy"])
|
||||
if isinstance(source.get("modalities"), list) and all(isinstance(x, str) for x in source["modalities"]):
|
||||
config.modalities = list(source["modalities"])
|
||||
if isinstance(source.get("extra_body"), dict):
|
||||
config.extra_body = dict(source["extra_body"])
|
||||
extra = config.extra_body
|
||||
if isinstance(extra.get("overlap_policy"), str):
|
||||
config.overlap_policy = cls._normalize_overlap_policy(extra["overlap_policy"])
|
||||
if isinstance(extra.get("overlap_short_ack_ms"), int | float):
|
||||
config.overlap_short_ack_ms = max(0, int(extra["overlap_short_ack_ms"]))
|
||||
if isinstance(extra.get("overlap_barge_in_ms"), int | float):
|
||||
config.overlap_barge_in_ms = max(0, int(extra["overlap_barge_in_ms"]))
|
||||
if isinstance(extra.get("overlap_silence_rms"), int | float):
|
||||
config.overlap_silence_rms = max(0.0, float(extra["overlap_silence_rms"]))
|
||||
if isinstance(extra.get("playback_commit_policy"), str):
|
||||
config.playback_commit_policy = cls._normalize_playback_commit_policy(extra["playback_commit_policy"])
|
||||
return config
|
||||
|
||||
@classmethod
|
||||
def from_realtime(
|
||||
cls,
|
||||
session_payload: Mapping[str, object],
|
||||
*,
|
||||
model: str | None = None,
|
||||
) -> DuplexSessionConfig:
|
||||
"""Build a config from an OpenAI Realtime ``session`` object (session.update / open_session).
|
||||
|
||||
Applies the wire defaults, validates audio formats and turn detection
|
||||
(raising :class:`DuplexConfigError` with the same codes the Realtime
|
||||
translator used), fills ``turn_detection`` defaults / derives
|
||||
``overlap_policy``, and stores the Realtime-only fields under the
|
||||
``realtime_*`` keys of ``extra_body`` exactly like the old
|
||||
``_session_create_from_realtime``.
|
||||
"""
|
||||
from vllm_omni.engine.duplex.realtime_commands import (
|
||||
RealtimeInputDefaults,
|
||||
duplex_response_format,
|
||||
input_audio_transcription_config,
|
||||
json_safe_realtime_payload,
|
||||
realtime_max_output_tokens,
|
||||
realtime_overlap_fields,
|
||||
validate_realtime_session_audio_formats,
|
||||
)
|
||||
from vllm_omni.engine.duplex.turn_detection import (
|
||||
normalize_turn_detection_session_payload,
|
||||
validate_realtime_turn_detection,
|
||||
)
|
||||
|
||||
payload: dict[str, object] = dict(session_payload)
|
||||
format_error = validate_realtime_session_audio_formats(payload)
|
||||
if format_error is not None:
|
||||
raise DuplexConfigError(format_error, code="unsupported_audio_format")
|
||||
turn_detection_error = validate_realtime_turn_detection(payload)
|
||||
if turn_detection_error is not None:
|
||||
raise DuplexConfigError(turn_detection_error, code="unsupported_turn_detection", param="turn_detection")
|
||||
normalize_turn_detection_session_payload(payload)
|
||||
defaults = RealtimeInputDefaults().with_session_payload(payload)
|
||||
payload.update(realtime_overlap_fields(payload))
|
||||
|
||||
audio_config = payload.get("audio")
|
||||
audio_input = audio_config.get("input") if isinstance(audio_config, dict) else None
|
||||
audio_output = audio_config.get("output") if isinstance(audio_config, dict) else None
|
||||
extra_body_payload = payload.get("extra_body")
|
||||
extra_body: dict[str, object] = dict(extra_body_payload) if isinstance(extra_body_payload, dict) else {}
|
||||
extra_body["realtime_session_payload"] = json_safe_realtime_payload(payload)
|
||||
if isinstance(payload.get("tools"), list):
|
||||
extra_body["realtime_tools"] = payload["tools"]
|
||||
if isinstance(payload.get("tool_choice"), str | dict):
|
||||
extra_body["realtime_tool_choice"] = payload["tool_choice"]
|
||||
metadata = payload.get("metadata")
|
||||
if isinstance(metadata, dict):
|
||||
extra_body["realtime_metadata"] = dict(metadata)
|
||||
include = payload.get("include")
|
||||
if isinstance(include, list):
|
||||
extra_body["realtime_include"] = list(include)
|
||||
prompt = payload.get("prompt")
|
||||
if isinstance(prompt, dict):
|
||||
extra_body["realtime_prompt"] = dict(prompt)
|
||||
transcription = input_audio_transcription_config(payload)
|
||||
if isinstance(transcription, dict):
|
||||
extra_body["realtime_input_audio_transcription"] = dict(transcription)
|
||||
noise_reduction = payload.get("input_audio_noise_reduction")
|
||||
if isinstance(noise_reduction, dict):
|
||||
extra_body["realtime_input_audio_noise_reduction"] = dict(noise_reduction)
|
||||
audio_noise_reduction = audio_input.get("noise_reduction") if isinstance(audio_input, dict) else None
|
||||
if isinstance(audio_noise_reduction, dict):
|
||||
extra_body["realtime_input_audio_noise_reduction"] = dict(audio_noise_reduction)
|
||||
if isinstance(audio_config, dict):
|
||||
extra_body["realtime_audio"] = dict(audio_config)
|
||||
if isinstance(payload.get("tracing"), str | dict):
|
||||
extra_body["realtime_tracing"] = payload["tracing"]
|
||||
if isinstance(payload.get("turn_detection"), dict):
|
||||
extra_body["realtime_turn_detection"] = dict(cast("Mapping[str, object]", payload["turn_detection"]))
|
||||
elif "turn_detection" in payload and payload.get("turn_detection") is None:
|
||||
extra_body["realtime_turn_detection"] = None
|
||||
extra_body.setdefault("realtime_output_audio_format", defaults.output_audio_format)
|
||||
voice = payload.get("voice")
|
||||
if not isinstance(voice, str) and isinstance(audio_output, dict):
|
||||
voice = audio_output.get("voice")
|
||||
speed = payload.get("speed")
|
||||
if not isinstance(speed, int | float) and isinstance(audio_output, dict):
|
||||
speed = audio_output.get("speed")
|
||||
resolved_model = payload.get("model") if isinstance(payload.get("model"), str) else model
|
||||
session: dict[str, object] = {
|
||||
"model": resolved_model,
|
||||
"modalities": payload.get("modalities") or payload.get("output_modalities") or ["text", "audio"],
|
||||
"instructions": payload.get("instructions"),
|
||||
# Not a Realtime field, but a session one: a client that cannot
|
||||
# reach the model by speech seeds its opening turn here. Without
|
||||
# this a websocket client could only use the older
|
||||
# ``extra_body.duplex_initial_user_text`` spelling.
|
||||
"initial_user_text": payload.get("initial_user_text"),
|
||||
"voice": voice,
|
||||
"ref_audio": payload.get("ref_audio"),
|
||||
"response_format": duplex_response_format(defaults.output_audio_format),
|
||||
"temperature": payload.get("temperature"),
|
||||
"max_tokens": realtime_max_output_tokens(
|
||||
payload.get("max_response_output_tokens")
|
||||
or payload.get("max_output_tokens")
|
||||
or payload.get("max_tokens")
|
||||
),
|
||||
"speed": speed,
|
||||
"idle_timeout_s": payload.get("idle_timeout_s") or 300.0,
|
||||
**realtime_overlap_fields(payload),
|
||||
"extra_body": extra_body,
|
||||
}
|
||||
return cls.from_event({"session": session})
|
||||
|
||||
def apply_realtime_update(
|
||||
self,
|
||||
patch: Mapping[str, object],
|
||||
*,
|
||||
session_id: str | None = None,
|
||||
audio_started: bool = False,
|
||||
) -> None:
|
||||
"""Apply a Realtime ``session.update`` patch in place.
|
||||
|
||||
Raises :class:`DuplexConfigError` (``code`` in ``model_update_unsupported``,
|
||||
``voice_update_after_audio_unsupported``, ``ref_audio_update_unsupported``)
|
||||
when the patch changes something a live session cannot change.
|
||||
``audio_started`` is ``playback.generated_ms > 0 or playback.sent_ms > 0``.
|
||||
"""
|
||||
from vllm_omni.engine.duplex.realtime_commands import (
|
||||
REALTIME_OUTPUT_AUDIO_FORMATS,
|
||||
duplex_response_format,
|
||||
input_audio_transcription_config,
|
||||
json_safe_realtime_payload,
|
||||
parse_realtime_audio_format,
|
||||
realtime_max_output_tokens,
|
||||
)
|
||||
|
||||
# Any: the patch is read with ``isinstance(payload.get(...))`` guards and consumed
|
||||
# through ``payload[...]``; typing the values ``object`` would need a cast per read.
|
||||
payload: dict[str, Any] = dict(patch)
|
||||
model = payload.get("model")
|
||||
audio_config = payload.get("audio")
|
||||
audio_input = audio_config.get("input") if isinstance(audio_config, dict) else None
|
||||
audio_output = audio_config.get("output") if isinstance(audio_config, dict) else None
|
||||
voice = payload.get("voice")
|
||||
if not isinstance(voice, str) and isinstance(audio_output, dict):
|
||||
voice = audio_output.get("voice")
|
||||
if isinstance(model, str) and self.model is not None and model != self.model:
|
||||
raise DuplexConfigError(
|
||||
"session.update cannot change model for an open realtime duplex session",
|
||||
code="model_update_unsupported",
|
||||
)
|
||||
if isinstance(model, str) and self.model is None:
|
||||
self.model = model
|
||||
if isinstance(voice, str) and audio_started:
|
||||
raise DuplexConfigError(
|
||||
"session.update cannot change voice after audio output has started",
|
||||
code="voice_update_after_audio_unsupported",
|
||||
)
|
||||
if isinstance(payload.get("ref_audio"), str):
|
||||
raise DuplexConfigError(
|
||||
"session.update cannot change ref_audio after the session is open", code="ref_audio_update_unsupported"
|
||||
)
|
||||
if isinstance(payload.get("instructions"), str):
|
||||
self.instructions = str(payload["instructions"])
|
||||
elif "instructions" in payload and payload.get("instructions") is None:
|
||||
self.instructions = None
|
||||
if isinstance(voice, str):
|
||||
self.voice = str(voice)
|
||||
elif "voice" in payload and payload.get("voice") is None:
|
||||
self.voice = None
|
||||
response_format = payload.get("output_audio_format") or payload.get("response_format")
|
||||
if response_format is None and isinstance(audio_output, dict):
|
||||
response_format = audio_output.get("format")
|
||||
response_format, _ = parse_realtime_audio_format(response_format)
|
||||
if isinstance(response_format, str) and response_format.lower() in REALTIME_OUTPUT_AUDIO_FORMATS:
|
||||
self.response_format = duplex_response_format(response_format)
|
||||
if isinstance(payload.get("temperature"), int | float):
|
||||
self.temperature = float(payload["temperature"])
|
||||
speed = payload.get("speed")
|
||||
if not isinstance(speed, int | float) and isinstance(audio_output, dict):
|
||||
speed = audio_output.get("speed")
|
||||
if isinstance(speed, int | float):
|
||||
self.speed = float(speed)
|
||||
max_tokens = (
|
||||
payload.get("max_response_output_tokens")
|
||||
if "max_response_output_tokens" in payload
|
||||
else payload.get("max_output_tokens")
|
||||
if "max_output_tokens" in payload
|
||||
else payload.get("max_tokens")
|
||||
)
|
||||
if "max_response_output_tokens" in payload or "max_output_tokens" in payload or "max_tokens" in payload:
|
||||
self.max_tokens = realtime_max_output_tokens(max_tokens)
|
||||
if isinstance(payload.get("overlap_policy"), str):
|
||||
self.overlap_policy = self._normalize_overlap_policy(str(payload["overlap_policy"]))
|
||||
if isinstance(payload.get("overlap_short_ack_ms"), int | float):
|
||||
self.overlap_short_ack_ms = max(0, int(payload["overlap_short_ack_ms"]))
|
||||
if isinstance(payload.get("overlap_barge_in_ms"), int | float):
|
||||
self.overlap_barge_in_ms = max(0, int(payload["overlap_barge_in_ms"]))
|
||||
if isinstance(payload.get("overlap_silence_rms"), int | float):
|
||||
self.overlap_silence_rms = max(0.0, float(payload["overlap_silence_rms"]))
|
||||
if isinstance(payload.get("playback_commit_policy"), str):
|
||||
self.playback_commit_policy = self._normalize_playback_commit_policy(str(payload["playback_commit_policy"]))
|
||||
modalities = payload.get("modalities") or payload.get("output_modalities")
|
||||
if isinstance(modalities, list) and all(isinstance(item, str) for item in modalities):
|
||||
self.modalities = list(modalities)
|
||||
if isinstance(payload.get("extra_body"), dict):
|
||||
self.extra_body.update(payload["extra_body"])
|
||||
extra = payload["extra_body"]
|
||||
if isinstance(extra.get("overlap_policy"), str):
|
||||
self.overlap_policy = self._normalize_overlap_policy(str(extra["overlap_policy"]))
|
||||
if isinstance(extra.get("playback_commit_policy"), str):
|
||||
self.playback_commit_policy = self._normalize_playback_commit_policy(
|
||||
str(extra["playback_commit_policy"])
|
||||
)
|
||||
if isinstance(payload.get("tools"), list):
|
||||
self.extra_body["realtime_tools"] = payload["tools"]
|
||||
elif "tools" in payload and payload.get("tools") is None:
|
||||
self.extra_body.pop("realtime_tools", None)
|
||||
if isinstance(payload.get("tool_choice"), str | dict):
|
||||
self.extra_body["realtime_tool_choice"] = payload["tool_choice"]
|
||||
elif "tool_choice" in payload and payload.get("tool_choice") is None:
|
||||
self.extra_body.pop("realtime_tool_choice", None)
|
||||
if isinstance(payload.get("metadata"), dict):
|
||||
self.extra_body["realtime_metadata"] = dict(payload["metadata"])
|
||||
elif "metadata" in payload and payload.get("metadata") is None:
|
||||
self.extra_body.pop("realtime_metadata", None)
|
||||
if isinstance(payload.get("include"), list):
|
||||
self.extra_body["realtime_include"] = list(payload["include"])
|
||||
elif "include" in payload and payload.get("include") is None:
|
||||
self.extra_body.pop("realtime_include", None)
|
||||
if isinstance(payload.get("prompt"), dict):
|
||||
self.extra_body["realtime_prompt"] = dict(payload["prompt"])
|
||||
elif "prompt" in payload and payload.get("prompt") is None:
|
||||
self.extra_body.pop("realtime_prompt", None)
|
||||
transcription = input_audio_transcription_config(payload)
|
||||
if isinstance(transcription, dict):
|
||||
self.extra_body["realtime_input_audio_transcription"] = dict(transcription)
|
||||
elif "input_audio_transcription" in payload and payload.get("input_audio_transcription") is None:
|
||||
self.extra_body.pop("realtime_input_audio_transcription", None)
|
||||
if isinstance(payload.get("input_audio_noise_reduction"), dict):
|
||||
self.extra_body["realtime_input_audio_noise_reduction"] = dict(payload["input_audio_noise_reduction"])
|
||||
elif "input_audio_noise_reduction" in payload and payload.get("input_audio_noise_reduction") is None:
|
||||
self.extra_body.pop("realtime_input_audio_noise_reduction", None)
|
||||
if isinstance(audio_input, dict) and isinstance(audio_input.get("noise_reduction"), dict):
|
||||
self.extra_body["realtime_input_audio_noise_reduction"] = dict(audio_input["noise_reduction"])
|
||||
elif isinstance(audio_input, dict) and audio_input.get("noise_reduction") is None:
|
||||
self.extra_body.pop("realtime_input_audio_noise_reduction", None)
|
||||
if isinstance(payload.get("audio"), dict):
|
||||
self.extra_body["realtime_audio"] = dict(payload["audio"])
|
||||
elif "audio" in payload and payload.get("audio") is None:
|
||||
self.extra_body.pop("realtime_audio", None)
|
||||
if isinstance(payload.get("tracing"), str | dict):
|
||||
self.extra_body["realtime_tracing"] = payload["tracing"]
|
||||
elif "tracing" in payload and payload.get("tracing") is None:
|
||||
self.extra_body.pop("realtime_tracing", None)
|
||||
if isinstance(payload.get("turn_detection"), dict):
|
||||
self.extra_body["realtime_turn_detection"] = dict(payload["turn_detection"])
|
||||
elif "turn_detection" in payload and payload.get("turn_detection") is None:
|
||||
self.extra_body["realtime_turn_detection"] = None
|
||||
self.extra_body["realtime_session_payload"] = json_safe_realtime_payload(payload)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _normalize_overlap_policy(value: str) -> str:
|
||||
normalized = value.strip().lower()
|
||||
if normalized in {policy.value for policy in DuplexOverlapPolicy}:
|
||||
return normalized
|
||||
return DuplexOverlapPolicy.LISTEN_ONLY.value
|
||||
|
||||
@staticmethod
|
||||
def _normalize_playback_commit_policy(value: str) -> str:
|
||||
normalized = value.strip().lower()
|
||||
if normalized in {policy.value for policy in DuplexPlaybackCommitPolicy}:
|
||||
return normalized
|
||||
return DuplexPlaybackCommitPolicy.COMMIT_ALL_ON_DONE.value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResponseCreateOptions:
|
||||
instructions: str | None = None
|
||||
voice: str | None = None
|
||||
response_format: str | None = None
|
||||
temperature: float | None = None
|
||||
max_tokens: int | None = None
|
||||
speed: float | None = None
|
||||
modalities: tuple[str, ...] | None = None
|
||||
extra_body: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def apply_to(self, config: DuplexSessionConfig) -> None:
|
||||
for field_name in ("instructions", "voice", "response_format", "temperature", "max_tokens", "speed"):
|
||||
value = getattr(self, field_name)
|
||||
if value is not None:
|
||||
setattr(config, field_name, value)
|
||||
if self.modalities is not None:
|
||||
config.modalities = list(self.modalities)
|
||||
config.extra_body.update(self.extra_body)
|
||||
|
||||
@classmethod
|
||||
def from_realtime(
|
||||
cls,
|
||||
response_payload: Mapping[str, object],
|
||||
*,
|
||||
private_runtime_config_keys: frozenset[str] = frozenset(),
|
||||
) -> ResponseCreateOptions:
|
||||
"""Parse an OpenAI Realtime ``response`` object into response-scoped options.
|
||||
|
||||
Raises :class:`DuplexConfigError` (``code="unsupported_native_response_options"``)
|
||||
for options a model-native duplex session cannot apply per response.
|
||||
Private runtime keys in ``extra_body`` are dropped.
|
||||
"""
|
||||
from vllm_omni.engine.duplex.realtime_commands import (
|
||||
REALTIME_OUTPUT_AUDIO_FORMATS,
|
||||
duplex_response_format,
|
||||
parse_realtime_audio_format,
|
||||
realtime_max_output_tokens,
|
||||
)
|
||||
|
||||
payload: dict[str, object] = dict(response_payload)
|
||||
audio_config = payload.get("audio")
|
||||
audio_output = audio_config.get("output") if isinstance(audio_config, dict) else None
|
||||
nested_voice = audio_output.get("voice") if isinstance(audio_output, dict) else None
|
||||
unsupported = (
|
||||
payload.get("instructions") is not None
|
||||
or payload.get("voice") is not None
|
||||
or nested_voice is not None
|
||||
or payload.get("temperature") is not None
|
||||
or any(
|
||||
payload.get(field_name) is not None
|
||||
for field_name in ("max_response_output_tokens", "max_output_tokens", "max_tokens")
|
||||
)
|
||||
or payload.get("tools") is not None
|
||||
or payload.get("tool_choice") is not None
|
||||
)
|
||||
if unsupported:
|
||||
raise DuplexConfigError(
|
||||
"response.create options are not supported by a model-native duplex session",
|
||||
code="unsupported_native_response_options",
|
||||
)
|
||||
instructions = str(payload["instructions"]) if isinstance(payload.get("instructions"), str) else None
|
||||
voice = payload.get("voice")
|
||||
if not isinstance(voice, str) and isinstance(audio_output, dict):
|
||||
voice = audio_output.get("voice")
|
||||
voice = str(voice) if isinstance(voice, str) else None
|
||||
response_format = payload.get("output_audio_format") or payload.get("response_format")
|
||||
if response_format is None and isinstance(audio_output, dict):
|
||||
response_format = audio_output.get("format")
|
||||
response_format, _ = parse_realtime_audio_format(response_format)
|
||||
if isinstance(response_format, str) and response_format.lower() in REALTIME_OUTPUT_AUDIO_FORMATS:
|
||||
response_format = duplex_response_format(response_format)
|
||||
else:
|
||||
response_format = None
|
||||
temperature = (
|
||||
float(cast("int | float", payload["temperature"]))
|
||||
if isinstance(payload.get("temperature"), int | float)
|
||||
else None
|
||||
)
|
||||
speed = payload.get("speed")
|
||||
if not isinstance(speed, int | float) and isinstance(audio_output, dict):
|
||||
speed = audio_output.get("speed")
|
||||
speed = float(speed) if isinstance(speed, int | float) else None
|
||||
max_tokens = (
|
||||
payload.get("max_response_output_tokens")
|
||||
if "max_response_output_tokens" in payload
|
||||
else payload.get("max_output_tokens")
|
||||
if "max_output_tokens" in payload
|
||||
else payload.get("max_tokens")
|
||||
)
|
||||
if "max_response_output_tokens" in payload or "max_output_tokens" in payload or "max_tokens" in payload:
|
||||
max_tokens = realtime_max_output_tokens(max_tokens)
|
||||
else:
|
||||
max_tokens = None
|
||||
modalities = payload.get("modalities") or payload.get("output_modalities")
|
||||
if isinstance(modalities, list) and all(isinstance(item, str) for item in modalities):
|
||||
modalities = tuple(modalities)
|
||||
else:
|
||||
modalities = None
|
||||
response_extra: dict[str, object] = {}
|
||||
conversation = payload.get("conversation")
|
||||
if isinstance(conversation, str):
|
||||
response_extra["realtime_response_conversation"] = conversation
|
||||
metadata = payload.get("metadata")
|
||||
if isinstance(metadata, dict):
|
||||
response_extra["realtime_response_metadata"] = dict(metadata)
|
||||
prompt = payload.get("prompt")
|
||||
if isinstance(prompt, dict):
|
||||
response_extra["realtime_response_prompt"] = dict(prompt)
|
||||
if isinstance(payload.get("tools"), list):
|
||||
response_extra["realtime_response_tools"] = payload["tools"]
|
||||
if isinstance(payload.get("tool_choice"), str | dict):
|
||||
response_extra["realtime_response_tool_choice"] = payload["tool_choice"]
|
||||
extra_body = payload.get("extra_body")
|
||||
if isinstance(extra_body, dict):
|
||||
response_extra.update(
|
||||
(key, value) for key, value in extra_body.items() if key not in private_runtime_config_keys
|
||||
)
|
||||
return cls(
|
||||
instructions=instructions,
|
||||
voice=voice,
|
||||
response_format=response_format,
|
||||
temperature=temperature,
|
||||
max_tokens=max_tokens,
|
||||
speed=speed,
|
||||
modalities=modalities,
|
||||
extra_body=response_extra,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplexCommittedInput:
|
||||
message: dict[str, object]
|
||||
turn_id: int
|
||||
epoch: int
|
||||
input_commit_seq: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplexAssistantAudioTextMark:
|
||||
text_chars: int
|
||||
audio_end_ms: int
|
||||
|
||||
|
||||
def realtime_item_to_history_message(item: object) -> dict[str, object] | None:
|
||||
"""Convert a Realtime conversation item into a chat history message (None when empty)."""
|
||||
if not isinstance(item, dict):
|
||||
return None
|
||||
role = item.get("role")
|
||||
if role not in {"system", "user", "assistant"}:
|
||||
return None
|
||||
content = item.get("content")
|
||||
if isinstance(content, str):
|
||||
text = content.strip()
|
||||
return {"role": role, "content": text} if text else None
|
||||
if not isinstance(content, list):
|
||||
return None
|
||||
text_chunks: list[str] = []
|
||||
audio_chunks: list[dict[str, object]] = []
|
||||
for part in content:
|
||||
if not isinstance(part, dict):
|
||||
continue
|
||||
part_type = part.get("type")
|
||||
if part_type in {"input_text", "text", "output_text"} and isinstance(part.get("text"), str):
|
||||
text_chunks.append(str(part["text"]))
|
||||
elif part_type in {"input_audio", "audio"}:
|
||||
audio = part.get("audio") or part.get("data")
|
||||
fmt = part.get("format") if isinstance(part.get("format"), str) else "wav"
|
||||
if isinstance(audio, str) and audio:
|
||||
audio_chunks.append({"type": "audio_url", "audio_url": {"url": f"data:audio/{fmt};base64,{audio}"}})
|
||||
elif part_type in {"audio_transcript", "transcript"} and isinstance(part.get("text"), str):
|
||||
text_chunks.append(str(part["text"]))
|
||||
text = "".join(text_chunks).strip()
|
||||
if audio_chunks:
|
||||
content_items: list[dict[str, object]] = []
|
||||
if text:
|
||||
content_items.append({"type": "text", "text": text})
|
||||
content_items.extend(audio_chunks)
|
||||
return {"role": role, "content": content_items}
|
||||
if text:
|
||||
return {"role": role, "content": text}
|
||||
return None
|
||||
|
||||
|
||||
def realtime_max_output_tokens(value: object) -> int | None:
|
||||
"""Normalize Realtime max output tokens (``"inf"`` -> ``None``)."""
|
||||
from vllm_omni.engine.duplex.realtime_commands import realtime_max_output_tokens as _impl
|
||||
|
||||
return _impl(value)
|
||||
|
||||
|
||||
def input_audio_transcription_config(session_payload: Mapping[str, object]) -> dict[str, object] | None:
|
||||
"""Return the ``input_audio_transcription`` object of a Realtime session payload."""
|
||||
from vllm_omni.engine.duplex.realtime_commands import input_audio_transcription_config as _impl
|
||||
|
||||
return _impl(session_payload)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DuplexAssistantAudioTextMark",
|
||||
"DuplexAudioChunk",
|
||||
"DuplexCapabilities",
|
||||
"DuplexCommittedInput",
|
||||
"DuplexConfigError",
|
||||
"DuplexOverlapPolicy",
|
||||
"DuplexPlaybackCommitPolicy",
|
||||
"DuplexPlaybackCursor",
|
||||
"DuplexPlaybackView",
|
||||
"DuplexSessionConfig",
|
||||
"DuplexSessionState",
|
||||
"DuplexTurnEventType",
|
||||
"DuplexTurnState",
|
||||
"ResponseCreateOptions",
|
||||
"input_audio_transcription_config",
|
||||
"realtime_item_to_history_message",
|
||||
"realtime_max_output_tokens",
|
||||
]
|
||||
@@ -1,102 +1,50 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Model-neutral contracts for the experimental duplex engine plugin.
|
||||
"""Model-neutral value types shared by the duplex engine components.
|
||||
|
||||
This module contains only immutable data transfer objects and narrow protocols.
|
||||
Duplex control algorithms, session implementations, model policy, and Realtime
|
||||
serving remain in sibling experimental modules.
|
||||
Immutable DTOs plus the ``DuplexStagePort`` base class that ``DuplexOrchestrator``
|
||||
implements for the session manager/runner.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from collections.abc import Iterable, Mapping
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
from types import MappingProxyType
|
||||
from typing import Any, Protocol
|
||||
|
||||
from vllm_omni.engine.duplex.messages import DuplexFence
|
||||
from vllm_omni.engine.messages import EngineQueueMessage
|
||||
|
||||
|
||||
class SessionMode(str, Enum):
|
||||
TURN = "turn"
|
||||
DUPLEX = "duplex"
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DuplexFence:
|
||||
"""Engine-internal session identity used for stage request ids and stale filtering."""
|
||||
|
||||
|
||||
class DuplexInputMode(str, Enum):
|
||||
APPEND_TOKENS = "append_tokens"
|
||||
APPEND_AUDIO_CHUNK = "append_audio_chunk"
|
||||
REPLACE_LATEST_CHUNK = "replace_latest_chunk"
|
||||
REENCODE_CONTEXT = "reencode_context"
|
||||
ROLLBACK_TO_CHECKPOINT = "rollback_to_checkpoint"
|
||||
TURN_COMMIT_ONLY = "turn_commit_only"
|
||||
session_id: str
|
||||
epoch: int = 0
|
||||
turn_id: int = 0
|
||||
|
||||
|
||||
class DuplexOutputAction(str, Enum):
|
||||
DIRECT_RESPONSE = "direct_response"
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplexRuntimeCapabilities:
|
||||
input_modes: set[DuplexInputMode] = field(default_factory=lambda: {DuplexInputMode.TURN_COMMIT_ONLY})
|
||||
implementation_level: str = "serving_session_adapter"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DuplexAppendPlan:
|
||||
prompt: dict[str, Any]
|
||||
prompt: dict[str, object]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DuplexOutputDecision:
|
||||
action: DuplexOutputAction
|
||||
metadata: Mapping[str, Any] = field(default_factory=dict)
|
||||
metadata: Mapping[str, object] = field(default_factory=dict)
|
||||
final_output_type: str = "text"
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "metadata", MappingProxyType(dict(self.metadata)))
|
||||
|
||||
|
||||
class DuplexRuntimeExtension(Protocol):
|
||||
"""Pure model policy invoked by the experimental duplex control plane."""
|
||||
|
||||
def configure_sampling_params(
|
||||
self,
|
||||
*,
|
||||
runtime_config: dict[str, Any],
|
||||
defaults: tuple[object, ...],
|
||||
) -> tuple[object, ...]: ...
|
||||
|
||||
def plan_append(
|
||||
self,
|
||||
*,
|
||||
request_id: str,
|
||||
fence: DuplexFence,
|
||||
session_config: dict[str, Any],
|
||||
runtime_config: dict[str, Any],
|
||||
seq: int,
|
||||
turn_seq: int,
|
||||
mode: DuplexInputMode,
|
||||
payload: object,
|
||||
final: bool,
|
||||
sampling_params: object,
|
||||
) -> DuplexAppendPlan: ...
|
||||
|
||||
def decide_output(
|
||||
self,
|
||||
*,
|
||||
stage_id: int,
|
||||
final_stage_id: int,
|
||||
segment_finished: bool,
|
||||
segment_token_ids: tuple[int, ...],
|
||||
segment_output_metadata: dict[str, Any],
|
||||
output: object,
|
||||
) -> DuplexOutputDecision | None: ...
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DuplexRequestIdentity:
|
||||
session_id: str
|
||||
@@ -112,8 +60,8 @@ class DuplexStageRequestContext:
|
||||
final_stage_id: int
|
||||
config_generation: int
|
||||
sampling_params: tuple[object, ...]
|
||||
session_config: Mapping[str, Any] = field(default_factory=dict)
|
||||
runtime_config: Mapping[str, Any] = field(default_factory=dict)
|
||||
session_config: Mapping[str, object] = field(default_factory=dict)
|
||||
runtime_config: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "sampling_params", tuple(self.sampling_params))
|
||||
@@ -128,7 +76,7 @@ class DuplexStageRequestContext:
|
||||
@dataclass(frozen=True)
|
||||
class DuplexStageSubmission:
|
||||
context: DuplexStageRequestContext
|
||||
prompt: Mapping[str, Any]
|
||||
prompt: Mapping[str, object]
|
||||
already_submitted: bool
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
@@ -148,7 +96,7 @@ class DuplexOutputContext:
|
||||
final_stage_id: int
|
||||
segment_finished: bool
|
||||
segment_token_ids: tuple[int, ...] = ()
|
||||
segment_output_metadata: Mapping[str, Any] = field(default_factory=dict)
|
||||
segment_output_metadata: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "segment_token_ids", tuple(self.segment_token_ids))
|
||||
@@ -159,53 +107,27 @@ class DuplexOutputContext:
|
||||
)
|
||||
|
||||
|
||||
class DuplexStagePort(Protocol):
|
||||
class DuplexStagePort(ABC):
|
||||
"""Narrow stage-management surface the session runner/manager use (implemented by DuplexOrchestrator)."""
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def stage_count(self) -> int: ...
|
||||
|
||||
@abstractmethod
|
||||
def sampling_defaults(self) -> tuple[object, ...]: ...
|
||||
|
||||
@abstractmethod
|
||||
def ensure_request(self, context: DuplexStageRequestContext) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
async def submit(self, submission: DuplexStageSubmission) -> DuplexStageSubmissionResult: ...
|
||||
|
||||
@abstractmethod
|
||||
async def cleanup(self, request_ids: list[str], *, abort: bool = False) -> None: ...
|
||||
|
||||
|
||||
class DuplexControlPlanePort(Protocol):
|
||||
@property
|
||||
def sessions(self) -> object: ...
|
||||
|
||||
def accepts(self, message: object) -> bool: ...
|
||||
|
||||
def dispatch(self, message: object) -> None: ...
|
||||
|
||||
async def shutdown(self) -> None: ...
|
||||
|
||||
def close_sessions_for_request_ids(self, request_ids: list[str]) -> dict[str, list[str]]: ...
|
||||
|
||||
def finalize_closed_sessions(self, session_ids: Iterable[str]) -> None: ...
|
||||
|
||||
def session_for_identity(self, identity: DuplexRequestIdentity | None) -> object | None: ...
|
||||
|
||||
def decide_output(
|
||||
self,
|
||||
stage_id: int,
|
||||
output: object,
|
||||
context: DuplexOutputContext | None,
|
||||
) -> DuplexOutputDecision | None: ...
|
||||
|
||||
|
||||
class CorrelatedRpcTransport(Protocol):
|
||||
def execute(
|
||||
self,
|
||||
key: tuple[str, str],
|
||||
message: EngineQueueMessage,
|
||||
*,
|
||||
timeout: float | None,
|
||||
timeout_message: str,
|
||||
block_on_submit: bool = False,
|
||||
) -> EngineQueueMessage: ...
|
||||
@abstractmethod
|
||||
async def abort_requests(self, request_ids: list[str]) -> None: ...
|
||||
|
||||
|
||||
def duplex_data_plane_request_info(result: dict[str, object]) -> tuple[str | None, int | None]:
|
||||
@@ -232,20 +154,19 @@ def duplex_resource_request_id(fence: DuplexFence, role: str) -> str:
|
||||
):
|
||||
raise ValueError(f"invalid duplex resource role: {role!r}")
|
||||
encoded_session_id = base64.urlsafe_b64encode(fence.session_id.encode("utf-8")).decode("ascii").rstrip("=")
|
||||
return f"duplex-s.{encoded_session_id}.i.{fence.incarnation}.e.{fence.epoch}.r.{role}"
|
||||
return f"duplex-s.{encoded_session_id}.e.{fence.epoch}.r.{role}"
|
||||
|
||||
|
||||
def duplex_resource_request_belongs_to_session(request_id: str, session_id: str) -> bool:
|
||||
"""Return whether a current-format resource request belongs to a session."""
|
||||
parts = request_id.split(".")
|
||||
if len(parts) != 8 or parts[0] != "duplex-s" or parts[2] != "i" or parts[4] != "e" or parts[6] != "r":
|
||||
if len(parts) != 6 or parts[0] != "duplex-s" or parts[2] != "e" or parts[4] != "r":
|
||||
return False
|
||||
try:
|
||||
int(parts[3])
|
||||
int(parts[5])
|
||||
except ValueError:
|
||||
return False
|
||||
role = parts[7]
|
||||
role = parts[5]
|
||||
if not role or any(
|
||||
character not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-" for character in role
|
||||
):
|
||||
@@ -255,21 +176,16 @@ def duplex_resource_request_belongs_to_session(request_id: str, session_id: str)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CorrelatedRpcTransport",
|
||||
"DuplexFence",
|
||||
"DuplexAppendPlan",
|
||||
"DuplexControlPlanePort",
|
||||
"DuplexInputMode",
|
||||
"DuplexOutputAction",
|
||||
"DuplexOutputContext",
|
||||
"DuplexOutputDecision",
|
||||
"DuplexRequestIdentity",
|
||||
"DuplexRuntimeCapabilities",
|
||||
"DuplexRuntimeExtension",
|
||||
"DuplexStagePort",
|
||||
"DuplexStageRequestContext",
|
||||
"DuplexStageSubmission",
|
||||
"DuplexStageSubmissionResult",
|
||||
"SessionMode",
|
||||
"duplex_data_plane_request_info",
|
||||
"duplex_resource_request_belongs_to_session",
|
||||
"duplex_resource_request_id",
|
||||
|
||||
@@ -1,228 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from collections.abc import Callable
|
||||
|
||||
from vllm_omni.engine.duplex.contracts import CorrelatedRpcTransport
|
||||
from vllm_omni.engine.duplex.lease import DuplexLeaseActivity
|
||||
from vllm_omni.engine.duplex.messages import (
|
||||
AppendDuplexInputMessage,
|
||||
CloseDuplexSessionMessage,
|
||||
DuplexControlResultMessage,
|
||||
DuplexFence,
|
||||
OpenDuplexSessionMessage,
|
||||
ResumeDuplexSessionMessage,
|
||||
SignalDuplexTurnMessage,
|
||||
TouchDuplexSessionMessage,
|
||||
)
|
||||
|
||||
DuplexControlMessage = (
|
||||
OpenDuplexSessionMessage
|
||||
| AppendDuplexInputMessage
|
||||
| SignalDuplexTurnMessage
|
||||
| CloseDuplexSessionMessage
|
||||
| TouchDuplexSessionMessage
|
||||
| ResumeDuplexSessionMessage
|
||||
)
|
||||
|
||||
|
||||
class DuplexControlRequestError(RuntimeError):
|
||||
"""Typed client-side failure returned by the duplex control plane."""
|
||||
|
||||
def __init__(self, result: dict[str, object]) -> None:
|
||||
error = result.get("error")
|
||||
error_data = error if isinstance(error, dict) else {}
|
||||
self.result = result
|
||||
self.code = str(error_data.get("code") or "internal_error")
|
||||
self.retryable = bool(error_data.get("retryable", False))
|
||||
accepted_fence = result.get("accepted_fence")
|
||||
self.accepted_fence = accepted_fence if isinstance(accepted_fence, DuplexFence) else None
|
||||
lease_generation = result.get("lease_generation")
|
||||
self.lease_generation = lease_generation if isinstance(lease_generation, int) else None
|
||||
super().__init__(f"duplex {result.get('operation')} failed: {result}")
|
||||
|
||||
|
||||
class DuplexControlClient:
|
||||
"""Builds duplex commands on top of an engine-owned RPC transport."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
transport: CorrelatedRpcTransport,
|
||||
*,
|
||||
control_id_factory: Callable[[], str] | None = None,
|
||||
) -> None:
|
||||
self._transport = transport
|
||||
self._control_id_factory = control_id_factory or (lambda: uuid.uuid4().hex)
|
||||
|
||||
def execute(self, message: DuplexControlMessage, *, timeout: float | None) -> dict[str, object]:
|
||||
result_message = self._transport.execute(
|
||||
("duplex", message.control_id),
|
||||
message,
|
||||
timeout=timeout,
|
||||
timeout_message=f"duplex control timed out after {timeout} seconds",
|
||||
)
|
||||
if not isinstance(result_message, DuplexControlResultMessage):
|
||||
raise RuntimeError(f"unexpected duplex control result type: {type(result_message).__name__}")
|
||||
if result_message.fence != message.fence:
|
||||
raise RuntimeError(
|
||||
f"duplex control fence mismatch: expected {message.fence!r}, got {result_message.fence!r}"
|
||||
)
|
||||
result = {
|
||||
"fence": result_message.fence,
|
||||
"operation": result_message.operation,
|
||||
"session_id": result_message.session_id,
|
||||
"ok": result_message.ok,
|
||||
"stage_results": list(result_message.stage_results),
|
||||
"unsupported_count": result_message.unsupported_count,
|
||||
"error_count": result_message.error_count,
|
||||
"accepted_fence": result_message.accepted_fence,
|
||||
"lease_generation": result_message.lease_generation,
|
||||
"error": (
|
||||
{
|
||||
"code": result_message.error.code,
|
||||
"message": result_message.error.message,
|
||||
"retryable": result_message.error.retryable,
|
||||
}
|
||||
if result_message.error is not None
|
||||
else None
|
||||
),
|
||||
}
|
||||
if not result_message.ok:
|
||||
raise DuplexControlRequestError(result)
|
||||
return result
|
||||
|
||||
def open(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
session_mode: str,
|
||||
capabilities: dict[str, object] | None,
|
||||
session_config: dict[str, object] | None,
|
||||
runtime_config: dict[str, object] | None,
|
||||
fence: DuplexFence,
|
||||
timeout: float | None,
|
||||
) -> dict[str, object]:
|
||||
return self.execute(
|
||||
OpenDuplexSessionMessage(
|
||||
control_id=self._control_id_factory(),
|
||||
fence=fence,
|
||||
session_id=session_id,
|
||||
session_mode=session_mode,
|
||||
capabilities=dict(capabilities or {}),
|
||||
session_config=dict(session_config or {}),
|
||||
runtime_config=dict(runtime_config or {}),
|
||||
),
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
def append(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
mode: str,
|
||||
payload: object,
|
||||
operation_id: str | None,
|
||||
final: bool,
|
||||
expected_epoch: int | None,
|
||||
fence: DuplexFence,
|
||||
timeout: float | None,
|
||||
) -> dict[str, object]:
|
||||
if expected_epoch is not None and expected_epoch != fence.epoch:
|
||||
raise ValueError("expected_epoch must match fence.epoch")
|
||||
return self.execute(
|
||||
AppendDuplexInputMessage(
|
||||
control_id=self._control_id_factory(),
|
||||
operation_id=operation_id,
|
||||
fence=fence,
|
||||
session_id=session_id,
|
||||
expected_epoch=expected_epoch,
|
||||
mode=mode,
|
||||
payload=payload,
|
||||
final=final,
|
||||
),
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
def signal(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
event: str,
|
||||
fence: DuplexFence,
|
||||
next_fence: DuplexFence | None,
|
||||
session_config: dict[str, object] | None,
|
||||
runtime_config: dict[str, object] | None,
|
||||
timeout: float | None,
|
||||
) -> dict[str, object]:
|
||||
return self.execute(
|
||||
SignalDuplexTurnMessage(
|
||||
control_id=self._control_id_factory(),
|
||||
fence=fence,
|
||||
session_id=session_id,
|
||||
event=event,
|
||||
next_fence=next_fence,
|
||||
session_config=dict(session_config) if session_config is not None else None,
|
||||
runtime_config=dict(runtime_config) if runtime_config is not None else None,
|
||||
),
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
def close(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
reason: str,
|
||||
fence: DuplexFence,
|
||||
timeout: float | None,
|
||||
) -> dict[str, object]:
|
||||
return self.execute(
|
||||
CloseDuplexSessionMessage(
|
||||
control_id=self._control_id_factory(),
|
||||
fence=fence,
|
||||
session_id=session_id,
|
||||
reason=reason,
|
||||
),
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
def touch(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
fence: DuplexFence,
|
||||
activity: DuplexLeaseActivity,
|
||||
timeout: float | None,
|
||||
) -> dict[str, object]:
|
||||
return self.execute(
|
||||
TouchDuplexSessionMessage(
|
||||
control_id=self._control_id_factory(),
|
||||
fence=fence,
|
||||
session_id=session_id,
|
||||
activity=activity.value,
|
||||
),
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
def resume(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
fence: DuplexFence,
|
||||
expected_lease_generation: int,
|
||||
timeout: float | None,
|
||||
) -> dict[str, object]:
|
||||
return self.execute(
|
||||
ResumeDuplexSessionMessage(
|
||||
control_id=self._control_id_factory(),
|
||||
fence=fence,
|
||||
session_id=session_id,
|
||||
expected_lease_generation=expected_lease_generation,
|
||||
),
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["CorrelatedRpcTransport", "DuplexControlClient", "DuplexControlMessage"]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,756 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Typed events emitted by a duplex session.
|
||||
|
||||
Every public event is a frozen dataclass with explicit fields. The Realtime
|
||||
wire JSON is *derived* from those fields by :meth:`DuplexEvent.to_realtime`,
|
||||
which is pure: it never consults session state. The stateful part (response /
|
||||
item ids, content-part bookkeeping) lives in
|
||||
``vllm_omni.engine.duplex.realtime_events`` on the session runner and is
|
||||
consumed when the events are *constructed*.
|
||||
|
||||
``session_id`` / ``epoch`` are bound by
|
||||
``DuplexSessionManager.emit`` when an event leaves the runner; producers
|
||||
(projector, serving handshake helpers) build events with the defaults.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field, fields
|
||||
from typing import ClassVar, cast
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
def new_event_id() -> str:
|
||||
return f"event_{uuid4().hex}"
|
||||
|
||||
|
||||
#: OpenAI Realtime ``error.type`` for each internal error code.
|
||||
REALTIME_ERROR_TYPES_BY_CODE: dict[str, str] = {
|
||||
"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_append_failed": "server_error",
|
||||
"runtime_append_task_failed": "server_error",
|
||||
"runtime_signal_failed": "server_error",
|
||||
"runtime_abort_failed": "server_error",
|
||||
"runtime_data_plane_stream_failed": "server_error",
|
||||
"runtime_data_plane_text_without_audio": "server_error",
|
||||
"resource_exhausted": "rate_limit_error",
|
||||
"session_exists": "invalid_request_error",
|
||||
"session_closed": "invalid_request_error",
|
||||
"unknown_session": "invalid_request_error",
|
||||
"invalid_duplex_runtime_config": "invalid_request_error",
|
||||
"instructions_update_unsupported": "invalid_request_error",
|
||||
"persona_update_unsupported": "invalid_request_error",
|
||||
"voice_update_unsupported": "invalid_request_error",
|
||||
"unsupported_nemotron_duplex_mode": "invalid_request_error",
|
||||
"unsupported_native_response_options": "invalid_request_error",
|
||||
"runtime_touch_failed": "server_error",
|
||||
"engine_error": "server_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",
|
||||
"text_only_turn_unsupported": "invalid_request_error",
|
||||
"commit_aborted": "server_error",
|
||||
"input_audio_buffer_empty": "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_turn_detection": "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",
|
||||
"invalid_video_frames": "invalid_request_error",
|
||||
"invalid_function_call_output": "invalid_request_error",
|
||||
"server_vad_unavailable": "server_error",
|
||||
}
|
||||
|
||||
_IDENTITY_FIELDS = frozenset({"session_id", "epoch", "event_id"})
|
||||
|
||||
|
||||
def _wire_value(value: object) -> object:
|
||||
if isinstance(value, Mapping):
|
||||
return {str(k): _wire_value(v) for k, v in value.items()}
|
||||
if isinstance(value, tuple | list):
|
||||
return [_wire_value(v) for v in value]
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class DuplexEvent:
|
||||
"""Base of every public session event."""
|
||||
|
||||
#: Realtime ``type`` this class renders to.
|
||||
wire_type: ClassVar[str] = ""
|
||||
#: Fields that are omitted from the wire object when ``None``.
|
||||
optional_wire_fields: ClassVar[frozenset[str]] = frozenset()
|
||||
|
||||
session_id: str = ""
|
||||
epoch: int | None = None
|
||||
#: Server event id (OpenAI ``event_id``); generated at construction.
|
||||
event_id: str = field(default_factory=new_event_id)
|
||||
|
||||
# ---- identity ----
|
||||
|
||||
@property
|
||||
def type(self) -> str:
|
||||
return self.wire_type
|
||||
|
||||
@property
|
||||
def is_terminal(self) -> bool:
|
||||
return False
|
||||
|
||||
# ---- generic accessors (None when the class has no such field) ----
|
||||
|
||||
@property
|
||||
def response_id(self) -> str | None:
|
||||
return None
|
||||
|
||||
@property
|
||||
def item_id(self) -> str | None:
|
||||
return None
|
||||
|
||||
@property
|
||||
def text(self) -> str | None:
|
||||
return None
|
||||
|
||||
@property
|
||||
def audio(self) -> bytes | None:
|
||||
return None
|
||||
|
||||
# ---- wire rendering (pure) ----
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
data: dict[str, object] = {}
|
||||
for f in fields(self):
|
||||
if f.name in _IDENTITY_FIELDS:
|
||||
continue
|
||||
value = getattr(self, f.name)
|
||||
if value is None and f.name in self.optional_wire_fields:
|
||||
continue
|
||||
data[f.name] = _wire_value(value)
|
||||
return data
|
||||
|
||||
def to_realtime(self) -> dict[str, object]:
|
||||
"""The Realtime wire JSON object for this event (derived from the fields)."""
|
||||
return {"type": self.wire_type, "event_id": self.event_id, **self._wire_fields()}
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover - debugging aid
|
||||
return f"{type(self).__name__}(type={self.wire_type!r}, session_id={self.session_id!r}, epoch={self.epoch!r})"
|
||||
|
||||
|
||||
# ---- session lifecycle ----
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionCreated(DuplexEvent):
|
||||
wire_type = "session.created"
|
||||
optional_wire_fields = frozenset({"attachment_generation", "resume_token"})
|
||||
|
||||
session: Mapping[str, object] = field(default_factory=dict)
|
||||
#: Transport resume credentials (set by the websocket handler when resume is supported).
|
||||
attachment_generation: int | None = None
|
||||
resume_token: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionUpdated(DuplexEvent):
|
||||
wire_type = "session.updated"
|
||||
|
||||
session: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionResumed(SessionCreated):
|
||||
wire_type = "session.resumed"
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"session_id": self.session_id, **DuplexEvent._wire_fields(self)}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionReplaced(DuplexEvent):
|
||||
"""A newer connection took the session over (sent to the replaced socket)."""
|
||||
|
||||
wire_type = "session.replaced"
|
||||
|
||||
attachment_generation: int = 0
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"session_id": self.session_id, **DuplexEvent._wire_fields(self)}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionResyncRequired(DuplexEvent):
|
||||
"""The replay journal cannot bridge the gap; the client must start over."""
|
||||
|
||||
wire_type = "session.resync_required"
|
||||
|
||||
reason: str = "journal_gap"
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"session_id": self.session_id, **DuplexEvent._wire_fields(self)}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionClosed(DuplexEvent):
|
||||
wire_type = "session.closed"
|
||||
|
||||
reason: str = "closed"
|
||||
#: The session-internal close event (kept for clients that inspect it).
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def is_terminal(self) -> bool:
|
||||
return True
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"session_id": self.session_id, "reason": self.reason, "event": _wire_value(self.details)}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionExpired(SessionClosed):
|
||||
wire_type = "session.expired"
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"session_id": self.session_id, "reason": self.reason}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionHeartbeatAck(DuplexEvent):
|
||||
wire_type = "session.heartbeat_ack"
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"session_id": self.session_id}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TurnEvent(DuplexEvent):
|
||||
"""Turn-state transition (``turn.event``)."""
|
||||
|
||||
wire_type = "turn.event"
|
||||
|
||||
event: str = ""
|
||||
turn_state: str = ""
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"session_id": self.session_id, "event": self.event, "turn_state": self.turn_state, "epoch": self.epoch}
|
||||
|
||||
|
||||
# ---- response lifecycle ----
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class _ResponseEvent(DuplexEvent):
|
||||
"""Events addressed to one response (and usually one output item / content part)."""
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
output_index: int = 0
|
||||
content_index: int = 0
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ResponseCreated(DuplexEvent):
|
||||
wire_type = "response.created"
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
response: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class Listen(DuplexEvent):
|
||||
"""The model decided to keep listening (no spoken response for this turn)."""
|
||||
|
||||
wire_type = "response.listen"
|
||||
optional_wire_fields = frozenset({"response_id"})
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
response: dict[str, object] = {
|
||||
"object": "realtime.response",
|
||||
"status": "listening",
|
||||
"metadata": _wire_value(self.details),
|
||||
}
|
||||
data: dict[str, object] = {"session_id": self.session_id, "epoch": self.epoch, "response": response}
|
||||
if self.response_id:
|
||||
response["id"] = self.response_id
|
||||
data["response_id"] = self.response_id
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class Speak(_ResponseEvent):
|
||||
wire_type = "response.speak"
|
||||
|
||||
metadata: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class OverlapDecision(DuplexEvent):
|
||||
wire_type = "overlap.decision"
|
||||
|
||||
policy: str | None = None
|
||||
action: str | None = None
|
||||
reason: str | None = None
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {
|
||||
"session_id": self.session_id,
|
||||
"epoch": self.epoch,
|
||||
"policy": self.policy,
|
||||
"action": self.action,
|
||||
"reason": self.reason,
|
||||
"metadata": _wire_value(self.details),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class OutputItemAdded(DuplexEvent):
|
||||
wire_type = "response.output_item.added"
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
output_index: int = 0
|
||||
item: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def item_id(self) -> str | None:
|
||||
value = self.item.get("id")
|
||||
return value if isinstance(value, str) else None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class OutputItemDone(OutputItemAdded):
|
||||
wire_type = "response.output_item.done"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ContentPartAdded(_ResponseEvent):
|
||||
wire_type = "response.content_part.added"
|
||||
|
||||
part: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ContentPartDone(ContentPartAdded):
|
||||
wire_type = "response.content_part.done"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class AudioDelta(_ResponseEvent):
|
||||
wire_type = "response.output_audio.delta"
|
||||
optional_wire_fields = frozenset({"sample_rate_hz", "metadata"})
|
||||
|
||||
#: Base64 audio in ``format``.
|
||||
delta: str = ""
|
||||
format: str = "pcm16"
|
||||
sample_rate_hz: int | None = None
|
||||
metadata: Mapping[str, object] | None = None
|
||||
|
||||
@property
|
||||
def audio(self) -> bytes | None:
|
||||
try:
|
||||
return base64.b64decode(self.delta)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class AudioDone(_ResponseEvent):
|
||||
wire_type = "response.output_audio.done"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TranscriptDelta(_ResponseEvent):
|
||||
wire_type = "response.output_audio_transcript.delta"
|
||||
|
||||
delta: str = ""
|
||||
|
||||
@property
|
||||
def text(self) -> str | None:
|
||||
return self.delta
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TranscriptDone(_ResponseEvent):
|
||||
wire_type = "response.output_audio_transcript.done"
|
||||
|
||||
transcript: str = ""
|
||||
|
||||
@property
|
||||
def text(self) -> str | None:
|
||||
return self.transcript
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TextDelta(_ResponseEvent):
|
||||
wire_type = "response.output_text.delta"
|
||||
|
||||
delta: str = ""
|
||||
|
||||
@property
|
||||
def text(self) -> str | None:
|
||||
return self.delta
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TextDone(_ResponseEvent):
|
||||
wire_type = "response.output_text.done"
|
||||
|
||||
text: str = "" # type: ignore[assignment]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class FunctionCallArgumentsDelta(DuplexEvent):
|
||||
wire_type = "response.function_call_arguments.delta"
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
output_index: int = 0
|
||||
call_id: str = ""
|
||||
delta: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class FunctionCallArgumentsDone(DuplexEvent):
|
||||
wire_type = "response.function_call_arguments.done"
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
output_index: int = 0
|
||||
call_id: str = ""
|
||||
arguments: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ResponseDone(DuplexEvent):
|
||||
wire_type = "response.done"
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
response: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def status(self) -> str | None:
|
||||
value = self.response.get("status")
|
||||
return value if isinstance(value, str) else None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class RateLimitsUpdated(DuplexEvent):
|
||||
wire_type = "rate_limits.updated"
|
||||
|
||||
rate_limits: tuple[Mapping[str, object], ...] = ()
|
||||
|
||||
|
||||
# ---- input buffer / conversation ----
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class InputCommitted(DuplexEvent):
|
||||
wire_type = "input_audio_buffer.committed"
|
||||
|
||||
previous_item_id: str | None = None
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
#: The session-internal ``input.committed`` event.
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {
|
||||
"previous_item_id": self.previous_item_id,
|
||||
"item_id": self.item_id,
|
||||
"event": _wire_value(self.details),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class InputCleared(DuplexEvent):
|
||||
wire_type = "input_audio_buffer.cleared"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SpeechStarted(DuplexEvent):
|
||||
wire_type = "input_audio_buffer.speech_started"
|
||||
|
||||
audio_start_ms: int = 0
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SpeechStopped(DuplexEvent):
|
||||
wire_type = "input_audio_buffer.speech_stopped"
|
||||
|
||||
audio_end_ms: int = 0
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class _ItemEvent(DuplexEvent):
|
||||
previous_item_id: str | None = None
|
||||
item: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def item_id(self) -> str | None:
|
||||
value = self.item.get("id")
|
||||
return value if isinstance(value, str) else None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ItemAdded(_ItemEvent):
|
||||
wire_type = "conversation.item.added"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ItemCreated(_ItemEvent):
|
||||
wire_type = "conversation.item.created"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ItemDone(_ItemEvent):
|
||||
wire_type = "conversation.item.done"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ItemRetrieved(DuplexEvent):
|
||||
wire_type = "conversation.item.retrieved"
|
||||
|
||||
item: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def item_id(self) -> str | None:
|
||||
value = self.item.get("id")
|
||||
return value if isinstance(value, str) else None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ItemDeleted(DuplexEvent):
|
||||
wire_type = "conversation.item.deleted"
|
||||
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"item_id": self.item_id, "event": _wire_value(self.details)}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ItemTruncated(DuplexEvent):
|
||||
wire_type = "conversation.item.truncated"
|
||||
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
content_index: int = 0
|
||||
audio_end_ms: int = 0
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {
|
||||
"item_id": self.item_id,
|
||||
"content_index": self.content_index,
|
||||
"audio_end_ms": self.audio_end_ms,
|
||||
"event": _wire_value(self.details),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class InputTranscriptionCompleted(DuplexEvent):
|
||||
wire_type = "conversation.item.input_audio_transcription.completed"
|
||||
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
content_index: int = 0
|
||||
transcript: str = ""
|
||||
|
||||
@property
|
||||
def text(self) -> str | None:
|
||||
return self.transcript
|
||||
|
||||
|
||||
# ---- playback / control ----
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class OutputAudioCleared(DuplexEvent):
|
||||
wire_type = "output_audio_buffer.cleared"
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class PlaybackAcknowledged(DuplexEvent):
|
||||
wire_type = "playback.acknowledged"
|
||||
|
||||
#: The session-internal ``playback.acknowledged`` event (cursor, committed_ms ...).
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"event": _wire_value(self.details)}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ErrorEvent(DuplexEvent):
|
||||
wire_type = "error"
|
||||
|
||||
code: str = "internal_error"
|
||||
message: str = ""
|
||||
#: Client ``event_id`` this error answers (OpenAI ``error.event_id``).
|
||||
related_event_id: str | None = None
|
||||
param: str | None = None
|
||||
#: Extra keys merged into the wire ``error`` object (``retryable`` ...).
|
||||
extra: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def error_type(self) -> str:
|
||||
return REALTIME_ERROR_TYPES_BY_CODE.get(self.code, "invalid_request_error")
|
||||
|
||||
@property
|
||||
def error(self) -> dict[str, object]:
|
||||
error: dict[str, object] = {"type": self.error_type, "code": self.code, "message": self.message}
|
||||
if self.related_event_id:
|
||||
error["event_id"] = self.related_event_id
|
||||
if self.param:
|
||||
error["param"] = self.param
|
||||
error.update(cast("Mapping[str, object]", _wire_value(self.extra)))
|
||||
return error
|
||||
|
||||
@property
|
||||
def text(self) -> str | None:
|
||||
return self.message
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"error": self.error}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class DuplexRawEvent(DuplexEvent):
|
||||
"""A session-internal event with no dedicated Realtime type (``duplex.<internal type>``)."""
|
||||
|
||||
wire_type = "duplex.raw"
|
||||
|
||||
internal_type: str = ""
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def type(self) -> str:
|
||||
return f"duplex.{self.internal_type}"
|
||||
|
||||
def to_realtime(self) -> dict[str, object]:
|
||||
return {"type": self.type, "event_id": self.event_id, "event": _wire_value(self.details)}
|
||||
|
||||
|
||||
def error_event(
|
||||
code: str,
|
||||
message: str,
|
||||
*,
|
||||
event_id: object | None = None,
|
||||
param: object | None = None,
|
||||
extra: Mapping[str, object] | None = None,
|
||||
) -> ErrorEvent:
|
||||
"""Build the error event for an internal code; ``event_id`` is the *client* event id."""
|
||||
return ErrorEvent(
|
||||
code=code,
|
||||
message=message,
|
||||
related_event_id=event_id if isinstance(event_id, str) and event_id else None,
|
||||
param=param if isinstance(param, str) and param else None,
|
||||
extra=dict(extra or {}),
|
||||
)
|
||||
|
||||
|
||||
#: Internal events that terminate a response/session and must never be dropped as stale.
|
||||
DOMAIN_TERMINAL_EVENTS = frozenset(
|
||||
{
|
||||
"response.done",
|
||||
"response.listen",
|
||||
"audio.cancelled",
|
||||
"input.cancelled",
|
||||
"session.closed",
|
||||
}
|
||||
)
|
||||
|
||||
#: Internal streaming model-output events subject to epoch/close stale filtering.
|
||||
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",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DOMAIN_TERMINAL_EVENTS",
|
||||
"MODEL_OUTPUT_EVENTS",
|
||||
"REALTIME_ERROR_TYPES_BY_CODE",
|
||||
"AudioDelta",
|
||||
"AudioDone",
|
||||
"ContentPartAdded",
|
||||
"ContentPartDone",
|
||||
"DuplexEvent",
|
||||
"DuplexRawEvent",
|
||||
"ErrorEvent",
|
||||
"FunctionCallArgumentsDelta",
|
||||
"FunctionCallArgumentsDone",
|
||||
"InputCleared",
|
||||
"InputCommitted",
|
||||
"InputTranscriptionCompleted",
|
||||
"ItemAdded",
|
||||
"ItemCreated",
|
||||
"ItemDeleted",
|
||||
"ItemDone",
|
||||
"ItemRetrieved",
|
||||
"ItemTruncated",
|
||||
"Listen",
|
||||
"OutputAudioCleared",
|
||||
"OutputItemAdded",
|
||||
"OutputItemDone",
|
||||
"OverlapDecision",
|
||||
"PlaybackAcknowledged",
|
||||
"RateLimitsUpdated",
|
||||
"ResponseCreated",
|
||||
"ResponseDone",
|
||||
"SessionClosed",
|
||||
"SessionCreated",
|
||||
"SessionExpired",
|
||||
"SessionHeartbeatAck",
|
||||
"SessionReplaced",
|
||||
"SessionResumed",
|
||||
"SessionResyncRequired",
|
||||
"SessionUpdated",
|
||||
"Speak",
|
||||
"SpeechStarted",
|
||||
"SpeechStopped",
|
||||
"TextDelta",
|
||||
"TextDone",
|
||||
"TranscriptDelta",
|
||||
"TranscriptDone",
|
||||
"TurnEvent",
|
||||
"error_event",
|
||||
"new_event_id",
|
||||
]
|
||||
@@ -1,130 +1,114 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Queue contracts owned by the experimental duplex control plane."""
|
||||
"""Queue envelopes exchanged between ``DuplexOmniEngine`` and ``DuplexOrchestrator``.
|
||||
|
||||
Sessions live inside the engine (``DuplexSessionRunner`` on the orchestrator
|
||||
loop). The API layer only opens/closes/resumes/touches sessions through
|
||||
correlated RPC and pushes ``DuplexCommand`` objects one-way; every session
|
||||
output travels back as a ``DuplexSessionEventMessage``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
from typing import TYPE_CHECKING, Literal
|
||||
|
||||
from vllm_omni.engine.messages import EngineQueueMessage
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.engine.duplex.commands import DuplexCommand
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.events import DuplexEvent
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DuplexFence:
|
||||
"""Identity fence carried by experimental duplex control messages."""
|
||||
|
||||
session_id: str
|
||||
epoch: int = 0
|
||||
turn_id: int = 0
|
||||
response_seq: int = 0
|
||||
incarnation: int = 0
|
||||
class DuplexSessionError(RuntimeError):
|
||||
"""A session control operation was rejected by the engine."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
*,
|
||||
code: str = "internal_error",
|
||||
retryable: bool = False,
|
||||
session_id: str | None = None,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.retryable = retryable
|
||||
self.session_id = session_id
|
||||
|
||||
|
||||
class OpenDuplexSessionMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["open_duplex_session"] = "open_duplex_session"
|
||||
control_id: str
|
||||
fence: DuplexFence
|
||||
session_id: str
|
||||
session_mode: str = "duplex"
|
||||
capabilities: dict[str, object]
|
||||
session_config: dict[str, object] | None = None
|
||||
runtime_config: dict[str, object] | None = None
|
||||
|
||||
|
||||
class AppendDuplexInputMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["append_duplex_input"] = "append_duplex_input"
|
||||
control_id: str
|
||||
operation_id: str | None = None
|
||||
fence: DuplexFence
|
||||
session_id: str
|
||||
expected_epoch: int | None = None
|
||||
mode: str
|
||||
payload: object
|
||||
final: bool = False
|
||||
|
||||
|
||||
class SignalDuplexTurnMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["signal_duplex_turn"] = "signal_duplex_turn"
|
||||
control_id: str
|
||||
fence: DuplexFence
|
||||
session_id: str
|
||||
event: str
|
||||
next_fence: DuplexFence | None = None
|
||||
session_config: dict[str, object] | None = None
|
||||
runtime_config: dict[str, object] | None = None
|
||||
#: Already normalized by ``DuplexOmni``; the queue is in-process, so the object crosses as is.
|
||||
session_config: DuplexSessionConfig
|
||||
|
||||
|
||||
class CloseDuplexSessionMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["close_duplex_session"] = "close_duplex_session"
|
||||
control_id: str
|
||||
fence: DuplexFence
|
||||
session_id: str
|
||||
reason: str = "client_close"
|
||||
|
||||
|
||||
class TouchDuplexSessionMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["touch_duplex_session"] = "touch_duplex_session"
|
||||
control_id: str
|
||||
fence: DuplexFence
|
||||
session_id: str
|
||||
activity: str
|
||||
|
||||
|
||||
class ResumeDuplexSessionMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["resume_duplex_session"] = "resume_duplex_session"
|
||||
control_id: str
|
||||
fence: DuplexFence
|
||||
session_id: str
|
||||
expected_lease_generation: int
|
||||
|
||||
|
||||
class DuplexSessionLifecycleMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["duplex_session_lifecycle"] = "duplex_session_lifecycle"
|
||||
fence: DuplexFence
|
||||
class TouchDuplexSessionMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["touch_duplex_session"] = "touch_duplex_session"
|
||||
control_id: str
|
||||
session_id: str
|
||||
event: str
|
||||
reason: str
|
||||
lease_generation: int
|
||||
submitted_request_ids: list[str]
|
||||
reserved_request_ids: list[str]
|
||||
activity: str
|
||||
|
||||
|
||||
class DuplexControlError(EngineQueueMessage, kw_only=True):
|
||||
code: str
|
||||
message: str
|
||||
retryable: bool = False
|
||||
class DuplexSessionCommandMessage(EngineQueueMessage, kw_only=True):
|
||||
"""One-way session command; rejections come back as ``ErrorEvent``."""
|
||||
|
||||
type: Literal["duplex_session_command"] = "duplex_session_command"
|
||||
session_id: str
|
||||
command: DuplexCommand
|
||||
|
||||
|
||||
class DuplexControlResultMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["duplex_control_result"] = "duplex_control_result"
|
||||
control_id: str
|
||||
fence: DuplexFence
|
||||
operation: str
|
||||
session_id: str
|
||||
ok: bool
|
||||
stage_results: list[dict[str, object]]
|
||||
unsupported_count: int = 0
|
||||
error_count: int = 0
|
||||
error: DuplexControlError | None = None
|
||||
accepted_fence: DuplexFence | None = None
|
||||
lease_generation: int | None = None
|
||||
capabilities: DuplexCapabilities | None = None
|
||||
#: The Realtime ``session`` object of the session (wire payload, already a dict).
|
||||
public_session: dict[str, object] | None = None
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
error_retryable: bool = False
|
||||
|
||||
@property
|
||||
def rpc_correlation_key(self) -> tuple[str, str]:
|
||||
return ("duplex", self.control_id)
|
||||
|
||||
|
||||
class DuplexSessionEventMessage(EngineQueueMessage, kw_only=True):
|
||||
"""A typed session event on the engine output queue."""
|
||||
|
||||
type: Literal["duplex_session_event"] = "duplex_session_event"
|
||||
session_id: str
|
||||
event: DuplexEvent
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AppendDuplexInputMessage",
|
||||
"CloseDuplexSessionMessage",
|
||||
"DuplexControlError",
|
||||
"DuplexControlResultMessage",
|
||||
"DuplexFence",
|
||||
"DuplexSessionLifecycleMessage",
|
||||
"DuplexSessionCommandMessage",
|
||||
"DuplexSessionError",
|
||||
"DuplexSessionEventMessage",
|
||||
"OpenDuplexSessionMessage",
|
||||
"ResumeDuplexSessionMessage",
|
||||
"SignalDuplexTurnMessage",
|
||||
"TouchDuplexSessionMessage",
|
||||
]
|
||||
@@ -0,0 +1,329 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Model plugin contract for full-duplex models.
|
||||
|
||||
One ``DuplexModelPlugin`` subclass per model binds what used to be two dotted
|
||||
paths (the engine ``DuplexRuntimeExtension`` and the serving
|
||||
``ServingRuntimeAdapter``). Everything runs engine-side now, so the plugin is
|
||||
loaded once by ``DuplexOmniEngine`` and handed to ``DuplexOrchestrator`` /
|
||||
``DuplexSessionManager``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Callable, Iterable, Mapping
|
||||
from importlib import import_module
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexAppendPlan,
|
||||
DuplexFence,
|
||||
DuplexOutputDecision,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import ModelConfig
|
||||
|
||||
|
||||
class DuplexRuntimeConfigError(ValueError):
|
||||
"""A model 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[DuplexRuntimeConfigError] = DuplexRuntimeConfigError,
|
||||
) -> None:
|
||||
if new_value != current_value:
|
||||
raise error_cls(message, code=code)
|
||||
|
||||
|
||||
class PcmAppendReservation(ABC):
|
||||
operation_id: str
|
||||
payload: dict[str, object] | None
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def active(self) -> bool: ...
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def byte_count(self) -> int: ...
|
||||
|
||||
@abstractmethod
|
||||
def commit(self) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
def rollback(self) -> None: ...
|
||||
|
||||
|
||||
class PcmAppendBuffer(ABC):
|
||||
@property
|
||||
@abstractmethod
|
||||
def pending_byte_count(self) -> int: ...
|
||||
|
||||
@abstractmethod
|
||||
def clear(self) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
def clear_force_listen(self) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
def has_pending(self) -> bool: ...
|
||||
|
||||
@abstractmethod
|
||||
def has_reserved(self) -> bool: ...
|
||||
|
||||
@abstractmethod
|
||||
def prepare_append(
|
||||
self,
|
||||
payload: dict[str, object],
|
||||
*,
|
||||
operation_id: str,
|
||||
chunk_period_ms: int,
|
||||
allow_emit: bool,
|
||||
) -> PcmAppendReservation | None: ...
|
||||
|
||||
@abstractmethod
|
||||
def prepare_commit(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
chunk_period_ms: int,
|
||||
) -> PcmAppendReservation: ...
|
||||
|
||||
@abstractmethod
|
||||
def flush(self, *, chunk_period_ms: int) -> dict[str, object] | None: ...
|
||||
|
||||
|
||||
class DuplexModelSessionState(ABC):
|
||||
"""Model-owned per-session state; owned by the session runner (one per session)."""
|
||||
|
||||
audio_buffer: PcmAppendBuffer
|
||||
input_since_commit: bool
|
||||
speech_since_commit: bool
|
||||
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
|
||||
continuation_owner_id: str | None
|
||||
continuation_units: int
|
||||
pending_silence_task: asyncio.Task[bool] | None
|
||||
pending_silence_owner_id: str | None
|
||||
|
||||
@abstractmethod
|
||||
def retain_committed_audio(
|
||||
self,
|
||||
payload: dict[str, object],
|
||||
*,
|
||||
operation_id: str | None,
|
||||
reserved_bytes: int = 0,
|
||||
) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
def clear_committed_audio(self) -> int: ...
|
||||
|
||||
@abstractmethod
|
||||
def clear_continuation(self) -> None: ...
|
||||
|
||||
|
||||
class DuplexDataPlane(ABC):
|
||||
"""Projects raw stage outputs of one model into internal duplex events."""
|
||||
|
||||
@abstractmethod
|
||||
def begin_request(self, request_id: str) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
def is_terminal(self, request_id: str | None) -> bool: ...
|
||||
|
||||
@abstractmethod
|
||||
def mark_terminal(self, request_id: str) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
def close_stream(self, request_id: str) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
def close_session(self, session_id: str, *, active_request_id: str | None = None) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
def project(self, result: object, *, context: object | None = None) -> Iterable[dict[str, object]]: ...
|
||||
|
||||
|
||||
EncodeAudio = Callable[[object, int, str, float | None], str | None]
|
||||
|
||||
|
||||
class DuplexModelPlugin(ABC):
|
||||
"""Everything vLLM-Omni needs to know about one full-duplex model.
|
||||
|
||||
Engine policy (sampling params, append planning, output decisions) and
|
||||
session policy (capabilities, runtime configuration, per-session state,
|
||||
data-plane projection) live on the same object so a mismatch between the
|
||||
two halves is impossible by construction.
|
||||
"""
|
||||
|
||||
plugin_id: str = ""
|
||||
private_runtime_config_keys: frozenset[str] = frozenset()
|
||||
#: Samples per silence unit the runner appends to keep a model turn going.
|
||||
silence_continuation_samples: int = 16000
|
||||
data_plane: DuplexDataPlane
|
||||
|
||||
def __init__(self, encode_audio: EncodeAudio) -> None:
|
||||
# Constructor-only: concrete plugins hand the encoder to their data plane.
|
||||
del encode_audio
|
||||
|
||||
# ---- engine policy (was DuplexRuntimeExtension) ----
|
||||
|
||||
@abstractmethod
|
||||
def configure_sampling_params(
|
||||
self,
|
||||
*,
|
||||
runtime_config: dict[str, object],
|
||||
defaults: tuple[object, ...],
|
||||
) -> tuple[object, ...]: ...
|
||||
|
||||
@abstractmethod
|
||||
def plan_append(
|
||||
self,
|
||||
*,
|
||||
request_id: str,
|
||||
fence: DuplexFence,
|
||||
session_config: dict[str, object],
|
||||
runtime_config: dict[str, object],
|
||||
seq: int,
|
||||
turn_seq: int,
|
||||
payload: object,
|
||||
final: bool,
|
||||
sampling_params: object,
|
||||
) -> DuplexAppendPlan: ...
|
||||
|
||||
@abstractmethod
|
||||
def decide_output(
|
||||
self,
|
||||
*,
|
||||
stage_id: int,
|
||||
final_stage_id: int,
|
||||
segment_finished: bool,
|
||||
segment_token_ids: tuple[int, ...],
|
||||
segment_output_metadata: dict[str, object],
|
||||
output: object,
|
||||
) -> DuplexOutputDecision | None: ...
|
||||
|
||||
# ---- session policy (was ServingRuntimeAdapter) ----
|
||||
|
||||
@abstractmethod
|
||||
def create_session_state(self) -> DuplexModelSessionState: ...
|
||||
|
||||
@abstractmethod
|
||||
def capabilities(self, *, max_sessions: int) -> DuplexCapabilities: ...
|
||||
|
||||
@abstractmethod
|
||||
def validate_client_extra_body(self, extra_body: object) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
async def prepare_runtime_config(
|
||||
self, config: DuplexSessionConfig, *, model_config: ModelConfig | None
|
||||
) -> dict[str, object]: ...
|
||||
|
||||
@abstractmethod
|
||||
def runtime_config_for_update(
|
||||
self,
|
||||
config: DuplexSessionConfig,
|
||||
current: Mapping[str, object],
|
||||
) -> dict[str, object]: ...
|
||||
|
||||
@abstractmethod
|
||||
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: ...
|
||||
|
||||
# Optional hook: build the runtime config patch for a function-call output
|
||||
# item. Plugins without tools keep the default (no change).
|
||||
def runtime_config_for_function_output(
|
||||
self,
|
||||
config: DuplexSessionConfig,
|
||||
current: Mapping[str, object],
|
||||
item: Mapping[str, object],
|
||||
) -> dict[str, object] | None:
|
||||
del config, current, item
|
||||
return None
|
||||
|
||||
|
||||
def load_duplex_plugin(path: str, encode_audio: EncodeAudio) -> DuplexModelPlugin:
|
||||
module_name, separator, attribute_name = path.rpartition(".")
|
||||
if not separator:
|
||||
raise ValueError(f"Invalid duplex plugin path: {path!r}")
|
||||
plugin_type = getattr(import_module(module_name), attribute_name)
|
||||
plugin = plugin_type(encode_audio)
|
||||
if not isinstance(plugin, DuplexModelPlugin):
|
||||
raise TypeError(f"{path!r} is not a DuplexModelPlugin")
|
||||
if not plugin.plugin_id:
|
||||
raise TypeError("Duplex plugin must declare plugin_id")
|
||||
if not isinstance(getattr(plugin, "data_plane", None), DuplexDataPlane):
|
||||
raise TypeError("Duplex plugin must declare a DuplexDataPlane as data_plane")
|
||||
return plugin
|
||||
|
||||
|
||||
def validate_duplex_plugin_sampling(plugin: DuplexModelPlugin, *, sampling_defaults: tuple[object, ...]) -> None:
|
||||
"""Fail fast when the plugin cannot produce one sampling parameter per stage."""
|
||||
configured = plugin.configure_sampling_params(runtime_config={}, defaults=sampling_defaults)
|
||||
if not isinstance(configured, tuple):
|
||||
raise TypeError("Duplex plugin must return sampling parameters as a tuple")
|
||||
if len(configured) != len(sampling_defaults):
|
||||
raise ValueError("Duplex plugin must return one sampling parameter per stage")
|
||||
for stage_id, (value, default) in enumerate(zip(configured, sampling_defaults, strict=True)):
|
||||
if default is not None and not isinstance(value, type(default)):
|
||||
raise TypeError(
|
||||
"Duplex plugin sampling parameter type mismatch "
|
||||
f"for stage {stage_id}: expected {type(default).__name__}, got {type(value).__name__}"
|
||||
)
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DuplexDataPlane",
|
||||
"DuplexModelPlugin",
|
||||
"DuplexModelSessionState",
|
||||
"DuplexRuntimeConfigError",
|
||||
"EncodeAudio",
|
||||
"PcmAppendBuffer",
|
||||
"PcmAppendReservation",
|
||||
"coerce_int",
|
||||
"load_duplex_plugin",
|
||||
"payload_turn_id",
|
||||
"reject_changed_runtime_value",
|
||||
"validate_duplex_plugin_sampling",
|
||||
]
|
||||
@@ -0,0 +1,887 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""OpenAI Realtime client events -> :class:`DuplexCommand` (stateless).
|
||||
|
||||
This is the mapping half of the former ``entrypoints/duplex/realtime_input.py``
|
||||
translator. Everything that needed per-session state in the old translator
|
||||
(input-buffer emptiness for commits, response-id fallbacks for cancels,
|
||||
conversation-item lookups, VAD) is resolved by the session runner through the
|
||||
helpers on :class:`~vllm_omni.engine.duplex.realtime_events.RealtimeProjectionState`;
|
||||
the commands produced here carry the raw client intent only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import Any, cast
|
||||
from uuid import uuid4
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm_omni.engine.duplex.audio import convert_input_audio_with_rate
|
||||
from vllm_omni.engine.duplex.commands import (
|
||||
AckPlayback,
|
||||
AppendAudio,
|
||||
AppendText,
|
||||
BargeIn,
|
||||
CancelInput,
|
||||
CancelResponse,
|
||||
ClearInput,
|
||||
ClearOutputAudio,
|
||||
CloseSession,
|
||||
Commit,
|
||||
CreateItem,
|
||||
CreateResponse,
|
||||
DeleteItem,
|
||||
DuplexCommand,
|
||||
DuplexCommandError,
|
||||
Heartbeat,
|
||||
SignalTurn,
|
||||
TruncateItem,
|
||||
UpdateSession,
|
||||
)
|
||||
|
||||
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",
|
||||
}
|
||||
|
||||
#: Wire hint keys copied verbatim from a client append onto the internal payload.
|
||||
REALTIME_INPUT_HINT_KEYS = (
|
||||
"duration_ms",
|
||||
"audio_duration_ms",
|
||||
"audio_start_ms",
|
||||
"audio_end_ms",
|
||||
"is_speech",
|
||||
"speech",
|
||||
"speech_probability",
|
||||
"vad",
|
||||
"overlap_action",
|
||||
"overlap",
|
||||
"force_barge_in",
|
||||
"force_listen",
|
||||
"text",
|
||||
"transcript",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RealtimeInputDefaults:
|
||||
"""Session-level wire defaults an append may omit (derived from the session object)."""
|
||||
|
||||
input_audio_format: str = "pcm16"
|
||||
input_sample_rate_hz: int = 16000
|
||||
output_audio_format: str = "pcm16"
|
||||
output_sample_rate_hz: int | None = None
|
||||
overlap_silence_rms: float = 0.003
|
||||
|
||||
def with_session_payload(self, session_payload: Mapping[str, object]) -> RealtimeInputDefaults:
|
||||
"""Return defaults updated from a Realtime ``session`` object (session.update)."""
|
||||
values = apply_realtime_session_defaults(self, session_payload)
|
||||
return values
|
||||
|
||||
|
||||
# ---- audio format helpers ----
|
||||
|
||||
|
||||
def parse_realtime_audio_format(raw_format: object) -> tuple[object, int | None]:
|
||||
def normalize_format(fmt: str) -> str:
|
||||
normalized = fmt.lower()
|
||||
if normalized in {"audio/pcm", "pcm"}:
|
||||
return "pcm16"
|
||||
if normalized in {"audio/wav", "wav"}:
|
||||
return "wav"
|
||||
if normalized in {"audio/pcm16", "pcm16", "pcm_s16le", "s16le"}:
|
||||
return "pcm16"
|
||||
if normalized in {"audio/pcm_f32le", "pcm_f32le", "f32le"}:
|
||||
return "pcm_f32le"
|
||||
if normalized in {"audio/g711_ulaw", "g711_ulaw", "g711-ulaw", "ulaw", "mulaw"}:
|
||||
return "g711_ulaw"
|
||||
if normalized in {"audio/g711_alaw", "g711_alaw", "g711-alaw", "alaw"}:
|
||||
return "g711_alaw"
|
||||
return fmt
|
||||
|
||||
if isinstance(raw_format, str):
|
||||
return normalize_format(raw_format), None
|
||||
if not isinstance(raw_format, dict):
|
||||
return raw_format, None
|
||||
rate = raw_format.get("rate") or raw_format.get("sample_rate_hz") or raw_format.get("sample_rate")
|
||||
sample_rate_hz = int(rate) if isinstance(rate, int | float) and rate > 0 else None
|
||||
fmt = raw_format.get("type") or raw_format.get("format")
|
||||
if not isinstance(fmt, str):
|
||||
return raw_format, sample_rate_hz
|
||||
return normalize_format(fmt), sample_rate_hz
|
||||
|
||||
|
||||
def duplex_response_format(realtime_format: str) -> str:
|
||||
normalized = realtime_format.lower()
|
||||
if normalized in {"pcm16", "pcm_s16le", "s16le"}:
|
||||
return "pcm"
|
||||
if normalized in {"g711_ulaw", "g711_alaw"}:
|
||||
return "pcm"
|
||||
if normalized in {"wav", "pcm"}:
|
||||
return normalized
|
||||
return "wav"
|
||||
|
||||
|
||||
def realtime_output_format(duplex_format: object) -> str:
|
||||
if isinstance(duplex_format, str) and duplex_format.lower() in {"g711_ulaw", "g711_alaw"}:
|
||||
return duplex_format.lower()
|
||||
if isinstance(duplex_format, str) and duplex_format.lower() == "pcm":
|
||||
return "pcm16"
|
||||
return str(duplex_format or "wav")
|
||||
|
||||
|
||||
def is_supported_realtime_input_format(fmt: object) -> bool:
|
||||
return isinstance(fmt, str) and fmt.lower() in REALTIME_INPUT_AUDIO_FORMATS
|
||||
|
||||
|
||||
def realtime_audio_format_object(fmt: object, *, sample_rate_hz: int | None = None) -> dict[str, object]:
|
||||
if isinstance(fmt, str) and fmt.lower() in {"pcm16", "pcm_s16le", "s16le", "pcm"}:
|
||||
payload: dict[str, object] = {"type": "audio/pcm"}
|
||||
elif isinstance(fmt, str) and fmt.lower() == "pcm_f32le":
|
||||
payload = {"type": "audio/pcm_f32le"}
|
||||
elif isinstance(fmt, str) and fmt.lower() == "g711_ulaw":
|
||||
payload = {"type": "audio/g711_ulaw"}
|
||||
elif isinstance(fmt, str) and fmt.lower() == "g711_alaw":
|
||||
payload = {"type": "audio/g711_alaw"}
|
||||
else:
|
||||
payload = {"type": "audio/wav"}
|
||||
if sample_rate_hz is not None:
|
||||
payload["rate"] = int(sample_rate_hz)
|
||||
return payload
|
||||
|
||||
|
||||
def validate_realtime_session_audio_formats(session_payload: Mapping[str, object]) -> str | None:
|
||||
audio_config = session_payload.get("audio")
|
||||
input_format: object = session_payload.get("input_audio_format")
|
||||
if input_format is None and isinstance(audio_config, dict):
|
||||
audio_input = audio_config.get("input")
|
||||
if isinstance(audio_input, dict):
|
||||
input_format = audio_input.get("format")
|
||||
parsed_input, _ = parse_realtime_audio_format(input_format)
|
||||
if input_format is not None and not (
|
||||
isinstance(parsed_input, str) and parsed_input.lower() in REALTIME_INPUT_AUDIO_FORMATS
|
||||
):
|
||||
return f"Unsupported input_audio_format: {input_format}"
|
||||
|
||||
output_format: object = session_payload.get("output_audio_format") or session_payload.get("response_format")
|
||||
if output_format is None and isinstance(audio_config, dict):
|
||||
audio_output = audio_config.get("output")
|
||||
if isinstance(audio_output, dict):
|
||||
output_format = audio_output.get("format")
|
||||
parsed_output, _ = parse_realtime_audio_format(output_format)
|
||||
if output_format is not None and not (
|
||||
isinstance(parsed_output, str) and parsed_output.lower() in REALTIME_OUTPUT_AUDIO_FORMATS
|
||||
):
|
||||
return f"Unsupported output_audio_format: {output_format}"
|
||||
return None
|
||||
|
||||
|
||||
def validate_realtime_response_audio_formats(response_payload: Mapping[str, object]) -> str | None:
|
||||
output_format: object = response_payload.get("output_audio_format") or response_payload.get("response_format")
|
||||
audio_config = response_payload.get("audio")
|
||||
if output_format is None and isinstance(audio_config, dict):
|
||||
audio_output = audio_config.get("output")
|
||||
if isinstance(audio_output, dict):
|
||||
output_format = audio_output.get("format")
|
||||
parsed_output, _ = parse_realtime_audio_format(output_format)
|
||||
if output_format is not None and not (
|
||||
isinstance(parsed_output, str) and parsed_output.lower() in REALTIME_OUTPUT_AUDIO_FORMATS
|
||||
):
|
||||
return f"Unsupported output_audio_format: {output_format}"
|
||||
return None
|
||||
|
||||
|
||||
def validate_conversation_item_audio_formats(item: object) -> str | None:
|
||||
if not isinstance(item, dict):
|
||||
return None
|
||||
content = item.get("content")
|
||||
if not isinstance(content, list):
|
||||
return None
|
||||
for part in content:
|
||||
if not isinstance(part, dict):
|
||||
continue
|
||||
if part.get("type") not in {"input_audio", "audio"}:
|
||||
continue
|
||||
raw_format = part.get("format")
|
||||
parsed_format, _ = parse_realtime_audio_format(raw_format)
|
||||
if raw_format is not None and not (
|
||||
isinstance(parsed_format, str) and parsed_format.lower() in REALTIME_INPUT_AUDIO_FORMATS
|
||||
):
|
||||
return f"Unsupported input_audio format in conversation.item.create: {raw_format}"
|
||||
return None
|
||||
|
||||
|
||||
def apply_realtime_session_defaults(
|
||||
defaults: RealtimeInputDefaults,
|
||||
session_payload: Mapping[str, object],
|
||||
) -> RealtimeInputDefaults:
|
||||
"""Derive the wire defaults a Realtime ``session`` object declares."""
|
||||
input_format: object = session_payload.get("input_audio_format")
|
||||
audio_config = session_payload.get("audio")
|
||||
if input_format is None and isinstance(audio_config, dict):
|
||||
audio_input = audio_config.get("input")
|
||||
if isinstance(audio_input, dict):
|
||||
input_format = audio_input.get("format")
|
||||
input_format, input_rate = parse_realtime_audio_format(input_format)
|
||||
# Any: heterogeneous field values splatted into ``dataclasses.replace`` below.
|
||||
updates: dict[str, Any] = {}
|
||||
if isinstance(input_format, str) and input_format.lower() in REALTIME_INPUT_AUDIO_FORMATS:
|
||||
updates["input_audio_format"] = input_format
|
||||
output_format: object = session_payload.get("output_audio_format") or session_payload.get("response_format")
|
||||
output_rate_raw: object | None = None
|
||||
if output_format is None and isinstance(audio_config, dict):
|
||||
audio_output = audio_config.get("output")
|
||||
if isinstance(audio_output, dict):
|
||||
output_format = audio_output.get("format")
|
||||
output_rate_raw = audio_output.get("sample_rate_hz") or audio_output.get("sample_rate")
|
||||
output_format, output_rate = parse_realtime_audio_format(output_format)
|
||||
if output_rate is None and isinstance(output_rate_raw, int | float) and output_rate_raw > 0:
|
||||
output_rate = int(output_rate_raw)
|
||||
if isinstance(output_format, str) and output_format.lower() in REALTIME_OUTPUT_AUDIO_FORMATS:
|
||||
updates["output_audio_format"] = realtime_output_format(output_format)
|
||||
sample_rate = session_payload.get("sample_rate_hz") or session_payload.get("sample_rate")
|
||||
if sample_rate is None and isinstance(audio_config, dict):
|
||||
audio_input = audio_config.get("input")
|
||||
if isinstance(audio_input, dict):
|
||||
sample_rate = audio_input.get("sample_rate_hz") or audio_input.get("sample_rate")
|
||||
if sample_rate is None:
|
||||
sample_rate = input_rate
|
||||
if isinstance(sample_rate, int | float) and sample_rate > 0:
|
||||
updates["input_sample_rate_hz"] = int(sample_rate)
|
||||
if isinstance(output_rate, int | float) and output_rate > 0:
|
||||
updates["output_sample_rate_hz"] = int(output_rate)
|
||||
overlap_fields = realtime_overlap_fields(session_payload)
|
||||
overlap_silence_rms = overlap_fields.get("overlap_silence_rms")
|
||||
if isinstance(overlap_silence_rms, int | float):
|
||||
updates["overlap_silence_rms"] = max(0.0, float(overlap_silence_rms))
|
||||
return replace(defaults, **updates) if updates else defaults
|
||||
|
||||
|
||||
def realtime_overlap_fields(session_payload: Mapping[str, object]) -> dict[str, object]:
|
||||
fields: dict[str, object] = {}
|
||||
if isinstance(session_payload.get("overlap_policy"), str):
|
||||
fields["overlap_policy"] = session_payload["overlap_policy"]
|
||||
for key in ("overlap_short_ack_ms", "overlap_barge_in_ms", "overlap_silence_rms"):
|
||||
value = session_payload.get(key)
|
||||
if isinstance(value, int | float):
|
||||
fields[key] = value
|
||||
if isinstance(session_payload.get("playback_commit_policy"), str):
|
||||
fields["playback_commit_policy"] = session_payload["playback_commit_policy"]
|
||||
return fields
|
||||
|
||||
|
||||
def json_safe_realtime_payload(payload: Mapping[str, object]) -> dict[str, object]:
|
||||
clean: dict[str, object] = {}
|
||||
for key, value in payload.items():
|
||||
if key == "extra_body":
|
||||
continue
|
||||
if isinstance(value, str | int | float | bool) or value is None:
|
||||
clean[key] = value
|
||||
elif isinstance(value, dict):
|
||||
clean[key] = json_safe_realtime_payload(value)
|
||||
elif isinstance(value, list):
|
||||
clean[key] = [
|
||||
(json_safe_realtime_payload(item) if isinstance(item, dict) else item)
|
||||
for item in value
|
||||
if isinstance(item, str | int | float | bool | dict) or item is None
|
||||
]
|
||||
return clean
|
||||
|
||||
|
||||
def input_audio_transcription_config(session_payload: Mapping[str, object]) -> dict[str, object] | None:
|
||||
transcription = session_payload.get("input_audio_transcription")
|
||||
if isinstance(transcription, dict):
|
||||
return transcription
|
||||
audio_config = session_payload.get("audio")
|
||||
if not isinstance(audio_config, dict):
|
||||
return None
|
||||
audio_input = audio_config.get("input")
|
||||
if not isinstance(audio_input, dict):
|
||||
return None
|
||||
transcription = audio_input.get("transcription")
|
||||
return transcription if isinstance(transcription, dict) else None
|
||||
|
||||
|
||||
def realtime_max_output_tokens(value: object) -> int | None:
|
||||
"""Normalize Realtime max output tokens (``"inf"`` -> ``None``)."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str) and value.strip().lower() in {"inf", "infinity", "unlimited"}:
|
||||
return None
|
||||
if isinstance(value, int) and value > 0:
|
||||
return int(value)
|
||||
return None
|
||||
|
||||
|
||||
# ---- speech hints ----
|
||||
|
||||
|
||||
def input_explicitly_non_speech(event: Mapping[str, object]) -> bool:
|
||||
for key in ("is_speech", "speech"):
|
||||
value = event.get(key)
|
||||
if isinstance(value, bool):
|
||||
return not value
|
||||
vad = event.get("vad")
|
||||
if isinstance(vad, dict):
|
||||
value = vad.get("is_speech")
|
||||
if isinstance(value, bool):
|
||||
return not value
|
||||
probability = vad.get("speech_probability", vad.get("probability"))
|
||||
if isinstance(probability, int | float):
|
||||
return float(probability) < 0.5
|
||||
probability = event.get("speech_probability")
|
||||
return isinstance(probability, int | float) and float(probability) < 0.5
|
||||
|
||||
|
||||
def input_looks_like_speech(
|
||||
event: Mapping[str, object],
|
||||
*,
|
||||
audio: object,
|
||||
fmt: object,
|
||||
overlap_silence_rms: float,
|
||||
) -> bool:
|
||||
if input_explicitly_non_speech(event):
|
||||
return False
|
||||
for key in ("is_speech", "speech"):
|
||||
value = event.get(key)
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
vad = event.get("vad")
|
||||
if isinstance(vad, dict):
|
||||
probability = vad.get("speech_probability", vad.get("probability"))
|
||||
if isinstance(probability, int | float):
|
||||
return float(probability) >= 0.5
|
||||
probability = event.get("speech_probability")
|
||||
if isinstance(probability, int | float):
|
||||
return float(probability) >= 0.5
|
||||
if fmt != "pcm_f32le":
|
||||
return True
|
||||
if isinstance(audio, bytes | bytearray):
|
||||
raw = bytes(audio)
|
||||
elif isinstance(audio, str):
|
||||
try:
|
||||
raw = base64.b64decode(audio, validate=True)
|
||||
except (binascii.Error, ValueError):
|
||||
return True
|
||||
else:
|
||||
return True
|
||||
if len(raw) < 4 or len(raw) % 4 != 0:
|
||||
return True
|
||||
samples = np.frombuffer(raw, dtype=np.float32)
|
||||
if samples.size == 0:
|
||||
return False
|
||||
rms = float(np.sqrt(np.mean(np.square(samples.astype(np.float32)))))
|
||||
threshold = event.get("overlap_silence_rms")
|
||||
if not isinstance(threshold, int | float):
|
||||
vad = event.get("vad")
|
||||
if isinstance(vad, dict):
|
||||
threshold = vad.get("silence_rms")
|
||||
silence_rms = float(threshold) if isinstance(threshold, int | float) else overlap_silence_rms
|
||||
return rms >= max(0.0, silence_rms)
|
||||
|
||||
|
||||
def copy_realtime_input_hints(source: Mapping[str, object], target: dict[str, object]) -> None:
|
||||
for key in REALTIME_INPUT_HINT_KEYS:
|
||||
if key in source:
|
||||
target[key] = source[key]
|
||||
|
||||
|
||||
def validate_realtime_video_frames(video_frames: object, max_slice_nums: object) -> str | None:
|
||||
"""Validate omni-duplex camera frames on input_audio_buffer.append.
|
||||
|
||||
Wire contract matches the official MiniCPM-o duplex loop: one base
|
||||
base64 JPEG per ~1 s audio chunk, optionally followed by that unit's
|
||||
stacked composite tiling the sub-frames captured inside it (at most 2
|
||||
images either way). A caller-supplied ``max_slice_nums`` is rejected rather
|
||||
than silently ignored: slicing is Stage 0's decision here, and Stage 0
|
||||
already applies the official HD suggestion for a stacked unit
|
||||
(``max_slice_nums=[2, 1]``). The wire simply does not let the client choose
|
||||
it.
|
||||
"""
|
||||
if max_slice_nums not in (None, 1):
|
||||
return "max_slice_nums is not selectable on the wire; Stage0 slices stacked units itself"
|
||||
if not isinstance(video_frames, list):
|
||||
return "video_frames must be a list of base64-encoded images"
|
||||
frames = [frame for frame in video_frames if frame is not None]
|
||||
if len(frames) > 2:
|
||||
return "video_frames carries more than 2 frames for one append; send ~1 frame per 1 s chunk"
|
||||
for frame in frames:
|
||||
if not isinstance(frame, str) or not frame:
|
||||
return "video_frames entries must be non-empty base64 strings"
|
||||
if len(frame) > 4_000_000:
|
||||
return "video_frames entry exceeds 4MB base64; reduce capture resolution or JPEG quality"
|
||||
try:
|
||||
header = base64.b64decode(frame[:64] + "=" * (-len(frame[:64]) % 4))
|
||||
except (binascii.Error, ValueError):
|
||||
return "video_frames entries must be valid base64"
|
||||
if not (header.startswith(b"\xff\xd8") or header.startswith(b"\x89PNG")):
|
||||
return "video_frames entries must be JPEG or PNG images"
|
||||
return None
|
||||
|
||||
|
||||
# ---- conversation items ----
|
||||
|
||||
|
||||
def normalize_conversation_item(item: Mapping[str, object]) -> dict[str, object]:
|
||||
normalized = dict(item)
|
||||
normalized.setdefault("id", f"item_{uuid4().hex}")
|
||||
normalized.setdefault("object", "realtime.item")
|
||||
normalized.setdefault("type", "message")
|
||||
normalized.setdefault("status", "completed")
|
||||
if "role" not in normalized and normalized.get("type") == "message":
|
||||
normalized["role"] = "user"
|
||||
if not isinstance(normalized.get("content"), list):
|
||||
normalized["content"] = []
|
||||
return normalized
|
||||
|
||||
|
||||
def text_chars_for_audio_ms_from_marks(
|
||||
audio_end_ms: int,
|
||||
text_len: int,
|
||||
marks: list[object],
|
||||
*,
|
||||
final_ms: object | None = None,
|
||||
) -> int:
|
||||
if text_len <= 0:
|
||||
return 0
|
||||
clean_marks: list[tuple[int, int]] = []
|
||||
for mark in marks:
|
||||
if not isinstance(mark, dict):
|
||||
continue
|
||||
raw_text_chars = mark.get("text_chars")
|
||||
raw_audio_end_ms = mark.get("audio_end_ms", mark.get("audio_ms"))
|
||||
if not isinstance(raw_text_chars, int | float) or not isinstance(raw_audio_end_ms, int | float):
|
||||
continue
|
||||
clean_marks.append((max(0, int(raw_audio_end_ms)), min(text_len, max(0, int(raw_text_chars)))))
|
||||
if not clean_marks:
|
||||
return 0 if audio_end_ms <= 0 else text_len
|
||||
clean_marks.sort(key=lambda item: item[0])
|
||||
audio_end_ms = max(0, int(audio_end_ms))
|
||||
if audio_end_ms <= 0:
|
||||
return 0
|
||||
previous_ms = 0
|
||||
previous_chars = 0
|
||||
for mark_ms, mark_chars in clean_marks:
|
||||
mark_ms = max(previous_ms, mark_ms)
|
||||
mark_chars = max(previous_chars, min(text_len, mark_chars))
|
||||
if audio_end_ms <= mark_ms:
|
||||
if mark_ms <= previous_ms:
|
||||
return mark_chars
|
||||
ratio = (audio_end_ms - previous_ms) / max(1, mark_ms - previous_ms)
|
||||
return int(previous_chars + (mark_chars - previous_chars) * max(0.0, min(1.0, ratio)))
|
||||
previous_ms = mark_ms
|
||||
previous_chars = mark_chars
|
||||
if isinstance(final_ms, int | float) and int(final_ms) > previous_ms:
|
||||
if audio_end_ms >= int(final_ms):
|
||||
return text_len
|
||||
ratio = (audio_end_ms - previous_ms) / max(1, int(final_ms) - previous_ms)
|
||||
return int(previous_chars + (text_len - previous_chars) * max(0.0, min(1.0, ratio)))
|
||||
return text_len if audio_end_ms >= previous_ms else previous_chars
|
||||
|
||||
|
||||
def truncate_realtime_item_content(item: dict[str, object], *, content_index: int, audio_end_ms: int) -> None:
|
||||
content = item.get("content")
|
||||
if not isinstance(content, list) or not content:
|
||||
return
|
||||
index = max(0, int(content_index))
|
||||
if index >= len(content):
|
||||
return
|
||||
part = content[index]
|
||||
if not isinstance(part, dict):
|
||||
return
|
||||
transcript = part.get("transcript")
|
||||
if not isinstance(transcript, str) or not transcript:
|
||||
return
|
||||
marks = part.get("audio_text_marks")
|
||||
if isinstance(marks, list):
|
||||
keep_chars = text_chars_for_audio_ms_from_marks(
|
||||
audio_end_ms,
|
||||
len(transcript),
|
||||
marks,
|
||||
final_ms=part.get("audio_duration_ms") or part.get("duration_ms") or part.get("audio_ms"),
|
||||
)
|
||||
part["transcript"] = transcript[:keep_chars].rstrip()
|
||||
return
|
||||
duration_ms = part.get("audio_duration_ms") or part.get("duration_ms") or part.get("audio_ms")
|
||||
if isinstance(duration_ms, int | float) and duration_ms > 0:
|
||||
keep_chars = int(len(transcript) * max(0.0, min(1.0, int(audio_end_ms) / float(duration_ms))))
|
||||
part["transcript"] = transcript[:keep_chars].rstrip()
|
||||
elif audio_end_ms <= 0:
|
||||
part["transcript"] = ""
|
||||
|
||||
|
||||
def validate_realtime_item_truncate(item: Mapping[str, object], *, content_index: int, audio_end_ms: int) -> str | None:
|
||||
if item.get("type") != "message" or item.get("role") != "assistant":
|
||||
return "conversation.item.truncate only supports assistant message items"
|
||||
if audio_end_ms < 0:
|
||||
return "conversation.item.truncate requires non-negative audio_end_ms"
|
||||
content = item.get("content")
|
||||
if not isinstance(content, list) or not content:
|
||||
return None
|
||||
index = max(0, int(content_index))
|
||||
if index >= len(content):
|
||||
return f"conversation.item.truncate content_index out of range: {content_index}"
|
||||
part = content[index]
|
||||
if not isinstance(part, dict):
|
||||
return "conversation.item.truncate target content part is invalid"
|
||||
if part.get("type") not in {"audio", "output_audio"}:
|
||||
return "conversation.item.truncate target content part must be audio"
|
||||
duration_ms = part.get("audio_duration_ms") or part.get("duration_ms") or part.get("audio_ms")
|
||||
if isinstance(duration_ms, int | float) and int(duration_ms) >= 0 and audio_end_ms > int(duration_ms):
|
||||
return "conversation.item.truncate audio_end_ms exceeds item audio duration"
|
||||
return None
|
||||
|
||||
|
||||
def input_transcript_from_item(item: Mapping[str, object]) -> str:
|
||||
content = item.get("content")
|
||||
if not isinstance(content, list):
|
||||
return ""
|
||||
parts: list[str] = []
|
||||
for part in content:
|
||||
if not isinstance(part, dict):
|
||||
continue
|
||||
for key in ("transcript", "text"):
|
||||
value = part.get(key)
|
||||
if isinstance(value, str) and value:
|
||||
if part.get("type") in {"input_audio", "audio", "audio_transcript", "transcript"}:
|
||||
parts.append(value)
|
||||
break
|
||||
return "".join(parts).strip()
|
||||
|
||||
|
||||
# ---- append / item audio conversion ----
|
||||
|
||||
|
||||
def build_append_audio(
|
||||
event: Mapping[str, object],
|
||||
*,
|
||||
defaults: RealtimeInputDefaults,
|
||||
hints_source: Mapping[str, object] | None = None,
|
||||
) -> AppendAudio:
|
||||
"""Validate, convert (to 16 kHz ``pcm_f32le`` base64) and pack one audio append.
|
||||
|
||||
Speech classification without VAD (``is_speech`` on the command) uses the
|
||||
explicit wire hints and the RMS fallback exactly like the old translator.
|
||||
"""
|
||||
event_id = cast("str", event.get("event_id")) if isinstance(event.get("event_id"), str) else None
|
||||
audio = event.get("audio") or event.get("delta")
|
||||
fmt, format_rate = parse_realtime_audio_format(
|
||||
event.get("format") or event.get("input_audio_format") or defaults.input_audio_format
|
||||
)
|
||||
sample_rate_hz = (
|
||||
event.get("sample_rate_hz") or event.get("sample_rate") or format_rate or defaults.input_sample_rate_hz
|
||||
)
|
||||
if not is_supported_realtime_input_format(fmt):
|
||||
raise DuplexCommandError(
|
||||
f"Unsupported input_audio_format: {fmt}",
|
||||
code="unsupported_audio_format",
|
||||
event_id=event_id,
|
||||
)
|
||||
try:
|
||||
audio, fmt, sample_rate_hz = convert_input_audio_with_rate(
|
||||
audio,
|
||||
fmt,
|
||||
sample_rate_hz=sample_rate_hz if isinstance(sample_rate_hz, int | float) else None,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise DuplexCommandError(str(exc), code="bad_event", event_id=event_id) from exc
|
||||
hints: dict[str, object] = {}
|
||||
if hints_source is not None:
|
||||
copy_realtime_input_hints(hints_source, hints)
|
||||
copy_realtime_input_hints(event, hints)
|
||||
looks_like_speech = input_looks_like_speech(
|
||||
{**(hints_source or {}), **event},
|
||||
audio=audio,
|
||||
fmt=fmt,
|
||||
overlap_silence_rms=defaults.overlap_silence_rms,
|
||||
)
|
||||
video_frames: tuple[str, ...] = ()
|
||||
raw_frames = event.get("video_frames")
|
||||
if raw_frames is not None:
|
||||
frames_error = validate_realtime_video_frames(raw_frames, event.get("max_slice_nums"))
|
||||
if frames_error is not None:
|
||||
raise DuplexCommandError(frames_error, code="invalid_video_frames", event_id=event_id)
|
||||
if isinstance(raw_frames, list):
|
||||
video_frames = tuple(frame for frame in raw_frames if isinstance(frame, str) and frame)
|
||||
duration_ms = hints.get("duration_ms", hints.get("audio_duration_ms"))
|
||||
audio_end_ms = hints.get("audio_end_ms")
|
||||
try:
|
||||
audio_bytes = base64.b64decode(audio, validate=True) if isinstance(audio, str) and audio else b""
|
||||
except (binascii.Error, ValueError) as exc:
|
||||
raise DuplexCommandError("input audio is not valid base64", code="bad_audio", event_id=event_id) from exc
|
||||
return AppendAudio(
|
||||
event_id=event_id,
|
||||
audio=audio_bytes,
|
||||
format=str(fmt),
|
||||
sample_rate_hz=int(sample_rate_hz) if isinstance(sample_rate_hz, int | float) else None,
|
||||
is_speech=looks_like_speech,
|
||||
video_frames=video_frames,
|
||||
duration_ms=int(duration_ms) if isinstance(duration_ms, int | float) else None,
|
||||
audio_end_ms=int(audio_end_ms) if isinstance(audio_end_ms, int | float) else None,
|
||||
hints=hints,
|
||||
)
|
||||
|
||||
|
||||
# ---- translation ----
|
||||
|
||||
|
||||
def translate_realtime_command(
|
||||
payload: Mapping[str, object],
|
||||
*,
|
||||
defaults: RealtimeInputDefaults | None = None,
|
||||
) -> DuplexCommand:
|
||||
"""Map one OpenAI Realtime client event onto a :class:`DuplexCommand`.
|
||||
|
||||
Raises :class:`DuplexCommandError` for malformed or unsupported payloads.
|
||||
``session.resume`` and ``session.event_ack`` are transport concerns and are
|
||||
rejected with ``code="unknown_event"``.
|
||||
"""
|
||||
defaults = defaults or RealtimeInputDefaults()
|
||||
event_type = payload.get("type")
|
||||
event_id = cast("str", payload.get("event_id")) if isinstance(payload.get("event_id"), str) else None
|
||||
if not isinstance(event_type, str):
|
||||
raise DuplexCommandError("Duplex event missing string type", code="bad_event", event_id=event_id)
|
||||
|
||||
if event_type == "session.update":
|
||||
session = payload.get("session")
|
||||
session_payload: Mapping[str, object] = session if isinstance(session, dict) else payload
|
||||
format_error = validate_realtime_session_audio_formats(session_payload)
|
||||
if format_error is not None:
|
||||
raise DuplexCommandError(format_error, code="unsupported_audio_format", event_id=event_id)
|
||||
from vllm_omni.engine.duplex.turn_detection import validate_realtime_turn_detection
|
||||
|
||||
turn_detection_error = validate_realtime_turn_detection(session_payload)
|
||||
if turn_detection_error is not None:
|
||||
raise DuplexCommandError(turn_detection_error, code="unsupported_turn_detection", event_id=event_id)
|
||||
return UpdateSession(event_id=event_id, patch=dict(session_payload))
|
||||
|
||||
if event_type == "conversation.item.create":
|
||||
item = payload.get("item")
|
||||
format_error = validate_conversation_item_audio_formats(item)
|
||||
if format_error is not None:
|
||||
raise DuplexCommandError(format_error, code="unsupported_audio_format", event_id=event_id)
|
||||
if not isinstance(item, dict):
|
||||
raise DuplexCommandError("conversation.item.create requires item", code="bad_event", event_id=event_id)
|
||||
previous_item_id = payload.get("previous_item_id")
|
||||
return CreateItem(
|
||||
event_id=event_id,
|
||||
item=normalize_conversation_item(item),
|
||||
previous_item_id=previous_item_id if isinstance(previous_item_id, str) else None,
|
||||
)
|
||||
|
||||
if event_type == "conversation.item.delete":
|
||||
item_id = payload.get("item_id")
|
||||
if not isinstance(item_id, str) or not item_id:
|
||||
raise DuplexCommandError(
|
||||
"conversation.item.delete requires item_id", code="missing_item_id", event_id=event_id
|
||||
)
|
||||
return DeleteItem(event_id=event_id, item_id=item_id)
|
||||
|
||||
if event_type == "conversation.item.truncate":
|
||||
item_id = payload.get("item_id")
|
||||
audio_end_ms = payload.get("audio_end_ms")
|
||||
content_index = payload.get("content_index", 0)
|
||||
if not isinstance(item_id, str) or not item_id:
|
||||
raise DuplexCommandError(
|
||||
"conversation.item.truncate requires item_id", code="missing_item_id", event_id=event_id
|
||||
)
|
||||
if not isinstance(audio_end_ms, int | float):
|
||||
raise DuplexCommandError(
|
||||
"conversation.item.truncate requires numeric audio_end_ms", code="bad_event", event_id=event_id
|
||||
)
|
||||
return TruncateItem(
|
||||
event_id=event_id,
|
||||
item_id=item_id,
|
||||
audio_end_ms=int(audio_end_ms),
|
||||
content_index=int(content_index) if isinstance(content_index, int | float) else 0,
|
||||
)
|
||||
|
||||
if event_type == "input_audio_buffer.append":
|
||||
return build_append_audio(dict(payload), defaults=defaults)
|
||||
|
||||
if event_type in {"input_audio_buffer.commit", "input.commit"}:
|
||||
final = payload.get("final", True)
|
||||
create_response = payload.get("response_create", payload.get("create_response"))
|
||||
is_speech = payload.get("is_speech")
|
||||
return Commit(
|
||||
event_id=event_id,
|
||||
final=bool(final) if isinstance(final, bool) else True,
|
||||
create_response=(
|
||||
bool(create_response)
|
||||
if isinstance(create_response, bool)
|
||||
else (True if event_type == "input.commit" and create_response is None else None)
|
||||
),
|
||||
is_speech=is_speech if isinstance(is_speech, bool) else None,
|
||||
)
|
||||
|
||||
if event_type == "input_audio_buffer.clear":
|
||||
return ClearInput(event_id=event_id)
|
||||
|
||||
if event_type == "output_audio_buffer.clear":
|
||||
response_id = payload.get("response_id")
|
||||
return ClearOutputAudio(
|
||||
event_id=event_id,
|
||||
response_id=response_id if isinstance(response_id, str) and response_id else None,
|
||||
)
|
||||
|
||||
if event_type == "response.cancel":
|
||||
response_id = payload.get("response_id")
|
||||
return CancelResponse(
|
||||
event_id=event_id,
|
||||
response_id=response_id if isinstance(response_id, str) and response_id else None,
|
||||
)
|
||||
|
||||
if event_type == "response.create":
|
||||
response_payload = payload.get("response")
|
||||
if isinstance(response_payload, dict):
|
||||
format_error = validate_realtime_response_audio_formats(response_payload)
|
||||
if format_error is not None:
|
||||
raise DuplexCommandError(format_error, code="unsupported_audio_format", event_id=event_id)
|
||||
return CreateResponse(
|
||||
event_id=event_id,
|
||||
options=dict(response_payload) if isinstance(response_payload, dict) else {},
|
||||
)
|
||||
|
||||
if event_type in {"playback.ack", "audio.playback_ack"}:
|
||||
played_ms = payload.get("played_ms")
|
||||
if not isinstance(played_ms, int | float):
|
||||
raise DuplexCommandError("playback.ack requires numeric played_ms", code="bad_event", event_id=event_id)
|
||||
committed_ms = payload.get("committed_ms")
|
||||
response_id = payload.get("response_id")
|
||||
item_id = payload.get("item_id")
|
||||
return AckPlayback(
|
||||
event_id=event_id,
|
||||
played_ms=int(played_ms),
|
||||
committed_ms=int(committed_ms) if isinstance(committed_ms, int | float) else None,
|
||||
response_id=response_id if isinstance(response_id, str) and response_id else None,
|
||||
item_id=item_id if isinstance(item_id, str) and item_id else None,
|
||||
)
|
||||
|
||||
if event_type == "session.heartbeat":
|
||||
return Heartbeat(event_id=event_id)
|
||||
|
||||
if event_type == "conversation.item.retrieve":
|
||||
# The projected conversation items live engine-side; the runner answers.
|
||||
return SignalTurn(event_id=event_id, event="conversation.item.retrieve", signal_payload=dict(payload))
|
||||
|
||||
if event_type in {"session.close", "close", "close_session"}:
|
||||
reason = payload.get("reason")
|
||||
return CloseSession(event_id=event_id, reason=reason if isinstance(reason, str) and reason else "client_close")
|
||||
|
||||
if event_type in {"input.text.append", "input_text.append", "push_text"}:
|
||||
text = payload.get("text")
|
||||
if not isinstance(text, str):
|
||||
raise DuplexCommandError("input.text.append requires text", code="bad_event", event_id=event_id)
|
||||
return AppendText(event_id=event_id, text=text)
|
||||
|
||||
if event_type == "input.cancel":
|
||||
return CancelInput(event_id=event_id)
|
||||
|
||||
if event_type == "barge_in":
|
||||
return BargeIn(event_id=event_id)
|
||||
|
||||
if event_type in {"turn.signal", "signal_turn"}:
|
||||
signal_event = payload.get("event")
|
||||
if not isinstance(signal_event, str) or not signal_event:
|
||||
raise DuplexCommandError("turn.signal requires event", code="bad_event", event_id=event_id)
|
||||
signal_payload = payload.get("payload")
|
||||
signal_payload = dict(signal_payload) if isinstance(signal_payload, dict) else {}
|
||||
if signal_event == "input.cancel":
|
||||
return CancelInput(event_id=event_id)
|
||||
if signal_event == "barge_in":
|
||||
return BargeIn(event_id=event_id)
|
||||
if signal_event == "response.cancel":
|
||||
response_id = signal_payload.get("response_id", payload.get("response_id"))
|
||||
return CancelResponse(
|
||||
event_id=event_id,
|
||||
response_id=response_id if isinstance(response_id, str) and response_id else None,
|
||||
)
|
||||
if signal_event == "session.update":
|
||||
return UpdateSession(event_id=event_id, patch=signal_payload)
|
||||
if signal_event == "conversation.item.create":
|
||||
item = signal_payload.get("item")
|
||||
if not isinstance(item, dict):
|
||||
raise DuplexCommandError("conversation.item.create requires item", code="bad_event", event_id=event_id)
|
||||
previous_item_id = signal_payload.get("previous_item_id")
|
||||
return CreateItem(
|
||||
event_id=event_id,
|
||||
item=normalize_conversation_item(item),
|
||||
previous_item_id=previous_item_id if isinstance(previous_item_id, str) else None,
|
||||
)
|
||||
if signal_event == "conversation.item.delete":
|
||||
item_id = signal_payload.get("item_id")
|
||||
if not isinstance(item_id, str) or not item_id:
|
||||
raise DuplexCommandError(
|
||||
"conversation.item.delete requires item_id", code="missing_item_id", event_id=event_id
|
||||
)
|
||||
return DeleteItem(event_id=event_id, item_id=item_id)
|
||||
if signal_event == "conversation.item.truncate":
|
||||
item_id = signal_payload.get("item_id")
|
||||
audio_end_ms = signal_payload.get("audio_end_ms")
|
||||
content_index = signal_payload.get("content_index", 0)
|
||||
if not isinstance(item_id, str) or not item_id or not isinstance(audio_end_ms, int | float):
|
||||
raise DuplexCommandError(
|
||||
"conversation.item.truncate requires item_id and numeric audio_end_ms",
|
||||
code="bad_event",
|
||||
event_id=event_id,
|
||||
)
|
||||
return TruncateItem(
|
||||
event_id=event_id,
|
||||
item_id=item_id,
|
||||
audio_end_ms=int(audio_end_ms),
|
||||
content_index=int(content_index) if isinstance(content_index, int | float) else 0,
|
||||
)
|
||||
return SignalTurn(event_id=event_id, event=signal_event, signal_payload=signal_payload)
|
||||
|
||||
raise DuplexCommandError(f"Unknown duplex event type: {event_type}", code="unknown_event", event_id=event_id)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"REALTIME_INPUT_AUDIO_FORMATS",
|
||||
"REALTIME_INPUT_HINT_KEYS",
|
||||
"REALTIME_OUTPUT_AUDIO_FORMATS",
|
||||
"RealtimeInputDefaults",
|
||||
"apply_realtime_session_defaults",
|
||||
"build_append_audio",
|
||||
"copy_realtime_input_hints",
|
||||
"duplex_response_format",
|
||||
"input_audio_transcription_config",
|
||||
"input_explicitly_non_speech",
|
||||
"input_looks_like_speech",
|
||||
"input_transcript_from_item",
|
||||
"is_supported_realtime_input_format",
|
||||
"json_safe_realtime_payload",
|
||||
"normalize_conversation_item",
|
||||
"parse_realtime_audio_format",
|
||||
"realtime_audio_format_object",
|
||||
"realtime_max_output_tokens",
|
||||
"realtime_output_format",
|
||||
"realtime_overlap_fields",
|
||||
"text_chars_for_audio_ms_from_marks",
|
||||
"translate_realtime_command",
|
||||
"truncate_realtime_item_content",
|
||||
"validate_conversation_item_audio_formats",
|
||||
"validate_realtime_item_truncate",
|
||||
"validate_realtime_response_audio_formats",
|
||||
"validate_realtime_session_audio_formats",
|
||||
"validate_realtime_video_frames",
|
||||
]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,108 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Experimental duplex runtime loading and compatibility exports."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from importlib import import_module
|
||||
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexAppendPlan,
|
||||
DuplexInputMode,
|
||||
DuplexOutputAction,
|
||||
DuplexOutputDecision,
|
||||
DuplexRuntimeCapabilities,
|
||||
DuplexRuntimeExtension,
|
||||
SessionMode,
|
||||
duplex_data_plane_request_info,
|
||||
duplex_resource_request_belongs_to_session,
|
||||
duplex_resource_request_id,
|
||||
)
|
||||
|
||||
|
||||
def load_duplex_runtime_extension(path: str | None) -> DuplexRuntimeExtension | None:
|
||||
if not path:
|
||||
return None
|
||||
module_name, separator, attribute_name = path.rpartition(".")
|
||||
if not separator:
|
||||
raise ValueError(f"Invalid duplex runtime extension path: {path!r}")
|
||||
extension_type = getattr(import_module(module_name), attribute_name)
|
||||
return validate_duplex_runtime_extension(extension_type())
|
||||
|
||||
|
||||
def validate_duplex_runtime_extension(
|
||||
extension: object,
|
||||
*,
|
||||
sampling_defaults: tuple[object, ...] | None = None,
|
||||
) -> DuplexRuntimeExtension:
|
||||
required_methods = (
|
||||
"configure_sampling_params",
|
||||
"plan_append",
|
||||
"decide_output",
|
||||
)
|
||||
missing = [name for name in required_methods if not callable(getattr(extension, name, None))]
|
||||
if missing:
|
||||
raise TypeError(f"Duplex runtime extension is missing callable method(s): {', '.join(missing)}")
|
||||
typed_extension = extension # type: ignore[assignment]
|
||||
if sampling_defaults is not None:
|
||||
configured = typed_extension.configure_sampling_params(
|
||||
runtime_config={},
|
||||
defaults=sampling_defaults,
|
||||
)
|
||||
if not isinstance(configured, tuple):
|
||||
raise TypeError("Duplex runtime extension must return sampling parameters as a tuple")
|
||||
if len(configured) != len(sampling_defaults):
|
||||
raise ValueError("Duplex runtime extension must return one sampling parameter per stage")
|
||||
for stage_id, (value, default) in enumerate(zip(configured, sampling_defaults, strict=True)):
|
||||
if default is not None and not isinstance(value, type(default)):
|
||||
raise TypeError(
|
||||
"Duplex runtime extension sampling parameter type mismatch "
|
||||
f"for stage {stage_id}: expected {type(default).__name__}, got {type(value).__name__}"
|
||||
)
|
||||
return typed_extension
|
||||
|
||||
|
||||
from vllm_omni.engine.duplex.lease import ( # noqa: E402, F401
|
||||
DuplexLeaseActivity,
|
||||
DuplexLeaseConfig,
|
||||
DuplexLeaseState,
|
||||
DuplexSessionExpiry,
|
||||
)
|
||||
from vllm_omni.engine.duplex.session import ( # noqa: E402, F401
|
||||
DuplexAppendReservation,
|
||||
DuplexCompletedAppend,
|
||||
DuplexFenceMismatchError,
|
||||
DuplexInputAppend,
|
||||
DuplexRequestResource,
|
||||
DuplexSessionRuntimeManager,
|
||||
DuplexSessionRuntimeState,
|
||||
DuplexStageBinding,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"DuplexAppendPlan",
|
||||
"DuplexAppendReservation",
|
||||
"DuplexCompletedAppend",
|
||||
"DuplexFenceMismatchError",
|
||||
"DuplexInputAppend",
|
||||
"DuplexInputMode",
|
||||
"DuplexLeaseActivity",
|
||||
"DuplexLeaseConfig",
|
||||
"DuplexLeaseState",
|
||||
"DuplexOutputAction",
|
||||
"DuplexOutputDecision",
|
||||
"DuplexRequestResource",
|
||||
"DuplexRuntimeCapabilities",
|
||||
"DuplexRuntimeExtension",
|
||||
"DuplexSessionExpiry",
|
||||
"DuplexSessionRuntimeManager",
|
||||
"DuplexSessionRuntimeState",
|
||||
"DuplexStageBinding",
|
||||
"SessionMode",
|
||||
"duplex_data_plane_request_info",
|
||||
"duplex_resource_request_belongs_to_session",
|
||||
"duplex_resource_request_id",
|
||||
"load_duplex_runtime_extension",
|
||||
"validate_duplex_runtime_extension",
|
||||
]
|
||||
@@ -1,534 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Callable, Iterable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexInputMode,
|
||||
DuplexRuntimeCapabilities,
|
||||
)
|
||||
from vllm_omni.engine.duplex.lease import (
|
||||
DuplexLeaseActivity,
|
||||
DuplexLeaseConfig,
|
||||
DuplexLeaseState,
|
||||
DuplexSessionExpiry,
|
||||
)
|
||||
from vllm_omni.engine.duplex.messages import DuplexFence
|
||||
|
||||
|
||||
def _default_capabilities() -> DuplexRuntimeCapabilities:
|
||||
return DuplexRuntimeCapabilities()
|
||||
|
||||
|
||||
class DuplexFenceMismatchError(RuntimeError):
|
||||
def __init__(self, expected: DuplexFence, actual: DuplexFence) -> None:
|
||||
super().__init__(f"duplex fence mismatch: expected {expected!r}, got {actual!r}")
|
||||
self.expected = expected
|
||||
self.actual = actual
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplexStageBinding:
|
||||
request_id: str
|
||||
fence: DuplexFence
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplexRequestResource:
|
||||
stage_id: int
|
||||
request_id: str
|
||||
fence: DuplexFence
|
||||
submitted: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplexInputAppend:
|
||||
seq: int
|
||||
turn_seq: int
|
||||
turn_id: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DuplexAppendReservation:
|
||||
fence: DuplexFence
|
||||
mode: DuplexInputMode
|
||||
base_fence: DuplexFence
|
||||
base_input_seq: int
|
||||
base_input_turn_seq: int
|
||||
base_append_turn_key: tuple[int, int, int] | None
|
||||
update: DuplexInputAppend
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DuplexCompletedAppend:
|
||||
fence: DuplexFence
|
||||
mode: DuplexInputMode
|
||||
final: bool
|
||||
stage_results: tuple[dict[str, object], ...]
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplexSessionRuntimeState:
|
||||
"""Engine resource handles associated with a core-owned identity fence."""
|
||||
|
||||
fence: DuplexFence
|
||||
lease: DuplexLeaseState
|
||||
_clock: Callable[[], float] = field(repr=False)
|
||||
capabilities: DuplexRuntimeCapabilities = field(default_factory=_default_capabilities)
|
||||
session_config: dict[str, Any] = field(default_factory=dict)
|
||||
runtime_config: dict[str, Any] = field(default_factory=dict)
|
||||
config_generation: int = 0
|
||||
stage_bindings: dict[int, DuplexStageBinding] = field(default_factory=dict)
|
||||
request_resources: dict[tuple[int, str], DuplexRequestResource] = field(default_factory=dict)
|
||||
input_seq: int = 0
|
||||
input_turn_seq: int = 0
|
||||
_append_turn_key: tuple[int, int, int] | None = None
|
||||
completed_append_limit: int = 256
|
||||
completed_appends: OrderedDict[str, DuplexCompletedAppend] = field(default_factory=OrderedDict)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.completed_append_limit <= 0:
|
||||
raise ValueError("completed_append_limit must be positive")
|
||||
|
||||
@property
|
||||
def session_id(self) -> str:
|
||||
return self.fence.session_id
|
||||
|
||||
@property
|
||||
def epoch(self) -> int:
|
||||
return self.fence.epoch
|
||||
|
||||
@property
|
||||
def turn_id(self) -> int:
|
||||
return self.fence.turn_id
|
||||
|
||||
def _validate_fence(self, fence: DuplexFence) -> None:
|
||||
if fence.session_id != self.session_id or fence.incarnation != self.fence.incarnation:
|
||||
raise DuplexFenceMismatchError(self.fence, fence)
|
||||
current = self.fence
|
||||
if fence.epoch < current.epoch or (
|
||||
fence.epoch == current.epoch
|
||||
and (fence.turn_id < current.turn_id or fence.response_seq < current.response_seq)
|
||||
):
|
||||
raise DuplexFenceMismatchError(current, fence)
|
||||
|
||||
def accept_fence(self, fence: DuplexFence) -> None:
|
||||
self._validate_fence(fence)
|
||||
if fence.epoch != self.fence.epoch:
|
||||
self.input_seq = 0
|
||||
self.input_turn_seq = 0
|
||||
self._append_turn_key = None
|
||||
self.completed_appends.clear()
|
||||
self.fence = fence
|
||||
|
||||
def touch(self, fence: DuplexFence, activity: DuplexLeaseActivity) -> None:
|
||||
self._validate_fence(fence)
|
||||
self.lease.touch(self._clock(), activity)
|
||||
|
||||
def detach(self, fence: DuplexFence) -> None:
|
||||
self._validate_fence(fence)
|
||||
self.lease.detach(self._clock())
|
||||
|
||||
def resume(self, fence: DuplexFence, *, expected_lease_generation: int) -> int:
|
||||
self._validate_fence(fence)
|
||||
return self.lease.resume(
|
||||
self._clock(),
|
||||
expected_generation=expected_lease_generation,
|
||||
)
|
||||
|
||||
def begin_operation(self, fence: DuplexFence, operation_id: str) -> None:
|
||||
self._validate_fence(fence)
|
||||
self.lease.begin_operation(self._clock(), operation_id)
|
||||
|
||||
def end_operation(self, fence: DuplexFence, operation_id: str) -> None:
|
||||
self._validate_fence(fence)
|
||||
self.lease.end_operation(self._clock(), operation_id)
|
||||
|
||||
def replace_session_config(self, session_config: dict[str, Any]) -> None:
|
||||
self.session_config = dict(session_config)
|
||||
self.config_generation += 1
|
||||
|
||||
def replace_runtime_config(self, runtime_config: dict[str, Any]) -> None:
|
||||
self.runtime_config = dict(runtime_config)
|
||||
self.config_generation += 1
|
||||
|
||||
def replace_configs(
|
||||
self,
|
||||
*,
|
||||
session_config: dict[str, Any] | None = None,
|
||||
runtime_config: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""Atomically publish one validated configuration generation."""
|
||||
if session_config is None and runtime_config is None:
|
||||
return
|
||||
next_session_config = self.session_config if session_config is None else dict(session_config)
|
||||
next_runtime_config = self.runtime_config if runtime_config is None else dict(runtime_config)
|
||||
self.session_config = next_session_config
|
||||
self.runtime_config = next_runtime_config
|
||||
self.config_generation += 1
|
||||
|
||||
def reserve_stage_request(self, stage_id: int, request_id: str, *, fence: DuplexFence) -> None:
|
||||
self._validate_fence(fence)
|
||||
resource_key = (stage_id, request_id)
|
||||
existing = self.request_resources.get(resource_key)
|
||||
if existing is not None:
|
||||
if (
|
||||
existing.fence.session_id != fence.session_id
|
||||
or existing.fence.incarnation != fence.incarnation
|
||||
or existing.fence.epoch != fence.epoch
|
||||
):
|
||||
raise ValueError(f"Duplex request resource already reserved with different identity: {request_id}")
|
||||
return
|
||||
self.request_resources[resource_key] = DuplexRequestResource(
|
||||
stage_id=stage_id,
|
||||
request_id=request_id,
|
||||
fence=fence,
|
||||
)
|
||||
|
||||
def bind_stage_request(self, stage_id: int, request_id: str, *, fence: DuplexFence) -> None:
|
||||
self.reserve_stage_request(stage_id, request_id, fence=fence)
|
||||
self.accept_fence(fence)
|
||||
resource = self.request_resources[(stage_id, request_id)]
|
||||
resource.fence = fence
|
||||
resource.submitted = True
|
||||
self.stage_bindings[stage_id] = DuplexStageBinding(request_id=request_id, fence=fence)
|
||||
|
||||
def stage_request_ids(self, fence: DuplexFence | None = None) -> list[str]:
|
||||
return [
|
||||
binding.request_id for binding in self.stage_bindings.values() if fence is None or binding.fence == fence
|
||||
]
|
||||
|
||||
def resource_request_ids(
|
||||
self,
|
||||
fence: DuplexFence | None = None,
|
||||
*,
|
||||
submitted: bool | None = None,
|
||||
) -> list[str]:
|
||||
return list(
|
||||
dict.fromkeys(
|
||||
resource.request_id
|
||||
for resource in self.request_resources.values()
|
||||
if (fence is None or resource.fence == fence) and (submitted is None or resource.submitted is submitted)
|
||||
)
|
||||
)
|
||||
|
||||
def release_request_ids(self, request_ids: list[str]) -> None:
|
||||
released = set(request_ids)
|
||||
if not released:
|
||||
return
|
||||
self.stage_bindings = {
|
||||
stage_id: binding for stage_id, binding in self.stage_bindings.items() if binding.request_id not in released
|
||||
}
|
||||
self.request_resources = {
|
||||
resource_key: resource
|
||||
for resource_key, resource in self.request_resources.items()
|
||||
if resource.request_id not in released
|
||||
}
|
||||
|
||||
def prepare_append(self, *, mode: DuplexInputMode, fence: DuplexFence) -> DuplexAppendReservation:
|
||||
if mode not in self.capabilities.input_modes:
|
||||
raise ValueError(f"Duplex input mode {mode.value!r} is not supported by session {self.session_id}")
|
||||
self._validate_fence(fence)
|
||||
input_seq = 0 if fence.epoch != self.fence.epoch else self.input_seq
|
||||
input_turn_seq = 0 if fence.epoch != self.fence.epoch else self.input_turn_seq
|
||||
append_turn_key = None if fence.epoch != self.fence.epoch else self._append_turn_key
|
||||
turn_key = (fence.epoch, fence.turn_id, fence.response_seq)
|
||||
turn_seq = input_turn_seq + 1 if turn_key == append_turn_key else 1
|
||||
return DuplexAppendReservation(
|
||||
fence=fence,
|
||||
mode=mode,
|
||||
base_fence=self.fence,
|
||||
base_input_seq=self.input_seq,
|
||||
base_input_turn_seq=self.input_turn_seq,
|
||||
base_append_turn_key=self._append_turn_key,
|
||||
update=DuplexInputAppend(
|
||||
seq=input_seq + 1,
|
||||
turn_seq=turn_seq,
|
||||
turn_id=fence.turn_id,
|
||||
),
|
||||
)
|
||||
|
||||
def commit_append(self, reservation: DuplexAppendReservation) -> DuplexInputAppend:
|
||||
if (
|
||||
self.fence != reservation.base_fence
|
||||
or self.input_seq != reservation.base_input_seq
|
||||
or self.input_turn_seq != reservation.base_input_turn_seq
|
||||
or self._append_turn_key != reservation.base_append_turn_key
|
||||
):
|
||||
raise RuntimeError("duplex append reservation is stale")
|
||||
self.accept_fence(reservation.fence)
|
||||
self.input_seq = reservation.update.seq
|
||||
self.input_turn_seq = reservation.update.turn_seq
|
||||
self._append_turn_key = (
|
||||
reservation.fence.epoch,
|
||||
reservation.fence.turn_id,
|
||||
reservation.fence.response_seq,
|
||||
)
|
||||
return reservation.update
|
||||
|
||||
def completed_append(
|
||||
self,
|
||||
operation_id: str,
|
||||
*,
|
||||
fence: DuplexFence,
|
||||
mode: DuplexInputMode,
|
||||
final: bool,
|
||||
) -> list[dict[str, object]] | None:
|
||||
self._validate_fence(fence)
|
||||
completed = self.completed_appends.get(operation_id)
|
||||
if completed is None:
|
||||
return None
|
||||
if completed.fence != fence or completed.mode != mode or completed.final != final:
|
||||
raise ValueError(f"duplex append operation {operation_id!r} was reused with different metadata")
|
||||
return [dict(result) for result in completed.stage_results]
|
||||
|
||||
def record_completed_append(
|
||||
self,
|
||||
operation_id: str,
|
||||
*,
|
||||
fence: DuplexFence,
|
||||
mode: DuplexInputMode,
|
||||
final: bool,
|
||||
stage_results: list[dict[str, object]],
|
||||
) -> None:
|
||||
self.completed_appends[operation_id] = DuplexCompletedAppend(
|
||||
fence=fence,
|
||||
mode=mode,
|
||||
final=final,
|
||||
stage_results=tuple(dict(result) for result in stage_results),
|
||||
)
|
||||
self.completed_appends.move_to_end(operation_id)
|
||||
while len(self.completed_appends) > self.completed_append_limit:
|
||||
self.completed_appends.popitem(last=False)
|
||||
|
||||
def append_input(self, *, mode: DuplexInputMode, fence: DuplexFence) -> DuplexInputAppend:
|
||||
return self.commit_append(self.prepare_append(mode=mode, fence=fence))
|
||||
|
||||
def release_fence(self, fence: DuplexFence) -> list[str]:
|
||||
stale = self.resource_request_ids(fence)
|
||||
self.stage_bindings = {
|
||||
stage_id: binding for stage_id, binding in self.stage_bindings.items() if binding.fence != fence
|
||||
}
|
||||
self.request_resources = {
|
||||
resource_key: resource
|
||||
for resource_key, resource in self.request_resources.items()
|
||||
if resource.fence != fence
|
||||
}
|
||||
return stale
|
||||
|
||||
def cancel_fence(self, cancelled_fence: DuplexFence, next_fence: DuplexFence) -> list[str]:
|
||||
stale = self.prepare_cancel_fence(cancelled_fence, next_fence)
|
||||
self.release_fence(cancelled_fence)
|
||||
return stale
|
||||
|
||||
def prepare_cancel_fence(self, cancelled_fence: DuplexFence, next_fence: DuplexFence) -> list[str]:
|
||||
"""Advance the cancellation fence without dropping cleanup records."""
|
||||
if cancelled_fence.session_id != self.session_id or cancelled_fence.incarnation != self.fence.incarnation:
|
||||
raise DuplexFenceMismatchError(self.fence, cancelled_fence)
|
||||
if (
|
||||
next_fence.session_id != self.session_id
|
||||
or next_fence.incarnation != self.fence.incarnation
|
||||
or next_fence.epoch <= cancelled_fence.epoch
|
||||
):
|
||||
raise DuplexFenceMismatchError(cancelled_fence, next_fence)
|
||||
current_key = (self.fence.epoch, self.fence.turn_id, self.fence.response_seq)
|
||||
cancelled_key = (cancelled_fence.epoch, cancelled_fence.turn_id, cancelled_fence.response_seq)
|
||||
next_key = (next_fence.epoch, next_fence.turn_id, next_fence.response_seq)
|
||||
if cancelled_key > current_key:
|
||||
raise DuplexFenceMismatchError(self.fence, cancelled_fence)
|
||||
if next_key > current_key:
|
||||
self.accept_fence(next_fence)
|
||||
return self.resource_request_ids(cancelled_fence)
|
||||
|
||||
def begin_close(self, fence: DuplexFence, *, reason: str) -> bool:
|
||||
"""Make close irreversible while retaining resources for cleanup retry."""
|
||||
self.accept_fence(fence)
|
||||
if self.lease.terminal_reason is not None:
|
||||
return True
|
||||
return self.lease.mark_terminal(reason)
|
||||
|
||||
def finalize_close(self) -> list[str]:
|
||||
return self.close()
|
||||
|
||||
def close(self, fence: DuplexFence | None = None) -> list[str]:
|
||||
if fence is not None:
|
||||
self.accept_fence(fence)
|
||||
stale = self.resource_request_ids()
|
||||
self.stage_bindings.clear()
|
||||
self.request_resources.clear()
|
||||
return stale
|
||||
|
||||
def terminate(self, fence: DuplexFence, *, reason: str) -> bool:
|
||||
if not self.begin_close(fence, reason=reason):
|
||||
return False
|
||||
self.finalize_close()
|
||||
return True
|
||||
|
||||
|
||||
class DuplexSessionRuntimeManager:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
clock: Callable[[], float] | None = None,
|
||||
max_sessions: int | None = None,
|
||||
completed_append_limit: int = 256,
|
||||
) -> None:
|
||||
if max_sessions is not None and max_sessions <= 0:
|
||||
raise ValueError("max_sessions must be positive or null")
|
||||
if completed_append_limit <= 0:
|
||||
raise ValueError("completed_append_limit must be positive")
|
||||
self._sessions: dict[str, DuplexSessionRuntimeState] = {}
|
||||
self._clock = clock or time.monotonic
|
||||
self._max_sessions = max_sessions
|
||||
self._completed_append_limit = completed_append_limit
|
||||
|
||||
def open_session(
|
||||
self,
|
||||
fence: DuplexFence,
|
||||
*,
|
||||
capabilities: DuplexRuntimeCapabilities | None = None,
|
||||
session_config: dict[str, Any] | None = None,
|
||||
runtime_config: dict[str, Any] | None = None,
|
||||
lease_config: DuplexLeaseConfig | None = None,
|
||||
) -> DuplexSessionRuntimeState:
|
||||
if not isinstance(fence, DuplexFence):
|
||||
raise TypeError("open_session requires DuplexFence")
|
||||
if fence.session_id in self._sessions:
|
||||
raise ValueError(f"Duplex session already exists: {fence.session_id}")
|
||||
if self._max_sessions is not None and len(self._sessions) >= self._max_sessions:
|
||||
raise RuntimeError(f"duplex_session_capacity_exhausted: limit={self._max_sessions}")
|
||||
session = DuplexSessionRuntimeState(
|
||||
fence=fence,
|
||||
lease=DuplexLeaseState(
|
||||
config=lease_config or DuplexLeaseConfig(),
|
||||
generation=0,
|
||||
last_activity=self._clock(),
|
||||
),
|
||||
_clock=self._clock,
|
||||
capabilities=capabilities or _default_capabilities(),
|
||||
session_config=dict(session_config or {}),
|
||||
runtime_config=dict(runtime_config or {}),
|
||||
completed_append_limit=self._completed_append_limit,
|
||||
)
|
||||
self._sessions[fence.session_id] = session
|
||||
return session
|
||||
|
||||
def get(self, session_id: str) -> DuplexSessionRuntimeState | None:
|
||||
return self._sessions.get(session_id)
|
||||
|
||||
def require(self, session_id: str) -> DuplexSessionRuntimeState:
|
||||
session = self.get(session_id)
|
||||
if session is None:
|
||||
raise KeyError(f"Unknown duplex session: {session_id}")
|
||||
return session
|
||||
|
||||
def close_session(
|
||||
self,
|
||||
fence: DuplexFence,
|
||||
*,
|
||||
reason: str = "explicit_close",
|
||||
) -> DuplexSessionRuntimeState | None:
|
||||
if not isinstance(fence, DuplexFence):
|
||||
raise TypeError("close_session requires DuplexFence")
|
||||
session = self._sessions.get(fence.session_id)
|
||||
if session is not None:
|
||||
if session.lease.terminal_reason is not None:
|
||||
return None
|
||||
if not session.terminate(fence, reason=reason):
|
||||
return None
|
||||
if self._sessions.get(fence.session_id) is session:
|
||||
self._sessions.pop(fence.session_id)
|
||||
return session
|
||||
|
||||
def begin_close_session(
|
||||
self,
|
||||
fence: DuplexFence,
|
||||
*,
|
||||
reason: str = "explicit_close",
|
||||
) -> DuplexSessionRuntimeState | None:
|
||||
if not isinstance(fence, DuplexFence):
|
||||
raise TypeError("begin_close_session requires DuplexFence")
|
||||
session = self._sessions.get(fence.session_id)
|
||||
if session is not None:
|
||||
session.begin_close(fence, reason=reason)
|
||||
return session
|
||||
|
||||
def finalize_close_session(self, session: DuplexSessionRuntimeState) -> None:
|
||||
session.finalize_close()
|
||||
if self._sessions.get(session.session_id) is session:
|
||||
self._sessions.pop(session.session_id, None)
|
||||
|
||||
def collect_expired(
|
||||
self,
|
||||
now: float | None = None,
|
||||
*,
|
||||
excluded_session_ids: set[str] | None = None,
|
||||
) -> list[DuplexSessionExpiry]:
|
||||
effective_now = self._clock() if now is None else now
|
||||
excluded = excluded_session_ids or set()
|
||||
expired: list[DuplexSessionExpiry] = []
|
||||
for session_id, session in list(self._sessions.items()):
|
||||
if session_id in excluded:
|
||||
continue
|
||||
if session.lease.disconnect_grace_expired(effective_now):
|
||||
reason = "disconnect_grace_expired"
|
||||
elif session.lease.idle_expired(effective_now):
|
||||
reason = "idle_ttl_expired"
|
||||
else:
|
||||
continue
|
||||
submitted = tuple(session.resource_request_ids(submitted=True))
|
||||
reserved = tuple(session.resource_request_ids(submitted=False))
|
||||
if not session.begin_close(session.fence, reason=reason):
|
||||
continue
|
||||
expired.append(
|
||||
DuplexSessionExpiry(
|
||||
session_id=session_id,
|
||||
fence=session.fence,
|
||||
lease_generation=session.lease.generation,
|
||||
reason=reason,
|
||||
submitted_request_ids=submitted,
|
||||
reserved_request_ids=reserved,
|
||||
)
|
||||
)
|
||||
return expired
|
||||
|
||||
def close_sessions_for_request_ids(self, request_ids: list[str]) -> dict[str, list[str]]:
|
||||
request_id_set = set(request_ids)
|
||||
closed: dict[str, list[str]] = {}
|
||||
for session_id, session in list(self._sessions.items()):
|
||||
stale = session.resource_request_ids()
|
||||
if request_id_set.isdisjoint(stale):
|
||||
continue
|
||||
if not session.begin_close(session.fence, reason="request_cleanup"):
|
||||
continue
|
||||
closed[session_id] = stale
|
||||
return closed
|
||||
|
||||
def finalize_closed_sessions(self, session_ids: Iterable[str]) -> None:
|
||||
for session_id in session_ids:
|
||||
session = self._sessions.get(session_id)
|
||||
if session is None or session.lease.terminal_reason is None:
|
||||
continue
|
||||
self.finalize_close_session(session)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DuplexAppendReservation",
|
||||
"DuplexCompletedAppend",
|
||||
"DuplexFenceMismatchError",
|
||||
"DuplexInputAppend",
|
||||
"DuplexLeaseActivity",
|
||||
"DuplexLeaseConfig",
|
||||
"DuplexLeaseState",
|
||||
"DuplexRequestResource",
|
||||
"DuplexSessionExpiry",
|
||||
"DuplexSessionRuntimeManager",
|
||||
"DuplexSessionRuntimeState",
|
||||
"DuplexStageBinding",
|
||||
]
|
||||
@@ -0,0 +1,38 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""One engine-resident duplex session, and everything that runs it.
|
||||
|
||||
``DuplexEngineSession`` (``engine_session``) is the state -- the input,
|
||||
response, playback and conversation ledgers, the lease and the identity fence.
|
||||
``DuplexSessionRunner`` (``runner``) owns one of those on the orchestrator loop
|
||||
and is the only writer of it; ``DuplexSessionManager`` (``manager``) owns the
|
||||
runners and the admission slots.
|
||||
|
||||
The rest of the package is what the runner was split into, and each module
|
||||
names the thing it owns rather than a layer:
|
||||
|
||||
* ``context`` -- the state a runner and its components share, and the only
|
||||
services a component may ask the runner for.
|
||||
* ``emitter`` -- everything the session sends: the Realtime projection, the
|
||||
epoch filter, the domain effects a terminal event applies.
|
||||
* ``model_channel`` -- the model side: submitting an append, projecting the
|
||||
stage output that comes back, continuing a turn with silence.
|
||||
* ``control`` -- server VAD and the events that reconfigure the session.
|
||||
* ``append_task`` -- one append in flight, and the rollback its failure owes.
|
||||
* ``helpers`` -- the small pure reads and payload builders over a session.
|
||||
* ``overlap_policy`` / ``commit_policy`` / ``playback_ledger`` -- the decisions
|
||||
a session makes about speech that arrives while the model is speaking, what a
|
||||
commit should do, and what the client has actually played.
|
||||
* ``lease`` -- the idle/activity lease that decides when a session expires.
|
||||
|
||||
Imports here are the package's public surface; a module of this package is fair
|
||||
game for anything inside it, but code outside ``engine.duplex`` should reach for
|
||||
these three names.
|
||||
"""
|
||||
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
from vllm_omni.engine.duplex.session.manager import DuplexSessionManager
|
||||
from vllm_omni.engine.duplex.session.runner import DuplexSessionRunner
|
||||
|
||||
__all__ = ["DuplexEngineSession", "DuplexSessionManager", "DuplexSessionRunner"]
|
||||
@@ -0,0 +1,195 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""One append in flight, and what its failure owes the session.
|
||||
|
||||
An append is not a call: it is a task queued behind the previous append, which
|
||||
may be cancelled, may find the session closed before it starts, and on any of
|
||||
those paths has to give back what it reserved --- the PCM bytes it took from the
|
||||
input budget, the committed audio it was going to consume, and the response it
|
||||
precreated.
|
||||
|
||||
That compensation is the reason this is an object. The five steps of an append
|
||||
all need the same eleven values, so as closures over ``_start_append`` they read
|
||||
as one function with five entry points and no way to test any of them. Named
|
||||
fields make the captured state explicit and the compensation a method.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexSessionState, DuplexTurnEventType
|
||||
from vllm_omni.engine.duplex.plugin import PcmAppendReservation
|
||||
from vllm_omni.engine.duplex.session import helpers
|
||||
from vllm_omni.engine.duplex.session.context import DuplexSessionContext
|
||||
from vllm_omni.engine.duplex.session.emitter import SessionEmitter
|
||||
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AppendAttempt:
|
||||
"""One queued append to the model, with the rollback each failure path owes."""
|
||||
|
||||
ctx: DuplexSessionContext
|
||||
out: SessionEmitter
|
||||
model: ModelChannel
|
||||
#: Marks the session closing before the close coroutine gets to run.
|
||||
fail_session: Callable[[str], None]
|
||||
|
||||
payload: dict[str, object]
|
||||
epoch: int
|
||||
request_id: str
|
||||
final: bool
|
||||
pcm_reservation: PcmAppendReservation | None
|
||||
operation_id: str | None
|
||||
#: Committed audio this append consumes; released once it is safely submitted.
|
||||
retained_committed_payload: dict[str, object] | None
|
||||
#: Response reserved before submission, to be failed if submission does not happen.
|
||||
precreated_response_id: str | None
|
||||
#: Last chance to call the append off, checked once the predecessor is done.
|
||||
before_append: Callable[[], bool] | None
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Compensation #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def discard_retained_audio(self) -> None:
|
||||
"""Release the committed audio this append was going to consume.
|
||||
|
||||
Only if it is still the session's: a later commit may have replaced it,
|
||||
and that one belongs to the append that will carry it.
|
||||
"""
|
||||
model_state = self.ctx.model_state
|
||||
if self.retained_committed_payload is not None and (
|
||||
model_state.committed_audio_payload is self.retained_committed_payload
|
||||
):
|
||||
self.ctx.session.release_input_bytes(model_state.clear_committed_audio())
|
||||
|
||||
def abandon(self) -> None:
|
||||
"""Give back everything this append reserved but never used."""
|
||||
if self.pcm_reservation is not None:
|
||||
self.pcm_reservation.rollback()
|
||||
self.discard_retained_audio()
|
||||
|
||||
def release_on_failure(self, done: asyncio.Task[bool]) -> None:
|
||||
"""Done-callback: a cancelled or failed append must not hold the audio."""
|
||||
if done.cancelled():
|
||||
self.discard_retained_audio()
|
||||
return
|
||||
try:
|
||||
append_ok = done.result()
|
||||
except Exception:
|
||||
append_ok = False
|
||||
if not append_ok:
|
||||
self.discard_retained_audio()
|
||||
|
||||
def clear_pending_silence(self, done: asyncio.Task[bool]) -> None:
|
||||
"""Done-callback of a silence continuation: it is no longer pending."""
|
||||
model_state = self.ctx.model_state
|
||||
if model_state.pending_silence_task is done:
|
||||
model_state.pending_silence_task = None
|
||||
model_state.pending_silence_owner_id = None
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Running #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
async def run_in_wire_order(self, predecessor: asyncio.Task[bool] | None) -> bool:
|
||||
"""Wait for the previous append, then submit this one if it still applies."""
|
||||
if predecessor is not None:
|
||||
try:
|
||||
predecessor_ok = await predecessor
|
||||
except asyncio.CancelledError:
|
||||
current = asyncio.current_task()
|
||||
if current is not None and current.cancelling():
|
||||
raise
|
||||
predecessor_ok = False
|
||||
except Exception:
|
||||
predecessor_ok = False
|
||||
if not predecessor_ok:
|
||||
self.abandon()
|
||||
return False
|
||||
run = self.ctx.run
|
||||
if run.closing or run.runtime_closed or self.ctx.session.state != DuplexSessionState.OPEN:
|
||||
self.abandon()
|
||||
return False
|
||||
if self.before_append is not None and not self.before_append():
|
||||
self.abandon()
|
||||
# Called off, not failed: the chain behind it still runs.
|
||||
return True
|
||||
if self.pcm_reservation is not None and not self.pcm_reservation.active:
|
||||
self.discard_retained_audio()
|
||||
return False
|
||||
return await self._submit()
|
||||
|
||||
async def _submit(self) -> bool:
|
||||
session = self.ctx.session
|
||||
model_state = self.ctx.model_state
|
||||
try:
|
||||
append_ok, emitted_response = await self.model.append_runtime_input(
|
||||
self.payload,
|
||||
operation_id=(
|
||||
self.pcm_reservation.operation_id if self.pcm_reservation is not None else self.operation_id
|
||||
),
|
||||
final=self.final,
|
||||
expected_epoch=self.epoch,
|
||||
)
|
||||
if append_ok:
|
||||
model_state.context_locked = True
|
||||
if self.pcm_reservation is not None:
|
||||
self.pcm_reservation.commit()
|
||||
session.release_input_bytes(self.pcm_reservation.byte_count)
|
||||
self.discard_retained_audio()
|
||||
else:
|
||||
self.abandon()
|
||||
if not append_ok and self._precreated_response_still_active():
|
||||
self._fail_precreated_response()
|
||||
if not append_ok and session.state == DuplexSessionState.CLOSED:
|
||||
self.ctx.run.runtime_closed = True
|
||||
return False
|
||||
if not emitted_response and session.epoch == self.epoch:
|
||||
if session.active_request_id == helpers.stage0_request_id(session, self.epoch):
|
||||
session.clear_request(self.request_id)
|
||||
if self.final:
|
||||
self.out.emit_events([session.signal_turn(DuplexTurnEventType.USER_STARTED.value)])
|
||||
return append_ok
|
||||
except asyncio.CancelledError:
|
||||
if self.pcm_reservation is not None:
|
||||
self.pcm_reservation.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
self.abandon()
|
||||
logger.exception("Native duplex append task failed: %s", exc)
|
||||
self.model.send_runtime_error("runtime_append_task_failed", exc)
|
||||
if session.state != DuplexSessionState.CLOSED:
|
||||
self.fail_session("runtime_append_task_failed")
|
||||
return False
|
||||
|
||||
def _precreated_response_still_active(self) -> bool:
|
||||
return (
|
||||
self.precreated_response_id is not None
|
||||
and self.ctx.session.active_response_id == self.precreated_response_id
|
||||
)
|
||||
|
||||
def _fail_precreated_response(self) -> None:
|
||||
session = self.ctx.session
|
||||
session.end_response(commit_text=False)
|
||||
self.out.emit(
|
||||
{
|
||||
"type": "response.done",
|
||||
"session_id": session.session_id,
|
||||
"response_id": self.precreated_response_id,
|
||||
"epoch": session.epoch,
|
||||
"committed": False,
|
||||
"status": "failed",
|
||||
"status_details": {"type": "failed", "reason": "runtime_append_failed"},
|
||||
"playback": session.playback.as_dict(),
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,41 @@
|
||||
# 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
|
||||
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.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"]
|
||||
@@ -0,0 +1,161 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Shared state for :class:`DuplexSessionRunner` and its components.
|
||||
|
||||
The runner is a state machine that several components read and write. Splitting
|
||||
it into modules only helps if the shared part stops being implicit: a component
|
||||
holding a back-reference to the runner is a mixin with extra steps, and one
|
||||
holding its own copy of a flag diverges from the others.
|
||||
|
||||
So the mutable part is named. ``DuplexRunState`` is the small set of flags that
|
||||
more than one component touches -- ``grep "\\.run\\."`` finds every mutation --
|
||||
and ``DuplexSessionContext`` is the read-mostly collaborator bundle everything
|
||||
is constructed with. Anything a component needs from the runner that is neither
|
||||
of those is infrastructure, and goes through :class:`RunnerServices`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Protocol, TypeVar
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.outputs import RequestOutput
|
||||
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexOutputContext,
|
||||
DuplexOutputDecision,
|
||||
DuplexStagePort,
|
||||
)
|
||||
from vllm_omni.engine.duplex.plugin import DuplexModelPlugin, DuplexModelSessionState
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
from vllm_omni.engine.duplex.session.manager import DuplexSessionManager
|
||||
from vllm_omni.metrics.stats import StageRequestStats
|
||||
|
||||
_OffloadT = TypeVar("_OffloadT")
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class DuplexRunState:
|
||||
"""Mutable per-run flags shared by the runner and its components.
|
||||
|
||||
Every field here is written by one component and read by another; that is
|
||||
the criterion for being in this object rather than private to a component.
|
||||
"""
|
||||
|
||||
#: An irreversible close has begun: commands and control ops are refused.
|
||||
closing: bool = False
|
||||
#: ``session.closed`` / ``session.expired`` already left the runner.
|
||||
closed_emitted: bool = False
|
||||
#: The terminal event is deferred to the manager, which emits it after the
|
||||
#: stage cleanup so it also means "the admission slot is free again".
|
||||
closed_deferred: bool = False
|
||||
close_reason: str | None = None
|
||||
#: The model runtime reported a close; further data-plane work is pointless.
|
||||
runtime_closed: bool = False
|
||||
#: Request id of the resumable data-plane stream currently bound to the session.
|
||||
stream_request_id: str | None = None
|
||||
|
||||
|
||||
class RunnerServices(Protocol):
|
||||
"""The only things a component may ask the runner for.
|
||||
|
||||
Deliberately two methods. A component that needs more than task scheduling
|
||||
from the runner is reaching for orchestration that belongs in the runner.
|
||||
"""
|
||||
|
||||
def spawn(self, coro: Awaitable[None], *, name: str) -> None:
|
||||
"""Run ``coro`` as a tracked background task on the session's loop."""
|
||||
...
|
||||
|
||||
async def offload(self, fn: Callable[..., _OffloadT], *args: object, **kwargs: object) -> _OffloadT:
|
||||
"""Run a blocking call off the orchestrator loop."""
|
||||
...
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class DuplexSessionContext:
|
||||
"""Collaborators one session's components are built with.
|
||||
|
||||
Read-mostly: the session and the model state are mutated through their own
|
||||
APIs, not by rebinding these fields. The mutable flags live in ``run``.
|
||||
"""
|
||||
|
||||
session: DuplexEngineSession
|
||||
model_state: DuplexModelSessionState
|
||||
plugin: DuplexModelPlugin
|
||||
stage_port: DuplexStagePort
|
||||
manager: DuplexSessionManager
|
||||
tasks: DuplexSessionTasks
|
||||
run: DuplexRunState
|
||||
services: RunnerServices
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Task bookkeeping #
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DuplexAppendTaskMeta:
|
||||
epoch: int
|
||||
final: bool
|
||||
response_bound: bool
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplexSessionTasks:
|
||||
"""Tracked task handles of one session (append tail, active response, pending silence)."""
|
||||
|
||||
append_tasks: dict[asyncio.Task[bool], DuplexAppendTaskMeta] = field(default_factory=dict)
|
||||
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,
|
||||
final: bool,
|
||||
response_bound: bool,
|
||||
) -> None:
|
||||
self.append_tasks[task] = DuplexAppendTaskMeta(epoch, final, response_bound)
|
||||
task.add_done_callback(self.append_tasks.pop)
|
||||
|
||||
def has_response_bound_append_tasks(self) -> bool:
|
||||
return any(meta.response_bound for meta in self.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.append_tasks.items() if not response_bound_only or meta.response_bound]
|
||||
if not tasks:
|
||||
return False
|
||||
cancelled_tail = self.append_tail if self.append_tail in tasks else None
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
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.append_tail is cancelled_tail:
|
||||
self.append_tail = None
|
||||
return True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Stage output (the mailbox item the orchestrator hands the runner) #
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class StageOutput:
|
||||
"""One stage result, queued for the session that owns the request."""
|
||||
|
||||
stage_id: int
|
||||
output: RequestOutput
|
||||
metrics: StageRequestStats | None
|
||||
request_id: str
|
||||
context: DuplexOutputContext
|
||||
decision: DuplexOutputDecision | None
|
||||
@@ -0,0 +1,328 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Control of one duplex session: server VAD, and the events that reconfigure it.
|
||||
|
||||
Server turn detection and ``session.update`` are the same concern seen from two
|
||||
sides. The detector is per-session mutable state, and ``session.update`` is the
|
||||
event that replaces it mid-flight -- along with the session config, the runtime
|
||||
config and the sampling policy, each of which has to be validated against a
|
||||
candidate before the live session adopts it. The rest of ``turn.signal``
|
||||
(conversation items, local turn markers) travels the same path and is small, so
|
||||
it lives here rather than in a module of its own.
|
||||
|
||||
The one thing this does not own is ordering against the data plane: a
|
||||
``session.update`` must not overtake an append still in flight, so the runner
|
||||
supplies ``wait_for_append_tail``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Awaitable, Callable
|
||||
from copy import deepcopy
|
||||
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexConfigError, realtime_item_to_history_message
|
||||
from vllm_omni.engine.duplex.plugin import DuplexRuntimeConfigError
|
||||
from vllm_omni.engine.duplex.session import helpers
|
||||
from vllm_omni.engine.duplex.session.context import DuplexSessionContext
|
||||
from vllm_omni.engine.duplex.session.emitter import SessionEmitter
|
||||
from vllm_omni.engine.duplex.session.lease import DuplexLeaseActivity
|
||||
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
|
||||
from vllm_omni.engine.duplex.turn_detection import (
|
||||
PendingTurnDetectionUpdate,
|
||||
ServerTurnDetector,
|
||||
ServerVADUnavailableError,
|
||||
SileroVADBackendProvider,
|
||||
TurnDetectionConfig,
|
||||
TurnDetectionResult,
|
||||
apply_turn_detection_result,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class SessionControl:
|
||||
"""Server VAD and the control events that reconfigure one session."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ctx: DuplexSessionContext,
|
||||
out: SessionEmitter,
|
||||
model: ModelChannel,
|
||||
*,
|
||||
wait_for_append_tail: Callable[[], Awaitable[bool]],
|
||||
) -> None:
|
||||
self._ctx = ctx
|
||||
self._out = out
|
||||
self._model = model
|
||||
self._wait_for_append_tail = wait_for_append_tail
|
||||
self._config: TurnDetectionConfig | None = None
|
||||
self._detector: ServerTurnDetector | None = None
|
||||
|
||||
def init_turn_detection(self) -> None:
|
||||
turn_detection = self._ctx.session.config.extra_body.get("realtime_turn_detection")
|
||||
if not isinstance(turn_detection, dict) or turn_detection.get("type") != "server_vad":
|
||||
self._config = None
|
||||
self._detector = None
|
||||
return
|
||||
try:
|
||||
config = TurnDetectionConfig.from_realtime(turn_detection)
|
||||
self._config = config
|
||||
self._detector = config.build_detector(self._vad_backend_provider())
|
||||
except Exception as exc:
|
||||
logger.warning("Duplex session %s: turn detection disabled: %s", self._ctx.session.session_id, exc)
|
||||
self._config = None
|
||||
self._detector = None
|
||||
|
||||
def _vad_backend_provider(self) -> SileroVADBackendProvider | None:
|
||||
"""The engine-wide Silero backend, so one model serves every session.
|
||||
|
||||
Held by the manager rather than built here: the ONNX backend is shared,
|
||||
and ``duplex_session.server_vad_model_path`` is a deploy-level setting.
|
||||
"""
|
||||
return getattr(self._ctx.manager, "vad_backend_provider", None)
|
||||
|
||||
def reset_vad(self) -> None:
|
||||
"""Drop the detector's speech state (a barge-in or a clear starts a new turn)."""
|
||||
if self._detector is not None:
|
||||
self._detector.reset()
|
||||
|
||||
async def run_turn_detection(self, event: dict[str, object]) -> TurnDetectionResult | None:
|
||||
detector = self._detector
|
||||
if detector is None:
|
||||
return None
|
||||
audio = event.get("audio")
|
||||
if not isinstance(audio, str) or not audio:
|
||||
return None
|
||||
fmt = event.get("format") if isinstance(event.get("format"), str) else "pcm_f32le"
|
||||
sample_rate_hz = event.get("sample_rate_hz")
|
||||
try:
|
||||
result = await self._ctx.services.offload(
|
||||
detector.process,
|
||||
audio,
|
||||
fmt=fmt,
|
||||
sample_rate_hz=sample_rate_hz if isinstance(sample_rate_hz, int) else None,
|
||||
audio_end_ms=event.get("audio_end_ms") if isinstance(event.get("audio_end_ms"), int) else None,
|
||||
)
|
||||
except ServerVADUnavailableError as exc:
|
||||
self._out.emit_error("server_vad_unavailable", str(exc))
|
||||
self._detector = None
|
||||
return None
|
||||
except ValueError as exc:
|
||||
self._out.emit_error("bad_audio", str(exc))
|
||||
return None
|
||||
apply_turn_detection_result(event, result)
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Control events #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
async def on_turn_signal(self, event: dict[str, object]) -> None:
|
||||
session = self._ctx.session
|
||||
turn_event = event.get("event")
|
||||
realtime_event_id = event.get("realtime_event_id")
|
||||
if not isinstance(turn_event, str):
|
||||
self._out.emit_error("bad_event", "turn.signal requires event")
|
||||
return
|
||||
if turn_event == "barge_in" and not session.capabilities.supports_barge_in:
|
||||
self._out.emit_events([helpers.barge_in_unsupported_error()])
|
||||
return
|
||||
if turn_event == "session.update":
|
||||
payload = event.get("payload")
|
||||
if not isinstance(payload, dict):
|
||||
self._out.emit_error(
|
||||
"bad_event", "session.update requires a session payload", event_id=realtime_event_id
|
||||
)
|
||||
return
|
||||
await self.on_session_update(
|
||||
payload,
|
||||
realtime_event_id=realtime_event_id if isinstance(realtime_event_id, str) else None,
|
||||
)
|
||||
return
|
||||
if turn_event == "conversation.item.create":
|
||||
await self._on_conversation_item_create(event)
|
||||
return
|
||||
if turn_event == "conversation.item.delete":
|
||||
payload = event.get("payload")
|
||||
item_id = payload.get("item_id") if isinstance(payload, dict) else None
|
||||
deleted = session.delete_history_item(item_id) if isinstance(item_id, str) else False
|
||||
self._out.emit(
|
||||
{
|
||||
"type": "conversation.item.deleted",
|
||||
"session_id": session.session_id,
|
||||
"item_id": item_id,
|
||||
"deleted": deleted,
|
||||
}
|
||||
)
|
||||
return
|
||||
if turn_event == "conversation.item.truncate":
|
||||
payload = event.get("payload")
|
||||
item_id = payload.get("item_id") if isinstance(payload, dict) else None
|
||||
audio_end_ms = payload.get("audio_end_ms") if isinstance(payload, dict) else None
|
||||
truncated = (
|
||||
session.truncate_history_item(
|
||||
item_id,
|
||||
audio_end_ms=int(audio_end_ms) if isinstance(audio_end_ms, int | float) else 0,
|
||||
hard=True,
|
||||
)
|
||||
if isinstance(item_id, str)
|
||||
else False
|
||||
)
|
||||
self._out.emit(
|
||||
{
|
||||
"type": "conversation.item.truncated",
|
||||
"session_id": session.session_id,
|
||||
"item_id": item_id,
|
||||
"content_index": (payload.get("content_index", 0) if isinstance(payload, dict) else 0),
|
||||
"audio_end_ms": audio_end_ms,
|
||||
"truncated": truncated,
|
||||
}
|
||||
)
|
||||
return
|
||||
self._out.emit_events([session.signal_turn(turn_event, event)])
|
||||
|
||||
async def on_session_update(self, payload: dict[str, object], *, realtime_event_id: str | None) -> None:
|
||||
session = self._ctx.session
|
||||
model_state = self._ctx.model_state
|
||||
pending_turn_detection: PendingTurnDetectionUpdate | None = None
|
||||
|
||||
def reject_update() -> None:
|
||||
if pending_turn_detection is not None:
|
||||
pending_turn_detection.reject()
|
||||
|
||||
try:
|
||||
pending_turn_detection = PendingTurnDetectionUpdate.prepare(
|
||||
payload, backend_provider=self._vad_backend_provider()
|
||||
)
|
||||
except Exception as exc:
|
||||
self._out.emit_error("unsupported_turn_detection", str(exc), event_id=realtime_event_id)
|
||||
return
|
||||
if not await self._wait_for_append_tail():
|
||||
self._out.emit_error(
|
||||
"session_update_aborted",
|
||||
"session.update was not applied because the preceding append failed",
|
||||
event_id=realtime_event_id,
|
||||
)
|
||||
reject_update()
|
||||
return
|
||||
try:
|
||||
self._ctx.plugin.validate_client_extra_body(payload.get("extra_body"))
|
||||
except DuplexRuntimeConfigError as exc:
|
||||
self._out.emit_error(exc.code, str(exc), event_id=realtime_event_id)
|
||||
reject_update()
|
||||
return
|
||||
candidate_config = deepcopy(session.config)
|
||||
audio_started = session.playback.generated_ms > 0 or session.playback.sent_ms > 0
|
||||
try:
|
||||
candidate_config.apply_realtime_update(
|
||||
payload,
|
||||
session_id=session.session_id,
|
||||
audio_started=audio_started,
|
||||
)
|
||||
except DuplexConfigError as exc:
|
||||
self._out.emit_error(exc.code, str(exc) or "session.update was rejected", event_id=realtime_event_id)
|
||||
reject_update()
|
||||
return
|
||||
if candidate_config.instructions != session.config.instructions and model_state.context_locked:
|
||||
self._out.emit_error(
|
||||
"instructions_update_unsupported",
|
||||
"session.update cannot change instructions after the native duplex context is initialized",
|
||||
event_id=realtime_event_id,
|
||||
)
|
||||
reject_update()
|
||||
return
|
||||
requests_audio = any(str(modality).lower() == "audio" for modality in candidate_config.modalities)
|
||||
if (
|
||||
requests_audio
|
||||
and "ref_audio_data" not in session.runtime_config
|
||||
and getattr(self._ctx.plugin, "requires_ref_audio", False)
|
||||
):
|
||||
self._out.emit_error(
|
||||
"ref_audio_required", "Native duplex audio output requires ref_audio", event_id=realtime_event_id
|
||||
)
|
||||
reject_update()
|
||||
return
|
||||
try:
|
||||
candidate_runtime_config = self._ctx.plugin.runtime_config_for_update(
|
||||
candidate_config,
|
||||
dict(session.runtime_config),
|
||||
)
|
||||
# Validate the sampling policy for the candidate before adopting it.
|
||||
self._ctx.plugin.configure_sampling_params(
|
||||
runtime_config=dict(candidate_runtime_config),
|
||||
defaults=tuple(self._ctx.stage_port.sampling_defaults()),
|
||||
)
|
||||
except (DuplexRuntimeConfigError, DuplexConfigError) as exc:
|
||||
self._out.emit_error(exc.code, str(exc), event_id=realtime_event_id)
|
||||
reject_update()
|
||||
return
|
||||
except Exception as exc:
|
||||
self._out.emit_error("runtime_signal_failed", str(exc), event_id=realtime_event_id)
|
||||
reject_update()
|
||||
return
|
||||
session.replace_config(candidate_config)
|
||||
session.replace_runtime_config(candidate_runtime_config)
|
||||
try:
|
||||
session.touch_lease(DuplexLeaseActivity.SIGNAL)
|
||||
except Exception:
|
||||
pass
|
||||
if pending_turn_detection is not None:
|
||||
self._config, self._detector = pending_turn_detection.commit(self._detector)
|
||||
projector = self._out.require_projector()
|
||||
projector.apply_session_defaults(payload)
|
||||
self._out.emit({"type": "session.updated", "session": session.as_public_dict()})
|
||||
|
||||
async def _on_conversation_item_create(self, event: dict[str, object]) -> None:
|
||||
session = self._ctx.session
|
||||
payload = event.get("payload")
|
||||
item = payload.get("item") if isinstance(payload, dict) else None
|
||||
item_type = item.get("type") if isinstance(item, dict) else None
|
||||
if item_type == "function_call_output" and isinstance(item, dict):
|
||||
if not await self._wait_for_append_tail():
|
||||
return
|
||||
try:
|
||||
candidate_runtime_config = self._ctx.plugin.runtime_config_for_function_output(
|
||||
session.config,
|
||||
dict(session.runtime_config),
|
||||
item,
|
||||
)
|
||||
except DuplexRuntimeConfigError as exc:
|
||||
self._out.emit_error(exc.code, str(exc))
|
||||
return
|
||||
if candidate_runtime_config is not None:
|
||||
session.replace_runtime_config(candidate_runtime_config)
|
||||
self._out.emit(
|
||||
{
|
||||
"type": "conversation.item.created",
|
||||
"session_id": session.session_id,
|
||||
"item": item,
|
||||
"created": True,
|
||||
}
|
||||
)
|
||||
self._ctx.services.spawn(
|
||||
self._model.maybe_continue_response(
|
||||
expected_epoch=session.epoch,
|
||||
expected_model_turn_id=session.turn_id,
|
||||
),
|
||||
name="duplex-continue",
|
||||
)
|
||||
return
|
||||
message = realtime_item_to_history_message(item)
|
||||
item_id = item.get("id") if isinstance(item, dict) else None
|
||||
if message is not None:
|
||||
session.append_history_message(message)
|
||||
session.register_history_item(item_id if isinstance(item_id, str) else None, message)
|
||||
if message.get("role") == "user":
|
||||
# A later response.create may answer this without any audio.
|
||||
session.notify_new_user_item()
|
||||
self._out.emit(
|
||||
{
|
||||
"type": "conversation.item.created",
|
||||
"session_id": session.session_id,
|
||||
"item": item,
|
||||
"created": message is not None,
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,249 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Everything one duplex session sends to its client.
|
||||
|
||||
Emission is the hub of the session runner: near enough every path through the
|
||||
runner ends in an event, which is why this is a collaborator rather than a
|
||||
module of functions. It owns three things the rest of the runner should not
|
||||
have to think about --- the Realtime projection state, the epoch filter that
|
||||
drops output from a superseded turn, and the domain transitions an outbound
|
||||
terminal event applies to the session before it is projected.
|
||||
|
||||
The one thing it cannot own is what happens *after* a terminal promotes
|
||||
deferred overlap audio: that re-enters the mailbox of the runner, so the
|
||||
runner injects it as ``promote_deferred_overlap``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexSessionState
|
||||
from vllm_omni.engine.duplex.events import (
|
||||
DOMAIN_TERMINAL_EVENTS,
|
||||
MODEL_OUTPUT_EVENTS,
|
||||
DuplexEvent,
|
||||
error_event,
|
||||
)
|
||||
from vllm_omni.engine.duplex.realtime_events import (
|
||||
RealtimeProjectionState,
|
||||
discard_pending_input_audio,
|
||||
project_internal_event,
|
||||
)
|
||||
from vllm_omni.engine.duplex.session import overlap_policy
|
||||
from vllm_omni.engine.duplex.session.context import DuplexSessionContext
|
||||
|
||||
|
||||
class SessionEmitter:
|
||||
"""Outbound events for one session."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ctx: DuplexSessionContext,
|
||||
*,
|
||||
promote_deferred_overlap: Callable[[dict[str, object], bool], None],
|
||||
) -> None:
|
||||
self._ctx = ctx
|
||||
self._promote_deferred_overlap = promote_deferred_overlap
|
||||
self._projector: RealtimeProjectionState | None = ctx.session.projector
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Projection state #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
@property
|
||||
def projector(self) -> RealtimeProjectionState | None:
|
||||
"""The Realtime projection state, or ``None`` before anything needs it."""
|
||||
return self._projector
|
||||
|
||||
@projector.setter
|
||||
def projector(self, value: RealtimeProjectionState | None) -> None:
|
||||
self._projector = value
|
||||
self._ctx.session.projector = value
|
||||
|
||||
def require_projector(self) -> RealtimeProjectionState:
|
||||
"""The projection state, created on first use.
|
||||
|
||||
A session torn down before ``start()`` never builds one, so the lazy
|
||||
path here is reachable rather than defensive.
|
||||
"""
|
||||
projector = self._projector
|
||||
if projector is None:
|
||||
session = self._ctx.session
|
||||
projector = RealtimeProjectionState(
|
||||
session_id=session.session_id,
|
||||
model=session.config.model,
|
||||
initial_session_update=True,
|
||||
)
|
||||
self.projector = projector
|
||||
return projector
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Sending #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def emit_events(self, events: list[DuplexEvent]) -> None:
|
||||
for event in events:
|
||||
self._ctx.manager.emit(self._ctx.session, event)
|
||||
|
||||
def emit_error(
|
||||
self,
|
||||
code: str,
|
||||
message: str,
|
||||
*,
|
||||
event_id: object | None = None,
|
||||
retryable: bool | None = None,
|
||||
) -> None:
|
||||
"""Send one typed ``error`` event (``event_id`` is the client event it answers)."""
|
||||
extra = {} if retryable is None else {"retryable": retryable}
|
||||
self.emit_events([error_event(code, message, event_id=event_id, extra=extra)])
|
||||
|
||||
def emit(self, payload: dict[str, object]) -> None:
|
||||
"""Apply the domain effects of an internal event, then project it to typed events and send them.
|
||||
|
||||
Only events with domain effects (response / cancel / close terminals) or
|
||||
Realtime projection state (response items, content parts) still travel as
|
||||
internal dictionaries; stateless events are constructed typed at the
|
||||
emit site.
|
||||
"""
|
||||
accepted, deferred_overlap_payload = self._apply_outbound_session_event(payload)
|
||||
if not accepted:
|
||||
return
|
||||
self.emit_events(project_internal_event(self.require_projector(), payload))
|
||||
if deferred_overlap_payload is not None and not self._ctx.run.closing:
|
||||
precreate_response = self._ctx.model_state.deferred_precreate_response
|
||||
self._ctx.model_state.deferred_precreate_response = False
|
||||
self._promote_deferred_overlap(deferred_overlap_payload, precreate_response)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Filtering and domain effects #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def auto_responds(self) -> bool:
|
||||
"""Whether the session answers committed input without a ``response.create``."""
|
||||
extra = getattr(self._ctx.session.config, "extra_body", None)
|
||||
if not isinstance(extra, dict):
|
||||
return False
|
||||
return extra.get("auto_response") is True or extra.get("full_duplex") is True
|
||||
|
||||
def is_stale_model_output(self, payload: dict[str, object]) -> bool:
|
||||
"""Whether ``payload`` belongs to a turn the session has already moved past."""
|
||||
session = self._ctx.session
|
||||
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._ctx.run.closing and event_type != "response.listen":
|
||||
return True
|
||||
if session.state == DuplexSessionState.CLOSED and event_type != "response.listen":
|
||||
return True
|
||||
epoch = payload.get("epoch")
|
||||
return isinstance(epoch, int) and epoch != session.epoch
|
||||
|
||||
def _apply_outbound_session_event(self, payload: dict[str, object]) -> tuple[bool, dict[str, object] | None]:
|
||||
"""Apply domain transitions before an event is projected (moved from serving)."""
|
||||
session = self._ctx.session
|
||||
model_state = self._ctx.model_state
|
||||
payload_type = payload.get("type")
|
||||
is_terminal = payload_type in DOMAIN_TERMINAL_EVENTS
|
||||
if is_terminal:
|
||||
payload_epoch = payload.get("epoch")
|
||||
if isinstance(payload_epoch, int) and payload_epoch != session.epoch:
|
||||
return False, None
|
||||
if payload_type in {"response.done", "response.listen"} and (
|
||||
self._ctx.run.closing or session.state == DuplexSessionState.CLOSED
|
||||
):
|
||||
return False, None
|
||||
elif self.is_stale_model_output(payload):
|
||||
return False, None
|
||||
|
||||
if payload_type == "session.closed":
|
||||
self._ctx.run.close_reason = self._ctx.run.close_reason or str(payload.get("reason") or "closed")
|
||||
session.mark_closing()
|
||||
|
||||
if not is_terminal:
|
||||
return True, None
|
||||
|
||||
terminal_status = payload.get("status")
|
||||
terminal_status_details = payload.get("status_details")
|
||||
if terminal_status is None and isinstance(terminal_status_details, dict):
|
||||
terminal_status = terminal_status_details.get("type")
|
||||
response_terminal = payload_type == "response.done" or (
|
||||
payload_type == "response.listen" and session.active_response_id is not None
|
||||
)
|
||||
can_promote_overlap = response_terminal and terminal_status not in {"cancelled", "failed"}
|
||||
deferred_overlap_payload: dict[str, object] | None = None
|
||||
continuous_input_crosses_terminal = (
|
||||
can_promote_overlap
|
||||
and self.auto_responds()
|
||||
and model_state.input_since_commit
|
||||
and not model_state.deferred_response_create
|
||||
)
|
||||
if continuous_input_crosses_terminal:
|
||||
session.reset_overlap_speech()
|
||||
return True, None
|
||||
realtime_input_still_open = (
|
||||
can_promote_overlap and model_state.input_since_commit and not model_state.deferred_response_create
|
||||
)
|
||||
if realtime_input_still_open:
|
||||
session.reset_overlap_speech()
|
||||
return True, None
|
||||
if can_promote_overlap and session.overlap_speech_ms > 0:
|
||||
has_deferred_overlap = (
|
||||
model_state.audio_buffer.has_pending() or model_state.committed_audio_payload is not None
|
||||
)
|
||||
should_promote_overlap = (
|
||||
session.state == DuplexSessionState.OPEN
|
||||
and has_deferred_overlap
|
||||
and session.overlap_speech_ms > session.config.overlap_short_ack_ms
|
||||
)
|
||||
if should_promote_overlap:
|
||||
flushed_reserved_bytes = model_state.audio_buffer.pending_byte_count
|
||||
deferred_overlap_payload = model_state.audio_buffer.flush(
|
||||
chunk_period_ms=session.capabilities.chunk_period_ms or 1000
|
||||
)
|
||||
if model_state.committed_audio_payload is not None:
|
||||
if deferred_overlap_payload is not None:
|
||||
deferred_overlap_payload = overlap_policy.merge_audio_payloads(
|
||||
model_state.committed_audio_payload,
|
||||
deferred_overlap_payload,
|
||||
)
|
||||
else:
|
||||
deferred_overlap_payload = model_state.committed_audio_payload
|
||||
if self.auto_responds() and deferred_overlap_payload is not None:
|
||||
deferred_overlap_payload = dict(deferred_overlap_payload)
|
||||
deferred_overlap_payload["force_listen"] = False
|
||||
if deferred_overlap_payload is not None:
|
||||
model_state.retain_committed_audio(
|
||||
deferred_overlap_payload,
|
||||
operation_id=model_state.committed_audio_operation_id,
|
||||
reserved_bytes=flushed_reserved_bytes,
|
||||
)
|
||||
model_state.input_since_commit = deferred_overlap_payload is not None
|
||||
# Realtime path: defer the promoted response to the next terminal.
|
||||
model_state.deferred_response_create = True
|
||||
model_state.deferred_precreate_response = False
|
||||
deferred_overlap_payload = None
|
||||
else:
|
||||
had_pending_overlap_audio = model_state.audio_buffer.has_pending()
|
||||
model_state.audio_buffer.clear()
|
||||
model_state.input_since_commit = False
|
||||
model_state.speech_since_commit = False
|
||||
if had_pending_overlap_audio and self._projector is not None:
|
||||
self.emit_events(discard_pending_input_audio(self._projector, session.overlap_speech_ms))
|
||||
if payload_type in {"audio.cancelled", "input.cancelled", "session.closed"}:
|
||||
session.release_input_bytes(model_state.clear_committed_audio())
|
||||
|
||||
session.reset_overlap_speech()
|
||||
if (
|
||||
can_promote_overlap
|
||||
and model_state.deferred_response_create
|
||||
and model_state.committed_audio_payload is not None
|
||||
):
|
||||
deferred_overlap_payload = model_state.committed_audio_payload
|
||||
model_state.deferred_response_create = False
|
||||
model_state.input_since_commit = False
|
||||
model_state.speech_since_commit = False
|
||||
return True, deferred_overlap_payload
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,195 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Small reads and payload builders over one duplex session.
|
||||
|
||||
None of these hold state or decide anything: they answer a question about the
|
||||
session, or shape one of the wire payloads its events carry. They were methods
|
||||
on the runner only because that is where the session reference lived, which
|
||||
made every component that needed one a reason to reach back into the runner.
|
||||
|
||||
Functions, not a component, because there is nothing here to own.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import binascii
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pybase64 as base64
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexPlaybackCommitPolicy
|
||||
from vllm_omni.engine.duplex.contracts import DuplexFence, duplex_resource_request_id
|
||||
from vllm_omni.engine.duplex.events import ErrorEvent, OverlapDecision, error_event
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Mapping
|
||||
|
||||
from vllm_omni.engine.duplex.session.context import DuplexSessionTasks
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexCommittedInput, DuplexEngineSession
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Questions about the session #
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def stage0_request_id(session: DuplexEngineSession, epoch: int) -> str:
|
||||
return duplex_resource_request_id(DuplexFence(session.session_id, epoch=epoch), "stage0")
|
||||
|
||||
|
||||
def response_in_progress(session: DuplexEngineSession, tasks: DuplexSessionTasks) -> bool:
|
||||
"""Whether the model still owns the turn.
|
||||
|
||||
Broader than ``active_response_id``: audio already sent but not yet played
|
||||
back, and an append still in flight, both mean the turn is not free.
|
||||
"""
|
||||
if session.active_response_id is not None:
|
||||
return True
|
||||
if assistant_playback_active(session):
|
||||
return True
|
||||
active_task = tasks.active_response_task
|
||||
if active_task is not None and not active_task.done():
|
||||
return True
|
||||
return tasks.has_response_bound_append_tasks()
|
||||
|
||||
|
||||
def assistant_playback_active(session: DuplexEngineSession) -> bool:
|
||||
"""Whether the client is still playing audio the session has sent."""
|
||||
return (
|
||||
session.config.playback_commit_policy == DuplexPlaybackCommitPolicy.ACK_ONLY.value
|
||||
and session.playback.sent_ms > session.playback.committed_ms
|
||||
)
|
||||
|
||||
|
||||
def audio_payload_size_bytes(payload: Mapping[str, object]) -> int:
|
||||
audio = payload.get("audio") or payload.get("data")
|
||||
if not isinstance(audio, str):
|
||||
return 0
|
||||
try:
|
||||
return len(base64.b64decode(audio, validate=True))
|
||||
except (ValueError, binascii.Error):
|
||||
return 0
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Turn transitions #
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def advance_barge_in_epoch(session: DuplexEngineSession) -> tuple[int, dict[str, int]]:
|
||||
"""Start a new epoch for a barge-in, returning it with the playback it cut off."""
|
||||
old_playback = session.playback.as_dict()
|
||||
new_epoch = session.barge_in()
|
||||
session.clear_playback_cursor()
|
||||
return new_epoch, old_playback
|
||||
|
||||
|
||||
def commit_played_response_history(
|
||||
session: DuplexEngineSession,
|
||||
response_id: str | None,
|
||||
committed_ms: int,
|
||||
) -> None:
|
||||
"""Truncate an interrupted response in history to what the client actually heard."""
|
||||
if not response_id or committed_ms < 0:
|
||||
return
|
||||
session.truncate_history_item(
|
||||
f"item_{response_id}",
|
||||
audio_end_ms=committed_ms,
|
||||
playback=session.playback_for_response(response_id),
|
||||
)
|
||||
|
||||
|
||||
def commit_audio_input(
|
||||
session: DuplexEngineSession,
|
||||
*,
|
||||
realtime_item_id: object | None = None,
|
||||
transcript: object | None = None,
|
||||
turn_id: int | None = None,
|
||||
) -> DuplexCommittedInput:
|
||||
clean_transcript = transcript.strip() if isinstance(transcript, str) else None
|
||||
committed = session.commit_audio_input(
|
||||
transcript=clean_transcript or None,
|
||||
turn_id=turn_id,
|
||||
)
|
||||
if isinstance(realtime_item_id, str) and realtime_item_id:
|
||||
session.register_history_item(realtime_item_id, committed.message)
|
||||
return committed
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Payloads #
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def barge_in_unsupported_error() -> ErrorEvent:
|
||||
return error_event("barge_in_unsupported", "Barge-in is not supported by this duplex model")
|
||||
|
||||
|
||||
def overlap_decision_event(session: DuplexEngineSession, decision: dict[str, object]) -> OverlapDecision:
|
||||
details: dict[str, object] = {
|
||||
"type": "overlap.decision",
|
||||
"session_id": session.session_id,
|
||||
"epoch": session.epoch,
|
||||
"policy": session.config.overlap_policy,
|
||||
**decision,
|
||||
}
|
||||
action = decision.get("action")
|
||||
reason = decision.get("reason")
|
||||
return OverlapDecision(
|
||||
policy=session.config.overlap_policy,
|
||||
action=action if isinstance(action, str) else None,
|
||||
reason=reason if isinstance(reason, str) else None,
|
||||
details=details,
|
||||
)
|
||||
|
||||
|
||||
def input_committed_payload(
|
||||
session: DuplexEngineSession,
|
||||
committed: DuplexCommittedInput,
|
||||
*,
|
||||
realtime_item_id: object | None = None,
|
||||
) -> dict[str, object]:
|
||||
payload: dict[str, object] = {
|
||||
"type": "input.committed",
|
||||
"session_id": session.session_id,
|
||||
"turn_id": committed.turn_id,
|
||||
"epoch": committed.epoch,
|
||||
"history_len": len(session.history),
|
||||
"message": committed.message,
|
||||
}
|
||||
if isinstance(realtime_item_id, str) and realtime_item_id:
|
||||
payload["realtime_item_id"] = realtime_item_id
|
||||
return payload
|
||||
|
||||
|
||||
def audio_committed_payload(
|
||||
session: DuplexEngineSession,
|
||||
*,
|
||||
committed: DuplexCommittedInput | None = None,
|
||||
realtime_item_id: object | None = None,
|
||||
transcript: object | None = None,
|
||||
) -> dict[str, object]:
|
||||
message = committed.message if committed is not None else None
|
||||
if not isinstance(message, dict):
|
||||
input_audio_part: dict[str, object] = {
|
||||
"type": "audio_url",
|
||||
"audio_url": {"url": "native-duplex:input-audio"},
|
||||
}
|
||||
if isinstance(transcript, str) and transcript:
|
||||
input_audio_part["transcript"] = transcript
|
||||
message = {"role": "user", "content": [input_audio_part]}
|
||||
payload: dict[str, object] = {
|
||||
"type": "input.committed",
|
||||
"session_id": session.session_id,
|
||||
"turn_id": committed.turn_id if committed is not None else session.turn_id,
|
||||
"epoch": committed.epoch if committed is not None else session.epoch,
|
||||
"history_len": len(session.history),
|
||||
"native_audio": True,
|
||||
"message": message,
|
||||
}
|
||||
if isinstance(transcript, str) and transcript:
|
||||
payload["transcript"] = transcript
|
||||
if isinstance(realtime_item_id, str) and realtime_item_id:
|
||||
payload["realtime_item_id"] = realtime_item_id
|
||||
return payload
|
||||
@@ -8,8 +8,6 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
|
||||
from vllm_omni.engine.duplex.messages import DuplexFence
|
||||
|
||||
|
||||
class DuplexLeaseActivity(str, Enum):
|
||||
APPEND = "append"
|
||||
@@ -111,19 +109,8 @@ class DuplexLeaseState:
|
||||
return True
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DuplexSessionExpiry:
|
||||
session_id: str
|
||||
fence: DuplexFence
|
||||
lease_generation: int
|
||||
reason: str
|
||||
submitted_request_ids: tuple[str, ...]
|
||||
reserved_request_ids: tuple[str, ...]
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DuplexLeaseActivity",
|
||||
"DuplexLeaseConfig",
|
||||
"DuplexLeaseState",
|
||||
"DuplexSessionExpiry",
|
||||
]
|
||||
@@ -0,0 +1,872 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Engine-side owner of duplex sessions: admission, lease reaping, command dispatch.
|
||||
|
||||
``DuplexOrchestrator`` hosts exactly one manager. The whole session
|
||||
(``DuplexEngineSession``) lives here, owned by one ``DuplexSessionRunner`` per
|
||||
session on the orchestrator loop; nothing outside the engine holds session
|
||||
state.
|
||||
|
||||
Control operations (open / close / resume / touch) arrive as correlated RPC
|
||||
messages and answer through ``result_sink``; session commands arrive one-way
|
||||
as ``DuplexSessionCommandMessage`` and are pushed onto the runner's ordered
|
||||
mailbox after backpressure admission; everything a session emits leaves
|
||||
through ``output_sink`` as ``DuplexSessionEventMessage``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import concurrent.futures
|
||||
import time
|
||||
from collections.abc import Awaitable, Callable, Iterable
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.engine.duplex.commands import AppendAudio, Commit, DuplexCommand
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexFence,
|
||||
DuplexStagePort,
|
||||
DuplexStageRequestContext,
|
||||
duplex_resource_request_belongs_to_session,
|
||||
duplex_resource_request_id,
|
||||
)
|
||||
from vllm_omni.engine.duplex.events import DuplexEvent, ErrorEvent, SessionClosed, SessionExpired, error_event
|
||||
from vllm_omni.engine.duplex.messages import (
|
||||
CloseDuplexSessionMessage,
|
||||
DuplexControlResultMessage,
|
||||
DuplexSessionCommandMessage,
|
||||
DuplexSessionError,
|
||||
DuplexSessionEventMessage,
|
||||
OpenDuplexSessionMessage,
|
||||
ResumeDuplexSessionMessage,
|
||||
TouchDuplexSessionMessage,
|
||||
)
|
||||
from vllm_omni.engine.duplex.plugin import DuplexModelPlugin, DuplexRuntimeConfigError, validate_duplex_plugin_sampling
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession, DuplexFenceMismatchError
|
||||
from vllm_omni.engine.duplex.session.lease import DuplexLeaseActivity, DuplexLeaseConfig, DuplexLeaseState
|
||||
from vllm_omni.engine.duplex.turn_detection import SileroVADBackendProvider
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import janus
|
||||
from vllm.config import ModelConfig
|
||||
|
||||
from vllm_omni.config.stage_config import DuplexSessionRuntimeConfig
|
||||
from vllm_omni.engine.duplex.session.runner import DuplexSessionRunner
|
||||
from vllm_omni.engine.messages import EngineQueueMessage
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _PendingRequestCleanup:
|
||||
session_id: str
|
||||
lease_generation: int
|
||||
request_ids: tuple[str, ...]
|
||||
abort: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _PendingSessionCleanup:
|
||||
"""A close/expiry whose stage cleanup has not succeeded yet (retried by the reaper)."""
|
||||
|
||||
kind: str
|
||||
session_id: str
|
||||
lease_generation: int
|
||||
reason: str
|
||||
submitted_request_ids: tuple[str, ...]
|
||||
reserved_request_ids: tuple[str, ...]
|
||||
|
||||
|
||||
class DuplexSessionManager:
|
||||
_CONTROL_TYPES = (
|
||||
OpenDuplexSessionMessage,
|
||||
CloseDuplexSessionMessage,
|
||||
ResumeDuplexSessionMessage,
|
||||
TouchDuplexSessionMessage,
|
||||
)
|
||||
_MESSAGE_TYPES = (*_CONTROL_TYPES, DuplexSessionCommandMessage)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
plugin: DuplexModelPlugin,
|
||||
stage_port: DuplexStagePort,
|
||||
output_sink: janus.AsyncQueue[EngineQueueMessage],
|
||||
result_sink: janus.AsyncQueue[EngineQueueMessage],
|
||||
runtime_config: DuplexSessionRuntimeConfig,
|
||||
model_config: ModelConfig | None,
|
||||
clock: Callable[[], float] | None = None,
|
||||
executor: concurrent.futures.ThreadPoolExecutor | None = None,
|
||||
) -> None:
|
||||
validate_duplex_plugin_sampling(plugin, sampling_defaults=tuple(stage_port.sampling_defaults()))
|
||||
self.plugin = plugin
|
||||
self.stage_port = stage_port
|
||||
self.model_config = model_config
|
||||
self.runtime_config = runtime_config
|
||||
self._output_sink = output_sink
|
||||
self._result_sink = result_sink
|
||||
self._clock = clock or time.monotonic
|
||||
self.executor = executor or concurrent.futures.ThreadPoolExecutor(
|
||||
max_workers=4,
|
||||
thread_name_prefix="duplex-session",
|
||||
)
|
||||
self._owns_executor = executor is None
|
||||
self._lease_config = DuplexLeaseConfig(
|
||||
idle_ttl_s=runtime_config.idle_ttl_s,
|
||||
disconnect_grace_s=runtime_config.disconnect_grace_s,
|
||||
)
|
||||
#: One Silero backend for the whole engine: the ONNX graph is stateless
|
||||
#: per call, so every session's detector can share it. Resolved lazily,
|
||||
#: on the first session that actually turns server VAD on.
|
||||
self.vad_backend_provider = SileroVADBackendProvider(
|
||||
model_path=getattr(runtime_config, "server_vad_model_path", None)
|
||||
)
|
||||
self.runners: dict[str, DuplexSessionRunner] = {}
|
||||
#: Sessions whose close/expiry began but whose stage cleanup has not finalized;
|
||||
#: they keep their admission slot until finalized.
|
||||
self._closing: dict[str, _PendingSessionCleanup] = {}
|
||||
#: Session ids whose ``open`` passed the capacity check and is still awaiting the plugin.
|
||||
self._admitting: set[str] = set()
|
||||
#: Opens whose caller gave up (control RPC timeout / cancellation) before
|
||||
#: admission finished. The open completes anyway -- it is already past
|
||||
#: the capacity check -- so it must tear itself down on arrival instead
|
||||
#: of holding a slot and a stage resource until idle expiry.
|
||||
self._abandoned_opens: set[str] = set()
|
||||
self._request_index: dict[str, str] = {}
|
||||
self._session_control_tails: dict[str, asyncio.Task[None]] = {}
|
||||
self._dispatched_control_tasks: set[asyncio.Task[None]] = set()
|
||||
self._pending_request_cleanups: dict[tuple[str, int], _PendingRequestCleanup] = {}
|
||||
self._request_cleanup_tasks: dict[tuple[str, int], asyncio.Task[None]] = {}
|
||||
self._request_cleanups_in_progress: set[tuple[str, int]] = set()
|
||||
#: Sessions retained for cleanup retry after their runner is gone.
|
||||
self._session_snapshots: dict[str, DuplexEngineSession] = {}
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Views #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def active_count(self) -> int:
|
||||
return len(self.runners)
|
||||
|
||||
def get(self, session_id: str) -> DuplexEngineSession | None:
|
||||
runner = self.runners.get(session_id)
|
||||
return runner.session if runner is not None else None
|
||||
|
||||
def sessions(self) -> dict[str, DuplexEngineSession]:
|
||||
return {session_id: runner.session for session_id, runner in self.runners.items()}
|
||||
|
||||
def runner_for_request_id(self, request_id: str) -> DuplexSessionRunner | None:
|
||||
session_id = self._request_index.get(request_id)
|
||||
if session_id is None:
|
||||
for candidate_id in self.runners:
|
||||
if duplex_resource_request_belongs_to_session(request_id, candidate_id):
|
||||
session_id = candidate_id
|
||||
break
|
||||
if session_id is None:
|
||||
return None
|
||||
return self.runners.get(session_id)
|
||||
|
||||
def register_request(self, request_id: str, session_id: str) -> None:
|
||||
self._request_index[request_id] = session_id
|
||||
|
||||
def unregister_request(self, request_id: str) -> None:
|
||||
self._request_index.pop(request_id, None)
|
||||
|
||||
def _unregister_session_requests(self, session_id: str) -> None:
|
||||
for request_id in [rid for rid, sid in self._request_index.items() if sid == session_id]:
|
||||
self._request_index.pop(request_id, None)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Message routing #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def accepts(self, message: object) -> bool:
|
||||
return isinstance(message, self._MESSAGE_TYPES)
|
||||
|
||||
def dispatch(self, message: object) -> None:
|
||||
"""Route one engine request-queue message without blocking the request handler."""
|
||||
if isinstance(message, DuplexSessionCommandMessage):
|
||||
self._dispatch_command(message)
|
||||
return
|
||||
if not isinstance(message, self._CONTROL_TYPES):
|
||||
raise TypeError(f"Unsupported duplex control message: {type(message).__name__}")
|
||||
session_id = message.session_id
|
||||
|
||||
async def handle_message() -> None:
|
||||
await self.handle(message)
|
||||
|
||||
self._run_control(session_id, f"duplex-control-{session_id}-{message.control_id}", handle_message)
|
||||
|
||||
def _run_control(
|
||||
self,
|
||||
session_id: str,
|
||||
name: str,
|
||||
operation: Callable[[], Awaitable[None]],
|
||||
) -> asyncio.Task[None]:
|
||||
"""Run one control operation after the session's previous one (per-session order)."""
|
||||
predecessor = self._session_control_tails.get(session_id)
|
||||
|
||||
async def run_ordered() -> None:
|
||||
if predecessor is not None:
|
||||
try:
|
||||
await predecessor
|
||||
except BaseException:
|
||||
pass
|
||||
await operation()
|
||||
|
||||
task = asyncio.create_task(run_ordered(), name=name)
|
||||
self._session_control_tails[session_id] = task
|
||||
self._track_task(task)
|
||||
|
||||
def discard(completed: asyncio.Task[None]) -> None:
|
||||
if self._session_control_tails.get(session_id) is completed:
|
||||
self._session_control_tails.pop(session_id, None)
|
||||
|
||||
task.add_done_callback(discard)
|
||||
return task
|
||||
|
||||
def _track_task(self, task: asyncio.Task[None]) -> None:
|
||||
"""Keep a background task alive until it finishes and log an escaped exception."""
|
||||
self._dispatched_control_tasks.add(task)
|
||||
|
||||
def done(completed: asyncio.Task[None]) -> None:
|
||||
self._dispatched_control_tasks.discard(completed)
|
||||
if not completed.cancelled() and completed.exception() is not None:
|
||||
logger.error("duplex control task %s failed: %r", completed.get_name(), completed.exception())
|
||||
|
||||
task.add_done_callback(done)
|
||||
|
||||
async def handle(self, message: object) -> None:
|
||||
if isinstance(message, OpenDuplexSessionMessage):
|
||||
await self.open(message)
|
||||
elif isinstance(message, CloseDuplexSessionMessage):
|
||||
await self.close(message)
|
||||
elif isinstance(message, ResumeDuplexSessionMessage):
|
||||
await self.resume(message)
|
||||
elif isinstance(message, TouchDuplexSessionMessage):
|
||||
await self.touch(message)
|
||||
elif isinstance(message, DuplexSessionCommandMessage):
|
||||
self._dispatch_command(message)
|
||||
else:
|
||||
raise TypeError(f"Unsupported duplex control message: {type(message).__name__}")
|
||||
|
||||
def _dispatch_command(self, message: DuplexSessionCommandMessage) -> None:
|
||||
"""Admit one command: identity check, backpressure, then the runner's ordered mailbox.
|
||||
|
||||
Backpressure contract shared with the runner: a ``Commit`` that passes
|
||||
admission holds one pending-turn reservation and an ``AppendAudio``
|
||||
holds its wire-size byte reservation until the runner dequeues the
|
||||
command (the runner then re-reserves the decoded size around its PCM
|
||||
reservation), so the mailbox never holds more bytes than the session
|
||||
limit even while the worker is busy.
|
||||
"""
|
||||
runner = self.runners.get(message.session_id)
|
||||
command = message.command
|
||||
if runner is None:
|
||||
self._emit_raw(
|
||||
message.session_id,
|
||||
self._error_event(
|
||||
"unknown_session",
|
||||
f"Unknown or closed duplex session: {message.session_id}",
|
||||
command=command,
|
||||
),
|
||||
)
|
||||
return
|
||||
session = runner.session
|
||||
if runner.closing:
|
||||
self.emit(
|
||||
session,
|
||||
self._error_event(
|
||||
"session_closed", f"Duplex session is closing: {session.session_id}", command=command
|
||||
),
|
||||
)
|
||||
return
|
||||
if isinstance(command, AppendAudio):
|
||||
limit = int(self.runtime_config.max_pending_input_bytes_per_session)
|
||||
if not session.reserve_input_bytes(len(command.audio), limit=limit):
|
||||
self.emit(
|
||||
session,
|
||||
self._error_event(
|
||||
"input_backpressure",
|
||||
"Duplex session has too many pending input bytes",
|
||||
command=command,
|
||||
),
|
||||
)
|
||||
return
|
||||
elif isinstance(command, Commit):
|
||||
if not session.reserve_pending_turn(limit=int(self.runtime_config.max_pending_turns_per_session)):
|
||||
self.emit(
|
||||
session,
|
||||
self._error_event(
|
||||
"input_backpressure",
|
||||
"Duplex session has too many pending input turns",
|
||||
command=command,
|
||||
),
|
||||
)
|
||||
return
|
||||
runner.submit(command)
|
||||
|
||||
@staticmethod
|
||||
def _error_event(code: str, message: str, *, command: DuplexCommand | None = None) -> ErrorEvent:
|
||||
return error_event(code, message, event_id=command.event_id if command is not None else None)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Emission #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def emit(self, session: DuplexEngineSession, event: DuplexEvent) -> None:
|
||||
"""Bind the session identity to one typed event and push it to the engine output queue."""
|
||||
self._emit_raw(session.session_id, event, epoch=session.epoch)
|
||||
|
||||
def _emit_raw(
|
||||
self,
|
||||
session_id: str,
|
||||
event: DuplexEvent,
|
||||
*,
|
||||
epoch: int | None = None,
|
||||
) -> None:
|
||||
event = replace(event, session_id=session_id, epoch=epoch)
|
||||
message = DuplexSessionEventMessage(session_id=session_id, event=event)
|
||||
put_nowait = getattr(self._output_sink, "put_nowait", None)
|
||||
if callable(put_nowait):
|
||||
put_nowait(message)
|
||||
else: # pragma: no cover - sink without put_nowait
|
||||
asyncio.ensure_future(self._output_sink.put(message))
|
||||
|
||||
async def _put_result(
|
||||
self,
|
||||
message: (
|
||||
OpenDuplexSessionMessage
|
||||
| CloseDuplexSessionMessage
|
||||
| ResumeDuplexSessionMessage
|
||||
| TouchDuplexSessionMessage
|
||||
),
|
||||
*,
|
||||
operation: str,
|
||||
ok: bool,
|
||||
session: DuplexEngineSession | None = None,
|
||||
error: BaseException | None = None,
|
||||
) -> None:
|
||||
error_code, error_message, error_retryable = (
|
||||
self._control_error(error) if error is not None else (None, None, False)
|
||||
)
|
||||
result = DuplexControlResultMessage(
|
||||
control_id=message.control_id,
|
||||
operation=operation,
|
||||
session_id=message.session_id,
|
||||
ok=ok,
|
||||
lease_generation=session.lease_generation if session is not None else None,
|
||||
capabilities=session.capabilities if session is not None and ok else None,
|
||||
public_session=session.as_public_dict() if session is not None and ok else None,
|
||||
error_code=error_code,
|
||||
error_message=error_message,
|
||||
error_retryable=error_retryable,
|
||||
)
|
||||
await self._result_sink.put(result)
|
||||
|
||||
@staticmethod
|
||||
def _control_error(error: BaseException) -> tuple[str, str, bool]:
|
||||
"""Map an exception to ``(code, message, retryable)`` for a control result."""
|
||||
message = str(error)
|
||||
retryable = False
|
||||
if isinstance(error, DuplexSessionError):
|
||||
code = error.code
|
||||
retryable = error.retryable
|
||||
elif isinstance(error, DuplexRuntimeConfigError):
|
||||
code = error.code
|
||||
elif isinstance(error, DuplexFenceMismatchError):
|
||||
code = "stale_fence"
|
||||
elif isinstance(error, KeyError):
|
||||
code = "not_found"
|
||||
elif isinstance(error, TypeError | ValueError):
|
||||
code = "invalid_argument"
|
||||
elif isinstance(error, TimeoutError):
|
||||
code = "timeout"
|
||||
retryable = True
|
||||
else:
|
||||
code = "failed_precondition"
|
||||
return code, message, retryable
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Sampling / stage request helpers shared with the runner #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def sampling_params_for(self, session: DuplexEngineSession) -> tuple[object, ...]:
|
||||
defaults = tuple(self.stage_port.sampling_defaults())
|
||||
configured = self.plugin.configure_sampling_params(
|
||||
runtime_config=dict(session.runtime_config),
|
||||
defaults=defaults,
|
||||
)
|
||||
if not isinstance(configured, tuple):
|
||||
raise TypeError("duplex plugin must return sampling parameters as a tuple")
|
||||
if len(configured) != len(defaults):
|
||||
raise ValueError("duplex plugin must return one sampling parameter per stage")
|
||||
return configured
|
||||
|
||||
@staticmethod
|
||||
def stage_request_id(fence: DuplexFence, *, stage_id: int) -> str:
|
||||
return duplex_resource_request_id(fence, f"stage{stage_id}")
|
||||
|
||||
def ensure_stage_request(
|
||||
self,
|
||||
session: DuplexEngineSession,
|
||||
*,
|
||||
stage_id: int,
|
||||
fence: DuplexFence | None = None,
|
||||
) -> DuplexStageRequestContext | None:
|
||||
"""Reserve the session's stage request id and register it with the stage port."""
|
||||
if stage_id >= self.stage_port.stage_count:
|
||||
return None
|
||||
effective_fence = fence or session.fence
|
||||
request_id = self.stage_request_id(effective_fence, stage_id=stage_id)
|
||||
session.reserve_stage_request(stage_id, request_id, fence=effective_fence)
|
||||
context = DuplexStageRequestContext(
|
||||
request_id=request_id,
|
||||
session_id=session.session_id,
|
||||
fence=effective_fence,
|
||||
stage_id=stage_id,
|
||||
final_stage_id=self.stage_port.stage_count - 1,
|
||||
config_generation=session.config_generation,
|
||||
sampling_params=self.sampling_params_for(session),
|
||||
session_config=session.config.as_dict(),
|
||||
runtime_config=session.runtime_config,
|
||||
)
|
||||
self.stage_port.ensure_request(context)
|
||||
self.register_request(request_id, session.session_id)
|
||||
return context
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Control operations #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def _admission_count(self) -> int:
|
||||
return len(set(self.runners) | set(self._closing) | self._admitting)
|
||||
|
||||
async def open(self, message: OpenDuplexSessionMessage) -> None:
|
||||
from vllm_omni.engine.duplex.session.runner import DuplexSessionRunner
|
||||
|
||||
session_id = message.session_id
|
||||
session: DuplexEngineSession | None = None
|
||||
runner: DuplexSessionRunner | None = None
|
||||
# Only the open that put the id in ``_admitting`` may take it out again:
|
||||
# a duplicate open must not release the slot the first one is holding.
|
||||
holds_admission_slot = False
|
||||
try:
|
||||
if session_id in self.runners or session_id in self._closing or session_id in self._admitting:
|
||||
raise DuplexSessionError(f"Duplex session already exists: {session_id}", code="session_exists")
|
||||
max_sessions = int(self.runtime_config.max_sessions)
|
||||
if self._admission_count() >= max_sessions:
|
||||
raise DuplexSessionError(
|
||||
f"duplex_session_capacity_exhausted: limit={max_sessions}",
|
||||
code="resource_exhausted",
|
||||
retryable=True,
|
||||
)
|
||||
# Hold the slot across the plugin await: opens of different
|
||||
# sessions run concurrently and must not all pass the check above.
|
||||
self._admitting.add(session_id)
|
||||
holds_admission_slot = True
|
||||
config = message.session_config
|
||||
self.plugin.validate_client_extra_body(config.extra_body)
|
||||
try:
|
||||
runtime_config = await self.plugin.prepare_runtime_config(config, model_config=self.model_config)
|
||||
except DuplexRuntimeConfigError:
|
||||
raise
|
||||
except ValueError as exc:
|
||||
raise DuplexRuntimeConfigError(str(exc)) from exc
|
||||
capabilities = self.plugin.capabilities(max_sessions=max_sessions)
|
||||
session = DuplexEngineSession(
|
||||
session_id=session_id,
|
||||
config=config,
|
||||
capabilities=capabilities,
|
||||
lease=DuplexLeaseState(config=self._lease_config, generation=0, last_activity=self._clock()),
|
||||
_clock=self._clock,
|
||||
_runtime_config=dict(runtime_config),
|
||||
)
|
||||
# Validates the plugin's sampling policy for this runtime config before admission.
|
||||
self.sampling_params_for(session)
|
||||
session.model_state = self.plugin.create_session_state()
|
||||
runner = DuplexSessionRunner(
|
||||
session=session,
|
||||
plugin=self.plugin,
|
||||
stage_port=self.stage_port,
|
||||
manager=self,
|
||||
model_config=self.model_config,
|
||||
)
|
||||
self.runners[session_id] = runner
|
||||
# Reserve the Stage0 request resource atomically with admission.
|
||||
self.ensure_stage_request(session, stage_id=0)
|
||||
runner.start()
|
||||
await self._put_result(message, operation="open", ok=True, session=session)
|
||||
if session_id in self._abandoned_opens:
|
||||
# The caller timed out while we were admitting; hand the slot
|
||||
# and the stage resource straight back.
|
||||
self._abandoned_opens.discard(session_id)
|
||||
await self._close_runner(runner, kind="close", reason="open_abandoned")
|
||||
except Exception as exc:
|
||||
error_code, _, _ = self._control_error(exc)
|
||||
if error_code in {"resource_exhausted", "session_exists"}:
|
||||
logger.info("open_duplex_session rejected: %s", exc)
|
||||
else:
|
||||
logger.exception("open_duplex_session failed: %s", exc)
|
||||
if runner is not None and self.runners.get(session_id) is runner:
|
||||
self.runners.pop(session_id, None)
|
||||
try:
|
||||
await runner.shutdown()
|
||||
except Exception:
|
||||
logger.exception("duplex open rollback: runner shutdown failed for %s", session_id)
|
||||
if session is not None:
|
||||
reserved = session.release_all_requests()
|
||||
if reserved:
|
||||
try:
|
||||
await self.stage_port.cleanup(list(reserved))
|
||||
except Exception:
|
||||
logger.warning("duplex open rollback: request cleanup pending for %s", session_id)
|
||||
self._unregister_session_requests(session_id)
|
||||
await self._put_result(message, operation="open", ok=False, error=exc)
|
||||
finally:
|
||||
if holds_admission_slot:
|
||||
self._admitting.discard(session_id)
|
||||
self._abandoned_opens.discard(session_id)
|
||||
|
||||
def _require_runner(self, session_id: str) -> DuplexSessionRunner:
|
||||
runner = self.runners.get(session_id)
|
||||
if runner is None:
|
||||
raise DuplexSessionError(f"Unknown duplex session: {session_id}", code="unknown_session")
|
||||
if runner.closing:
|
||||
raise DuplexSessionError(f"Duplex session is closing: {session_id}", code="session_closed")
|
||||
return runner
|
||||
|
||||
async def close(self, message: CloseDuplexSessionMessage) -> None:
|
||||
session_id = message.session_id
|
||||
runner = self.runners.get(session_id)
|
||||
if runner is None:
|
||||
if session_id in self._admitting:
|
||||
# The open is still awaiting the plugin. It cannot be cancelled
|
||||
# from here, so leave a note it checks before returning.
|
||||
self._abandoned_opens.add(session_id)
|
||||
# Already closing, or closed and forgotten: ids are never reused
|
||||
# (D16), so a repeated close is idempotent rather than an error.
|
||||
await self._put_result(message, operation="close", ok=True)
|
||||
return
|
||||
session = runner.session
|
||||
try:
|
||||
await self._close_runner(runner, kind="close", reason=message.reason)
|
||||
except Exception as exc:
|
||||
# The session is closed either way; only the stage cleanup is
|
||||
# outstanding and the reaper retries it while the slot stays held.
|
||||
logger.warning("close_duplex_session: stage cleanup for %s remains pending: %s", session_id, exc)
|
||||
await self._put_result(message, operation="close", ok=True, session=session)
|
||||
|
||||
def close_from_runner(self, runner: DuplexSessionRunner, reason: str) -> None:
|
||||
"""Finish a close the runner started from its command stream (``session.close``).
|
||||
|
||||
Runs on the orchestrator loop as a tracked task (the runner's worker
|
||||
cannot await its own teardown): stage requests are aborted, the
|
||||
admission slot is released and ``session.closed`` is emitted last.
|
||||
"""
|
||||
session_id = runner.session.session_id
|
||||
if self.runners.get(session_id) is not runner:
|
||||
return
|
||||
|
||||
async def close_runner() -> None:
|
||||
if self.runners.get(session_id) is runner:
|
||||
await self._close_runner(runner, kind="close", reason=reason)
|
||||
|
||||
# Chained on the session's control tail so a control RPC issued after
|
||||
# the wire close observes the closed session, never a half-torn one.
|
||||
self._run_control(session_id, f"duplex-close-{session_id}", close_runner)
|
||||
|
||||
async def _close_runner(self, runner: DuplexSessionRunner, *, kind: str, reason: str) -> None:
|
||||
"""Begin an irreversible close, tear down the runner, then release stage resources.
|
||||
|
||||
The session keeps its admission slot (``_closing``) until stage cleanup
|
||||
succeeded; a failed cleanup is retried by the reaper. For an explicit
|
||||
close the ``session.closed`` event is emitted only after the cleanup
|
||||
attempt, so a client that sees it can open a replacement session at
|
||||
once (the runner used to emit it before the stage requests were
|
||||
aborted, which let a prompt reopen hit ``resource_exhausted``).
|
||||
"""
|
||||
session = runner.session
|
||||
submitted = tuple(session.resource_request_ids(submitted=True))
|
||||
reserved = tuple(session.resource_request_ids(submitted=False))
|
||||
session.begin_close(reason=reason)
|
||||
pending = _PendingSessionCleanup(
|
||||
kind=kind,
|
||||
session_id=session.session_id,
|
||||
lease_generation=session.lease_generation,
|
||||
reason=reason,
|
||||
submitted_request_ids=submitted,
|
||||
reserved_request_ids=reserved,
|
||||
)
|
||||
self._closing[session.session_id] = pending
|
||||
if self.runners.get(session.session_id) is runner:
|
||||
self.runners.pop(session.session_id, None)
|
||||
emit_after_cleanup = kind in {"close", "expired"} and not runner.closed_emitted
|
||||
try:
|
||||
if kind == "expired":
|
||||
await runner.expire(reason, emit_expired=not emit_after_cleanup)
|
||||
else:
|
||||
await runner.close(reason, emit_closed=not emit_after_cleanup)
|
||||
except Exception:
|
||||
logger.exception("duplex runner %s failed for session %s", kind, session.session_id)
|
||||
session.close()
|
||||
try:
|
||||
await self._finalize_pending_cleanup(pending, session)
|
||||
finally:
|
||||
# ``emit_after_cleanup`` was decided before the teardown awaits; a
|
||||
# runtime close racing them may have emitted the terminal already.
|
||||
if emit_after_cleanup and not runner.closed_emitted:
|
||||
runner.mark_closed_emitted()
|
||||
terminal: DuplexEvent = (
|
||||
SessionExpired(reason=reason) if kind == "expired" else SessionClosed(reason=reason)
|
||||
)
|
||||
self.emit(session, terminal)
|
||||
|
||||
async def _finalize_pending_cleanup(
|
||||
self,
|
||||
pending: _PendingSessionCleanup,
|
||||
session: DuplexEngineSession | None,
|
||||
) -> None:
|
||||
if pending.submitted_request_ids:
|
||||
await self.stage_port.cleanup(list(pending.submitted_request_ids), abort=True)
|
||||
if pending.reserved_request_ids:
|
||||
await self.stage_port.cleanup(list(pending.reserved_request_ids))
|
||||
if session is not None:
|
||||
session.release_all_requests()
|
||||
self._unregister_session_requests(pending.session_id)
|
||||
if self._closing.get(pending.session_id) is pending:
|
||||
self._closing.pop(pending.session_id, None)
|
||||
self._session_snapshots.pop(pending.session_id, None)
|
||||
|
||||
async def resume(self, message: ResumeDuplexSessionMessage) -> None:
|
||||
session: DuplexEngineSession | None = None
|
||||
try:
|
||||
runner = self._require_runner(message.session_id)
|
||||
session = runner.session
|
||||
try:
|
||||
session.resume_lease(expected_lease_generation=message.expected_lease_generation)
|
||||
except ValueError as exc:
|
||||
raise DuplexSessionError(str(exc), code="session_resume_conflict") from exc
|
||||
await self._put_result(message, operation="resume", ok=True, session=session)
|
||||
except Exception as exc:
|
||||
logger.exception("resume_duplex_session failed: %s", exc)
|
||||
await self._put_result(message, operation="resume", ok=False, session=session, error=exc)
|
||||
|
||||
async def touch(self, message: TouchDuplexSessionMessage) -> None:
|
||||
session: DuplexEngineSession | None = None
|
||||
try:
|
||||
runner = self._require_runner(message.session_id)
|
||||
session = runner.session
|
||||
activity = DuplexLeaseActivity(message.activity)
|
||||
if activity is DuplexLeaseActivity.DETACH:
|
||||
session.detach_lease()
|
||||
else:
|
||||
session.touch_lease(activity)
|
||||
await self._put_result(message, operation="touch", ok=True, session=session)
|
||||
except DuplexSessionError as exc:
|
||||
# A lease touch racing the session's own close is routine: the
|
||||
# caller learns the session is gone from the result, not a fault.
|
||||
logger.debug("touch_duplex_session skipped: %s", exc)
|
||||
await self._put_result(message, operation="touch", ok=False, session=session, error=exc)
|
||||
except Exception as exc:
|
||||
logger.exception("touch_duplex_session failed: %s", exc)
|
||||
await self._put_result(message, operation="touch", ok=False, session=session, error=exc)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Lease expiry / reaper #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
async def reaper_loop(self, shutdown_event: asyncio.Event) -> None:
|
||||
interval = float(self.runtime_config.reaper_interval_s)
|
||||
while not shutdown_event.is_set():
|
||||
try:
|
||||
await asyncio.wait_for(shutdown_event.wait(), timeout=interval)
|
||||
except TimeoutError:
|
||||
try:
|
||||
await self.reap_expired()
|
||||
except Exception:
|
||||
logger.exception("[DuplexSessionManager] expiry cleanup failed; retrying on next tick")
|
||||
|
||||
async def reap_expired(self, now: float | None = None) -> int:
|
||||
completed = 0
|
||||
effective_now = self._clock() if now is None else now
|
||||
# Retry request cleanups recorded by the orchestrator error paths.
|
||||
for key, request_cleanup in list(self._pending_request_cleanups.items()):
|
||||
if key in self._request_cleanups_in_progress:
|
||||
continue
|
||||
try:
|
||||
await self._complete_request_cleanup(key, request_cleanup)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"duplex request cleanup remains pending for session %s: %s",
|
||||
request_cleanup.session_id,
|
||||
exc,
|
||||
)
|
||||
continue
|
||||
completed += 1
|
||||
# Retry closes/expiries whose stage cleanup failed.
|
||||
for session_id, session_cleanup in list(self._closing.items()):
|
||||
if session_id in self.runners:
|
||||
continue
|
||||
if session_cleanup.kind == "request_cleanup" and any(
|
||||
key[0] == session_id for key in self._pending_request_cleanups
|
||||
):
|
||||
# The stage cleanup is owned by the request-cleanup path (orchestrator
|
||||
# or the retry above); ``finalize_closed_sessions`` releases the slot.
|
||||
continue
|
||||
try:
|
||||
await self._finalize_pending_cleanup(session_cleanup, self._session_snapshots.get(session_id))
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"duplex %s cleanup remains pending for session %s: %s",
|
||||
session_cleanup.kind,
|
||||
session_id,
|
||||
exc,
|
||||
)
|
||||
continue
|
||||
completed += 1
|
||||
# Expire leases.
|
||||
for session_id, runner in list(self.runners.items()):
|
||||
lease = runner.session.lease
|
||||
if lease.disconnect_grace_expired(effective_now):
|
||||
reason = "disconnect_grace_expired"
|
||||
elif lease.idle_expired(effective_now):
|
||||
reason = "idle_ttl_expired"
|
||||
else:
|
||||
continue
|
||||
self._session_snapshots[session_id] = runner.session
|
||||
try:
|
||||
await self._close_runner(runner, kind="expired", reason=reason)
|
||||
except Exception as exc:
|
||||
logger.warning("duplex expiry cleanup remains pending for session %s: %s", session_id, exc)
|
||||
continue
|
||||
completed += 1
|
||||
return completed
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Request-triggered cleanup (orchestrator error paths) #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def close_sessions_for_request_ids(
|
||||
self,
|
||||
request_ids: list[str],
|
||||
*,
|
||||
abort: bool = False,
|
||||
cleanup_in_progress: bool = False,
|
||||
) -> dict[str, list[str]]:
|
||||
request_id_set = set(request_ids)
|
||||
closed: dict[str, list[str]] = {}
|
||||
for session_id, runner in list(self.runners.items()):
|
||||
session = runner.session
|
||||
stale = session.resource_request_ids()
|
||||
if request_id_set.isdisjoint(stale):
|
||||
continue
|
||||
if not session.begin_close(reason="request_cleanup"):
|
||||
continue
|
||||
closed[session_id] = stale
|
||||
key = (session_id, session.lease_generation)
|
||||
existing = self._pending_request_cleanups.get(key)
|
||||
merged = tuple(dict.fromkeys([*(existing.request_ids if existing is not None else ()), *stale]))
|
||||
self._pending_request_cleanups[key] = _PendingRequestCleanup(
|
||||
session_id=session_id,
|
||||
lease_generation=session.lease_generation,
|
||||
request_ids=merged,
|
||||
abort=abort or (existing.abort if existing is not None else False),
|
||||
)
|
||||
if cleanup_in_progress:
|
||||
self._request_cleanups_in_progress.add(key)
|
||||
# Tear the runner down in the background; the orchestrator owns the stage cleanup.
|
||||
self._session_snapshots[session_id] = session
|
||||
self._closing[session_id] = _PendingSessionCleanup(
|
||||
kind="request_cleanup",
|
||||
session_id=session_id,
|
||||
lease_generation=session.lease_generation,
|
||||
reason="request_cleanup",
|
||||
submitted_request_ids=(),
|
||||
reserved_request_ids=(),
|
||||
)
|
||||
self.runners.pop(session_id, None)
|
||||
task = asyncio.create_task(runner.expire("request_cleanup"), name=f"duplex-request-cleanup-{session_id}")
|
||||
self._track_task(task)
|
||||
return closed
|
||||
|
||||
def defer_request_cleanups(self, session_ids: Iterable[str]) -> None:
|
||||
session_id_set = set(session_ids)
|
||||
active_keys = {key for key in self._request_cleanups_in_progress if key[0] in session_id_set}
|
||||
self._request_cleanups_in_progress.difference_update(active_keys)
|
||||
|
||||
def finalize_closed_sessions(self, session_ids: Iterable[str]) -> None:
|
||||
session_id_set = set(session_ids)
|
||||
for key in list(self._pending_request_cleanups):
|
||||
if key[0] not in session_id_set:
|
||||
continue
|
||||
self._pending_request_cleanups.pop(key, None)
|
||||
self._request_cleanups_in_progress.discard(key)
|
||||
for session_id in session_id_set:
|
||||
session = self._session_snapshots.pop(session_id, None)
|
||||
if session is not None and session.lease.terminal_reason is not None:
|
||||
session.release_all_requests()
|
||||
session.close()
|
||||
self._closing.pop(session_id, None)
|
||||
self._unregister_session_requests(session_id)
|
||||
|
||||
async def _complete_request_cleanup(
|
||||
self,
|
||||
key: tuple[str, int],
|
||||
pending: _PendingRequestCleanup,
|
||||
) -> None:
|
||||
task = self._request_cleanup_tasks.get(key)
|
||||
if task is not None and task.done():
|
||||
self._request_cleanup_tasks.pop(key, None)
|
||||
task = None
|
||||
if task is None:
|
||||
task = asyncio.create_task(
|
||||
self._run_request_cleanup(key, pending),
|
||||
name=f"duplex-request-cleanup-{pending.session_id}",
|
||||
)
|
||||
self._request_cleanup_tasks[key] = task
|
||||
|
||||
def discard(completed: asyncio.Task[None]) -> None:
|
||||
if self._request_cleanup_tasks.get(key) is completed:
|
||||
self._request_cleanup_tasks.pop(key, None)
|
||||
|
||||
task.add_done_callback(discard)
|
||||
await asyncio.shield(task)
|
||||
|
||||
async def _run_request_cleanup(self, key: tuple[str, int], pending: _PendingRequestCleanup) -> None:
|
||||
await self.stage_port.cleanup(list(pending.request_ids), abort=pending.abort)
|
||||
if self._pending_request_cleanups.get(key) is pending:
|
||||
self._pending_request_cleanups.pop(key, None)
|
||||
self._request_cleanups_in_progress.discard(key)
|
||||
self.finalize_closed_sessions([pending.session_id])
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Shutdown #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
async def shutdown(self) -> None:
|
||||
runners = list(self.runners.values())
|
||||
self.runners.clear()
|
||||
for runner in runners:
|
||||
try:
|
||||
await runner.shutdown()
|
||||
except Exception:
|
||||
logger.exception("duplex runner shutdown failed for %s", runner.session.session_id)
|
||||
tasks = tuple(self._dispatched_control_tasks | set(self._request_cleanup_tasks.values()))
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
if tasks:
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
self._session_control_tails.clear()
|
||||
self._closing.clear()
|
||||
self._session_snapshots.clear()
|
||||
self._request_index.clear()
|
||||
if self._owns_executor:
|
||||
self.executor.shutdown(wait=False, cancel_futures=True)
|
||||
|
||||
|
||||
__all__ = ["DuplexSessionManager"]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,388 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""How one duplex session reacts to input that arrives while it is speaking.
|
||||
|
||||
Short acknowledgement, barge-in, or keep listening: the rules read the session
|
||||
config and the incoming append, and nothing else. Extracted from
|
||||
``DuplexSessionRunner`` because they were a decision function wearing a
|
||||
method's clothes -- the only runner state they ever touched was ``session`` --
|
||||
and because reaching them previously meant driving a whole append through the
|
||||
runner.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import binascii
|
||||
from collections.abc import Mapping
|
||||
|
||||
import numpy as np
|
||||
import pybase64 as base64
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexOverlapPolicy
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
|
||||
|
||||
def decide(
|
||||
session: DuplexEngineSession,
|
||||
event: dict[str, object],
|
||||
payload: dict[str, object],
|
||||
*,
|
||||
auto_responds: bool,
|
||||
) -> dict[str, object]:
|
||||
duration_ms = input_audio_duration_ms(event, payload)
|
||||
is_speech = input_looks_like_speech(session, event, payload)
|
||||
if not session.capabilities.supports_barge_in and event_requests_barge_in(event):
|
||||
return defer_unsupported_barge_in(session, duration_ms=duration_ms, is_speech=is_speech)
|
||||
explicit = event.get("overlap_action") or event.get("overlap")
|
||||
if isinstance(explicit, str):
|
||||
normalized = explicit.strip().lower()
|
||||
if normalized in {"barge_in", "interrupt", "cancel"}:
|
||||
return {
|
||||
"action": "barge_in",
|
||||
"reason": "client_overlap_action",
|
||||
"duration_ms": duration_ms,
|
||||
"buffer_audio": True,
|
||||
}
|
||||
if normalized in {"listen", "continue", "continue_output", "ack"}:
|
||||
session.reset_overlap_speech()
|
||||
return {
|
||||
"action": "listen",
|
||||
"reason": "client_overlap_action",
|
||||
"duration_ms": duration_ms,
|
||||
"buffer_audio": (
|
||||
normalized == "listen" and is_speech and duration_ms > session.config.overlap_short_ack_ms
|
||||
),
|
||||
"defer_runtime_append": True,
|
||||
}
|
||||
if normalized in {"drop", "ignore", "silence"}:
|
||||
session.reset_overlap_speech()
|
||||
return {
|
||||
"action": "drop",
|
||||
"reason": "client_overlap_action",
|
||||
"duration_ms": duration_ms,
|
||||
"buffer_audio": False,
|
||||
}
|
||||
|
||||
if bool(event.get("force_barge_in", False)):
|
||||
return {
|
||||
"action": "barge_in",
|
||||
"reason": "client_force_barge_in",
|
||||
"duration_ms": duration_ms,
|
||||
"buffer_audio": True,
|
||||
}
|
||||
if auto_responds:
|
||||
if is_speech:
|
||||
session.accumulate_overlap_speech(duration_ms)
|
||||
speech_started = vad_speech_started(event, payload)
|
||||
if (
|
||||
session.capabilities.supports_barge_in
|
||||
and is_speech
|
||||
and session.config.overlap_policy == DuplexOverlapPolicy.BARGE_IN_ON_SPEECH.value
|
||||
and speech_started is not False
|
||||
):
|
||||
return {
|
||||
"action": "barge_in",
|
||||
"reason": ("server_vad_speech_started" if speech_started is True else "barge_in_on_speech"),
|
||||
"cancel_reason": "turn_detected" if speech_started is True else "barge_in",
|
||||
"duration_ms": duration_ms,
|
||||
"overlap_speech_ms": session.overlap_speech_ms,
|
||||
"buffer_audio": True,
|
||||
}
|
||||
return {
|
||||
"action": "listen",
|
||||
"reason": "auto_response_continuous",
|
||||
"duration_ms": duration_ms,
|
||||
"overlap_speech_ms": session.overlap_speech_ms,
|
||||
"buffer_audio": True,
|
||||
"defer_runtime_append": False,
|
||||
"force_listen": event.get("force_listen") is True or payload.get("force_listen") is True,
|
||||
"preserve_realtime_input": True,
|
||||
}
|
||||
if bool(event.get("force_listen", False)):
|
||||
session.reset_overlap_speech()
|
||||
return {
|
||||
"action": "listen",
|
||||
"reason": "client_force_listen",
|
||||
"duration_ms": duration_ms,
|
||||
"buffer_audio": is_speech,
|
||||
"defer_runtime_append": True,
|
||||
}
|
||||
|
||||
policy = session.config.overlap_policy
|
||||
if not is_speech:
|
||||
if session.overlap_speech_ms <= 0:
|
||||
session.reset_overlap_speech()
|
||||
return {
|
||||
"action": "drop",
|
||||
"reason": "silence_or_noise",
|
||||
"duration_ms": duration_ms,
|
||||
"overlap_speech_ms": session.overlap_speech_ms,
|
||||
"buffer_audio": False,
|
||||
}
|
||||
|
||||
if is_short_ack_transcript_hint(event, payload):
|
||||
session.reset_overlap_speech()
|
||||
return {
|
||||
"action": "listen",
|
||||
"reason": "short_ack_transcript",
|
||||
"duration_ms": duration_ms,
|
||||
"overlap_speech_ms": session.overlap_speech_ms,
|
||||
"buffer_audio": False,
|
||||
"defer_runtime_append": True,
|
||||
}
|
||||
|
||||
if policy == DuplexOverlapPolicy.LISTEN_ONLY.value:
|
||||
session.accumulate_overlap_speech(duration_ms)
|
||||
return {
|
||||
"action": "listen",
|
||||
"reason": "policy_listen_only",
|
||||
"duration_ms": duration_ms,
|
||||
"overlap_speech_ms": session.overlap_speech_ms,
|
||||
"buffer_audio": True,
|
||||
"defer_runtime_append": True,
|
||||
}
|
||||
|
||||
if policy == DuplexOverlapPolicy.BARGE_IN_ON_SPEECH.value and not session.capabilities.supports_barge_in:
|
||||
return defer_unsupported_barge_in(session, duration_ms=duration_ms, is_speech=True)
|
||||
|
||||
session.accumulate_overlap_speech(duration_ms)
|
||||
if policy == DuplexOverlapPolicy.BARGE_IN_ON_SPEECH.value:
|
||||
speech_started = vad_speech_started(event, payload)
|
||||
if speech_started is False:
|
||||
return {
|
||||
"action": "listen",
|
||||
"reason": "server_vad_utterance_active",
|
||||
"duration_ms": duration_ms,
|
||||
"overlap_speech_ms": session.overlap_speech_ms,
|
||||
"buffer_audio": True,
|
||||
"defer_runtime_append": False,
|
||||
"force_listen": True,
|
||||
"preserve_realtime_input": True,
|
||||
}
|
||||
return {
|
||||
"action": "barge_in",
|
||||
"reason": ("server_vad_speech_started" if speech_started is True else "policy_barge_in_on_speech"),
|
||||
"cancel_reason": "turn_detected" if speech_started is True else "barge_in",
|
||||
"duration_ms": duration_ms,
|
||||
"overlap_speech_ms": session.overlap_speech_ms,
|
||||
"buffer_audio": True,
|
||||
}
|
||||
|
||||
if (
|
||||
duration_ms <= session.config.overlap_short_ack_ms
|
||||
and session.overlap_speech_ms <= session.config.overlap_short_ack_ms
|
||||
):
|
||||
return {
|
||||
"action": "listen",
|
||||
"reason": "short_ack",
|
||||
"duration_ms": duration_ms,
|
||||
"overlap_speech_ms": session.overlap_speech_ms,
|
||||
"buffer_audio": True,
|
||||
"defer_runtime_append": True,
|
||||
}
|
||||
if session.overlap_speech_ms >= session.config.overlap_barge_in_ms:
|
||||
if not session.capabilities.supports_barge_in:
|
||||
return {
|
||||
"action": "listen",
|
||||
"reason": "barge_in_unsupported",
|
||||
"duration_ms": duration_ms,
|
||||
"overlap_speech_ms": session.overlap_speech_ms,
|
||||
"buffer_audio": True,
|
||||
"defer_runtime_append": True,
|
||||
}
|
||||
return {
|
||||
"action": "barge_in",
|
||||
"reason": "long_overlap_speech",
|
||||
"duration_ms": duration_ms,
|
||||
"overlap_speech_ms": session.overlap_speech_ms,
|
||||
"buffer_audio": True,
|
||||
}
|
||||
return {
|
||||
"action": "listen",
|
||||
"reason": "accumulating_overlap_speech",
|
||||
"duration_ms": duration_ms,
|
||||
"overlap_speech_ms": session.overlap_speech_ms,
|
||||
"buffer_audio": True,
|
||||
"defer_runtime_append": True,
|
||||
}
|
||||
|
||||
|
||||
def vad_speech_started(event: Mapping[str, object], payload: Mapping[str, object]) -> bool | None:
|
||||
for source in (event, payload):
|
||||
vad = source.get("vad")
|
||||
if isinstance(vad, Mapping) and isinstance(vad.get("speech_started"), bool):
|
||||
return bool(vad["speech_started"])
|
||||
return None
|
||||
|
||||
|
||||
def event_requests_barge_in(event: Mapping[str, object]) -> bool:
|
||||
if event.get("force_barge_in") is True:
|
||||
return True
|
||||
explicit = event.get("overlap_action") or event.get("overlap")
|
||||
return isinstance(explicit, str) and explicit.strip().lower() in {"barge_in", "interrupt", "cancel"}
|
||||
|
||||
|
||||
def defer_unsupported_barge_in(
|
||||
session: DuplexEngineSession,
|
||||
*,
|
||||
duration_ms: int,
|
||||
is_speech: bool,
|
||||
) -> dict[str, object]:
|
||||
if is_speech:
|
||||
session.accumulate_overlap_speech(duration_ms)
|
||||
return {
|
||||
"action": "listen",
|
||||
"reason": "barge_in_unsupported",
|
||||
"duration_ms": duration_ms,
|
||||
"overlap_speech_ms": session.overlap_speech_ms,
|
||||
"buffer_audio": is_speech,
|
||||
"defer_runtime_append": True,
|
||||
}
|
||||
|
||||
|
||||
def is_short_ack_transcript_hint(event: dict[str, object], payload: dict[str, object]) -> bool:
|
||||
raw_text = event.get("transcript") or event.get("text") or payload.get("transcript") or payload.get("text")
|
||||
if not isinstance(raw_text, str):
|
||||
return False
|
||||
normalized = raw_text.strip().lower()
|
||||
if not normalized:
|
||||
return False
|
||||
compact = "".join(ch for ch in normalized if ch.isalnum() or "一" <= ch <= "鿿")
|
||||
if compact in {
|
||||
"嗯",
|
||||
"嗯嗯",
|
||||
"对",
|
||||
"对的",
|
||||
"好",
|
||||
"好的",
|
||||
"继续",
|
||||
"继续说",
|
||||
"可以",
|
||||
"是的",
|
||||
"yes",
|
||||
"yeah",
|
||||
"yep",
|
||||
"ok",
|
||||
"okay",
|
||||
"continue",
|
||||
"goon",
|
||||
"right",
|
||||
}:
|
||||
return True
|
||||
return normalized in {"go on", "keep going", "please continue"}
|
||||
|
||||
|
||||
def input_audio_duration_ms(event: dict[str, object], payload: dict[str, object]) -> int:
|
||||
for key in ("duration_ms", "audio_duration_ms"):
|
||||
value = event.get(key)
|
||||
if isinstance(value, int | float):
|
||||
return max(0, int(value))
|
||||
fmt = payload.get("format")
|
||||
sample_rate_hz = payload.get("sample_rate_hz")
|
||||
audio = payload.get("audio")
|
||||
if fmt == "pcm_f32le" and isinstance(sample_rate_hz, int) and sample_rate_hz > 0 and isinstance(audio, str):
|
||||
try:
|
||||
raw = base64.b64decode(audio, validate=True)
|
||||
except (binascii.Error, ValueError):
|
||||
return 0
|
||||
return int((len(raw) // 4) * 1000 / sample_rate_hz)
|
||||
return 0
|
||||
|
||||
|
||||
def merge_audio_payloads(first: dict[str, object], second: dict[str, object]) -> dict[str, object]:
|
||||
if first.get("format") != "pcm_f32le" or second.get("format") != "pcm_f32le":
|
||||
return second
|
||||
first_rate = first.get("sample_rate_hz")
|
||||
second_rate = second.get("sample_rate_hz")
|
||||
if not isinstance(first_rate, int) or not isinstance(second_rate, int) or first_rate != second_rate:
|
||||
return second
|
||||
first_audio = first.get("audio")
|
||||
second_audio = second.get("audio")
|
||||
if not isinstance(first_audio, str) or not isinstance(second_audio, str):
|
||||
return second
|
||||
try:
|
||||
first_raw = base64.b64decode(first_audio, validate=True)
|
||||
second_raw = base64.b64decode(second_audio, validate=True)
|
||||
except (binascii.Error, ValueError):
|
||||
return second
|
||||
merged = dict(second)
|
||||
merged["audio"] = base64.b64encode(first_raw + second_raw).decode("ascii")
|
||||
merged["sample_rate_hz"] = first_rate
|
||||
merged_frames = [
|
||||
frame
|
||||
for source in (first.get("video_frames"), second.get("video_frames"))
|
||||
if isinstance(source, list)
|
||||
for frame in source
|
||||
if isinstance(frame, str) and frame
|
||||
]
|
||||
if merged_frames:
|
||||
merged["video_frames"] = merged_frames
|
||||
else:
|
||||
merged.pop("video_frames", None)
|
||||
merged["force_listen"] = bool(first.get("force_listen", False)) or bool(second.get("force_listen", False))
|
||||
merged.pop("force_speak", None)
|
||||
merged["is_speech"] = bool(first.get("is_speech", False)) or bool(second.get("is_speech", False))
|
||||
return merged
|
||||
|
||||
|
||||
def should_force_listen_for_short_commit(
|
||||
session: DuplexEngineSession, event: dict[str, object], payload: dict[str, object]
|
||||
) -> bool:
|
||||
if event.get("force_listen") is True or payload.get("force_listen") is True:
|
||||
return True
|
||||
if event.get("force_barge_in") is True:
|
||||
return False
|
||||
if event.get("response_create") is not True:
|
||||
return False
|
||||
duration_ms = input_audio_duration_ms(event, payload)
|
||||
return 0 < duration_ms <= session.config.overlap_short_ack_ms
|
||||
|
||||
|
||||
def should_force_listen_for_auto_response_overlap(
|
||||
event: dict[str, object], payload: dict[str, object], *, auto_responds: bool
|
||||
) -> bool:
|
||||
if not auto_responds:
|
||||
return False
|
||||
if event.get("force_barge_in") is True:
|
||||
return False
|
||||
return event.get("force_listen") is True or payload.get("force_listen") is True
|
||||
|
||||
|
||||
def input_looks_like_speech(session: DuplexEngineSession, event: dict[str, object], payload: dict[str, object]) -> bool:
|
||||
for key in ("is_speech", "speech"):
|
||||
value = event.get(key)
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
vad = event.get("vad")
|
||||
if isinstance(vad, dict):
|
||||
value = vad.get("is_speech")
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
probability = vad.get("speech_probability", vad.get("probability"))
|
||||
if isinstance(probability, int | float):
|
||||
return float(probability) >= 0.5
|
||||
probability = event.get("speech_probability")
|
||||
if isinstance(probability, int | float):
|
||||
return float(probability) >= 0.5
|
||||
|
||||
fmt = payload.get("format")
|
||||
audio = payload.get("audio")
|
||||
if fmt in {"pcm_f32le", "pcm16"} and isinstance(audio, str):
|
||||
try:
|
||||
raw = base64.b64decode(audio, validate=True)
|
||||
except (binascii.Error, ValueError):
|
||||
return True
|
||||
if fmt == "pcm_f32le":
|
||||
if len(raw) < 4 or len(raw) % 4 != 0:
|
||||
return True
|
||||
samples = np.frombuffer(raw, dtype=np.float32)
|
||||
else:
|
||||
if len(raw) < 2 or len(raw) % 2 != 0:
|
||||
return True
|
||||
samples = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0
|
||||
if samples.size == 0:
|
||||
return False
|
||||
rms = float(np.sqrt(np.mean(np.square(samples.astype(np.float32)))))
|
||||
return rms >= session.config.overlap_silence_rms
|
||||
return True
|
||||
@@ -0,0 +1,137 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Applying one ``playback.ack`` to a duplex session.
|
||||
|
||||
The client reports how much of a response it has actually played; the session
|
||||
uses that to commit or truncate the assistant item in conversation history, and
|
||||
to release the response's playback state once it is fully played.
|
||||
|
||||
Extracted from ``DuplexSessionRunner`` because the only runner state it touched
|
||||
was ``session``. It returns the events it produces rather than emitting them,
|
||||
so the rules can be exercised without a runner.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from vllm_omni.engine.duplex.events import DuplexEvent, PlaybackAcknowledged, error_event
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
from vllm_omni.engine.duplex.session.lease import DuplexLeaseActivity
|
||||
|
||||
|
||||
def apply_playback_ack(session: DuplexEngineSession, event: dict[str, object]) -> list[DuplexEvent]:
|
||||
"""Apply one ``playback.ack`` and return the events it produces."""
|
||||
played_ms = event.get("played_ms", event.get("audio_ms", 0))
|
||||
committed_ms = event.get("committed_ms")
|
||||
if not isinstance(played_ms, int | float):
|
||||
return [error_event("bad_event", "playback.ack requires played_ms")]
|
||||
try:
|
||||
session.touch_lease(DuplexLeaseActivity.PLAYBACK_ACK)
|
||||
except Exception:
|
||||
pass
|
||||
committed_cursor = int(committed_ms) if isinstance(committed_ms, int | float) else int(played_ms)
|
||||
item_id = event.get("item_id")
|
||||
response_id = event.get("response_id")
|
||||
response_id = response_id if isinstance(response_id, str) and response_id else None
|
||||
if not isinstance(item_id, str) or not item_id:
|
||||
item_id = f"item_{response_id}" if response_id is not None else None
|
||||
elif response_id is None and item_id.startswith("item_"):
|
||||
response_id = item_id.removeprefix("item_")
|
||||
if response_id is None and item_id is None and len(session.pending_history_item_ids) == 1:
|
||||
item_id = next(iter(session.pending_history_item_ids))
|
||||
if item_id.startswith("item_"):
|
||||
response_id = item_id.removeprefix("item_")
|
||||
if response_id is None and item_id is None and session.active_response_id is not None:
|
||||
response_id = session.active_response_id
|
||||
item_id = f"item_{response_id}"
|
||||
if response_id is not None:
|
||||
expected_item_id = f"item_{response_id}"
|
||||
if item_id is None:
|
||||
item_id = expected_item_id
|
||||
elif item_id != expected_item_id:
|
||||
return [error_event("playback_item_mismatch", "playback.ack item_id must match item_<response_id>.")]
|
||||
if not session.has_assistant_response_item(response_id, item_id):
|
||||
return [
|
||||
error_event("playback_item_not_found", f"No assistant response item is registered for {response_id}.")
|
||||
]
|
||||
if session.playback_ack_is_too_late(response_id, item_id):
|
||||
return [
|
||||
error_event("playback_ack_too_late", "playback.ack arrived after a later user input was committed.")
|
||||
]
|
||||
session.reserve_history_item(item_id)
|
||||
elif item_id is not None:
|
||||
return [error_event("playback_item_not_found", "playback.ack requires a response-owned assistant item.")]
|
||||
hard_truncate = event.get("truncate") is True
|
||||
if hard_truncate:
|
||||
playback = session.acknowledge_playback(int(played_ms), committed_cursor, response_id=response_id)
|
||||
playback = session.truncate_playback_commit(committed_cursor, response_id=response_id)
|
||||
else:
|
||||
playback = session.acknowledge_playback(int(played_ms), committed_cursor, response_id=response_id)
|
||||
committed_history = False
|
||||
if isinstance(item_id, str) and item_id:
|
||||
expected_item_id = f"item_{response_id}" if response_id is not None else None
|
||||
if (
|
||||
expected_item_id == item_id
|
||||
and item_id not in session.history_item_ids
|
||||
and item_id not in session.pending_history_item_ids
|
||||
):
|
||||
session.register_history_item(item_id, None)
|
||||
committed_history = session.truncate_history_item(
|
||||
item_id,
|
||||
audio_end_ms=committed_cursor,
|
||||
playback=playback,
|
||||
hard=hard_truncate,
|
||||
)
|
||||
elif session.pending_history_item_ids:
|
||||
pending_ids = list(session.pending_history_item_ids)
|
||||
if len(pending_ids) == 1:
|
||||
item_id = pending_ids[0]
|
||||
committed_history = session.truncate_history_item(
|
||||
item_id,
|
||||
audio_end_ms=committed_cursor,
|
||||
playback=playback,
|
||||
hard=hard_truncate,
|
||||
)
|
||||
elif session.active_response_id is not None:
|
||||
item_id = f"item_{session.active_response_id}"
|
||||
committed_history = session.truncate_history_item(
|
||||
item_id,
|
||||
audio_end_ms=committed_cursor,
|
||||
playback=playback,
|
||||
hard=hard_truncate,
|
||||
)
|
||||
elif session.last_assistant_full_message is not None:
|
||||
if item_id is None and session.history_item_ids:
|
||||
assistant_item_ids = [
|
||||
known_item_id
|
||||
for known_item_id, message in session.history_item_ids.items()
|
||||
if message.get("role") == "assistant"
|
||||
]
|
||||
if len(assistant_item_ids) == 1:
|
||||
item_id = assistant_item_ids[0]
|
||||
if isinstance(item_id, str) and item_id:
|
||||
committed_history = session.truncate_history_item(
|
||||
item_id,
|
||||
audio_end_ms=committed_cursor,
|
||||
playback=playback,
|
||||
hard=hard_truncate,
|
||||
)
|
||||
events: list[DuplexEvent] = [
|
||||
PlaybackAcknowledged(
|
||||
details={
|
||||
"type": "playback.acknowledged",
|
||||
"session_id": session.session_id,
|
||||
"epoch": session.epoch,
|
||||
"item_id": item_id,
|
||||
"played_ms": int(played_ms),
|
||||
"committed_ms": committed_cursor,
|
||||
"truncate": event.get("truncate") is True,
|
||||
"playback": playback.as_dict(),
|
||||
"history_committed": committed_history,
|
||||
}
|
||||
)
|
||||
]
|
||||
if committed_history and committed_cursor >= max(playback.sent_ms, playback.generated_ms):
|
||||
session.release_response_playback(response_id)
|
||||
session.release_response_history_snapshot(response_id)
|
||||
return events
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,301 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Server-side turn detection (``turn_detection: server_vad``) for the session runner.
|
||||
|
||||
Moved from the Realtime input translator: the runner owns one
|
||||
``ServerTurnDetector`` per session, feeds each appended chunk to it and emits
|
||||
``input_audio_buffer.speech_started`` / ``speech_stopped`` from the result.
|
||||
The two-phase ``session.update`` commit (prepare / commit / reject) that used
|
||||
to live on the translator is expressed by :class:`PendingTurnDetectionUpdate`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm_omni.engine.duplex.vad import (
|
||||
SILERO_VAD_MIN_THRESHOLD,
|
||||
ServerVADUnavailableError,
|
||||
SileroStreamingVAD,
|
||||
SileroVADBackendProvider,
|
||||
SileroVADConfig,
|
||||
StreamingVADResult,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"PendingTurnDetectionUpdate",
|
||||
"SileroVADBackendProvider",
|
||||
"ServerTurnDetector",
|
||||
"ServerVADUnavailableError",
|
||||
"TurnDetectionConfig",
|
||||
"TurnDetectionResult",
|
||||
"apply_turn_detection_result",
|
||||
"configured_realtime_turn_detection",
|
||||
"normalize_turn_detection_session_payload",
|
||||
"validate_realtime_turn_detection",
|
||||
]
|
||||
|
||||
|
||||
def configured_realtime_turn_detection(session_payload: Mapping[str, object]) -> tuple[str | None, object]:
|
||||
"""Return ``(field_path, value)`` for the turn detection setting present in the payload."""
|
||||
field = "turn_detection" if "turn_detection" in session_payload else None
|
||||
selected = session_payload.get("turn_detection")
|
||||
audio_config = session_payload.get("audio")
|
||||
if isinstance(audio_config, dict):
|
||||
audio_input = audio_config.get("input")
|
||||
if isinstance(audio_input, dict) and "turn_detection" in audio_input:
|
||||
field, selected = "audio.input.turn_detection", audio_input["turn_detection"]
|
||||
return field, selected
|
||||
|
||||
|
||||
def _valid_vad_number(value: object, *, minimum: float, maximum: float | None = None, strict: bool = False) -> bool:
|
||||
return (
|
||||
isinstance(value, int | float)
|
||||
and not isinstance(value, bool)
|
||||
and np.isfinite(float(value))
|
||||
and (float(value) > minimum if strict else float(value) >= minimum)
|
||||
and (maximum is None or float(value) <= maximum)
|
||||
)
|
||||
|
||||
|
||||
#: Every field a ``server_vad`` object may carry. Unknown keys are refused
|
||||
#: rather than ignored: a misspelled tuning knob that silently does nothing is
|
||||
#: worse than a rejected session, because the endpointing still *looks* applied.
|
||||
_SERVER_VAD_FIELDS = frozenset(
|
||||
{
|
||||
"type",
|
||||
"threshold",
|
||||
"prefix_padding_ms",
|
||||
"silence_duration_ms",
|
||||
"create_response",
|
||||
"interrupt_response",
|
||||
"min_speech_duration_ms",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def validate_realtime_turn_detection(session_payload: Mapping[str, object]) -> str | None:
|
||||
"""Validate the ``turn_detection`` object of a Realtime session payload (None when valid)."""
|
||||
field, turn_detection = configured_realtime_turn_detection(session_payload)
|
||||
if field is None:
|
||||
if session_payload.get("overlap_policy") == "barge_in_on_speech":
|
||||
return (
|
||||
"overlap_policy='barge_in_on_speech' requires turn_detection.type='server_vad' on the Realtime endpoint"
|
||||
)
|
||||
return None
|
||||
if turn_detection is not None and not isinstance(turn_detection, dict):
|
||||
return f"{field} must be null or an object with type='server_vad'"
|
||||
if isinstance(turn_detection, dict):
|
||||
if turn_detection.get("type") != "server_vad":
|
||||
return f"{field}.type must be 'server_vad'"
|
||||
unknown = sorted(set(turn_detection) - _SERVER_VAD_FIELDS)
|
||||
if unknown:
|
||||
return f"Unknown {field} field(s): {', '.join(unknown)}"
|
||||
threshold = turn_detection.get("threshold", 0.5)
|
||||
if not _valid_vad_number(threshold, minimum=SILERO_VAD_MIN_THRESHOLD, strict=True, maximum=1):
|
||||
return f"{field}.threshold must be greater than {SILERO_VAD_MIN_THRESHOLD} and at most 1"
|
||||
for name in ("prefix_padding_ms", "silence_duration_ms", "min_speech_duration_ms"):
|
||||
value = turn_detection.get(name)
|
||||
if value is not None and not _valid_vad_number(value, minimum=0):
|
||||
return f"{field}.{name} must be a non-negative number"
|
||||
if turn_detection.get("interrupt_response", True) is not True:
|
||||
return (
|
||||
f"{field}.interrupt_response=false is unsupported; use turn_detection=null for model-owned listen/speak"
|
||||
)
|
||||
desired_policy = "barge_in_on_speech" if turn_detection is not None else "listen_only"
|
||||
overlap_policy = session_payload.get("overlap_policy")
|
||||
if isinstance(overlap_policy, str) and overlap_policy != desired_policy:
|
||||
return f"overlap_policy={overlap_policy!r} conflicts with turn_detection; expected {desired_policy!r}"
|
||||
return None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class TurnDetectionConfig:
|
||||
"""Normalized ``server_vad`` configuration (all fields filled with defaults)."""
|
||||
|
||||
threshold: float = 0.5
|
||||
prefix_padding_ms: int = 300
|
||||
silence_duration_ms: int = 500
|
||||
min_speech_duration_ms: int = 96
|
||||
create_response: bool = True
|
||||
interrupt_response: bool = True
|
||||
|
||||
@classmethod
|
||||
def from_realtime(cls, turn_detection: Mapping[str, object]) -> TurnDetectionConfig:
|
||||
return cls(
|
||||
threshold=float(turn_detection.get("threshold", 0.5)),
|
||||
prefix_padding_ms=int(turn_detection.get("prefix_padding_ms", 300)),
|
||||
silence_duration_ms=int(turn_detection.get("silence_duration_ms", 500)),
|
||||
min_speech_duration_ms=int(turn_detection.get("min_speech_duration_ms", 96)),
|
||||
create_response=bool(turn_detection.get("create_response", True)),
|
||||
interrupt_response=bool(turn_detection.get("interrupt_response", True)),
|
||||
)
|
||||
|
||||
@property
|
||||
def overlap_policy(self) -> str:
|
||||
return "barge_in_on_speech"
|
||||
|
||||
def build_detector(self, backend_provider: SileroVADBackendProvider | None = None) -> ServerTurnDetector:
|
||||
return ServerTurnDetector(self, backend_provider=backend_provider)
|
||||
|
||||
|
||||
def normalize_turn_detection_session_payload(
|
||||
session_payload: dict[str, object],
|
||||
) -> tuple[bool, TurnDetectionConfig | None]:
|
||||
"""Fill ``turn_detection`` defaults and derive ``overlap_policy`` in place.
|
||||
|
||||
Returns ``(configured, config)`` where ``configured`` is False when the
|
||||
payload does not mention turn detection at all (nothing changes), and
|
||||
``config`` is ``None`` for ``turn_detection: null`` (model-owned turns,
|
||||
``overlap_policy`` forced to ``listen_only``).
|
||||
"""
|
||||
field, configured = configured_realtime_turn_detection(session_payload)
|
||||
if field is None:
|
||||
return False, None
|
||||
if configured is None:
|
||||
session_payload["overlap_policy"] = "listen_only"
|
||||
return True, None
|
||||
assert isinstance(configured, dict)
|
||||
merged = {
|
||||
"type": "server_vad",
|
||||
"interrupt_response": True,
|
||||
"threshold": 0.5,
|
||||
"prefix_padding_ms": 300,
|
||||
"silence_duration_ms": 500,
|
||||
"min_speech_duration_ms": 96,
|
||||
**configured,
|
||||
}
|
||||
config = TurnDetectionConfig.from_realtime(merged)
|
||||
session_payload["turn_detection"] = dict(merged)
|
||||
session_payload["overlap_policy"] = config.overlap_policy
|
||||
return True, config
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class TurnDetectionResult:
|
||||
is_speech: bool
|
||||
speech_active: bool
|
||||
speech_started: bool = False
|
||||
speech_stopped: bool = False
|
||||
speech_probability: float = 0.0
|
||||
audio_start_ms: int | None = None
|
||||
audio_end_ms: int | None = None
|
||||
#: A ``speech_stopped`` under ``server_vad`` ends the user turn.
|
||||
should_commit: bool = False
|
||||
#: Whether the auto-commit should also request a response (``create_response``).
|
||||
create_response: bool = True
|
||||
|
||||
def as_payload(self) -> dict[str, object]:
|
||||
return {
|
||||
"backend": "silero",
|
||||
"is_speech": self.is_speech,
|
||||
"speech_active": self.speech_active,
|
||||
"speech_started": self.speech_started,
|
||||
"speech_stopped": self.speech_stopped,
|
||||
"speech_probability": self.speech_probability,
|
||||
}
|
||||
|
||||
|
||||
class ServerTurnDetector:
|
||||
"""One Silero-backed streaming detector per session."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: TurnDetectionConfig,
|
||||
*,
|
||||
backend_provider: SileroVADBackendProvider | None = None,
|
||||
) -> None:
|
||||
self.config = config
|
||||
self._vad = SileroStreamingVAD(
|
||||
SileroVADConfig(
|
||||
threshold=float(config.threshold),
|
||||
prefix_padding_ms=int(config.prefix_padding_ms),
|
||||
silence_duration_ms=int(config.silence_duration_ms),
|
||||
min_speech_duration_ms=max(32, int(config.min_speech_duration_ms)),
|
||||
),
|
||||
backend_provider=backend_provider,
|
||||
)
|
||||
|
||||
@property
|
||||
def vad(self) -> SileroStreamingVAD:
|
||||
return self._vad
|
||||
|
||||
def reset(self) -> None:
|
||||
self._vad.reset()
|
||||
|
||||
def process(
|
||||
self,
|
||||
base64_audio: str,
|
||||
*,
|
||||
fmt: str,
|
||||
sample_rate_hz: int | None,
|
||||
audio_end_ms: int | None = None,
|
||||
) -> TurnDetectionResult:
|
||||
"""Score one appended chunk. Raises ``ServerVADUnavailableError`` / ``ValueError`` like the VAD."""
|
||||
result: StreamingVADResult = self._vad.process_base64(base64_audio, fmt=fmt, sample_rate_hz=sample_rate_hz)
|
||||
stop_ms = result.speech_end_ms if result.speech_end_ms is not None else audio_end_ms
|
||||
return TurnDetectionResult(
|
||||
is_speech=result.is_speech,
|
||||
speech_active=result.speech_active,
|
||||
speech_started=result.speech_started,
|
||||
speech_stopped=result.speech_stopped,
|
||||
speech_probability=result.speech_probability,
|
||||
audio_start_ms=result.speech_start_ms,
|
||||
audio_end_ms=stop_ms,
|
||||
should_commit=bool(result.speech_stopped and not result.speech_active),
|
||||
create_response=self.config.create_response,
|
||||
)
|
||||
|
||||
|
||||
def apply_turn_detection_result(payload: dict[str, object], result: TurnDetectionResult) -> None:
|
||||
"""Merge a detector result onto an internal ``input_audio_buffer.append`` payload.
|
||||
|
||||
Mirrors what the old translator attached: ``is_speech`` from the detector,
|
||||
the ``vad`` hint block, and ``force_listen`` while speech is active.
|
||||
"""
|
||||
payload["is_speech"] = result.is_speech
|
||||
payload["vad"] = result.as_payload()
|
||||
if result.speech_active:
|
||||
payload["force_listen"] = True
|
||||
if result.audio_start_ms is not None and result.speech_started:
|
||||
payload["audio_start_ms"] = result.audio_start_ms
|
||||
if result.audio_end_ms is not None and result.speech_stopped:
|
||||
payload["audio_end_ms"] = result.audio_end_ms
|
||||
|
||||
|
||||
@dataclass
|
||||
class PendingTurnDetectionUpdate:
|
||||
"""A ``session.update`` turn-detection change awaiting the engine ACK (two-phase)."""
|
||||
|
||||
config: TurnDetectionConfig | None
|
||||
detector: ServerTurnDetector | None
|
||||
|
||||
@classmethod
|
||||
def prepare(
|
||||
cls,
|
||||
session_payload: dict[str, object],
|
||||
*,
|
||||
backend_provider: SileroVADBackendProvider | None = None,
|
||||
) -> PendingTurnDetectionUpdate | None:
|
||||
"""Normalize the payload in place and stage the new detector; None when not configured."""
|
||||
configured, config = normalize_turn_detection_session_payload(session_payload)
|
||||
if not configured:
|
||||
return None
|
||||
detector = config.build_detector(backend_provider) if config is not None else None
|
||||
return cls(config=config, detector=detector)
|
||||
|
||||
def commit(
|
||||
self, current: ServerTurnDetector | None
|
||||
) -> tuple[TurnDetectionConfig | None, ServerTurnDetector | None]:
|
||||
"""Adopt the staged detector; the replaced one is reset. Returns the new (config, detector)."""
|
||||
if current is not None:
|
||||
current.reset()
|
||||
return self.config, self.detector
|
||||
|
||||
def reject(self) -> None:
|
||||
if self.detector is not None:
|
||||
self.detector.reset()
|
||||
@@ -0,0 +1,488 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Silero server VAD for the engine-resident duplex session.
|
||||
|
||||
The detector keeps the split upstream's serving-side ``server_vad`` module
|
||||
used, because the split is what makes one model serve many sessions: a
|
||||
**backend** scores one 512-sample frame and is otherwise stateless, and the
|
||||
per-stream state -- the partial frame, the model state, the endpoint counters --
|
||||
belongs to :class:`SileroStreamingVAD`, one per session.
|
||||
|
||||
Two backends. :class:`SileroVADBackend` runs the pinned Silero v6.2 ONNX graph on
|
||||
CPU and is shared process-wide, which is why its state is passed in and out
|
||||
rather than held on the session object. :class:`TorchSileroBackend` loads the
|
||||
same model through the ``silero-vad`` package for environments that have no
|
||||
local ONNX artifact; torch keeps its state inside the module, so that one is per
|
||||
session.
|
||||
|
||||
Endpointing follows Silero v6.2's streaming hysteresis: activation uses the
|
||||
configured threshold, while a turn can only *end* on frames below
|
||||
``max(threshold - 0.15, 0.01)``. Once a silence candidate exists, louder frames
|
||||
keep the elapsed-silence clock running but cannot themselves close the turn.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import binascii
|
||||
import hashlib
|
||||
import threading
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
|
||||
import numpy as np
|
||||
import pybase64 as base64
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
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
|
||||
|
||||
_SAMPLE_RATE_HZ = 16_000
|
||||
_FRAME_SAMPLES = 512
|
||||
|
||||
|
||||
class ServerVADUnavailableError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SileroVADConfig:
|
||||
threshold: float = 0.5
|
||||
prefix_padding_ms: int = 300
|
||||
silence_duration_ms: int = 500
|
||||
min_speech_duration_ms: int = 96
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class StreamingVADResult:
|
||||
is_speech: bool
|
||||
speech_active: bool
|
||||
speech_started: bool = False
|
||||
speech_stopped: bool = False
|
||||
speech_probability: float = 0.0
|
||||
speech_start_ms: int | None = None
|
||||
speech_end_ms: int | None = None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Backends #
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
class SpeechDetectorBackend(Protocol):
|
||||
"""Scores one frame. Per-stream state is created here but owned by the caller."""
|
||||
|
||||
frame_samples: int
|
||||
|
||||
def new_state(self) -> object: ...
|
||||
|
||||
def infer(self, frame: np.ndarray, state: object) -> tuple[float, object]: ...
|
||||
|
||||
|
||||
@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 = _SAMPLE_RATE_HZ
|
||||
frame_samples = _FRAME_SAMPLES
|
||||
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 ServerVADUnavailableError("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 not {"input", "sr", "state"} <= input_names:
|
||||
raise ServerVADUnavailableError(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)
|
||||
# ONNX Runtime permits concurrent Run calls on one CPU session. Stream
|
||||
# state is explicit, so independent sessions can safely share this one.
|
||||
output = self._session.run(
|
||||
None,
|
||||
{
|
||||
"input": model_input,
|
||||
"state": model_state,
|
||||
"sr": np.asarray(self.sample_rate_hz, dtype=np.int64),
|
||||
},
|
||||
)
|
||||
if len(output) < 2:
|
||||
raise ServerVADUnavailableError("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 TorchSileroBackend:
|
||||
"""The same model through the ``silero-vad`` package, for hosts with no ONNX artifact.
|
||||
|
||||
Torch keeps the recurrent state inside the module, so unlike the ONNX
|
||||
backend this one cannot be shared: each session gets its own instance and
|
||||
``new_state`` only resets it.
|
||||
"""
|
||||
|
||||
sample_rate_hz = _SAMPLE_RATE_HZ
|
||||
frame_samples = _FRAME_SAMPLES
|
||||
|
||||
def __init__(self) -> None:
|
||||
try:
|
||||
import torch
|
||||
from silero_vad import load_silero_vad
|
||||
except ImportError as exc:
|
||||
raise ServerVADUnavailableError(
|
||||
"server_vad needs either a local Silero ONNX artifact (see "
|
||||
"duplex_session.server_vad_model_path) or the optional 'silero-vad' "
|
||||
"package; install vllm-omni[server-vad]"
|
||||
) from exc
|
||||
self._torch = torch
|
||||
self._model = load_silero_vad(onnx=False)
|
||||
|
||||
def new_state(self) -> object:
|
||||
reset_states = getattr(self._model, "reset_states", None)
|
||||
if callable(reset_states):
|
||||
reset_states()
|
||||
return None
|
||||
|
||||
def infer(self, frame: np.ndarray, state: object) -> tuple[float, object]:
|
||||
tensor = self._torch.from_numpy(np.ascontiguousarray(frame, dtype=np.float32))
|
||||
return float(self._model(tensor, self.sample_rate_hz).item()), state
|
||||
|
||||
|
||||
class SileroVADBackendProvider:
|
||||
"""Resolve, verify and load one detector backend per engine process.
|
||||
|
||||
ONNX is preferred and shared; the torch package is the fallback and is built
|
||||
per call because its state is internal.
|
||||
"""
|
||||
|
||||
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) -> SpeechDetectorBackend:
|
||||
"""The shared ONNX backend, or a per-session torch one when it cannot be built.
|
||||
|
||||
An explicitly configured ``server_vad_model_path`` never falls back: the
|
||||
operator named that artifact, so a missing file or a missing ONNX Runtime
|
||||
is their error, not something to paper over with a different model.
|
||||
"""
|
||||
if self._backend is not None:
|
||||
return self._backend
|
||||
with self._lock:
|
||||
if self._backend is not None:
|
||||
return self._backend
|
||||
path = self._resolve_local_artifact()
|
||||
if path is None:
|
||||
# No pinned artifact: the torch package keeps state internally,
|
||||
# so this instance belongs to one session only.
|
||||
return TorchSileroBackend()
|
||||
self._verify_checksum(path)
|
||||
try:
|
||||
self._backend = SileroVADBackend(path)
|
||||
except ServerVADUnavailableError:
|
||||
if self.model_path:
|
||||
raise
|
||||
logger.warning(
|
||||
"Silero ONNX artifact %s found but ONNX Runtime is unavailable; "
|
||||
"falling back to the torch 'silero-vad' package (one model per session)",
|
||||
path,
|
||||
)
|
||||
return TorchSileroBackend()
|
||||
return self._backend
|
||||
|
||||
def _resolve_local_artifact(self) -> Path | None:
|
||||
if self.model_path:
|
||||
path = Path(self.model_path).expanduser()
|
||||
if path.is_file():
|
||||
return path
|
||||
# Explicitly configured: a missing file is an error, not a fallback.
|
||||
raise ServerVADUnavailableError(f"Configured Silero VAD model does not exist: {path}")
|
||||
try:
|
||||
from vllm.transformers_utils.repo_utils import try_get_local_file
|
||||
|
||||
cached = try_get_local_file(
|
||||
model=SILERO_VAD_REPO_ID,
|
||||
file_name=SILERO_VAD_FILENAME,
|
||||
revision=SILERO_VAD_REVISION,
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
return cached if isinstance(cached, Path) and cached.is_file() else None
|
||||
|
||||
def _verify_checksum(self, path: Path) -> None:
|
||||
digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
if digest != SILERO_VAD_SHA256:
|
||||
raise ServerVADUnavailableError(
|
||||
f"Silero VAD checksum mismatch for {path}: expected {SILERO_VAD_SHA256}, got {digest}"
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Per-session streaming detector #
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
class SileroStreamingVAD:
|
||||
_SAMPLE_RATE_HZ = _SAMPLE_RATE_HZ
|
||||
_WINDOW_SAMPLES = _FRAME_SAMPLES
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: SileroVADConfig,
|
||||
*,
|
||||
backend: SpeechDetectorBackend | None = None,
|
||||
backend_provider: SileroVADBackendProvider | None = None,
|
||||
frame_scorer: Callable[[np.ndarray], float] | None = None,
|
||||
) -> None:
|
||||
self.config = config
|
||||
self._explicit_backend = backend
|
||||
self._provider = backend_provider
|
||||
self._frame_scorer = frame_scorer
|
||||
self._backend: SpeechDetectorBackend | None = backend
|
||||
self._detector_state: object = None
|
||||
self._clear_stream_state()
|
||||
|
||||
def _clear_stream_state(self) -> None:
|
||||
self._pending = np.empty(0, dtype=np.float32)
|
||||
self._speech_active = False
|
||||
self._candidate_samples = 0
|
||||
self._candidate_start_sample: int | None = None
|
||||
self._silence_samples = 0
|
||||
self._processed_samples = 0
|
||||
self._stream_start_ms = 0
|
||||
self._resample_rate_hz: int | None = None
|
||||
self._resample_remainder = 0
|
||||
|
||||
@property
|
||||
def scratch_bytes(self) -> int:
|
||||
"""Bytes this detector holds between chunks (the partial frame only)."""
|
||||
return int(self._pending.nbytes)
|
||||
|
||||
@property
|
||||
def speech_active(self) -> bool:
|
||||
return self._speech_active
|
||||
|
||||
def reset(self) -> None:
|
||||
"""Drop stream state while preserving the session-relative audio clock.
|
||||
|
||||
The clock survives so ``speech_start_ms`` after a barge-in still refers
|
||||
to the session's timeline; ``_stream_start_ms`` then stops the prefix
|
||||
padding reaching back into audio that was discarded.
|
||||
"""
|
||||
stream_start_ms = round(self._processed_samples * 1000 / self._SAMPLE_RATE_HZ)
|
||||
processed = self._processed_samples
|
||||
self._clear_stream_state()
|
||||
self._processed_samples = processed
|
||||
self._stream_start_ms = stream_start_ms
|
||||
if self._backend is not None:
|
||||
self._detector_state = self._backend.new_state()
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Input #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def process_base64(
|
||||
self,
|
||||
audio: object,
|
||||
*,
|
||||
fmt: object,
|
||||
sample_rate_hz: object,
|
||||
) -> StreamingVADResult:
|
||||
if not isinstance(audio, str):
|
||||
raise ValueError("Silero server VAD requires base64 audio")
|
||||
try:
|
||||
raw = base64.b64decode(audio, validate=True)
|
||||
except (binascii.Error, ValueError) as exc:
|
||||
raise ValueError("Silero server VAD received invalid base64 audio") from exc
|
||||
rate = int(sample_rate_hz) if isinstance(sample_rate_hz, int | float) else self._SAMPLE_RATE_HZ
|
||||
if rate <= 0:
|
||||
raise ValueError("Silero server VAD requires a positive sample rate")
|
||||
|
||||
if fmt == "pcm_f32le":
|
||||
if len(raw) % 4:
|
||||
raise ValueError("Silero server VAD received an incomplete pcm_f32le frame")
|
||||
samples = np.frombuffer(raw, dtype="<f4").astype(np.float32, copy=False)
|
||||
elif fmt == "pcm16":
|
||||
if len(raw) % 2:
|
||||
raise ValueError("Silero server VAD received an incomplete pcm16 sample")
|
||||
samples = np.frombuffer(raw, dtype="<i2").astype(np.float32) * np.float32(1.0 / 32768.0)
|
||||
else:
|
||||
raise ValueError("Silero server VAD requires pcm_f32le or pcm16 audio")
|
||||
|
||||
return self.process(self._to_16k(samples, rate))
|
||||
|
||||
def _to_16k(self, samples: np.ndarray, rate: int) -> np.ndarray:
|
||||
"""Resample to 16 kHz, carrying the fractional sample-count remainder.
|
||||
|
||||
A fallback path: the session runner already normalises input to 16 kHz
|
||||
through ``convert_input_audio_with_rate`` before the detector sees it,
|
||||
so this runs only for callers that feed the VAD directly.
|
||||
|
||||
Carrying the remainder keeps the *number* of output samples exact, so
|
||||
frame boundaries cannot drift over a long stream. The interpolation
|
||||
itself is per chunk and has no filter state, so sample values near a
|
||||
chunk edge differ slightly from resampling the same audio in one go --
|
||||
enough for the frame grid to stay put, not enough to call it a
|
||||
streaming resampler.
|
||||
"""
|
||||
if rate == self._SAMPLE_RATE_HZ:
|
||||
self._resample_rate_hz = None
|
||||
self._resample_remainder = 0
|
||||
return samples
|
||||
if self._resample_rate_hz is not None and rate != self._resample_rate_hz:
|
||||
raise ValueError("server_vad input sample rate cannot change within a continuous audio stream")
|
||||
self._resample_rate_hz = rate
|
||||
numerator = samples.size * self._SAMPLE_RATE_HZ + self._resample_remainder
|
||||
target_size, self._resample_remainder = divmod(numerator, rate)
|
||||
if target_size == 0:
|
||||
return np.empty(0, dtype=np.float32)
|
||||
if samples.size == 1:
|
||||
return np.full(target_size, samples[0], dtype=np.float32)
|
||||
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)
|
||||
return np.interp(target_x, source_x, samples).astype(np.float32)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Endpointing #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def process(self, samples: np.ndarray) -> StreamingVADResult:
|
||||
samples = np.asarray(samples, dtype=np.float32).reshape(-1)
|
||||
if samples.size:
|
||||
self._pending = np.concatenate((self._pending, samples))
|
||||
|
||||
started = False
|
||||
stopped = False
|
||||
start_ms: int | None = None
|
||||
end_ms: int | None = None
|
||||
max_probability = 0.0
|
||||
contained_speech = self._speech_active
|
||||
min_speech_samples = max(1, round(self.config.min_speech_duration_ms * self._SAMPLE_RATE_HZ / 1000))
|
||||
min_silence_samples = max(1, round(self.config.silence_duration_ms * self._SAMPLE_RATE_HZ / 1000))
|
||||
negative_threshold = max(self.config.threshold - SILERO_VAD_MIN_THRESHOLD, 0.01)
|
||||
|
||||
pending = self._pending
|
||||
offset = 0
|
||||
while pending.size - offset >= self._WINDOW_SAMPLES:
|
||||
frame = np.ascontiguousarray(pending[offset : offset + self._WINDOW_SAMPLES], dtype=np.float32)
|
||||
offset += self._WINDOW_SAMPLES
|
||||
frame_start = self._processed_samples
|
||||
self._processed_samples += self._WINDOW_SAMPLES
|
||||
probability = min(1.0, max(0.0, self._score_frame(frame)))
|
||||
max_probability = max(max_probability, probability)
|
||||
|
||||
if self._speech_active:
|
||||
contained_speech = True
|
||||
below_negative_threshold = probability < negative_threshold
|
||||
if not below_negative_threshold and self._silence_samples == 0:
|
||||
continue
|
||||
# A silence candidate is running: louder frames keep its clock
|
||||
# moving but cannot themselves close the turn.
|
||||
self._silence_samples += self._WINDOW_SAMPLES
|
||||
if not below_negative_threshold or self._silence_samples < min_silence_samples:
|
||||
continue
|
||||
self._speech_active = False
|
||||
self._silence_samples = 0
|
||||
stopped = True
|
||||
# OpenAI defines audio_end_ms as the end of the audio sent to
|
||||
# the model, trailing silence included.
|
||||
end_ms = max(0, round(self._processed_samples * 1000 / self._SAMPLE_RATE_HZ))
|
||||
continue
|
||||
|
||||
if probability >= self.config.threshold:
|
||||
if self._candidate_samples == 0:
|
||||
self._candidate_start_sample = frame_start
|
||||
self._candidate_samples += self._WINDOW_SAMPLES
|
||||
if self._candidate_samples >= min_speech_samples:
|
||||
candidate_start = self._candidate_start_sample or 0
|
||||
detected_start_ms = round(candidate_start * 1000 / self._SAMPLE_RATE_HZ)
|
||||
self._speech_active = True
|
||||
self._candidate_samples = self._silence_samples = 0
|
||||
self._candidate_start_sample = None
|
||||
contained_speech = True
|
||||
started = True
|
||||
# Prefix audio from before the last reset is gone.
|
||||
start_ms = max(
|
||||
self._stream_start_ms,
|
||||
max(0, detected_start_ms - self.config.prefix_padding_ms),
|
||||
)
|
||||
else:
|
||||
self._candidate_samples = 0
|
||||
self._candidate_start_sample = None
|
||||
|
||||
# Copy the residual once, after the frames are scored, so a large input
|
||||
# chunk is neither pinned by a view nor re-copied for every frame.
|
||||
self._pending = pending[offset:].copy()
|
||||
|
||||
return StreamingVADResult(
|
||||
contained_speech, self._speech_active, started, stopped, max_probability, start_ms, end_ms
|
||||
)
|
||||
|
||||
def _score_frame(self, frame: np.ndarray) -> float:
|
||||
if self._frame_scorer is not None:
|
||||
return float(self._frame_scorer(frame))
|
||||
backend = self._require_backend()
|
||||
probability, self._detector_state = backend.infer(frame, self._detector_state)
|
||||
return float(probability)
|
||||
|
||||
def _require_backend(self) -> SpeechDetectorBackend:
|
||||
if self._backend is None:
|
||||
provider = self._provider or SileroVADBackendProvider()
|
||||
self._backend = provider.get()
|
||||
self._detector_state = self._backend.new_state()
|
||||
return self._backend
|
||||
@@ -0,0 +1,299 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""DuplexOmniEngine: the duplex engine sibling of ``AsyncOmniEngine``.
|
||||
|
||||
It is deliberately small. The engine base owns the stage processes, the
|
||||
orchestrator thread and the correlated RPC transport; this class only knows
|
||||
how duplex session messages enter the engine (open/close/resume/touch through
|
||||
correlated RPC, session commands one-way) and which orchestrator to build
|
||||
(``DuplexOrchestrator`` with the model plugin loaded).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import queue
|
||||
import uuid
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.config.stage_config import DuplexSessionRuntimeConfig
|
||||
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.messages import (
|
||||
CloseDuplexSessionMessage,
|
||||
DuplexControlResultMessage,
|
||||
DuplexSessionCommandMessage,
|
||||
DuplexSessionError,
|
||||
OpenDuplexSessionMessage,
|
||||
ResumeDuplexSessionMessage,
|
||||
TouchDuplexSessionMessage,
|
||||
)
|
||||
from vllm_omni.engine.duplex.plugin import DuplexModelPlugin, EncodeAudio, load_duplex_plugin
|
||||
from vllm_omni.engine.messages import EngineQueueMessage
|
||||
from vllm_omni.engine.orchestrator import OrchestratorBase
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.engine.duplex.commands import DuplexCommand
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_DEFAULT_CONTROL_TIMEOUT_S = 10.0
|
||||
_COMMAND_PUT_TIMEOUT_S = 30.0
|
||||
|
||||
|
||||
class DuplexOmniEngine(AsyncOmniEngine):
|
||||
"""Engine for full-duplex models; sessions run inside ``DuplexOrchestrator``."""
|
||||
|
||||
plugin: DuplexModelPlugin | None = None
|
||||
#: Set by ``_validate_deployment`` from the deploy config before any stage starts.
|
||||
duplex_session_config: DuplexSessionRuntimeConfig
|
||||
|
||||
# Any: **kwargs is forwarded verbatim to ``OmniEngineBase.__init__``.
|
||||
def __init__(self, model: str, *, duplex_audio_encoder: EncodeAudio, **kwargs: Any) -> None:
|
||||
# Injected by ``DuplexOmni`` (entrypoint layer): the engine package
|
||||
# knows how to hand model audio to the plugin, not how to encode it.
|
||||
self._audio_encoder = duplex_audio_encoder
|
||||
super().__init__(model, **kwargs)
|
||||
|
||||
# ---- orchestrator construction (orchestrator thread) ----
|
||||
|
||||
def _validate_deployment(self) -> None:
|
||||
"""Load the plugin and check the scheduler contract before any stage process starts."""
|
||||
pipeline_config = self.pipeline_config
|
||||
plugin_path = getattr(pipeline_config, "duplex_plugin", None) if pipeline_config is not None else None
|
||||
if pipeline_config is None:
|
||||
raise ValueError(
|
||||
f"{self.model!r}: the model pipeline could not be resolved (models with custom HF code "
|
||||
"such as MiniCPM-o need trust_remote_code=True)"
|
||||
)
|
||||
if not plugin_path:
|
||||
raise ValueError(f"{self.model!r} is not a duplex model: the pipeline declares no duplex_plugin")
|
||||
deploy_config = self.deploy_config
|
||||
if deploy_config is None:
|
||||
raise ValueError("DuplexOmniEngine requires a deploy config with session_mode: duplex (none resolved)")
|
||||
if getattr(deploy_config, "session_mode", "turn") != "duplex":
|
||||
raise ValueError(
|
||||
"DuplexOmniEngine requires a deploy config with session_mode: duplex "
|
||||
f"(got {getattr(deploy_config, 'session_mode', None)!r})"
|
||||
)
|
||||
self.duplex_session_config = deploy_config.duplex_session
|
||||
self.plugin = load_duplex_plugin(plugin_path, self._audio_encoder)
|
||||
|
||||
# Any: signature of the ``OmniEngineBase._create_orchestrator`` seam it overrides.
|
||||
def _create_orchestrator(self, **orchestrator_kwargs: Any) -> OrchestratorBase:
|
||||
from vllm_omni.engine.duplex_orchestrator import DuplexOrchestrator
|
||||
|
||||
assert self.plugin is not None, "_validate_deployment() must run before the orchestrator is created"
|
||||
stage0_vllm_config = self.stage_pools[0].stage_vllm_config if self.stage_pools else None
|
||||
model_config = getattr(stage0_vllm_config, "model_config", None)
|
||||
return DuplexOrchestrator(
|
||||
plugin=self.plugin,
|
||||
duplex_session_config=self.duplex_session_config,
|
||||
model_config=model_config,
|
||||
**orchestrator_kwargs,
|
||||
)
|
||||
|
||||
# ---- deployment facts ----
|
||||
|
||||
@property
|
||||
def duplex_capabilities(self) -> DuplexCapabilities:
|
||||
if self.plugin is None:
|
||||
raise RuntimeError("duplex plugin is not loaded")
|
||||
return self.plugin.capabilities(max_sessions=self.duplex_session_config.max_sessions)
|
||||
|
||||
# ---- session message surface ----
|
||||
|
||||
def _execute_control(
|
||||
self,
|
||||
message: EngineQueueMessage,
|
||||
*,
|
||||
control_id: str,
|
||||
operation: str,
|
||||
session_id: str,
|
||||
timeout: float | None,
|
||||
) -> DuplexControlResultMessage:
|
||||
try:
|
||||
result = self.rpc_client.execute(
|
||||
("duplex", control_id),
|
||||
message,
|
||||
timeout=timeout,
|
||||
timeout_message=f"duplex {operation} timed out for session {session_id}",
|
||||
# Block rather than surface a raw queue.Full: the handlers below
|
||||
# promise a typed DuplexSessionError, and a momentarily full
|
||||
# request queue is backpressure, not a failed control op.
|
||||
block_on_submit=True,
|
||||
)
|
||||
except TimeoutError as exc:
|
||||
raise DuplexSessionError(str(exc), code="timeout", retryable=True, session_id=session_id) from exc
|
||||
except RuntimeError as exc:
|
||||
# The RPC router is closed or the orchestrator reported a terminal error.
|
||||
raise DuplexSessionError(str(exc), code="engine_error", session_id=session_id) from exc
|
||||
if not isinstance(result, DuplexControlResultMessage):
|
||||
raise DuplexSessionError(
|
||||
f"unexpected duplex control result: {type(result).__name__}",
|
||||
code="internal_error",
|
||||
session_id=session_id,
|
||||
)
|
||||
if not result.ok:
|
||||
raise DuplexSessionError(
|
||||
result.error_message or f"duplex {operation} failed",
|
||||
code=result.error_code or "internal_error",
|
||||
retryable=result.error_retryable,
|
||||
session_id=session_id,
|
||||
)
|
||||
return result
|
||||
|
||||
def _open_session(
|
||||
self,
|
||||
session_id: str,
|
||||
session_config: DuplexSessionConfig,
|
||||
*,
|
||||
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
|
||||
) -> DuplexControlResultMessage:
|
||||
control_id = uuid.uuid4().hex
|
||||
return self._execute_control(
|
||||
OpenDuplexSessionMessage(
|
||||
control_id=control_id,
|
||||
session_id=session_id,
|
||||
session_config=session_config,
|
||||
),
|
||||
control_id=control_id,
|
||||
operation="open",
|
||||
session_id=session_id,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
async def open_session_async(
|
||||
self,
|
||||
session_id: str,
|
||||
session_config: DuplexSessionConfig,
|
||||
*,
|
||||
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
|
||||
) -> DuplexControlResultMessage:
|
||||
loop = asyncio.get_running_loop()
|
||||
return await loop.run_in_executor(None, lambda: self._open_session(session_id, session_config, timeout=timeout))
|
||||
|
||||
def _close_session(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
reason: str = "client_close",
|
||||
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
|
||||
) -> DuplexControlResultMessage:
|
||||
control_id = uuid.uuid4().hex
|
||||
return self._execute_control(
|
||||
CloseDuplexSessionMessage(
|
||||
control_id=control_id,
|
||||
session_id=session_id,
|
||||
reason=reason,
|
||||
),
|
||||
control_id=control_id,
|
||||
operation="close",
|
||||
session_id=session_id,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
async def close_session_async(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
reason: str = "client_close",
|
||||
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
|
||||
) -> DuplexControlResultMessage:
|
||||
loop = asyncio.get_running_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
lambda: self._close_session(session_id, reason=reason, timeout=timeout),
|
||||
)
|
||||
|
||||
def _resume_session(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
expected_lease_generation: int,
|
||||
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
|
||||
) -> DuplexControlResultMessage:
|
||||
control_id = uuid.uuid4().hex
|
||||
return self._execute_control(
|
||||
ResumeDuplexSessionMessage(
|
||||
control_id=control_id,
|
||||
session_id=session_id,
|
||||
expected_lease_generation=expected_lease_generation,
|
||||
),
|
||||
control_id=control_id,
|
||||
operation="resume",
|
||||
session_id=session_id,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
async def resume_session_async(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
expected_lease_generation: int,
|
||||
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
|
||||
) -> DuplexControlResultMessage:
|
||||
loop = asyncio.get_running_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
lambda: self._resume_session(
|
||||
session_id,
|
||||
expected_lease_generation=expected_lease_generation,
|
||||
timeout=timeout,
|
||||
),
|
||||
)
|
||||
|
||||
def _touch_session(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
activity: str,
|
||||
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
|
||||
) -> DuplexControlResultMessage:
|
||||
control_id = uuid.uuid4().hex
|
||||
return self._execute_control(
|
||||
TouchDuplexSessionMessage(
|
||||
control_id=control_id,
|
||||
session_id=session_id,
|
||||
activity=activity,
|
||||
),
|
||||
control_id=control_id,
|
||||
operation="touch",
|
||||
session_id=session_id,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
async def touch_session_async(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
activity: str,
|
||||
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
|
||||
) -> DuplexControlResultMessage:
|
||||
loop = asyncio.get_running_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
lambda: self._touch_session(session_id, activity=activity, timeout=timeout),
|
||||
)
|
||||
|
||||
def _submit_command(self, session_id: str, command: DuplexCommand) -> None:
|
||||
"""One-way: enqueue a session command in caller order (blocks only on queue backpressure)."""
|
||||
if not self.is_alive():
|
||||
raise DuplexSessionError("engine is not alive", code="engine_dead", session_id=session_id)
|
||||
message = DuplexSessionCommandMessage(session_id=session_id, command=command)
|
||||
try:
|
||||
self.request_queue.sync_q.put(message, timeout=_COMMAND_PUT_TIMEOUT_S)
|
||||
except queue.Full as exc:
|
||||
raise DuplexSessionError(
|
||||
"engine request queue is full", code="engine_backpressure", retryable=True, session_id=session_id
|
||||
) from exc
|
||||
|
||||
async def submit_command_async(self, session_id: str, command: DuplexCommand) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
await loop.run_in_executor(None, lambda: self._submit_command(session_id, command))
|
||||
|
||||
|
||||
__all__ = ["DuplexOmniEngine"]
|
||||
@@ -0,0 +1,352 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""DuplexOrchestrator: the duplex sibling of ``Orchestrator``.
|
||||
|
||||
It hosts the ``DuplexSessionManager`` (admission, leases, session runners) on
|
||||
the orchestrator loop and implements the ``DuplexStagePort`` the runners use
|
||||
to submit resumable Stage0 requests. Generic stage forwarding, prewarm and
|
||||
cleanup stay in ``OrchestratorBase``; this class only fills the template seams
|
||||
and applies the session-owned policy.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time as _time
|
||||
from collections.abc import Coroutine
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.config.stage_config import DuplexSessionRuntimeConfig
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexFence,
|
||||
DuplexOutputContext,
|
||||
DuplexRequestIdentity,
|
||||
DuplexStagePort,
|
||||
DuplexStageRequestContext,
|
||||
DuplexStageSubmission,
|
||||
DuplexStageSubmissionResult,
|
||||
)
|
||||
from vllm_omni.engine.duplex.plugin import DuplexModelPlugin
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexFenceMismatchError
|
||||
from vllm_omni.engine.duplex.session.manager import DuplexSessionManager
|
||||
from vllm_omni.engine.messages import EngineQueueMessage, OutputMessage
|
||||
from vllm_omni.engine.orchestrator import (
|
||||
Orchestrator,
|
||||
OrchestratorRequestState,
|
||||
build_engine_core_request_from_tokens,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import ModelConfig
|
||||
from vllm.outputs import RequestOutput
|
||||
|
||||
from vllm_omni.metrics.stats import StageRequestStats
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplexOrchestratorRequestState(OrchestratorRequestState):
|
||||
"""Request bookkeeping for a session-owned (resumable duplex) stage request."""
|
||||
|
||||
session_id: str = ""
|
||||
fence: DuplexFence | None = None
|
||||
stage_fences: dict[int, DuplexFence] = field(default_factory=dict)
|
||||
config_generation: int = -1
|
||||
|
||||
|
||||
class DuplexOrchestrator(Orchestrator, DuplexStagePort):
|
||||
"""Stage management for a duplex deployment; owns one ``DuplexSessionManager``.
|
||||
|
||||
Extends the turn-based orchestrator rather than sitting beside it, so one
|
||||
engine serves both a duplex session and an ordinary request. The
|
||||
dependency runs duplex -> turn-based and never the reverse, which is what
|
||||
keeps ``Orchestrator`` free of duplex code.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
# Any: ``*args`` / ``**kwargs`` are forwarded verbatim to ``OrchestratorBase.__init__``.
|
||||
*args: Any,
|
||||
plugin: DuplexModelPlugin,
|
||||
duplex_session_config: DuplexSessionRuntimeConfig,
|
||||
model_config: ModelConfig | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self.plugin = plugin
|
||||
self.duplex_session_config = duplex_session_config
|
||||
self.session_manager = DuplexSessionManager(
|
||||
plugin=plugin,
|
||||
stage_port=self,
|
||||
output_sink=self.output_async_queue,
|
||||
result_sink=self.rpc_async_queue,
|
||||
runtime_config=self.duplex_session_config,
|
||||
model_config=model_config,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Template seams #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
async def _dispatch_message(self, msg: EngineQueueMessage) -> bool:
|
||||
if self.session_manager.accepts(msg):
|
||||
self.session_manager.dispatch(msg)
|
||||
return True
|
||||
# Not a session message: it is an ordinary turn-based request.
|
||||
return await super()._dispatch_message(msg)
|
||||
|
||||
# Any: ``Coroutine``'s send/yield parameters, as in the ``OrchestratorBase`` seam.
|
||||
def _background_tasks(self) -> list[Coroutine[Any, Any, None]]:
|
||||
return [self.session_manager.reaper_loop(self._shutdown_event)]
|
||||
|
||||
async def _shutdown_extensions(self) -> None:
|
||||
await self.session_manager.shutdown()
|
||||
|
||||
def _on_stage_submitted(
|
||||
self,
|
||||
stage_id: int,
|
||||
request_id: str,
|
||||
replica_id: int,
|
||||
req_state: OrchestratorRequestState,
|
||||
) -> None:
|
||||
del replica_id
|
||||
if not isinstance(req_state, DuplexOrchestratorRequestState) or req_state.fence is None:
|
||||
return
|
||||
runner = self.session_manager.runner_for_request_id(request_id)
|
||||
if runner is None:
|
||||
return
|
||||
fence = req_state.fence
|
||||
req_state.stage_fences[stage_id] = fence
|
||||
try:
|
||||
runner.session.bind_stage_request(stage_id, request_id, fence=fence)
|
||||
except DuplexFenceMismatchError:
|
||||
# The session already advanced past this request's epoch (cancel
|
||||
# raced the submit); the cancel path aborts the stale request id.
|
||||
logger.debug("[DuplexOrchestrator] stale stage binding ignored for %s stage-%s", request_id, stage_id)
|
||||
return
|
||||
req_state.stage_submit_ts[stage_id] = _time.time()
|
||||
self._register_running_request(req_state)
|
||||
self.session_manager.register_request(request_id, req_state.session_id)
|
||||
|
||||
async def _intercept_stage_output(
|
||||
self,
|
||||
stage_id: int,
|
||||
replica_id: int,
|
||||
output: RequestOutput,
|
||||
req_state: OrchestratorRequestState,
|
||||
stage_metrics: StageRequestStats | None,
|
||||
submit_ts: float | None,
|
||||
) -> bool:
|
||||
del replica_id, submit_ts
|
||||
if not isinstance(req_state, DuplexOrchestratorRequestState) or req_state.fence is None:
|
||||
return False
|
||||
request_id = output.request_id
|
||||
runner = self.session_manager.runner_for_request_id(request_id)
|
||||
if runner is None:
|
||||
# Session gone: nothing may forward or reach a client.
|
||||
return True
|
||||
segment = req_state.streaming.segment(stage_id)
|
||||
context = DuplexOutputContext(
|
||||
identity=DuplexRequestIdentity(
|
||||
session_id=req_state.session_id,
|
||||
fence=req_state.stage_fences.get(stage_id, req_state.fence),
|
||||
),
|
||||
final_stage_id=req_state.final_stage_id,
|
||||
segment_finished=req_state.streaming.enabled and segment.finished,
|
||||
segment_token_ids=tuple(segment.token_ids),
|
||||
segment_output_metadata=segment.output_metadata,
|
||||
)
|
||||
return runner.on_stage_output(
|
||||
stage_id,
|
||||
output,
|
||||
stage_metrics,
|
||||
request_id=request_id,
|
||||
context=context,
|
||||
)
|
||||
|
||||
async def _handle_forward_failure(
|
||||
self,
|
||||
req_id: str,
|
||||
next_stage_id: int,
|
||||
req_state: OrchestratorRequestState,
|
||||
exc: BaseException,
|
||||
) -> bool:
|
||||
if not req_state.session_owned:
|
||||
return False
|
||||
runner = self.session_manager.runner_for_request_id(req_id)
|
||||
if runner is not None:
|
||||
runner.on_stage_failure(next_stage_id, exc)
|
||||
await self._cleanup_request_ids(
|
||||
[req_id, *self._cfg_tracker.cleanup_parent(req_id)],
|
||||
abort=True,
|
||||
release_owners=True,
|
||||
)
|
||||
return True
|
||||
|
||||
async def _cleanup_request_ids(
|
||||
self,
|
||||
request_ids: list[str],
|
||||
*,
|
||||
abort: bool = False,
|
||||
release_owners: bool = False,
|
||||
) -> list[OutputMessage]:
|
||||
if not request_ids:
|
||||
return []
|
||||
cleanup_ids = list(dict.fromkeys(request_ids))
|
||||
closing_session_ids: list[str] = []
|
||||
if release_owners:
|
||||
closed_sessions = self.session_manager.close_sessions_for_request_ids(
|
||||
cleanup_ids,
|
||||
abort=abort,
|
||||
cleanup_in_progress=True,
|
||||
)
|
||||
closing_session_ids.extend(closed_sessions)
|
||||
for session_id, stale_request_ids in closed_sessions.items():
|
||||
logger.info(
|
||||
"[DuplexOrchestrator] closed duplex session %s while cleaning failed request ids %s",
|
||||
session_id,
|
||||
stale_request_ids,
|
||||
)
|
||||
cleanup_ids.extend(stale_request_ids)
|
||||
cleanup_ids = list(dict.fromkeys(cleanup_ids))
|
||||
try:
|
||||
outputs = await super()._cleanup_request_ids(cleanup_ids, abort=abort)
|
||||
except BaseException:
|
||||
if closing_session_ids:
|
||||
self.session_manager.defer_request_cleanups(closing_session_ids)
|
||||
raise
|
||||
if closing_session_ids:
|
||||
self.session_manager.finalize_closed_sessions(closing_session_ids)
|
||||
for request_id in cleanup_ids:
|
||||
self.session_manager.unregister_request(request_id)
|
||||
return outputs
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# DuplexStagePort #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
@property
|
||||
def stage_count(self) -> int:
|
||||
return len(self.stage_pools)
|
||||
|
||||
def sampling_defaults(self) -> tuple[object, ...]:
|
||||
defaults = []
|
||||
for pool in self.stage_pools:
|
||||
client = pool.stage_client
|
||||
if client is None:
|
||||
# Every replica of this stage was evicted (engine core died); a
|
||||
# session cannot be admitted until the deployment is restarted.
|
||||
raise RuntimeError(f"stage {pool.stage_id} has no live replica")
|
||||
defaults.append(client.default_sampling_params)
|
||||
return tuple(defaults)
|
||||
|
||||
@staticmethod
|
||||
def _sync_bridge_state(
|
||||
request_state: OrchestratorRequestState,
|
||||
context: DuplexStageRequestContext,
|
||||
) -> None:
|
||||
duplex_state = request_state.streaming.bridge_states.setdefault("duplex", {})
|
||||
if not isinstance(duplex_state, dict):
|
||||
duplex_state = {}
|
||||
request_state.streaming.bridge_states["duplex"] = duplex_state
|
||||
previous_epoch = duplex_state.get("epoch")
|
||||
current_model_turn_id = duplex_state.get("model_turn_id")
|
||||
if (
|
||||
not isinstance(current_model_turn_id, int)
|
||||
or previous_epoch != context.fence.epoch
|
||||
or current_model_turn_id < context.fence.turn_id
|
||||
):
|
||||
# A safety boundary can close a response before the model emits
|
||||
# its normal turn_eos. Catch up the engine-owned identity when the
|
||||
# next fenced append starts.
|
||||
duplex_state["model_turn_id"] = context.fence.turn_id
|
||||
duplex_state.update(
|
||||
{
|
||||
"session_id": context.session_id,
|
||||
"fence": context.fence,
|
||||
"epoch": context.fence.epoch,
|
||||
"turn_id": context.fence.turn_id,
|
||||
"session_config": dict(context.session_config),
|
||||
"runtime_config": dict(context.runtime_config),
|
||||
}
|
||||
)
|
||||
|
||||
def ensure_request(self, context: DuplexStageRequestContext) -> None:
|
||||
request_state = self.request_states.get(context.request_id)
|
||||
if request_state is None:
|
||||
request_state = DuplexOrchestratorRequestState(
|
||||
request_id=context.request_id,
|
||||
prompt=None,
|
||||
sampling_params_list=list(context.sampling_params),
|
||||
final_stage_id=context.final_stage_id,
|
||||
session_owned=True,
|
||||
session_id=context.session_id,
|
||||
fence=context.fence,
|
||||
config_generation=context.config_generation,
|
||||
)
|
||||
request_state.streaming.enabled = True
|
||||
self.request_states[context.request_id] = request_state
|
||||
elif isinstance(request_state, DuplexOrchestratorRequestState):
|
||||
if request_state.config_generation != context.config_generation:
|
||||
request_state.sampling_params_list = list(context.sampling_params)
|
||||
request_state.config_generation = context.config_generation
|
||||
request_state.session_id = context.session_id
|
||||
request_state.fence = context.fence
|
||||
else:
|
||||
raise RuntimeError(f"request {context.request_id} is not session-owned")
|
||||
self._sync_bridge_state(request_state, context)
|
||||
self.session_manager.register_request(context.request_id, context.session_id)
|
||||
|
||||
async def submit(self, submission: DuplexStageSubmission) -> DuplexStageSubmissionResult:
|
||||
context = submission.context
|
||||
request_state = self.request_states.get(context.request_id)
|
||||
if not isinstance(request_state, DuplexOrchestratorRequestState):
|
||||
raise RuntimeError(f"duplex request was not preregistered: {context.request_id}")
|
||||
request = build_engine_core_request_from_tokens(
|
||||
request_id=context.request_id,
|
||||
prompt=dict(submission.prompt),
|
||||
params=context.stage_sampling_params,
|
||||
model_config=self.stage_pools[context.stage_id].stage_vllm_config.model_config,
|
||||
resumable=True,
|
||||
)
|
||||
request.external_req_id = request.request_id
|
||||
pool = self.stage_pools[context.stage_id]
|
||||
if submission.already_submitted:
|
||||
replica_id = await pool.submit_update(context.request_id, request_state, request)
|
||||
else:
|
||||
replica_id = await pool.submit_initial(context.request_id, request_state, request, prompt_text=None)
|
||||
if self.async_chunk and context.stage_id == 0:
|
||||
prewarmed = await self._prewarm_async_chunk_stages(
|
||||
context.request_id,
|
||||
request,
|
||||
request_state,
|
||||
)
|
||||
if not prewarmed:
|
||||
# The prewarm already failed the request, aborted it and
|
||||
# popped its state; the runner turns this into an append
|
||||
# error instead of writing onto an orphaned object.
|
||||
raise RuntimeError(
|
||||
f"async-chunk prewarm failed for duplex request {context.request_id}; the request was aborted"
|
||||
)
|
||||
request_state.stage_fences[context.stage_id] = context.fence
|
||||
request_state.stage_submit_ts[context.stage_id] = _time.time()
|
||||
self._register_running_request(request_state)
|
||||
return DuplexStageSubmissionResult(
|
||||
request_id=context.request_id,
|
||||
stage_id=context.stage_id,
|
||||
replica_id=replica_id,
|
||||
)
|
||||
|
||||
async def cleanup(self, request_ids: list[str], *, abort: bool = False) -> None:
|
||||
await self._cleanup_request_ids(request_ids, abort=abort)
|
||||
|
||||
async def abort_requests(self, request_ids: list[str]) -> None:
|
||||
if request_ids:
|
||||
await self._abort_request_ids(list(dict.fromkeys(request_ids)))
|
||||
|
||||
|
||||
__all__ = ["DuplexOrchestrator", "DuplexOrchestratorRequestState"]
|
||||
File diff suppressed because it is too large.
Load diff
+376
-624
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user