File size: 34,262 Bytes
f730521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
"""Full-duplex WebSocket endpoint in front of the baseline's vLLM server.

Client -> server
  text   {"type": "session.start", "system_prompt": "...", "endpointing": "controller" | "vad" | "manual"}
  binary one 80 ms frame: 1280 samples, 16 kHz mono, 16-bit little-endian (2560 bytes)
  text   {"type": "input.commit"}     end the caller's turn now (used with "manual")
  text   {"type": "session.end"}

Server -> client
  text   session.started, reply.start, transcript.delta, reply.audio.first, reply.done, control, error
  binary one 80 ms frame of reply audio: 1920 samples, 24 kHz mono, 16-bit little-endian

The clock is the caller's audio: for every frame that comes in, at most one frame of
reply audio goes out. So the reply plays in real time, a STOP cuts it within one frame,
and the controller sees the model's own audio exactly as the caller hears it.

Who decides when to speak ("endpointing"):
  controller  the trained controller: START begins the reply, STOP cuts it off, WAIT
              holds, BACKCHANNEL does not interrupt.
  vad         no controller: energy threshold, START after a fixed silence, STOP on any
              240 ms of caller speech (the plain baseline to compare against).
  manual      only input.commit starts a reply (used to measure the model alone).
  judge       240 ms into a silence the reply is started speculatively and kept silent, and
              the baseline itself is asked whether the caller has finished (serving/judge.py).
              "yes" lets the reply be heard; if the caller goes on, the reply is withdrawn
              unheard; after --judge-timeout-ms of silence it is heard anyway. A loaded
              controller is used for STOP against BACKCHANNEL only.

Third run (docs/numbers.md), with --think-first. The first two cost accuracy and are off by default;
--lead-in is part of the final configuration; --keep-interrupted was not measured.
  --carry-thought   a withdrawn reply leaves its reasoning for the next one;
  --listen-think    the baseline also reasons while the caller is still speaking;
  --keep-interrupted  a reply the caller cut in on stays in the conversation (their question
                      and the part of the answer that was played).
  --lead-in         once a reasoning reply may be heard, the baseline says one short sentence
                    ("let me work that out") while the reasoning goes on; the answer follows it.
                    reply.audio.first is then the lead-in, reply.answer.first the answer.

  python -m serving.server --reply-prefix '<tts_start>' --step-audio2-dir /src/Step-Audio2 \
      --token2wav-dir /models/Step-Audio-2-mini/token2wav --prompt-wav prompt.wav \
      --encoder-ckpt runs/encoder/final.pt --controller-ckpt runs/controller/final.pt
"""
import argparse
import asyncio
import json
import time
from concurrent.futures import ThreadPoolExecutor

import aiohttp
import numpy as np
from aiohttp import web
from scipy.signal import resample_poly

from duplex.spec import BACKCHANNEL, FRAME, LABELS, OUT_FRAME, OUT_SR, SR, START, STOP, WAIT
from serving.baseline_client import human_turn, stream_chat
from serving.judge import judge_finished
from serving.listen_think import Thought

IN_BYTES, OUT_BYTES = FRAME * 2, OUT_FRAME * 2
SILENT = np.zeros(FRAME, dtype=np.float32)
THINK_OPEN, THINK_CLOSE = "<think>" + chr(10), "</think>"      # the baseline's reasoning block, as its chat template opens it
JUDGE_AT = 3             # frames of quiet (240 ms) at which the judge is asked and a reply is started speculatively
ONSET_GAP = 5           # frames of quiet (400 ms) after which caller speech counts as a new onset
MIN_VOICED = 3           # frames of caller speech (240 ms) needed before a reply may start
# --lead-in: what the baseline is told when it is asked to say something while the real reply is still reasoning
LEAD_IN = ("The caller has just finished speaking and you need a moment to think before you answer. Say one short sentence "
           "telling them you are working it out, and mention what they asked about. Do not give the answer or any part of it.")


