fix(conversation,voice_worker): going on survives the answer starting, ignores empty finals; cancel checks before every model call; context finals stay batched

- A speaker who starts their next utterance within call.continueMs holds their request open for
  that final, also if the answer starts playing meanwhile; an empty final (rejected noise) joins
  nothing and asks nothing again
- The engine checks the cancel before the tool router, the planner and a planned tool call too
- Finals with a context are batched again: each context is cut from its end to the shortest one in
  the batch (ctranslate2 needs the start token at one position); ten finals at once 1.3 s
- Measured harsh conditions (docs/v2/stt-accuracy-plan.md): the context never made them worse

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-19 20:30:29 +09:00
parent c1b561d66d
commit 251f5e116d
7 changed files with 193 additions and 35 deletions

View File

@@ -68,6 +68,14 @@ TRACE_RESULT_CHARS = 2000
TRACE_THINKING_CHARS = 8000
def _cancelled(before: str) -> bool:
"""The answer is no longer wanted (turn_state.cancel): stop before the next model or tool call."""
if _turn_state.cancelled():
debug_log(f"reply cancelled before {before}", "planning")
return True
return False
def _clip(text: str, limit: int) -> str:
return text if len(text) <= limit else text[:limit] + "…"
@@ -1253,6 +1261,8 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
# Step 0.5: Deterministic on-screen site search. If the user named a site and
# asked to search/open it while broadcasting, do it directly — the small chat
# model otherwise just narrates without calling the browser tool.
if _cancelled("it started"):
return None
_site_search_reply = _maybe_deterministic_site_search(text, db, cfg, language)
if _site_search_reply is not None:
return _site_search_reply
@@ -1390,6 +1400,8 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
routed_tools = list(_cached_routed)
debug_log("tool router served from hot-window cache", "planning")
else:
if _cancelled("the tool router"):
return None
routed_tools = _route_tools(cfg, redacted, _builtin_tools, mcp_tools, recent_messages)
# Don't cache the router's "fall open to all tools" fallback. That
# path fires when the LLM router times out, returns empty, or emits
@@ -1532,6 +1544,8 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
if _one_step_tool:
debug_log(f"intent judge: one-step tool {_one_step_tool}, no plan", "planning")
elif not intent_judge or _turn_needs_tools:
if _cancelled("the planner"):
return None
action_plan = plan_query(
cfg=cfg,
query=redacted,
@@ -2376,8 +2390,7 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
_one_step_nudged = False
while turn < max_turns:
if _turn_state.cancelled():
debug_log("reply cancelled: no longer wanted", "planning")
if _cancelled("a model call"):
return None
turn += 1
debug_log(f"🔁 messages loop turn {turn}", "planning")
@@ -2496,6 +2509,8 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
}
],
})
if _cancelled("a planned tool call"):
return None
tools_started += 1
_plan_result = run_tool_with_retries(
db=db,
@@ -2844,8 +2859,7 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
continue
# Execute tool (not for an answer that is no longer wanted: no actions on its behalf)
if _turn_state.cancelled():
debug_log("reply cancelled before a tool call", "planning")
if _cancelled("a tool call"):
return None
tools_started += 1
result = run_tool_with_retries(

View File

@@ -19,7 +19,9 @@ SR = 16000
# over it: every hallucination stayed below, real speech above except two short words in loud noise.
# Whisper's no_speech_prob is not used: large-v3-turbo reports 0.0 for silence and noise alike.
MIN_MEAN_LOGPROB = -0.7
MAX_COMPRESSION_RATIO = 2.4 # repetition loops ("A B A B A B ...") compress far better than speech
MAX_COMPRESSION_RATIO = 2.4
# faster-whisper keeps at most this many previous-text tokens in a prompt (max_length // 2 - 1).
MAX_PREVIOUS_TOKENS = 223 # repetition loops ("A B A B A B ...") compress far better than speech
def _letters(text: str) -> str:
@@ -127,19 +129,27 @@ class WhisperTranscriber:
contexts: list[str] | None = None) -> list[str]:
"""Clips arrive loudness-equalised by the session. ``contexts``: per clip, the recent
conversation to prompt with ("" for none); see ``choose_with_context``."""
if contexts and any(contexts):
# Prompts of different lengths cannot share one generate call (the start token must sit
# at the same position): one clip at a time. The encoder costs the same per clip anyway.
return [self._with_context(c, opts, ctx) for c, ctx in zip(clips, contexts)]
enc, langs = self._encode(clips, opts)
return self._choose(enc, langs, opts, None)
def _with_context(self, clip: np.ndarray, opts: DecodeOptions, context: str) -> str:
enc, langs = self._encode([clip], opts)
heard = self._choose(enc, langs, opts, None)[0]
if not context:
heard = self._choose(enc, langs, opts, None)
prev = self._previous(langs, contexts)
if prev is None:
return heard
return choose_with_context(heard, self._choose(enc, langs, opts, [context])[0], opts.hotwords)
prompted = self._choose(enc, langs, opts, prev)
return [choose_with_context(h, p, opts.hotwords) if c else h
for h, p, c in zip(heard, prompted, contexts)]
def _previous(self, langs: list[str], contexts: list[str] | None) -> list[list[int]] | None:
"""The contexts as previous-text tokens of one length for the whole batch: the decoder needs
the start token at the same position in every prompt. Each is cut from its end to the
shortest one (a channel's clips share most of their context); a clip without one borrows
another's, and its prompted result is not used."""
if not contexts or not any(contexts):
return None
toks = [self._tokenizer(lang).encode(" " + ctx.strip())[-MAX_PREVIOUS_TOKENS:] if ctx else None
for lang, ctx in zip(langs, contexts)]
n = min(len(t) for t in toks if t is not None)
filler = next(t for t in toks if t is not None)[-n:]
return [t[-n:] if t is not None else filler for t in toks]
def _encode(self, clips: list[np.ndarray], opts: DecodeOptions):
m = self.model
@@ -156,20 +166,18 @@ class WhisperTranscriber:
langs = [r[0][0][2:-2] for r in m.model.detect_language(enc)]
return enc, langs
def _choose(self, enc, langs: list[str], opts: DecodeOptions, contexts: list[str] | None) -> list[str]:
plain = self._decode(enc, langs, opts.beam, None, contexts)
def _choose(self, enc, langs: list[str], opts: DecodeOptions, prev: list[list[int]] | None) -> list[str]:
plain = self._decode(enc, langs, opts.beam, None, prev)
if not opts.hotwords:
return [text if keep_transcript(text, lp) else "" for text, lp in plain]
hinted = self._decode(enc, langs, opts.beam, " ".join(opts.hotwords), contexts)
hinted = self._decode(enc, langs, opts.beam, " ".join(opts.hotwords), prev)
return [choose_with_hint(ht, hlp, pt, plp, opts.hotwords) for (ht, hlp), (pt, plp) in zip(hinted, plain)]
def _decode(self, enc, langs: list[str], beam: int, hotwords: str | None,
contexts: list[str] | None = None) -> list[tuple[str, float]]:
prev: list[list[int]] | None = None) -> list[tuple[str, float]]:
m = self.model
prompts = [m.get_prompt(self._tokenizer(lang),
self._tokenizer(lang).encode(" " + ctx.strip()) if ctx else [],
without_timestamps=True, hotwords=hotwords)
for lang, ctx in zip(langs, contexts or [""] * len(langs))]
prompts = [m.get_prompt(self._tokenizer(lang), p, without_timestamps=True, hotwords=hotwords)
for lang, p in zip(langs, prev or [[]] * len(langs))]
results = m.model.generate(enc, prompts, beam_size=beam, max_length=224, suppress_blank=True,
suppress_tokens=[-1], return_scores=True)
# ``scores`` is the sequence log-probability divided by its length: the mean per token.

View File

@@ -171,8 +171,9 @@ decoded with the recent conversation as its previous-text prompt:
was kept, it stays within half that text's letters of it, and it holds every hotword exactly as
often; otherwise the text without context is used. On noise or unsure audio the prompt makes
Whisper write words of the conversation; this rule keeps that out, as for the hint.
- Prompts of different lengths cannot share one decoder call, so finals with a context are decoded
one clip at a time (the encoder costs the same per clip).
- Finals stay batched. The decoder needs the start token at the same position in every prompt of a
batch, so each clip's context is cut from its end to the shortest one in the batch (a channel's
clips share most of it); a clip without a context borrows another's and keeps its plain result.
Measured (2026-11-19, the game PC's RTX 5070 Ti with Strata loaded, large-v3-turbo int8_float16,
beam 2, the 100 recordings of the user's speech from 2026-11-16 to 19, 16 of them with the user's own
@@ -180,7 +181,11 @@ text): character error rate 12.0% without and 7.5% with the context (wrong sente
empty results (17 of 100 both ways), final decode 134 ms to 182 ms on average (p95 170 to 253 ms).
On the 108 noise clips decoded straight (no VAD), as many came out with text with the context as
without it (16 each); without the rule above it was 22 with turbo, and with large-v3 63, which wrote
whole sentences of the prompt. Evidence and the model comparison: `docs/v2/stt-accuracy-plan.md`.
whole sentences of the prompt. Under harsh copies of the same recordings (a weak voice over a mic
noise floor, ESC-50 noise at SNR 10 and 5 dB, a 300-3400 Hz headset, Opus 12 kbps, reverb) the
context never made the error rate worse (it fell most with Opus and reverb). Ten finals at once stay
one batch: 1.3 s with contexts, 1.6-2.0 s without (Strata running). Evidence and the model comparison:
`docs/v2/stt-accuracy-plan.md`.
Measured (2026-11-11, RTX 5050) with 54 real noise recordings from ESC-50 (typing, mouse, breathing,
coughing, laughing, crying, vacuum, ...), each at its own level and at -25 dBFS: of the 108 noise-only