Metadata-Version: 2.5
Name: checkjson-repair
Version: 0.1.0a2
Summary: Repairs broken LLM tool calls before they reach your tools.
Project-URL: Homepage, https://himanshu5trpth.github.io/checkjson-interactive/
Project-URL: Live demo, https://huggingface.co/spaces/himanshu5trpth/checkjson
Project-URL: Website source, https://github.com/himanshu5trpth/checkjson-interactive
Author: Himanshu Tripathi
License: MIT
License-File: LICENSE
Keywords: json,json-schema,llm,repair,tool-calling
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.10
Requires-Dist: jsonschema>=4.20
Requires-Dist: textual>=8; sys_platform != 'emscripten'
Provides-Extra: all
Requires-Dist: gradio>=5; extra == 'all'
Requires-Dist: lm-format-enforcer>=0.11.3; extra == 'all'
Requires-Dist: torch>=2.1; extra == 'all'
Requires-Dist: transformers<5,>=4.57.6; extra == 'all'
Provides-Extra: demo
Requires-Dist: gradio>=5; extra == 'demo'
Provides-Extra: dev
Requires-Dist: build; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: twine; extra == 'dev'
Provides-Extra: model
Requires-Dist: lm-format-enforcer>=0.11.3; extra == 'model'
Requires-Dist: torch>=2.1; extra == 'model'
Requires-Dist: transformers<5,>=4.57.6; extra == 'model'
Description-Content-Type: text/markdown

<p align="center">
  <img src="https://raw.githubusercontent.com/himanshu5trpth/checkjson-interactive/a023351/img/canva-wordmark.png" width="460" alt="CheckJSON">
</p>

<p align="center"><strong>Validate and repair LLM tool calls before execution.</strong></p>

<p align="center">
  <img src="https://img.shields.io/badge/python-3.10%2B-17243b" alt="Python 3.10 or newer">
  <img src="https://img.shields.io/badge/license-MIT-008073" alt="MIT license">
  <img src="https://img.shields.io/badge/status-alpha-b7791f" alt="Alpha release">
</p>

<p align="center">
  <a href="https://himanshu5trpth.github.io/checkjson-interactive/"><strong>Interactive website</strong></a> ·
  <a href="https://huggingface.co/spaces/himanshu5trpth/checkjson"><strong>Try it on Hugging Face</strong></a>
</p>

<p align="center">
  <a href="#install">Install</a> ·
  <a href="#quickstart">Quickstart</a> ·
  <a href="#how-it-works">How it works</a> ·
  <a href="#python-api">Python API</a> ·
  <a href="#command-line">Command line</a> ·
  <a href="#known-limits">Known limits</a> ·
  <a href="#research-results">Results</a>
</p>

CheckJSON takes a generated tool call and the tool's JSON Schema. It can fix malformed JSON, normalize supported argument types, and return a trace of what changed. Rules run first. An optional model can propose values for fields the rules leave unresolved.

For example, if a tool expects an array, CheckJSON can repair `"rooms": "Entry"` to `"rooms": ["Entry"]` while preserving the other arguments.

## Install

Requires **Python 3.10 or newer**. For an alpha release, use the prerelease install command.

```bash
python -m pip install checkjson-repair
# To opt in to prereleases
python -m pip install --pre checkjson-repair
```

| Install | Includes |
| --- | --- |
| `checkjson-repair` | Rule-based repair, Python API, CLI, and terminal interface |
| `checkjson-repair[model]` | Dependencies for a local Transformers corrector |
| `checkjson-repair[demo]` | Gradio interface for the local browser demo |

## Quickstart

Run the built-in example with no API key or model download.

```bash
checkjson example
checkjson tui
```

The package installs as `checkjson-repair`. You import it as `checkjson`. The commands `checkjson`, `ckjn`, `checkjson-repair` and `checkjson-llm` do the same thing, for example `ckjn tui` or `ckjn --help`.

In the terminal interface, select an example on **Repair**, then press **Ctrl+R**. The result shows the repaired payload and a step-by-step trace. Inputs and results sit side by side on wide terminals and stack on narrow ones.

| Page | Shortcut | What you can do |
| --- | --- | --- |
| Repair | F1 | Paste a candidate call and tool schema, or load a built-in example |
| Ask a model | F2 | Send a request to a configured model and inspect the original reply and repair |
| Dashboard | F3 | Review outcome counts and inspect recent runs by project |
| Setup | F4 | Choose a project, provider, generator, corrector, and history settings |

The terminal uses navy panels, teal for schema-valid results, amber for pending work, and red for errors or calls that need review. Status labels give the same information in monochrome terminals. While a run is pending, the checkmark and semicolon bounce and turn into dots on impact.