class Session:
    def __init__(self, app, ws, cfg):
        self.app, self.ws, self.args = app, ws, app["args"]
        self.system_prompt = str(cfg.get("system_prompt", ""))
        default = "controller" if app["ctl"] else "vad"
        self.mode = cfg.get("endpointing", default)
        if self.mode == "controller" and not app["ctl"]:
            raise ValueError("this server was started without a controller")
        if self.mode not in ("controller", "vad", "manual", "judge"):
            raise ValueError(f"unknown endpointing {self.mode!r}")
        # in "judge" mode a loaded controller is still used, but only for STOP against BACKCHANNEL
        self.ctl_state = app["ctl"].new_session() if app["ctl"] and self.mode in ("controller", "judge") else None
        self.t0 = time.perf_counter()
        self.state = "listening"      # listening | pending (reply asked, no audio yet) | speaking
        self.turn = []                # caller frames of the turn being heard
        self.turn_voiced = 0          # how many of them are voiced
        self.barge = []               # caller frames since their last onset while a reply is in flight
        self.silence = 0              # frames since the caller was last voiced
        self.voiced_run = 0           # consecutive voiced frames
        self.history = []
        self.reply = None
        self.frame = 0
        self.out24, self.out16, self.n24, self.n16 = bytearray(), np.zeros(0, np.float32), 0, 0
        a = self.args
        # the reasoning of the caller's turn in progress (serving/listen_think.py)
        self.thought = Thought(a.listen_stance, a.thought_min_chars) if a.think_first and (a.listen_think or a.carry_thought) else None
        self.listener = None          # the request that reasons while the caller speaks
        self.listened = 0             # voiced frames the last such request had heard

    # ---- plumbing -------------------------------------------------------------
    def voiced(self, x):
        rms = float(np.sqrt(np.mean((x.astype(np.float32) / 32768.0) ** 2)))
        return bool(20 * np.log10(rms + 1e-9) > self.args.vad_db)

    def context(self):
        return ([{"role": "system", "content": self.system_prompt}] if self.system_prompt else []) + self.history

    async def send(self, **event):
        event["t_ms"] = round((time.perf_counter() - self.t0) * 1000, 1)
        await self.ws.send_str(json.dumps(event, ensure_ascii=False))

    def enqueue(self, pcm):
        """Reply audio from the decoder (24 kHz bytes): queue it for the caller, and keep a
        16 kHz copy, sample-aligned, for the controller."""
        self.out24 += pcm
        x = np.frombuffer(pcm, dtype="<i2").astype(np.float32) / 32768.0
        self.n24 += len(x)
        want = self.n24 * SR // OUT_SR - self.n16
        y = resample_poly(x, 2, 3).astype(np.float32)[:want]
        self.out16 = np.concatenate([self.out16, y, np.zeros(want - len(y), np.float32)])
        self.n16 += want

    # ---- one caller frame in, at most one reply frame out ---------------------
    async def on_frame(self, data):
        x = np.frombuffer(data, dtype="<i2")
        if self.frame == 0:
            self.t_first_frame = time.perf_counter()
        is_voiced = self.voiced(x)
        own = await self.pump()

        new_onset = is_voiced and self.silence >= ONSET_GAP
        self.silence = 0 if is_voiced else self.silence + 1
        self.voiced_run = self.voiced_run + 1 if is_voiced else 0
        if self.state == "listening":
            self.turn_voiced += is_voiced
            # before any speech keep only 400 ms of lead-in; never hold more than 60 s
            self.turn = (self.turn + [x])[-(750 if self.turn_voiced else ONSET_GAP):]
            th = self.thought
            if (th is not None and self.args.listen_think and is_voiced and not th.full()
                    and (self.listener is None or self.listener.done())
                    and (self.turn_voiced - max(th.voiced, self.listened)) * 80 >= self.args.listen_every_ms):
                self.listened = self.turn_voiced
                self.listener = asyncio.create_task(self.listen())
        else:
            if new_onset:
                self.barge = []
            self.barge = (self.barge + [x])[-312:]            # at most 25 s

        label = WAIT
        if self.ctl_state is not None:
            probs = await asyncio.get_running_loop().run_in_executor(
                self.app["ctl_pool"], self.app["ctl"].step, self.ctl_state, x.astype(np.float32) / 32768.0, own)
            label = int(np.argmax(probs))
            if self.mode == "judge" and label == START:
                label = WAIT                      # the judge decides when to start
            if label != WAIT:
                await self.send(type="control", label=LABELS[label], frame=self.frame, probs=[round(float(p), 3) for p in probs])
        if self.mode == "judge":
            held = self.reply is not None and self.reply["held"]
            if self.state == "listening" and self.silence == JUDGE_AT:
                # Speculate: start the reply now, keep it silent, and ask the baseline whether the caller has finished.
                await self.start_reply("judge", held=True)
            elif held and self.voiced_run >= 2:
                await self.end_reply("withdrawn")              # the caller went on: nothing was heard, nothing is lost
            elif held and self.silence * 80 >= self.args.judge_timeout_ms:
                await self.release("timeout")                  # quiet this long: reply whatever the judge said
            elif self.ctl_state is None and self.state != "listening" and not held and self.voiced_run >= MIN_VOICED:
                label = STOP
        elif self.mode == "vad":
            if self.state == "listening" and self.silence * 80 >= self.args.vad_silence_ms:
                label = START
            elif self.state != "listening" and self.voiced_run >= MIN_VOICED:
                label = STOP
        self.frame += 1

        if label == STOP and self.reply is not None and (self.reply["held"] or self.reply["frames"] == 0):
            await self.end_reply("withdrawn")                  # a STOP against a reply nobody has heard yet
        elif label == START and self.state == "listening":
            await self.start_reply(self.mode)
        elif label == STOP and self.state != "listening":
            await self.end_reply("interrupted")
        # WAIT holds. BACKCHANNEL does not interrupt: the reply keeps playing.

    async def pump(self):
        """Send one frame of reply audio if one is due. Returns that frame at 16 kHz."""
        r = self.reply
        if r is None or r["held"]:
            return SILENT
        if r["frames"] == 0 and r["lead_left"] > 0 and self.silence * 80 < self.args.lead_in_after_ms:
            # The lead-in is ready but the caller has been quiet only briefly. Measured in the third run: played at
            # once, it was heard in the pauses inside a question (4 of the first 8 questions). So it waits; if the
            # caller goes on meanwhile, the reply is withdrawn unheard as before.
            return SILENT
        if len(self.out24) >= OUT_BYTES or (r["generated"] and self.out24):
            chunk = bytes(self.out24[:OUT_BYTES]).ljust(OUT_BYTES, b"\0")
            del self.out24[:OUT_BYTES]
            own = np.concatenate([self.out16[:FRAME], SILENT])[:FRAME]
            self.out16 = self.out16[FRAME:]
            if r["first_audio"] is None:
                r["first_audio"] = time.perf_counter()
                self.state = "speaking"
                await self.send(type="reply.audio.first", ttfa_ms=round((r["first_audio"] - r["t_commit"]) * 1000, 1))
            if r["lead_left"] > 0:
                r["lead_left"] -= OUT_BYTES
            elif r["answer_audio"] is None:
                r["answer_audio"] = time.perf_counter()
                await self.send(type="reply.answer.first", answer_ms=round((r["answer_audio"] - r["t_commit"]) * 1000, 1))
            await self.ws.send_bytes(chunk)
            r["frames"] += 1
            return own
        if r["generated"]:
            await self.end_reply("done")
        elif r["first_audio"] is not None and r["answer_audio"] is None:
            r["lead_gap"] += 1           # the lead-in has played and the answer is not ready: a silence, not a stutter
        elif r["first_audio"] is not None:
            r["underruns"] += 1          # a frame was due and none was ready: the caller hears a gap
        return SILENT

    # ---- reasoning while the caller speaks -------------------------------------
    async def listen(self):
        """Ask the baseline to reason on the audio heard so far, opened with what it has already worked out."""
        a, th = self.args, self.thought
        voiced, pcm, t0 = self.turn_voiced, np.concatenate(self.turn), time.perf_counter()
        opening, _ = th.opening(voiced, final=False)
        messages = self.context() + [human_turn(pcm), {"role": "assistant", "content": THINK_OPEN + opening, "eot": False}]
        new, info, failed = "", {}, None
        try:
            async for _, text, _ in stream_chat(self.app["http"], a.vllm_url, a.model, messages, info=info, max_tokens=a.listen_max_tokens,
                                                temperature=a.temperature, repetition_penalty=1.0, stop_token_ids=[151665],
                                                stop=[THINK_CLOSE]):
                new += text
        except asyncio.CancelledError:
            raise                        # the caller paused and a reply took over: what was streamed so far is kept below
        except Exception as e:
            failed = repr(e)
        finally:
            th.keep(opening, new, voiced, closed=info.get("finish_reason") == "stop")
        if failed:
            await self.send(type="error", message=f"listen: {failed}")
        else:
            await self.send(type="control", label="LISTEN", frame=self.frame, heard_voiced_ms=voiced * 80, chars=len(new),
                            closed=th.closed, ms=round((time.perf_counter() - t0) * 1000, 1))

    async def stop_listening(self):
        task, self.listener = self.listener, None
        if task is not None and not task.done():
            task.cancel()
            await asyncio.gather(task, return_exceptions=True)      # its partial reasoning is in self.thought once this returns

    # ---- replies --------------------------------------------------------------
    async def say(self, r, text, kind):
        """Transcript text goes out at once, or waits with a held reply."""
        if r["held"]:
            r["backlog"].append((text, kind))
        else:
            await self.send(type="transcript.delta", text=text, kind=kind)

    async def release(self, why):
        """Let a held (speculative) reply be heard."""
        r = self.reply
        r["held"], r["released_by"] = False, why
        lag = (time.perf_counter() - self.t_first_frame) * 1000 - (self.frame - 1) * 80
        await self.send(type="reply.start", by=f"judge:{why}", frame=self.frame, heard_ms=len(r["heard"]) * 80, lag_ms=round(lag, 1),
                        speculated_ms=round((time.perf_counter() - r["t_commit"]) * 1000, 1))
        for text, kind in r["backlog"]:
            await self.send(type="transcript.delta", text=text, kind=kind)
        r["backlog"] = []
        self.maybe_lead_in(r)

    def maybe_lead_in(self, r):
        a = self.args
        if a.lead_in and a.think_first and not r["think_done"] and "lead" not in r:
            r["lead"] = asyncio.create_task(self.lead_in(r))

    async def lead_in(self, r):
        """One short spoken sentence while the reply is still reasoning. Its audio is queued ahead of the answer's."""
        a, speech = self.args, self.app["speech"]
        st = speech.new_reply()
        messages = [{"role": "system", "content": LEAD_IN}] + self.history + [r["human"], {"role": "assistant", "content": a.reply_prefix, "eot": False}]

        def queue(pcm):
            if self.reply is r:
                self.enqueue(pcm)
                r["lead_left"] += len(pcm)
        try:
            async for _, text, tokens in stream_chat(self.app["http"], a.vllm_url, a.model, messages, max_tokens=a.lead_in_max_tokens,
                                                     temperature=a.temperature, top_p=a.top_p, repetition_penalty=a.repetition_penalty,
                                                     stop_token_ids=[151665]):
                if text:
                    r["lead_text"] += text
                    await self.send(type="transcript.delta", text=text, kind="lead")
                if tokens:
                    for pcm in await speech.feed(st, tokens):
                        queue(pcm)
            for pcm in await speech.finish(st):
                queue(pcm)
        except asyncio.CancelledError:
            raise
        except Exception as e:
            await self.send(type="error", message=f"lead-in: {e!r}")
        finally:
            st["cache"], st["buf"] = None, []

    async def ask_judge(self, r, pcm):
        a = self.args
        try:
            said = await judge_finished(self.app["http"], a.vllm_url, a.model, pcm, prompt=a.judge_prompt, think_tokens=a.judge_think_tokens)
        except Exception as e:
            said = None
            await self.send(type="error", message=f"judge: {e!r}")
        if self.reply is not r or not r["held"]:
            return                                             # withdrawn or already released meanwhile
        await self.send(type="control", label="JUDGE", finished=said, frame=self.frame,
                        judge_ms=round((time.perf_counter() - r["t_commit"]) * 1000, 1))
        if said is not False:
            await self.release("finished")                     # "no" keeps it held until the caller goes on or the timeout

    async def start_reply(self, by, held=False):
        if self.turn_voiced < MIN_VOICED:
            return
        await self.stop_listening()
        heard, voiced = self.turn, self.turn_voiced
        pcm = np.concatenate(heard)
        self.turn, self.turn_voiced = [], 0
        human = human_turn(pcm)
        messages = self.context() + [human, {"role": "assistant", "content": self.args.reply_prefix, "eot": False}]
        r = {"t_commit": time.perf_counter(), "first_token": None, "first_audio": None, "t_generated": None, "generated": False,
             "frames": 0, "underruns": 0, "text": "", "tts_audio": "", "human": human, "by": by, "heard": heard,
             "voiced": voiced, "held": held, "backlog": [],
             "think_done": False, "lead_left": 0, "lead_gap": 0, "lead_text": "", "answer_audio": None,
             "thinking": self.args.reply_prefix.startswith("<think>")}
        self.reply, self.state = r, "pending"
        self.out24, self.out16, self.n24, self.n16 = bytearray(), np.zeros(0, np.float32), 0, 0
        r["task"] = asyncio.create_task(self.generate(r, messages))
        if held:
            r["judge"] = asyncio.create_task(self.ask_judge(r, pcm))
            await self.send(type="reply.speculative", frame=self.frame, heard_ms=round(len(pcm) * 1000 / SR))
            return
        # lag_ms: how far this session's processing is behind the caller's audio clock (0 when the server keeps up)
        lag = (time.perf_counter() - self.t_first_frame) * 1000 - (self.frame - 1) * 80 if self.frame else 0.0
        await self.send(type="reply.start", by=by, frame=self.frame, heard_ms=round(len(pcm) * 1000 / SR), lag_ms=round(lag, 1))
        self.maybe_lead_in(r)

    async def generate(self, r, messages):
        a, speech = self.args, self.app["speech"]
        st = speech.new_reply()
        try:
            if a.think_first:
                # Think, then speak. Measured on 100 Big Bench Audio questions: the baseline scores 97 when
                # its reply is opened for reasoning (text out) and 65 when it is opened for speech: asked
                # to speak, it does not reason. So it reasons first, as text, and the speech is then opened
                # with that reasoning already in the reply.
                # With a carried thought (serving/listen_think.py) the reasoning opens with what was worked out
                # while the caller spoke, or by a reply that was withdrawn; `ready` means nothing is left to do.
                th = self.thought
                opening, ready = th.opening(r["voiced"], final=True) if th else ("", False)
                r["carried_chars"], r["thought_ready"] = len(opening), ready
                thought = ""
                if opening:
                    await self.say(r, opening, "think")
                if not ready:
                    think_msgs = messages[:-1] + [{"role": "assistant", "content": THINK_OPEN + opening, "eot": False}]
                    closed = False
                    try:
                        async for _, text, _ in stream_chat(self.app["http"], a.vllm_url, a.model, think_msgs, max_tokens=a.think_max_tokens,
                                                            temperature=a.temperature, repetition_penalty=1.0, stop_token_ids=[151665],
                                                            stop=[THINK_CLOSE]):
                            r["first_token"] = r["first_token"] or time.perf_counter()
                            if text:
                                thought += text
                                await self.say(r, text, "think")
                        closed = True
                    finally:
                        if th:                   # also when this reply is withdrawn in the middle of its reasoning
                            th.keep(opening, thought, r["voiced"], closed)
                r["think_done"] = True
                if "lead" in r:
                    await asyncio.gather(r["lead"], return_exceptions=True)       # the answer's audio goes behind the lead-in's
                await self.say(r, THINK_CLOSE, "think")
                r["thought_ms"] = round((time.perf_counter() - r["t_commit"]) * 1000, 1)
                spoken_open = THINK_OPEN + opening + thought + THINK_CLOSE + chr(10) + a.reply_prefix
                messages = messages[:-1] + [{"role": "assistant", "content": spoken_open, "eot": False}]
            async for _, text, tokens in stream_chat(self.app["http"], a.vllm_url, a.model, messages, max_tokens=a.max_tokens,
                                                     temperature=a.temperature, top_p=a.top_p,
                                                     repetition_penalty=a.repetition_penalty, stop_token_ids=[151665]):
                r["first_token"] = r["first_token"] or time.perf_counter()
                if text:
                    r["text"] += text
                    await self.say(r, text, "think" if r["thinking"] else "say")
                    if "</think>" in r["text"]:
                        r["thinking"] = False
                if tokens:
                    r["tts_audio"] += "".join(f"<audio_{t}>" for t in tokens)
                    playing = self.reply is r and not r["held"] and r["first_audio"] is not None
                    for pcm in await speech.feed(st, tokens, buffered_ms=len(self.out24) / 48 if playing else None):
                        if self.reply is r:
                            self.enqueue(pcm)
            for pcm in await speech.finish(st):
                if self.reply is r:
                    self.enqueue(pcm)
        except asyncio.CancelledError:
            raise
        except Exception as e:
            await self.send(type="error", message=repr(e))
        finally:
            r["generated"], r["t_generated"] = True, time.perf_counter()
            r["decodes"], r["decode_ms"] = st["decodes"], round(st["decode_ms"], 1)
            # Free the decoder caches now. The reply, its task and this coroutine refer to each other, so
            # Python frees them only when its cycle collector runs, and it cannot see GPU memory: measured,
            # the decoder process grew to 30.6 GiB and one load test died of CUDA out-of-memory.
            st["cache"], st["buf"] = None, []

    async def end_reply(self, reason):
        r, self.reply, self.state = self.reply, None, "listening"
        r["task"].cancel()               # no effect when generation already finished
        for extra in ("judge", "lead"):
            if extra in r:
                r[extra].cancel()
        self.out24, self.out16 = bytearray(), np.zeros(0, np.float32)
        turn_goes_on = reason != "done" and r["frames"] * 80 < self.args.false_start_ms
        if self.thought is not None and not turn_goes_on:
            self.thought.reset()                               # the caller's next words are a new turn
            self.listened = 0
        if reason == "done":
            # history as in the released multi-turn text example: the assistant's words as plain content
            # (the R1.1 chat template renders only `content`)
            said = {"role": "assistant", "content": (r["lead_text"] + " " + r["text"]).strip()}
            self.history = (self.history + [r["human"], said])[-2 * self.args.max_history_turns:] if self.args.max_history_turns else []
            self.turn = list(self.barge) if self.silence < ONSET_GAP else []     # the caller already began their next turn
        elif r["frames"] * 80 < self.args.false_start_ms:
            # cut off before it had really begun: the caller was not finished. Keep what they had said, add what they said since.
            self.turn = (r["heard"] + list(self.barge))[-750:]
        else:
            self.turn = list(self.barge)                                         # what the caller said to cut in starts the new turn
            if self.args.keep_interrupted and self.args.max_history_turns:
                # The caller cut in on a reply they had been hearing. Without this their question and the answer
                # are forgotten and "no, I meant four" has nothing to refer to. The words that were played are
                # estimated from the share of the generated audio that was played.
                share = min(1.0, r["frames"] * OUT_FRAME / max(self.n24, 1))
                said = r["text"][: int(len(r["text"]) * share)].rsplit(" ", 1)[0].strip()
                if said:
                    self.history = (self.history + [r["human"], {"role": "assistant", "content": said}])[-2 * self.args.max_history_turns:]
        self.barge = []
        self.turn_voiced = sum(self.voiced(f) for f in self.turn)
        if reason == "withdrawn":                              # a speculative reply nobody heard
            await self.send(type="reply.withdrawn", frame=self.frame)
            return
        ms = lambda t: round((t - r["t_commit"]) * 1000, 1) if t else None
        await self.send(type="reply.done", reason=reason, by=r["by"], text=r["text"], audio_ms=r["frames"] * 80, underruns=r["underruns"],
                        ttfa_ms=ms(r["first_audio"]), first_token_ms=ms(r["first_token"]), generated_ms=ms(r["t_generated"]),
                        thought_ms=r.get("thought_ms"), answer_ms=ms(r["answer_audio"]), lead_gap_ms=r["lead_gap"] * 80, lead_text=r["lead_text"],
                        carried_chars=r.get("carried_chars"), thought_ready=r.get("thought_ready"),
                        decodes=r.get("decodes"), decode_ms=r.get("decode_ms"))


