llm-format-guard 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,41 @@
1
+ """llm-format-guard: catch LLM answers that miss the user's format and length instructions.
2
+
3
+ Typical use::
4
+
5
+ from llm_format_guard import guard
6
+ result = guard(messages, call_llm) # call_llm(list[dict]) -> str
7
+ print(result.text)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from .check import check
13
+ from .detect import detect
14
+ from .errors import FormatGuardError, LLMCallError, SplitterUnavailable
15
+ from .guard import guard
16
+ from .ledger import Ledger
17
+ from .measure import measure
18
+ from .mock import MockLLM
19
+ from .repair import repair
20
+ from .types import Constraint, GuardResult, Metrics, RepairResult, Violation
21
+
22
+ __version__ = "0.1.2"
23
+
24
+ __all__ = [
25
+ "Constraint",
26
+ "FormatGuardError",
27
+ "GuardResult",
28
+ "LLMCallError",
29
+ "Ledger",
30
+ "Metrics",
31
+ "MockLLM",
32
+ "RepairResult",
33
+ "SplitterUnavailable",
34
+ "Violation",
35
+ "__version__",
36
+ "check",
37
+ "detect",
38
+ "guard",
39
+ "measure",
40
+ "repair",
41
+ ]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,138 @@
1
+ """Judge an answer against constraints (loose or strict) and describe violations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Iterable, List, Sequence, Union
6
+
7
+ from .measure import measure
8
+ from .types import Constraint, Metrics, Violation
9
+
10
+ __all__ = ["check", "describe_target", "violation_distance", "MODES"]
11
+
12
+ MODES = ("loose", "strict")
13
+
14
+ _UNIT = {
15
+ "ko": {"lines": "줄", "sentences": "문장", "chars": "자", "chars_no_space": "자", "words": "단어",
16
+ "items": "개 항목", "paragraphs": "문단", "table_rows": "행"},
17
+ "en": {"lines": "lines", "sentences": "sentences", "chars": "characters",
18
+ "chars_no_space": "characters", "words": "words", "items": "items",
19
+ "paragraphs": "paragraphs", "table_rows": "table rows"},
20
+ }
21
+ _NOTE = {
22
+ "ko": {"chars": "공백 포함", "chars_no_space": "공백 제외", "table_rows": "표의 데이터 행"},
23
+ "en": {"chars": "spaces included", "chars_no_space": "spaces excluded", "table_rows": "table data rows"},
24
+ }
25
+ _OP = {
26
+ "ko": {"le": "이하", "lt": "미만", "ge": "이상", "gt": "초과", "eq": "", "approx": "내외"},
27
+ "en": {"le": "at most", "lt": "fewer than", "ge": "at least", "gt": "more than", "eq": "exactly",
28
+ "approx": "about"},
29
+ }
30
+ _ATTR = {"lines": "lines", "sentences": "sentences", "chars": "chars", "chars_no_space": "chars_no_space",
31
+ "words": "words", "items": "items", "paragraphs": "paragraphs", "table_rows": "table_rows"}
32
+
33
+
34
+ def unit_of(axis: str, lang: str) -> str:
35
+ return _UNIT[lang].get(axis, "")
36
+
37
+
38
+ def note_of(axis: str, lang: str) -> str:
39
+ return _NOTE[lang].get(axis, "")
40
+
41
+
42
+ def describe_target(c: Constraint, lang: str = "ko") -> str:
43
+ """Human wording of a numeric target, e.g. "3줄 이하" or "at most 3 lines"."""
44
+ unit = unit_of(c.axis, lang)
45
+ if lang == "ko":
46
+ if c.op == "eq":
47
+ return f"정확히 {c.value}{unit}"
48
+ return f"{c.value}{unit} {_OP['ko'][c.op]}"
49
+ return f"{_OP['en'][c.op]} {c.value} {unit}"
50
+
51
+
52
+ def _ok(op: str, actual: float, value: int, tolerance: float) -> bool:
53
+ if op == "le":
54
+ return actual <= value
55
+ if op == "lt":
56
+ return actual < value
57
+ if op == "ge":
58
+ return actual >= value
59
+ if op == "gt":
60
+ return actual > value
61
+ if op == "eq":
62
+ return actual == value
63
+ return abs(actual - value) <= tolerance * value + 1e-9 # approx
64
+
65
+
66
+ def _candidates(c: Constraint, m: Metrics, mode: str) -> List[int]:
67
+ if c.axis == "lines" and mode == "loose":
68
+ return [m.lines, m.lines_wo_preamble] # a one-line lead-in ("다음은 요약입니다:") is forgiven
69
+ return [getattr(m, _ATTR[c.axis])]
70
+
71
+
72
+ def _message(c: Constraint, actual: int, lang: str) -> str:
73
+ unit = unit_of(c.axis, lang)
74
+ note = note_of(c.axis, lang)
75
+ if lang == "ko":
76
+ text = f"현재 {actual}{unit}, 목표 {describe_target(c, 'ko')}"
77
+ return f"{text} ({note})" if note else text
78
+ text = f"currently {actual} {unit}, target {describe_target(c, 'en')}"
79
+ return f"{text} ({note})" if note else text
80
+
81
+
82
+ def check(
83
+ text_or_metrics: Union[str, Metrics],
84
+ constraints: Iterable[Constraint],
85
+ *,
86
+ mode: str = "loose",
87
+ approx_tolerance: float = 0.1,
88
+ lang: str = "ko",
89
+ ) -> List[Violation]:
90
+ """Return the constraints the answer breaks (empty list = all satisfied).
91
+
92
+ ``mode="loose"`` (default) gives the answer the benefit of the doubt: an upper
93
+ bound uses the smaller of the plausible counts, a lower bound the larger one.
94
+ ``mode="strict"`` uses the raw count. ``approx`` constraints ("200자 내외")
95
+ allow ``approx_tolerance`` (10% by default).
96
+ """
97
+ if mode not in MODES:
98
+ raise ValueError(f"mode must be one of {MODES}, got {mode!r}")
99
+ if lang not in _UNIT:
100
+ raise ValueError(f"lang must be 'ko' or 'en', got {lang!r}")
101
+ if not 0 <= approx_tolerance < 1:
102
+ raise ValueError("approx_tolerance must be between 0 and 1 (for example 0.1 for 10%)")
103
+ m = text_or_metrics if isinstance(text_or_metrics, Metrics) else measure(text_or_metrics)
104
+ out: List[Violation] = []
105
+ for c in constraints:
106
+ if c.axis == "shape_table":
107
+ if not m.has_table:
108
+ msg = "표 형식이 아님, 목표: 마크다운 표" if lang == "ko" else "no table found, target: a markdown table"
109
+ out.append(Violation(c, 0, "shape_mismatch", msg))
110
+ continue
111
+ if c.axis == "shape_list":
112
+ if not m.has_list:
113
+ msg = "목록 형식이 아님, 목표: 글머리 목록" if lang == "ko" else "no list found, target: a bulleted list"
114
+ out.append(Violation(c, 0, "shape_mismatch", msg))
115
+ continue
116
+ values = _candidates(c, m, mode)
117
+ if c.op in ("le", "lt"):
118
+ actual = min(values)
119
+ elif c.op in ("ge", "gt"):
120
+ actual = max(values)
121
+ else:
122
+ actual = values[0]
123
+ passed = (any(_ok(c.op, v, c.value, approx_tolerance) for v in values)
124
+ if c.op in ("eq", "approx") else _ok(c.op, actual, c.value, approx_tolerance))
125
+ if passed:
126
+ continue
127
+ over = actual > c.value if c.op in ("eq", "approx") else c.op in ("le", "lt")
128
+ out.append(Violation(c, actual, "over" if over else "under", _message(c, actual, lang)))
129
+ return out
130
+
131
+
132
+ def violation_distance(v: Violation) -> float:
133
+ """How far an answer is from the target, scaled by the target (shape mismatch = 1.0)."""
134
+ c = v.constraint
135
+ if v.kind == "shape_mismatch":
136
+ return 1.0
137
+ target = {"le": c.value, "lt": c.value - 1, "ge": c.value, "gt": c.value + 1}.get(c.op, c.value)
138
+ return abs(v.actual - target) / max(c.value, 1)
@@ -0,0 +1,104 @@
1
+ """Command line: ``llm-format-guard detect | measure | eval``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import dataclasses
7
+ import json
8
+ import sys
9
+ from typing import List, Optional, Sequence
10
+
11
+ from . import __version__
12
+ from .detect import detect
13
+ from .errors import FormatGuardError
14
+ from .evaluate import evaluate, load_conversations
15
+ from .measure import measure
16
+ from .mock import MOCK_NOTICE
17
+
18
+
19
+ def _table(rows: Sequence[Sequence[str]]) -> str:
20
+ widths = [max(len(str(r[i])) for r in rows) for i in range(len(rows[0]))]
21
+ return "\n".join(" ".join(str(c).ljust(w) for c, w in zip(r, widths)).rstrip() for r in rows)
22
+
23
+
24
+ def _cmd_detect(args: argparse.Namespace) -> int:
25
+ found = detect(args.text)
26
+ if args.json:
27
+ print(json.dumps([dataclasses.asdict(c) for c in found], ensure_ascii=False, indent=2))
28
+ elif not found:
29
+ print("(no format or length constraint found)")
30
+ else:
31
+ print(_table([("axis", "op", "value", "text")] + [(c.axis, c.op, str(c.value), c.unit_text) for c in found]))
32
+ return 0
33
+
34
+
35
+ def _cmd_measure(args: argparse.Namespace) -> int:
36
+ if args.file == "-":
37
+ text = sys.stdin.read()
38
+ else:
39
+ with open(args.file, encoding="utf-8") as fh:
40
+ text = fh.read()
41
+ m = measure(text, splitter=args.splitter)
42
+ if args.json:
43
+ print(json.dumps(dataclasses.asdict(m), ensure_ascii=False, indent=2))
44
+ else:
45
+ print(_table([("metric", "value")] + [(k, str(v)) for k, v in dataclasses.asdict(m).items()]))
46
+ return 0
47
+
48
+
49
+ def _cmd_eval(args: argparse.Namespace) -> int:
50
+ report = evaluate(load_conversations(args.jsonl), mock=args.mock, mode=args.mode)
51
+ if args.json:
52
+ print(json.dumps(report, ensure_ascii=False, indent=2))
53
+ return 0
54
+ if args.mock:
55
+ print(f"NOTE: {MOCK_NOTICE}")
56
+ print(f"conversations={report['conversations']} with_constraints={report['with_constraints']} "
57
+ f"detection_rate={report['detection_rate']} false_detections={report['false_detections']} "
58
+ f"mode={report['mode']}")
59
+ stages = list(report["stages"])
60
+ print("\ncompliance (share of conversations with no violation)")
61
+ print(_table([("stage", "rate")] + [(s, f"{report['stages'][s]:.2f}") for s in stages]))
62
+ print("\ncompliance by axis")
63
+ print(_table([("axis", *stages)] + [(a, *(f"{v[s]:.2f}" for s in stages))
64
+ for a, v in report["compliance_by_axis"].items()]))
65
+ print("\nviolations by kind")
66
+ for s in stages:
67
+ print(f" {s}: {report['violations_by_kind'][s] or '{}'}")
68
+ return 0
69
+
70
+
71
+ def build_parser() -> argparse.ArgumentParser:
72
+ p = argparse.ArgumentParser(prog="llm-format-guard",
73
+ description="Detect, measure and evaluate format/length instructions for LLM answers.")
74
+ p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
75
+ sub = p.add_subparsers(dest="command", required=True)
76
+ d = sub.add_parser("detect", help="show the constraints found in one message")
77
+ d.add_argument("text")
78
+ d.add_argument("--json", action="store_true")
79
+ d.set_defaults(func=_cmd_detect)
80
+ m = sub.add_parser("measure", help="count lines, sentences, characters ... of an answer file ('-' = stdin)")
81
+ m.add_argument("file")
82
+ m.add_argument("--splitter", choices=["builtin", "kss"], default="builtin")
83
+ m.add_argument("--json", action="store_true")
84
+ m.set_defaults(func=_cmd_measure)
85
+ e = sub.add_parser("eval", help="score a conversations JSONL file")
86
+ e.add_argument("jsonl")
87
+ e.add_argument("--mock", action="store_true", help="run the practice mock model in three stages")
88
+ e.add_argument("--mode", choices=["loose", "strict"], default="loose")
89
+ e.add_argument("--json", action="store_true")
90
+ e.set_defaults(func=_cmd_eval)
91
+ return p
92
+
93
+
94
+ def main(argv: Optional[List[str]] = None) -> int:
95
+ args = build_parser().parse_args(argv)
96
+ try:
97
+ return args.func(args)
98
+ except (FormatGuardError, OSError, ValueError) as exc:
99
+ print(f"error: {exc}", file=sys.stderr)
100
+ return 2
101
+
102
+
103
+ if __name__ == "__main__": # pragma: no cover
104
+ sys.exit(main())
@@ -0,0 +1,198 @@
1
+ """Regex first filter: pull format and length instructions out of one message.
2
+
3
+ The detector is deliberately precision-first. A bare "5개" ("사과 5개로 나눠") or a
4
+ one-syllable Sino-Korean number without a relation word ("이 자료") is ignored,
5
+ because a wrong constraint is worse than a missed one.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from bisect import bisect_left
12
+ from typing import Dict, FrozenSet, List, Optional, Tuple
13
+
14
+ from .numerals import is_sino_single, number_pattern, to_int
15
+ from .types import Constraint
16
+
17
+ __all__ = ["detect", "detect_release", "LENGTH_AXES", "SHAPE_AXES"]
18
+
19
+ LENGTH_AXES: Tuple[str, ...] = ("lines", "sentences", "chars", "chars_no_space", "words",
20
+ "items", "paragraphs", "table_rows")
21
+ SHAPE_AXES: Tuple[str, ...] = ("shape_table", "shape_list")
22
+
23
+ _NUM = number_pattern()
24
+
25
+ _REL_KO: Dict[str, str] = {"이내": "le", "이하": "le", "미만": "lt", "이상": "ge", "초과": "gt",
26
+ "내외": "approx", "정도": "approx", "안팎": "approx"}
27
+ _PRE_KO: Dict[str, str] = {"정확히": "eq", "딱": "eq", "최대": "le", "최소": "ge"}
28
+ _UNIT_KO: Dict[str, str] = {"줄": "lines", "문장": "sentences", "글자": "chars", "자": "chars",
29
+ "단어": "words", "항목": "items", "포인트": "items", "불릿": "items",
30
+ "글머리": "items", "가지": "items", "문단": "paragraphs",
31
+ "단락": "paragraphs", "행": "table_rows"}
32
+ _NOUNS_KO = "항목|포인트|불릿|글머리|문단|단락|문장|줄|단어"
33
+ _REL_KO_RE = "이내|이하|미만|이상|초과|내외|정도|안팎"
34
+ _PRE_KO_RE = "정확히|딱|최대|최소"
35
+ # A counter may be followed by a particle ("줄로"), but not by more Hangul ("자료", "자리").
36
+ _KO_END = r"(?=[^가-힣]|$|[로으짜만씩에의도는은이가을를])"
37
+ _KO_START = r"(?<![0-9A-Za-z.])"
38
+
39
+ _KO_A = re.compile(
40
+ rf"{_KO_START}(?:(?P<pre>{_PRE_KO_RE})\s*)?(?P<num>{_NUM})\s*"
41
+ rf"(?P<unit>글자|문장|단어|항목|포인트|불릿|글머리|문단|단락|가지|줄|자|행)"
42
+ rf"(?:\s*(?P<rel>{_REL_KO_RE}))?{_KO_END}")
43
+ # "항목 5개로" -> the noun in front of "N개" decides the unit.
44
+ _KO_B = re.compile(
45
+ rf"(?P<noun>{_NOUNS_KO})\s*(?:(?P<pre>{_PRE_KO_RE})\s*)?(?P<num>{_NUM})\s*개"
46
+ rf"(?:\s*(?P<rel>{_REL_KO_RE}))?{_KO_END}")
47
+ # "2개 문단으로" / "5개의 항목" -> the noun after "N개" decides the unit.
48
+ _KO_C = re.compile(
49
+ rf"{_KO_START}(?:(?P<pre>{_PRE_KO_RE})\s*)?(?P<num>{_NUM})\s*개(?:의)?\s*(?P<noun>{_NOUNS_KO})"
50
+ rf"(?:\s*(?P<rel>{_REL_KO_RE}))?{_KO_END}")
51
+ # "첫 3줄만 봐 줘", "50줄 넘는데": the number describes the material (code, log), not the
52
+ # answer the user wants. Drop those; "3줄로", "3줄 이내", "3줄만 써" stay.
53
+ _KO_OBJECT_AFTER = re.compile(r"\s*(?:(?:만|을|를)\s*)?(?:봐|보[고세아]|읽)|\s*(?:넘|짜리|에서|째)")
54
+ _KO_OBJECT_BEFORE = re.compile(r"(?:첫|마지막|처음|맨\s*앞|위|아래|앞|뒤)\s*$")
55
+ #: Largest value accepted as an instruction; bigger numbers are noise.
56
+ MAX_VALUE = 100_000
57
+ _KO_TABLE = re.compile(r"(?<![가-힣])(?:표|테이블)(?:로|\s*형식|\s*형태|\s*포맷|\s*모양)")
58
+ _KO_LIST = re.compile(r"(?:목록|리스트|글머리\s*기호|불릿|불렛)(?:으로|로|\s*형식|\s*형태)")
59
+
60
+ _EN_NUMS = r"\d{1,3}(?:,\d{3})+|\d+|(?:one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|fifteen|twenty|thirty|fifty)"
61
+ _EN_PRE = {"no more than": "le", "at most": "le", "within": "le", "up to": "le",
62
+ "maximum of": "le", "max of": "le", "a maximum of": "le",
63
+ "under": "lt", "less than": "lt", "fewer than": "lt",
64
+ "at least": "ge", "minimum of": "ge", "a minimum of": "ge", "more than": "gt",
65
+ "exactly": "eq", "about": "approx", "around": "approx",
66
+ "approximately": "approx", "roughly": "approx"}
67
+ _EN_UNIT = {"bullet point": "items", "bullet": "items", "sentence": "sentences", "character": "chars",
68
+ "char": "chars", "word": "words", "line": "lines", "paragraph": "paragraphs",
69
+ "item": "items", "point": "items", "row": "table_rows"}
70
+ _EN_A = re.compile(
71
+ r"(?<![\w.-])(?:(?P<pre>" + "|".join(sorted(_EN_PRE, key=len, reverse=True)) + r")\s+)?"
72
+ rf"(?P<num>{_EN_NUMS})[\s-]*"
73
+ r"(?P<unit>bullet points?|bullets?|sentences?|characters?|chars?|words?|lines?|paragraphs?|items?|points?|rows?)"
74
+ r"(?P<tail>\s+or\s+(?:fewer|less|more))?\b", re.I)
75
+ _EN_SINGLE = re.compile(r"\b(?:a\s+)?single\s+(?P<unit>sentence|line|paragraph|word)\b", re.I)
76
+ _EN_TABLE = re.compile(r"\b(?:(?:in|as|into)\s+(?:a\s+)?(?:markdown\s+)?table\b|table\s+format\b|tabular\b)", re.I)
77
+ _EN_LIST = re.compile(
78
+ r"\bas\s+(?:a\s+)?(?:(?:bulleted|numbered|bullet)\s+)?list\b|\bbullet\s+points?\b|\b(?:in|as)\s+bullets?\b"
79
+ r"|\bbulleted\s+list\b|\bnumbered\s+list\b", re.I)
80
+
81
+ _NO_SPACE = re.compile(r"공백\s*(?:을\s*)?(?:제외|빼고|없이)|띄어쓰기\s*(?:를\s*)?(?:제외|없이)|"
82
+ r"(?:excluding|without)\s+(?:white\s*)?spaces?|no\s+spaces|spaces?\s+excluded", re.I)
83
+ # Per-item instructions ("각 줄 30자") are out of scope for 0.1: drop them.
84
+ _PER_ITEM_BEFORE = re.compile(
85
+ r"(?:각\s*(?:줄|문장|항목|문단|단락)\s*[은는이가]?|(?:줄|문장|항목|문단|단락)\s*(?:마다|당|별)|"
86
+ r"(?:each|every|per)\s+[\w-]+)\s*$", re.I)
87
+
88
+ _RELEASE_LENGTH = re.compile(
89
+ r"길게\s*(?:써|작성|답)|길이\s*(?:는\s*)?(?:상관\s*없|제한\s*없)|제한\s*없이|분량\s*(?:은\s*)?(?:상관\s*없|자유)|"
90
+ r"no\s+(?:length\s+)?limits?|any\s+length|as\s+long\s+as\s+you\s+(?:like|want)|"
91
+ r"without\s+(?:a\s+)?(?:length\s+)?limit|length\s+(?:doesn.t|does\s+not)\s+matter", re.I)
92
+ _RELEASE_FORMAT = re.compile(
93
+ r"형식\s*(?:은\s*)?(?:상관\s*없|자유)|아무\s*형식|자유\s*형식|any\s+format|free\s*-?\s*form|"
94
+ r"format\s+(?:doesn.t|does\s+not)\s+matter", re.I)
95
+ _RELEASE_ALL = re.compile(
96
+ r"(?:모든\s*)?(?:제약|형식\s*지시|지시)\s*(?:을\s*|는\s*)?(?:모두\s*)?(?:해제|무시|취소)|"
97
+ r"(?:forget|ignore)\s+(?:the\s+)?(?:previous\s+)?(?:format|constraints?)", re.I)
98
+
99
+
100
+ def _op_from(pre: Optional[str], rel: Optional[str], table: Dict[str, str]) -> str:
101
+ if rel:
102
+ return _REL_KO[rel]
103
+ if pre:
104
+ return table[pre.lower()]
105
+ return "le" # "세 줄로" is read as an upper bound: most complaints are about overshooting
106
+
107
+
108
+ def detect_release(text: str) -> FrozenSet[str]:
109
+ """Return the axes the user released ("길게 써도 돼", "no limit", "any format")."""
110
+ axes: set = set()
111
+ if _RELEASE_ALL.search(text):
112
+ axes.update(LENGTH_AXES + SHAPE_AXES)
113
+ if _RELEASE_FORMAT.search(text):
114
+ axes.update(SHAPE_AXES)
115
+ stripped = _RELEASE_FORMAT.sub(" ", text)
116
+ if _RELEASE_LENGTH.search(stripped):
117
+ axes.update(LENGTH_AXES)
118
+ return frozenset(axes)
119
+
120
+
121
+ def detect(text: str, *, turn: int = 0) -> List[Constraint]:
122
+ """Pull format and length constraints out of one message (regex only, deterministic)."""
123
+ if not isinstance(text, str):
124
+ raise TypeError(f"detect() expects a str, got {type(text).__name__}; "
125
+ "pass the message text, not the message dict")
126
+ # (start, end, axis, op, value, unit_text)
127
+ found: List[Tuple[int, int, str, str, int, str]] = []
128
+
129
+ def add_num(m: "re.Match[str]", axis: str, op: str, token: str) -> None:
130
+ value = to_int(token)
131
+ if value is None or value <= 0 or value > MAX_VALUE:
132
+ return
133
+ if _PER_ITEM_BEFORE.search(text[max(0, m.start() - 14):m.start()]):
134
+ return
135
+ found.append((m.start(), m.end(), axis, op, value, m.group(0).strip()))
136
+
137
+ for m in _KO_A.finditer(text):
138
+ token = m.group("num")
139
+ if not m.group("rel") and (_KO_OBJECT_AFTER.match(text, m.end())
140
+ or _KO_OBJECT_BEFORE.search(text[max(0, m.start() - 6):m.start()])):
141
+ continue # describes the material, not the answer
142
+ if is_sino_single(token) and not (m.group("rel") or m.group("pre")):
143
+ continue # "이 자료": a lone Sino-Korean syllable is only a number when a relation follows
144
+ add_num(m, _UNIT_KO[m.group("unit")], _op_from(m.group("pre"), m.group("rel"), _PRE_KO), token)
145
+ for pattern in (_KO_B, _KO_C):
146
+ for m in pattern.finditer(text):
147
+ token = m.group("num")
148
+ if is_sino_single(token) and not (m.group("rel") or m.group("pre")):
149
+ continue
150
+ add_num(m, _UNIT_KO[m.group("noun")], _op_from(m.group("pre"), m.group("rel"), _PRE_KO), token)
151
+ for m in _KO_TABLE.finditer(text):
152
+ found.append((m.start(), m.end(), "shape_table", "eq", 1, m.group(0)))
153
+ for m in _KO_LIST.finditer(text):
154
+ found.append((m.start(), m.end(), "shape_list", "eq", 1, m.group(0)))
155
+
156
+ for m in _EN_A.finditer(text):
157
+ unit = m.group("unit").lower()
158
+ unit = unit[:-1] if unit.endswith("s") and unit != "bullet points" else unit
159
+ unit = "bullet point" if unit.startswith("bullet point") else unit
160
+ axis = _EN_UNIT[unit]
161
+ tail = (m.group("tail") or "").strip().lower()
162
+ if m.group("pre"):
163
+ op = _EN_PRE[m.group("pre").lower()]
164
+ elif tail.endswith("more"):
165
+ op = "ge"
166
+ else:
167
+ op = "le"
168
+ add_num(m, axis, op, m.group("num"))
169
+ for m in _EN_SINGLE.finditer(text):
170
+ found.append((m.start(), m.end(), _EN_UNIT[m.group("unit").lower()], "le", 1, m.group(0)))
171
+ for m in _EN_TABLE.finditer(text):
172
+ found.append((m.start(), m.end(), "shape_table", "eq", 1, m.group(0)))
173
+ for m in _EN_LIST.finditer(text):
174
+ found.append((m.start(), m.end(), "shape_list", "eq", 1, m.group(0)))
175
+
176
+ # Overlapping matches describe the same words: keep the longest one only.
177
+ # `kept` stays sorted by start and non-overlapping, so only the two neighbours of a
178
+ # candidate can collide with it (O(n log n) instead of O(n^2)).
179
+ found.sort(key=lambda f: (-(f[1] - f[0]), f[0]))
180
+ kept: List[Tuple[int, int, str, str, int, str]] = []
181
+ starts: List[int] = []
182
+ for cand in found:
183
+ i = bisect_left(starts, cand[0])
184
+ if i > 0 and kept[i - 1][1] > cand[0]:
185
+ continue
186
+ if i < len(kept) and kept[i][0] < cand[1]:
187
+ continue
188
+ kept.insert(i, cand)
189
+ starts.insert(i, cand[0])
190
+
191
+ no_space = bool(_NO_SPACE.search(text))
192
+ out: List[Constraint] = []
193
+ for start, end, axis, op, value, unit_text in kept:
194
+ if axis in ("chars", "chars_no_space"):
195
+ axis = "chars_no_space" if no_space else "chars"
196
+ out.append(Constraint(axis=axis, op=op, value=value, unit_text=unit_text,
197
+ span=(start, end), turn=turn))
198
+ return out
@@ -0,0 +1,15 @@
1
+ """Exceptions raised by llm_format_guard."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class FormatGuardError(Exception):
7
+ """Base class for every error raised on purpose by this package."""
8
+
9
+
10
+ class SplitterUnavailable(FormatGuardError):
11
+ """The optional Korean sentence splitter (kss) is not installed."""
12
+
13
+
14
+ class LLMCallError(FormatGuardError):
15
+ """The ``call_llm`` callback misbehaved (for example, it returned a non-string)."""
@@ -0,0 +1,115 @@
1
+ """Evaluate a JSONL file of conversations: how often are format instructions kept?
2
+
3
+ Each line is ``{"id": ..., "messages": [...], "answer": "...", "expect": ["lines"]}``.
4
+ ``answer`` is the model's recorded reply (needed unless ``mock=True``); ``expect``
5
+ optionally lists the axes a human sees in the user's instructions (used for the
6
+ detection rate).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from collections import Counter
13
+ from pathlib import Path
14
+ from typing import Any, Dict, List, Sequence, Tuple
15
+
16
+ from .check import check
17
+ from .errors import FormatGuardError
18
+ from .guard import guard
19
+ from .ledger import Ledger
20
+ from .mock import MOCK_NOTICE, MockLLM
21
+ from .types import Constraint
22
+
23
+ __all__ = ["load_conversations", "evaluate"]
24
+
25
+
26
+ def load_conversations(path: str) -> List[Dict[str, Any]]:
27
+ """Read and validate a conversations JSONL file."""
28
+ rows: List[Dict[str, Any]] = []
29
+ with open(Path(path), encoding="utf-8") as fh:
30
+ for no, raw in enumerate(fh, 1):
31
+ if not raw.strip():
32
+ continue
33
+ try:
34
+ row = json.loads(raw)
35
+ except json.JSONDecodeError as exc:
36
+ raise FormatGuardError(f"{path}:{no}: invalid JSON ({exc.msg}). One JSON object per line.") from exc
37
+ msgs = row.get("messages") if isinstance(row, dict) else None
38
+ if not (isinstance(msgs, list) and msgs and all(isinstance(m, dict) and "role" in m for m in msgs)):
39
+ raise FormatGuardError(
40
+ f'{path}:{no}: needs "messages": a non-empty list of {{"role": ..., "content": ...}}')
41
+ rows.append(row)
42
+ if not rows:
43
+ raise FormatGuardError(f"{path}: no conversations found")
44
+ return rows
45
+
46
+
47
+ def _axis_key(axis: str) -> str:
48
+ return "chars" if axis.startswith("chars") else "shape" if axis.startswith("shape_") else axis
49
+
50
+
51
+ def _rate(ok: int, total: int) -> float:
52
+ return round(ok / total, 4) if total else 0.0
53
+
54
+
55
+ def evaluate(conversations: Sequence[Dict[str, Any]], *, mock: bool = False, mode: str = "loose") -> Dict[str, Any]:
56
+ """Score every conversation; returns a JSON-friendly dict."""
57
+ stage_names = ("raw", "injected", "repaired") if mock else ("recorded",)
58
+ stage_ok: Counter = Counter()
59
+ axis_ok: Dict[Tuple[str, str], int] = Counter()
60
+ axis_total: Counter = Counter()
61
+ kinds: Dict[str, Counter] = {s: Counter() for s in stage_names}
62
+ with_constraints = 0
63
+ expected_total = expected_hit = false_detect = 0
64
+ labelled_any = any("expect" in c for c in conversations)
65
+
66
+ for i, conv in enumerate(conversations):
67
+ msgs = conv["messages"]
68
+ ledger = Ledger.from_messages(msgs)
69
+ active: List[Constraint] = ledger.active
70
+ detected = {_axis_key(c.axis) for c in active}
71
+ if "expect" in conv:
72
+ expected = {_axis_key(a) for a in conv["expect"]}
73
+ expected_total += len(expected)
74
+ expected_hit += len(expected & detected)
75
+ false_detect += len(detected - expected)
76
+ if not active:
77
+ continue
78
+ with_constraints += 1
79
+ answers: Dict[str, str] = {}
80
+ if mock:
81
+ answers["raw"] = MockLLM()(msgs)
82
+ answers["injected"] = MockLLM()(ledger.inject(msgs, lang="auto"))
83
+ answers["repaired"] = guard(msgs, MockLLM(), mode=mode).text
84
+ else:
85
+ if not isinstance(conv.get("answer"), str):
86
+ raise FormatGuardError(
87
+ f'conversation {conv.get("id", i + 1)!r} has no "answer"; add the recorded reply or use --mock')
88
+ answers["recorded"] = conv["answer"]
89
+ for stage, text in answers.items():
90
+ violations = check(text, active, mode=mode)
91
+ bad = {id(v.constraint) for v in violations}
92
+ stage_ok[stage] += 0 if violations else 1
93
+ for c in active:
94
+ axis_total[(c.axis, stage)] += 1
95
+ axis_ok[(c.axis, stage)] += 0 if id(c) in bad else 1
96
+ for v in violations:
97
+ kinds[stage][v.kind] += 1
98
+
99
+ detection = (_rate(expected_hit, expected_total) if labelled_any and expected_total
100
+ else _rate(with_constraints, len(conversations)))
101
+ axes = sorted({a for a, _ in axis_total})
102
+ report: Dict[str, Any] = {
103
+ "mock": mock,
104
+ "mode": mode,
105
+ "conversations": len(conversations),
106
+ "with_constraints": with_constraints,
107
+ "detection_rate": detection,
108
+ "false_detections": false_detect,
109
+ "stages": {s: _rate(stage_ok[s], with_constraints) for s in stage_names},
110
+ "compliance_by_axis": {a: {s: _rate(axis_ok[(a, s)], axis_total[(a, s)]) for s in stage_names} for a in axes},
111
+ "violations_by_kind": {s: dict(sorted(kinds[s].items())) for s in stage_names},
112
+ }
113
+ if mock:
114
+ report["notice"] = MOCK_NOTICE
115
+ return report