[Core] Generalized turn-based /v1/realtime implementation (#8339)
Signed-off-by: Nick Cao <ncao@redhat.com> Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
1 parent
25fb257667
commit
65699fe94c
16 files changed
+716
-799
No files matched your search
@@ -4,8 +4,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Sequence
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from fastapi import WebSocket
|
||||
from vllm.logger import init_logger
|
||||
@@ -13,27 +11,12 @@ from vllm.utils import random_uuid
|
||||
|
||||
from vllm_omni.entrypoints.duplex.warmup import DUPLEX_WARMUP_CLIENT_WAIT_S
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.config.omni_config import BaseVllmOmniStageConfig
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_QWEN3_OMNI_REALTIME_ARCH = "Qwen3OmniMoeForConditionalGeneration"
|
||||
_QWEN3_OMNI_REALTIME_STAGES = {"thinker", "talker", "code2wav"}
|
||||
|
||||
# Keep OpenAI connection imports in the handlers: openai/__init__.py imports
|
||||
# api_server, which imports this module.
|
||||
|
||||
|
||||
def supports_qwen3_omni_realtime(stage_configs: Sequence[BaseVllmOmniStageConfig] | None) -> bool:
|
||||
stages = stage_configs or ()
|
||||
return (
|
||||
len(stages) == len(_QWEN3_OMNI_REALTIME_STAGES)
|
||||
and all(stage.model_config.model_arch == _QWEN3_OMNI_REALTIME_ARCH for stage in stages)
|
||||
and {stage.model_stage for stage in stages} == _QWEN3_OMNI_REALTIME_STAGES
|
||||
)
|
||||
|
||||
|
||||
async def reject_realtime_websocket(websocket: WebSocket, message: str) -> None:
|
||||
await websocket.accept()
|
||||
await websocket.send_json(
|
||||
@@ -52,27 +35,21 @@ async def reject_realtime_websocket(websocket: WebSocket, message: str) -> None:
|
||||
await websocket.close(code=1008)
|
||||
|
||||
|
||||
async def dispatch_generic_realtime_websocket(websocket: WebSocket) -> None:
|
||||
"""Fall back to the generic OpenAI Realtime API for non-Qwen3-Omni models."""
|
||||
serving = getattr(websocket.app.state, "openai_serving_realtime", None)
|
||||
if serving is None:
|
||||
await websocket.accept()
|
||||
await websocket.send_json({"type": "error", "error": "Realtime API is not available", "code": "unsupported"})
|
||||
await websocket.close()
|
||||
return
|
||||
from vllm_omni.entrypoints.openai.realtime_connection import RealtimeConnection
|
||||
|
||||
connection = RealtimeConnection(websocket, serving)
|
||||
await connection.handle_connection()
|
||||
async def _reject_unavailable_realtime_websocket(websocket: WebSocket) -> None:
|
||||
await websocket.accept()
|
||||
await websocket.send_json({"type": "error", "error": "Realtime API is not available", "code": "unsupported"})
|
||||
await websocket.close()
|
||||
|
||||
|
||||
async def dispatch_realtime_websocket(websocket: WebSocket) -> None:
|
||||
"""Handle Realtime sessions not already routed to the proprietary duplex
|
||||
handler by the caller: Qwen3-Omni gets a conformant full-duplex connection,
|
||||
everything else falls back to the generic turn-based Realtime API."""
|
||||
"""Route a turn-based Realtime session to the OpenAI connection handler."""
|
||||
state = websocket.app.state
|
||||
if not supports_qwen3_omni_realtime(getattr(state, "stage_configs", None)):
|
||||
await dispatch_generic_realtime_websocket(websocket)
|
||||
if (
|
||||
getattr(state, "diffusion_engine", None) is not None
|
||||
or getattr(state, "engine_client", None) is None
|
||||
or getattr(state, "openai_serving_chat", None) is None
|
||||
):
|
||||
await _reject_unavailable_realtime_websocket(websocket)
|
||||
return
|
||||
|
||||
model_name = state.openai_serving_models.base_model_paths[0].name
|
||||
@@ -95,14 +72,13 @@ async def dispatch_realtime_websocket(websocket: WebSocket) -> None:
|
||||
DUPLEX_WARMUP_CLIENT_WAIT_S,
|
||||
)
|
||||
|
||||
tokenizer = await state.engine_client.get_tokenizer()
|
||||
from vllm_omni.entrypoints.openai.realtime.connection import OpenAIFullDuplexConnection
|
||||
|
||||
connection = OpenAIFullDuplexConnection(
|
||||
websocket=websocket,
|
||||
engine=state.engine_client,
|
||||
model_name=model_name,
|
||||
tokenizer=tokenizer,
|
||||
chat_handler=state.openai_serving_chat,
|
||||
tool_call_parser=getattr(state.args, "tool_call_parser", None),
|
||||
enable_auto_tool_choice=getattr(state.args, "enable_auto_tool_choice", False),
|
||||
)
|
||||
|
||||
@@ -73,7 +73,6 @@ from vllm.entrypoints.serve.utils.api_utils import (
|
||||
)
|
||||
from vllm.entrypoints.serve.utils.orca_metrics import metrics_header
|
||||
from vllm.entrypoints.serve.utils.request_logger import RequestLogger
|
||||
from vllm.entrypoints.speech_to_text.realtime.serving import OpenAIServingRealtime
|
||||
from vllm.entrypoints.speech_to_text.transcription.serving import (
|
||||
OpenAIServingTranscription,
|
||||
)
|
||||
@@ -692,7 +691,6 @@ async def _init_duplex_app_state(
|
||||
"openai_streaming_speech",
|
||||
"openai_streaming_video",
|
||||
"openai_streaming_video_output",
|
||||
"openai_serving_realtime",
|
||||
"openai_serving_realtime_robot",
|
||||
"anthropic_serving_messages",
|
||||
):
|
||||
@@ -1227,12 +1225,6 @@ async def omni_init_app_state(
|
||||
else None
|
||||
)
|
||||
state.openai_serving_duplex = None
|
||||
state.openai_serving_realtime = OpenAIServingRealtime(
|
||||
engine_client=engine_client,
|
||||
models=state.openai_serving_models,
|
||||
request_logger=request_logger,
|
||||
)
|
||||
|
||||
state.openai_serving_video = OmniOpenAIServingVideo(
|
||||
engine_client,
|
||||
model_name=served_model_names[0] if served_model_names else None,
|
||||
|
||||
@@ -5,10 +5,11 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import binascii
|
||||
import io
|
||||
import json
|
||||
import time
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
import wave
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import numpy as np
|
||||
@@ -21,12 +22,13 @@ from vllm.entrypoints.openai.chat_completion.protocol import (
|
||||
ChatCompletionRequest,
|
||||
ChatCompletionToolsParam,
|
||||
)
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.logger import init_logger
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams, StructuredOutputsParams
|
||||
from vllm.tool_parsers import ToolParserManager
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.inputs import TokensPrompt
|
||||
from vllm.inputs import EngineInput
|
||||
|
||||
from vllm_omni.entrypoints.async_omni import AsyncOmni
|
||||
from vllm_omni.entrypoints.openai.realtime.session import (
|
||||
@@ -37,27 +39,20 @@ from vllm_omni.entrypoints.openai.realtime.session import (
|
||||
_gen_id,
|
||||
merge_session_config,
|
||||
)
|
||||
from vllm_omni.utils.audio import audio_chunk_sample_rate
|
||||
from vllm_omni.utils.audio_resample import StreamingAudioResampler
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_CLIENT_EVENT_ADAPTER = TypeAdapter(types.RealtimeClientEvent)
|
||||
|
||||
# Qwen3-Omni's Realtime contract is mono signed PCM16 at 24 kHz. PCM16 is the
|
||||
# sample width; 24 kHz is the sample rate.
|
||||
# The Realtime PCM contract is mono signed PCM16 at 24 kHz.
|
||||
SAMPLE_RATE_HZ = 24000
|
||||
BYTES_PER_SAMPLE_PCM16 = 2
|
||||
# Application safety caps for one append and the complete pending input turn.
|
||||
MAX_AUDIO_APPEND_BYTES = 15 * 1024 * 1024
|
||||
MAX_INPUT_AUDIO_BUFFER_BYTES = 64 * 1024 * 1024
|
||||
|
||||
# The Qwen3-Omni chat template uses these literal special tokens for audio.
|
||||
# The generic chat-template interface does not expose that placeholder as
|
||||
# metadata, so it cannot be inferred reliably from the Realtime event schema.
|
||||
AUDIO_PLACEHOLDER = "<|audio_start|><|audio_pad|><|audio_end|>"
|
||||
|
||||
# Empirically calibrated for Qwen3-Omni from 8,808 ms / 23 thinker tokens.
|
||||
QWEN3_OMNI_MS_PER_TOKEN = 383.0
|
||||
|
||||
AUTO_TRUNCATION_TRIGGER_RATIO = 0.8
|
||||
AUTO_TRUNCATION_TARGET_RATIO = 0.5
|
||||
|
||||
@@ -85,13 +80,15 @@ class OpenAIFullDuplexConnection:
|
||||
websocket: WebSocket,
|
||||
engine: AsyncOmni,
|
||||
model_name: str,
|
||||
tokenizer: Any,
|
||||
chat_handler: Any,
|
||||
tool_call_parser: str | None = None,
|
||||
enable_auto_tool_choice: bool = False,
|
||||
):
|
||||
self.ws = websocket
|
||||
self.engine = engine
|
||||
self.model_name = model_name
|
||||
self.chat_handler = chat_handler
|
||||
self._tokenizer = chat_handler.renderer.get_tokenizer()
|
||||
self._tool_call_parser_name = tool_call_parser if enable_auto_tool_choice else None
|
||||
|
||||
self.session = AudioFullDuplexSessionState()
|
||||
@@ -102,8 +99,6 @@ class OpenAIFullDuplexConnection:
|
||||
self._response_cancel_event = asyncio.Event()
|
||||
self._send_lock = asyncio.Lock()
|
||||
|
||||
self._tokenizer = self._resolve_tokenizer(tokenizer)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Lifecycle #
|
||||
# ------------------------------------------------------------------ #
|
||||
@@ -140,23 +135,6 @@ class OpenAIFullDuplexConnection:
|
||||
await self._cancel_active_response()
|
||||
logger.info("[realtime] connection closed, session_id=%s", self.session.session_id)
|
||||
|
||||
def _resolve_tokenizer(self, tokenizer: Any) -> Any:
|
||||
if getattr(tokenizer, "chat_template", None):
|
||||
return tokenizer
|
||||
|
||||
input_processor = getattr(self.engine, "input_processor", None)
|
||||
if input_processor is None:
|
||||
return tokenizer
|
||||
try:
|
||||
from vllm.transformers_utils.processor import cached_processor_from_config
|
||||
|
||||
processor = cached_processor_from_config(input_processor.model_config)
|
||||
if getattr(processor, "apply_chat_template", None):
|
||||
return processor
|
||||
except Exception:
|
||||
logger.warning("Could not load processor for chat templating")
|
||||
return tokenizer
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Event dispatch #
|
||||
# ------------------------------------------------------------------ #
|
||||
@@ -332,6 +310,16 @@ class OpenAIFullDuplexConnection:
|
||||
raise ValueError("PCM audio data must contain complete 16-bit samples")
|
||||
return decoded
|
||||
|
||||
@staticmethod
|
||||
def _pcm16_wav_b64(audio: bytes) -> str:
|
||||
with io.BytesIO() as buffer:
|
||||
with wave.open(buffer, "wb") as wav:
|
||||
wav.setnchannels(1)
|
||||
wav.setsampwidth(BYTES_PER_SAMPLE_PCM16)
|
||||
wav.setframerate(SAMPLE_RATE_HZ)
|
||||
wav.writeframes(audio)
|
||||
return base64.b64encode(buffer.getvalue()).decode("ascii")
|
||||
|
||||
async def _commit_audio_buffer(
|
||||
self,
|
||||
event_id: str | None = None,
|
||||
@@ -340,13 +328,12 @@ class OpenAIFullDuplexConnection:
|
||||
s = self.session
|
||||
if len(s.input_audio_buffer) == 0:
|
||||
return None
|
||||
pcm16 = np.frombuffer(bytes(s.input_audio_buffer), dtype=np.int16)
|
||||
audio_f32 = pcm16.astype(np.float32) / 32768.0
|
||||
audio = base64.b64encode(s.input_audio_buffer).decode("ascii")
|
||||
item = types.RealtimeConversationItemUserMessage(
|
||||
type="message",
|
||||
role="user",
|
||||
status="completed",
|
||||
content=[{"type": "input_audio", "audio": self._pcm16_b64(audio_f32)}],
|
||||
content=[{"type": "input_audio", "audio": audio}],
|
||||
)
|
||||
try:
|
||||
s.insert_item(item)
|
||||
@@ -447,37 +434,24 @@ class OpenAIFullDuplexConnection:
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
async def _estimate_total_tokens(
|
||||
async def _prepare_engine_input_with_auto_truncation(
|
||||
self,
|
||||
tools: list | None,
|
||||
response: _ResolvedResponse,
|
||||
*,
|
||||
instructions: str | None = None,
|
||||
items: list[Any] | None = None,
|
||||
) -> int:
|
||||
t0 = time.monotonic()
|
||||
prompt = await self._build_full_prompt(tools=tools, instructions=instructions, items=items)
|
||||
total = len(prompt["prompt_token_ids"])
|
||||
audio_arrays = prompt.get("multi_modal_data", {}).get("audio", [])
|
||||
if audio_arrays:
|
||||
raw_tok = getattr(self._tokenizer, "tokenizer", self._tokenizer)
|
||||
placeholder_len = len(raw_tok.encode(AUDIO_PLACEHOLDER, add_special_tokens=False))
|
||||
for arr, sr in audio_arrays:
|
||||
total += self._qwen3_omni_audio_token_count(arr.shape[0], sr) - placeholder_len
|
||||
elapsed = time.monotonic() - t0
|
||||
if elapsed > 0.05:
|
||||
logger.warning(
|
||||
"[realtime] _estimate_total_tokens took %.3fs (history=%d items, %d audio segments)",
|
||||
elapsed,
|
||||
len(items if items is not None else self.session.items),
|
||||
len(audio_arrays),
|
||||
)
|
||||
return total
|
||||
|
||||
async def _maybe_truncate_history(self, response: _ResolvedResponse) -> bool:
|
||||
preflight_only: bool = False,
|
||||
) -> EngineInput | None:
|
||||
s = self.session
|
||||
max_model_len = getattr(self.engine.model_config, "max_model_len", None)
|
||||
if not max_model_len:
|
||||
return True
|
||||
persistent = response.input is None
|
||||
items: list[Any] = s.items if response.input is None else response.input
|
||||
staged_deletions: list[Any] = []
|
||||
if max_model_len is None:
|
||||
return await self._build_full_prompt(
|
||||
tools=response.tools,
|
||||
instructions=response.instructions,
|
||||
items=items,
|
||||
skip_mm_cache=preflight_only,
|
||||
)
|
||||
|
||||
truncation = s.config.truncation or "auto"
|
||||
ratio = 1.0
|
||||
@@ -503,22 +477,36 @@ class OpenAIFullDuplexConnection:
|
||||
trigger = limit
|
||||
target = limit
|
||||
|
||||
persistent = response.input is None
|
||||
items: list[Any] = s.items if response.input is None else response.input
|
||||
total = await self._estimate_total_tokens(
|
||||
response.tools,
|
||||
# Budget checks are speculative and may render repeatedly while
|
||||
# truncating, so keep them off the shared sender cache. Once accepted,
|
||||
# render again through the normal cache path for engine submission.
|
||||
engine_input = await self._build_full_prompt(
|
||||
tools=response.tools,
|
||||
instructions=response.instructions,
|
||||
items=items,
|
||||
skip_mm_cache=True,
|
||||
)
|
||||
total = len(engine_input["prompt_token_ids"])
|
||||
if total <= trigger:
|
||||
return True
|
||||
if preflight_only:
|
||||
return engine_input
|
||||
return await self._build_full_prompt(
|
||||
tools=response.tools,
|
||||
instructions=response.instructions,
|
||||
items=items,
|
||||
)
|
||||
if mode == "disabled":
|
||||
logger.warning(
|
||||
"[realtime] token budget exceeded (%d/%d) and truncation is disabled -- rejecting response.create",
|
||||
total,
|
||||
limit,
|
||||
)
|
||||
return False
|
||||
return None
|
||||
|
||||
if persistent:
|
||||
# Preflight truncation is speculative. Work on a snapshot so a
|
||||
# rejected response.create does not delete items from session history.
|
||||
items = list(items)
|
||||
|
||||
idx = 0
|
||||
while total > target and idx < len(items):
|
||||
@@ -547,23 +535,36 @@ class OpenAIFullDuplexConnection:
|
||||
for remove_idx in sorted(remove_indexes, reverse=True):
|
||||
removed = items[remove_idx]
|
||||
if persistent:
|
||||
s.remove_item(removed.id)
|
||||
await self._send_event(
|
||||
types.ConversationItemDeletedEvent(
|
||||
event_id=_gen_id("evt"),
|
||||
type="conversation.item.deleted",
|
||||
item_id=removed.id,
|
||||
)
|
||||
)
|
||||
else:
|
||||
del items[remove_idx]
|
||||
total = await self._estimate_total_tokens(
|
||||
response.tools,
|
||||
staged_deletions.append(removed)
|
||||
del items[remove_idx]
|
||||
engine_input = await self._build_full_prompt(
|
||||
tools=response.tools,
|
||||
instructions=response.instructions,
|
||||
items=items,
|
||||
skip_mm_cache=True,
|
||||
)
|
||||
total = len(engine_input["prompt_token_ids"])
|
||||
|
||||
return total <= limit
|
||||
if total > limit:
|
||||
return None
|
||||
if preflight_only:
|
||||
return engine_input
|
||||
engine_input = await self._build_full_prompt(
|
||||
tools=response.tools,
|
||||
instructions=response.instructions,
|
||||
items=items,
|
||||
)
|
||||
for removed in staged_deletions:
|
||||
if removed.id is None or s.remove_item(removed.id) is None:
|
||||
continue
|
||||
await self._send_event(
|
||||
types.ConversationItemDeletedEvent(
|
||||
event_id=_gen_id("evt"),
|
||||
type="conversation.item.deleted",
|
||||
item_id=removed.id,
|
||||
)
|
||||
)
|
||||
return engine_input
|
||||
|
||||
async def _handle_response_create(self, event: types.ResponseCreateEvent):
|
||||
s = self.session
|
||||
@@ -582,7 +583,16 @@ class OpenAIFullDuplexConnection:
|
||||
await self._send_error(str(exc), "invalid_request_error", event_id=event.event_id)
|
||||
return
|
||||
|
||||
if not await self._maybe_truncate_history(response):
|
||||
had_active_response = s.active_response is not None
|
||||
try:
|
||||
engine_input = await self._prepare_engine_input_with_auto_truncation(
|
||||
response,
|
||||
preflight_only=had_active_response,
|
||||
)
|
||||
except VLLMValidationError as exc:
|
||||
await self._send_error(str(exc), "invalid_request_error", event_id=event.event_id)
|
||||
return
|
||||
if engine_input is None:
|
||||
await self._send_error(
|
||||
"The response input exceeds the model's input token limit",
|
||||
"invalid_request_error",
|
||||
@@ -590,6 +600,22 @@ class OpenAIFullDuplexConnection:
|
||||
)
|
||||
return
|
||||
|
||||
if had_active_response:
|
||||
if s.active_response is not None:
|
||||
await self._cancel_active_response()
|
||||
try:
|
||||
engine_input = await self._prepare_engine_input_with_auto_truncation(response)
|
||||
except VLLMValidationError as exc:
|
||||
await self._send_error(str(exc), "invalid_request_error", event_id=event.event_id)
|
||||
return
|
||||
if engine_input is None:
|
||||
await self._send_error(
|
||||
"The response input exceeds the model's input token limit",
|
||||
"invalid_request_error",
|
||||
event_id=event.event_id,
|
||||
)
|
||||
return
|
||||
|
||||
response_id = _gen_id("resp")
|
||||
await self._send_event(
|
||||
types.ResponseCreatedEvent(
|
||||
@@ -599,13 +625,10 @@ class OpenAIFullDuplexConnection:
|
||||
)
|
||||
)
|
||||
|
||||
if s.active_response is not None:
|
||||
await self._cancel_active_response()
|
||||
|
||||
s.active_response = ActiveResponse(response_id=response_id, request_id=f"rt-{response_id}")
|
||||
|
||||
self._response_cancel_event.clear()
|
||||
self._response_task = asyncio.create_task(self._run_response(response_id, response))
|
||||
self._response_task = asyncio.create_task(self._run_response(response_id, response, engine_input))
|
||||
|
||||
def _response_object(
|
||||
self,
|
||||
@@ -630,7 +653,12 @@ class OpenAIFullDuplexConnection:
|
||||
usage=usage,
|
||||
)
|
||||
|
||||
async def _run_response(self, response_id: str, response: _ResolvedResponse):
|
||||
async def _run_response(
|
||||
self,
|
||||
response_id: str,
|
||||
response: _ResolvedResponse,
|
||||
engine_input: EngineInput,
|
||||
):
|
||||
s = self.session
|
||||
active = s.active_response
|
||||
if active is None:
|
||||
@@ -638,7 +666,7 @@ class OpenAIFullDuplexConnection:
|
||||
|
||||
completed = False
|
||||
try:
|
||||
await self._run_response_inner(response_id, response, s, active)
|
||||
await self._run_response_inner(response_id, response, s, active, engine_input)
|
||||
completed = True
|
||||
except asyncio.CancelledError:
|
||||
if self._response_cancel_event.is_set():
|
||||
@@ -716,17 +744,11 @@ class OpenAIFullDuplexConnection:
|
||||
except Exception:
|
||||
logger.debug("Failed to send failure response.done for %s", response_id, exc_info=True)
|
||||
|
||||
async def _run_response_inner(self, response_id, response, s, active):
|
||||
async def _run_response_inner(self, response_id, response, s, active, engine_input: EngineInput):
|
||||
previous_item_id = s.items[-1].id if s.items else None
|
||||
modalities = response.modalities
|
||||
is_audio = "audio" in modalities
|
||||
tools, tool_choice = response.tools, response.tool_choice
|
||||
prompt = await self._build_full_prompt(
|
||||
tools=tools,
|
||||
instructions=response.instructions,
|
||||
items=response.input,
|
||||
)
|
||||
|
||||
item_id = _gen_id("item")
|
||||
active.item_id = item_id
|
||||
output_index = 0
|
||||
@@ -804,12 +826,13 @@ class OpenAIFullDuplexConnection:
|
||||
limit_reached = False
|
||||
usage = ResponseUsage()
|
||||
total_audio_samples = 0
|
||||
audio_resampler: StreamingAudioResampler | None = None
|
||||
|
||||
previous_text = ""
|
||||
previous_token_ids: list[int] = []
|
||||
pending_tool_calls: dict[int, dict[str, Any]] = {}
|
||||
next_output_index = 1 # 0 is the message item, reserved above
|
||||
# Qwen's talker speaks tool markup, so stop audio after detecting a call.
|
||||
# Tool-call markup is control output, so suppress its audio after detection.
|
||||
tool_call_seen = False
|
||||
|
||||
async def emit_content_delta(piece: str) -> None:
|
||||
@@ -843,6 +866,26 @@ class OpenAIFullDuplexConnection:
|
||||
)
|
||||
)
|
||||
|
||||
async def emit_audio_delta(chunk: np.ndarray) -> None:
|
||||
nonlocal total_audio_samples
|
||||
if not chunk.size:
|
||||
return
|
||||
# Honor the requested modality and suppress audio after a tool call.
|
||||
if not is_audio or tool_call_seen:
|
||||
return
|
||||
total_audio_samples += chunk.shape[0]
|
||||
await self._send_event(
|
||||
types.ResponseAudioDeltaEvent(
|
||||
event_id=_gen_id("evt"),
|
||||
type="response.output_audio.delta",
|
||||
response_id=response_id,
|
||||
item_id=item_id,
|
||||
output_index=output_index,
|
||||
content_index=content_index,
|
||||
delta=self._pcm16_b64(chunk),
|
||||
)
|
||||
)
|
||||
|
||||
async def handle_tool_parser_delta(delta_msg) -> None:
|
||||
nonlocal next_output_index, tool_call_seen
|
||||
if delta_msg is None:
|
||||
@@ -911,8 +954,11 @@ class OpenAIFullDuplexConnection:
|
||||
sp.structured_outputs = StructuredOutputsParams(structural_tag=structural_tag_json)
|
||||
thinker_params_configured = True
|
||||
|
||||
sampling_params_list = self.chat_handler._fix_minicpmo45_audio_stream_output_kinds(
|
||||
sampling_params_list, modalities
|
||||
)
|
||||
gen = self.engine.generate(
|
||||
prompt=prompt,
|
||||
prompt=engine_input,
|
||||
request_id=active.request_id,
|
||||
sampling_params_list=sampling_params_list,
|
||||
output_modalities=modalities,
|
||||
@@ -927,31 +973,14 @@ class OpenAIFullDuplexConnection:
|
||||
output_type = getattr(output, "final_output_type", "text")
|
||||
if output_type == "audio":
|
||||
audio_chunks = self._extract_audio_deltas(output)
|
||||
for chunk in audio_chunks:
|
||||
total_audio_samples += chunk.shape[0]
|
||||
# is_audio guard is defense-in-depth: generate() is
|
||||
# now given output_modalities=modalities above, so
|
||||
# the engine shouldn't produce audio-typed output
|
||||
# for a text-only response -- but don't rely on
|
||||
# that alone to honor the client's explicit
|
||||
# request; never flip session state or forward
|
||||
# audio it didn't ask for.
|
||||
if not is_audio:
|
||||
continue
|
||||
if tool_call_seen:
|
||||
continue
|
||||
b64 = self._pcm16_b64(chunk)
|
||||
await self._send_event(
|
||||
types.ResponseAudioDeltaEvent(
|
||||
event_id=_gen_id("evt"),
|
||||
type="response.output_audio.delta",
|
||||
response_id=response_id,
|
||||
item_id=item_id,
|
||||
output_index=output_index,
|
||||
content_index=content_index,
|
||||
delta=b64,
|
||||
if audio_chunks:
|
||||
if audio_resampler is None:
|
||||
audio_resampler = StreamingAudioResampler(
|
||||
audio_chunk_sample_rate(output),
|
||||
SAMPLE_RATE_HZ,
|
||||
)
|
||||
)
|
||||
for chunk in audio_chunks:
|
||||
await emit_audio_delta(audio_resampler.process(chunk))
|
||||
continue
|
||||
|
||||
if output.outputs:
|
||||
@@ -966,11 +995,8 @@ class OpenAIFullDuplexConnection:
|
||||
delta_text = first_out.text or ""
|
||||
delta_token_ids = list(first_out.token_ids)
|
||||
usage.output_tokens += len(delta_token_ids)
|
||||
# Raw thinker token stream, in talker-consumption order --
|
||||
# this is what _qwen3_omni_truncate_transcript correlates
|
||||
# against codec frames, independent of any tool-parser
|
||||
# stripping applied to full_text/full_transcript below
|
||||
# (the talker speaks the raw stream, tool tags included).
|
||||
# Keep the raw token stream for approximate transcript
|
||||
# truncation, independent of any tool-parser stripping.
|
||||
full_token_ids.extend(delta_token_ids)
|
||||
|
||||
if output.prompt_token_ids:
|
||||
@@ -1021,6 +1047,10 @@ class OpenAIFullDuplexConnection:
|
||||
if self._response_cancel_event.is_set():
|
||||
cancelled = True
|
||||
|
||||
if audio_resampler is not None and not cancelled:
|
||||
tail = audio_resampler.process(np.empty(0, dtype=np.float32), final=True)
|
||||
await emit_audio_delta(tail)
|
||||
|
||||
status = "cancelled" if cancelled else "incomplete" if limit_reached else "completed"
|
||||
|
||||
if is_audio:
|
||||
@@ -1170,11 +1200,9 @@ class OpenAIFullDuplexConnection:
|
||||
s.item_duration_ms[item_obj.id] = total_audio_samples / SAMPLE_RATE_HZ * 1000
|
||||
# Skip storing for tool-call responses: full_token_ids is
|
||||
# the raw thinker stream (tool-call tags included), but
|
||||
# this item's transcript/text is the tool-parser-stripped
|
||||
# content -- the two no longer line up token-for-token,
|
||||
# so _qwen3_omni_truncate_transcript falls back to
|
||||
# blanking (today's behavior) rather than risk splicing
|
||||
# raw <tool_call> text into a truncated transcript.
|
||||
# this item's transcript/text is tool-parser-stripped,
|
||||
# so truncation falls back to a blank transcript rather
|
||||
# than splice raw tool markup into it.
|
||||
if not pending_tool_calls:
|
||||
s.item_token_ids[item_obj.id] = full_token_ids
|
||||
await self._send_conversation_item_added_and_done(history_item, previous_item_id)
|
||||
@@ -1488,16 +1516,10 @@ class OpenAIFullDuplexConnection:
|
||||
)
|
||||
return
|
||||
|
||||
# Per spec, truncating audio must not leave text in context the user
|
||||
# never heard -- but rather than blanking the transcript entirely
|
||||
# (the previous, spec-minimum behavior), reconstruct the prefix that
|
||||
# *was* actually heard using Qwen3-Omni's fixed talker text/frame
|
||||
# correlation (see _qwen3_omni_truncate_transcript). This keeps the
|
||||
# model's own memory of what it said in sync with what the user
|
||||
# actually heard, instead of wiping it and confusing later turns.
|
||||
# Falls back to "" (today's behavior) when we don't have a captured
|
||||
# token stream for this item (e.g. it included a tool call).
|
||||
truncated_text = self._qwen3_omni_truncate_transcript(item_id, audio_end_ms)
|
||||
# Preserve only the transcript prefix proportional to the audio heard.
|
||||
# Exact token/audio alignment is model-specific, so fall back to an
|
||||
# empty transcript when token IDs or duration are unavailable.
|
||||
truncated_text = self._truncate_transcript(item_id, audio_end_ms)
|
||||
part = new_content[content_index]
|
||||
if hasattr(part, "transcript"):
|
||||
new_content[content_index] = {
|
||||
@@ -1602,45 +1624,33 @@ class OpenAIFullDuplexConnection:
|
||||
resolved.append(referenced)
|
||||
return resolved
|
||||
|
||||
def _qwen3_omni_truncate_transcript(self, item_id: str, audio_end_ms: float) -> str:
|
||||
"""Approximate the transcript heard before ``audio_end_ms``."""
|
||||
def _truncate_transcript(self, item_id: str, audio_end_ms: float) -> str:
|
||||
"""Estimate the transcript prefix heard before ``audio_end_ms``."""
|
||||
token_ids = self.session.item_token_ids.get(item_id)
|
||||
if not token_ids:
|
||||
duration_ms = self.session.item_duration_ms.get(item_id)
|
||||
if not token_ids or duration_ms is None or duration_ms <= 0:
|
||||
return ""
|
||||
tokens_heard = round(audio_end_ms / QWEN3_OMNI_MS_PER_TOKEN)
|
||||
tokens_heard = min(tokens_heard, len(token_ids))
|
||||
tokens_heard = int(len(token_ids) * audio_end_ms / duration_ms)
|
||||
if tokens_heard <= 0:
|
||||
return ""
|
||||
raw_tok = getattr(self._tokenizer, "tokenizer", self._tokenizer)
|
||||
return raw_tok.decode(token_ids[:tokens_heard], skip_special_tokens=True)
|
||||
|
||||
@staticmethod
|
||||
def _qwen3_omni_audio_token_count(num_samples: int, sample_rate: int) -> int:
|
||||
"""Return Qwen3-Omni's expanded token count for an audio segment."""
|
||||
from vllm.model_executor.models.qwen3_omni_moe_thinker import (
|
||||
_get_feat_extract_output_lengths,
|
||||
)
|
||||
|
||||
num_samples_16k = round(num_samples * 16000 / sample_rate)
|
||||
input_lengths = num_samples_16k // 160
|
||||
output_lengths = _get_feat_extract_output_lengths(input_lengths)
|
||||
return int(output_lengths) + 2 # + <|audio_start|> + <|audio_end|>
|
||||
|
||||
async def _build_full_prompt(
|
||||
self,
|
||||
tools: list | None = None,
|
||||
*,
|
||||
instructions: str | None = None,
|
||||
items: list | None = None,
|
||||
) -> TokensPrompt:
|
||||
"""Render the effective instructions and items into an engine prompt."""
|
||||
from vllm.inputs import TokensPrompt
|
||||
skip_mm_cache: bool = False,
|
||||
) -> EngineInput:
|
||||
"""Render the effective conversation through normal chat preprocessing."""
|
||||
chat_handler = self.chat_handler
|
||||
|
||||
s = self.session
|
||||
effective_instructions = instructions if instructions is not None else s.config.instructions
|
||||
effective_items = items if items is not None else s.items
|
||||
messages: list[dict[str, Any]] = []
|
||||
audio_arrays: list[tuple[np.ndarray, int]] = []
|
||||
converted_tools = self._convert_tools(tools) if tools else None
|
||||
|
||||
if effective_instructions:
|
||||
@@ -1648,11 +1658,7 @@ class OpenAIFullDuplexConnection:
|
||||
|
||||
for item in effective_items:
|
||||
if item.type == "function_call":
|
||||
# "" not None: this model's chat template only handles
|
||||
# message.content as a string or a list (line 55/59 of its
|
||||
# Jinja template unconditionally iterates non-string content
|
||||
# assuming it's a list) -- None crashes with "'NoneType'
|
||||
# object is not iterable" (confirmed in production logs).
|
||||
# Some chat templates iterate message content unconditionally.
|
||||
messages.append(
|
||||
{
|
||||
"role": "assistant",
|
||||
@@ -1673,17 +1679,23 @@ class OpenAIFullDuplexConnection:
|
||||
|
||||
role = getattr(item, "role", None)
|
||||
if role == "user":
|
||||
parts_text = []
|
||||
content = []
|
||||
for part in item.content:
|
||||
if part.type == "input_audio" and part.audio:
|
||||
parts_text.append(AUDIO_PLACEHOLDER)
|
||||
audio_bytes = self._decode_pcm16(part.audio, MAX_INPUT_AUDIO_BUFFER_BYTES)
|
||||
pcm16 = np.frombuffer(audio_bytes, dtype=np.int16)
|
||||
audio_arrays.append((pcm16.astype(np.float32) / 32768.0, SAMPLE_RATE_HZ))
|
||||
content.append(
|
||||
{
|
||||
"type": "input_audio",
|
||||
"input_audio": {
|
||||
"data": self._pcm16_wav_b64(audio_bytes),
|
||||
"format": "wav",
|
||||
},
|
||||
}
|
||||
)
|
||||
elif part.type == "input_text" and part.text:
|
||||
parts_text.append(part.text)
|
||||
if parts_text:
|
||||
messages.append({"role": "user", "content": "".join(parts_text)})
|
||||
content.append({"type": "text", "text": part.text})
|
||||
if content:
|
||||
messages.append({"role": "user", "content": content})
|
||||
elif role == "assistant":
|
||||
text = self._assistant_item_text(item)
|
||||
if text:
|
||||
@@ -1693,21 +1705,24 @@ class OpenAIFullDuplexConnection:
|
||||
if text:
|
||||
messages.append({"role": "system", "content": text})
|
||||
|
||||
chat_template_kwargs: dict[str, Any] = {
|
||||
"tokenize": False,
|
||||
"add_generation_prompt": True,
|
||||
"add_special_tokens": False,
|
||||
}
|
||||
if converted_tools:
|
||||
chat_template_kwargs["tools"] = converted_tools
|
||||
text = self._tokenizer.apply_chat_template(messages, **chat_template_kwargs)
|
||||
raw_tok = getattr(self._tokenizer, "tokenizer", self._tokenizer)
|
||||
token_ids = raw_tok.encode(text, add_special_tokens=False)
|
||||
|
||||
prompt_data = TokensPrompt(prompt_token_ids=token_ids)
|
||||
if audio_arrays:
|
||||
prompt_data["multi_modal_data"] = {"audio": audio_arrays}
|
||||
return prompt_data
|
||||
request = ChatCompletionRequest(model=self.model_name, messages=messages)
|
||||
tok_params = replace(
|
||||
request.build_tok_params(self.engine.model_config),
|
||||
max_total_tokens=None,
|
||||
)
|
||||
_, (engine_input,) = await chat_handler._preprocess_chat(
|
||||
request,
|
||||
messages,
|
||||
default_template=request.chat_template or chat_handler.chat_template,
|
||||
default_template_content_format=chat_handler.chat_template_content_format,
|
||||
default_template_kwargs=chat_handler._effective_chat_template_kwargs(request),
|
||||
tool_dicts=converted_tools,
|
||||
tok_params=tok_params,
|
||||
skip_mm_cache=skip_mm_cache,
|
||||
)
|
||||
if engine_input.get("prompt_token_ids") is None:
|
||||
raise RuntimeError("Realtime renderer did not return prompt token IDs")
|
||||
return engine_input
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Audio output processing #
|
||||
|
||||
@@ -1,229 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
from collections.abc import AsyncGenerator, Mapping
|
||||
from typing import cast
|
||||
from uuid import uuid4
|
||||
|
||||
import numpy as np
|
||||
from vllm.entrypoints.serve.engine.protocol import UsageInfo
|
||||
from vllm.entrypoints.speech_to_text.realtime.connection import RealtimeConnection as VllmRealtimeConnection
|
||||
from vllm.entrypoints.speech_to_text.realtime.protocol import TranscriptionDelta, TranscriptionDone
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.entrypoints.async_omni import AsyncOmni
|
||||
from vllm_omni.entrypoints.utils import coerce_param_message_types
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class RealtimeConnection(VllmRealtimeConnection):
|
||||
"""Omni realtime connection with audio-only server events.
|
||||
|
||||
Reuses upstream vLLM websocket/session lifecycle and only customizes
|
||||
generation output handling to emit audio deltas.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.engine = cast(AsyncOmni, self.serving.engine_client)
|
||||
self._realtime_audio_ref: np.ndarray | None = None
|
||||
|
||||
async def start_generation(self):
|
||||
await super().start_generation()
|
||||
|
||||
@staticmethod
|
||||
def _tensor_to_numpy(value) -> np.ndarray | None:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, np.ndarray):
|
||||
arr = value
|
||||
elif hasattr(value, "detach"):
|
||||
arr = value.detach().float().cpu().numpy()
|
||||
else:
|
||||
try:
|
||||
arr = np.asarray(value)
|
||||
except Exception:
|
||||
return None
|
||||
if arr.ndim > 1:
|
||||
arr = arr.reshape(-1)
|
||||
return arr.astype(np.float32, copy=False)
|
||||
|
||||
@staticmethod
|
||||
def _numpy_audio_prefix_match(prev: np.ndarray, curr: np.ndarray) -> bool:
|
||||
n = prev.shape[0]
|
||||
if n == 0:
|
||||
return True
|
||||
if curr.shape[0] < n:
|
||||
return False
|
||||
return bool(np.allclose(curr[:n], prev, rtol=1e-3, atol=2e-4))
|
||||
|
||||
def _raw_waveform_to_deltas(self, arr: np.ndarray) -> list[np.ndarray]:
|
||||
"""Convert one streaming PCM f32 chunk into incremental piece(s) for the client.
|
||||
|
||||
Some engine paths emit a growing cumulative waveform each step; others emit
|
||||
true per-step deltas. We support both without duplicating audio on the client.
|
||||
"""
|
||||
if arr.size == 0:
|
||||
return []
|
||||
ref = self._realtime_audio_ref
|
||||
if ref is None:
|
||||
self._realtime_audio_ref = arr.copy()
|
||||
return [arr]
|
||||
if self._numpy_audio_prefix_match(ref, arr):
|
||||
delta = arr[ref.shape[0] :]
|
||||
self._realtime_audio_ref = arr.copy()
|
||||
return [delta] if delta.size > 0 else []
|
||||
# True per-step delta (not a prefix extension of what we have seen).
|
||||
self._realtime_audio_ref = np.concatenate([ref, arr])
|
||||
return [arr]
|
||||
|
||||
def _extract_audio_chunks(self, output) -> tuple[list[np.ndarray], int]:
|
||||
mm = getattr(output, "multimodal_output", None)
|
||||
if mm is None:
|
||||
return [], 24000
|
||||
# Support both MultimodalPayload and plain dict
|
||||
if not isinstance(mm, Mapping):
|
||||
return [], 24000
|
||||
|
||||
sr = mm.get("sr") or mm.get("sample_rate") or mm.get("audio_sample_rate") or 24000
|
||||
if isinstance(sr, (list, tuple)) and sr:
|
||||
sr = sr[-1]
|
||||
if hasattr(sr, "item"):
|
||||
sr = sr.item()
|
||||
sample_rate_hz = int(sr)
|
||||
key = "audio" if "audio" in mm else ("model_outputs" if "model_outputs" in mm else None)
|
||||
if key is None:
|
||||
return [], sample_rate_hz
|
||||
|
||||
raw_audio = mm.get(key)
|
||||
chunks: list[np.ndarray] = []
|
||||
if isinstance(raw_audio, (list, tuple)):
|
||||
if len(raw_audio) > 0:
|
||||
arr = self._tensor_to_numpy(raw_audio[-1])
|
||||
if arr is not None and arr.size > 0:
|
||||
chunks.extend(self._raw_waveform_to_deltas(arr))
|
||||
else:
|
||||
arr = self._tensor_to_numpy(raw_audio)
|
||||
if arr is not None and arr.size > 0:
|
||||
chunks.extend(self._raw_waveform_to_deltas(arr))
|
||||
return chunks, sample_rate_hz
|
||||
|
||||
@staticmethod
|
||||
def _pcm16_b64(audio_f32: np.ndarray) -> str:
|
||||
clipped = np.clip(audio_f32, -1.0, 1.0)
|
||||
pcm16 = (clipped * 32767.0).astype(np.int16)
|
||||
return base64.b64encode(pcm16.tobytes()).decode("utf-8")
|
||||
|
||||
async def _run_generation(
|
||||
self,
|
||||
streaming_input_gen: AsyncGenerator,
|
||||
input_stream: asyncio.Queue[list[int]],
|
||||
):
|
||||
request_id = f"rt-{self.connection_id}-{uuid4()}"
|
||||
sent_audio = False
|
||||
audio_done_sent = False
|
||||
full_text = ""
|
||||
prompt_token_ids_len = 0
|
||||
completion_tokens_len = 0
|
||||
self._realtime_audio_ref = None
|
||||
|
||||
# Coerce cumulative outputs to delta outputs; this ensures
|
||||
# we don't emit redundant MM data & drain after emitting.
|
||||
sampling_params_list = list(self.engine.default_sampling_params_list)
|
||||
sampling_params_list = coerce_param_message_types(
|
||||
sampling_params_list,
|
||||
is_streaming=True,
|
||||
)
|
||||
|
||||
result_gen = None
|
||||
try:
|
||||
result_gen = self.engine.generate(
|
||||
prompt=streaming_input_gen,
|
||||
request_id=request_id,
|
||||
sampling_params_list=sampling_params_list,
|
||||
)
|
||||
|
||||
async for output in result_gen:
|
||||
stage_id = getattr(output, "stage_id", None)
|
||||
if stage_id == 0 and output.outputs:
|
||||
first_output = output.outputs[0]
|
||||
new_token_ids = list(first_output.token_ids)
|
||||
if new_token_ids:
|
||||
input_stream.put_nowait(new_token_ids)
|
||||
|
||||
if output.prompt_token_ids:
|
||||
prompt_token_ids_len = max(
|
||||
prompt_token_ids_len,
|
||||
len(output.prompt_token_ids),
|
||||
)
|
||||
|
||||
delta_text = first_output.text or ""
|
||||
full_text += delta_text
|
||||
completion_tokens_len += len(new_token_ids)
|
||||
|
||||
if delta_text:
|
||||
await self.send(TranscriptionDelta(delta=delta_text))
|
||||
|
||||
audio_chunks, sample_rate = self._extract_audio_chunks(output)
|
||||
|
||||
for chunk in audio_chunks:
|
||||
sent_audio = True
|
||||
await self.send_json(
|
||||
{
|
||||
"type": "response.output_audio.delta",
|
||||
"audio": self._pcm16_b64(chunk),
|
||||
"format": "pcm16",
|
||||
"sample_rate_hz": sample_rate,
|
||||
}
|
||||
)
|
||||
|
||||
if not self._is_connected:
|
||||
break
|
||||
|
||||
usage = UsageInfo(
|
||||
prompt_tokens=prompt_token_ids_len,
|
||||
completion_tokens=completion_tokens_len,
|
||||
total_tokens=prompt_token_ids_len + completion_tokens_len,
|
||||
)
|
||||
await self.send(TranscriptionDone(text=full_text, usage=usage))
|
||||
|
||||
if sent_audio:
|
||||
await self.send_json({"type": "response.output_audio.done", "has_audio": True})
|
||||
audio_done_sent = True
|
||||
except Exception as e:
|
||||
logger.exception("Error in generation: %s", e)
|
||||
await self.send_error(str(e), "processing_error")
|
||||
finally:
|
||||
# Close the generator explicitly so AsyncOmni.generate's cleanup
|
||||
# (input-pump cancellation and engine-side abort) runs now rather
|
||||
# than whenever the event loop garbage-collects the async
|
||||
# generator; the delay window is where a disconnected session
|
||||
# keeps cycling through the stages (issue #4271).
|
||||
if result_gen is not None:
|
||||
try:
|
||||
await result_gen.aclose()
|
||||
except Exception:
|
||||
logger.exception("Failed to close realtime result generator")
|
||||
# Always send terminal event so clients don't hang forever.
|
||||
if self._is_connected and not audio_done_sent:
|
||||
try:
|
||||
await self.send_json({"type": "response.output_audio.done", "has_audio": sent_audio})
|
||||
except Exception:
|
||||
logger.exception("Failed to send response.output_audio.done")
|
||||
while not self.audio_queue.empty():
|
||||
self.audio_queue.get_nowait()
|
||||
|
||||
async def send_json(self, payload: dict):
|
||||
try:
|
||||
await self.websocket.send_text(json.dumps(payload))
|
||||
except Exception:
|
||||
# A failed send means the client is gone; flag it so the
|
||||
# generation loop stops instead of retrying into a dead socket.
|
||||
self._is_connected = False
|
||||
raise
|
||||
@@ -105,6 +105,7 @@ from vllm.parser.mistral import MistralToolCall
|
||||
from vllm.reasoning import ReasoningParser
|
||||
from vllm.renderers import BaseRenderer, merge_kwargs
|
||||
from vllm.renderers.inputs import TokPrompt
|
||||
from vllm.renderers.params import TokenizeParams
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
from vllm.tokenizers import TokenizerLike
|
||||
from vllm.tokenizers import TokenizerLike as AnyTokenizer
|
||||
@@ -977,6 +978,8 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
continue_final_message: bool = False,
|
||||
documents: list[dict[str, str]] | None = None,
|
||||
add_special_tokens: bool = False,
|
||||
tok_params: TokenizeParams | None = None,
|
||||
skip_mm_cache: bool = False,
|
||||
) -> tuple[list[ConversationMessage], list[TokPrompt]]:
|
||||
if renderer is None:
|
||||
renderer = self.renderer
|
||||
@@ -995,7 +998,8 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
),
|
||||
)
|
||||
|
||||
tok_params = request.build_tok_params(self.model_config)
|
||||
if tok_params is None:
|
||||
tok_params = request.build_tok_params(self.model_config)
|
||||
mm_config = self.model_config.multimodal_config
|
||||
chat_params = request.build_chat_params(
|
||||
default_template,
|
||||
@@ -1020,6 +1024,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
prompt_extras={
|
||||
k: v for k in ("mm_processor_kwargs", "cache_salt") if (v := getattr(request, k, None)) is not None
|
||||
},
|
||||
skip_mm_cache=skip_mm_cache,
|
||||
)
|
||||
|
||||
tokenizer = renderer.get_tokenizer()
|
||||
|
||||
Reference in new issue
Block a user