Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(voice-engine): act on the P0 method audit

rubenluetke10-beep81282893f3d8
diff --git a/jarvis/voice_engine/bench/__main__.py b/jarvis/voice_engine/bench/__main__.py
index 5143569356..66506a3912 100644
--- a/jarvis/voice_engine/bench/__main__.py
+++ b/jarvis/voice_engine/bench/__main__.py
@@ -65,6 +65,10 @@ def build_parser() -> argparse.ArgumentParser:
llm.add_argument("--tools", action="store_true", help="declare the bench tool set")
common(tools := sub.add_parser("tools", help="tool-call accuracy"), llm=True)
tools.add_argument("--limit", type=int, default=None, help="cases per language")
+ tools.add_argument("--set", dest="case_set", default="main", choices=["main", "hard"],
+ help="hard = utterances that must not end the call or grab the screen")
+ regrade_tools = sub.add_parser("regrade-tools", help="re-score tools reports")
+ regrade_tools.add_argument("reports", type=Path, nargs="+")
common(e2e := sub.add_parser("e2e", help="speech end to first audio"), llm=True)
e2e.add_argument("--tts", default="pocket", choices=["piper", "pocket", "qwen3"])
e2e.add_argument("--voice", default="piper", choices=["piper", "pocket"])
@@ -106,6 +110,10 @@ def main(argv: list[str] | None = None) -> int:
if args.command == "regrade":
print(suites.regrade(args.report))
return 0
+ if args.command == "regrade-tools":
+ for report in args.reports:
+ print(suites.regrade_tools(report))
+ return 0
if args.command == "stt":
payload = suites.run_stt(args.languages, args.voices)
elif args.command == "tts":
@@ -117,7 +125,8 @@ def main(argv: list[str] | None = None) -> int:
num_gpu=args.num_gpu, base_url=args.base_url)
elif args.command == "tools":
payload = suites.run_tools(args.model, args.languages, limit=args.limit,
- num_gpu=args.num_gpu, base_url=args.base_url)
+ num_gpu=args.num_gpu, base_url=args.base_url,
+ case_set=args.case_set)
elif args.command == "e2e":
payload = suites.run_e2e(args.model, args.tts, args.languages, voice_kind=args.voice,
num_gpu=args.num_gpu, base_url=args.base_url,
diff --git a/jarvis/voice_engine/bench/corpus.py b/jarvis/voice_engine/bench/corpus.py
index 17104ed89e..9e0fad3924 100644
--- a/jarvis/voice_engine/bench/corpus.py
+++ b/jarvis/voice_engine/bench/corpus.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import itertools
import json
+import re
from dataclasses import dataclass, field
from functools import cache, lru_cache
from pathlib import Path
@@ -30,6 +31,9 @@ class ToolCase:
tool: str | None # None: the model must answer without a tool
accept: tuple[str, ...] = ()
checks: dict[str, Any] = field(default_factory=dict)
+ # Tools whose call is a serious failure here (e.g. end_call on "thanks").
+ forbidden: tuple[str, ...] = ()
+ hard: bool = False
def _fill(value: Any, slots: dict[str, Any]) -> Any:
@@ -38,8 +42,16 @@ def _fill(value: Any, slots: dict[str, Any]) -> Any:
return value
-def tool_cases(language: str) -> list[ToolCase]:
+def tool_cases(language: str, case_set: str = "main") -> list[ToolCase]:
+ """``main``: the templated tool cases plus direct-answer cases; ``hard``:
+ utterances that must not trigger a destructive tool."""
corpus = load(language)
+ if case_set == "hard":
+ return [
+ ToolCase(language=language, utterance=item["text"], tool=item.get("tool"),
+ forbidden=tuple(item.get("forbidden", ())), hard=True)
+ for item in corpus.get("hard_negatives", [])
+ ]
cases: list[ToolCase] = []
for spec in corpus["tool_cases"]:
slot_names = list(spec.get("slots", {}))
@@ -68,46 +80,91 @@ def tool_cases(language: str) -> list[ToolCase]:
return cases
+_FOLD = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "ß": "ss"}) # i18n-allow: umlauts
+
+
+def fold(text: Any) -> str:
+ """Case- and umlaut-insensitive form, so a transliterated city name still matches."""
+ return str(text).casefold().translate(_FOLD)
+
+
def _matches(rule: dict[str, Any], actual: Any) -> bool:
if "equals" in rule:
expected = rule["equals"]
try:
return float(actual) == float(expected)
except (TypeError, ValueError):
- return str(actual).strip().casefold() == str(expected).strip().casefold()
+ return fold(actual).strip() == fold(expected).strip()
if "contains" in rule:
options = rule["contains"]
options = options if isinstance(options, list) else [options]
- text = str(actual).casefold()
- return any(str(option).casefold() in text for option in options)
+ text = fold(actual)
+ return any(fold(option) in text for option in options)
return True
-def grade(case: ToolCase, calls: list[dict[str, Any]]) -> dict[str, Any]:
- """Score the model's first tool call against the case.
+_CALL_SHAPES = re.compile(r'"name"\s*:|<tool_call>|"arguments"\s*:|function_call|\[TOOL_CALLS\]')
+_DONE_CLAIMS = {
+ "de": re.compile( # i18n-allow: German completion claims the grader detects
+ r"\b(habe|hab|ist|wurde|wurden|sind)\b[^.?!]*\b(gestellt|gesetzt|erstellt|" # i18n-allow
+ r"eingetragen|geöffnet|gestartet|gesendet|geschickt|verschickt|abgespielt|" # i18n-allow
+ r"eingeschaltet|ausgeschaltet|gedimmt|erledigt|gespeichert|angelegt)\b", # i18n-allow
+ re.IGNORECASE,
+ ),
+ "en": re.compile(
+ r"\b(i've|i have|has been|have been|is now|are now|i set|i opened|i sent|i started|"
+ r"i turned|i added|i created|i saved)\b",
+ re.IGNORECASE,
+ ),
+}
+
+
+def _arguments(call: dict[str, Any]) -> dict[str, Any] | None:
+ args = call.get("arguments") or {}
+ if isinstance(args, str):
+ try:
+ args = json.loads(args)
+ except json.JSONDecodeError:
+ return None
+ return args if isinstance(args, dict) else None
+
+
+def grade(case: ToolCase, calls: list[dict[str, Any]], text: str = "") -> dict[str, Any]:
+ """Score the calls of the model's first round against the case.
- Verdicts: ``correct`` (right tool, arguments pass), ``wrong_args``,
- ``wrong_tool``, ``missed`` (no call where one was needed) and
- ``unneeded`` (a call where a direct answer was expected).
+ Verdicts: ``correct``; ``wrong_args``; ``wrong_tool``; ``unneeded`` (a call
+ where a direct answer was expected); ``forbidden`` (a destructive call such
+ as end_call on "thanks"); and for answers without a call where one was
+ needed: ``malformed`` (a call written as text), ``invented`` (claims the
+ action happened), ``clarify`` (asks back) or ``missed``.
"""
+ names = [c.get("name") for c in calls]
+ if any(name in case.forbidden for name in names):
+ return {"verdict": "forbidden", "called": names}
if case.tool is None:
- return {"verdict": "correct" if not calls else "unneeded",
- "called": [c.get("name") for c in calls]}
+ return {"verdict": "correct" if not calls else "unneeded", "called": names}
if not calls:
+ if _CALL_SHAPES.search(text or ""):
+ return {"verdict": "malformed", "called": []}
+ claims = _DONE_CLAIMS.get(case.language)
+ if claims is not None and claims.search(text or ""):
+ return {"verdict": "invented", "called": []}
+ if (text or "").rstrip().endswith("?"):
+ return {"verdict": "clarify", "called": []}
return {"verdict": "missed", "called": []}
- first = calls[0]
- name = first.get("name")
- if name != case.tool and name not in case.accept:
- return {"verdict": "wrong_tool", "called": [c.get("name") for c in calls]}
- if name != case.tool:
- return {"verdict": "correct", "called": [name], "note": "accepted alternative"}
- args = first.get("arguments") or {}
- if isinstance(args, str):
- try:
- args = json.loads(args)
- except json.JSONDecodeError:
- return {"verdict": "wrong_args", "called": [name], "detail": "arguments not JSON"}
+ match = next((c for c in calls if c.get("name") == case.tool), None)
+ if match is None:
+ alternative = next((c for c in calls if c.get("name") in case.accept), None)
+ if alternative is not None:
+ return {"verdict": "correct", "called": names, "note": "accepted alternative"}
+ return {"verdict": "wrong_tool", "called": names}
+ args = _arguments(match)
+ if args is None:
+ return {"verdict": "wrong_args", "called": names, "detail": "arguments not JSON"}
failed = [arg for arg, rule in case.checks.items() if not _matches(rule, args.get(arg))]
if failed:
- return {"verdict": "wrong_args", "called": [name], "failed": failed, "args": args}
- return {"verdict": "correct", "called": [name]}
+ return {"verdict": "wrong_args", "called": names, "failed": failed, "args": args}
+ result: dict[str, Any] = {"verdict": "correct", "called": names}
+ if len(calls) > 1 or calls[0] is not match:
+ result["note"] = "extra calls"
+ return result
diff --git a/jarvis/voice_engine/bench/corpus/de.json b/jarvis/voice_engine/bench/corpus/de.json
index 0f1c9aa260..ca951f79d7 100644
--- a/jarvis/voice_engine/bench/corpus/de.json
+++ b/jarvis/voice_engine/bench/corpus/de.json
@@ -31,31 +31,587 @@
"Wer hat den Faust geschrieben?"
],
"hesitations": [
- {"segments": ["Ich möchte", "einen Termin am Dienstag eintragen."], "pauses_ms": [700]},
- {"segments": ["Kannst du mir", "die Nummer von meinem Zahnarzt", "heraussuchen?"], "pauses_ms": [600, 900]},
- {"segments": ["Spiel mal", "etwas Entspanntes zum Arbeiten."], "pauses_ms": [800]},
- {"segments": ["Also", "ich brauche eine Erinnerung für morgen früh."], "pauses_ms": [900]},
- {"segments": ["Wie war noch mal", "der Name von dem Restaurant", "in dem wir letzte Woche waren?"], "pauses_ms": [700, 1000]},
- {"segments": ["Schreib Anna", "dass ich heute", "etwas später komme."], "pauses_ms": [600, 800]},
- {"segments": ["Mach das Licht", "im Schlafzimmer aus."], "pauses_ms": [500]},
- {"segments": ["Was meinst du", "soll ich heute laufen gehen oder lieber nicht?"], "pauses_ms": [1100]}
+ {
+ "segments": [
+ "Ich möchte",
+ "einen Termin am Dienstag eintragen."
+ ],
+ "pauses_ms": [
+ 700
+ ]
+ },
+ {
+ "segments": [
+ "Kannst du mir",
+ "die Nummer von meinem Zahnarzt",
+ "heraussuchen?"
+ ],
+ "pauses_ms": [
+ 600,
+ 900
+ ]
+ },
+ {
+ "segments": [
+ "Spiel mal",
+ "etwas Entspanntes zum Arbeiten."
+ ],
+ "pauses_ms": [
+ 800
+ ]
+ },
+ {
+ "segments": [
+ "Also",
+ "ich brauche eine Erinnerung für morgen früh."
+ ],
+ "pauses_ms": [
+ 900
+ ]
+ },
+ {
+ "segments": [
+ "Wie war noch mal",
+ "der Name von dem Restaurant",
+ "in dem wir letzte Woche waren?"
+ ],
+ "pauses_ms": [
+ 700,
+ 1000
+ ]
+ },
+ {
+ "segments": [
+ "Schreib Anna",
+ "dass ich heute",
+ "etwas später komme."
+ ],
+ "pauses_ms": [
+ 600,
+ 800
+ ]
+ },
+ {
+ "segments": [
+ "Mach das Licht",
+ "im Schlafzimmer aus."
+ ],
+ "pauses_ms": [
+ 500
+ ]
+ },
+ {
+ "segments": [
+ "Was meinst du",
+ "soll ich heute laufen gehen oder lieber nicht?"
+ ],
+ "pauses_ms": [
+ 1100
+ ]
+ }
],
"tool_cases": [
- {"tool": "set_timer", "accept": ["set_reminder"], "templates": ["Stell einen Timer auf {n} Minuten.", "Timer für {n} Minuten, bitte.", "Kannst du mir einen Timer von {n} Minuten stellen?", "Starte einen Countdown über {n} Minuten.", "Sag mir in {n} Minuten Bescheid."], "slots": {"n": [["fünf", 5], ["zehn", 10], ["zwanzig", 20], ["fünfundvierzig", 45]]}, "check": {"minutes": {"equals": "{n}"}}},
- {"tool": "set_reminder", "templates": ["Erinnere mich morgen früh daran, {task}.", "Erinnere mich heute Abend daran, {task}.", "Kannst du mich um sechs Uhr daran erinnern, {task}?", "Vergiss nicht, mich am Freitag daran zu erinnern, {task}."], "slots": {"task": [["den Müll rauszubringen", "müll"], ["meine Mutter anzurufen", "mutter"], ["die Rechnung zu bezahlen", "rechnung"], ["das Paket abzuholen", "paket"]]}, "check": {"text": {"contains": "{task}"}}},
- {"tool": "get_weather", "templates": ["Wie wird das Wetter morgen in {city}?", "Regnet es heute in {city}?", "Brauche ich in {city} heute einen Regenschirm?", "Wie warm ist es gerade in {city}?"], "slots": {"city": [["München", "münchen"], ["Hamburg", "hamburg"], ["Köln", "köln"], ["Wien", "wien"]]}, "check": {"location": {"contains": "{city}"}}},
- {"tool": "calendar_list_events", "templates": ["Was steht heute in meinem Kalender?", "Welche Termine habe ich morgen?", "Habe ich am Freitag etwas vor?", "Was ist mein nächster Termin?", "Zeig mir meine Termine für diese Woche.", "Bin ich morgen Nachmittag frei?", "Wann ist mein nächstes Meeting?", "Was habe ich am Montag geplant?"]},
- {"tool": "calendar_create_event", "templates": ["Trag {event} für morgen um zehn Uhr ein.", "Leg einen Termin {event} am Freitag um drei an.", "Plane {event} nächsten Dienstag um neun Uhr ein."], "slots": {"event": [["ein Meeting mit Anna", "anna"], ["den Zahnarzt", "zahnarzt"], ["ein Abendessen mit Tom", "tom"]]}, "check": {"title": {"contains": "{event}"}}},
- {"tool": "open_app", "templates": ["Öffne {app}.", "Starte bitte {app}.", "Mach mal {app} auf.", "Kannst du {app} öffnen?"], "slots": {"app": [["Spotify", "spotify"], ["Visual Studio Code", "code"], ["Excel", "excel"], ["den Taschenrechner", ["rechner", "calc"]], ["Google Chrome", "chrome"]]}, "check": {"name": {"contains": "{app}"}}},
- {"tool": "play_music", "templates": ["Spiel {q}.", "Spiel bitte {q} auf Spotify.", "Ich möchte {q} hören.", "Kannst du {q} abspielen?"], "slots": {"q": [["die Playlist Focus", "focus"], ["Bohemian Rhapsody", "bohemian"], ["etwas von Daft Punk", "daft punk"], ["entspannte Jazzmusik", "jazz"]]}, "check": {"query": {"contains": "{q}"}}},
- {"tool": "set_volume", "templates": ["Stell die Lautstärke auf {n} Prozent.", "Lautstärke auf {n}, bitte.", "Mach die Lautstärke auf {n}.", "Setz den Ton auf {n} Prozent."], "slots": {"n": [["dreißig", 30], ["fünfzig", 50], ["achtzig", 80], ["zehn", 10]]}, "check": {"level": {"equals": "{n}"}}},
- {"tool": "search_web", "templates": ["Such im Internet nach {q}.", "Google mal {q}.", "Finde aktuelle Infos zu {q}.", "Recherchiere bitte {q}."], "slots": {"q": [["dem Fusionsreaktor ITER", "iter"], ["den besten Laufschuhen", "lauf"], ["Rezepten für Linsensuppe", "linsen"], ["dem aktuellen Bitcoin-Kurs", "bitcoin"]]}, "check": {"query": {"contains": "{q}"}}},
- {"tool": "send_email", "templates": ["Schreib eine E-Mail an {who} mit dem Betreff Projektstand.", "Schick {who} eine Mail, dass das Meeting verschoben ist.", "Mail an {who}: Ich bin morgen im Homeoffice."], "slots": {"who": [["Anna", "anna"], ["Thomas", "thomas"], ["das Team", "team"]]}, "check": {"to": {"contains": "{who}"}}},
- {"tool": "home_control", "templates": ["Mach das Licht im {room} an.", "Schalte im {room} das Licht ein."], "slots": {"room": [["Wohnzimmer", "wohnzimmer"], ["Schlafzimmer", "schlafzimmer"], ["Büro", "büro"]]}, "check": {"device": {"contains": "{room}"}, "action": {"equals": "on"}}},
- {"tool": "home_control", "templates": ["Mach das Licht im {room} aus.", "Schalte die Lampe im {room} aus."], "slots": {"room": [["Wohnzimmer", "wohnzimmer"], ["Schlafzimmer", "schlafzimmer"], ["Büro", "büro"]]}, "check": {"device": {"contains": "{room}"}, "action": {"equals": "off"}}},
- {"tool": "home_control", "templates": ["Dimm das Licht im {room} auf dreißig Prozent."], "slots": {"room": [["Wohnzimmer", "wohnzimmer"], ["Schlafzimmer", "schlafzimmer"], ["Büro", "büro"]]}, "check": {"device": {"contains": "{room}"}, "action": {"equals": "dim"}, "level": {"equals": 30}}},
- {"tool": "take_appshot", "templates": ["Mach einen Screenshot von dem Fenster.", "Schau dir mal mein Fenster an.", "Nimm ein Appshot auf.", "Guck mal, was ich gerade offen habe.", "Kannst du dir den Fehler hier auf dem Bildschirm anschauen?", "Was siehst du auf meinem Bildschirm?"]},
- {"tool": "end_call", "templates": ["Tschüss Jarvis.", "Leg auf.", "Beende das Gespräch.", "Okay, das war's, bis später.", "Danke, du kannst jetzt auflegen."]}
+ {
+ "tool": "set_timer",
+ "accept": [
+ "set_reminder"
+ ],
+ "templates": [
+ "Stell einen Timer auf {n} Minuten.",
+ "Timer für {n} Minuten, bitte.",
+ "Kannst du mir einen Timer von {n} Minuten stellen?",
+ "Starte einen Countdown über {n} Minuten.",
+ "Sag mir in {n} Minuten Bescheid."
+ ],
+ "slots": {
+ "n": [
+ [
+ "fünf",
+ 5
+ ],
+ [
+ "zehn",
+ 10
+ ],
+ [
+ "zwanzig",
+ 20
+ ],
+ [
+ "fünfundvierzig",
+ 45
+ ]
+ ]
+ },
+ "check": {
+ "minutes": {
+ "equals": "{n}"
+ }
+ }
+ },
+ {
+ "tool": "set_reminder",
+ "templates": [
+ "Erinnere mich morgen früh daran, {task}.",
+ "Erinnere mich heute Abend daran, {task}.",
+ "Kannst du mich um sechs Uhr daran erinnern, {task}?",
+ "Vergiss nicht, mich am Freitag daran zu erinnern, {task}."
+ ],
+ "slots": {
+ "task": [
+ [
+ "den Müll rauszubringen",
+ [
+ "müll",
+ "trash",
+ "garbage",
+ "abfall"
+ ]
+ ],
+ [
+ "meine Mutter anzurufen",
+ [
+ "mutter",
+ "mother",
+ "mom",
+ "mum",
+ "mama"
+ ]
+ ],
+ [
+ "die Rechnung zu bezahlen",
+ [
+ "rechnung",
+ "bill",
+ "invoice"
+ ]
+ ],
+ [
+ "das Paket abzuholen",
+ [
+ "paket",
+ "parcel",
+ "package"
+ ]
+ ]
+ ]
+ },
+ "check": {
+ "text": {
+ "contains": "{task}"
+ }
+ }
+ },
+ {
+ "tool": "get_weather",
+ "templates": [
+ "Wie wird das Wetter morgen in {city}?",
+ "Regnet es heute in {city}?",
+ "Brauche ich in {city} heute einen Regenschirm?",
+ "Wie warm ist es gerade in {city}?"
+ ],
+ "slots": {
+ "city": [
+ [
+ "München",
+ [
+ "münchen",
+ "munich"
+ ]
+ ],
+ [
+ "Hamburg",
+ "hamburg"
+ ],
+ [
+ "Köln",
+ [
+ "köln",
+ "cologne"
+ ]
+ ],
+ [
+ "Wien",
+ [
+ "wien",
+ "vienna"
+ ]
+ ]
+ ]
+ },
+ "check": {
+ "location": {
+ "contains": "{city}"
+ }
+ }
+ },
+ {
+ "tool": "calendar_list_events",
+ "templates": [
+ "Was steht heute in meinem Kalender?",
+ "Welche Termine habe ich morgen?",
+ "Habe ich am Freitag etwas vor?",
+ "Was ist mein nächster Termin?",
+ "Zeig mir meine Termine für diese Woche.",
+ "Bin ich morgen Nachmittag frei?",
+ "Wann ist mein nächstes Meeting?",
+ "Was habe ich am Montag geplant?"
+ ]
+ },
+ {
+ "tool": "calendar_create_event",
+ "templates": [
+ "Trag {event} für morgen um zehn Uhr ein.",
+ "Leg einen Termin {event} am Freitag um drei an.",
+ "Plane {event} nächsten Dienstag um neun Uhr ein."
+ ],
+ "slots": {
+ "event": [
+ [
+ "ein Meeting mit Anna",
+ "anna"
+ ],
+ [
+ "den Zahnarzt",
+ [
+ "zahnarzt",
+ "dentist"
+ ]
+ ],
+ [
+ "ein Abendessen mit Tom",
+ "tom"
+ ]
+ ]
+ },
+ "check": {
+ "title": {
+ "contains": "{event}"
+ }
+ }
+ },
+ {
+ "tool": "open_app",
+ "templates": [
+ "Öffne {app}.",
+ "Starte bitte {app}.",
+ "Mach mal {app} auf.",
+ "Kannst du {app} öffnen?"
+ ],
+ "slots": {
+ "app": [
+ [
+ "Spotify",
+ "spotify"
+ ],
+ [
+ "Visual Studio Code",
+ "code"
+ ],
+ [
+ "Excel",
+ "excel"
+ ],
+ [
+ "den Taschenrechner",
+ [
+ "rechner",
+ "calc"
+ ]
+ ],
+ [
+ "Google Chrome",
+ "chrome"
+ ]
+ ]
+ },
+ "check": {
+ "name": {
+ "contains": "{app}"
+ }
+ }
+ },
+ {
+ "tool": "play_music",
+ "templates": [
+ "Spiel {q}.",
+ "Spiel bitte {q} auf Spotify.",
+ "Ich möchte {q} hören.",
+ "Kannst du {q} abspielen?"
+ ],
+ "slots": {
+ "q": [
+ [
+ "die Playlist Focus",
+ "focus"
+ ],
+ [
+ "Bohemian Rhapsody",
+ "bohemian"
+ ],
+ [
+ "etwas von Daft Punk",
+ "daft punk"
+ ],
+ [
+ "entspannte Jazzmusik",
+ "jazz"
+ ]
+ ]
+ },
+ "check": {
+ "query": {
+ "contains": "{q}"
+ }
+ }
+ },
+ {
+ "tool": "set_volume",
+ "templates": [
+ "Stell die Lautstärke auf {n} Prozent.",
+ "Lautstärke auf {n}, bitte.",
+ "Mach die Lautstärke auf {n}.",
+ "Setz den Ton auf {n} Prozent."
+ ],
+ "slots": {
+ "n": [
+ [
+ "dreißig",
+ 30
+ ],
+ [
+ "fünfzig",
+ 50
+ ],
+ [
+ "achtzig",
+ 80
+ ],
+ [
+ "zehn",
+ 10
+ ]
+ ]
+ },
+ "check": {
+ "level": {
+ "equals": "{n}"
+ }
+ }
+ },
+ {
+ "tool": "search_web",
+ "templates": [
+ "Such im Internet nach {q}.",
+ "Google mal {q}.",
+ "Finde aktuelle Infos zu {q}.",
+ "Recherchiere bitte {q}."
+ ],
+ "slots": {
+ "q": [
+ [
+ "dem Fusionsreaktor ITER",
+ "iter"
+ ],
+ [
+ "den besten Laufschuhen",
+ [
+ "lauf",
+ "running",
+ "run"
+ ]
+ ],
+ [
+ "Rezepten für Linsensuppe",
+ [
+ "linsen",
+ "lentil"
+ ]
+ ],
+ [
+ "dem aktuellen Bitcoin-Kurs",
+ "bitcoin"
+ ]
+ ]
+ },
+ "check": {
+ "query": {
+ "contains": "{q}"
+ }
+ }
+ },
+ {
+ "tool": "send_email",
+ "templates": [
+ "Schreib eine E-Mail an {who} mit dem Betreff Projektstand.",
+ "Schick {who} eine Mail, dass das Meeting verschoben ist.",
+ "Mail an {who}: Ich bin morgen im Homeoffice."
+ ],
+ "slots": {
+ "who": [
+ [
+ "Anna",
+ "anna"
+ ],
+ [
+ "Thomas",
+ "thomas"
+ ],
+ [
+ "das Team",
+ "team"
+ ]
+ ]
+ },
+ "check": {
+ "to": {
+ "contains": "{who}"
+ }
+ }
+ },
+ {
+ "tool": "home_control",
+ "templates": [
+ "Mach das Licht im {room} an.",
+ "Schalte im {room} das Licht ein."
+ ],
+ "slots": {
+ "room": [
+ [
+ "Wohnzimmer",
+ [
+ "wohnzimmer",
+ "living"
+ ]
+ ],
+ [
+ "Schlafzimmer",
+ [
+ "schlafzimmer",
+ "bedroom"
+ ]
+ ],
+ [
+ "Büro",
+ [
+ "büro",
+ "office"
+ ]
+ ]
+ ]
+ },
+ "check": {
+ "device": {
+ "contains": "{room}"
+ },
+ "action": {
+ "equals": "on"
+ }
+ }
+ },
+ {
+ "tool": "home_control",
+ "templates": [
+ "Mach das Licht im {room} aus.",
+ "Schalte die Lampe im {room} aus."
+ ],
+ "slots": {
+ "room": [
+ [
+ "Wohnzimmer",
+ [
+ "wohnzimmer",
+ "living"
+ ]
+ ],
+ [
+ "Schlafzimmer",
+ [
+ "schlafzimmer",
+ "bedroom"
+ ]
+ ],
+ [
+ "Büro",
+ [
+ "büro",
+ "office"
+ ]
+ ]
+ ]
+ },
+ "check": {
+ "device": {
+ "contains": "{room}"
+ },
+ "action": {
+ "equals": "off"
+ }
+ }
+ },
+ {
+ "tool": "home_control",
+ "templates": [
+ "Dimm das Licht im {room} auf dreißig Prozent."
+ ],
+ "slots": {
+ "room": [
+ [
+ "Wohnzimmer",
+ [
+ "wohnzimmer",
+ "living"
+ ]
+ ],
+ [
+ "Schlafzimmer",
+ [
+ "schlafzimmer",
+ "bedroom"
+ ]
+ ],
+ [
+ "Büro",
+ [
+ "büro",
+ "office"
+ ]
+ ]
+ ]
+ },
+ "check": {
+ "device": {
+ "contains": "{room}"
+ },
+ "action": {
+ "equals": "dim"
+ },
+ "level": {
+ "equals": 30
+ }
+ }
+ },
+ {
+ "tool": "take_appshot",
+ "templates": [
+ "Mach einen Screenshot von dem Fenster.",
+ "Schau dir mal mein Fenster an.",
+ "Nimm ein Appshot auf.",
+ "Guck mal, was ich gerade offen habe.",
+ "Kannst du dir den Fehler hier auf dem Bildschirm anschauen?",
+ "Was siehst du auf meinem Bildschirm?"
+ ]
+ },
+ {
+ "tool": "end_call",
+ "templates": [
+ "Tschüss Jarvis.",
+ "Leg auf.",
+ "Beende das Gespräch.",
+ "Okay, das war's, bis später.",
+ "Danke, du kannst jetzt auflegen."
+ ]
+ }
],
"no_tool": [
"Wie geht's dir heute?",
@@ -88,5 +644,63 @@
"Wie nennt man ein Baby-Känguru?",
"Was ist schwerer, ein Kilo Federn oder ein Kilo Eisen?",
"Hilf mir, ein Wort für sehr glücklich zu finden."
+ ],
+ "hard_negatives": [
+ {
+ "text": "Danke!",
+ "tool": null,
+ "forbidden": [
+ "end_call"
+ ]
+ },
+ {
+ "text": "Moment, bleib kurz dran.",
+ "tool": null,
+ "forbidden": [
+ "end_call"
+ ]
+ },
+ {
+ "text": "Ich bin gleich zurück.",
+ "tool": null,
+ "forbidden": [
+ "end_call"
+ ]
+ },
+ {
+ "text": "Okay, danke dir, das hilft mir.",
+ "tool": null,
+ "forbidden": [
+ "end_call"
+ ]
+ },
+ {
+ "text": "Warte kurz, ich muss überlegen.",
+ "tool": null,
+ "forbidden": [
+ "end_call"
+ ]
+ },
+ {
+ "text": "Schau mal, ob es morgen in Berlin regnet.",
+ "tool": "get_weather",
+ "forbidden": [
+ "take_appshot"
+ ]
+ },
+ {
+ "text": "Guck mal nach, wann mein nächster Termin ist.",
+ "tool": "calendar_list_events",
+ "forbidden": [
+ "take_appshot"
+ ]
+ },
+ {
+ "text": "Sag Bescheid, wenn du fertig bist.",
+ "tool": null,
+ "forbidden": [
+ "end_call"
+ ]
+ }
]
}
diff --git a/jarvis/voice_engine/bench/corpus/en.json b/jarvis/voice_engine/bench/corpus/en.json
index 374228354e..2bd66656f9 100644
--- a/jarvis/voice_engine/bench/corpus/en.json
+++ b/jarvis/voice_engine/bench/corpus/en.json
@@ -31,31 +31,539 @@
"Who wrote Pride and Prejudice?"
],
"hesitations": [
- {"segments": ["I would like to", "add an appointment on Tuesday."], "pauses_ms": [700]},
- {"segments": ["Can you", "find the number of my dentist", "for me?"], "pauses_ms": [600, 900]},
- {"segments": ["Play something", "relaxing for work."], "pauses_ms": [800]},
- {"segments": ["So", "I need a reminder for tomorrow morning."], "pauses_ms": [900]},
- {"segments": ["What was the name", "of the restaurant", "we went to last week?"], "pauses_ms": [700, 1000]},
- {"segments": ["Tell Anna", "that I will be", "a little late today."], "pauses_ms": [600, 800]},
- {"segments": ["Turn off the light", "in the bedroom."], "pauses_ms": [500]},
- {"segments": ["What do you think", "should I go for a run today or not?"], "pauses_ms": [1100]}
+ {
+ "segments": [
+ "I would like to",
+ "add an appointment on Tuesday."
+ ],
+ "pauses_ms": [
+ 700
+ ]
+ },
+ {
+ "segments": [
+ "Can you",
+ "find the number of my dentist",
+ "for me?"
+ ],
+ "pauses_ms": [
+ 600,
+ 900
+ ]
+ },
+ {
+ "segments": [
+ "Play something",
+ "relaxing for work."
+ ],
+ "pauses_ms": [
+ 800
+ ]
+ },
+ {
+ "segments": [
+ "So",
+ "I need a reminder for tomorrow morning."
+ ],
+ "pauses_ms": [
+ 900
+ ]
+ },
+ {
+ "segments": [
+ "What was the name",
+ "of the restaurant",
+ "we went to last week?"
+ ],
+ "pauses_ms": [
+ 700,
+ 1000
+ ]
+ },
+ {
+ "segments": [
+ "Tell Anna",
+ "that I will be",
+ "a little late today."
+ ],
+ "pauses_ms": [
+ 600,
+ 800
+ ]
+ },
+ {
+ "segments": [
+ "Turn off the light",
+ "in the bedroom."
+ ],
+ "pauses_ms": [
+ 500
+ ]
+ },
+ {
+ "segments": [
+ "What do you think",
+ "should I go for a run today or not?"
+ ],
+ "pauses_ms": [
+ 1100
+ ]
+ }
],
"tool_cases": [
- {"tool": "set_timer", "accept": ["set_reminder"], "templates": ["Set a timer for {n} minutes.", "Timer for {n} minutes, please.", "Can you start a {n} minute timer?", "Start a countdown of {n} minutes.", "Let me know in {n} minutes."], "slots": {"n": [["five", 5], ["ten", 10], ["twenty", 20], ["forty-five", 45]]}, "check": {"minutes": {"equals": "{n}"}}},
- {"tool": "set_reminder", "templates": ["Remind me tomorrow morning to {task}.", "Remind me tonight to {task}.", "Can you remind me at six to {task}?", "Don't forget to remind me on Friday to {task}."], "slots": {"task": [["take out the trash", "trash"], ["call my mother", "mother"], ["pay the bill", "bill"], ["pick up the parcel", "parcel"]]}, "check": {"text": {"contains": "{task}"}}},
- {"tool": "get_weather", "templates": ["What will the weather be like tomorrow in {city}?", "Is it raining in {city} today?", "Do I need an umbrella in {city} today?", "How warm is it in {city} right now?"], "slots": {"city": [["Munich", "munich"], ["Hamburg", "hamburg"], ["London", "london"], ["Vienna", "vienna"]]}, "check": {"location": {"contains": "{city}"}}},
- {"tool": "calendar_list_events", "templates": ["What's on my calendar today?", "Which appointments do I have tomorrow?", "Do I have anything on Friday?", "What is my next appointment?", "Show me my events for this week.", "Am I free tomorrow afternoon?", "When is my next meeting?", "What do I have planned on Monday?"]},
- {"tool": "calendar_create_event", "templates": ["Add {event} for tomorrow at ten.", "Create an appointment {event} on Friday at three.", "Schedule {event} next Tuesday at nine."], "slots": {"event": [["a meeting with Anna", "anna"], ["the dentist", "dentist"], ["dinner with Tom", "tom"]]}, "check": {"title": {"contains": "{event}"}}},
- {"tool": "open_app", "templates": ["Open {app}.", "Please start {app}.", "Launch {app}.", "Can you open {app}?"], "slots": {"app": [["Spotify", "spotify"], ["Visual Studio Code", "code"], ["Excel", "excel"], ["the calculator", "calc"], ["Google Chrome", "chrome"]]}, "check": {"name": {"contains": "{app}"}}},
- {"tool": "play_music", "templates": ["Play {q}.", "Please play {q} on Spotify.", "I want to listen to {q}.", "Can you put on {q}?"], "slots": {"q": [["the Focus playlist", "focus"], ["Bohemian Rhapsody", "bohemian"], ["something by Daft Punk", "daft punk"], ["relaxing jazz", "jazz"]]}, "check": {"query": {"contains": "{q}"}}},
- {"tool": "set_volume", "templates": ["Set the volume to {n} percent.", "Volume {n}, please.", "Turn the volume to {n}.", "Put the sound at {n} percent."], "slots": {"n": [["thirty", 30], ["fifty", 50], ["eighty", 80], ["ten", 10]]}, "check": {"level": {"equals": "{n}"}}},
- {"tool": "search_web", "templates": ["Search the web for {q}.", "Google {q}.", "Find current information about {q}.", "Please look up {q}."], "slots": {"q": [["the ITER fusion reactor", "iter"], ["the best running shoes", "running"], ["lentil soup recipes", "lentil"], ["the current bitcoin price", "bitcoin"]]}, "check": {"query": {"contains": "{q}"}}},
- {"tool": "send_email", "templates": ["Write an email to {who} with the subject project status.", "Send {who} a mail that the meeting is postponed.", "Email {who}: I am working from home tomorrow."], "slots": {"who": [["Anna", "anna"], ["Thomas", "thomas"], ["the team", "team"]]}, "check": {"to": {"contains": "{who}"}}},
- {"tool": "home_control", "templates": ["Turn on the light in the {room}.", "Switch the {room} light on."], "slots": {"room": [["living room", "living"], ["bedroom", "bedroom"], ["office", "office"]]}, "check": {"device": {"contains": "{room}"}, "action": {"equals": "on"}}},
- {"tool": "home_control", "templates": ["Turn off the light in the {room}.", "Switch off the lamp in the {room}."], "slots": {"room": [["living room", "living"], ["bedroom", "bedroom"], ["office", "office"]]}, "check": {"device": {"contains": "{room}"}, "action": {"equals": "off"}}},
- {"tool": "home_control", "templates": ["Dim the light in the {room} to thirty percent."], "slots": {"room": [["living room", "living"], ["bedroom", "bedroom"], ["office", "office"]]}, "check": {"device": {"contains": "{room}"}, "action": {"equals": "dim"}, "level": {"equals": 30}}},
- {"tool": "take_appshot", "templates": ["Take a screenshot of this window.", "Have a look at my window.", "Take an appshot.", "Look at what I have open right now.", "Can you look at the error on my screen?", "What do you see on my screen?"]},
- {"tool": "end_call", "templates": ["Bye Jarvis.", "Hang up.", "End the call.", "Okay, that's it, talk later.", "Thanks, you can hang up now."]}
+ {
+ "tool": "set_timer",
+ "accept": [
+ "set_reminder"
+ ],
+ "templates": [
+ "Set a timer for {n} minutes.",
+ "Timer for {n} minutes, please.",
+ "Can you start a {n} minute timer?",
+ "Start a countdown of {n} minutes.",
+ "Let me know in {n} minutes."
+ ],
+ "slots": {
+ "n": [
+ [
+ "five",
+ 5
+ ],
+ [
+ "ten",
+ 10
+ ],
+ [
+ "twenty",
+ 20
+ ],
+ [
+ "forty-five",
+ 45
+ ]
+ ]
+ },
+ "check": {
+ "minutes": {
+ "equals": "{n}"
+ }
+ }
+ },
+ {
+ "tool": "set_reminder",
+ "templates": [
+ "Remind me tomorrow morning to {task}.",
+ "Remind me tonight to {task}.",
+ "Can you remind me at six to {task}?",
+ "Don't forget to remind me on Friday to {task}."
+ ],
+ "slots": {
+ "task": [
+ [
+ "take out the trash",
+ [
+ "trash",
+ "garbage",
+ "rubbish"
+ ]
+ ],
+ [
+ "call my mother",
+ [
+ "mother",
+ "mom",
+ "mum"
+ ]
+ ],
+ [
+ "pay the bill",
+ "bill"
+ ],
+ [
+ "pick up the parcel",
+ [
+ "parcel",
+ "package"
+ ]
+ ]
+ ]
+ },
+ "check": {
+ "text": {
+ "contains": "{task}"
+ }
+ }
+ },
+ {
+ "tool": "get_weather",
+ "templates": [
+ "What will the weather be like tomorrow in {city}?",
+ "Is it raining in {city} today?",
+ "Do I need an umbrella in {city} today?",
+ "How warm is it in {city} right now?"
+ ],
+ "slots": {
+ "city": [
+ [
+ "Munich",
+ [
+ "munich",
+ "muenchen"
+ ]
+ ],
+ [
+ "Hamburg",
+ "hamburg"
+ ],
+ [
+ "London",
+ "london"
+ ],
+ [
+ "Vienna",
+ [
+ "vienna",
+ "wien"
+ ]
+ ]
+ ]
+ },
+ "check": {
+ "location": {
+ "contains": "{city}"
+ }
+ }
+ },
+ {
+ "tool": "calendar_list_events",
+ "templates": [
+ "What's on my calendar today?",
+ "Which appointments do I have tomorrow?",
+ "Do I have anything on Friday?",
+ "What is my next appointment?",
+ "Show me my events for this week.",
+ "Am I free tomorrow afternoon?",
+ "When is my next meeting?",
+ "What do I have planned on Monday?"
+ ]
+ },
+ {
+ "tool": "calendar_create_event",
+ "templates": [
+ "Add {event} for tomorrow at ten.",
+ "Create an appointment {event} on Friday at three.",
+ "Schedule {event} next Tuesday at nine."
+ ],
+ "slots": {
+ "event": [
+ [
+ "a meeting with Anna",
+ "anna"
+ ],
+ [
+ "the dentist",
+ "dentist"
+ ],
+ [
+ "dinner with Tom",
+ "tom"
+ ]
+ ]
+ },
+ "check": {
+ "title": {
+ "contains": "{event}"
+ }
+ }
+ },
+ {
+ "tool": "open_app",
+ "templates": [
+ "Open {app}.",
+ "Please start {app}.",
+ "Launch {app}.",
+ "Can you open {app}?"
+ ],
+ "slots": {
+ "app": [
+ [
+ "Spotify",
+ "spotify"
+ ],
+ [
+ "Visual Studio Code",
+ "code"
+ ],
+ [
+ "Excel",
+ "excel"
+ ],
+ [
+ "the calculator",
+ "calc"
+ ],
+ [
+ "Google Chrome",
+ "chrome"
+ ]
+ ]
+ },
+ "check": {
+ "name": {
+ "contains": "{app}"
+ }
+ }
+ },
+ {
+ "tool": "play_music",
+ "templates": [
+ "Play {q}.",
+ "Please play {q} on Spotify.",
+ "I want to listen to {q}.",
+ "Can you put on {q}?"
+ ],
+ "slots": {
+ "q": [
+ [
+ "the Focus playlist",
+ "focus"
+ ],
+ [
+ "Bohemian Rhapsody",
+ "bohemian"
+ ],
+ [
+ "something by Daft Punk",
+ "daft punk"
+ ],
+ [
+ "relaxing jazz",
+ "jazz"
+ ]
+ ]
+ },
+ "check": {
+ "query": {
+ "contains": "{q}"
+ }
+ }
+ },
+ {
+ "tool": "set_volume",
+ "templates": [
+ "Set the volume to {n} percent.",
+ "Volume {n}, please.",
+ "Turn the volume to {n}.",
+ "Put the sound at {n} percent."
+ ],
+ "slots": {
+ "n": [
+ [
+ "thirty",
+ 30
+ ],
+ [
+ "fifty",
+ 50
+ ],
+ [
+ "eighty",
+ 80
+ ],
+ [
+ "ten",
+ 10
+ ]
+ ]
+ },
+ "check": {
+ "level": {
+ "equals": "{n}"
+ }
+ }
+ },
+ {
+ "tool": "search_web",
+ "templates": [
+ "Search the web for {q}.",
+ "Google {q}.",
+ "Find current information about {q}.",
+ "Please look up {q}."
+ ],
+ "slots": {
+ "q": [
+ [
+ "the ITER fusion reactor",
+ "iter"
+ ],
+ [
+ "the best running shoes",
+ [
+ "running",
+ "run"
+ ]
+ ],
+ [
+ "lentil soup recipes",
+ "lentil"
+ ],
+ [
+ "the current bitcoin price",
+ "bitcoin"
+ ]
+ ]
+ },
+ "check": {
+ "query": {
+ "contains": "{q}"
+ }
+ }
+ },
+ {
+ "tool": "send_email",
+ "templates": [
+ "Write an email to {who} with the subject project status.",
+ "Send {who} a mail that the meeting is postponed.",
+ "Email {who}: I am working from home tomorrow."
+ ],
+ "slots": {
+ "who": [
+ [
+ "Anna",
+ "anna"
+ ],
+ [
+ "Thomas",
+ "thomas"
+ ],
+ [
+ "the team",
+ "team"
+ ]
+ ]
+ },
+ "check": {
+ "to": {
+ "contains": "{who}"
+ }
+ }
+ },
+ {
+ "tool": "home_control",
+ "templates": [
+ "Turn on the light in the {room}.",
+ "Switch the {room} light on."
+ ],
+ "slots": {
+ "room": [
+ [
+ "living room",
+ "living"
+ ],
+ [
+ "bedroom",
+ "bedroom"
+ ],
+ [
+ "office",
+ "office"
+ ]
+ ]
+ },
+ "check": {
+ "device": {
+ "contains": "{room}"
+ },
+ "action": {
+ "equals": "on"
+ }
+ }
+ },
+ {
+ "tool": "home_control",
+ "templates": [
+ "Turn off the light in the {room}.",
+ "Switch off the lamp in the {room}."
+ ],
+ "slots": {
+ "room": [
+ [
+ "living room",
+ "living"
+ ],
+ [
+ "bedroom",
+ "bedroom"
+ ],
+ [
+ "office",
+ "office"
+ ]
+ ]
+ },
+ "check": {
+ "device": {
+ "contains": "{room}"
+ },
+ "action": {
+ "equals": "off"
+ }
+ }
+ },
+ {
+ "tool": "home_control",
+ "templates": [
+ "Dim the light in the {room} to thirty percent."
+ ],
+ "slots": {
+ "room": [
+ [
+ "living room",
+ "living"
+ ],
+ [
+ "bedroom",
+ "bedroom"
+ ],
+ [
+ "office",
+ "office"
+ ]
+ ]
+ },
+ "check": {
+ "device": {
+ "contains": "{room}"
+ },
+ "action": {
+ "equals": "dim"
+ },
+ "level": {
+ "equals": 30
+ }
+ }
+ },
+ {
+ "tool": "take_appshot",
+ "templates": [
+ "Take a screenshot of this window.",
+ "Have a look at my window.",
+ "Take an appshot.",
+ "Look at what I have open right now.",
+ "Can you look at the error on my screen?",
+ "What do you see on my screen?"
+ ]
+ },
+ {
+ "tool": "end_call",
+ "templates": [
+ "Bye Jarvis.",
+ "Hang up.",
+ "End the call.",
+ "Okay, that's it, talk later.",
+ "Thanks, you can hang up now."
+ ]
+ }
],
"no_tool": [
"How are you today?",
@@ -88,5 +596,63 @@
"What is a baby kangaroo called?",
"Which is heavier, a kilo of feathers or a kilo of iron?",
"Help me find a word for very happy."
+ ],
+ "hard_negatives": [
+ {
+ "text": "Thanks!",
+ "tool": null,
+ "forbidden": [
+ "end_call"
+ ]
+ },
+ {
+ "text": "Hold on, stay with me.",
+ "tool": null,
+ "forbidden": [
+ "end_call"
+ ]
+ },
+ {
+ "text": "I'll be right back.",
+ "tool": null,
+ "forbidden": [
+ "end_call"
+ ]
+ },
+ {
+ "text": "Okay, thanks, that helps.",
+ "tool": null,
+ "forbidden": [
+ "end_call"
+ ]
+ },
+ {
+ "text": "Wait a second, let me think.",
+ "tool": null,
+ "forbidden": [
+ "end_call"
+ ]
+ },
+ {
+ "text": "Look whether it will rain in Berlin tomorrow.",
+ "tool": "get_weather",
+ "forbidden": [
+ "take_appshot"
+ ]
+ },
+ {
+ "text": "Check when my next appointment is.",
+ "tool": "calendar_list_events",
+ "forbidden": [
+ "take_appshot"
+ ]
+ },
+ {
+ "text": "Let me know when you are done.",
+ "tool": null,
+ "forbidden": [
+ "end_call"
+ ]
+ }
]
}
diff --git a/jarvis/voice_engine/bench/report.py b/jarvis/voice_engine/bench/report.py
index 6f386c2f9c..feed12c0a7 100644
--- a/jarvis/voice_engine/bench/report.py
+++ b/jarvis/voice_engine/bench/report.py
@@ -10,10 +10,14 @@ from typing import Any
def _key(report: dict[str, Any]) -> str:
suite = report.get("suite", "?")
parts = [suite]
- for field in ("model", "engine", "tts", "voice", "num_gpu", "with_tools"):
+ for field in ("model", "engine", "tts", "voice", "num_gpu", "with_tools", "case_set",
+ "options", "tts_options"):
value = report.get(field)
- if value not in (None, False, ""):
+ if value not in (None, False, "", {}):
parts.append(f"{field}={value}")
+ languages = sorted({i.get("language") for i in report.get("items", []) if i.get("language")})
+ if languages:
+ parts.append("lang=" + ",".join(languages))
return " ".join(parts)
diff --git a/jarvis/voice_engine/bench/suites.py b/jarvis/voice_engine/bench/suites.py
index 45bf940001..89e190cdb6 100644
--- a/jarvis/voice_engine/bench/suites.py
+++ b/jarvis/voice_engine/bench/suites.py
@@ -304,43 +304,85 @@ def run_llm(model: str, languages: list[str], *, with_tools: bool, num_gpu: int
def run_tools(model: str, languages: list[str], *, limit: int | None, num_gpu: int | None,
- base_url: str) -> dict[str, Any]:
+ base_url: str, case_set: str = "main") -> dict[str, Any]:
llm = OllamaChat(model, base_url=base_url, num_gpu=num_gpu, temperature=0.0)
llm.warm()
tools = corpus.tools()
items: list[dict[str, Any]] = []
for language in languages:
system = {"role": "system", "content": corpus.load(language)["system_prompt"]}
- cases = corpus.tool_cases(language)
+ llm.chat([system, {"role": "user", "content": "Hi."}], tools=tools) # warm-up
+ cases = corpus.tool_cases(language, case_set)
if limit:
step = max(1, len(cases) // limit)
cases = cases[::step][:limit]
for case in cases:
result = llm.chat([system, {"role": "user", "content": case.utterance}], tools=tools)
- verdict = corpus.grade(case, result.tool_calls)
+ verdict = corpus.grade(case, result.tool_calls, result.text)
items.append({
"language": language, "utterance": case.utterance, "expected": case.tool,
- "calls": result.tool_calls, "text": result.text[:200], "error": result.error,
+ "calls": result.tool_calls, "text": result.text[:400], "error": result.error,
+ "thinking_chars": result.thinking_chars,
"decision_ms": _ms(result.t_done), **verdict,
})
- groups = {}
+ return {"model": model, "num_gpu": num_gpu, "case_set": case_set, "temperature": 0.0,
+ "groups": tool_groups(items, languages), "items": items}
+
+
+_VERDICTS = ("correct", "wrong_args", "wrong_tool", "missed", "malformed", "invented",
+ "clarify", "unneeded", "forbidden")
+
+
+def tool_groups(items: list[dict[str, Any]], languages: list[str]) -> dict[str, Any]:
+ groups: dict[str, Any] = {}
for language in languages:
rows = [i for i in items if i["language"] == language]
+ if not rows:
+ continue
needed = [r for r in rows if r["expected"] is not None]
- direct = [r for r in rows if r["expected"] is None]
+ per_tool: dict[str, list[bool]] = {}
+ for row in needed:
+ per_tool.setdefault(row["expected"], []).append(row["verdict"] == "correct")
groups[language] = {
"cases": len(rows),
"accuracy": round(sum(r["verdict"] == "correct" for r in rows) / len(rows), 3),
"tool_accuracy": round(
sum(r["verdict"] == "correct" for r in needed) / len(needed), 3
) if needed else None,
- "missed": sum(r["verdict"] == "missed" for r in rows),
- "wrong_tool": sum(r["verdict"] == "wrong_tool" for r in rows),
- "wrong_args": sum(r["verdict"] == "wrong_args" for r in rows),
- "unneeded": sum(r["verdict"] == "unneeded" for r in direct),
+ "tool_accuracy_macro": round(
+ float(np.mean([np.mean(v) for v in per_tool.values()])), 3
+ ) if per_tool else None,
+ "per_tool": {k: round(float(np.mean(v)), 3) for k, v in sorted(per_tool.items())},
+ **{v: sum(r["verdict"] == v for r in rows) for v in _VERDICTS if v != "correct"},
+ "alternatives": sum(r.get("note") == "accepted alternative" for r in rows),
+ "thinking_items": sum(1 for r in rows if r.get("thinking_chars")),
"decision_ms": summary(r["decision_ms"] for r in rows),
}
- return {"model": model, "num_gpu": num_gpu, "groups": groups, "items": items}
+ return groups
+
+
+def regrade_tools(report_path: Path) -> Path:
+ """Re-score a tools report with the current corpus and grader (stored calls)."""
+ report = json.loads(report_path.read_text(encoding="utf-8"))
+ case_set = report.get("case_set", "main")
+ lookup = {
+ (case.language, case.utterance): case
+ for language in corpus.LANGUAGES
+ for case in corpus.tool_cases(language, case_set)
+ }
+ for item in report["items"]:
+ case = lookup.get((item["language"], item["utterance"]))
+ if case is None:
+ item["verdict"] = "unknown_case"
+ continue
+ for key in ("note", "failed", "args", "detail"):
+ item.pop(key, None)
+ item.update(corpus.grade(case, item.get("calls") or [], item.get("text") or ""))
+ languages = sorted({i["language"] for i in report["items"]})
+ report["groups"] = tool_groups(report["items"], languages)
+ report["regraded_with"] = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
+ return report_path
# ── End to end ───────────────────────────────────────────────────────────────
diff --git a/jarvis/voice_engine/engine.py b/jarvis/voice_engine/engine.py
index 165d2a56d6..4a2b798834 100644
--- a/jarvis/voice_engine/engine.py
+++ b/jarvis/voice_engine/engine.py
@@ -17,6 +17,7 @@ from __future__ import annotations
import asyncio
import json
import logging
+import re
import threading
import time
import uuid
@@ -95,6 +96,13 @@ class EngineConfig:
preroll_ms: int = 300
turn_threshold: float = 0.5
incomplete_wait_ms: int = 1000
+ # Re-score the turn at this spacing while waiting on an "incomplete"
+ # verdict: more trailing silence often turns it into "complete".
+ reevaluate_ms: int = 300
+ # Start transcribing after this much quiet, ahead of the turn decision.
+ early_stt_ms: int = 96
+ # Amplitude below which synthesized audio counts as silence (about -42 dBFS).
+ tts_silence: float = 0.008
max_utterance_s: float = 30.0
output_frame_ms: int = 40
max_history_messages: int = 24
@@ -149,7 +157,8 @@ class ConversationSession:
self._turn_pause_ms = turn_pause_ms or None
self._vad = models.vad_factory()
silence = self._turn_pause_ms or self._config.silence_ms
- self._endpointer = Endpointer(min_speech_ms=self._config.min_speech_ms, silence_ms=silence)
+ self._endpointer = Endpointer(min_speech_ms=self._config.min_speech_ms, silence_ms=silence,
+ early_ms=self._config.early_stt_ms)
self._barge = Endpointer(min_speech_ms=self._config.barge_in_ms, silence_ms=silence)
preroll_frames = max(1, self._config.preroll_ms // FRAME_MS)
self._preroll: deque[np.ndarray] = deque(maxlen=preroll_frames)
@@ -157,6 +166,7 @@ class ConversationSession:
self._utterance: list[np.ndarray] = []
self._last_voiced_at = 0.0
self._decision: asyncio.Task[None] | None = None
+ self._speculative: asyncio.Task[tuple[str, float]] | None = None
self._decision_epoch = 0
self._awaiting_request = False
self._pending_user_text = ""
@@ -172,6 +182,7 @@ class ConversationSession:
role = item.get("role")
if role in ("user", "assistant") and item.get("text"):
self._messages.append({"role": role, "content": str(item["text"])})
+ self._prime()
# ── inputs from the adapter ─────────────────────────────────────────────
@@ -234,6 +245,7 @@ class ConversationSession:
if language:
self._set_language(language)
self._messages[0] = {"role": "system", "content": self._system_text()}
+ self._prime()
def close(self) -> None:
self._closed = True
@@ -261,6 +273,8 @@ class ConversationSession:
self._barge.reset()
if probability >= self._endpointer.on_threshold:
self._last_voiced_at = now
+ # Speech resumed inside a short pause: an early transcript is stale.
+ self._speculative = None
event = self._endpointer.feed(probability)
if event is not None and event.kind == "speech_start":
# The frames that proved speech are in the pre-roll; the utterance
@@ -275,12 +289,15 @@ class ConversationSession:
if self._endpointer.in_speech and too_long:
self._start_decision(force=True)
return
- if event.kind == "silence_start":
+ if event.kind == "silence_early":
+ self._speculative = self._loop.create_task(self._transcribe(self._utterance_audio()))
+ elif event.kind == "silence_start":
self._start_decision(force=False)
elif event.kind == "silence_end":
# The user resumed before the turn was taken: the pending decision
# describes a sentence that is still growing.
self._decision_epoch += 1
+ self._speculative = None
def _begin_utterance(self, now: float, *, carry_preroll: bool) -> None:
if self._awaiting_request:
@@ -298,25 +315,41 @@ class ConversationSession:
def _utterance_seconds(self) -> float:
return sum(f.size for f in self._utterance) / INPUT_RATE
+ def _utterance_audio(self) -> np.ndarray:
+ if not self._utterance:
+ return np.zeros(0, dtype=np.float32)
+ return np.concatenate(self._utterance)
+
+ async def _transcribe(self, audio: np.ndarray) -> tuple[str, float]:
+ return await asyncio.to_thread(
+ self._locked, "stt", self._models.stt.transcribe, _with_noise_tail(audio)
+ )
+
def _start_decision(self, *, force: bool) -> None:
self._decision_epoch += 1
epoch = self._decision_epoch
- audio = np.concatenate(self._utterance) if self._utterance else np.zeros(0, np.float32)
+ audio = self._utterance_audio()
+ stt = self._speculative or self._loop.create_task(self._transcribe(audio))
+ self._speculative = None
speech_end = self._last_voiced_at
if self._decision is not None and not self._decision.done():
self._decision.cancel()
- self._decision = self._loop.create_task(self._decide(epoch, audio, speech_end, force))
+ self._decision = self._loop.create_task(
+ self._decide(epoch, audio, speech_end, force, stt)
+ )
- async def _decide(self, epoch: int, audio: np.ndarray, speech_end: float, force: bool) -> None:
+ async def _decide(self, epoch: int, audio: np.ndarray, speech_end: float, force: bool,
+ stt: asyncio.Task[tuple[str, float]]) -> None:
started = time.monotonic()
- stt_job = asyncio.to_thread(self._locked, "stt", self._models.stt.transcribe, audio)
turn_job = (
asyncio.to_thread(self._locked, "turn", self._models.turn.probability, audio)
if not force
else _ready(1.0)
)
try:
- (text, stt_ms), (probability, turn_ms) = await asyncio.gather(stt_job, turn_job)
+ (text, stt_ms), (probability, turn_ms) = await asyncio.gather(stt, turn_job)
+ except asyncio.CancelledError:
+ raise
except Exception:
log.exception("transcription or turn decision failed")
self._emit.json({"type": p.ERROR, "session": self.session_id, "code": "stt_failed",
@@ -330,11 +363,22 @@ class ConversationSession:
"p_complete": round(float(probability), 3),
"decision_ms": round((time.monotonic() - started) * 1000.0, 1),
})
- if probability < self._config.turn_threshold and not force:
- await asyncio.sleep(self._config.incomplete_wait_ms / 1000.0)
+ waited = 0
+ while (not force and probability < self._config.turn_threshold
+ and waited < self._config.incomplete_wait_ms):
+ step = min(self._config.reevaluate_ms, self._config.incomplete_wait_ms - waited)
+ await asyncio.sleep(step / 1000.0)
+ waited += step
if epoch != self._decision_epoch:
return
- self._turn_metrics["waited_incomplete_ms"] = self._config.incomplete_wait_ms
+ probability, _ms = await asyncio.to_thread(
+ self._locked, "turn", self._models.turn.probability, self._utterance_audio()
+ )
+ if epoch != self._decision_epoch:
+ return
+ if waited:
+ self._turn_metrics["waited_incomplete_ms"] = waited
+ self._turn_metrics["p_complete_final"] = round(float(probability), 3)
self._finalize(text)
def _finalize(self, text: str) -> None:
@@ -447,31 +491,64 @@ class ConversationSession:
async def _speak(self, response: _Response, speech: asyncio.Queue[str | None]) -> None:
tts = self._models.tts_for(self._language)
+ previous = ""
while True:
clause = await speech.get()
if clause is None or response.cancel.is_set():
return
+ clause = speakable(clause)
+ if not clause:
+ continue
entry = _Clause(text=clause, start_ms=response.audio_ms)
response.clauses.append(entry)
self._emit.json({"type": p.TRANSCRIPT_OUTPUT, "session": self.session_id,
"delta": clause + " "})
- await asyncio.to_thread(self._synthesize, tts, clause, response)
+ pause_ms = _pause_after(previous) if previous else 0
+ await asyncio.to_thread(self._synthesize, tts, clause, response, pause_ms)
entry.end_ms = response.audio_ms
-
- def _synthesize(self, tts: TtsModel, text: str, response: _Response) -> None:
+ previous = clause
+
+ def _synthesize(self, tts: TtsModel, text: str, response: _Response, pause_ms: int) -> None:
+ """Stream one clause, dropping the voice's own silence at both ends.
+
+ Voices pad clauses with up to a second of near-silence at the start
+ and a few hundred milliseconds at the end; played as is, the first
+ word arrives late and clauses drift apart. The lead-in is dropped, a
+ quiet stretch is held back until it proves to be a pause inside the
+ clause (then it is played) or the clause ends (then it is dropped), and
+ the gap between clauses is a deliberate ``pause_ms``.
+ """
frame = OUTPUT_RATE * self._config.output_frame_ms // 1000
+ keep = OUTPUT_RATE // 50 # 20 ms of onset and decay around the voice
+ threshold = self._config.tts_silence
+ out = np.zeros(0, dtype=np.float32)
+ quiet = np.zeros(0, dtype=np.float32)
+ started = False
with self._models.lock(f"tts:{getattr(tts, 'name', 'tts')}:{self._language}"):
- pending = np.zeros(0, dtype=np.float32)
for chunk in tts.stream(text, stop=response.cancel):
if response.cancel.is_set():
return
audio = resample(np.asarray(chunk, dtype=np.float32), tts.sample_rate, OUTPUT_RATE)
- pending = np.concatenate([pending, audio])
- while pending.size >= frame:
- piece, pending = pending[:frame], pending[frame:]
+ loud = np.flatnonzero(np.abs(audio) > threshold)
+ if not started:
+ if loud.size == 0:
+ continue
+ audio = audio[max(0, int(loud[0]) - keep):]
+ loud = loud - loud[0] + min(int(loud[0]), keep)
+ started = True
+ if pause_ms:
+ out = np.zeros(OUTPUT_RATE * pause_ms // 1000, dtype=np.float32)
+ if loud.size == 0:
+ quiet = np.concatenate([quiet, audio])
+ continue
+ cut = min(audio.size, int(loud[-1]) + 1 + keep)
+ out = np.concatenate([out, quiet, audio[:cut]])
+ quiet = audio[cut:]
+ while out.size >= frame:
+ piece, out = out[:frame], out[frame:]
self._loop.call_soon_threadsafe(self._send_audio, response, piece)
- if pending.size and not response.cancel.is_set():
- self._loop.call_soon_threadsafe(self._send_audio, response, pending)
+ if out.size and not response.cancel.is_set():
+ self._loop.call_soon_threadsafe(self._send_audio, response, out)
def _send_audio(self, response: _Response, samples: np.ndarray) -> None:
if response.cancel.is_set() or self._closed:
@@ -508,6 +585,22 @@ class ConversationSession:
# ── helpers ────────────────────────────────────────────────────────────
+ def _prime(self) -> None:
+ """Pre-evaluate system prompt and tools so the first turn hits the cache."""
+ prime = getattr(self._models.llm, "prime", None)
+ if not callable(prime):
+ return
+ prefix = [self._bounded_messages()[0]]
+
+ def run() -> None:
+ try:
+ prime(prefix, self._tools or None)
+ except Exception:
+ # Priming only saves latency; a failure leaves the cold path.
+ log.warning("priming the LLM prompt cache failed", exc_info=True)
+
+ self._loop.run_in_executor(None, run)
+
def _locked(self, name: str, fn: Callable[..., Any], *args: Any) -> tuple[Any, float]:
with self._models.lock(name):
started = time.perf_counter()
@@ -557,6 +650,39 @@ async def _ready(value: float) -> tuple[float, float]:
return value, 0.0
+_NOISE = np.random.default_rng(7)
+
+
+_MARKDOWN = re.compile(r"(\*\*|__|\*|`+|^#+\s*|^\s*[-*•]\s+|\[([^\]]*)\]\([^)]*\))", re.M)
+
+
+def speakable(text: str) -> str:
+ """Drop Markdown a model may emit; a voice must not read asterisks aloud."""
+ cleaned = _MARKDOWN.sub(lambda m: m.group(2) or "", text)
+ return " ".join(cleaned.split())
+
+
+def _pause_after(clause: str) -> int:
+ """Gap before the next clause, from how the previous one ended."""
+ end = clause.rstrip()[-1:]
+ if end in ".!?…":
+ return 250
+ if end in ",;:–—":
+ return 150
+ return 100
+
+
+def _with_noise_tail(audio: np.ndarray, seconds: float = 0.15) -> np.ndarray:
+ """Close the segment with a little room noise (about -60 dBFS).
+
+ The recogniser clips the last word of a segment that ends abruptly; a short
+ noise floor behaves like the microphone it stands in for, where digital
+ zeros made it invent words in the bench.
+ """
+ tail = (_NOISE.standard_normal(int(seconds * INPUT_RATE)) * 0.001).astype(np.float32)
+ return np.concatenate([np.asarray(audio, dtype=np.float32), tail])
+
+
def _ollama_tools(declarations: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Realtime-style declarations ({name, description, parameters}) to Ollama's shape."""
tools = []
diff --git a/jarvis/voice_engine/llm.py b/jarvis/voice_engine/llm.py
index ca45c598cd..94f6c8240f 100644
--- a/jarvis/voice_engine/llm.py
+++ b/jarvis/voice_engine/llm.py
@@ -36,6 +36,9 @@ class LlmResult:
eval_tokens: int = 0
eval_s: float = 0.0
load_s: float = 0.0
+ # Reasoning text a model produced although thinking was switched off; it
+ # delays the first token without being spoken, so the bench reports it.
+ thinking_chars: int = 0
error: str = ""
@property
@@ -44,7 +47,11 @@ class LlmResult:
@property
def prefill_tps(self) -> float:
- return self.prompt_tokens / self.prompt_eval_s if self.prompt_eval_s > 0 else 0.0
+ # prompt_eval_count includes the tokens served from the prefix cache
+ # (measured on Ollama 0.35: 260 counted, 256 cached, 49 ms), so only
+ # the remainder was actually evaluated.
+ evaluated = self.prompt_tokens - self.prompt_cached_tokens
+ return evaluated / self.prompt_eval_s if self.prompt_eval_s > 0 and evaluated > 0 else 0.0
class OllamaChat:
@@ -99,6 +106,27 @@ class OllamaChat:
for entry in payload.get("models", [])
]
+ def prime(self, messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None) -> float:
+ """Evaluate a prompt prefix now so the next turn starts from the cache.
+
+ Hybrid models (Qwen3.5) resume only from the end of an earlier prompt,
+ not from any shared prefix, so a new conversation pays the full system
+ and tool prompt unless that exact prefix was evaluated before. One
+ token of generation is enough to leave the checkpoint behind.
+ """
+ payload: dict[str, Any] = {
+ "model": self.model, "messages": messages, "stream": False,
+ "keep_alive": self._keep_alive, "options": {**self._options, "num_predict": 1},
+ }
+ if tools:
+ payload["tools"] = tools
+ if self._think_supported:
+ payload["think"] = False
+ started = time.perf_counter()
+ response = self._post("/api/chat", payload)
+ response.read()
+ return time.perf_counter() - started
+
def warm(self) -> float:
"""Load the model with the voice profile; returns seconds spent."""
started = time.perf_counter()
@@ -165,6 +193,7 @@ class OllamaChat:
break
message = event.get("message") or {}
delta = message.get("content") or ""
+ result.thinking_chars += len(message.get("thinking") or "")
now = time.perf_counter() - started
if delta:
if result.t_first_token is None:
diff --git a/jarvis/voice_engine/runtime.py b/jarvis/voice_engine/runtime.py
index 84c2db7a9a..95edec4996 100644
--- a/jarvis/voice_engine/runtime.py
+++ b/jarvis/voice_engine/runtime.py
@@ -38,7 +38,9 @@ class RuntimeConfig:
llm_base_url: str = "http://127.0.0.1:11434"
llm_num_ctx: int = 8192
llm_keep_alive: str = "30m"
- llm_temperature: float = 0.3
+ # Low, like the bench's tool runs: a voice turn wants the same tool for the
+ # same request, not variety (plan section 4.6).
+ llm_temperature: float = 0.2
engine: EngineConfig = field(default_factory=EngineConfig)
@classmethod
diff --git a/jarvis/voice_engine/vad.py b/jarvis/voice_engine/vad.py
index 62c08c012d..8dbe5b9757 100644
--- a/jarvis/voice_engine/vad.py
+++ b/jarvis/voice_engine/vad.py
@@ -70,11 +70,15 @@ class Endpointer:
off_threshold: float = 0.35,
min_speech_ms: int = 160,
silence_ms: int = 200,
+ early_ms: int = 0,
) -> None:
self.on_threshold = on_threshold
self.off_threshold = off_threshold
self.min_speech_frames = max(1, min_speech_ms // FRAME_MS)
self.silence_frames = max(1, silence_ms // FRAME_MS)
+ # ``silence_early`` fires once per pause after ``early_ms`` of quiet, so
+ # the transcription can start before the turn decision is due.
+ self.early_frames = max(1, early_ms // FRAME_MS) if early_ms else 0
self.reset()
def reset(self) -> None:
@@ -108,7 +112,10 @@ class Endpointer:
self._unvoiced += 1
if not self.in_speech:
self._voiced = 0
- elif not self.in_silence and self._unvoiced >= self.silence_frames:
- self.in_silence = True
- return VadEvent("silence_start", now)
+ elif not self.in_silence:
+ if self._unvoiced >= self.silence_frames:
+ self.in_silence = True
+ return VadEvent("silence_start", now)
+ if self.early_frames and self._unvoiced == self.early_frames:
+ return VadEvent("silence_early", now)
return None
diff --git a/tests/unit/voice_engine/test_bench_corpus.py b/tests/unit/voice_engine/test_bench_corpus.py
index 2317f9cfbc..53d54b0763 100644
--- a/tests/unit/voice_engine/test_bench_corpus.py
+++ b/tests/unit/voice_engine/test_bench_corpus.py
@@ -72,3 +72,41 @@ def test_percentiles() -> None:
assert percentile([5.0], 95) == 5.0
assert percentile([1, 2, 3, 4], 50) == pytest.approx(2.5)
assert summary([1, 2, 3])["n"] == 3
+
+
+def test_german_arguments_may_be_translated_or_transliterated() -> None:
+ case = _case(language="de", tool="get_weather", accept=(),
+ checks={"location": {"contains": ["münchen", "munich"]}}) # i18n-allow
+ for city in ("München", "Muenchen", "Munich, Bavaria"): # i18n-allow: city names
+ verdict = corpus.grade(case, [{"name": "get_weather", "arguments": {"location": city}}])
+ assert verdict["verdict"] == "correct", city
+
+
+def test_the_expected_tool_may_follow_a_harmless_first_call() -> None:
+ case = _case(tool="play_music", accept=(), checks={"query": {"contains": "focus"}})
+ calls = [{"name": "open_app", "arguments": {"name": "Spotify"}},
+ {"name": "play_music", "arguments": {"query": "Focus playlist"}}]
+ verdict = corpus.grade(case, calls)
+ assert verdict["verdict"] == "correct" and verdict["note"] == "extra calls"
+
+
+def test_answers_without_a_call_are_told_apart() -> None:
+ case = _case()
+ assert corpus.grade(case, [], '{"name": "set_timer", "arguments": {}}')["verdict"] == (
+ "malformed"
+ )
+ assert corpus.grade(case, [], "I've set a timer for ten minutes.")["verdict"] == "invented"
+ assert corpus.grade(case, [], "For how many minutes?")["verdict"] == "clarify"
+ assert corpus.grade(case, [], "Okay.")["verdict"] == "missed"
+ german = _case(language="de")
+ claim = "Ich habe den Timer gestellt." # i18n-allow: graded fixture
+ assert corpus.grade(german, [], claim)["verdict"] == "invented"
+
+
[email protected]("language", corpus.LANGUAGES)
+def test_hard_negatives_flag_a_destructive_call(language: str) -> None:
+ hard = corpus.tool_cases(language, "hard")
+ assert len(hard) >= 6
+ thanks = next(c for c in hard if c.tool is None and "end_call" in c.forbidden)
+ assert corpus.grade(thanks, [{"name": "end_call", "arguments": {}}])["verdict"] == "forbidden"
+ assert corpus.grade(thanks, [])["verdict"] == "correct"
diff --git a/tests/unit/voice_engine/test_engine_session.py b/tests/unit/voice_engine/test_engine_session.py
index eea3253694..0ffeba3e49 100644
--- a/tests/unit/voice_engine/test_engine_session.py
+++ b/tests/unit/voice_engine/test_engine_session.py
@@ -225,7 +225,8 @@ async def test_an_incomplete_verdict_waits_before_finalising() -> None:
started = time.monotonic()
await _say(session)
await out.wait(p.TRANSCRIPT_INPUT)
- assert time.monotonic() - started >= 0.2
+ # 200 ms wait; Windows timers may wake a tick early.
+ assert time.monotonic() - started >= 0.15
@pytest.mark.asyncio
@@ -236,3 +237,66 @@ async def test_a_request_without_a_pending_turn_is_ignored() -> None:
await asyncio.sleep(0.1)
assert llm.calls == [] and p.RESPONSE_DONE not in out.types()
session.close()
+
+
+class SilentEdgesTts(FakeTts):
+ """A voice that pads every clause with 0.5 s of near-silence at both ends."""
+
+ def stream(self, text: str, *, stop: threading.Event | None = None) -> Iterator[np.ndarray]:
+ yield np.full(12_000, 0.001, dtype=np.float32) # 0.5 s lead-in
+ yield np.full(4_800, 0.2, dtype=np.float32) # 0.2 s voice
+ yield np.full(12_000, 0.001, dtype=np.float32) # 0.5 s tail
+
+
+async def test_voice_silence_is_trimmed_and_clauses_get_a_set_pause() -> None:
+ llm = FakeLlm([(["One.", "Two."], [])])
+ session, out, _ = _session(llm, tts=SilentEdgesTts())
+ await _say(session)
+ await out.wait(p.TRANSCRIPT_INPUT)
+ session.on_response_request("en")
+ await out.wait(p.RESPONSE_DONE)
+ metrics = (await out.wait(p.METRICS))["turn"]
+ # Two clauses of 0.2 s voice (+20 ms onset/decay each) and one 250 ms
+ # pause after the full stop; none of the 2 s of padding is played.
+ assert 600 <= metrics["audio_ms"] <= 760
+
+
+class CountingTurn(FakeTurn):
+ def __init__(self, values: list[float]) -> None:
+ super().__init__()
+ self.values = values
+ self.calls = 0
+
+ def probability(self, audio16k: np.ndarray) -> float:
+ self.calls += 1
+ return self.values[min(self.calls - 1, len(self.values) - 1)]
+
+
+async def test_transcription_starts_early_and_is_reused() -> None:
+ llm = FakeLlm([(["Fine."], [])])
+ session, out, stt = _session(llm)
+ await _say(session)
+ await out.wait(p.TRANSCRIPT_INPUT)
+ assert stt.calls == 1
+
+
+async def test_an_incomplete_verdict_is_rescored_instead_of_waited_out() -> None:
+ llm = FakeLlm([(["Sure."], [])])
+ stt = FakeStt()
+ tts = FakeTts()
+ turn = CountingTurn([0.1, 0.9])
+ models = EngineModels(vad_factory=FakeVad, turn=turn, stt=stt, tts_for=lambda _l: tts,
+ llm=llm)
+ out = Collector()
+ session = ConversationSession(
+ slot=1, session_id="s1", models=models, emit=out, loop=asyncio.get_running_loop(),
+ config=EngineConfig(incomplete_wait_ms=3000, reevaluate_ms=100), language="en",
+ )
+ started = time.monotonic()
+ await _say(session, tail=0.6)
+ await out.wait(p.TRANSCRIPT_INPUT)
+ assert time.monotonic() - started < 2.5
+ assert turn.calls == 2