← Lesson
Parseable Actions
Joeven
Run
Reset
Python loads on first run
import json TOOLS = { "get_job": lambda job_id: {"id": job_id, "status": "failed", "error": "vendor timeout"}, "finish": lambda answer: {"final": answer}, "handoff": lambda reason: {"handoff": reason}, } def parse_action(text): obj = json.loads(text) if obj.get("tool") not in TOOLS: raise ValueError("unknown tool") if not isinstance(obj.get("args"), dict): raise ValueError("args") return obj def run_loop(script, max_steps=4): for step, blob in enumerate(script, start=1): if step > max_steps: return "STOP: budget" turn = parse_action(blob) result = TOOLS[turn["tool"]](**turn["args"]) print("step", step, turn["tool"], result) if turn["tool"] in {"finish", "handoff"}: return result return "STOP: no finish" script = [ '{"thought": "need the job", "tool": "get_job", "args": {"job_id": 17}}', '{"thought": "report it", "tool": "finish", "args": {"answer": "Job 17 failed: vendor timeout"}}', ] print("OUT:", run_loop(script)) print("prose fails") try: parse_action("I will now Get-Job :)") except Exception as e: print(type(e).__name__, e)
Run to execute this in your browser. Nothing is sent to a server.