perf(voice): ask the done-by-user question while the user still speaks

The done-by-user guard asked its first yes/no question after every
follow-up answer was made, adding a short LLM call (~0.4 s) before
Jarvis spoke. The question depends only on the user's words, so the
voice worker's prepare now asks it on the partial transcript after the
tool pick (prepare_done_by_user, follow-up turns only) and the guard
uses that judgement (prepared_done), asking only whether the answer
refuses when the user said they did it. Without a prepared judgement,
or when it failed, the guard asks for itself as before. The reply does
not wait for the judgement, only the guard does.

Measured on Qwen3.6 through the game PC's Strata, 12 pairs of short
follow-up questions in alternating order: brain time median 1.06 s
before, 0.69 s after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-18 22:07:04 +09:00
parent a59ed43ae1
commit b58fc149d4
8 changed files with 153 additions and 18 deletions

View File

@@ -198,7 +198,7 @@ Every distinct LLM call in Jarvis, what feeds it, what consumes it, and how it i
## 16. Done-by-user judgements (v2 reply engine)
- **File**: [src/jarvis/reply/done_guard.py](src/jarvis/reply/done_guard.py) — `superseded()`; called by `run_reply_engine` after the answer is made, before it is kept ([reply.spec.md](src/jarvis/reply/reply.spec.md), "Earlier answers after the user did it (v2)").
- **Trigger**: v2 replies (a history context) in which no tool run was started, with an earlier plain Jarvis answer in the asker's short-term dialogue memory (follow-up turns). The second question runs only after a yes to the first. Not on the second try.
- **Trigger**: v2 replies (a history context) in which no tool run was started, with an earlier plain Jarvis answer in the asker's short-term dialogue memory (follow-up turns). The second question runs only after a yes to the first. Not on the second try. The first question is asked ahead by `prepare_done_by_user()` in the voice worker's `prepare` (after `prepare_intent()`, on the partial transcript, only on follow-up turns) and passed back as `prepared_done`; the guard asks it itself only when nothing was prepared or that judgement failed.
- **Model**: `ollama_chat_model` (Strata in v2), non-thinking, temperature 0, timeout 5 s.
- **Inputs**: 1) the user's utterance fenced in `<utterance>`: do they say they themselves already did, changed, set or fixed something; 2) the answer fenced in `<reply>`: does it say something is not supported, not possible, or that the assistant cannot do it. Data only, never instructions.
- **Output**: one word yes/no each (anything else is no). Two yeses: the reply is made once more ([1] again, plus [7] from the hot-window cache) with Jarvis's earlier plain answers and its answer lines in the history context (`HistoryContext.answers`) left out of its context (`left_out`).

View File

