"""SA-005 tools (owner YES 26 Nov 2026 15:59 UK). Plain code the model can call; no learning inside them.""" import base64, datetime as dt, json, re TOOLS = [ {"type": "function", "function": {"name": "solve_sudoku", "description": "Solve a 9x9 Sudoku. Returns the completed grid as 9 lines of 9 digits.", "parameters": {"type": "object", "properties": {"grid": {"type": "string", "description": "The puzzle as 9 lines of 9 characters, digits for givens and '.' for empty cells."}}, "required": ["grid"]}}}, {"type": "function", "function": {"name": "calculate", "description": "Exact whole-number arithmetic on big numbers. Supports + - * / (exact integer division).", "parameters": {"type": "object", "properties": {"expression": {"type": "string", "description": "For example '3625701979503 - 361983218841'."}}, "required": ["expression"]}}}, {"type": "function", "function": {"name": "days_between", "description": "Number of days from one date to another.", "parameters": {"type": "object", "properties": {"start": {"type": "string", "description": "Date, e.g. '26 June 2002' or '2002-06-26'."}, "end": {"type": "string"}}, "required": ["start", "end"]}}}, {"type": "function", "function": {"name": "add_days", "description": "The date a number of days after a date (use a negative number for days before). Returns YYYY-MM-DD.", "parameters": {"type": "object", "properties": {"date": {"type": "string"}, "days": {"type": "integer"}}, "required": ["date", "days"]}}}, {"type": "function", "function": {"name": "weekday", "description": "The day of the week of a date, e.g. Monday.", "parameters": {"type": "object", "properties": {"date": {"type": "string"}}, "required": ["date"]}}}, {"type": "function", "function": {"name": "decode_caesar", "description": "Decode text that was encoded with a Caesar cipher by shifting each letter forward by 'shift'.", "parameters": {"type": "object", "properties": {"text": {"type": "string"}, "shift": {"type": "integer"}}, "required": ["text", "shift"]}}}, {"type": "function", "function": {"name": "decode_base64", "description": "Decode base64 text to plain text.", "parameters": {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}}}, ] def _date(s): s = str(s).strip().replace(",", "") for f in ("%Y-%m-%d", "%d %B %Y", "%d %b %Y", "%B %d %Y", "%d/%m/%Y"): try: return dt.datetime.strptime(s, f).date() except ValueError: pass raise ValueError(f"cannot read date {s!r}") def _sudoku(grid): cells = [c for c in str(grid) if c in "0123456789."] if len(cells) != 81: raise ValueError("grid must have 81 cells") g = [0 if c in ".0" else int(c) for c in cells] def ok(i, v): r, c = divmod(i, 9) if any(g[r * 9 + j] == v for j in range(9)) or any(g[k * 9 + c] == v for k in range(9)): return False br, bc = r // 3 * 3, c // 3 * 3 return not any(g[(br + a) * 9 + bc + b] == v for a in range(3) for b in range(3)) def go(): best = None for i in range(81): if g[i] == 0: opts = [v for v in range(1, 10) if ok(i, v)] if best is None or len(opts) < len(best[1]): best = (i, opts) if not opts: return False if best is None: return True i, opts = best for v in opts: g[i] = v if go(): return True g[i] = 0; return False if not go(): raise ValueError("no solution") return "\n".join("".join(map(str, g[r * 9:r * 9 + 9])) for r in range(9)) def _calc(expr): e = str(expr).replace("×", "*").replace("÷", "/").replace("−", "-").replace(",", "").replace(" ", "") m = re.fullmatch(r"(-?\d+)([-+*/])(-?\d+)", e) if not m: raise ValueError("use: <+|-|*|/> ") a, op, b = int(m.group(1)), m.group(2), int(m.group(3)) if op == "/": if b == 0: raise ValueError("division by zero") q, r = divmod(a, b); return str(q) if r == 0 else f"{q} remainder {r}" return str({"+": a + b, "-": a - b, "*": a * b}[op]) def _caesar(text, shift): k = int(shift) % 26 return "".join(chr((ord(c) - 97 - k) % 26 + 97) if c.islower() else chr((ord(c) - 65 - k) % 26 + 65) if c.isupper() else c for c in str(text)) def run(name, args): """Returns the tool result as a string (errors come back as 'error: ...' so the model can see them).""" try: a = args or {} if name == "solve_sudoku": return _sudoku(a["grid"]) if name == "calculate": return _calc(a["expression"]) if name == "days_between": return str((_date(a["end"]) - _date(a["start"])).days) if name == "add_days": return (_date(a["date"]) + dt.timedelta(days=int(a["days"]))).isoformat() if name == "weekday": return _date(a["date"]).strftime("%A") if name == "decode_caesar": return _caesar(a["text"], a["shift"]) if name == "decode_base64": return base64.b64decode(str(a["text"]).strip()).decode("utf-8", "replace") return f"error: unknown tool {name}" except Exception as ex: return f"error: {ex}" def parse_calls(t): out = [] for b in re.findall(r"\s*(.*?)\s*", t, re.S): try: d = json.loads(b); a = d.get("arguments", {}) if isinstance(a, str): a = json.loads(a) out.append({"name": d["name"], "arguments": a}) except Exception: out.append({"name": "", "arguments": {}}) return out