← Lesson
Parse, Then Fail Closed
Joeven
Run
Reset
Python loads on first run
import json REGISTRY = { "add": lambda a, b: a + b, "finish": lambda text: {"final": text}, } FENCE = chr(96) * 3 def strip_fence(raw): s = raw.strip() if s.startswith(FENCE): lines = s.splitlines()[1:] if lines and lines[-1].strip() == FENCE: lines = lines[:-1] s = chr(10).join(lines) return s.strip() def parse(raw): try: obj = json.loads(strip_fence(raw)) except json.JSONDecodeError: return {"error": "bad_json"} if not isinstance(obj, dict): return {"error": "not_object"} name = obj.get("name") args = obj.get("args") if name not in REGISTRY: return {"error": "unknown_tool", "name": name} if not isinstance(args, dict): return {"error": "bad_args"} return {"ok": True, "name": name, "args": args} def execute(decision): if not decision.get("ok"): return decision return {"obs": REGISTRY[decision["name"]](**decision["args"])} fenced = FENCE + "json" + chr(10) + '{"name": "finish", "args": {"text": "5"}}' + chr(10) + FENCE print(execute(parse('{"name": "add", "args": {"a": 2, "b": 3}}'))) print(execute(parse(fenced))) print(execute(parse('{"name": "launch_nukes", "args": {}}'))) print(execute(parse("not json")))
Run to execute this in your browser. Nothing is sent to a server.