llm-format-guard 0.1.2__tar.gz

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.
Files changed (37) hide show
  1. llm_format_guard-0.1.2/LICENSE +21 -0
  2. llm_format_guard-0.1.2/PKG-INFO +428 -0
  3. llm_format_guard-0.1.2/README.md +405 -0
  4. llm_format_guard-0.1.2/pyproject.toml +46 -0
  5. llm_format_guard-0.1.2/setup.cfg +4 -0
  6. llm_format_guard-0.1.2/src/llm_format_guard/__init__.py +41 -0
  7. llm_format_guard-0.1.2/src/llm_format_guard/__main__.py +5 -0
  8. llm_format_guard-0.1.2/src/llm_format_guard/check.py +138 -0
  9. llm_format_guard-0.1.2/src/llm_format_guard/cli.py +104 -0
  10. llm_format_guard-0.1.2/src/llm_format_guard/detect.py +198 -0
  11. llm_format_guard-0.1.2/src/llm_format_guard/errors.py +15 -0
  12. llm_format_guard-0.1.2/src/llm_format_guard/evaluate.py +115 -0
  13. llm_format_guard-0.1.2/src/llm_format_guard/guard.py +65 -0
  14. llm_format_guard-0.1.2/src/llm_format_guard/ledger.py +177 -0
  15. llm_format_guard-0.1.2/src/llm_format_guard/measure.py +102 -0
  16. llm_format_guard-0.1.2/src/llm_format_guard/mock.py +216 -0
  17. llm_format_guard-0.1.2/src/llm_format_guard/numerals.py +70 -0
  18. llm_format_guard-0.1.2/src/llm_format_guard/py.typed +0 -0
  19. llm_format_guard-0.1.2/src/llm_format_guard/repair.py +65 -0
  20. llm_format_guard-0.1.2/src/llm_format_guard/splitters.py +64 -0
  21. llm_format_guard-0.1.2/src/llm_format_guard/types.py +90 -0
  22. llm_format_guard-0.1.2/src/llm_format_guard.egg-info/PKG-INFO +428 -0
  23. llm_format_guard-0.1.2/src/llm_format_guard.egg-info/SOURCES.txt +35 -0
  24. llm_format_guard-0.1.2/src/llm_format_guard.egg-info/dependency_links.txt +1 -0
  25. llm_format_guard-0.1.2/src/llm_format_guard.egg-info/entry_points.txt +2 -0
  26. llm_format_guard-0.1.2/src/llm_format_guard.egg-info/requires.txt +3 -0
  27. llm_format_guard-0.1.2/src/llm_format_guard.egg-info/top_level.txt +1 -0
  28. llm_format_guard-0.1.2/tests/test_check.py +87 -0
  29. llm_format_guard-0.1.2/tests/test_cli.py +124 -0
  30. llm_format_guard-0.1.2/tests/test_detect.py +65 -0
  31. llm_format_guard-0.1.2/tests/test_guard.py +144 -0
  32. llm_format_guard-0.1.2/tests/test_ledger.py +144 -0
  33. llm_format_guard-0.1.2/tests/test_measure.py +33 -0
  34. llm_format_guard-0.1.2/tests/test_repair.py +94 -0
  35. llm_format_guard-0.1.2/tests/test_splitter.py +46 -0
  36. llm_format_guard-0.1.2/tests/test_stdlib_only.py +42 -0
  37. llm_format_guard-0.1.2/tests/test_table_cells.py +37 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LeeGyeongPil
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,428 @@
1
+ Metadata-Version: 2.4
2
+ Name: llm-format-guard
3
+ Version: 0.1.2
4
+ Summary: Catch LLM answers that miss the user's format and length instructions: extract, re-inject, measure, repair once.
5
+ Author: LeeGyeongPil
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/LeeGyeongPil/llm-format-guard
8
+ Keywords: llm,guardrails,output-validation,instruction-following,korean
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Software Development :: Libraries
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Provides-Extra: kss
21
+ Requires-Dist: kss==6.0.6; extra == "kss"
22
+ Dynamic: license-file
23
+
24
+ # llm-format-guard
25
+
26
+ **English** | [한국어](https://github.com/LeeGyeongPil/llm-format-guard/blob/v0.1.2/README.ko.md)
27
+
28
+ A small Python library that catches LLM answers which ignore the user's format and length instructions ("in three lines", "within 200 characters", "as a table") during a conversation. It extracts the constraints from the chat, re-injects them before the last user message, measures the answer deterministically (Korean and markdown aware), and asks the model to rewrite the answer exactly once, adopting the rewrite only when it is strictly better. Zero runtime dependencies, Python 3.10+. Install: `uv add git+https://github.com/LeeGyeongPil/llm-format-guard`.
29
+
30
+ ![quickstart run screen](https://raw.githubusercontent.com/LeeGyeongPil/llm-format-guard/v0.1.2/docs/images/01-quickstart.png)
31
+
32
+ *Figure 1. Output of `examples/quickstart.py`. The model forgot the "in three lines" instruction and answered in 4 lines; the library caught it and fixed it to 3 lines. The model is a practice mock.*
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ uv add git+https://github.com/LeeGyeongPil/llm-format-guard
38
+ ```
39
+
40
+ - Supported versions: Python 3.10 or later (the CI matrix targets 3.10, 3.12 and 3.13; locally, passing tests were confirmed on 3.10 and 3.12). Zero runtime dependencies.
41
+ - If you do not have uv: `curl -LsSf https://astral.sh/uv/install.sh | sh` (installation guide: https://docs.astral.sh/uv/).
42
+ - For more accurate Korean sentence splitting there is an optional `kss` extra. Installation is heavy (measured: 44.4 s to install, 558 MB virtual environment, 6.3 s to import). Use it only when you really need it.
43
+ - Install as a library: `uv add "llm-format-guard[kss] @ git+https://github.com/LeeGyeongPil/llm-format-guard"` (pip uses the same form)
44
+ - If you cloned the repo: `uv sync --extra kss`
45
+ - See [Troubleshooting](#troubleshooting) for details.
46
+ - It has not been published to PyPI yet. Install from the GitHub address as shown above.
47
+
48
+ To clone the repo and run it yourself:
49
+
50
+ ```bash
51
+ git clone https://github.com/LeeGyeongPil/llm-format-guard
52
+ cd llm-format-guard
53
+ uv run python examples/quickstart.py
54
+ ```
55
+
56
+ ## Quick start
57
+
58
+ On the first turn the user says "세 줄로" (in three lines), and two turns later only says "이것도 부탁해" (do this one too). Models usually forget the instruction around here.
59
+
60
+ ```python
61
+ from llm_format_guard import MockLLM, guard
62
+
63
+ messages = [
64
+ {"role": "user", "content": "앞으로 세 줄로 요약해 줘"},
65
+ {"role": "assistant", "content": "네, 세 줄로 요약하겠습니다."},
66
+ {"role": "user", "content": "점심 뭐 먹을까?"},
67
+ {"role": "assistant", "content": "비빔밥은 어때요?"},
68
+ {"role": "user", "content": "이것도 부탁해: 회사가 신제품을 공개했다. 가격은 낮아졌다. 출시는 다음 달이다."},
69
+ ]
70
+ result = guard(messages, MockLLM()) # Put your own model-calling function in place of MockLLM
71
+ print(result.text)
72
+ ```
73
+
74
+ (The Korean messages say: "From now on, summarize in three lines" / "Okay, I'll summarize in three lines." / "What should we eat for lunch?" / "How about bibimbap?" / "Do this one too: The company unveiled a new product. The price went down. The release is next month.")
75
+
76
+ The full runnable file is [`examples/quickstart.py`](https://github.com/LeeGyeongPil/llm-format-guard/blob/v0.1.2/examples/quickstart.py). Actual output:
77
+
78
+ ```text
79
+ 연습용 목(mock) 모델입니다. 규칙으로 흉내 낸 답이며 실제 모델의 측정값이 아닙니다. (practice mock model - not a measurement of any real model)
80
+
81
+ [1] 대화에서 뽑은 제약:
82
+ lines le 3 (말한 곳: 사용자 1번째 메시지, "세 줄")
83
+ [2] 마지막 사용자 메시지 바로 앞에 다시 넣은 블록:
84
+ [활성 제약]
85
+ - 답은 3줄 이하로 쓴다.
86
+ [3] 모델의 첫 답: 4줄
87
+ 위반: 현재 4줄, 목표 3줄 이하
88
+ [4] 수치 피드백으로 1회 수선 -> 채택 여부 adopted=True (improved)
89
+ [5] 최종 답:
90
+ 핵심 내용을 먼저 짚어 보면 전체 흐름이 한눈에 들어옵니다.
91
+ 배경을 조금 더 풀어 말하면 이 주제가 나온 이유가 분명해집니다.
92
+ 중요한 조건은 상황마다 달라서 앞뒤 맥락을 함께 보는 편이 좋습니다.
93
+
94
+ 모델 호출 2회 (MockLLM 호출 카운터 2)
95
+ RESULT before_lines=4 after_lines=3 violations_after=0 adopted=True
96
+ ```
97
+
98
+ (Gloss of the Korean output: "This is a practice mock model; answers are imitated by rules and are not measurements of a real model." / [1] constraint extracted from the conversation: lines at most 3 (said in: user message 1, "세 줄"). [2] block re-inserted just before the last user message: "[active constraints] - write the answer in 3 lines or fewer." [3] the model's first answer: 4 lines; violation: currently 4 lines, target at most 3. [4] one repair with numeric feedback -> adopted. [5] final answer (three filler sentences). "Model calls: 2".)
99
+
100
+ > **This is a practice mock model.** `MockLLM` is an imitation model that deliberately forgets instructions by fixed rules; it is not a real model. It is a device to let you run everything end to end without keys or a network, and the figures shown here are not the performance of any real model.
101
+ > This repo has not yet been run against a real model (Ollama etc.). [`examples/with_ollama.py`](https://github.com/LeeGyeongPil/llm-format-guard/blob/v0.1.2/examples/with_ollama.py) was only written and its execution has not been verified. Real models can be slow, so the timeout is set generously (300 seconds by default).
102
+
103
+ ## Core concepts
104
+
105
+ ```mermaid
106
+ flowchart LR
107
+ A["Conversation history"] --> B["Constraint extraction<br/>detect / Ledger"]
108
+ B --> C["Re-injection<br/>before the last user message"]
109
+ C --> D["Model call"]
110
+ D --> E["Measure + judge<br/>measure / check"]
111
+ E -->|"no violation"| F["Answer as is"]
112
+ E -->|"violation"| G["One repair with<br/>numeric feedback"]
113
+ G --> H{"Did violations<br/>strictly decrease?"}
114
+ H -->|"yes"| I["Adopt repaired answer"]
115
+ H -->|"no"| F
116
+ ```
117
+
118
+ *Figure 2. What one `guard()` call does. The model is called at most twice.*
119
+
120
+ 1. **Constraint extraction**: regular expressions pull out instructions such as "3 lines or fewer", "within 200 characters" and "as a table". It reads Korean and English, Arabic numerals and Korean numerals such as "세" and "삼" (both "three"). Ambiguous ones are dropped (it prefers missing a constraint to a false detection).
121
+ 2. **Re-injection**: the constraints it remembers are put back, as an `[활성 제약]` ("active constraints") block written in positive sentences, right before the last user message. This brings the old instruction back in front of the model's eyes.
122
+ 3. **Deterministic measurement**: it does not ask the model "did you comply?"; code counts lines, sentences, characters, words, items, paragraphs and table rows. Code blocks and `<think>` tags are excluded. The visible characters of table cells count toward the character and word counts (separator rows and pipes excluded; sentence counts excluded).
123
+ 4. **Conditional repair**: if there is a violation, the model is asked to rewrite exactly once with numeric feedback such as "currently 4 lines, target 3 or fewer", and the new answer is used **only if `(number of violations, distance to target)` strictly decreased**. An answer that met the length but turned a table into a list is rejected.
124
+
125
+ More detail is in [docs/how-it-works.md](https://github.com/LeeGyeongPil/llm-format-guard/blob/v0.1.2/docs/how-it-works.md) (Korean).
126
+
127
+ ## Seeing it step by step
128
+
129
+ ### 1) Extracting constraints
130
+
131
+ ```bash
132
+ uv run llm-format-guard detect "항목 5개로, 200자 이내로 정리하고 표로 줘"
133
+ ```
134
+ ```text
135
+ axis op value text
136
+ items le 5 항목 5개
137
+ chars le 200 200자 이내
138
+ shape_table eq 1 표로
139
+ ```
140
+
141
+ (The input means "Organize it in 5 items, within 200 characters, and give it as a table".)
142
+
143
+ ![detect run screen](https://raw.githubusercontent.com/LeeGyeongPil/llm-format-guard/v0.1.2/docs/images/02-detect.png)
144
+
145
+ *Figure 3. Three constraints were extracted from one sentence. `op` is the comparison operator (`le` means "at most").*
146
+
147
+ ### 2) Measuring answer length
148
+
149
+ ```bash
150
+ uv run llm-format-guard measure examples/data/answer.md
151
+ ```
152
+ ```text
153
+ metric value
154
+ lines 8
155
+ lines_wo_preamble 7
156
+ sentences 5
157
+ chars 120
158
+ chars_no_space 105
159
+ words 27
160
+ items 2
161
+ paragraphs 4
162
+ has_table True
163
+ table_rows 3
164
+ has_list True
165
+ ```
166
+
167
+ ![measure run screen](https://raw.githubusercontent.com/LeeGyeongPil/llm-format-guard/v0.1.2/docs/images/03-measure.png)
168
+
169
+ *Figure 4. The result of code counting the same answer. Code blocks and `<think>` are left out. (This screenshot is from 0.1.1. For the current values that include the table-cell character count, see the text example above.)*
170
+
171
+ ### 3) Judging without a model
172
+
173
+ [`examples/check_only.py`](https://github.com/LeeGyeongPil/llm-format-guard/blob/v0.1.2/examples/check_only.py):
174
+
175
+ ```python
176
+ from llm_format_guard import check, detect, measure
177
+
178
+ constraints = detect("항목 5개로, 200자 이내로 정리하고 표로 줘")
179
+ answer = "- 하나\n- 둘\n- 셋\n- 넷\n- 다섯\n- 여섯"
180
+
181
+ print(measure(answer))
182
+ for v in check(answer, constraints):
183
+ print(v.kind, "|", v.message)
184
+ ```
185
+ ```text
186
+ Metrics(lines=6, lines_wo_preamble=6, sentences=6, chars=9, chars_no_space=9, words=6, items=6, paragraphs=1, has_table=False, table_rows=0, has_list=True)
187
+ over | 현재 6개 항목, 목표 5개 항목 이하
188
+ shape_mismatch | 표 형식이 아님, 목표: 마크다운 표
189
+ ```
190
+
191
+ (The Korean messages read: "currently 6 items, target 5 items or fewer" and "not a table format, target: markdown table".)
192
+
193
+ ![check run screen](https://raw.githubusercontent.com/LeeGyeongPil/llm-format-guard/v0.1.2/docs/images/04-check-only.png)
194
+
195
+ *Figure 5. Six items exceed the limit (`over`), and a list is not a table, so the shape does not match (`shape_mismatch`).*
196
+
197
+ ### 4) Evaluating many conversations at once
198
+
199
+ Before deployment, you can see "how well were format instructions followed" across the conversation logs you have collected. The input is JSONL (one JSON object per line). Below is [`examples/data/my-chats.jsonl`](https://github.com/LeeGyeongPil/llm-format-guard/blob/v0.1.2/examples/data/my-chats.jsonl), a two-line file made by hand. The first line (mine-1) is an example answering four lines to a three-line instruction, and the second line (mine-2) answers a table instruction with a list (so a shape_table violation appears).
200
+
201
+ ```json
202
+ {"id": "mine-1", "messages": [{"role": "user", "content": "세 줄로 요약해 줘"}, {"role": "assistant", "content": "네."}, {"role": "user", "content": "이번엔 신제품 소식도 부탁해"}], "answer": "신제품이 공개됐습니다.\n가격은 낮아졌습니다.\n출시는 다음 달입니다.\n사전 예약도 열립니다.", "expect": ["lines"]}
203
+ ```
204
+
205
+ | Field | Required | Meaning |
206
+ |---|---|---|
207
+ | `messages` | Required | A list of `{"role", "content"}`. Must not be empty |
208
+ | `answer` | Required without `--mock` | The answer the model actually gave (a recording). With `--mock` the practice mock model produces it, so it is unnecessary |
209
+ | `expect` | Optional | Names of the axes a human would say should be extracted from this conversation (`lines`, etc.). Used only to compute `detection_rate` (the share extracted without missing) and `false_detections` (the number of times an unexpected axis was extracted) |
210
+ | `id`, `source`, `note` | Optional | Labels for human readers |
211
+
212
+ ```bash
213
+ uv run llm-format-guard eval examples/data/my-chats.jsonl
214
+ ```
215
+ ```text
216
+ conversations=2 with_constraints=2 detection_rate=1.0 false_detections=0 mode=loose
217
+
218
+ compliance (share of conversations with no violation)
219
+ stage rate
220
+ recorded 0.00
221
+
222
+ compliance by axis
223
+ axis recorded
224
+ lines 0.00
225
+ shape_table 0.00
226
+
227
+ violations by kind
228
+ recorded: {'over': 1, 'shape_mismatch': 1}
229
+ ```
230
+
231
+ Without `--mock` there is a single stage, `recorded` (the recorded answer as is). With `--json` the same content comes out as JSON, with the keys `mock`, `mode`, `conversations`, `with_constraints`, `detection_rate`, `false_detections`, `stages`, `compliance_by_axis` and `violations_by_kind`.
232
+
233
+ Now the keyless practice mock mode, which compares three stages (as is / re-injected / repaired). This is the example file with 30 conversations.
234
+
235
+ ```bash
236
+ uv run llm-format-guard eval examples/data/conversations.jsonl --mock
237
+ ```
238
+ ```text
239
+ conversations=30 with_constraints=23 detection_rate=1.0 false_detections=0 mode=loose
240
+
241
+ compliance (share of conversations with no violation)
242
+ stage rate
243
+ raw 0.09
244
+ injected 0.30
245
+ repaired 0.96
246
+
247
+ compliance by axis
248
+ axis raw injected repaired
249
+ chars 0.00 0.00 1.00
250
+ chars_no_space 0.00 0.00 1.00
251
+ items 0.00 0.00 1.00
252
+ lines 0.00 0.00 1.00
253
+ paragraphs 1.00 0.00 1.00
254
+ sentences 0.20 0.20 1.00
255
+ shape_list 0.25 1.00 1.00
256
+ shape_table 0.25 1.00 1.00
257
+ table_rows 0.00 0.00 0.00
258
+ words 0.00 0.00 1.00
259
+
260
+ violations by kind
261
+ raw: {'over': 15, 'shape_mismatch': 6}
262
+ injected: {'over': 16}
263
+ repaired: {'over': 1}
264
+ ```
265
+
266
+ (At the very top of the real output, a one-line `NOTE:` about the mock model comes first.)
267
+
268
+ ![eval run screen](https://raw.githubusercontent.com/LeeGyeongPil/llm-format-guard/v0.1.2/docs/images/05-eval.png)
269
+
270
+ *Figure 6. Compliance rate at three stages (as is / re-injected / repaired). It is a product of the mock model's rules, not a measurement of a real model.*
271
+
272
+ How to read it: it only shows the **tendency** that re-injection restores the shape (table, list) but cannot fix counts, and that repair with numeric feedback fixes the counts. `table_rows 0.00` is a deliberately built scenario (repair turned the table into a list and was rejected, so the original 5 rows remain).
273
+
274
+ ## API
275
+
276
+ Public names are imported directly from `llm_format_guard`.
277
+
278
+ | Name | What it does | Main arguments | Returns |
279
+ |---|---|---|---|
280
+ | `guard(messages, call_llm, *, ledger=None, repair=True, mode="loose", position="before_last_user", lang="auto")` | Extract → re-inject → call → measure → one repair if needed, all at once | `call_llm(list[dict]) -> str` | `GuardResult` |
281
+ | `detect(text, *, turn=0)` | Extracts constraints from one message (regex, deterministic) | `text: str` | `list[Constraint]` |
282
+ | `Ledger(max_items=5, window=6, scan_edge=300)` | Remembers, expires and renders constraints across turns | Methods `update(user_text, turn)`, `from_messages(messages)`, `active` (property), `render(lang)`, `inject(messages, position)` | `Ledger` |
283
+ | `measure(text, *, splitter="builtin")` | Measures lines, sentences, characters, words, items, paragraphs, tables | `splitter="kss"` optional | `Metrics` |
284
+ | `check(text_or_metrics, constraints, *, mode="loose", approx_tolerance=0.1, lang="ko")` | Returns the list of violations (empty list = all satisfied) | `mode="strict"` uses raw counts | `list[Violation]` |
285
+ | `repair(messages, answer, violations, call_llm, *, constraints, mode, lang)` | One rewrite, adopted only if it improves | | `RepairResult` |
286
+ | `MockLLM(script=None)` | Practice mock model (not a real model) | | Callable object |
287
+ | Data types | `Constraint`, `Metrics`, `Violation`, `RepairResult`, `GuardResult` | | Read-only dataclasses |
288
+ | Exceptions | `FormatGuardError` (base), `LLMCallError` (the callback returned a non-string value), `SplitterUnavailable` (kss not installed) | | |
289
+
290
+ - Constraint axes (`Constraint.axis`): `lines`, `sentences`, `chars`, `chars_no_space`, `words`, `items`, `paragraphs`, `table_rows`, `shape_table`, `shape_list`.
291
+ - Comparison operators (`op`): `le` (at most), `lt` (less than), `ge` (at least), `gt` (more than), `eq` (exactly), `approx` (around, ±10% by default).
292
+ - `GuardResult` fields: `text` (final answer), `original`, `constraints`, `violations_before`, `violations_after`, `adopted`, `llm_calls`, `injected`, `repair_reason`, `messages_sent`.
293
+ - Terminal commands: `llm-format-guard detect | measure | eval` (`--json` supported; `eval` takes `--mock` and `--mode loose|strict`).
294
+
295
+ ## Usage examples
296
+
297
+ ### Connecting your own model
298
+
299
+ `call_llm` can be any function that "takes a message list and returns the answer string". The example for OpenAI-compatible servers (for example a local Ollama) is [`examples/with_ollama.py`](https://github.com/LeeGyeongPil/llm-format-guard/blob/v0.1.2/examples/with_ollama.py). For the environment variables, see `.env.example`. If run without configuration, it exits with a guidance message.
300
+
301
+ ```bash
302
+ uv run python examples/with_ollama.py
303
+ ```
304
+ ```text
305
+ Set LFG_BASE_URL and LFG_MODEL first (see .env.example). For a no-key demo run examples/quickstart.py instead.
306
+ ```
307
+
308
+ ![screen when run without environment variables](https://raw.githubusercontent.com/LeeGyeongPil/llm-format-guard/v0.1.2/docs/images/06-missing-env.png)
309
+
310
+ *Figure 7. This is the intended guidance screen (exit code 1). Calls to a real model have not been verified.*
311
+
312
+ ### Using only the constraint ledger
313
+
314
+ [`examples/ledger_demo.py`](https://github.com/LeeGyeongPil/llm-format-guard/blob/v0.1.2/examples/ledger_demo.py):
315
+
316
+ ```python
317
+ from llm_format_guard import Ledger
318
+
319
+ ledger = Ledger()
320
+ ledger.update("세 줄로 요약해 줘", turn=0)
321
+ ledger.update("점심 뭐 먹을까?", turn=1)
322
+ print(ledger.render())
323
+ print("--- after a release phrase ---")
324
+ ledger.update("이제 길게 써도 돼", turn=2)
325
+ print(repr(ledger.render()), len(ledger.active))
326
+ ```
327
+ ```text
328
+ [활성 제약]
329
+ - 답은 3줄 이하로 쓴다.
330
+ --- after a release phrase ---
331
+ '' 0
332
+ ```
333
+
334
+ (The inputs mean "Summarize in three lines", "What should we eat for lunch?" and "Now you may write long".)
335
+
336
+ When a release phrase such as "길게 써도 돼" ("you may write long") appears, the corresponding constraint disappears. A new instruction on the same axis overwrites the old one (latest wins).
337
+
338
+ ## Settings and default behavior
339
+
340
+ | Item | Default | Description |
341
+ |---|---|---|
342
+ | `mode` | `loose` | A one-line preamble ("다음은 요약입니다:", "Here is the summary:") is tolerated. `strict` uses raw counts |
343
+ | `Ledger(window=6)` | 6 | Only constraints within the last 6 user turns are valid |
344
+ | `Ledger(max_items=5)` | 5 | Upper limit of constraints held at once. 0 turns off re-injection |
345
+ | `Ledger(scan_edge=300)` | 300 | For long messages over 1200 characters (a pasted article), only the first and last 300 characters are read to prevent false detections |
346
+ | "세 줄로" ("in three lines") | Upper bound (`le`) | Becomes `eq` only when "exactly/just" is attached |
347
+ | `repair=False` | | Only re-injects and measures; skips repair |
348
+ | `position` | `before_last_user` | Where the constraint block is placed. See the table below |
349
+
350
+ ### Choosing the injection position (`position`)
351
+
352
+ | Value | How it is inserted | When to use |
353
+ |---|---|---|
354
+ | `before_last_user` (default) | Inserts a `system` message right before the last user message | Places that accept a mid-conversation `system` message, such as OpenAI-compatible APIs and Ollama |
355
+ | `system_end` | Appends to the end of the first `system` message (creates a new one at the very start if there is none) | APIs that reject mid-conversation `system` messages or take `system` as a separate argument |
356
+ | `in_last_user` | Appends to the end of the last user message | APIs with no `system` role at all |
357
+
358
+ If a request is rejected after sending with the default, switch to `system_end` or `in_last_user`. Check what was actually sent with `GuardResult.messages_sent`. Here is the role order from applying the three values to the same conversation.
359
+
360
+ ```text
361
+ before_last_user ['system', 'user', 'assistant', 'system', 'user']
362
+ system_end ['system', 'user', 'assistant', 'user']
363
+ in_last_user ['system', 'user', 'assistant', 'user']
364
+ ```
365
+
366
+ (`system_end` and `in_last_user` have the same role order; only where the content is appended differs.)
367
+
368
+ ## When to use it
369
+
370
+ - Use it when you want the model to obey free-text format instructions the user gave during a conversation, such as line count, character count or a table.
371
+ - It also fits when you want to measure the length of Korean answers with no dependencies.
372
+ - If your goal is JSON or Pydantic structured output, see [Instructor](https://python.useinstructor.com/).
373
+ - If you need a general-purpose validator and retry framework, see [Guardrails AI](https://www.guardrailsai.com/docs).
374
+ - If your goal is offline benchmark scoring, see [IFEval](https://github.com/google-research/google-research/tree/master/instruction_following_eval).
375
+
376
+ ## Versions and compatibility
377
+
378
+ - Follows Semantic Versioning (SemVer). During 0.x the API may change in minor versions, and any change is recorded in [CHANGELOG.md](https://github.com/LeeGyeongPil/llm-format-guard/blob/v0.1.2/CHANGELOG.md).
379
+ - Currently `0.1.2`. It reads Korean and English instructions only.
380
+
381
+ ## Limitations and roadmap
382
+
383
+ Limitations (0.1.2):
384
+ - Instruction extraction uses regular expressions, so some phrasings are missed. Ambiguous phrasing is dropped on purpose (only things with a noun attached, like "항목 5개" ("5 items"), are caught; a sentence about the size of the material, like "첫 3줄만 봐 줘" ("just look at the first 3 lines"), is not treated as a constraint).
385
+ - For range instructions written with a tilde, such as `3~5줄` (3-5 lines), only the upper bound (5 lines or fewer) is read and the lower bound is dropped. A range spelled out as "세 줄 이상 다섯 줄 이하" ("at least three and at most five lines") is captured as two bounds, lower and upper.
386
+ - Compound instructions applied per line ("각 줄 30자", "30 characters per line") are dropped.
387
+ - Streaming responses are not supported (only complete strings are accepted).
388
+ - It has not been run against a real model. Evaluation figures are based on the mock model and hand-written recorded answers.
389
+ - Measuring the same file with hand-written recorded answers, without the mock (`eval` without `--mock`), gave `recorded 0.48`.
390
+
391
+ Roadmap (planned, not a promise):
392
+ - 0.2.0: `guard_stream` (stream handling), an OpenAI-compatible adapter, recorded answers from real models, an optional LLM extractor
393
+ - 0.3.0: per-item compound constraints, range instructions like `3~5줄`, heading counts, PyPI publishing preparation
394
+
395
+ ## Troubleshooting
396
+
397
+ | Symptom | Cause | Fix |
398
+ |---|---|---|
399
+ | `LLMCallError: call_llm must return the answer as a str` | The callback returned the whole response object | Return only the string, e.g. `completion.choices[0].message.content` |
400
+ | `SplitterUnavailable` (message: `splitter="kss" needs the optional kss package ...`) | `measure(..., splitter="kss")` was used but kss is missing | If installed as a library, `uv add "llm-format-guard[kss] @ git+https://github.com/LeeGyeongPil/llm-format-guard"`; in the repo, `uv sync --extra kss` |
401
+ | `ValueError: position must be one of ...` / the API rejects a mid-conversation `system` message | A typo in the `position` value, or the provider cannot accept a mid-conversation `system` | Choose `system_end` or `in_last_user` from the [injection position](#choosing-the-injection-position-position) table |
402
+ | Several sentences on one line without periods count as 1 sentence | The built-in splitter counts per line but cannot split sentences without periods | Use the optional `kss` feature |
403
+ | Running `python` directly inside the package folder gives an error | The package's `types.py` shadows the standard `types` | Always run from the repo root |
404
+ | A violation about character count appears for a table answer | The visible characters of table cells also count toward the character count (since 0.1.2) | Adjust the length constraint to fit the table size, or ask without a table |
405
+ | A constraint is not picked up | The phrasing is not in the regex list, or is ambiguous | Check with `uv run llm-format-guard detect "<sentence>"` and then report it as an issue |
406
+
407
+ ## Development and contributing
408
+
409
+ ```bash
410
+ uv sync
411
+ uv run pytest -q
412
+ uv run python examples/quickstart.py
413
+ uv run llm-format-guard eval examples/data/conversations.jsonl --mock
414
+ ```
415
+
416
+ The tests are written as standard `unittest` classes, so they also run with `python -m unittest discover -s tests`. For security issues, see [SECURITY.md](https://github.com/LeeGyeongPil/llm-format-guard/blob/v0.1.2/SECURITY.md).
417
+
418
+ ## Learn more
419
+
420
+ - IFEval paper (verifiable instructions): https://arxiv.org/abs/2311.07911 (checked 2026-11-09)
421
+ - IFEval code: https://github.com/google-research/google-research/tree/master/instruction_following_eval
422
+ - Instructor's retry approach: https://python.useinstructor.com/
423
+ - Guardrails AI: https://www.guardrailsai.com/docs
424
+ - kss (Korean sentence splitter): https://github.com/hyunwoongko/kss
425
+
426
+ ## License
427
+
428
+ MIT. See [LICENSE](https://github.com/LeeGyeongPil/llm-format-guard/blob/v0.1.2/LICENSE).