Spaces:
Running on Zero
Running on Zero
Download checkjson/cli.py from himanshu5trpth/checkjson: direct link, hf CLI and curl.
- Browser
- Download file 9.97 kB
-
https://huggingface.co/spaces/himanshu5trpth/checkjson/resolve/main/checkjson/cli.py
- Command line
-
hf download hf://spaces/himanshu5trpth/checkjson/checkjson/cli.py
-
curl -L -o cli.py https://huggingface.co/spaces/himanshu5trpth/checkjson/resolve/main/checkjson/cli.py
9.97 kB
| """The `checkjson` command. `ckjn`, `checkjson-repair` and `checkjson-llm` run the same command. | |
| checkjson repair [FILE] [--trace] [--rules-only] repair one tool call (a task JSON from FILE or stdin) | |
| checkjson proxy --upstream URL --port N --mode on put CheckJSON between an app and a model server | |
| checkjson demo start the demo page (needs: pip install "checkjson-repair[demo]") | |
| checkjson tui the terminal page: repair, ask a model, projects, counts | |
| checkjson stats [--project NAME] how many calls were checked and repaired | |
| checkjson example repair a sample call and show each step | |
| """ | |
| import argparse | |
| import codecs | |
| import importlib.util | |
| import json | |
| import sys | |
| from pathlib import Path | |
| from . import __version__ | |
| COMMANDS = ("checkjson", "ckjn", "checkjson-repair", "checkjson-llm") | |
| REPAIR_HELP = """The input is one JSON object: | |
| {"context": [...], "request": "...", "tools": [{"name", "description", "parameters"}], "candidate_json": "..."} | |
| `candidate_json` is the generator's output as text. It can be broken. The output is the result as JSON: | |
| status ("ok", "no_tool_needed", "unsupported" or "unresolved"), payload, trail and more. | |
| The exit code is 1 when the status is "unresolved" (do not run the call), else 0.""" | |
| def read_task(path): | |
| raw = sys.stdin.buffer.read() if path in (None, "-") else open(path, "rb").read() | |
| if raw.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)): | |
| text = raw.decode("utf-16") | |
| else: | |
| text = raw.decode("utf-8-sig") | |
| task = json.loads(text) | |
| if not isinstance(task, dict) or "tools" not in task or "candidate_json" not in task: | |
| raise ValueError('the input must be a JSON object with "tools" and "candidate_json"') | |
| return {"context": [], "request": "", **task} | |
| def repair(args): | |
| try: | |
| task = read_task(args.file) | |
| except (OSError, ValueError) as exc: | |
| print(f"checkjson repair: {exc}", file=sys.stderr) | |
| return 2 | |
| if args.rules_only: | |
| from .rulesonly import RulesOnly | |
| checker = RulesOnly() | |
| else: | |
| from .nesy_repair import NeSyRepair | |
| checker = NeSyRepair() # the corrector loads only when a call needs it | |
| try: | |
| result = checker.repair(task, trace=args.trace) | |
| except ImportError as exc: | |
| print(f"checkjson repair: {exc}\nOn the command line, add --rules-only to run without a model.", file=sys.stderr) | |
| return 2 | |
| if args.project: | |
| from .history import Store, is_valid_call | |
| Store().record(args.project, "command", result, corrector="rules only" if args.rules_only else "default", | |
| valid_alone=is_valid_call(task["candidate_json"], task["tools"]), | |
| content={"request": task["request"], "candidate": task["candidate_json"]}) | |
| print(json.dumps(result, indent=2, ensure_ascii=False, default=str)) | |
| return 1 if result["status"] == "unresolved" else 0 | |
| def proxy(args): | |
| from .proxy import CheckJSONProxy | |
| engine = None | |
| if args.corrector and not args.rules_only: | |
| from .model_layer import OllamaBackend | |
| engine = OllamaBackend(args.corrector, url=args.corrector_url) | |
| on_record = None | |
| if args.project: | |
| from .history import Store | |
| store = Store() | |
| def on_record(record): | |
| if record["corrected"] is not None: # a plain text reply is not a tool call | |
| store.record(args.project, "proxy", record["corrected"], model=record["model"], | |
| corrector="rules only" if args.rules_only else (args.corrector or "default"), | |
| valid_alone=record["valid_alone"], repaired_is_valid=bool(record["valid_corrected"]), | |
| content={"candidate": json.dumps(record["raw"], ensure_ascii=False)}) | |
| server = CheckJSONProxy(args.upstream, mode=args.mode, engine=engine, rules_only=args.rules_only, | |
| log=args.log, host=args.host, port=args.port, on_record=on_record) | |
| corrector = "none (rules only)" if args.rules_only else (args.corrector or "default") | |
| print(f"CheckJSON proxy on {server.address[0]}:{server.address[1]} -> {args.upstream} mode={args.mode} " | |
| f"corrector={corrector} log={args.log or 'off'}", flush=True) | |
| try: | |
| server.serve_forever() | |
| except KeyboardInterrupt: | |
| print("stopped") | |
| finally: | |
| server.httpd.server_close() | |
| return 0 | |
| def demo(args): | |
| if importlib.util.find_spec("gradio") is None: | |
| print('The demo needs Gradio. Install it with: pip install "checkjson-repair[demo]"', file=sys.stderr) | |
| return 2 | |
| try: | |
| from .ui.app import launch | |
| except ImportError: | |
| print("The demo app is not part of this version of checkjson yet.", file=sys.stderr) | |
| return 2 | |
| launch(port=args.port, share=False) | |
| return 0 | |
| def tui(args): | |
| try: | |
| from .tui.app import run | |
| except ImportError as exc: | |
| print(f"The terminal page needs Textual ({exc}). Install it with: pip install textual", file=sys.stderr) | |
| return 2 | |
| run(project=args.project) | |
| return 0 | |
| def stats(args): | |
| from .history import Store | |
| data = Store().stats(args.project) | |
| if args.json: | |
| print(json.dumps(data, indent=2)) | |
| return 0 | |
| print(f"{'project ' + args.project if args.project else 'all projects'}") | |
| row = "{:<34}{:>8}{:>8}{:>10}{:>12}{:>9}" | |
| print(row.format("", "checked", "valid", "repaired", "unresolved", "no call")) | |
| keys = ("total", "already_valid", "repaired", "unresolved", "no_call") | |
| print(row.format("total", *(data[k] for k in keys))) | |
| for title, group in (("project", "by_project"), ("model", "by_model"), ("source", "by_source")): | |
| for name, g in sorted(data[group].items()): | |
| print(row.format(f"{title}: {name}"[:33], *(g[k] for k in keys))) | |
| return 0 | |
| def example(args): | |
| from . import trace_demo | |
| trace_demo.main() | |
| return 0 | |
| def build_parser(): | |
| name = Path(sys.argv[0]).stem | |
| ap = argparse.ArgumentParser(prog=name if name in COMMANDS else "checkjson", # show the name the user typed | |
| description="Repairs broken LLM tool calls before they reach your tools. " | |
| "Also runs as ckjn, checkjson-repair and checkjson-llm.") | |
| ap.add_argument("--version", action="version", version=f"checkjson {__version__}") | |
| sub = ap.add_subparsers(dest="command", metavar="{repair,proxy,demo,tui,stats,example}") | |
| r = sub.add_parser("repair", help="repair one tool call", description=REPAIR_HELP, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| r.add_argument("file", nargs="?", help="a task JSON file (default: read standard input)") | |
| r.add_argument("--trace", action="store_true", help="add the step-by-step trace to the result") | |
| r.add_argument("--rules-only", action="store_true", help="use the rule layers only. Never load the corrector.") | |
| r.add_argument("--project", help="count this call in a project (see checkjson stats)") | |
| r.set_defaults(run=repair) | |
| p = sub.add_parser("proxy", help="run CheckJSON between an app and a model server", | |
| description="Point your app at this proxy instead of the model server. " | |
| "Modes: off = forward only, log = check and log, on = replace invalid calls with repaired ones.") | |
| p.add_argument("--upstream", default="http://localhost:11434", help="the model server (default: %(default)s)") | |
| p.add_argument("--host", default="127.0.0.1", help="the address to listen on (default: %(default)s)") | |
| p.add_argument("--port", type=int, default=11435, help="the port to listen on (default: %(default)s)") | |
| p.add_argument("--mode", choices=("on", "off", "log"), default="on") | |
| p.add_argument("--log", metavar="FILE", help="write a JSONL log. Without it, nothing is written. Headers are never logged.") | |
| p.add_argument("--rules-only", action="store_true", help="never use a corrector model") | |
| p.add_argument("--corrector", metavar="OLLAMA_TAG", help="run the corrector on Ollama, for example qwen3:4b-instruct") | |
| p.add_argument("--corrector-url", default="http://127.0.0.1:11434", help="the Ollama server for --corrector") | |
| p.add_argument("--project", help="count the checked calls in a project (see checkjson stats)") | |
| p.set_defaults(run=proxy) | |
| d = sub.add_parser("demo", help="start the demo page", description='Needs: pip install "checkjson-repair[demo]"') | |
| d.add_argument("--port", type=int, default=7860) | |
| d.set_defaults(run=demo) | |
| t = sub.add_parser("tui", help="open the terminal page") | |
| t.add_argument("--project", default="default", help="the project to open (default: %(default)s)") | |
| t.set_defaults(run=tui) | |
| s = sub.add_parser("stats", help="show the counts of checked and repaired calls") | |
| s.add_argument("--project", help="one project only") | |
| s.add_argument("--json", action="store_true", help="print JSON") | |
| s.set_defaults(run=stats) | |
| e = sub.add_parser("example", help="repair a sample call and show each step (no key, no model)") | |
| e.set_defaults(run=example) | |
| return ap | |
| def main(argv=None): | |
| for stream in (sys.stdout, sys.stderr): | |
| try: | |
| stream.reconfigure(encoding="utf-8") | |
| except (AttributeError, ValueError): | |
| pass | |
| ap = build_parser() | |
| args = ap.parse_args(argv) | |
| if not getattr(args, "run", None): | |
| ap.print_help() | |
| return 0 | |
| return args.run(args) | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |