Metadata-Version: 2.4
Name: structured-output-repair
Version: 0.4.0
Summary: Deterministic extraction and heuristic repair of structured LLM output
License-Expression: MIT
Project-URL: Repository, https://github.com/AlexanderOnischenko/llm-output-repair
Project-URL: Issues, https://github.com/AlexanderOnischenko/llm-output-repair/issues
Project-URL: Changelog, https://github.com/AlexanderOnischenko/llm-output-repair/blob/main/CHANGELOG.md
Keywords: llm,json,yaml,repair,parser
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Text Processing
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: PyYAML<7,>=6
Requires-Dist: pydantic<3,>=1
Provides-Extra: pydantic
Requires-Dist: pydantic<3,>=1; extra == "pydantic"
Provides-Extra: test
Requires-Dist: pytest<9,>=8; extra == "test"
Requires-Dist: pydantic<3,>=1; extra == "test"
Dynamic: license-file

# Structured Output Repair

Structured Output Repair extracts and repairs JSON and YAML generated by
language models. It runs locally on text you already have, using Python and deterministic
parsing and repair rules. Use it between a model response and your
application's own schema or domain validation.

## Install

Install the package in a fresh Python 3.11–3.13 environment:

```sh
python -m venv .venv
.venv/bin/python -m pip install structured-output-repair==0.4.0
```

On Windows, use `.venv\Scripts\python.exe`. For a local build, install the wheel by its file path.

The distribution is named **`structured-output-repair`**. The Python import remains
**`llm_output_repair`** and the diagnostic command remains **`llm-repair`**.
The [PyPI project named `llm-output-repair`](https://pypi.org/project/llm-output-repair/)
belongs to a different project. Its 0.2.0 source distribution uses
`llm_json_repair` and declares no console commands.
Use a clean environment for Structured Output Repair, especially if you
previously installed a Git-based distribution of this repository under the old name. The old Git
distribution shares the namespace and CLI.

## Quick start

```python
from llm_output_repair import repair

result = repair('Result:\n{"items": [1,,2,], "ok": true}')
assert result == {"items": [1, 2], "ok": True}
```

`repair()` returns the decoded Python value. It defaults to SAFE for JSON
and TOLERANT for YAML. The named helpers `repair_json()` and
`repair_yaml()` retain their historical TOLERANT defaults for plain calls.
With a schema hint, `repair_json(raw, schema=hint)` defaults to SAFE.

## Choose a policy

| Policy | JSON | YAML |
| --- | --- | --- |
| `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. |
| `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. |
| `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. |

SAFE can handle supported headings, fences and prose around one object. It
also handles supported combinations of missing and redundant separators where
keys and values are already present. It may reject malformed text that an
application could interpret using more context. In the development version, a strict object may be repeated verbatim after a
prose heading in a labeled JSON code fence. Bare repetitions and differences
inside the fenced copy cause a refusal. JSON SAFE accepts
an optional JSON Schema hint, for example
`repair(raw, schema=Plan.model_json_schema())`. Valid objects and unique syntax
repairs retain every field, including undeclared properties. For adjacent
strings in an array, inline array-length hints can disambiguate two readings.
Validate the returned value in your application. CrashRecorder stores the hint
with the original input for replay.
The [SAFE v2 design contract](https://github.com/AlexanderOnischenko/llm-output-repair/blob/main/docs/json-safe-v2.md)
includes future behavior beyond this release.

Use `parse_json(raw, policy="safe")` for a `JsonResult` with `value`,
`repaired` and `strategy`. Its default expected root is `dict`. For
STRICT or TOLERANT, pass `expected_type=object` to allow any supported JSON
root. Previously exported legacy extractors remain available.
`extract_json_new()` returns JSON **text**, and `extract_yaml_new()`
returns a Python value. `dump_yaml()` returns YAML text. YAML can return
`None` for an empty document. STRICT JSON uses the Python decoder’s float
semantics, including overflow in exponent notation. SAFE rejects that overflow.
In TOLERANT mode, `parse_json()` tries the checked decoder before its repair
fallback. The historical `repair_json()` default calls the extractor directly.

## Handle failures and validate the result

```python
from llm_output_repair import repair

def read_items(raw: str) -> list[int]:
    result = repair(raw)
    items = result.get("items")
    if not isinstance(items, list) or any(type(item) is not int for item in items):
        raise ValueError("Expected an array of integers")
    return items

try:
    items = read_items('{"items":[1,2,],}')
except ValueError:
    # Report a parsing or validation failure through your application.
    items = None
```

JSON parsing and policy refusals raise `ValueError` (including
`json.JSONDecodeError`). Non-string arguments to `repair()` raise
`TypeError`. YAML loading can raise `yaml.YAMLError`; tolerant YAML
normalization can also raise `ValueError`. Deep inputs may hit Python's
recursion limit. Validate field types, required fields and domain invariants
after parsing. Errors can include input text, so handle their details as application data.

## Opt-in diagnostics and replay

Importing the package and parsing normally create no diagnostic files or
directories. The library performs no network calls, inference or background
work. To capture a terminal failure explicitly, attach a `CrashRecorder`
and choose a private directory:

```python
from llm_output_repair import CrashRecorder, repair

recorder = CrashRecorder("./private-dumps")
try:
    repair('{"items":', recorder=recorder)
except ValueError:
    pass
```

```sh
.venv/bin/llm-repair replay ./private-dumps/CASE_ID.json
.venv/bin/llm-repair verify --corpus ./private-regressions --bucket fixed
```

Replay uses the saved operation and options locally. An expected terminal
failure returns exit code 1 when replaying a raw dump. For a reviewed
regression fixture, exit code 0 means the expectation matched. Use
`llm-repair promote --help` to turn a dump into a fixture with an explicit
expected value or error. Dumps can contain the original response. Keep them
private. `CrashLogger` remains available for legacy diagnostic logs.

## Beta support and limits

Supported and tested Python versions are 3.11, 3.12 and 3.13. The runtime
requires PyYAML and Pydantic. The library has no Fetchgraph dependency.
When migrating from a Git pin, install the new distribution in a fresh
environment. A dependency declaration for the old distribution name must be
updated separately.

The JSON and YAML repair and extraction entry points check a limit of
1,000,000 Python string characters before parsing. The malformed-object
scan in JSON SAFE caps nesting at 128 levels. An object that decodes
strictly can take a different path. The repeated candidate search in
TOLERANT JSON caps the sum of inspected suffix lengths at 8,000,000
characters per search. These checks
do not bound total CPU, memory, output size or depth across all decoder
paths. For untrusted input, limit payloads, resulting sizes and alias
expansion in the calling application. Use process-level limits when you need
an enforceable execution budget.

See the [changelog](https://github.com/AlexanderOnischenko/llm-output-repair/blob/main/CHANGELOG.md)
for compatibility changes and the [repository](https://github.com/AlexanderOnischenko/llm-output-repair)
for implementation, provenance and issue tracking.

## License

This standalone library is licensed under [MIT](LICENSE). The [NOTICE](NOTICE)
records the provenance of the code extracted from Backplane.