## How it works

A model often writes a tool call that is almost right. CheckJSON sits between that model and your tool. It keeps every value it can trust and repairs only what breaks the tool's JSON Schema.

<p align="center">
  <img src="https://raw.githubusercontent.com/himanshu5trpth/checkjson-interactive/a023351/img/figure2-overview.png" width="100%" alt="The CheckJSON pipeline: detection, lexical repair, semantic repair, a small language model for holes, and the output">
</p>

| Stage | What happens | Uses a model |
| --- | --- | --- |
| Detection | A strict JSON parser and the tool schema find the problems. A valid call is returned unchanged. | No |
| Lexical repair | Small edits fix punctuation, quotes, brackets, literals and cut-off text. | No |
| Semantic repair | Tool names, argument names and types are fixed when the schema proves the change. Two values are swapped only when their formats prove it. | No |
| Corrector | A small model writes only the missing parts. Trusted values stay fixed. | Yes |
| Output | A valid call, an unresolved result, or no call. | |

## Use it with your own model

Pass your model's reply to `repair_chat`. It accepts OpenAI-style and Ollama-style messages, tools and replies. It returns the calls you can run, or `[]`.

```python
from checkjson import CheckJSON, OllamaBackend, repair_chat

checker = CheckJSON(engine=OllamaBackend("qwen3:4b-instruct"))   # or RulesOnly() for no model

calls = repair_chat(messages, tools, reply, checker=checker)     # reply is your model's message
for call in calls:
    print(call["name"], call["arguments"])
```

`[]` means that no call is needed, or that CheckJSON could not make a valid one. Use `checker.repair(task)` when you need to know which.

### Choose a corrector

| Corrector | How to use it | Needs |
| --- | --- | --- |
| None | `RulesOnly()` | Nothing |
| Ollama | `CheckJSON(engine=OllamaBackend("qwen3:4b-instruct"))` | A running Ollama with that model |
| Local Transformers | `CheckJSON()` | `pip install "checkjson-repair[model]"`. The first use downloads Qwen3-4B-Instruct-2507. A GPU is recommended. |
| Your own | `CheckJSON(engine=my_object)` | A `chat(messages, schema=None, tools=None, budget=400)` method that returns `(message, usage)` |

## Python API

This example uses deterministic rules to repair an argument in a read-only query.

```python
import json

from checkjson import RulesOnly

tools = [
    {
        "name": "get_room_status",
        "description": "Read the status of one or more rooms.",
        "parameters": {
            "type": "object",
            "properties": {
                "rooms": {"type": "array", "items": {"type": "string"}},
            },
            "required": ["rooms"],
        },
    }
]
candidate = {"turns": [{"calls": [
    {"name": "get_room_status", "arguments": {"rooms": "Entry"}}
]}]}

result = RulesOnly().repair(
    {
        "context": [],
        "request": "What is the status of the entry room?",
        "tools": tools,
        "candidate_json": json.dumps(candidate),
    },
    trace=True,
)

if result["status"] == "ok":
    print(result["payload"]["turns"][0]["calls"][0]["arguments"])
    # {'rooms': ['Entry']}
```

Use `CheckJSON().repair(task)` for the model-capable pipeline. When a value is missing, it needs a corrector: install `checkjson-repair[model]`, or pass one such as `CheckJSON(engine=OllamaBackend("qwen3:4b-instruct"))`. `RulesOnly()` never needs a model. Use `repair_chat(messages, tools, reply)` when you need a list of accepted calls from a chat response. Use the full repair result when your app needs to distinguish the statuses below.

| Status | Meaning |
| --- | --- |
| `ok` | The payload passed the tool schema checks. Review the action and arguments before dispatch. |
| `no_tool_needed` | The result indicates that no tool call is needed. |
| `unsupported` | No offered tool fits the call, for example a call to a tool that does not exist. Do not run anything. |
| `unresolved` | The repair left a problem unresolved. Withhold the call. |

Schema validation checks the shape and types of the arguments. Your application decides whether the call matches the user's intent and is authorized to execute.

## Command line

```bash
checkjson repair task.json --rules-only --trace
checkjson tui --project my-app
checkjson stats --project my-app
checkjson proxy --upstream http://localhost:11434 --port 11435 --mode on --rules-only --project my-app
```

To start the local browser demo, install `checkjson-repair[demo]` and run `checkjson demo`. In the TUI, the generator and corrector are separate settings. The generator produces the original call. The corrector can fill unresolved fields. To try an Ollama corrector, pull `qwen3:4b-instruct` and select **Ollama model** in Setup.

### Proxy for existing apps

The proxy sits between your app and a model server. Your app needs no code change. Point it at the proxy address.

