|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import hashlib |
| 4 | +import json |
| 5 | +from dataclasses import dataclass |
| 6 | +from typing import Any, Callable |
| 7 | + |
| 8 | + |
| 9 | +class StopRun(Exception): |
| 10 | + def __init__(self, reason: str): |
| 11 | + super().__init__(reason) |
| 12 | + self.reason = reason |
| 13 | + |
| 14 | + |
| 15 | +@dataclass(frozen=True) |
| 16 | +class Budget: |
| 17 | + max_steps: int = 8 |
| 18 | + max_tool_calls: int = 6 |
| 19 | + max_seconds: int = 20 |
| 20 | + |
| 21 | + |
| 22 | +def _stable_json(value: Any) -> str: |
| 23 | + if value is None or isinstance(value, (bool, int, float, str)): |
| 24 | + return json.dumps(value, ensure_ascii=True, sort_keys=True) |
| 25 | + if isinstance(value, list): |
| 26 | + return "[" + ",".join(_stable_json(item) for item in value) + "]" |
| 27 | + if isinstance(value, dict): |
| 28 | + parts = [] |
| 29 | + for key in sorted(value): |
| 30 | + parts.append( |
| 31 | + json.dumps(str(key), ensure_ascii=True) + ":" + _stable_json(value[key]) |
| 32 | + ) |
| 33 | + return "{" + ",".join(parts) + "}" |
| 34 | + return json.dumps(str(value), ensure_ascii=True) |
| 35 | + |
| 36 | + |
| 37 | +def args_hash(args: dict[str, Any]) -> str: |
| 38 | + raw = _stable_json(args or {}) |
| 39 | + return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:12] |
| 40 | + |
| 41 | + |
| 42 | +def validate_action(action: Any) -> dict[str, Any]: |
| 43 | + if not isinstance(action, dict): |
| 44 | + raise StopRun("invalid_action:not_object") |
| 45 | + |
| 46 | + kind = action.get("kind") |
| 47 | + if kind == "invalid": |
| 48 | + raise StopRun("invalid_action:bad_json") |
| 49 | + if kind not in {"tool", "final"}: |
| 50 | + raise StopRun("invalid_action:bad_kind") |
| 51 | + |
| 52 | + if kind == "final": |
| 53 | + allowed = {"kind", "answer"} |
| 54 | + extra = set(action.keys()) - allowed |
| 55 | + if extra: |
| 56 | + raise StopRun("invalid_action:extra_keys") |
| 57 | + answer = action.get("answer") |
| 58 | + if not isinstance(answer, str) or not answer.strip(): |
| 59 | + raise StopRun("invalid_action:missing_answer") |
| 60 | + return {"kind": "final", "answer": answer.strip()} |
| 61 | + |
| 62 | + allowed = {"kind", "name", "args"} |
| 63 | + extra = set(action.keys()) - allowed |
| 64 | + if extra: |
| 65 | + raise StopRun("invalid_action:extra_keys") |
| 66 | + |
| 67 | + name = action.get("name") |
| 68 | + if not isinstance(name, str) or not name: |
| 69 | + raise StopRun("invalid_action:missing_tool_name") |
| 70 | + |
| 71 | + args = action.get("args", {}) |
| 72 | + if args is None: |
| 73 | + args = {} |
| 74 | + if not isinstance(args, dict): |
| 75 | + raise StopRun("invalid_action:bad_args") |
| 76 | + |
| 77 | + return {"kind": "tool", "name": name, "args": args} |
| 78 | + |
| 79 | + |
| 80 | +class ToolGateway: |
| 81 | + def __init__( |
| 82 | + self, |
| 83 | + *, |
| 84 | + allow: set[str], |
| 85 | + registry: dict[str, Callable[..., dict[str, Any]]], |
| 86 | + budget: Budget, |
| 87 | + ): |
| 88 | + self.allow = set(allow) |
| 89 | + self.registry = registry |
| 90 | + self.budget = budget |
| 91 | + self.tool_calls = 0 |
| 92 | + self.seen_calls: set[str] = set() |
| 93 | + |
| 94 | + def call(self, name: str, args: dict[str, Any]) -> dict[str, Any]: |
| 95 | + self.tool_calls += 1 |
| 96 | + if self.tool_calls > self.budget.max_tool_calls: |
| 97 | + raise StopRun("max_tool_calls") |
| 98 | + |
| 99 | + if name not in self.allow: |
| 100 | + raise StopRun(f"tool_denied:{name}") |
| 101 | + |
| 102 | + tool = self.registry.get(name) |
| 103 | + if tool is None: |
| 104 | + raise StopRun(f"tool_missing:{name}") |
| 105 | + |
| 106 | + signature = f"{name}:{args_hash(args)}" |
| 107 | + if signature in self.seen_calls: |
| 108 | + raise StopRun("loop_detected") |
| 109 | + self.seen_calls.add(signature) |
| 110 | + |
| 111 | + try: |
| 112 | + return tool(**args) |
| 113 | + except TypeError as exc: |
| 114 | + raise StopRun(f"tool_bad_args:{name}") from exc |
| 115 | + except Exception as exc: |
| 116 | + raise StopRun(f"tool_error:{name}") from exc |
0 commit comments