Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

CheckJSON

Validate and repair LLM tool calls before execution.

Python 3.10 or newer MIT license Alpha release

Interactive website · Try it on Hugging Face

Install · Quickstart · How it works · Python API · Command line · Known limits · Results

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.

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.

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.

The CheckJSON pipeline: detection, lexical repair, semantic repair, a small language model for holes, and the output

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 [].

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.

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

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.

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.

{
  "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.

CheckJSON icon

Metadata

Release files for checkjson-repair 0.1.0a2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for checkjson-repair 0.1.0a2
File Size Uploaded Provenance Actions
checkjson_repair-0.1.0a2.tar.gz 105.4 kB Without provenance Details for checkjson_repair-0.1.0a2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for checkjson-repair 0.1.0a2
File Interpreter ABI Platform Actions
checkjson_repair-0.1.0a2-py3-none-any.whl Python 3 none any Details for checkjson_repair-0.1.0a2-py3-none-any.whl

Total release size: 200.9 kB

Release files / checkjson_repair-0.1.0a2.tar.gz

Download URL checkjson_repair-0.1.0a2.tar.gz
Size 105.4 kB
Tags Source
SHA-256 checksum
How to use checksums
159842e615b743077a2698be729117055edd27e25305f568e70eb46328532906
BLAKE2b-256 checksum
How to use checksums
e4be12193cebda998012fc56370f4d6c83fcf7a4c36017356d9bc22ea8cce944
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.16

Release files / checkjson_repair-0.1.0a2-py3-none-any.whl

Download URL checkjson_repair-0.1.0a2-py3-none-any.whl
Size 95.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ab7098874ea7597148fbb1a9cd64c1669ffc3aceee9edddbb626010c6bd35df1
BLAKE2b-256 checksum
How to use checksums
779b5adf6f09bcd9b51461f753aa864186c1899a56904d6e8680becf3c9b27f2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.16

Security for checkjson-repair 0.1.0a2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page