[Model] Add native full-duplex Nemotron VoiceChat serving (#6089)

Signed-off-by: Sysy <1370724210@qq.com>
Signed-off-by: sy03 <137072421@qq.com>
Co-authored-by: sy03 <137072421@qq.com>
This commit is contained in:
Sy03andsy03 authored and GitHub committed 2026-08-26 13:19:20 -07:00
1 parent c2723979c0
commit 432b2c6ca3
40 files changed
+3560 -154

No files matched your search

@@ -0,0 +1,4 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Native Full-Duplex integration for NVIDIA NemotronLabs VoiceChat."""
@@ -0,0 +1,403 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Output projection for Nemotron VoiceChat's independent channels."""
from __future__ import annotations
import json
from collections.abc import Callable, Iterator, Mapping
from dataclasses import dataclass, field
from typing import Any
from uuid import uuid4
import numpy as np
import torch
from vllm.logger import init_logger
from vllm_omni.experimental.fullduplex.engine.contracts import (
duplex_resource_request_belongs_to_session,
)
from vllm_omni.experimental.fullduplex.output import (
get_duplex_output_decision,
)
logger = init_logger(__name__)
EncodeAudio = Callable[[object, int, str, float | None], str | None]
@dataclass(frozen=True, slots=True)
class NemotronVoiceChatDataPlaneContext:
epoch: int = 0
turn_id: int = 0
auto_responds: bool = True
response_format: str = "wav"
speed: float | None = None
modalities: tuple[str, ...] = ("text", "audio")
@dataclass(slots=True)
class _RequestState:
text_frames: int = 0
audio_frames: int = 0
pending_speech_end_frames: list[int] = field(default_factory=list)
function_active: bool = False
function_tokens: list[int] = field(default_factory=list)
function_call_id: str | None = None
terminal: bool = False
def _coerce_ints(value: object) -> list[int]:
if value is None:
return []
if isinstance(value, torch.Tensor):
value = value.detach().cpu().reshape(-1).tolist()
elif isinstance(value, np.ndarray):
value = value.reshape(-1).tolist()
if isinstance(value, int):
return [value]
if not isinstance(value, list | tuple):
return []
values: list[int] = []
for item in value:
if isinstance(item, torch.Tensor):
if item.numel() != 1:
continue
item = item.item()
elif isinstance(item, np.generic):
item = item.item()
try:
values.append(int(item))
except (TypeError, ValueError):
continue
return values
def _unwrap(output: object) -> tuple[object, object | None, int | None]:
stage_id = getattr(output, "stage_id", None)
inner = getattr(output, "request_output", None)
if inner is not None and inner is not output:
output = inner
outputs = getattr(output, "outputs", None)
completion = outputs[0] if isinstance(outputs, list) and outputs else None
if stage_id is None:
stage_id = getattr(output, "stage_id", None)
return output, completion, int(stage_id) if isinstance(stage_id, int) else None
def _multimodal(output: object, completion: object | None) -> dict[str, object]:
decision = get_duplex_output_decision(output)
metadata = getattr(decision, "metadata", None)
if isinstance(metadata, Mapping):
return dict(metadata)
for candidate in (
getattr(output, "multimodal_output", None),
getattr(completion, "multimodal_output", None) if completion is not None else None,
):
if isinstance(candidate, Mapping):
return dict(candidate)
return {}
def _audio_value(metadata: Mapping[str, object]) -> object | None:
value = next((metadata[key] for key in ("audio", "model_outputs", "latent") if key in metadata), None)
if isinstance(value, list) and len(value) == 1:
return value[0]
return value
def _sample_rate(metadata: Mapping[str, object]) -> int:
value = metadata.get("sr", metadata.get("sample_rate_hz", 22050))
if isinstance(value, list) and value:
value = value[0]
if hasattr(value, "item"):
value = value.item()
return int(value) if isinstance(value, int | float) else 22050
def _audio_samples(audio: object | None) -> int:
if audio is None:
return 0
if isinstance(audio, torch.Tensor):
return int(audio.numel())
try:
return int(np.asarray(audio, dtype=np.float32).size)
except (TypeError, ValueError):
return 0
def _speech_end_event(request_id: str) -> dict[str, object]:
return {
"stage_role": "tts",
"is_listen": False,
"data_plane_request_id": request_id,
"text": "",
"end_of_turn": True,
}
class NemotronVoiceChatDataPlaneSession:
"""Join frame-locked text/function outputs with Stage-2 audio."""
def __init__(self, encode_audio: EncodeAudio) -> None:
self._encode_audio = encode_audio
self._requests: dict[str, _RequestState] = {}
self._tokenizer = None
self._tokenizer_ref: str | None = None
self._special_ids: dict[str, int] | None = None
def configure_runtime(self, runtime_config: Mapping[str, object], *, tokenizer: Any | None = None) -> None:
"""Install the serving-resolved tokenizer contract as the sole truth."""
try:
special_ids = {
"bos": int(runtime_config["nvc_text_bos_id"]),
"eos": int(runtime_config["nvc_text_eos_id"]),
"pad": int(runtime_config["nvc_text_pad_id"]),
"sotc": int(runtime_config["nvc_function_sotc_id"]),
"eotc": int(runtime_config["nvc_function_eotc_id"]),
}
except (KeyError, TypeError, ValueError) as exc:
raise ValueError("Nemotron VoiceChat data plane requires resolved special-token ids") from exc
tokenizer_ref = runtime_config.get("nvc_tokenizer_ref")
if not isinstance(tokenizer_ref, str) or not tokenizer_ref:
raise ValueError("Nemotron VoiceChat data plane requires nvc_tokenizer_ref")
self._special_ids = special_ids
self._tokenizer_ref = tokenizer_ref
self._tokenizer = tokenizer
def begin_request(self, request_id: str) -> None:
self._requests.setdefault(request_id, _RequestState()).terminal = False
def is_terminal(self, request_id: str | None) -> bool:
return bool(request_id and self._requests.get(request_id) and self._requests[request_id].terminal)
def mark_terminal(self, request_id: str) -> None:
self._requests.setdefault(request_id, _RequestState()).terminal = True
def close_stream(self, request_id: str) -> None:
self._requests.pop(request_id, None)
def close_session(self, session_id: str, *, active_request_id: str | None = None) -> None:
if active_request_id:
self._requests.pop(active_request_id, None)
for request_id in tuple(self._requests):
if duplex_resource_request_belongs_to_session(request_id, session_id):
self._requests.pop(request_id, None)
def _load_tokenizer(self):
if self._tokenizer is None:
from transformers import AutoTokenizer
if self._tokenizer_ref is None:
raise RuntimeError("Nemotron VoiceChat data plane was used before runtime configuration")
self._tokenizer = AutoTokenizer.from_pretrained(self._tokenizer_ref, trust_remote_code=False)
return self._tokenizer
def _ids(self) -> dict[str, int]:
if self._special_ids is None:
raise RuntimeError("Nemotron VoiceChat data plane was used before runtime configuration")
return self._special_ids
def _decode(self, token_ids: list[int]) -> str:
if not token_ids:
return ""
return str(self._load_tokenizer().decode(token_ids, skip_special_tokens=True))
def project(
self,
result: object,
*,
context: NemotronVoiceChatDataPlaneContext | None = None,
) -> Iterator[dict[str, object]]:
if not isinstance(result, dict):
return
outputs = result.get("data_plane_outputs")
if not isinstance(outputs, list):
return
for output in outputs:
yield from self.project_output(output, context=context)
def project_output(
self,
output: object,
*,
context: NemotronVoiceChatDataPlaneContext | None = None,
) -> Iterator[dict[str, object]]:
context = context or NemotronVoiceChatDataPlaneContext()
outer = output
output, completion, stage_id = _unwrap(output)
request_id = getattr(output, "request_id", None) or getattr(outer, "request_id", None)
request_id = str(request_id) if request_id is not None else ""
state = self._requests.setdefault(request_id, _RequestState())
metadata = _multimodal(outer, completion)
modalities = {modality.lower() for modality in context.modalities}
wants_text = "text" in modalities
wants_audio = "audio" in modalities
if stage_id == 0 or "nvc_text_token_ids" in metadata:
ids = self._ids()
text_ids = _coerce_ints(metadata.get("nvc_text_token_ids"))
if not text_ids and completion is not None:
text_ids = _coerce_ints(
getattr(completion, "token_ids", None) or getattr(completion, "cumulative_token_ids", None)
)
for token_id in text_ids[-1:]:
state.text_frames += 1
if token_id == ids["eos"]:
if state.audio_frames >= state.text_frames:
yield _speech_end_event(request_id)
else:
state.pending_speech_end_frames.append(state.text_frames)
elif token_id == ids["pad"]:
yield {
"stage_role": "llm",
"is_listen": True,
"model_listen": True,
"listen_source": "model_listen",
"data_plane_request_id": request_id,
"end_of_turn": False,
}
elif token_id != ids["bos"] and wants_text:
text = self._decode([token_id])
if text:
yield {
"stage_role": "llm",
"is_listen": False,
"data_plane_request_id": request_id,
"text": text,
"end_of_turn": False,
}
for function_id in _coerce_ints(metadata.get("nvc_function_token"))[-1:]:
yield from self._project_function_token(
function_id,
state=state,
request_id=request_id,
ids=ids,
)
return
audio = _audio_value(metadata)
sample_rate = _sample_rate(metadata)
sample_count = _audio_samples(audio)
encoded = (
self._encode_audio(audio, sample_rate, context.response_format, context.speed)
if wants_audio and audio is not None
else None
)
audio_chunk_complete = sample_count > 0
if audio_chunk_complete:
# A native-duplex Stage-2 segment can contain one or more 80 ms
# codec frames. Count them against the frame-locked Stage-0 text
# channel. The long-lived codec request deliberately keeps
# ``finished=False`` across scheduler wakes; a non-empty decoded
# chunk, not request lifetime, is the audio-coverage signal.
duration_ms = sample_count * 1000 / max(1, sample_rate)
state.audio_frames += max(1, round(duration_ms / 80))
end_of_turn = bool(state.pending_speech_end_frames) and state.audio_frames >= state.pending_speech_end_frames[0]
if encoded:
yield {
"stage_role": "tts",
"is_listen": False,
"data_plane_request_id": request_id,
"text": "",
"audio_data": encoded,
"audio_format": context.response_format,
"sample_rate_hz": sample_rate,
"audio_duration_ms": round(sample_count * 1000 / max(1, sample_rate)),
"audio_text_mark": True,
"end_of_turn": end_of_turn,
}
elif end_of_turn:
yield _speech_end_event(request_id)
if end_of_turn:
state.pending_speech_end_frames.pop(0)
def _project_function_token(
self,
token_id: int,
*,
state: _RequestState,
request_id: str,
ids: Mapping[str, int],
) -> Iterator[dict[str, object]]:
if token_id == ids["sotc"]:
state.function_active = True
state.function_tokens.clear()
state.function_call_id = f"call_{uuid4().hex}"
return
if token_id == ids["eotc"] and state.function_active:
state.function_active = False
raw = self._decode(state.function_tokens)
state.function_tokens.clear()
try:
calls = self._parse_calls(raw)
except ValueError as exc:
state.function_call_id = None
yield {
"stage_role": "function",
"data_plane_request_id": request_id,
"error_code": "nemotron_function_call_parse_error",
"error": str(exc),
}
return
for index, call in enumerate(calls):
yield {
"stage_role": "function",
"data_plane_request_id": request_id,
"function_call": True,
"call_id": (
state.function_call_id if index == 0 and state.function_call_id else f"call_{uuid4().hex}"
),
"name": str(call["name"]),
"arguments": (
call.get("arguments")
if isinstance(call.get("arguments"), str)
else json.dumps(call.get("arguments", {}), separators=(",", ":"))
),
}
state.function_call_id = None
return
if state.function_active and token_id != ids["pad"]:
state.function_tokens.append(token_id)
@staticmethod
def _parse_calls(value: str) -> list[dict[str, object]]:
text = value.strip()
if "<TOOLCALL>" in text:
text = text.split("<TOOLCALL>", 1)[1]
if "</TOOLCALL>" in text:
text = text.split("</TOOLCALL>", 1)[0]
try:
parsed = json.loads(text)
except json.JSONDecodeError as exc:
raise ValueError("Nemotron VoiceChat produced malformed function-call JSON") from exc
if isinstance(parsed, dict):
parsed = [parsed]
if not isinstance(parsed, list) or not parsed:
raise ValueError("Nemotron VoiceChat function-call payload must be a non-empty object or list")
calls: list[dict[str, object]] = []
for item in parsed:
if not isinstance(item, dict):
raise ValueError("Nemotron VoiceChat function-call entries must be objects")
name = item.get("name")
if not isinstance(name, str) or not name.strip():
raise ValueError("Nemotron VoiceChat function-call entries require a non-empty name")
arguments = item.get("arguments", {})
if isinstance(arguments, str):
try:
decoded_arguments = json.loads(arguments)
except json.JSONDecodeError as exc:
raise ValueError("Nemotron VoiceChat function-call arguments contain malformed JSON") from exc
if not isinstance(decoded_arguments, dict):
raise ValueError("Nemotron VoiceChat function-call arguments must encode a JSON object")
elif not isinstance(arguments, dict):
raise ValueError("Nemotron VoiceChat function-call arguments must be a JSON object")
calls.append({"name": name.strip(), "arguments": arguments})
return calls
__all__ = [
"NemotronVoiceChatDataPlaneContext",
"NemotronVoiceChatDataPlaneSession",
]
@@ -0,0 +1,225 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""80 ms PCM packetization for Nemotron VoiceChat native duplex."""
from __future__ import annotations
import binascii
import numpy as np
import pybase64 as base64
NEMOTRON_VOICECHAT_SAMPLE_RATE = 16000
NEMOTRON_VOICECHAT_FRAME_SAMPLES = 1280
_SAMPLE_BYTES = 4
_FRAME_BYTES = NEMOTRON_VOICECHAT_FRAME_SAMPLES * _SAMPLE_BYTES
def _require_terminal_tail(buffered_bytes: int) -> None:
if buffered_bytes > _FRAME_BYTES:
raise ValueError(
"Nemotron VoiceChat manual/deferred commit cannot contain more than one 80 ms frame; "
"enable extra_body.auto_response for native full-duplex streaming"
)
def decode_pcm_f32le(payload: object, *, exact_frame: bool = False) -> bytes:
if not isinstance(payload, dict):
raise ValueError("Nemotron VoiceChat duplex audio payload must be a mapping")
if payload.get("format") != "pcm_f32le":
raise ValueError("Nemotron VoiceChat duplex audio format must be pcm_f32le")
if payload.get("sample_rate_hz") != NEMOTRON_VOICECHAT_SAMPLE_RATE:
raise ValueError("Nemotron VoiceChat duplex audio sample_rate_hz must be 16000")
encoded = payload.get("audio")
if not isinstance(encoded, str):
raise ValueError("Nemotron VoiceChat duplex audio must be base64 pcm_f32le")
try:
raw = base64.b64decode(encoded, validate=True)
except (binascii.Error, ValueError) as exc:
raise ValueError("Nemotron VoiceChat duplex audio is not valid base64") from exc
if len(raw) % _SAMPLE_BYTES:
raise ValueError("Nemotron VoiceChat pcm_f32le payload has a partial sample")
values = np.frombuffer(raw, dtype="<f4")
if values.size and not bool(np.isfinite(values).all()):
raise ValueError("Nemotron VoiceChat duplex audio samples must be finite")
if exact_frame and len(raw) != _FRAME_BYTES:
raise ValueError(
f"Nemotron VoiceChat native duplex append must contain exactly {NEMOTRON_VOICECHAT_FRAME_SAMPLES} samples"
)
return raw
def _frame_payload(raw: bytes, *, final: bool) -> dict[str, object]:
return {
"type": "audio",
"audio": base64.b64encode(raw).decode("ascii"),
"format": "pcm_f32le",
"sample_rate_hz": NEMOTRON_VOICECHAT_SAMPLE_RATE,
"final": final,
}
class NemotronVoiceChatPcmAppendReservation:
def __init__(
self,
owner: NemotronVoiceChatPcmAppendBuffer,
*,
operation_id: str,
payload: dict[str, object] | None,
raw: bytes,
) -> None:
self._owner = owner
self.operation_id = operation_id
self.payload = payload
self.raw = raw
self._active = True
@property
def active(self) -> bool:
return self._active
@property
def byte_count(self) -> int:
return len(self.raw)
def commit(self) -> None:
if not self._active:
return
self._active = False
if self in self._owner._reservations:
self._owner._reservations.remove(self)
def rollback(self) -> None:
if not self._active:
return
try:
index = self._owner._reservations.index(self)
except ValueError:
self._active = False
return
restore = bytearray()
for reservation in self._owner._reservations[index:]:
if reservation._active:
restore.extend(reservation.raw)
reservation._active = False
del self._owner._reservations[index:]
self._owner._buffer[:0] = restore
class NemotronVoiceChatPcmAppendBuffer:
"""Adapt Realtime packets to the current full-duplex PCM buffer contract.
The model consumes exactly one 1280-sample frame per scheduler append.
Realtime packets may split a frame arbitrarily, but a single packet is
capped at one frame so the serving contract never silently drops a second
ready frame behind a single-reservation API.
"""
def __init__(self) -> None:
self._buffer = bytearray()
self._reservations: list[NemotronVoiceChatPcmAppendReservation] = []
@property
def pending_byte_count(self) -> int:
return len(self._buffer)
def clear(self) -> None:
for reservation in self._reservations:
reservation._active = False
self._reservations.clear()
self._buffer.clear()
def clear_force_listen(self) -> None:
# Nemotron VoiceChat has no serving-side force-listen packet bit.
return
def has_pending(self) -> bool:
return bool(self._buffer)
def has_reserved(self) -> bool:
return any(reservation.active for reservation in self._reservations)
def _reserve_frame(
self,
*,
operation_id: str,
final: bool,
) -> NemotronVoiceChatPcmAppendReservation | None:
if len(self._buffer) < _FRAME_BYTES:
return None
raw = bytes(self._buffer[:_FRAME_BYTES])
del self._buffer[:_FRAME_BYTES]
reservation = NemotronVoiceChatPcmAppendReservation(
self,
operation_id=operation_id,
payload=_frame_payload(raw, final=final),
raw=raw,
)
self._reservations.append(reservation)
return reservation
def prepare_append(
self,
payload: dict[str, object],
*,
operation_id: str,
chunk_period_ms: int,
allow_emit: bool,
) -> NemotronVoiceChatPcmAppendReservation | None:
if chunk_period_ms != 80:
raise ValueError("Nemotron VoiceChat native duplex chunk_period_ms must be 80")
raw = decode_pcm_f32le(payload)
if len(raw) > _FRAME_BYTES:
raise ValueError("Nemotron VoiceChat Realtime append must contain at most 1280 samples")
self._buffer.extend(raw)
if not allow_emit:
return None
return self._reserve_frame(operation_id=operation_id, final=False)
def prepare_commit(
self,
*,
operation_id: str,
chunk_period_ms: int,
) -> NemotronVoiceChatPcmAppendReservation:
if chunk_period_ms != 80:
raise ValueError("Nemotron VoiceChat native duplex chunk_period_ms must be 80")
_require_terminal_tail(len(self._buffer))
if not self._buffer:
reservation = NemotronVoiceChatPcmAppendReservation(
self,
operation_id=operation_id,
payload=None,
raw=b"",
)
else:
raw = bytes(self._buffer)
self._buffer.clear()
reservation = NemotronVoiceChatPcmAppendReservation(
self,
operation_id=operation_id,
payload=_frame_payload(raw + bytes(_FRAME_BYTES - len(raw)), final=True),
raw=raw,
)
self._reservations.append(reservation)
return reservation
def flush(self, *, chunk_period_ms: int) -> dict[str, object] | None:
if chunk_period_ms != 80:
raise ValueError("Nemotron VoiceChat native duplex chunk_period_ms must be 80")
_require_terminal_tail(len(self._buffer))
if not self._buffer:
return None
raw = bytes(self._buffer)
self._buffer.clear()
return _frame_payload(raw + bytes(_FRAME_BYTES - len(raw)), final=True)
__all__ = [
"NEMOTRON_VOICECHAT_FRAME_SAMPLES",
"NEMOTRON_VOICECHAT_SAMPLE_RATE",
"NemotronVoiceChatPcmAppendBuffer",
"NemotronVoiceChatPcmAppendReservation",
"decode_pcm_f32le",
]
@@ -0,0 +1,167 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Engine policy for Nemotron VoiceChat's frame-locked duplex timeline."""
from __future__ import annotations
from typing import Any
from vllm.sampling_params import RequestOutputKind, SamplingParams
from vllm_omni.experimental.fullduplex.engine.contracts import (
DuplexAppendPlan,
DuplexInputMode,
DuplexOutputAction,
DuplexOutputDecision,
)
from vllm_omni.experimental.fullduplex.engine.messages import DuplexFence
from vllm_omni.experimental.fullduplex.nemotron_voicechat.input import (
decode_pcm_f32le,
)
def _plain_token_ids(value: object, *, name: str) -> list[int]:
if not isinstance(value, list | tuple) or not value:
raise ValueError(f"Nemotron VoiceChat runtime requires non-empty {name}")
try:
return [int(token_id) for token_id in value]
except (TypeError, ValueError) as exc:
raise ValueError(f"Nemotron VoiceChat {name} must contain token ids") from exc
def _positive_int(value: object, *, name: str) -> int:
try:
parsed = int(value)
except (TypeError, ValueError) as exc:
raise ValueError(f"Nemotron VoiceChat requires a positive {name}") from exc
if parsed <= 0:
raise ValueError(f"Nemotron VoiceChat requires a positive {name}")
return parsed
class NemotronVoiceChatDuplexRuntimeExtension:
"""Append one 80 ms acoustic frame to one resumable thinker request."""
def configure_sampling_params(
self,
*,
runtime_config: dict[str, Any],
defaults: tuple[object, ...],
) -> tuple[object, ...]:
del runtime_config
if not defaults:
return defaults
# Every scheduler segment is one transport wake of a long-lived
# request. CUMULATIVE output makes the multimodal output processor
# concatenate all earlier Stage-2 waveforms and resend them on every
# wake (80, 160, 240, ... ms), causing O(n^2) audio replay. Duplex
# consumers require per-wake deltas at every stage.
configured = [params.clone() if isinstance(params, SamplingParams) else params for params in defaults]
for params in configured:
if isinstance(params, SamplingParams):
params.output_kind = RequestOutputKind.DELTA
stage0 = defaults[0]
if isinstance(stage0, SamplingParams):
stage0 = stage0.clone()
stage0.temperature = 0.0
stage0.top_p = 1.0
stage0.top_k = 0
stage0.max_tokens = 1
stage0.ignore_eos = True
stage0.output_kind = RequestOutputKind.DELTA
configured[0] = stage0
return tuple(configured)
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:
del sampling_params, turn_seq
if mode is not DuplexInputMode.APPEND_AUDIO_CHUNK:
raise ValueError(f"Nemotron VoiceChat does not support duplex input mode {mode.value!r}")
decode_pcm_f32le(payload, exact_frame=True)
normalized_payload = dict(payload)
prompt_ids = _plain_token_ids(
runtime_config.get("nvc_prompt_token_ids"),
name="nvc_prompt_token_ids",
)
max_model_len = _positive_int(
runtime_config.get("nvc_max_model_len"),
name="nvc_max_model_len",
)
required_model_len = len(prompt_ids) + seq + 1
if required_model_len > max_model_len:
raise ValueError(
"Nemotron VoiceChat native duplex session exceeds the Stage-0 "
f"max_model_len: prompt_tokens={len(prompt_ids)} + input_frames={seq} + "
f"sampled_token=1 gives {required_model_len} > {max_model_len}; "
"start a new session or raise Stage 0 max_model_len"
)
try:
pad_id = int(runtime_config["nvc_text_pad_id"])
except (KeyError, TypeError, ValueError) as exc:
raise ValueError("Nemotron VoiceChat runtime requires nvc_text_pad_id") from exc
scheduler_prompt = prompt_ids + [pad_id] if seq <= 1 else [pad_id]
return DuplexAppendPlan(
prompt={
"prompt_token_ids": scheduler_prompt,
"model_intermediate_buffer": {
"request_id": request_id,
"global_request_id": [fence.session_id],
"duplex": {
"data_plane": True,
"fence": fence,
"session_id": fence.session_id,
"incarnation": fence.incarnation,
"epoch": fence.epoch,
"source_input_seq": seq,
"seq": seq,
"mode": mode.value,
"payload": normalized_payload,
"final": final,
"session_config": dict(session_config),
"runtime_config": dict(runtime_config),
"scheduler_token_budget": len(scheduler_prompt),
},
},
}
)
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:
del final_stage_id, segment_finished, output
if stage_id != 0:
return None
metadata = dict(segment_output_metadata)
metadata["nvc_text_token_ids"] = list(segment_token_ids)
# Stage 0 is a client-visible side channel even though Stage 2 is the
# configured audio response stage. Mark it explicitly so the shared
# collector does not discard it while waiting for the final stage.
metadata["duplex_direct_response"] = True
return DuplexOutputDecision(
action=DuplexOutputAction.DIRECT_RESPONSE,
metadata=metadata,
final_output_type="text",
)
__all__ = ["NemotronVoiceChatDuplexRuntimeExtension"]
@@ -0,0 +1,363 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Realtime serving adapter for Nemotron VoiceChat native duplex."""
from __future__ import annotations
import asyncio
import json
import os
from collections.abc import Callable, Mapping
from copy import deepcopy
from typing import Any
from vllm_omni.experimental.fullduplex.minicpmo45.session import (
MiniCPMO45ServingSessionState,
)
from vllm_omni.experimental.fullduplex.nemotron_voicechat.data_plane import (
NemotronVoiceChatDataPlaneContext,
NemotronVoiceChatDataPlaneSession,
)
from vllm_omni.experimental.fullduplex.nemotron_voicechat.input import (
NemotronVoiceChatPcmAppendBuffer,
)
from vllm_omni.experimental.fullduplex.openai.protocol import DuplexCapabilities
from vllm_omni.experimental.fullduplex.openai.runtime_adapter import ServingRuntimeConfigError
EncodeAudio = Callable[[object, int, str, float | None], str | None]
_DEFAULT_SYSTEM_PROMPT = (
"You are an AI voice assistant developed by NVIDIA. "
"Your name is NVIDIA Voice Chat. "
"Answer in a spoken, conversational style rather than a written one. "
"Do not repeat the same sentence over and over again. "
"Start the conversation by greeting the user."
)
_PRIVATE_KEYS = frozenset(
{
"nvc_prompt_token_ids",
"nvc_text_bos_id",
"nvc_text_eos_id",
"nvc_text_pad_id",
"nvc_function_sotc_id",
"nvc_function_eotc_id",
"nvc_function_eotr_id",
"nvc_max_model_len",
"nvc_tokenizer_ref",
"nvc_tools_signature",
"nvc_function_response_generation",
"nvc_function_response_token_ids",
"nvc_function_response_call_id",
"nvc_function_response_batches",
}
)
def _stt_config(model_config: Any) -> dict[str, Any]:
hf_config = getattr(model_config, "hf_config", None)
stt_cfg = getattr(hf_config, "stt_cfg", None)
if not isinstance(stt_cfg, dict):
raise ServingRuntimeConfigError("Nemotron VoiceChat checkpoint STT configuration is unavailable")
return stt_cfg
def _normalized_tools(config: object) -> tuple[list[dict[str, object]], str]:
extra_body = getattr(config, "extra_body", None)
raw_tools = extra_body.get("realtime_tools") if isinstance(extra_body, dict) else None
if raw_tools is None:
return [], "[]"
if not isinstance(raw_tools, list):
raise ServingRuntimeConfigError("Nemotron VoiceChat tools must be a list")
if len(raw_tools) > 5:
raise ServingRuntimeConfigError("Nemotron VoiceChat supports at most 5 tools per session")
normalized: list[dict[str, object]] = []
for index, tool in enumerate(raw_tools):
if not isinstance(tool, dict):
raise ServingRuntimeConfigError(f"Nemotron VoiceChat tool {index} must be an object")
function = tool.get("function", tool)
if not isinstance(function, dict):
raise ServingRuntimeConfigError(f"Nemotron VoiceChat tool {index} has no function definition")
definition = {key: value for key, value in function.items() if key != "type"}
if not isinstance(definition.get("name"), str) or not str(definition["name"]).strip():
raise ServingRuntimeConfigError(f"Nemotron VoiceChat tool {index} requires a name")
normalized.append(definition)
signature = json.dumps(normalized, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
return normalized, signature
def _render_tool_prompt(instructions: str, tools: list[dict[str, object]]) -> str:
if not tools:
return instructions
available = json.dumps(tools, ensure_ascii=False, sort_keys=True)
return (
f"{instructions}\n\n"
"You can use the following tools to assist the user if required:"
f"\n<AVAILABLE_TOOLS>{available}</AVAILABLE_TOOLS>\n\n"
"If you decide to call any tool(s), use the following format:\n"
'<TOOLCALL>[{"name": "tool_name1", "arguments": "tool_args1"}, '
'{"name": "tool_name2", "arguments": "tool_args2"}]</TOOLCALL>\n\n'
"The user will execute tool-calls and return responses from tool(s) in this format:\n"
'<TOOL_RESPONSE>[{"tool_response1"}, {"tool_response2"}]</TOOL_RESPONSE>\n\n'
"Based on the tool responses, you can call additional tools if needed, correct tool calls if any "
"errors are found, or just respond to the user."
)
def _render_tool_response(output: str) -> str:
"""Serialize one Realtime function result using NVIDIA's function channel."""
try:
value = json.loads(output)
except json.JSONDecodeError:
value = output
payload = json.dumps([value], ensure_ascii=True, separators=(",", ":"))
return f"<TOOL_RESPONSE>{payload}</TOOL_RESPONSE>"
def _require_native_full_duplex(config: object) -> None:
extra_body = getattr(config, "extra_body", None)
enabled = isinstance(extra_body, dict) and (
extra_body.get("auto_response") is True or extra_body.get("full_duplex") is True
)
if not enabled:
raise ServingRuntimeConfigError(
"Nemotron VoiceChat currently supports model-native full-duplex streaming only; "
"set extra_body.auto_response=true",
code="unsupported_nemotron_duplex_mode",
)
def _tokenize_runtime(model_config: Any, instructions: str) -> tuple[dict[str, object], Any]:
from transformers import AutoTokenizer
stt_cfg = _stt_config(model_config)
tokenizer_ref = os.environ.get("NEMOTRON_VOICECHAT_LLM_PATH") or stt_cfg.get(
"pretrained_llm", "nvidia/NVIDIA-Nemotron-Nano-9B-v2"
)
tokenizer = AutoTokenizer.from_pretrained(tokenizer_ref, trust_remote_code=False)
def token(name: str, default: str) -> int:
value = tokenizer.convert_tokens_to_ids(stt_cfg.get(name, default))
if value is None:
raise ServingRuntimeConfigError(f"Nemotron VoiceChat tokenizer does not define {name}")
return int(value)
bos_id = token("bos_token", "<s>")
eos_id = token("eos_token", "</s>")
pad_id = token("pad_token", "<SPECIAL_12>")
prompt_ids = [bos_id] + list(tokenizer.encode(instructions, add_special_tokens=False)) + [eos_id]
runtime = {
"instructions": instructions,
"nvc_prompt_token_ids": prompt_ids,
"nvc_text_bos_id": bos_id,
"nvc_text_eos_id": eos_id,
"nvc_text_pad_id": pad_id,
"nvc_function_sotc_id": int(tokenizer.convert_tokens_to_ids("<SPECIAL_20>")),
"nvc_function_eotc_id": int(tokenizer.convert_tokens_to_ids("<SPECIAL_21>")),
"nvc_function_eotr_id": int(tokenizer.convert_tokens_to_ids("<SPECIAL_22>")),
"nvc_tokenizer_ref": str(tokenizer_ref),
}
return runtime, tokenizer
class NemotronVoiceChatServingRuntimeAdapter:
adapter_id = "nemotron_voicechat"
silence_continuation_samples = 1280
# The session-owned persistent drain is the sole data-plane output
# consumer. Collecting on append would race that drain and can consume a
# Stage2 audio output before the realtime projector observes it.
collect_outputs_on_append = False
clean_response_done_prefix = ""
interrupted_tts_prefix = ""
private_runtime_config_keys = _PRIVATE_KEYS
def __init__(self, encode_audio: EncodeAudio) -> None:
self.session_states: dict[str, MiniCPMO45ServingSessionState] = {}
self.data_plane = NemotronVoiceChatDataPlaneSession(encode_audio)
self._tokenizer: Any | None = None
def create_session_state(self) -> MiniCPMO45ServingSessionState:
return MiniCPMO45ServingSessionState(
audio_buffer=NemotronVoiceChatPcmAppendBuffer(),
)
def session_state(self, session_id: str) -> MiniCPMO45ServingSessionState:
return self.session_states.setdefault(session_id, self.create_session_state())
def remove_session_state(self, session_id: str) -> None:
self.session_states.pop(session_id, None)
@staticmethod
def is_enabled(config: object) -> bool:
del config
return True
@staticmethod
def capabilities(*, max_sessions: int) -> DuplexCapabilities:
supports_multi_session = max_sessions > 1
return DuplexCapabilities(
supports_model_native_turn_policy=True,
supports_external_turn_signal=False,
supports_client_commit=True,
supports_barge_in=False,
supports_playback_ack=True,
supports_input_append=True,
supports_replace_latest_chunk=False,
supports_reencode_context=False,
supports_rollback_to_checkpoint=False,
supports_turn_commit_only=False,
supports_kv_lease=False,
supports_core_kv_lease=False,
supports_model_internal_state=True,
supports_stage_resumption=True,
supports_scheduler_native_append=False,
supports_core_resumable_request=True,
supports_stage_connector_handoff=True,
supports_independent_io_streams=True,
supports_realtime_endpoint=True,
supports_multi_session=supports_multi_session,
supports_multi_session_same_replica=False,
supports_session_lease=True,
supports_session_resume=True,
session_admission_mode="engine_managed",
supports_audio_truncate=False,
requires_model_runner_kv=True,
requires_native_stage_role=True,
implementation_level="model_native_duplex",
adapter_patterns=["scheduler_data_plane"],
input_modes=["append_audio_chunk"],
signal_sources=["model_native", "client_event"],
stage_handoff_transport="scheduler_data_plane",
chunk_period_ms=80,
target_barge_in_latency_ms=None,
)
@staticmethod
def validate_client_extra_body(extra_body: object) -> None:
if not isinstance(extra_body, dict):
return
private = sorted(_PRIVATE_KEYS.intersection(extra_body))
if private:
raise ServingRuntimeConfigError(
"Nemotron VoiceChat runtime configuration is server-owned: " + ", ".join(private)
)
async def prepare_runtime_config(
self,
config: object,
*,
model_config: Any,
) -> dict[str, object]:
self.validate_client_extra_body(getattr(config, "extra_body", None))
_require_native_full_duplex(config)
instructions = str(getattr(config, "instructions", None) or _DEFAULT_SYSTEM_PROMPT)
tools, tools_signature = _normalized_tools(config)
rendered_prompt = _render_tool_prompt(instructions, tools)
runtime, tokenizer = await asyncio.to_thread(_tokenize_runtime, model_config, rendered_prompt)
max_model_len = getattr(model_config, "max_model_len", None)
if not isinstance(max_model_len, int) or max_model_len <= 0:
raise ServingRuntimeConfigError("Nemotron VoiceChat requires a positive Stage-0 max_model_len")
runtime["nvc_max_model_len"] = max_model_len
# Keep raw session values for immutable-in-incarnation update checks;
# only the rendered prompt token ids enter Stage-0 KV.
runtime["instructions"] = instructions
runtime["nvc_tools_signature"] = tools_signature
self.data_plane.configure_runtime(runtime, tokenizer=tokenizer)
self._tokenizer = tokenizer
return runtime
def runtime_config_for_function_output(
self,
item: Mapping[str, object],
current: Mapping[str, object],
) -> dict[str, object]:
"""Queue a client tool result for frame-locked function-channel injection."""
call_id = item.get("call_id")
output = item.get("output")
if not isinstance(call_id, str) or not call_id:
raise ServingRuntimeConfigError(
"function_call_output requires call_id",
code="invalid_function_call_output",
)
if not isinstance(output, str):
raise ServingRuntimeConfigError(
"function_call_output requires a string output",
code="invalid_function_call_output",
)
if self._tokenizer is None:
raise ServingRuntimeConfigError(
"Nemotron VoiceChat tokenizer is unavailable for function output",
code="invalid_function_call_output",
)
response_token_ids = list(
self._tokenizer.encode(
_render_tool_response(output),
add_special_tokens=False,
)
)
if not response_token_ids:
raise ServingRuntimeConfigError(
"function_call_output tokenized to an empty response",
code="invalid_function_call_output",
)
runtime = deepcopy(dict(current))
generation = int(runtime.get("nvc_function_response_generation", 0)) + 1
token_ids = [int(token_id) for token_id in response_token_ids]
batches = runtime.get("nvc_function_response_batches")
if not isinstance(batches, list):
batches = []
batches = [*batches, {"generation": generation, "call_id": call_id, "token_ids": token_ids}]
runtime["nvc_function_response_generation"] = generation
runtime["nvc_function_response_token_ids"] = token_ids
runtime["nvc_function_response_call_id"] = call_id
runtime["nvc_function_response_batches"] = batches
return runtime
@staticmethod
def runtime_config_for_update(
config: object,
current: Mapping[str, object],
) -> dict[str, object]:
NemotronVoiceChatServingRuntimeAdapter.validate_client_extra_body(getattr(config, "extra_body", None))
_require_native_full_duplex(config)
runtime = deepcopy(dict(current))
instructions = str(getattr(config, "instructions", None) or _DEFAULT_SYSTEM_PROMPT)
_, tools_signature = _normalized_tools(config)
# The system/tool prompt is already resident in Stage-0 KV. Updating it
# without a new incarnation would make the advertised config disagree
# with model state, so reject such updates explicitly.
if runtime and instructions != runtime.get("instructions"):
raise ServingRuntimeConfigError(
"Nemotron VoiceChat instructions cannot change inside an active duplex incarnation"
)
if runtime and tools_signature != runtime.get("nvc_tools_signature", "[]"):
raise ServingRuntimeConfigError(
"Nemotron VoiceChat tools cannot change inside an active duplex incarnation"
)
return runtime
@staticmethod
def data_plane_context(
*,
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, ...],
) -> NemotronVoiceChatDataPlaneContext:
del active_response_turn_id, active_response_id
return NemotronVoiceChatDataPlaneContext(
epoch=epoch,
turn_id=turn_id,
auto_responds=auto_responds,
response_format=response_format,
speed=speed,
modalities=modalities,
)
__all__ = ["NemotronVoiceChatServingRuntimeAdapter"]
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import asyncio
@@ -1052,6 +1055,46 @@ class RealtimeInputTranslator:
item_id = str(item["id"])
item_type = item.get("type")
role = item.get("role")
if item_type == "function_call_output":
call_id = item.get("call_id")
output = item.get("output")
matching_call = any(
known.get("type") == "function_call" and known.get("call_id") == call_id
for known in self._conversation_items.values()
)
duplicate_output = any(
known.get("type") == "function_call_output" and known.get("call_id") == call_id
for known in self._conversation_items.values()
)
if not isinstance(call_id, str) or not call_id or not matching_call:
await self._send_realtime_payload(
self._realtime_error_payload(
"invalid_function_call_output",
"function_call_output requires the call_id of a completed function call",
event_id=event.get("event_id"),
param="item.call_id",
)
)
return None
if not isinstance(output, str) or duplicate_output:
await self._send_realtime_payload(
self._realtime_error_payload(
"invalid_function_call_output",
(
"function_call_output requires a string output"
if not isinstance(output, str)
else f"function_call_output already exists for call_id {call_id}"
),
event_id=event.get("event_id"),
param="item.output",
)
)
return None
# Do not retain the result until SessionRunner has delivered its
# runtime update. On success, the resulting
# ``conversation.item.created`` event records it in the shared
# input/output protocol state; on failure the client may retry the
# same call_id instead of being rejected by provisional history.
if item_type != "message" or role in {"assistant", "system"}:
return {
"type": "turn.signal",
@@ -346,6 +346,67 @@ class RealtimeOutputProjector:
"reason": event.get("finish_reason") or "stop",
},
)
if event_type == "function_call.done":
call_id = event.get("call_id")
name = event.get("name")
arguments = event.get("arguments", "")
if not isinstance(call_id, str) or not call_id or not isinstance(name, str) or not name:
return [{"type": "duplex.function_call.done", "event": event}]
if not isinstance(arguments, str):
arguments = str(arguments)
response_id = f"resp_{uuid4().hex}"
item = {
"id": f"item_{uuid4().hex}",
"object": "realtime.item",
"type": "function_call",
"status": "completed",
"name": name,
"call_id": call_id,
"arguments": arguments,
}
self._conversation_items[str(item["id"])] = item
response = {
"id": response_id,
"object": "realtime.response",
"status": "completed",
"status_details": {"type": "completed", "reason": "completed"},
"output": [dict(item)],
"metadata": {},
}
return [
{"type": "response.created", "response": {**response, "status": "in_progress", "output": []}},
*self._conversation_item_added_events(item),
{
"type": "response.output_item.added",
"response_id": response_id,
"output_index": 0,
"item": dict(item),
},
{
"type": "response.function_call_arguments.delta",
"response_id": response_id,
"item_id": item["id"],
"output_index": 0,
"call_id": call_id,
"delta": arguments,
},
{
"type": "response.function_call_arguments.done",
"response_id": response_id,
"item_id": item["id"],
"output_index": 0,
"call_id": call_id,
"arguments": arguments,
},
{
"type": "response.output_item.done",
"response_id": response_id,
"output_index": 0,
"item": dict(item),
},
self._conversation_item_done_event(item),
{"type": "response.done", "response": response},
]
if event_type == "error":
raw_error = event.get("error")
if isinstance(raw_error, dict):
@@ -124,6 +124,7 @@ class ServingRuntimeAdapter(Protocol):
clean_response_done_prefix: str
interrupted_tts_prefix: str
private_runtime_config_keys: frozenset[str]
collect_outputs_on_append: bool
def create_session_state(self) -> ServingRuntimeSessionState: ...
@@ -135,7 +135,9 @@ class NativeRuntimeBridgeMixin:
incarnation=session.incarnation,
)
if self._callable_accepts_keyword(append_input, "collect_outputs"):
append_kwargs["collect_outputs"] = False
append_kwargs["collect_outputs"] = bool(
getattr(self._serving_runtime_adapter, "collect_outputs_on_append", False)
)
result = await append_input(session.session_id, **append_kwargs)
except Exception as exc:
logger.exception("Failed to append duplex runtime input: %s", exc)
@@ -315,16 +317,21 @@ class NativeRuntimeBridgeMixin:
native.data_plane_task = task
return True
# One model unit (1 s at 16 kHz) of pcm_f32le silence, matching the
# official full-duplex behavior where the microphone keeps streaming
# silence while the assistant speaks; replies span multiple units.
# One MiniCPM model unit (1 s at 16 kHz) is the compatibility default.
# Other native-duplex adapters may use a different frame-locked unit.
_NATIVE_SILENCE_UNIT_PAYLOAD_AUDIO = base64.b64encode(bytes(16000 * 4)).decode("ascii")
_NATIVE_RESPONSE_MAX_CONTINUATION_UNITS = 8
def _native_silence_unit_payload(self) -> dict[str, object]:
samples = int(getattr(self._serving_runtime_adapter, "silence_continuation_samples", 16000))
audio = (
self._NATIVE_SILENCE_UNIT_PAYLOAD_AUDIO
if samples == 16000
else base64.b64encode(bytes(samples * 4)).decode("ascii")
)
return {
"type": "audio",
"audio": self._NATIVE_SILENCE_UNIT_PAYLOAD_AUDIO,
"audio": audio,
"format": "pcm_f32le",
"sample_rate_hz": 16000,
}
@@ -826,6 +833,18 @@ class NativeRuntimeBridgeMixin:
}
)
return close_reason, True
if native_result.get("function_call") is True:
await send_json(
{
"type": "function_call.done",
"session_id": session.session_id,
"epoch": session.epoch,
"call_id": native_result.get("call_id"),
"name": native_result.get("name"),
"arguments": native_result.get("arguments", ""),
}
)
return close_reason, True
if native_result.get("requires_stage_handoff") is True or native_result.get("requires_tts_stage") is True:
# Stage0 announces a talker handoff before Stage1 has produced
# client-visible audio. A single client input stream may contain
@@ -1728,6 +1728,10 @@ class OmniDuplexSessionHandler(
session.truncate_history_item(item_id, audio_end_ms=committed_ms)
new_epoch, old_playback = self._advance_barge_in_epoch(session)
if old_request_id is not None:
# Epoch-scoped request ids prevent state reuse, but explicitly
# release projector/parser cursors so cancelled epochs do not
# accumulate until the whole session closes.
self._serving_runtime_adapter.data_plane.close_stream(old_request_id)
await self._abort_request_background(
session,
old_request_id,
@@ -345,6 +345,13 @@ class DuplexSessionRunnerMixin:
)
precreated_response_id = session.active_response_id if precreate_response else None
def _discard_retained_committed_audio() -> None:
if (
retained_committed_payload is not None
and native.committed_audio_payload is retained_committed_payload
):
session.release_input_bytes(native.clear_committed_audio())
async def _run() -> bool:
nonlocal runtime_closed
try:
@@ -367,8 +374,10 @@ class DuplexSessionRunnerMixin:
and native.committed_audio_payload is retained_committed_payload
):
session.release_input_bytes(native.clear_committed_audio())
elif pcm_reservation is not None:
pcm_reservation.rollback()
else:
if pcm_reservation is not None:
pcm_reservation.rollback()
_discard_retained_committed_audio()
if (
not append_ok
and precreated_response_id is not None
@@ -406,6 +415,7 @@ class DuplexSessionRunnerMixin:
except Exception as exc:
if pcm_reservation is not None:
pcm_reservation.rollback()
_discard_retained_committed_audio()
logger.exception("Native duplex append task failed: %s", exc)
await self._send_runtime_error(emit_event, "runtime_append_task_failed", exc, session=session)
if session.state != DuplexSessionState.CLOSED:
@@ -440,19 +450,34 @@ class DuplexSessionRunnerMixin:
if not predecessor_ok:
if pcm_reservation is not None:
pcm_reservation.rollback()
_discard_retained_committed_audio()
return False
if actor.closing or runtime_closed or session.state != DuplexSessionState.OPEN:
if pcm_reservation is not None:
pcm_reservation.rollback()
_discard_retained_committed_audio()
return False
if before_append is not None and not before_append():
if pcm_reservation is not None:
pcm_reservation.rollback()
_discard_retained_committed_audio()
return True
if pcm_reservation is not None and not pcm_reservation.active:
_discard_retained_committed_audio()
return False
return await _run()
def _release_cancelled_retained_audio(done: asyncio.Task[bool]) -> None:
if done.cancelled():
_discard_retained_committed_audio()
return
try:
append_ok = done.result()
except Exception:
append_ok = False
if not append_ok:
_discard_retained_committed_audio()
predecessor = actor.native_append_tail
if predecessor is not None and predecessor.done():
try:
@@ -465,6 +490,7 @@ class DuplexSessionRunnerMixin:
# is an explicit retry and starts a new chain.
predecessor = None
task = asyncio.create_task(_run_in_wire_order(predecessor))
task.add_done_callback(_release_cancelled_retained_audio)
actor.native_append_tail = task
actor.track_append_task(
task,
@@ -929,6 +955,8 @@ class DuplexSessionRunnerMixin:
had_native_append = await actor.cancel_append_tasks(
response_bound_only=event_type in {"response.cancel", "output_audio_buffer.clear"},
)
if event_type == "response.cancel":
session.release_input_bytes(native.clear_committed_audio())
had_native_stream = native.data_plane_task is not None
cancelled = await self._cancel_active_response(
session,
@@ -1109,6 +1137,53 @@ class DuplexSessionRunnerMixin:
if turn_event == "conversation.item.create":
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
prepare_function_output = getattr(
self._serving_runtime_adapter,
"runtime_config_for_function_output",
None,
)
if item_type == "function_call_output" and callable(prepare_function_output):
if not await wait_for_native_append_tail():
continue
try:
candidate_runtime_config = prepare_function_output(
item,
dict(session.runtime_config),
)
except ServingRuntimeConfigError as exc:
await emit_event(
{
"type": "error",
"session_id": session.session_id,
"code": exc.code,
"error": str(exc),
}
)
continue
if not await self._signal_runtime_session(
session,
"session.update",
emit_event,
runtime_config=candidate_runtime_config,
):
continue
session.replace_runtime_config(candidate_runtime_config)
await emit_event(
{
"type": "conversation.item.created",
"session_id": session.session_id,
"item": item,
"created": True,
}
)
await self._maybe_continue_native_response(
emit_event,
session=session,
expected_epoch=session.epoch,
expected_model_turn_id=session.turn_id,
)
continue
message = self._realtime_item_to_history_message(item)
item_id = item.get("id") if isinstance(item, dict) else None
if message is not None:
@@ -121,12 +121,15 @@ class DuplexSessionTasks:
]
if not tasks:
return False
cancelled_tail = self.native_append_tail if self.native_append_tail in tasks else None
for task in tasks:
task.cancel()
try:
await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), timeout=timeout_s)
except TimeoutError:
pass
if cancelled_tail is not None and self.native_append_tail is cancelled_tail:
self.native_append_tail = None
return True