@@ -62,9 +62,15 @@ def earlier_answers(recent_messages: Iterable[dict], history: Any) -> list[str]:
return answers + [x for x in getattr(history, "answers", None) or [] if x in shown]
def superseded(cfg, text: str, reply: str, timeout_sec: float = 5.0) -> bool:
def said_done(cfg, text: str, timeout_sec: float = 5.0) -> Optional[bool]:
"""Does the user say they themselves already did something? None: no usable judgement."""
return _yes_no(cfg, _DONE_PROMPT, f"<utterance>{text}</utterance>", "user says done", timeout_sec)
def superseded(cfg, text: str, reply: str, timeout_sec: float = 5.0, said: Optional[bool] = None) -> bool:
"""True when the user says they did something themselves and ``reply`` still says something
cannot be done. No usable judgement is False (the answer is kept)."""
if not _yes_no(cfg, _DONE_PROMPT, f"<utterance>{text}</utterance>", "user says done", timeout_sec):
cannot be done. ``said``: that first judgement when it was already made (the prepare stage);
None asks for it. No usable judgement is False (the answer is kept)."""
if not (said if said is not None else said_done(cfg, text, timeout_sec)):
return False
return bool(_yes_no(cfg, _REFUSES_PROMPT, f"<reply>{reply}</reply>", "reply refuses", timeout_sec))

View File

@@ -1172,6 +1172,17 @@ def prepare_intent(cfg, text: str, dialogue_memory, chat_available: bool,
return list(routed)
def prepare_done_by_user(cfg, text: str, dialogue_memory) -> Optional[bool]:
"""The done-by-user guard's first judgement for ``text`` ahead of its reply (v2: on a partial
transcript while the user still speaks), passed back through ``prepared_done``. Only asked when
the guard could run (an earlier plain answer in the dialogue memory); otherwise None."""
from .done_guard import _is_answer, said_done
if not any(_is_answer(m) for m in _recent_messages(cfg, dialogue_memory)):
return None
return said_done(cfg, redact(text))
def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
text: str, dialogue_memory: "DialogueMemory",
language: Optional[str] = None,
@@ -1182,7 +1193,8 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
intent_judge: bool = False,
prepared_tools: Optional[list] = None,
person_notes: Optional[list] = None,
left_out: Optional[list] = None) -> Optional[str]:
left_out: Optional[list] = None,
prepared_done: Optional[Callable[[], Optional[bool]]] = None) -> Optional[str]:
"""
Main entry point for reply generation.
@@ -1221,6 +1233,9 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
not see (the done-by-user guard's second try, reply.spec.md
"Earlier answers after the user did it (v2)"); the guard does not run
again.
prepared_done: v2 only. Gives the guard's first judgement (does the
user say they did it) that ``prepare_done_by_user`` made while the
user was still speaking; None from it: the guard asks for itself.
Returns:
Generated reply text or None
@@ -3167,7 +3182,8 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
if history is not None and left_out is None and not tools_started:
from .done_guard import earlier_answers, superseded
_earlier = earlier_answers(recent_messages, history)
if _earlier and superseded(cfg, redacted, reply):
if _earlier and superseded(cfg, redacted, reply,
said=prepared_done() if prepared_done is not None else None):
debug_log(f"done-by-user guard: answering again without {len(_earlier)} earlier line(s)",
"planning")
return run_reply_engine(db, cfg, tts, text, dialogue_memory, language=language,

View File

@@ -113,6 +113,7 @@ Design principles enforced by the engine:
- After the answer is made and before it is kept or spoken: when the reply has history (v2), no tool run was started in this reply (whatever it returned), and the asker's short-term dialogue memory holds an earlier plain answer of Jarvis (not a native tool call message), `done_guard.superseded` asks the chat model two short yes/no questions (non-thinking, temperature 0, 5 s, texts fenced as data): does the user say they themselves already did, changed, set or fixed something; only on a yes, does the answer say something is not supported, not possible or that Jarvis cannot do it. On two yeses the answer is dropped and made once more with `left_out`: Jarvis's earlier plain answers in the dialogue memory and the history lines that are its answers to the asker (`HistoryContext.answers`, history.spec.md) are not in that reply's context. The user's own earlier words, other people's lines (even with the same words) and earlier tool calls with their results stay. The second try keeps whatever it answers and runs no guard; the turn is stored once, with that answer.
- Anything else keeps the first answer: a "no" (the user asked a question, asked to repeat, or only asked for something), a non-refusing answer, no usable judgement, no earlier answer, or a tool run started in the reply, even one that returned nothing or failed (a second try would run it again).
- Cost: one short call on v2 follow-up turns (an earlier answer in the dialogue memory), a second only after a yes, and a second reply only when both are yes. Logs carry the outcomes, never the text.
- Latency: the first question depends only on the user's words, so the voice worker's `prepare` asks it ahead on the partial transcript (`prepare_done_by_user`, only on follow-up turns, after the tool pick) and the reply passes it as `prepared_done`. The guard then asks only the second question when the first was a yes; without a prepared judgement, or when it failed, it asks the first itself. Measured on Qwen3.6 (2026-11-18, 12 pairs of short follow-up questions): brain time median 1.06 s without, 0.69 s with.
- Eval: `evals/test_said_not_asked.py` (`speed-adjusted-field` with the field turn's history and dialogue memory; control: "what did you just say? say it again" still says it again).
Task-list planner (all model sizes, strongest impact on small models):

View File

@@ -151,6 +151,12 @@ class _Prepared:
at: float
done: threading.Event = dataclasses.field(default_factory=threading.Event)
tools: Optional[list] = None # the intent judge's pick; None: none made
# The done-by-user guard's first judgement, made after the pick; None: none made.
said_ready: threading.Event = dataclasses.field(default_factory=threading.Event)
said: Optional[bool] = None
def said_done(self) -> Optional[bool]:
return self.said if self.said_ready.wait(PREPARED_WAIT_S) else None
# The app passes the MCP servers' environment values (API keys, kept in its encrypted secrets)
@@ -266,7 +272,7 @@ class JarvisBrain:
return len(mem.get_recent_messages()) if mem.has_recent_messages() else 0
def prepare(self, user: str, text: str, chat: bool) -> None:
from jarvis.reply.engine import prepare_intent
from jarvis.reply.engine import prepare_done_by_user, prepare_intent
mem = self._memory(user)
p = _Prepared(text=text, turns=self._turns(mem), at=time.monotonic())
@@ -278,18 +284,23 @@ class JarvisBrain:
notes_available=True, screen_available=True)
finally:
p.done.set()
debug_log(f"brain prepare user={user} picked={p.tools is not None} "
f"ms={(time.perf_counter() - t0) * 1000:.0f}", "llm")
t1 = time.perf_counter()
try:
p.said = Muted.run(prepare_done_by_user, self.cfg, text, mem)
finally:
p.said_ready.set()
debug_log(f"brain prepare user={user} picked={p.tools is not None} said={p.said} "
f"ms={(t1 - t0) * 1000:.0f}+{(time.perf_counter() - t1) * 1000:.0f}", "llm")
def _prepared_tools(self, user: str, text: str) -> Optional[list]:
"""The pick prepared for about this text, waiting for one still being made; None if none fits."""
def _take_prepared(self, user: str, text: str) -> Optional[_Prepared]:
"""What was prepared for about this text, waiting for a pick still being made; None if none fits."""
with self._lock:
p = self._prepared.pop(user, None)
if p is None or not similar(p.text, text) or time.monotonic() - p.at > PREPARED_MAX_AGE_S:
return None
if not p.done.wait(PREPARED_WAIT_S) or p.turns != self._turns(self._memory(user)):
return None
return p.tools
return p
def _task_cfg(self):
from jarvis.tools.registry import BUILTIN_TOOLS
@@ -306,7 +317,8 @@ class JarvisBrain:
t0 = time.perf_counter()
# A task has its own short-term memory: it is not a turn of the person's conversation.
prepared = None if task else self._prepared_tools(user, text)
p = None if task else self._take_prepared(user, text)
prepared = p.tools if p is not None else None
cfg = self._task_cfg() if task else self.cfg
memory = DialogueMemory(inactivity_timeout=self.cfg.dialogue_memory_timeout, max_interactions=20) \
if task else self._memory(user)
@@ -326,7 +338,8 @@ class JarvisBrain:
language=self.language, history=history, legacy_memory=False,
default_language=self.reply_language, compact_prompt=True,
intent_judge=True, prepared_tools=prepared,
person_notes=notes or None)
person_notes=notes or None,
prepared_done=p.said_done if p is not None else None)
finally:
turn_state.reset()

