feat(voice_worker): a short voice prompt and one judgement before each v2 answer
- compact_prompt: the v2 persona in a tenth of v1's words, answers as short as possible, the full tool guidance only on turns with a data tool. A greeting's reply prompt went from about 4,500 to 1,400 tokens on Strata. - intent_judge: the tool router judges whether the turn needs tools; the planner runs only when it does. prepare_intent runs the pick ahead on a partial transcript (worker message prepare), and the reply reuses it. - Without stream_browser the screen-share tools are not offered. - The time context carries the 12-hour form (10:37 was read as pm). - A <tool_call> block written as the reply is parsed as a call, not spoken. Evals (Qwen3.6 on Strata, EVAL_COMPACT_PROMPT=1 EVAL_INTENT_JUDGE=1): 221 passed, 4 failed (known failures); new evals/test_voice_reply_length.py (v2 answers 234 chars against v1's 416) and test_reply_language_default.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,6 +11,8 @@ from typing import Optional, TYPE_CHECKING
|
||||
from ..utils.redact import redact
|
||||
from ..system_prompt import (
|
||||
build_system_prompt,
|
||||
build_voice_persona,
|
||||
COMPACT_ACTION_RULE,
|
||||
load_agent_instructions,
|
||||
reply_language_directive,
|
||||
tool_honesty_reminder,
|
||||
@@ -321,6 +323,26 @@ def _extract_text_tool_call(content_field: str, known_names: set):
|
||||
return None, None, None
|
||||
content_field = content_field
|
||||
|
||||
# Form: `<tool_call>` block as text — Qwen's XML (`<function=name><parameter=key>value</parameter>`)
|
||||
# or Hermes JSON (`{"name": ..., "arguments": {...}}`). Field run 2026-11-12 (Qwen3.6 on Strata):
|
||||
# asked for a timer with no timer tool offered, the model wrote this block as its reply, which
|
||||
# TTS would read aloud. Any name is returned: one not on offer gets the "not available" answer.
|
||||
tc_block = re.search(r"<tool_call>\s*(.+?)\s*(?:</tool_call>|$)", content_field, re.DOTALL)
|
||||
if tc_block:
|
||||
body = tc_block.group(1)
|
||||
fn = re.match(r"<function=([^>\s]+)>(.*?)(?:</function>|$)", body, re.DOTALL)
|
||||
if fn:
|
||||
args = {k: v.strip() for k, v in re.findall(r"<parameter=([^>\s]+)>(.*?)</parameter>", fn.group(2), re.DOTALL)}
|
||||
return fn.group(1).strip(), args, f"call_{uuid.uuid4().hex[:8]}"
|
||||
try:
|
||||
data = json.loads(body)
|
||||
name = str(data.get("name", "")).strip() if isinstance(data, dict) else ""
|
||||
if name:
|
||||
args = data.get("arguments", {})
|
||||
return name, (args if isinstance(args, dict) else {}), f"call_{uuid.uuid4().hex[:8]}"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Form: markdown fence
|
||||
fence_match = re.search(
|
||||
r"```tool_call\s*\n({.+?})\s*\n```",
|
||||
@@ -977,12 +999,95 @@ def _history_block(history: Any) -> str:
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def _dialogue_context(recent_messages: list) -> str:
|
||||
"""The planner's DIALOGUE CONTEXT: the last few user/assistant lines, shortened."""
|
||||
lines: list[str] = []
|
||||
for m in (recent_messages or [])[-6:]:
|
||||
role = m.get("role", "")
|
||||
content = (m.get("content") or "").strip().replace("\n", " ")
|
||||
if role in ("user", "assistant") and content:
|
||||
lines.append(f"{role}: {content[:200]}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _recent_messages(cfg, dialogue_memory) -> list:
|
||||
if not (dialogue_memory and dialogue_memory.has_recent_messages()):
|
||||
return []
|
||||
if hasattr(dialogue_memory, "get_recent_turns_with_tools"):
|
||||
return dialogue_memory.get_recent_turns_with_tools(
|
||||
max_tool_turns=getattr(cfg, "tool_carryover_max_turns", 2),
|
||||
per_entry_chars=getattr(cfg, "tool_carryover_per_entry_chars", 1200),
|
||||
)
|
||||
return dialogue_memory.get_recent_messages()
|
||||
|
||||
|
||||
# The on-screen browser tools work only in screen-share mode (cfg.stream_browser); without it they
|
||||
# only refuse, and offered anyway the router picked them for unrelated asks (field run 2026-11-12,
|
||||
# v2: "피곤하다" routed to browseAndPlay).
|
||||
_SCREEN_SHARE_TOOLS = ("controlBrowser", "browseAndPlay", "setBroadcast")
|
||||
|
||||
|
||||
def _offered_builtins(cfg, chat_available: bool) -> dict:
|
||||
"""The built-in tools this turn can offer: chatChannels only with a chat backend
|
||||
(chat_channels.spec.md), the screen-share tools only in screen-share mode."""
|
||||
stream = getattr(cfg, "stream_browser", True)
|
||||
return {k: v for k, v in BUILTIN_TOOLS.items()
|
||||
if (k != "chatChannels" or chat_available) and (stream or k not in _SCREEN_SHARE_TOOLS)}
|
||||
|
||||
|
||||
def _route_tools(cfg, redacted: str, builtin_tools: dict, mcp_tools: dict, recent_messages: list):
|
||||
"""The tool router's pick for this query (``select_tools`` with the engine's settings)."""
|
||||
try:
|
||||
strategy = ToolSelectionStrategy(getattr(cfg, "tool_selection_strategy", "llm"))
|
||||
except ValueError:
|
||||
strategy = ToolSelectionStrategy.LLM
|
||||
return select_tools(
|
||||
query=redacted,
|
||||
builtin_tools=builtin_tools,
|
||||
mcp_tools=mcp_tools,
|
||||
strategy=strategy,
|
||||
llm_base_url=cfg.ollama_base_url,
|
||||
llm_model=resolve_tool_router_model(cfg),
|
||||
llm_timeout_sec=float(getattr(cfg, "llm_tools_timeout_sec", 8.0)),
|
||||
embed_model=getattr(cfg, "ollama_embed_model", "nomic-embed-text"),
|
||||
embed_timeout_sec=float(getattr(cfg, "llm_embed_timeout_sec", 10.0)),
|
||||
context_hint=_build_enrichment_context_hint(cfg, recent_messages),
|
||||
)
|
||||
|
||||
|
||||
def prepare_intent(cfg, text: str, dialogue_memory, chat_available: bool) -> Optional[list]:
|
||||
"""Run the intent judge (the tool router) for ``text`` ahead of its reply (v2: on a partial
|
||||
transcript while the user still speaks), with the inputs ``run_reply_engine(intent_judge=True)``
|
||||
would give it, so its pick can be passed back as ``prepared_tools``. None when the router gave
|
||||
up (its fall-open to the whole catalogue is not a pick). ``chat_available``: the reply will
|
||||
have a chat backend (the chatChannels tool is in the catalogue)."""
|
||||
mcp_tools: dict = {}
|
||||
if getattr(cfg, "mcps", {}):
|
||||
try:
|
||||
from ..tools.registry import get_cached_mcp_tools
|
||||
mcp_tools = get_cached_mcp_tools()
|
||||
except Exception:
|
||||
mcp_tools = {}
|
||||
builtin = _offered_builtins(cfg, chat_available)
|
||||
try:
|
||||
routed = _route_tools(cfg, redact(text), builtin, mcp_tools, _recent_messages(cfg, dialogue_memory))
|
||||
except Exception as exc: # pragma: no cover — defensive
|
||||
debug_log(f"intent judge (prepare) failed (non-fatal): {exc}", "planning")
|
||||
return None
|
||||
if routed is None or set(routed) >= set(builtin) | set(mcp_tools):
|
||||
return None
|
||||
return list(routed)
|
||||
|
||||
|
||||
def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
|
||||
text: str, dialogue_memory: "DialogueMemory",
|
||||
language: Optional[str] = None,
|
||||
history: Optional[Any] = None,
|
||||
legacy_memory: bool = True,
|
||||
default_language: Optional[str] = None) -> Optional[str]:
|
||||
default_language: Optional[str] = None,
|
||||
compact_prompt: bool = False,
|
||||
intent_judge: bool = False,
|
||||
prepared_tools: Optional[list] = None) -> Optional[str]:
|
||||
"""
|
||||
Main entry point for reply generation.
|
||||
|
||||
@@ -1008,6 +1113,15 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
|
||||
default_language: v2 only. The language to reply in unless the user
|
||||
explicitly asks for another one (e.g. "Korean"). An
|
||||
``output_language`` lock still wins. None: the user's language.
|
||||
compact_prompt: v2 only. The short voice persona and, on turns where
|
||||
no data tool was routed, one action rule instead of the full tool
|
||||
guidance (prompt length is reply latency on Strata).
|
||||
intent_judge: v2 only. One judgement before the reply: the tool
|
||||
router decides which tools the turn needs and the planner does
|
||||
not run (planner.spec.md, "Intent judge (v2)").
|
||||
prepared_tools: v2 only, with ``intent_judge``. The router's tools
|
||||
``prepare_intent`` already chose for this text (while the user was
|
||||
still speaking); the router is not run again.
|
||||
|
||||
Returns:
|
||||
Generated reply text or None
|
||||
@@ -1095,19 +1209,12 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
|
||||
# (chat_channels.spec.md); otherwise it is not in the catalogue at all.
|
||||
from .turn_state import get_chat as _get_chat
|
||||
_chat_backend = _get_chat()
|
||||
_builtin_tools = {k: v for k, v in BUILTIN_TOOLS.items()
|
||||
if k != "chatChannels" or _chat_backend is not None}
|
||||
_builtin_tools = _offered_builtins(cfg, _chat_backend is not None)
|
||||
_all_builtin_names = list(_builtin_tools.keys())
|
||||
_all_mcp_names = list(mcp_tools.keys())
|
||||
_full_catalog_names = _all_builtin_names + _all_mcp_names
|
||||
|
||||
_dialogue_lines: list[str] = []
|
||||
for _m in (recent_messages or [])[-6:]:
|
||||
_role = _m.get("role", "")
|
||||
_content = (_m.get("content") or "").strip().replace("\n", " ")
|
||||
if _role in ("user", "assistant") and _content:
|
||||
_dialogue_lines.append(f"{_role}: {_content[:200]}")
|
||||
_dialogue_ctx = "\n".join(_dialogue_lines)
|
||||
_dialogue_ctx = _dialogue_context(recent_messages)
|
||||
|
||||
# Step 2a: Tool routing FIRST.
|
||||
#
|
||||
@@ -1138,22 +1245,15 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
|
||||
dialogue_memory.hot_cache_get(_router_cache_key)
|
||||
if dialogue_memory and hasattr(dialogue_memory, "hot_cache_get") else None
|
||||
)
|
||||
if isinstance(_cached_routed, list):
|
||||
if intent_judge and prepared_tools is not None:
|
||||
# Intent judge (v2): the router's pick made while the user was still speaking.
|
||||
routed_tools = list(prepared_tools)
|
||||
debug_log(f"intent judge: prepared pick used ({len(routed_tools)} tool(s))", "planning")
|
||||
elif isinstance(_cached_routed, list):
|
||||
routed_tools = list(_cached_routed)
|
||||
debug_log("tool router served from hot-window cache", "planning")
|
||||
else:
|
||||
routed_tools = select_tools(
|
||||
query=redacted,
|
||||
builtin_tools=_builtin_tools,
|
||||
mcp_tools=mcp_tools,
|
||||
strategy=strategy,
|
||||
llm_base_url=cfg.ollama_base_url,
|
||||
llm_model=resolve_tool_router_model(cfg),
|
||||
llm_timeout_sec=float(getattr(cfg, "llm_tools_timeout_sec", 8.0)),
|
||||
embed_model=getattr(cfg, "ollama_embed_model", "nomic-embed-text"),
|
||||
embed_timeout_sec=float(getattr(cfg, "llm_embed_timeout_sec", 10.0)),
|
||||
context_hint=context_hint,
|
||||
)
|
||||
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
|
||||
# a response no token of which matches a known tool name — i.e. the
|
||||
@@ -1217,6 +1317,9 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
|
||||
"deleteMeal", "localFiles", "controlBrowser", "browseAndPlay", "screenshot",
|
||||
}
|
||||
_router_wants_data = any(t in routed_tools for t in _DATA_TOOLS)
|
||||
# Intent judge (v2): the planner only runs on turns that need a tool (the chat tool aside,
|
||||
# which is offered on every turn below); a turn without one goes straight to its answer.
|
||||
_turn_needs_tools = any(t not in ("chatChannels", "stop", "toolSearchTool") for t in routed_tools)
|
||||
|
||||
# In screen-share mode, always offer setBroadcast. "Turn the broadcast
|
||||
# on/off" is language-agnostic intent the embedding/keyword router won't
|
||||
@@ -1261,13 +1364,16 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
|
||||
|
||||
action_plan: list[str] = []
|
||||
try:
|
||||
action_plan = plan_query(
|
||||
cfg=cfg,
|
||||
query=redacted,
|
||||
dialogue_context=_dialogue_ctx,
|
||||
tools=_planner_tool_catalog,
|
||||
live_context=_live_time_location_string(cfg),
|
||||
)
|
||||
# Intent judge (v2): the router decides whether the turn needs tools; only then does the
|
||||
# planner order the steps (planner.spec.md, "Intent judge (v2)").
|
||||
if not intent_judge or _turn_needs_tools:
|
||||
action_plan = plan_query(
|
||||
cfg=cfg,
|
||||
query=redacted,
|
||||
dialogue_context=_dialogue_ctx,
|
||||
tools=_planner_tool_catalog,
|
||||
live_context=_live_time_location_string(cfg),
|
||||
)
|
||||
except Exception as _plan_exc: # pragma: no cover — defensive
|
||||
debug_log(f"planner step failed (non-fatal): {_plan_exc}", "planning")
|
||||
action_plan = []
|
||||
@@ -1717,7 +1823,8 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
|
||||
# _resolve_output_language). Building the persona from the raw env var while
|
||||
# the directive used the config value made the two contradict each other.
|
||||
_output_language = _resolve_output_language()
|
||||
_persona_prompt = build_system_prompt(_assistant_name, _output_language, default_language)
|
||||
_persona_prompt = (build_voice_persona if compact_prompt else build_system_prompt)(
|
||||
_assistant_name, _output_language, default_language)
|
||||
# File-based operator instructions: every *.md in AGENTS_DIR (default
|
||||
# /app/agents, bind-mounted from ./agents). Read once per turn so edits in
|
||||
# the folder apply on the next reply without a restart; fail-open to "".
|
||||
@@ -1726,8 +1833,18 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
|
||||
def _build_initial_system_message() -> str:
|
||||
guidance = [_persona_prompt.strip()]
|
||||
|
||||
# Add model-size-appropriate prompt components
|
||||
guidance.extend(prompts.to_list())
|
||||
if compact_prompt:
|
||||
# The persona already covers voice style, inference and tool use; the tool guidance
|
||||
# (named entities, auto-derived and self-contained arguments) matters only when a
|
||||
# data tool is on offer. The sentinels and the always-offered chat tool are not.
|
||||
guidance.append(prompts.asr_note)
|
||||
if any(t not in ("stop", "toolSearchTool", "chatChannels") for t in allowed_tools):
|
||||
guidance.extend(c for c in (prompts.tool_guidance, prompts.tool_constraints) if c)
|
||||
else:
|
||||
guidance.append(COMPACT_ACTION_RULE)
|
||||
else:
|
||||
# Add model-size-appropriate prompt components
|
||||
guidance.extend(prompts.to_list())
|
||||
|
||||
# Reply-language policy: an explicit OUTPUT_LANGUAGE lock wins, else
|
||||
# Piper/Chatterbox TTS forces English (English-only voices), else the
|
||||
|
||||
Reference in New Issue
Block a user