"""Turning raw model output into a tool call or an answer, and checking it.
Everything here is deterministic. The judging model only scores what cannot be
checked this way: whether an answer is actually helpful.
"""
import json
import re
# Qwen3.5: \n\n\nvalue\n\n\n
_QWEN_XML = re.compile(r"\s*\s]+)>(.*?)", re.S)
_QWEN_PARAM = re.compile(r"\s]+)>\s*(.*?)\s*", re.S)
# Qwen3 and others: {"name": ..., "arguments": {...}}
_JSON_CALL = re.compile(r"\s*(\{.*?\})\s*", re.S)
# Gemma 4: <|tool_call>call:name{key:<|"|>value<|"|>, ...}
_GEMMA = re.compile(r"call:([A-Za-z0-9_\-]+)\{(.*?)\}", re.S)
_GEMMA_ARG = re.compile(r'([A-Za-z0-9_]+):(?:<\|"\|>(.*?)<\|"\|>|([^,}]+))', re.S)
def parse_tool_call(text: str) -> dict | None:
"""The first tool call in `text`, as {"name", "arguments"}, or None."""
if m := _QWEN_XML.search(text):
args = {k: v.strip() for k, v in _QWEN_PARAM.findall(m.group(2))}
return {"name": m.group(1), "arguments": args}
if m := _JSON_CALL.search(text):
try:
call = json.loads(m.group(1))
return {"name": call.get("name"), "arguments": call.get("arguments") or {}}
except json.JSONDecodeError:
pass
if m := _GEMMA.search(text):
args = {k: (a or b).strip() for k, a, b in _GEMMA_ARG.findall(m.group(2))}
return {"name": m.group(1), "arguments": args}
return None
def parse_tool_calls(text: str) -> list[dict]:
"""Every tool call in `text`, in order: a model may call several at once."""
calls = []
for m in _QWEN_XML.finditer(text):
calls.append({"name": m.group(1), "arguments": {k: v.strip() for k, v in _QWEN_PARAM.findall(m.group(2))}})
if calls:
return calls
for m in _JSON_CALL.finditer(text):
try:
call = json.loads(m.group(1))
calls.append({"name": call.get("name"), "arguments": call.get("arguments") or {}})
except json.JSONDecodeError:
pass
return calls
_THINK = re.compile(r".*?", re.S)
def visible_answer(text: str) -> str:
"""What Duckwork would show and speak: no reasoning, no tool-call markup."""
text = _THINK.sub("", text)
text = re.sub(r"<\|?tool_call\|?>.*?(||$)", "", text, flags=re.S)
return text.strip()
_MARKDOWN = [
(re.compile(r"\*\*[^*]+\*\*"), "bold"),
(re.compile(r"^\s{0,3}#{1,6}\s", re.M), "heading"),
(re.compile(r"^\s*[-*•]\s+\S", re.M), "bullet list"),
(re.compile(r"^\s*\d+[.)]\s+\S", re.M), "numbered list"),
(re.compile(r"`[^`]+`"), "code"),
]
def markdown_found(text: str) -> list[str]:
return [name for pattern, name in _MARKDOWN if pattern.search(text)]
# Tools whose names start with one of these only look something up. Duckwork's
# prompt allows a lookup any time; only an action needs an explicit request.
# Any other verb counts as an action, so an unknown name never passes as a lookup.
LOOKUP_VERBS = {
"get", "list", "search", "fetch", "find", "check", "query", "read", "retrieve", "view", "lookup",
"look", "show", "describe", "count", "compare", "preview", "browse", "inspect", "track", "verify",
"estimate", "calculate", "convert", "current", "date", "forecast", "predict", "analyze",
"summarize", "suggest", "validate", "scan", "discover", "simulate",
}
def is_lookup(name: str) -> bool:
verb = re.split(r"_|-|(?<=[a-z])(?=[A-Z])", name, maxsplit=1)[0].lower()
return verb in LOOKUP_VERBS
def check(task: dict, output: str) -> dict:
"""Score one output against the task's `expect`. Returns
{"passed": bool, "failures": [...], "tool_call": ..., "answer": ...}."""
expect = task.get("expect", {})
call = parse_tool_call(output)
answer = visible_answer(output)
failures: list[str] = []
if expect.get("no_tool") and call:
failures.append(f"called {call['name']} but no tool was needed")
# The action was only mentioned: ask first. Looking something up is fine.
if expect.get("no_action") and call and not is_lookup(call["name"]):
failures.append(f"called {call['name']}, an action, without asking first")
if names := expect.get("tool_any"):
if not call:
failures.append(f"expected a call to one of {names}, got an answer")
elif call["name"] not in names:
failures.append(f"called {call['name']}, expected one of {names}")
elif words := expect.get("args_mention"):
# The arguments should be about the right thing: at least one of
# these words in any argument value, case-insensitive.
flat = " ".join(str(v) for v in call["arguments"].values()).lower()
if not any(w.lower() in flat for w in words):
failures.append(f"{call['name']} arguments {call['arguments']} mention none of {words}")
if not call and expect.get("spoken", False):
found = markdown_found(answer)
if expect.get("lists_ok"): # steps or a list asked for: plain numbered lines are fine
found = [f for f in found if f not in {"numbered list", "bullet list"}]
if found:
failures.append("markdown in a spoken answer: " + ", ".join(found))
if not call and (limit := expect.get("max_words")):
count = len(answer.split())
if count > limit:
failures.append(f"{count} words, limit {limit}")
if not call and (words := expect.get("answer_mentions")):
if not any(w.lower() in answer.lower() for w in words):
failures.append(f"answer mentions none of {words}")
if not call and not expect.get("tool_any") and not answer:
failures.append("empty answer")
return {"passed": not failures, "failures": failures, "tool_call": call, "answer": answer}