async def handler(request):
    ws = web.WebSocketResponse(max_msg_size=1 << 20)
    await ws.prepare(request)
    sess = None
    try:
        async for msg in ws:
            if msg.type == web.WSMsgType.BINARY:
                if sess is None or len(msg.data) != IN_BYTES:
                    await ws.send_str(json.dumps({"type": "error", "message": f"send session.start first, then {IN_BYTES}-byte frames"}))
                    continue
                await sess.on_frame(msg.data)
            elif msg.type == web.WSMsgType.TEXT:
                m = json.loads(msg.data)
                if m.get("type") == "session.start":
                    try:
                        sess = Session(request.app, ws, m)
                    except ValueError as e:
                        await ws.send_str(json.dumps({"type": "error", "message": str(e)}))
                        continue
                    await sess.send(type="session.started", endpointing=sess.mode, frame_ms=80, input_sample_rate=SR, output_sample_rate=OUT_SR)
                elif sess and m.get("type") == "input.commit" and sess.state == "listening":
                    await sess.start_reply("manual")
                elif m.get("type") == "session.end":
                    break
    finally:
        if sess and sess.reply:
            sess.reply["task"].cancel()
        if sess and sess.listener:
            sess.listener.cancel()
    return ws


async def on_startup(app):
    app["http"] = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=None))


