duplex-v0 / serving /baseline_client.py
Jr23xd23's picture
RightNow Duplex v0
f730521 verified
Raw History Blame Contribute Delete
3.79 kB
"""Async client for the baseline's released vLLM endpoint.
The request and response handling mirror the released clients
(stepaudior1vllm.py in stepfun-ai/Step-Audio-R1, stepaudio2vllm.py in stepfun-ai/Step-Audio2):
role "human", audio as `input_audio` wav parts of at most 25 s, skip_special_tokens false,
the assistant prefix sent as an unfinished last message, text read from
tts_content.tts_text or content, audio tokens read from tts_content.tts_audio.
Nothing here is guessed; where the released code is silent (how R1.1 is asked to
speak), serving/probe_baseline.py tries the released prefixes and records what comes back.
"""
import base64
import io
import json
import re
import wave
import numpy as np
from duplex.spec import SR
AUDIO_TOKEN = re.compile(r"<audio_(\d+)>")
SPEECH_MARKUP = re.compile(r"<audio_\d+>|<tts_(?:start|end|pad)>")
MAX_CLIP_S = 25.0 # the released client splits longer audio into 25 s parts
def wav_bytes(pcm16, sr=SR):
buf = io.BytesIO()
with wave.open(buf, "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(sr)
w.writeframes(np.asarray(pcm16, dtype="<i2").tobytes())
return buf.getvalue()
def human_turn(pcm16):
"""One caller turn (int16, 16 kHz mono) as a released-format message."""
step = int(MAX_CLIP_S * SR)
parts = [pcm16[i: i + step] for i in range(0, len(pcm16), step)]
return {"role": "human", "content": [
{"type": "input_audio", "input_audio": {"data": base64.b64encode(wav_bytes(p)).decode(), "format": "wav"}} for p in parts
]}
async def stream_chat(http, api_url, model, messages, info=None, **params):
"""Yields (delta, text, audio_tokens) per streamed chunk, as the released client does.
info: a dict that receives "finish_reason" ("stop": the model or a stop string ended it; "length": the token limit)."""
payload = dict(params, model=model, stream=True, skip_special_tokens=False)
last = messages[-1]
if last.get("role") == "assistant" and last.get("content") is None:
messages = messages[:-1]
payload.update(continue_final_message=False, add_generation_prompt=True)
elif last.get("eot", True):
payload.update(continue_final_message=False, add_generation_prompt=True)
else:
payload.update(continue_final_message=True, add_generation_prompt=False)
payload["messages"] = messages
async with http.post(api_url, json=payload) as r:
if r.status != 200:
raise RuntimeError(f"vLLM answered {r.status}: {(await r.text())[:500]}")
async for raw in r.content:
line = raw.decode("utf-8").strip()
if not line.startswith("data: "):
continue
line = line[6:]
if line == "[DONE]":
break
try:
choice = json.loads(line)["choices"][0]
if info is not None and choice.get("finish_reason"):
info["finish_reason"] = choice["finish_reason"]
delta = choice["delta"]
except (ValueError, KeyError, IndexError):
continue
tts = delta.get("tts_content") or {}
content = delta.get("content") or ""
text = tts.get("tts_text")
text = text if text is not None else content
# Measured on 2026-11-30 with the released image and R1.1: tts_content stays empty and the
# audio tokens arrive inside `content`, interleaved with the words (one word piece, four
# audio tokens, with <tts_pad> and <tts_end> markers). So audio is read from both places.
audio = [int(i) for i in AUDIO_TOKEN.findall(tts.get("tts_audio") or content)]
yield delta, SPEECH_MARKUP.sub("", text), audio