View File

@@ -324,7 +324,11 @@ which carry Discord's own time.
intent judge's tool pick for it on its own thread, with the asker's dialogue memory and the tool
catalogue the reply will have. A `reply` from that user whose text is about the same (letters and
digits, 85% alike), within 30 s and with the dialogue memory unchanged, uses that pick instead of
making its own, waiting up to 5 s for one still being made. Each prepared judgement is used at most once.
making its own, waiting up to 5 s for one still being made. On a follow-up turn (an earlier answer
of Jarvis in the asker's dialogue memory) the same prepare then asks the done-by-user guard's first
question for that text (`jarvis/reply/reply.spec.md`, "Earlier answers after the user did it"), and
that reply's guard uses it, waiting up to 5 s for it, instead of asking after the answer is made;
the reply itself does not wait for it. Each prepared judgement is used at most once.
One `prepare` per user runs at a time: while it runs only the newest text waits, a text about the
same as the one last prepared is dropped, and a `reply` from that user drops the waiting text.
Nothing is sent back; without a brain, or with one that cannot prepare, it is ignored.

View File

@@ -29,7 +29,7 @@ def _content(text: str) -> dict:
def _run(mock_config, db, dialogue_memory, *, text, chat_replies, done="yes", earlier=True, tool_first=False,
tool_text="ok", others=()):
tool_text="ok", others=(), prepared_done=None):
"""``done``: the judge's word for "the user says they did it"; a reply is judged a refusal when
it is one of REFUSALS. ``tool_text``: what the tool returns; ``others``: history lines of other
people, after Jarvis's answer."""
@@ -71,7 +71,7 @@ def _run(mock_config, db, dialogue_memory, *, text, chat_replies, done="yes", ea
patch("jarvis.reply.done_guard.call_llm_direct", side_effect=fake_judge):
reply = engine_mod.run_reply_engine(
db=db, cfg=mock_config, tts=None, text=text, dialogue_memory=dialogue_memory,
history=history, legacy_memory=False, intent_judge=True)
history=history, legacy_memory=False, intent_judge=True, prepared_done=prepared_done)
return reply, seen, judged
@@ -170,3 +170,43 @@ def test_only_jarvis_lines_leave_the_history(mock_config, db, dialogue_memory):
assert reply == SPOKEN
assert quoted in _said(seen[1])
assert "자비스: " + REFUSAL not in _said(seen[1])
@pytest.mark.unit
@pytest.mark.parametrize("said, expected", [(True, SPOKEN), (False, REFUSAL)], ids=["did it", "did not"])
def test_a_judgement_made_ahead_is_not_asked_again(mock_config, db, dialogue_memory, said, expected):
"""The prepare stage judged the words while the user was still speaking (latency, reply.spec.md):
the guard uses that judgement and asks only whether the answer refuses."""
reply, seen, judged = _run(mock_config, db, dialogue_memory, text=DID_IT,
chat_replies=[_content(REFUSAL), _content(SPOKEN)], done="no" if said else "yes",
prepared_done=lambda: said)
assert reply == expected
assert not [j for j in judged if j.startswith("<utterance>")]
@pytest.mark.unit
def test_no_judgement_made_ahead_asks_for_itself(mock_config, db, dialogue_memory):
reply, seen, judged = _run(mock_config, db, dialogue_memory, text=DID_IT,
chat_replies=[_content(REFUSAL), _content(SPOKEN)], prepared_done=lambda: None)
assert reply == SPOKEN
assert DID_IT in judged[0]
@pytest.mark.unit
def test_said_done_ahead_judges_only_a_follow_up(mock_config, dialogue_memory):
"""No earlier answer: no guard would run, so nothing is asked ahead either."""
from jarvis.reply import engine as engine_mod
asked = []
def fake_judge(base_url, model, system, user_content, **kwargs):
asked.append(user_content)
return "yes"
with patch("jarvis.reply.done_guard.call_llm_direct", side_effect=fake_judge):
assert engine_mod.prepare_done_by_user(mock_config, DID_IT, dialogue_memory) is None
assert asked == []
dialogue_memory.add_message("user", QUESTION)
dialogue_memory.add_message("assistant", REFUSAL)
assert engine_mod.prepare_done_by_user(mock_config, DID_IT, dialogue_memory) is True
assert len(asked) == 1 and DID_IT in asked[0]