async def on_cleanup(app):
    await app["http"].close()


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--host", default="127.0.0.1", help="local only: the machine has a public address")
    ap.add_argument("--port", type=int, default=8765)
    ap.add_argument("--vllm-url", default="http://localhost:9999/v1/chat/completions")
    ap.add_argument("--model", default="Step-Audio-R1.1")
    ap.add_argument("--reply-prefix", required=True, help="how the assistant turn is opened; taken from what serving/probe_baseline.py measured")
    ap.add_argument("--step-audio2-dir", required=True)
    ap.add_argument("--token2wav-dir", required=True)
    ap.add_argument("--prompt-wav", required=True)
    ap.add_argument("--first-chunk", type=int, default=25, help="audio tokens in a reply's first decoded chunk (released recipe: 25, one second)")
    ap.add_argument("--min-chunk", type=int, default=25, help="smallest later chunk, used while the play buffer is below --low-water-ms")
    ap.add_argument("--low-water-ms", type=int, default=0)
    ap.add_argument("--decoder-workers", type=int, default=1, help="independent audio decoders")
    ap.add_argument("--decoder-fp16", action="store_true", help="run the released decoder in half precision (its own float16 option)")
    ap.add_argument("--encoder-ckpt")
    ap.add_argument("--controller-ckpt")
    ap.add_argument("--controller-device", default="cuda:1")
    ap.add_argument("--vad-db", type=float, default=-45.0)
    ap.add_argument("--vad-silence-ms", type=int, default=640)
    ap.add_argument("--max-history-turns", type=int, default=4)
    ap.add_argument("--judge-prompt", default="v2", help="wording of the end-of-turn question (serving/judge.py)")
    ap.add_argument("--judge-think-tokens", type=int, default=0, help="reasoning tokens the judge may use before it answers")
    ap.add_argument("--judge-timeout-ms", type=int, default=1600, help="reply after this much silence even when the judge said the caller will go on")
    ap.add_argument("--think-first", action="store_true", help="reason as text first, then speak with that reasoning in the reply")
    ap.add_argument("--think-max-tokens", type=int, default=2048)
    ap.add_argument("--carry-thought", action="store_true", help="with --think-first: a withdrawn reply leaves its reasoning for the next one")
    ap.add_argument("--listen-think", action="store_true", help="with --think-first: reason while the caller is still speaking (implies --carry-thought)")
    ap.add_argument("--listen-every-ms", type=int, default=2400, help="caller speech between two listening requests")
    ap.add_argument("--listen-max-tokens", type=int, default=96, help="reasoning tokens one listening request may add")
    ap.add_argument("--listen-stance", default="plain", choices=["bare", "plain", "check", "notes"], help="wording of the carried reasoning (serving/listen_think.py)")
    ap.add_argument("--thought-min-chars", type=int, default=60, help="an addition to the carried reasoning shorter than this is dropped")
    ap.add_argument("--lead-in", action="store_true", help="with --think-first: say one short sentence while the reply is still reasoning")
    ap.add_argument("--lead-in-max-tokens", type=int, default=300, help="150 cut the audio of longer lead-ins short (third run)")
    ap.add_argument("--short-whole", action="store_true", help="decode a reply shorter than one audio chunk in one piece (serving/speech_out.py)")
    ap.add_argument("--lead-in-after-ms", type=int, default=1200, help="the lead-in is not played before the caller has been quiet this long")
    ap.add_argument("--keep-interrupted", action="store_true", help="keep a reply the caller cut in on, as far as it was played, in the conversation")
    ap.add_argument("--false-start-ms", type=int, default=2000, help="a reply cut off before it played this long counts as a false start: the caller's earlier words are kept")
    ap.add_argument("--max-tokens", type=int, default=2048)
    ap.add_argument("--temperature", type=float, default=0.7)
    ap.add_argument("--top-p", type=float, default=0.9)
    ap.add_argument("--repetition-penalty", type=float, default=1.05)
    args = ap.parse_args()

    from serving.speech_out import NativeSpeechOut
    app = web.Application()
    app["args"] = args
    app["speech"] = NativeSpeechOut(args.step_audio2_dir, args.token2wav_dir, args.prompt_wav, first_chunk=args.first_chunk,
                                    min_chunk=args.min_chunk, low_water_ms=args.low_water_ms, workers=args.decoder_workers,
                                    float16=args.decoder_fp16, whole_short=args.short_whole)
    app["ctl"], app["ctl_pool"] = None, ThreadPoolExecutor(max_workers=1)
    if args.controller_ckpt:
        from controller.runtime import DuplexController
        app["ctl"] = DuplexController(args.encoder_ckpt, args.controller_ckpt, args.controller_device)
    app.router.add_get("/ws", handler)
    app.on_startup.append(on_startup)
    app.on_cleanup.append(on_cleanup)
    web.run_app(app, host=args.host, port=args.port)


if __name__ == "__main__":
    main()