structured-output-repair 0.3.0b1__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 (39) hide show
  1. structured_output_repair-0.3.0b1/CHANGELOG.md +45 -0
  2. structured_output_repair-0.3.0b1/LICENSE +18 -0
  3. structured_output_repair-0.3.0b1/MANIFEST.in +2 -0
  4. structured_output_repair-0.3.0b1/NOTICE +10 -0
  5. structured_output_repair-0.3.0b1/PKG-INFO +180 -0
  6. structured_output_repair-0.3.0b1/README.md +151 -0
  7. structured_output_repair-0.3.0b1/examples/quickstart.py +14 -0
  8. structured_output_repair-0.3.0b1/pyproject.toml +44 -0
  9. structured_output_repair-0.3.0b1/setup.cfg +4 -0
  10. structured_output_repair-0.3.0b1/src/llm_output_repair/__init__.py +25 -0
  11. structured_output_repair-0.3.0b1/src/llm_output_repair/_limits.py +8 -0
  12. structured_output_repair-0.3.0b1/src/llm_output_repair/_version.py +3 -0
  13. structured_output_repair-0.3.0b1/src/llm_output_repair/api.py +96 -0
  14. structured_output_repair-0.3.0b1/src/llm_output_repair/cli.py +106 -0
  15. structured_output_repair-0.3.0b1/src/llm_output_repair/controlled_json.py +491 -0
  16. structured_output_repair-0.3.0b1/src/llm_output_repair/crash_logger.py +104 -0
  17. structured_output_repair-0.3.0b1/src/llm_output_repair/crash_recorder.py +210 -0
  18. structured_output_repair-0.3.0b1/src/llm_output_repair/extract_json.py +1213 -0
  19. structured_output_repair-0.3.0b1/src/llm_output_repair/extract_yaml.py +642 -0
  20. structured_output_repair-0.3.0b1/src/llm_output_repair/regression.py +311 -0
  21. structured_output_repair-0.3.0b1/src/llm_output_repair/yaml_normalizer.py +899 -0
  22. structured_output_repair-0.3.0b1/src/llm_output_repair/yaml_transport.py +241 -0
  23. structured_output_repair-0.3.0b1/src/structured_output_repair.egg-info/PKG-INFO +180 -0
  24. structured_output_repair-0.3.0b1/src/structured_output_repair.egg-info/SOURCES.txt +37 -0
  25. structured_output_repair-0.3.0b1/src/structured_output_repair.egg-info/dependency_links.txt +1 -0
  26. structured_output_repair-0.3.0b1/src/structured_output_repair.egg-info/entry_points.txt +2 -0
  27. structured_output_repair-0.3.0b1/src/structured_output_repair.egg-info/requires.txt +9 -0
  28. structured_output_repair-0.3.0b1/src/structured_output_repair.egg-info/top_level.txt +1 -0
  29. structured_output_repair-0.3.0b1/tests/test_controlled_json.py +327 -0
  30. structured_output_repair-0.3.0b1/tests/test_crash_logger.py +115 -0
  31. structured_output_repair-0.3.0b1/tests/test_crash_recorder.py +164 -0
  32. structured_output_repair-0.3.0b1/tests/test_facade.py +97 -0
  33. structured_output_repair-0.3.0b1/tests/test_json_safe_v2.py +109 -0
  34. structured_output_repair-0.3.0b1/tests/test_json_utils.py +408 -0
  35. structured_output_repair-0.3.0b1/tests/test_loop_experiment.py +212 -0
  36. structured_output_repair-0.3.0b1/tests/test_public_api.py +15 -0
  37. structured_output_repair-0.3.0b1/tests/test_regression.py +129 -0
  38. structured_output_repair-0.3.0b1/tests/test_yaml_normalizer.py +27 -0
  39. structured_output_repair-0.3.0b1/tests/test_yaml_parser.py +164 -0