View File

@@ -1126,14 +1126,20 @@ def _jarvis_brain(tmp_path, monkeypatch, plans):
seen["judged"].append((text, chat_available))
return plans.get(text)
def fake_engine(db, cfg, tts, text, mem, prepared_tools=None, intent_judge=False, **kw):
def fake_engine(db, cfg, tts, text, mem, prepared_tools=None, intent_judge=False, prepared_done=None, **kw):
seen["prepared"].append(prepared_tools)
seen["intent_judge"] = intent_judge
seen.setdefault("done", []).append(prepared_done() if prepared_done is not None else "not passed")
mem.add_message("user", text)
mem.add_message("assistant", "ok")
return "ok"
def fake_done(cfg, text, mem):
seen.setdefault("done_asked", []).append(text)
return True
monkeypatch.setattr(engine, "prepare_intent", fake_prepare)
monkeypatch.setattr(engine, "prepare_done_by_user", fake_done)
monkeypatch.setattr(engine, "run_reply_engine", fake_engine)
return brain_mod.JarvisBrain(), seen
@@ -1170,6 +1176,55 @@ def test_a_prepared_pick_is_not_used_for_other_words_another_person_or_a_changed
assert seen["prepared"][-1] is None
@pytest.mark.unit
def test_a_reply_uses_the_done_by_user_judgement_prepared_for_its_text(tmp_path, monkeypatch):
"""The done-by-user guard's first question is asked while the user still speaks, so a follow-up
turn does not wait for it after the answer (reply.spec.md, "Earlier answers after the user did it")."""
from jarvis.memory.history import HistoryContext
b, seen = _jarvis_brain(tmp_path, monkeypatch, {"자비스 속도 조절했으니 말해 봐": []})
b.prepare("100", "자비스 속도 조절했으니 말해 봐", False)
assert seen["done_asked"] == ["자비스 속도 조절했으니 말해 봐"]
b.reply("100", "자비스, 속도 조절했으니 말해 봐", HistoryContext())
assert seen["done"] == [True]
# Not prepared: the guard asks for itself.
b.reply("100", "자비스, 속도 조절했으니 말해 봐", HistoryContext())
assert seen["done"][-1] == "not passed"
@pytest.mark.unit
def test_a_slow_done_judgement_does_not_hold_up_the_prepared_pick(tmp_path, monkeypatch):
"""The reply starts with the prepared tools at once; only the guard waits for the judgement."""
import threading
import time as _time
from jarvis.memory.history import HistoryContext
import jarvis.reply.engine as engine
b, seen = _jarvis_brain(tmp_path, monkeypatch, {"자비스 날씨 어때": ["getWeather"]})
release = threading.Event()
def slow_done(cfg, text, mem):
release.wait(5)
return False
monkeypatch.setattr(engine, "prepare_done_by_user", slow_done)
started = {}
def fake_engine(db, cfg, tts, text, mem, prepared_tools=None, prepared_done=None, **kw):
started["tools"] = prepared_tools
release.set() # the answer is being made while the judgement finishes
started["done"] = prepared_done()
return "ok"
monkeypatch.setattr(engine, "run_reply_engine", fake_engine)
t = threading.Thread(target=b.prepare, args=("100", "자비스 날씨 어때", False))
t.start()
_time.sleep(0.1)
t0 = _time.monotonic()
b.reply("100", "자비스 날씨 어때?", HistoryContext())
t.join()
assert started == {"tools": ["getWeather"], "done": False}
assert _time.monotonic() - t0 < 2
@pytest.mark.unit
def test_a_reply_waits_for_a_pick_still_being_prepared_for_its_text(tmp_path, monkeypatch):
import threading