← Lesson
Parse JSON from a Model
Joeven
Run
Reset
Python loads on first run
import json fence = "`" * 3 def strip_fences(text): text = text.strip() lines = text.splitlines() if lines and lines[0].startswith(fence): lines = lines[1:] if lines and lines[-1].strip() == fence: lines = lines[:-1] text = chr(10).join(lines) return text.strip() def extract_object(text): start = text.find("{") end = text.rfind("}") if start == -1 or end <= start: return None return text[start : end + 1] def parse_action(text): try: blob = strip_fences(text) blob = extract_object(blob) or blob data = json.loads(blob) except json.JSONDecodeError as exc: return {"tool": None, "args": {}, "error": "bad_json", "detail": str(exc)} if not isinstance(data, dict): return {"tool": None, "args": {}, "error": "not_object"} tool = data.get("tool") or data.get("name") args = data.get("args") or data.get("arguments") or {} if not tool: return {"tool": None, "args": {}, "error": "missing_tool"} if not isinstance(args, dict): return {"tool": None, "args": {}, "error": "args_not_object"} return {"tool": tool, "args": args} clean = '{"tool": "search", "args": {"q": "rain"}}' fenced = chr(10).join( [fence + "json", '{"tool": "search", "args": {"q": "coat"}}', fence] ) noisy = ( "Sure, here you go:" + chr(10) + '{"tool": "finish", "args": {"text": "done"}}' + chr(10) + "Thanks!" ) bad = "not json at all" # BAD, never do this with model text: # action = eval(clean) for label, sample in [ ("clean", clean), ("fenced", fenced), ("noisy", noisy), ("bad", bad), ]: print(label, parse_action(sample))
Run to execute this in your browser. Nothing is sent to a server.