@@ -0,0 +1,45 @@
1
+ # Changelog
2
+
3
+ ## 0.3.0b1 (planned)
4
+
5
+ - License the standalone library under MIT and include its provenance notice.
6
+ - Prepare the first PyPI beta as `structured-output-repair`. The import
7
+ `llm_output_repair`, the `llm-repair` CLI and repair policy defaults stay the same.
8
+ - Apply the existing 1,000,000-character JSON input limit to the legacy JSON
9
+ extractor and to public YAML parsing. Stop a repeated TOLERANT JSON candidate
10
+ search when its work budget is exhausted. These cases raise `ValueError`.
11
+ - Verify wheel and source installations independently and add a tag-based
12
+ publication workflow.
13
+
14
+ ## 0.2.2
15
+
16
+ ### Fixed
17
+
18
+ - JSON SAFE can combine lossless comma repairs within one object, including repeated separators, missing separators between complete values or members, and commas next to a member's colon.
19
+ - SAFE continues to reject possible missing array values, ambiguous adjacent strings, duplicate keys, and combinations of the new comma repairs with non-JSON whitespace outside strings.
20
+
21
+ ## 0.2.1
22
+
23
+ ### Fixed
24
+
25
+ - JSON SAFE recovers a complete object under a plain-text heading without a code fence. It also handles unambiguous surrounding prose and labeled JSON fences, including bodies that need an existing SAFE syntax repair.
26
+ - JSON SAFE accounts for surrounding text before repair and continues to reject competing payloads, incomplete structured fragments, duplicate keys and ambiguous values.
27
+ - CrashRecorder reports the installed package version. Wheel metadata and the public Python version share a single source.
28
+
29
+ ## 0.2.0
30
+
31
+ ### Added
32
+
33
+ - SAFE can read a single explicitly labeled JSON fence that encloses one complete object.
34
+ - SAFE can remove redundant commas between complete array elements or object members. It can also remove a single comma between a complete object key and its colon. Each repair must preserve the other tokens and pass strict decoding.
35
+ - The experiment evaluator can require the private v2 corpus by fixture count and fingerprint, then run the shared regression runner.
36
+
37
+ ### Fixed
38
+
39
+ - SAFE rejects adjacent quoted array strings when inserting a comma would choose between plausible values. This is an intentional compatibility change for malformed inputs.
40
+ - SAFE rejects finite-looking numeric literals that overflow to infinity, including during fallback repairs.
41
+ - JSON repair requires no third-party JSON repair package. The existing PyYAML and Pydantic dependencies remain.
42
+
43
+ ## 0.1.0
44
+
45
+ - Initial package version with JSON and YAML repair, optional crash capture, and the local replay and regression CLI.
@@ -0,0 +1,18 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 Alexander Onishchenko
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
6
+ associated documentation files (the "Software"), to deal in the Software without restriction, including
7
+ without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
9
+ following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all copies or substantial
12
+ portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
15
+ LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
16
+ EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
18
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,2 @@
1
+ include CHANGELOG.md
2
+ include examples/quickstart.py
@@ -0,0 +1,10 @@
1
+ Structured Output Repair (Python import: llm_output_repair)
2
+
3
+ The standalone repository is https://github.com/AlexanderOnischenko/llm-output-repair.
4
+
5
+ The JSON and YAML extractors and YAML normalization and transport helpers
6
+ trace back to the Backplane utilities and the standalone extraction commit
7
+ b5d6818cfa7218926fca2ff1a5e47e945eccb5fd in this repository. Subsequent
8
+ changes are recorded in the standalone repository's Git history.
9
+
10
+ This standalone library is distributed under the MIT License. See LICENSE.
@@ -0,0 +1,180 @@
1
+ Metadata-Version: 2.4
2
+ Name: structured-output-repair
3
+ Version: 0.3.0b1
4
+ Summary: Deterministic extraction and heuristic repair of structured LLM output
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/AlexanderOnischenko/llm-output-repair
7
+ Project-URL: Issues, https://github.com/AlexanderOnischenko/llm-output-repair/issues
8
+ Project-URL: Changelog, https://github.com/AlexanderOnischenko/llm-output-repair/blob/main/CHANGELOG.md
9
+ Keywords: llm,json,yaml,repair,parser
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Text Processing
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ License-File: NOTICE
21
+ Requires-Dist: PyYAML<7,>=6
22
+ Requires-Dist: pydantic<3,>=1
23
+ Provides-Extra: pydantic
24
+ Requires-Dist: pydantic<3,>=1; extra == "pydantic"
25
+ Provides-Extra: test
26
+ Requires-Dist: pytest<9,>=8; extra == "test"
27
+ Requires-Dist: pydantic<3,>=1; extra == "test"
28
+ Dynamic: license-file
29
+
30
+ # Structured Output Repair
31
+
32
+ Structured Output Repair extracts and repairs JSON and YAML generated by
33
+ language models. It runs locally on text you already have, using Python and deterministic
34
+ parsing and repair rules. Use it between a model response and your
35
+ application's own schema or domain validation.
36
+
37
+ ## Install
38
+
39
+ The first PyPI beta is planned as `structured-output-repair==0.3.0b1`. Once it is
40
+ published, install it in a fresh Python 3.11–3.13 environment:
41
+
42
+ ```sh
43
+ python -m venv .venv
44
+ .venv/bin/python -m pip install structured-output-repair==0.3.0b1
45
+ ```
46
+
47
+ On Windows, use `.venv\Scripts\python.exe`. To try a local beta build before
48
+ publication, install its `structured_output_repair-0.3.0b1-py3-none-any.whl` by path instead.
49
+
50
+ The distribution is named **`structured-output-repair`**. The Python import remains
51
+ **`llm_output_repair`** and the diagnostic command remains **`llm-repair`**.
52
+ The [PyPI project named `llm-output-repair`](https://pypi.org/project/llm-output-repair/)
53
+ belongs to a different project. Its 0.2.0 source distribution uses
54
+ `llm_json_repair` and declares no console commands.
55
+ Use a clean environment for Structured Output Repair, especially if you
56
+ previously installed a Git-based distribution of this repository under the old name. The old Git
57
+ distribution shares the namespace and CLI.
58
+
59
+ ## Quick start
60
+
61
+ ```python
62
+ from llm_output_repair import repair
63
+
64
+ result = repair('Result:\n{"items": [1,,2,], "ok": true}')
65
+ assert result == {"items": [1, 2], "ok": True}
66
+ ```
67
+
68
+ `repair()` returns the decoded Python value. It defaults to SAFE for JSON
69
+ and TOLERANT for YAML. The named helpers `repair_json()` and
70
+ `repair_yaml()` retain their historical TOLERANT defaults.
71
+
72
+ ## Choose a policy
73
+
74
+ | Policy | JSON | YAML |
75
+ | --- | --- | --- |
76
+ | `strict` | Decode without repair, with duplicate-key and nonstandard constant rejection. Supports objects, arrays and scalars through the value-returning helpers. | One document through PyYAML's `safe_load`, with native YAML value types. |
77
+ | `safe` | Object root only. Recover one object from supported presentation and apply supported local syntax repairs with data-preservation checks. Reject missing or competing structured content, duplicate keys, ambiguous repairs and floats that decode to infinity. | Unavailable. |
78
+ | `tolerant` | Legacy heuristic extraction and repair. Can select a fragment, remove placeholders or reinterpret encoded strings. Supports objects, arrays and scalar values when the extractor can decode them. | Legacy normalization of YAML-like text followed by safe loading. The heuristics can change formatting, structure and scalar interpretation. |
79
+
80
+ SAFE can handle supported headings, fences and prose around one object. It
81
+ also handles supported combinations of missing and redundant separators where
82
+ keys and values are already present. It may reject malformed text that an
83
+ application could interpret using more context. Even two identical JSON
84
+ documents in one response are rejected. Schema-aware repair remains planned.
85
+ The [SAFE v2 design contract](https://github.com/AlexanderOnischenko/llm-output-repair/blob/main/docs/json-safe-v2.md)
86
+ includes future behavior beyond this beta.
87
+
88
+ Use `parse_json(raw, policy="safe")` for a `JsonResult` with `value`,
89
+ `repaired` and `strategy`. Its default expected root is `dict`. For
90
+ STRICT or TOLERANT, pass `expected_type=object` to allow any supported JSON
91
+ root. Previously exported legacy extractors remain available.
92
+ `extract_json_new()` returns JSON **text**, and `extract_yaml_new()`
93
+ returns a Python value. `dump_yaml()` returns YAML text. YAML can return
94
+ `None` for an empty document. STRICT JSON uses the Python decoder’s float
95
+ semantics, including overflow in exponent notation. SAFE rejects that overflow.
96
+ In TOLERANT mode, `parse_json()` tries the checked decoder before its repair
97
+ fallback. The historical `repair_json()` default calls the extractor directly.
98
+
99
+ ## Handle failures and validate the result
100
+
101
+ ```python
102
+ from llm_output_repair import repair
103
+
104
+ def read_items(raw: str) -> list[int]:
105
+ result = repair(raw)
106
+ items = result.get("items")
107
+ if not isinstance(items, list) or any(type(item) is not int for item in items):
108
+ raise ValueError("Expected an array of integers")
109
+ return items
110
+
111
+ try:
112
+ items = read_items('{"items":[1,2,],}')
113
+ except ValueError:
114
+ # Report a parsing or validation failure through your application.
115
+ items = None
116
+ ```
117
+
118
+ JSON parsing and policy refusals raise `ValueError` (including
119
+ `json.JSONDecodeError`). Non-string arguments to `repair()` raise
120
+ `TypeError`. YAML loading can raise `yaml.YAMLError`; tolerant YAML
121
+ normalization can also raise `ValueError`. Deep inputs may hit Python's
122
+ recursion limit. Validate field types, required fields and domain invariants
123
+ after parsing. Errors can include input text, so handle their details as application data.
124
+
125
+ ## Opt-in diagnostics and replay
126
+
127
+ Importing the package and parsing normally create no diagnostic files or
128
+ directories. The library performs no network calls, inference or background
129
+ work. To capture a terminal failure explicitly, attach a `CrashRecorder`
130
+ and choose a private directory:
131
+
132
+ ```python
133
+ from llm_output_repair import CrashRecorder, repair
134
+
135
+ recorder = CrashRecorder("./private-dumps")
136
+ try:
137
+ repair('{"items":', recorder=recorder)
138
+ except ValueError:
139
+ pass
140
+ ```
141
+
142
+ ```sh
143
+ .venv/bin/llm-repair replay ./private-dumps/CASE_ID.json
144
+ .venv/bin/llm-repair verify --corpus ./private-regressions --bucket fixed
145
+ ```
146
+
147
+ Replay uses the saved operation and options locally. An expected terminal
148
+ failure returns exit code 1 when replaying a raw dump. For a reviewed
149
+ regression fixture, exit code 0 means the expectation matched. Use
150
+ `llm-repair promote --help` to turn a dump into a fixture with an explicit
151
+ expected value or error. Dumps can contain the original response. Keep them
152
+ private. `CrashLogger` remains available for legacy diagnostic logs.
153
+
154
+ ## Beta support and limits
155
+
156
+ Supported and tested Python versions are 3.11, 3.12 and 3.13. The runtime
157
+ requires PyYAML and Pydantic. The library has no Fetchgraph dependency.
158
+ When migrating from a Git pin, install the new distribution in a fresh
159
+ environment. A dependency declaration for the old distribution name must be
160
+ updated separately.
161
+
162
+ The JSON and YAML repair and extraction entry points check a limit of
163
+ 1,000,000 Python string characters before parsing. The malformed-object
164
+ scan in JSON SAFE caps nesting at 128 levels. An object that decodes
165
+ strictly can take a different path. The repeated candidate search in
166
+ TOLERANT JSON caps the sum of inspected suffix lengths at 8,000,000
167
+ characters per search. These checks
168
+ do not bound total CPU, memory, output size or depth across all decoder
169
+ paths. For untrusted input, limit payloads, resulting sizes and alias
170
+ expansion in the calling application. Use process-level limits when you need
171
+ an enforceable execution budget.
172
+
173
+ See the [changelog](https://github.com/AlexanderOnischenko/llm-output-repair/blob/main/CHANGELOG.md)
174
+ for compatibility changes and the [repository](https://github.com/AlexanderOnischenko/llm-output-repair)
175
+ for implementation, provenance and issue tracking.
176
+
177
+ ## License
178
+
179
+ This standalone library is licensed under [MIT](LICENSE). The [NOTICE](NOTICE)
180
+ records the provenance of the code extracted from Backplane.
@@ -0,0 +1,151 @@
1
+ # Structured Output Repair
2
+
3
+ Structured Output Repair extracts and repairs JSON and YAML generated by
4
+ language models. It runs locally on text you already have, using Python and deterministic
5
+ parsing and repair rules. Use it between a model response and your
6
+ application's own schema or domain validation.
7
+
8
+ ## Install
9
+
10
+ The first PyPI beta is planned as `structured-output-repair==0.3.0b1`. Once it is
11
+ published, install it in a fresh Python 3.11–3.13 environment:
12
+
13
+ ```sh
14
+ python -m venv .venv
15
+ .venv/bin/python -m pip install structured-output-repair==0.3.0b1
16
+ ```
17
+
18
+ On Windows, use `.venv\Scripts\python.exe`. To try a local beta build before
19
+ publication, install its `structured_output_repair-0.3.0b1-py3-none-any.whl` by path instead.
20
+
21
+ The distribution is named **`structured-output-repair`**. The Python import remains
22
+ **`llm_output_repair`** and the diagnostic command remains **`llm-repair`**.
23
+ The [PyPI project named `llm-output-repair`](https://pypi.org/project/llm-output-repair/)
24
+ belongs to a different project. Its 0.2.0 source distribution uses
25
+ `llm_json_repair` and declares no console commands.
26
+ Use a clean environment for Structured Output Repair, especially if you
27
+ previously installed a Git-based distribution of this repository under the old name. The old Git
28
+ distribution shares the namespace and CLI.
29
+
30
+ ## Quick start
31
+
32
+ ```python
33
+ from llm_output_repair import repair
34
+
35
+ result = repair('Result:\n{"items": [1,,2,], "ok": true}')
36
+ assert result == {"items": [1, 2], "ok": True}
37
+ ```
38
+
39
+ `repair()` returns the decoded Python value. It defaults to SAFE for JSON
40
+ and TOLERANT for YAML. The named helpers `repair_json()` and
41
+ `repair_yaml()` retain their historical TOLERANT defaults.
42
+
43
+ ## Choose a policy
44
+
45
+ | Policy | JSON | YAML |
46
+ | --- | --- | --- |
47
+ | `strict` | Decode without repair, with duplicate-key and nonstandard constant rejection. Supports objects, arrays and scalars through the value-returning helpers. | One document through PyYAML's `safe_load`, with native YAML value types. |
48
+ | `safe` | Object root only. Recover one object from supported presentation and apply supported local syntax repairs with data-preservation checks. Reject missing or competing structured content, duplicate keys, ambiguous repairs and floats that decode to infinity. | Unavailable. |
49
+ | `tolerant` | Legacy heuristic extraction and repair. Can select a fragment, remove placeholders or reinterpret encoded strings. Supports objects, arrays and scalar values when the extractor can decode them. | Legacy normalization of YAML-like text followed by safe loading. The heuristics can change formatting, structure and scalar interpretation. |
50
+
51
+ SAFE can handle supported headings, fences and prose around one object. It
52
+ also handles supported combinations of missing and redundant separators where
53
+ keys and values are already present. It may reject malformed text that an
54
+ application could interpret using more context. Even two identical JSON
55
+ documents in one response are rejected. Schema-aware repair remains planned.
56
+ The [SAFE v2 design contract](https://github.com/AlexanderOnischenko/llm-output-repair/blob/main/docs/json-safe-v2.md)
57
+ includes future behavior beyond this beta.
58
+
59
+ Use `parse_json(raw, policy="safe")` for a `JsonResult` with `value`,
60
+ `repaired` and `strategy`. Its default expected root is `dict`. For
61
+ STRICT or TOLERANT, pass `expected_type=object` to allow any supported JSON
62
+ root. Previously exported legacy extractors remain available.
63
+ `extract_json_new()` returns JSON **text**, and `extract_yaml_new()`
64
+ returns a Python value. `dump_yaml()` returns YAML text. YAML can return
65
+ `None` for an empty document. STRICT JSON uses the Python decoder’s float
66
+ semantics, including overflow in exponent notation. SAFE rejects that overflow.
67
+ In TOLERANT mode, `parse_json()` tries the checked decoder before its repair
68
+ fallback. The historical `repair_json()` default calls the extractor directly.
69
+
70
+ ## Handle failures and validate the result
71
+
72
+ ```python
73
+ from llm_output_repair import repair
74
+
75
+ def read_items(raw: str) -> list[int]:
76
+ result = repair(raw)
77
+ items = result.get("items")
78
+ if not isinstance(items, list) or any(type(item) is not int for item in items):
79
+ raise ValueError("Expected an array of integers")
80
+ return items
81
+
82
+ try:
83
+ items = read_items('{"items":[1,2,],}')
84
+ except ValueError:
85
+ # Report a parsing or validation failure through your application.
86
+ items = None
87
+ ```
88
+
89
+ JSON parsing and policy refusals raise `ValueError` (including
90
+ `json.JSONDecodeError`). Non-string arguments to `repair()` raise
91
+ `TypeError`. YAML loading can raise `yaml.YAMLError`; tolerant YAML
92
+ normalization can also raise `ValueError`. Deep inputs may hit Python's
93
+ recursion limit. Validate field types, required fields and domain invariants
94
+ after parsing. Errors can include input text, so handle their details as application data.
95
+
96
+ ## Opt-in diagnostics and replay
97
+
98
+ Importing the package and parsing normally create no diagnostic files or
99
+ directories. The library performs no network calls, inference or background
100
+ work. To capture a terminal failure explicitly, attach a `CrashRecorder`
101
+ and choose a private directory:
102
+
103
+ ```python
104
+ from llm_output_repair import CrashRecorder, repair
105
+
106
+ recorder = CrashRecorder("./private-dumps")
107
+ try:
108
+ repair('{"items":', recorder=recorder)
109
+ except ValueError:
110
+ pass
111
+ ```
112
+
113
+ ```sh
114
+ .venv/bin/llm-repair replay ./private-dumps/CASE_ID.json
115
+ .venv/bin/llm-repair verify --corpus ./private-regressions --bucket fixed
116
+ ```
117
+
118
+ Replay uses the saved operation and options locally. An expected terminal
119
+ failure returns exit code 1 when replaying a raw dump. For a reviewed
120
+ regression fixture, exit code 0 means the expectation matched. Use
121
+ `llm-repair promote --help` to turn a dump into a fixture with an explicit
122
+ expected value or error. Dumps can contain the original response. Keep them
123
+ private. `CrashLogger` remains available for legacy diagnostic logs.
124
+
125
+ ## Beta support and limits
126
+
127
+ Supported and tested Python versions are 3.11, 3.12 and 3.13. The runtime
128
+ requires PyYAML and Pydantic. The library has no Fetchgraph dependency.
129
+ When migrating from a Git pin, install the new distribution in a fresh
130
+ environment. A dependency declaration for the old distribution name must be
131
+ updated separately.
132
+
133
+ The JSON and YAML repair and extraction entry points check a limit of
134
+ 1,000,000 Python string characters before parsing. The malformed-object
135
+ scan in JSON SAFE caps nesting at 128 levels. An object that decodes
136
+ strictly can take a different path. The repeated candidate search in
137
+ TOLERANT JSON caps the sum of inspected suffix lengths at 8,000,000
138
+ characters per search. These checks
139
+ do not bound total CPU, memory, output size or depth across all decoder
140
+ paths. For untrusted input, limit payloads, resulting sizes and alias
141
+ expansion in the calling application. Use process-level limits when you need
142
+ an enforceable execution budget.
143
+
144
+ See the [changelog](https://github.com/AlexanderOnischenko/llm-output-repair/blob/main/CHANGELOG.md)
145
+ for compatibility changes and the [repository](https://github.com/AlexanderOnischenko/llm-output-repair)
146
+ for implementation, provenance and issue tracking.
147
+
148
+ ## License
149
+
150
+ This standalone library is licensed under [MIT](LICENSE). The [NOTICE](NOTICE)
151
+ records the provenance of the code extracted from Backplane.
@@ -0,0 +1,14 @@
1
+ """Run in an environment where the Structured Output Repair distribution is installed."""
2
+
3
+ from llm_output_repair import parse_json, repair, repair_json
4
+
5
+ result = repair('Result:\n{"items": [1,,2,], "ok": true}')
6
+ assert result == {"items": [1, 2], "ok": True}
7
+
8
+ assert repair('[1, 2]', policy="strict") == [1, 2]
9
+ assert repair("status: ok\n", format="yaml") == {"status": "ok"}
10
+ assert repair_json('The result: {"status":"ok"}') == {"status": "ok"}
11
+
12
+ details = parse_json('{"user":"Ada",}')
13
+ assert details.value == {"user": "Ada"} and details.repaired
14
+ print(result)
@@ -0,0 +1,44 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "structured-output-repair"
7
+ dynamic = ["version"]
8
+ description = "Deterministic extraction and heuristic repair of structured LLM output"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE", "NOTICE"]
12
+ requires-python = ">=3.11"
13
+ keywords = ["llm", "json", "yaml", "repair", "parser"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Topic :: Text Processing",
22
+ ]
23
+ dependencies = ["PyYAML>=6,<7", "pydantic>=1,<3"]
24
+
25
+ [project.optional-dependencies]
26
+ pydantic = ["pydantic>=1,<3"]
27
+ test = ["pytest>=8,<9", "pydantic>=1,<3"]
28
+
29
+ [project.urls]
30
+ Repository = "https://github.com/AlexanderOnischenko/llm-output-repair"
31
+ Issues = "https://github.com/AlexanderOnischenko/llm-output-repair/issues"
32
+ Changelog = "https://github.com/AlexanderOnischenko/llm-output-repair/blob/main/CHANGELOG.md"
33
+
34
+ [project.scripts]
35
+ llm-repair = "llm_output_repair.cli:main"
36
+
37
+ [tool.setuptools.dynamic]
38
+ version = {attr = "llm_output_repair._version.__version__"}
39
+
40
+ [tool.setuptools.packages.find]
41
+ where = ["src"]
42
+
43
+ [tool.pytest.ini_options]
44
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,25 @@
1
+ """Deterministic extraction and heuristic repair of LLM-generated JSON/YAML."""
2
+ from __future__ import annotations
3
+
4
+ from ._version import __version__
5
+ from .api import repair, repair_json, repair_yaml
6
+ from .controlled_json import JsonResult, parse_json
7
+ from .crash_logger import CrashLogger
8
+ from .crash_recorder import CrashRecorder
9
+ from .extract_json import extract_json_new
10
+ from .extract_yaml import dump_yaml, extract_yaml_new
11
+ from .yaml_normalizer import YamlNormalizer
12
+
13
+ __all__ = [
14
+ "repair",
15
+ "repair_json",
16
+ "repair_yaml",
17
+ "parse_json",
18
+ "JsonResult",
19
+ "CrashLogger",
20
+ "CrashRecorder",
21
+ "extract_json_new",
22
+ "extract_yaml_new",
23
+ "dump_yaml",
24
+ "YamlNormalizer",
25
+ ]
@@ -0,0 +1,8 @@
1
+ """Input length limit for the public parsing entry points."""
2
+
3
+ MAX_INPUT_CHARS = 1_000_000
4
+
5
+
6
+ def check_input_size(raw: str, format_name: str) -> None:
7
+ if len(raw) > MAX_INPUT_CHARS:
8
+ raise ValueError(f"{format_name} input exceeds {MAX_INPUT_CHARS:,} characters")
@@ -0,0 +1,3 @@
1
+ """Version shared by the package and its distribution metadata."""
2
+
3
+ __version__ = "0.3.0b1"
@@ -0,0 +1,96 @@
1
+ """Application-facing entry points for structured LLM output."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from typing import Any, Literal
6
+
7
+ import yaml
8
+
9
+ from ._limits import check_input_size
10
+ from .crash_logger import CrashLogger, capture_failure
11
+ from .crash_recorder import CrashRecorder, _capture_failure
12
+ from .controlled_json import parse_json
13
+
14
+ Format = Literal["json", "yaml"]
15
+ Policy = Literal["strict", "safe", "tolerant"]
16
+
17
+
18
+ def _require_text(raw: str) -> None:
19
+ if not isinstance(raw, str):
20
+ raise TypeError("LLM output must be a string")
21
+
22
+
23
+ def repair_json(
24
+ raw: str,
25
+ *,
26
+ policy: Policy = "tolerant",
27
+ crash_logger: CrashLogger | None = None,
28
+ recorder: CrashRecorder | None = None,
29
+ ) -> Any:
30
+ """Decode JSON-like output with the historical tolerant default."""
31
+ from . import extract_json_new
32
+
33
+ if policy not in ("strict", "safe", "tolerant"):
34
+ raise ValueError("Unknown JSON repair policy")
35
+ if policy != "tolerant":
36
+ _require_text(raw)
37
+ return parse_json(
38
+ raw, policy=policy, expected_type=dict if policy == "safe" else object,
39
+ crash_logger=crash_logger, recorder=recorder,
40
+ ).value
41
+ try:
42
+ return json.loads(extract_json_new(raw))
43
+ except Exception as error:
44
+ _capture_failure(recorder, operation="repair_json", raw=raw, error=error)
45
+ capture_failure(crash_logger, raw, format="json", policy=policy, error=error)
46
+ raise
47
+
48
+
49
+ def repair_yaml(
50
+ raw: str,
51
+ *,
52
+ policy: Literal["strict", "tolerant"] = "tolerant",
53
+ crash_logger: CrashLogger | None = None,
54
+ recorder: CrashRecorder | None = None,
55
+ ) -> Any:
56
+ """Decode YAML-like output with the historical tolerant default."""
57
+ from . import extract_yaml_new
58
+
59
+ if policy not in ("strict", "tolerant"):
60
+ raise ValueError("YAML supports only 'strict' or 'tolerant' policies")
61
+ try:
62
+ if policy == "strict":
63
+ _require_text(raw)
64
+ check_input_size(raw, "YAML")
65
+ return yaml.safe_load(raw)
66
+ return extract_yaml_new(raw)
67
+ except Exception as error:
68
+ _capture_failure(
69
+ recorder, operation="repair_yaml", raw=raw, error=error,
70
+ options={"policy": "strict"} if policy == "strict" else None,
71
+ )
72
+ capture_failure(crash_logger, raw, format="yaml", policy=policy, error=error)
73
+ raise
74
+
75
+
76
+ def repair(
77
+ raw: str,
78
+ *,
79
+ format: Format = "json",
80
+ policy: Policy | None = None,
81
+ crash_logger: CrashLogger | None = None,
82
+ recorder: CrashRecorder | None = None,
83
+ ) -> Any:
84
+ """Repair structured output, using SAFE for JSON and TOLERANT for YAML."""
85
+ _require_text(raw)
86
+ if format == "json":
87
+ return repair_json(
88
+ raw, policy="safe" if policy is None else policy,
89
+ crash_logger=crash_logger, recorder=recorder,
90
+ )
91
+ if format == "yaml":
92
+ return repair_yaml(
93
+ raw, policy="tolerant" if policy is None else policy,
94
+ crash_logger=crash_logger, recorder=recorder,
95
+ )
96
+ raise ValueError("Unsupported format; expected 'json' or 'yaml'")