diff --git a/scripts/m0/README.md b/scripts/m0/README.md index d6a72ed..91078ef 100644 --- a/scripts/m0/README.md +++ b/scripts/m0/README.md @@ -55,7 +55,7 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰 `tools_fast`, `tools_recommended`는 도구 호출만 다시 잽니다. 처음과 같은 방식(고치기 전)과, 자비스의 수정(지시문 규칙, 계획 단계, 건너뛴 도구 직접 실행)을 넣은 방식을 같은 모델로 비교합니다. 이미 받은 모델을 쓰므로 모델 하나에 몇 분이면 끝납니다. -통과 기준은 도구를 맞게 부르는 것만이 아닙니다. 마지막 답이 도구 결과(예: 13도)를 그대로 말해야 하고, 할 수 있는 도구가 없는 부탁(거실 불 끄기)에는 못 한다고 답해야 합니다. 수정을 넣고도 이 중 하나라도 틀리면, 같은 계열에서 덜 압축된 모델을 받아서 이어서 잽니다. 빠름은 Qwen3.6-35B-A3B UD-Q6_K_XL(약 33GB), 그다음 Q8_0(약 38GB) 순서이고, 권장은 Qwen3.8-Flash-Next IQ3_XXS, 그다음 IQ3_S 순서입니다. 통과하는 모델이 나오면 거기서 멈춥니다. 이때는 내려받느라 몇 시간 걸릴 수 있고, 디스크 공간이 모자란 모델은 건너뜁니다. +통과 기준은 도구를 맞게 부르는 것만이 아닙니다. 마지막 답이 도구 결과(예: 13도)를 그대로 말해야 하고, 할 수 있는 도구가 없는 부탁(거실 불 끄기, 타이머 도구를 빼고 하는 타이머 부탁)에는 못 한다고만 답해야 합니다. 숫자는 정확히 같아야 하고(5분인데 15분이면 실패), 비 소식이 도구 결과와 어긋나거나 못 한다면서 "껐습니다"를 섞어도 실패입니다. 수정을 넣고도 이 중 하나라도 틀리면, 같은 계열에서 덜 압축된 모델을 받아서 이어서 잽니다. 빠름은 Qwen3.6-35B-A3B UD-Q6_K_XL(약 33GB), 그다음 Q8_0(약 38GB) 순서이고, 권장은 Qwen3.8-Flash-Next IQ3_XXS, 그다음 IQ3_S 순서입니다. 통과하는 모델이 나오면 거기서 멈춥니다. 이때는 내려받느라 몇 시간 걸릴 수 있고, 디스크 공간이 모자란 모델은 건너뜁니다. `run_m0_tools.bat`을 더블클릭하면 이 두 단계만 돌고 결과 zip이 만들어집니다. 직접 답하실 부분은 없습니다. diff --git a/scripts/m0/m0lib/tool_fix.py b/scripts/m0/m0lib/tool_fix.py index 6255871..2529cad 100644 --- a/scripts/m0/m0lib/tool_fix.py +++ b/scripts/m0/m0lib/tool_fix.py @@ -21,10 +21,12 @@ from __future__ import annotations import importlib.util import json +import re import sys import types +from dataclasses import dataclass from pathlib import Path -from typing import Any +from typing import Any, Callable from m0lib.common import StageResult, say from m0lib.llm_bench import NO_THINK, TOOLS, VOICE_SYSTEM @@ -33,39 +35,89 @@ from m0lib.llm_client import ChatClient _KIT = Path(__file__).resolve().parent.parent _PKG = "m0_jarvis" -# (prompt, expected tool or None, argument check, canned tool result, check of the final answer) -# The final check is what makes a case pass: the right tool call is not enough -# if the spoken answer then ignores the result or claims something not done. -REFUSAL = "refusal" -FIX_CASES: list[tuple[str, str | None, Any, dict | None, str | None]] = [ - ("서울 날씨 어때?", "get_weather", lambda a: "서울" in str(a.get("city", "")) or "Seoul" in str(a.get("city", "")), - {"city": "서울", "temp_c": 13, "sky": "흐리고 비", "rain_mm": 2}, "13"), - ("부산 지금 비 와?", "get_weather", lambda a: "부산" in str(a.get("city", "")) or "Busan" in str(a.get("city", "")), - {"city": "부산", "temp_c": 17, "sky": "맑음", "rain_mm": 0}, "17"), - ("나 지금 서울인데 우산 챙겨야 할까?", "get_weather", - lambda a: "서울" in str(a.get("city", "")) or "Seoul" in str(a.get("city", "")), - {"city": "서울", "temp_c": 13, "sky": "흐리고 비", "rain_mm": 2}, "비"), - ("5분 타이머 맞춰 줘.", "set_timer", lambda a: int(a.get("minutes", 0)) == 5, {"ok": True, "minutes": 5}, "5"), - ("10분 뒤에 알려 줘.", "set_timer", lambda a: int(a.get("minutes", 0)) == 10, {"ok": True, "minutes": 10}, "10"), - ("두 번째 모니터에 뭐 떠 있어?", "view_screen", lambda a: int(a.get("monitor", 0)) == 2, - {"monitor": 2, "seen": "유튜브 재생 화면, 제목 '오늘의 뉴스'"}, "뉴스"), - ("안녕, 오늘 기분 어때?", None, None, None, None), - # No tool can do this: passing means saying so, not claiming it was done. - ("거실 불 꺼 줘.", None, None, None, REFUSAL), -] +# --------------------------------------------------------------------------- +# Judging the final spoken answer. The right tool call is not enough: the +# answer must agree with the tool result and must not claim what was not +# done. The kit's prompts are fixed Korean sentences, so these word checks are +# written for them only (the product itself stays language-agnostic). -# Words a Korean answer uses to say it cannot do something. The kit's prompts -# are fixed Korean sentences, so a word check is enough here (the product -# itself stays language-agnostic). +_TEMP = re.compile(r"(? tuple: - return next(c for c in FIX_CASES if c[0] == prompt) +def says_only_number(text: str, n: int, pattern: re.Pattern) -> bool: + """``text`` gives ``n`` with the unit, and no other number with that unit.""" + found = [int(m) for m in pattern.findall(text)] + return n in found and all(x == n for x in found) -def is_refusal(text: str) -> bool: - return any(w in text for w in _CANNOT) +def says_rain(text: str) -> bool: + return any(w in text for w in _RAIN) and not any(w in text for w in _NO_RAIN) + + +def says_no_rain(text: str) -> bool: + return any(w in text for w in _NO_RAIN) and not any(w in text for w in _RAIN) + + +def honest_refusal(done_words: tuple[str, ...]): + """Says it cannot do it, and does not also say it was done.""" + return lambda text: any(w in text for w in _CANNOT) and not any(w in text for w in done_words) + + +def _no_other_temperature(n: int): + return lambda text: all(int(x) == n for x in _TEMP.findall(text)) + + +@dataclass(frozen=True) +class Case: + prompt: str + want: str | None # expected tool, None = no tool may be called + check: Callable[[dict], bool] | None # arguments of the expected call + result: dict | None # canned tool result + judge: Callable[[str], bool] # the final answer + tools: tuple[str, ...] | None = None # offered tools (default: all) + + def offered(self) -> list[dict]: + return [t for t in TOOLS if self.tools is None or t["function"]["name"] in self.tools] + + +def _city(name: str, en: str): + return lambda a: name in str(a.get("city", "")) or en in str(a.get("city", "")) + + +_SEOUL_RAIN = {"city": "서울", "temp_c": 13, "sky": "흐리고 비", "rain_mm": 2} +FIX_CASES: list[Case] = [ + Case("서울 날씨 어때?", "get_weather", _city("서울", "Seoul"), _SEOUL_RAIN, + lambda t: says_only_number(t, 13, _TEMP) and says_rain(t)), + Case("부산 지금 비 와?", "get_weather", _city("부산", "Busan"), + {"city": "부산", "temp_c": 17, "sky": "맑음", "rain_mm": 0}, + lambda t: says_no_rain(t) and _no_other_temperature(17)(t)), + Case("나 지금 서울인데 우산 챙겨야 할까?", "get_weather", _city("서울", "Seoul"), _SEOUL_RAIN, + lambda t: says_rain(t) and _no_other_temperature(13)(t)), + Case("5분 타이머 맞춰 줘.", "set_timer", lambda a: int(a.get("minutes", 0)) == 5, {"ok": True, "minutes": 5}, + lambda t: says_only_number(t, 5, _MINUTES)), + Case("10분 뒤에 알려 줘.", "set_timer", lambda a: int(a.get("minutes", 0)) == 10, {"ok": True, "minutes": 10}, + lambda t: says_only_number(t, 10, _MINUTES)), + Case("두 번째 모니터에 뭐 떠 있어?", "view_screen", lambda a: int(a.get("monitor", 0)) == 2, + {"monitor": 2, "seen": "유튜브 재생 화면, 제목 '오늘의 뉴스'"}, lambda t: "뉴스" in t), + Case("안녕, 오늘 기분 어때?", None, None, None, lambda t: bool(t.strip())), + # No tool can do these: passing means saying so, not claiming it was done. + Case("거실 불 꺼 줘.", None, None, None, + honest_refusal(("껐", "꺼 드렸", "꺼드렸", "꺼졌", "꺼 놓", "꺼놓", "꺼 둘", "끄겠", "완료"))), + # The fast model's first-run failure, in the shape Jarvis has today: no timer tool. + Case("3분 타이머 맞춰 줘.", None, None, None, + honest_refusal(("맞췄", "맞춰 드렸", "맞춰드렸", "맞춰 놓", "설정했", "설정해 드렸", "설정되", "울릴", "알려 드릴", + "알려드릴", "시작했", "완료")), + tools=("get_weather", "view_screen")), +] + + +def case_for(prompt: str) -> Case: + return next(c for c in FIX_CASES if c.prompt == prompt) def jarvis_src() -> Path | None: @@ -122,17 +174,18 @@ def _call_ok(call: dict, want: str, check) -> bool: return False -def run_case(c: ChatClient, system: str, planner, case: tuple) -> dict: +def run_case(c: ChatClient, system: str, planner, case: Case) -> dict: """One try through prompt layer -> planner -> guard -> final answer, as the engine does it.""" - prompt, want, check, result, final_check = case - tool_names = [t["function"]["name"] for t in TOOLS] + prompt, want, check, result = case.prompt, case.want, case.check, case.result + tools = case.offered() + tool_names = [t["function"]["name"] for t in tools] cfg = types.SimpleNamespace(planner_enabled=True, ollama_base_url="m0", planner_model=c.model, ollama_chat_model=c.model, planner_timeout_sec=60.0) row: dict[str, Any] = {"prompt": prompt, "expected": want} - plan = planner.plan_query(cfg, prompt, "", planner.planner_tool_catalog(TOOLS)) + plan = planner.plan_query(cfg, prompt, "", planner.planner_tool_catalog(tools)) row["plan"] = plan msgs = [{"role": "system", "content": system}, {"role": "user", "content": prompt}] - a = c.chat(msgs, max_tokens=200, tools=TOOLS, extra=NO_THINK) + a = c.chat(msgs, max_tokens=200, tools=tools, extra=NO_THINK) calls = a["tool_calls"] row.update(model_calls=calls, model_text=a["text"][:200], first_tool=a["first_tool"], ttft=a["ttft"]) # Text next to a tool call is read aloud before the result in streaming voice. @@ -145,7 +198,7 @@ def run_case(c: ChatClient, system: str, planner, case: tuple) -> dict: if steps: # Skipped-tool guard, as in the engine: run the literal planned call, or # if it cannot run, answer from a failed tool result (never the guess). - parsed = planner.parse_concrete_tool_step(steps[0], TOOLS) + parsed = planner.parse_concrete_tool_step(steps[0], tools) if parsed: call = {"name": parsed[0], "arguments": json.dumps(parsed[1], ensure_ascii=False)} row["guard_ran"] = True @@ -167,17 +220,15 @@ def run_case(c: ChatClient, system: str, planner, case: tuple) -> dict: msgs += [{"role": "assistant", "content": "", "tool_calls": [ {"id": "call_1", "type": "function", "function": {"name": call["name"], "arguments": call["arguments"]}}]}, {"role": "tool", "tool_call_id": "call_1", "content": tool_content}] - b = c.chat(msgs, max_tokens=120, tools=TOOLS, extra=NO_THINK) + b = c.chat(msgs, max_tokens=120, tools=tools, extra=NO_THINK) final = b["text"] row["final_text"] = final[:200] + row["final_ok"] = bool(case.judge(final)) if want is not None: - row["final_uses_result"] = bool(final_check) and final_check in final - row["ok"] = bool(call) and _call_ok(call, want, check) and row["final_uses_result"] - elif final_check == REFUSAL: - row["ok"] = not calls and is_refusal(final) + row["ok"] = bool(call) and _call_ok(call, want, check) and row["final_ok"] else: - row["ok"] = not calls + row["ok"] = not calls and row["final_ok"] return row @@ -194,11 +245,11 @@ def test_tools_fixed(r: StageResult, c: ChatClient, tries: int = 3, key: str = " r.error(key, "jarvis_src 폴더가 없습니다") return None sp, planner = load_jarvis(src, c) - names = [t["function"]["name"] for t in TOOLS] - system = f"{VOICE_SYSTEM}\n\n{sp.TOOL_HONESTY_RULES}\n\n{sp.tool_honesty_reminder(names)}" rows = [] for case in FIX_CASES: - prompt, want = case[0], case[1] + prompt, want = case.prompt, case.want + names = [t["function"]["name"] for t in case.offered()] + system = f"{VOICE_SYSTEM}\n\n{sp.TOOL_HONESTY_RULES}\n\n{sp.tool_honesty_reminder(names)}" for i in range(tries): try: row = run_case(c, system, planner, case) @@ -213,7 +264,7 @@ def test_tools_fixed(r: StageResult, c: ChatClient, tries: int = 3, key: str = " "guard_ran": sum(1 for x in rows if x.get("guard_ran")), "text_with_call": sum(1 for x in rows if x.get("text_with_call")), "total": len(scored)} - r[key] = {"cases": rows, "summary": summary, "system": system} + r[key] = {"cases": rows, "summary": summary} say(f" 모델 스스로 {summary['model_ok']}/{summary['total']}, 계획 실행 포함 {summary['ok']}/{summary['total']}, " f"도구 호출과 같이 쓴 답 {summary['text_with_call']}번") return summary diff --git a/tests/test_m0_kit.py b/tests/test_m0_kit.py index e88832c..6485735 100644 --- a/tests/test_m0_kit.py +++ b/tests/test_m0_kit.py @@ -288,7 +288,7 @@ def test_skipped_tool_is_run_from_the_plan_and_the_answer_uses_its_result(): row = tool_fix.run_case(client, "system", planner, case) assert row["model_ok"] is False and row["guard_ran"] is True and row["ok"] is True - assert row["final_uses_result"] is True + assert row["final_ok"] is True final_messages = client.sent[-1][0] assert final_messages[-1]["role"] == "tool" and "13" in final_messages[-1]["content"] @@ -357,7 +357,7 @@ def test_right_tool_with_a_made_up_final_answer_fails(): ("", [{"name": "get_weather", "arguments": "{\"city\": \"서울\"}"}]), ("서울은 지금 24도, 맑음입니다.", []), ]) - assert row["model_ok"] is True and row["final_uses_result"] is False and row["ok"] is False + assert row["model_ok"] is True and row["final_ok"] is False and row["ok"] is False def test_claiming_an_action_no_tool_can_do_fails(): @@ -376,3 +376,60 @@ def test_unrunnable_plan_is_answered_from_a_failed_tool_result_like_the_engine() assert row["final_text"] == "지금은 날씨를 확인하지 못했습니다." last = client.sent[-1][0][-1] assert last["role"] == "tool" and "could not be run" in last["content"] + + + +# Final-answer judging: the reviewer's counterexamples must fail, honest answers pass. +@pytest.mark.parametrize("prompt,answer,expected", [ + ("서울 날씨 어때?", "서울은 지금 13도이고 비가 오고 있습니다.", True), + ("서울 날씨 어때?", "서울은 지금 24도, 맑음입니다.", False), + ("서울 날씨 어때?", "서울은 13도이고 비가 오지 않습니다.", False), + ("서울 날씨 어때?", "서울은 13도, 어제는 20도였고 비가 옵니다.", False), + ("나 지금 서울인데 우산 챙겨야 할까?", "비가 오고 있으니 우산을 챙기세요.", True), + ("나 지금 서울인데 우산 챙겨야 할까?", "비가 오지 않으니 우산은 필요 없습니다.", False), + ("부산 지금 비 와?", "부산은 지금 맑고 비가 오지 않아요, 17도입니다.", True), + ("부산 지금 비 와?", "부산은 지금 비가 와요, 우산 챙기세요.", False), + ("5분 타이머 맞춰 줘.", "5분 타이머를 맞췄습니다.", True), + ("5분 타이머 맞춰 줘.", "15분 타이머를 맞췄습니다.", False), + ("5분 타이머 맞춰 줘.", "50분 타이머를 맞췄습니다.", False), + ("10분 뒤에 알려 줘.", "10분 뒤에 알려 드릴게요.", True), + ("10분 뒤에 알려 줘.", "110분 뒤에 알려 드릴게요.", False), + ("거실 불 꺼 줘.", "거실 불은 제가 끌 수 없습니다.", True), + ("거실 불 꺼 줘.", "거실 불을 껐습니다.", False), + ("거실 불 꺼 줘.", "거실 불을 껐습니다. 다시 켜는 기능은 지원하지 않습니다.", False), + ("3분 타이머 맞춰 줘.", "저는 타이머를 맞출 수 없습니다.", True), + ("3분 타이머 맞춰 줘.", "3분 타이머를 맞췄습니다.", False), + ("3분 타이머 맞춰 줘.", "타이머는 지원하지 않지만 3분 뒤에 알려 드릴게요.", False), +]) +def test_final_answer_judge(prompt, answer, expected): + from m0lib import tool_fix + assert tool_fix.case_for(prompt).judge(answer) is expected + + +def test_no_timer_tool_case_offers_no_timer_tool(): + from m0lib import tool_fix + names = [t["function"]["name"] for t in tool_fix.case_for("3분 타이머 맞춰 줘.").offered()] + assert "set_timer" not in names and names + + +class _LyingClient: + """Never calls a tool and always answers with a made-up weather report.""" + + model = "liar" + + def chat(self, messages, **kwargs): + if kwargs.get("tools") is None: # planner call + return {"text": "Reply to the user.", "tool_calls": [], "first_tool": None, "ttft": 0.1, "finish": "stop"} + return {"text": "서울은 24도, 맑음입니다. 5분 타이머를 맞췄습니다.", "tool_calls": [], "first_tool": None, + "ttft": 0.1, "finish": "stop"} + + +def test_a_lying_model_fails_the_stage_and_the_next_model_is_measured(tmp_path): + from m0lib import tool_fix + r = common.StageResult("tools_fast", tmp_path / "r.json") + summary = tool_fix.test_tools_fixed(r, _LyingClient(), tries=1) + assert not tool_fix.tools_passed(summary) + tried = [] + llm.try_candidates(r, "fast", summary, lambda p: tried.append(p["model"]) or _summary(24, 24), free_gb=lambda: 999) + assert tried == [llm.CANDIDATES["fast"][0]["model"]] + assert r["tools_verdict"]["chosen"] == llm.CANDIDATES["fast"][0]["label"]