```bash
checkjson proxy --upstream http://localhost:11434 --port 11435 --mode on --corrector qwen3:4b-instruct
```

| Mode | What the app receives |
| --- | --- |
| `on` | CheckJSON's calls, only when the reply is not a valid call and the repair is valid. A valid reply is never changed. |
| `log` | The original reply. CheckJSON checks it and can write a log. |
| `off` | The original request and reply, forwarded as they are. |

The proxy handles Ollama `/api/chat` and OpenAI-style `/v1/chat/completions`. It listens on `127.0.0.1`. It writes a log only with `--log FILE`, and it never logs request headers.

### Repair a task file

Save this example as `task.json`. The outer file must be valid JSON. Put the raw model output in the `candidate_json` string, which can contain malformed JSON.

```json
{
  "request": "What is the status of the entry room?",
  "tools": [
    {
      "name": "get_room_status",
      "description": "Read room status.",
      "parameters": {
        "type": "object",
        "properties": {
          "rooms": {
            "type": "array",
            "items": {
              "type": "string"
            }
          }
        },
        "required": [
          "rooms"
        ]
      }
    }
  ],
  "candidate_json": "{\"turns\":[{\"calls\":[{\"name\":\"get_room_status\",\"arguments\":{\"rooms\":\"Entry\"}}]}]}"
}
```

Run `checkjson repair task.json --rules-only --trace`. Look for `"status": "ok"` and `"rooms": ["Entry"]` in the payload. Omit the filename to read the task from standard input. For automation, inspect the returned status before dispatch. The CLI exits with code 1 for an unresolved repair and code 2 when it cannot read the task file.

### Connect a model in the TUI

1. Press **F4** and choose a provider. For a custom OpenAI-compatible endpoint, choose **custom** and enter the API base URL.
2. Enter a model ID that supports tool calling. Enter an API key if the provider requires one.
3. Choose **Rules only** to start, then select **Test connection** and **Save**.
4. Press **F2**, enter a request and tool schemas, and select **Ask and inspect**. Compare **Model reply (raw)** with **Repaired call** and **Repair trace**. A successful connection test checks that the model responds. Tool calling still depends on the selected model.

### Troubleshooting

| Symptom | What to check |
| --- | --- |
| `checkjson` is not found | Activate the environment where you installed the package or try `python -m checkjson --help`. |
| Invalid task or tool schema | Validate the outer task JSON. Supply a `tools` array and keep the candidate call as a string. |
| Connection or authentication error | Check the base URL, key, and model ID in Setup. Use Test connection before running a request. |
| Model returns no tool call | Verify tool-calling support and inspect the raw reply. Use the Repair tab if you already have a candidate. |
| The repair is unresolved | Read the trace, check the schema and input, and review missing or ambiguous values before retrying. |
| Local corrector dependencies are missing | Install `checkjson-repair[model]` in the same environment, or switch to **Rules only**. |


## Network and history

Rules-only repair runs locally. **Ask a model** sends the request and tool definitions to the provider you configure. Model-assisted repair uses the configured corrector. The TUI keeps the API key in memory. Project settings and run counts are stored in `~/.checkjson/history.db` by default. The TUI stores call text only when you enable it for that project.

## Known limits

- **Schema valid is not the same as correct.** A value can fit the schema and still be wrong. Check important actions before you run them.
- **Cut-off text can lose a value.** An unfinished optional argument can be dropped.
- **Some badly quoted input can give a wrong value.** For example, arguments written as a Python dictionary with single quotes inside double-quoted JSON can come back as `ok` with several values merged into one.
- **A corrector can fail.** When it writes nothing useful, the result is `unresolved`.
- **This is an alpha release.** The interface can change.

## Research results

### Results by setting

All values are percentages except sample sizes, counts, and percentage-point changes. R/H means rescued/harmed for exact-call or validity checks and improved/worsened for paired application runs. These figures describe the evaluated research pipeline. The recorded-output and corruption tasks came from the pool used to refine the rules. Application runs sampled separate model replies in each condition.

| Setting | Metric | n | Baseline | CheckJSON | Change (pp) | R/H |
|---|---|---:|---:|---:|---:|---:|
| Controlled corruption | Accuracy | 20,674 | 53.39 | 88.90 | +35.51 | 7,391/50 |
| Llama-3.1-8B | Exact-call accuracy | 12,164 | 38.36 | 43.19 | +4.83 | 608/20 |
| Llama-3.2-3B | Exact-call accuracy | 1,000 | 33.40 | 38.30 | +4.90 | 51/2 |
| Qwen3-1.7B | Exact-call accuracy | 1,000 | 41.80 | 46.30 | +4.50 | 47/2 |
| Qwen3-4B | Exact-call accuracy | 1,000 | 44.70 | 46.00 | +1.30 | 14/1 |
| BFCL, Llama-3.1-8B | BFCL score | 3,641 | 36.14 | 51.11 | +14.97 | 620/75 |
| BFCL, Llama-3.2-3B | BFCL score | 3,641 | 62.95 | 65.97 | +3.02 | 115/5 |
| BFCL, Qwen3-1.7B | BFCL score | 3,641 | 77.95 | 78.28 | +0.33 | 26/14 |
| BFCL, Qwen3-4B | BFCL score | 3,641 | 79.26 | 81.10 | +1.84 | 78/11 |
| ToolBench | Valid calls | 765 | 72.68 | 99.35 | +26.67 | 204/0 |
| RestGPT | Valid calls | 157 | 46.50 | 99.36 | +52.86 | 83/0 |
| Tau² airline and retail logs | Valid calls | 1,379 | 73.39 | 91.66 | +18.27 | 252/0 |
| Tau² telecom logs | Valid calls | 1,938 | 28.74 | 39.89 | +11.15 | 216/0 |
| ToolSandbox | Valid calls | 3,161 | 45.24 | 87.19 | +41.95 | 1,326/0 |
| Tau² telecom live, 4-bit corrector | Tasks solved | 114 | 18.4 | 19.3 | +0.9 | 7/6 |
| Home Assistant | Runs solved | 705 | 48.4 | 60.0 | +11.6 | 119/37 |
| Goose | Runs solved | 120 | 18.3 | 28.3 | +10.0 | 17/5 |
| Open WebUI | Runs solved | 222 | 84.2 | 84.2 | 0.0 | 5/5 |

### Repair strategy comparison

The real-output columns refer to 12,164 recorded Llama-3.1-8B outputs. Controlled accuracy uses 20,674 tasks. Corrector inputs count distinct outputs routed to model assistance. Harm rates use the 4,666 originally correct outputs as the denominator.

| Method | Decoder access | Generator reruns | Corrector inputs | Real accuracy (%) | R/H | Harm (%) | Controlled accuracy (%) |
|---|---|---:|---:|---:|---:|---:|---:|
| Generator alone | — | 0 | 0 | 38.36 | — | — | 53.39 |
| json_repair | No | 0 | 0 | 38.18 | 10/32 | 0.69 | — |
| Validate and retry | No | 1,980 | 0 | 41.38 | 390/22 | 0.47 | — |
| Constrained decoding | Yes | 12,164 | 0 | 43.61 | 1,305/666 | 14.27 | — |
| Validation-gated constrained decoding | Yes | 1,980 | 0 | 44.28 | 739/19 | 0.41 | — |
| Deterministic only | No | 0 | 0 | 41.54 | 407/20 | 0.43 | 81.26 |
| Full rewrite, failing inputs | No | 0 | 1,980 | 44.77 | 791/11 | 0.24 | 80.48 |
| CheckJSON | No | 0 | 892 | 43.19 | 608/20 | 0.43 | 88.90 |

CheckJSON made 1,141 corrector invocations. Gated full rewriting made 1,980. On the paired comparison, rewriting uniquely solved 239 items and CheckJSON uniquely solved 47. The advantage for rewriting was 1.58 pp (95% paired CI 1.31 to 1.85 pp). This corresponds to 515 versus 394 net recoveries per 1,000 corrector invocations.

### Error analysis and ablations

- Controlled accuracy 88.90% (95% CI 88.46 to 89.32). Clean preservation was 9,724 of 9,726. Recovery was 93.18% for syntactic and 60.08% for semantic corruptions. At three semantic mutations it was 9.17% across 109 cases. Oracle filling reached 95.59% under known-value completion. Of 50 controlled harms, 48 involved cases that required abstention.
- The corrector added 201 rescuable real outputs over deterministic repair. Qwen3-4B 4-bit, Phi-4-mini, and Granite-3.3-2B recorded 43.29%, 43.07%, and 43.03% real-output accuracy. Each had 20 harms.
- 19 of 20 real-output harms and 70 of 75 BFCL harms were on tasks requiring abstention. Repair can expose a malformed attempted call that was previously scored as no action.
- Valid-call rates measure parse and schema acceptance. They do not establish exact-call correctness or task success. The live telecom gain was 0.9 pp. Open WebUI paired changes netted to zero.

## License

MIT. See the `LICENSE` file included in the distribution.

<p align="center">
  <img src="https://raw.githubusercontent.com/himanshu5trpth/checkjson-interactive/a023351/img/canva-icon.png" width="72" alt="CheckJSON icon">
</p>

