"""Tool registry: schemas, protocol renderers, and argument normalisation. Grading rests on normalisation, not string equality. Every tool declares how its arguments are canonicalised so that semantically identical calls compare equal (`Berlin` / `berlin ` / `Берлин`, `300` / `300.0`, `45+12` / `57`). """ from __future__ import annotations import ast import json import math import re import unicodedata from dataclasses import dataclass from typing import Any, Callable, Mapping, Sequence from .schema import Protocol @dataclass(frozen=True) class ToolSpec: name: str description: str parameters: Mapping[str, str] required: tuple[str, ...] normalizers: Mapping[str, Callable[[Any], Any]] optional: tuple[str, ...] = () def schema(self) -> dict[str, Any]: return { "name": self.name, "description": self.description, "parameters": { "type": "object", "properties": { key: {"type": param_type, "description": self.parameters[key]} for key, param_type in self.parameters.items() }, "required": list(self.required), }, } _QUOTES = str.maketrans({"«": "", "»": "", "“": "", "”": "", '"': "", "'": ""}) def _squash(value: Any) -> str: text = unicodedata.normalize("NFKC", str(value)) text = text.translate(_QUOTES).replace("\u0451", "\u0435").replace("\u00eb", "e") text = re.sub(r"\s+", " ", text).strip().lower() return text _CITY_ALIASES = { "spb": "saint petersburg", "st petersburg": "saint petersburg", "st. petersburg": "saint petersburg", "sankt peterburg": "saint petersburg", "petersburg": "saint petersburg", "\u043f\u0438\u0442\u0435\u0440": "saint petersburg", "\u0441\u0430\u043d\u043a\u0442-\u043f\u0435\u0442\u0435\u0440\u0431\u0443\u0440\u0433": "saint petersburg", "\u0441\u043f\u0431": "saint petersburg", "nyc": "new york", "new york city": "new york", "\u043d\u044c\u044e-\u0439\u043e\u0440\u043a": "new york", "msk": "moscow", "\u043c\u043e\u0441\u043a\u0432\u0430": "moscow", "kiev": "kyiv", "\u043a\u0438\u0435\u0432": "kyiv", "\u043a\u0438\u0457\u0432": "kyiv", "\u0431\u0435\u0440\u043b\u0438\u043d": "berlin", "\u043b\u043e\u043d\u0434\u043e\u043d": "london", "\u0442\u043e\u043a\u0438\u043e": "tokyo", "\u043f\u0430\u0440\u0438\u0436": "paris", "\u0434\u0443\u0431\u0430\u0439": "dubai", "\u0430\u043b\u043c\u0430\u0442\u044b": "almaty", "\u043a\u0430\u0437\u0430\u043d\u044c": "kazan", } _LANGUAGE_ALIASES = { "english": "en", "eng": "en", "en-us": "en", "en-gb": "en", "\u0430\u043d\u0433\u043b\u0438\u0439\u0441\u043a\u0438\u0439": "en", "russian": "ru", "rus": "ru", "ru-ru": "ru", "\u0440\u0443\u0441\u0441\u043a\u0438\u0439": "ru", "german": "de", "\u043d\u0435\u043c\u0435\u0446\u043a\u0438\u0439": "de", "germany": "de", "spanish": "es", "\u0438\u0441\u043f\u0430\u043d\u0441\u043a\u0438\u0439": "es", "french": "fr", "\u0444\u0440\u0430\u043d\u0446\u0443\u0437\u0441\u043a\u0438\u0439": "fr", "italian": "it", "\u0438\u0442\u0430\u043b\u044c\u044f\u043d\u0441\u043a\u0438\u0439": "it", "japanese": "ja", "\u044f\u043f\u043e\u043d\u0441\u043a\u0438\u0439": "ja", "chinese": "zh", "\u043a\u0438\u0442\u0430\u0439\u0441\u043a\u0438\u0439": "zh", "portuguese": "pt", "\u043f\u043e\u0440\u0442\u0443\u0433\u0430\u043b\u044c\u0441\u043a\u0438\u0439": "pt", "turkish": "tr", "\u0442\u0443\u0440\u0435\u0446\u043a\u0438\u0439": "tr", "kazakh": "kk", "\u043a\u0430\u0437\u0430\u0445\u0441\u043a\u0438\u0439": "kk", "ukrainian": "uk", "\u0443\u043a\u0440\u0430\u0438\u043d\u0441\u043a\u0438\u0439": "uk", "arabic": "ar", "\u0430\u0440\u0430\u0431\u0441\u043a\u0438\u0439": "ar", "korean": "ko", "\u043a\u043e\u0440\u0435\u0439\u0441\u043a\u0438\u0439": "ko", "dutch": "nl", "\u0433\u043e\u043b\u043b\u0430\u043d\u0434\u0441\u043a\u0438\u0439": "nl", "polish": "pl", "\u043f\u043e\u043b\u044c\u0441\u043a\u0438\u0439": "pl", "hindi": "hi", } _CURRENCY_ALIASES = { "$": "USD", "usd": "USD", "us dollar": "USD", "us dollars": "USD", "dollar": "USD", "dollars": "USD", "\u0434\u043e\u043b\u043b\u0430\u0440": "USD", "\u0434\u043e\u043b\u043b\u0430\u0440\u043e\u0432": "USD", "usd.": "USD", "\u20ac": "EUR", "eur": "EUR", "euro": "EUR", "euros": "EUR", "\u0435\u0432\u0440\u043e": "EUR", "\u20bd": "RUB", "rub": "RUB", "ruble": "RUB", "rubles": "RUB", "rouble": "RUB", "\u0440\u0443\u0431": "RUB", "\u0440\u0443\u0431\u043b\u044c": "RUB", "\u0440\u0443\u0431\u043b\u0435\u0439": "RUB", "\u20b8": "KZT", "kzt": "KZT", "tenge": "KZT", "\u0442\u0435\u043d\u0433\u0435": "KZT", "\u00a3": "GBP", "gbp": "GBP", "pound": "GBP", "pounds": "GBP", "sterling": "GBP", "\u0444\u0443\u043d\u0442": "GBP", "\u00a5": "JPY", "jpy": "JPY", "yen": "JPY", "\u0438\u0435\u043d\u0430": "JPY", "\u00a5\u00a5": "CNY", "cny": "CNY", "rmb": "CNY", "yuan": "CNY", "\u044e\u0430\u043d\u044c": "CNY", "try": "TRY", "\u20ba": "TRY", "lira": "TRY", "\u043b\u0438\u0440\u0430": "TRY", "\u20b4": "UAH", "uah": "UAH", "hryvnia": "UAH", "\u0433\u0440\u0438\u0432\u043d\u0430": "UAH", "\u20b9": "INR", "inr": "INR", "rupee": "INR", "rupees": "INR", "chf": "CHF", "franc": "CHF", "cad": "CAD", "aud": "AUD", "brl": "BRL", "real": "BRL", "sek": "SEK", "nok": "NOK", "pln": "PLN", "zloty": "PLN", "czk": "CZK", "krone": "NOK", } _UNIT_ALIASES = { "km": "km", "kilometer": "km", "kilometers": "km", "kilometre": "km", "kilometres": "km", "\u043a\u043c": "km", "\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440": "km", "\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440\u043e\u0432": "km", "mile": "mi", "miles": "mi", "mi": "mi", "\u043c\u0438\u043b\u044f": "mi", "\u043c\u0438\u043b\u044c": "mi", "\u043c\u0438\u043b\u0438": "mi", "m": "m", "meter": "m", "meters": "m", "metre": "m", "\u043c\u0435\u0442\u0440": "m", "\u043c\u0435\u0442\u0440\u043e\u0432": "m", "ft": "ft", "foot": "ft", "feet": "ft", "\u0444\u0443\u0442": "ft", "\u0444\u0443\u0442\u043e\u0432": "ft", "cm": "cm", "centimeter": "cm", "centimeters": "cm", "\u0441\u043c": "cm", "inch": "in", "inches": "in", "in": "in", "\u0434\u044e\u0439\u043c": "in", "\u0434\u044e\u0439\u043c\u043e\u0432": "in", "mm": "mm", "millimeter": "mm", "\u043c\u043c": "mm", "kg": "kg", "kilogram": "kg", "kilograms": "kg", "\u043a\u0433": "kg", "kilogramm": "kg", "lb": "lb", "lbs": "lb", "pound": "lb", "pounds": "lb", "\u0444\u0443\u043d\u0442": "lb", "g": "g", "gram": "g", "grams": "g", "\u0433": "g", "\u0433\u0440\u0430\u043c\u043c": "g", "\u0433\u0440\u0430\u043c\u043c\u043e\u0432": "g", "c": "celsius", "celsius": "celsius", "\u00b0c": "celsius", "\u0433\u0440\u0430\u0434\u0443\u0441\u043e\u0432": "celsius", "\u0446\u0435\u043b\u044c\u0441\u0438\u0439": "celsius", "f": "fahrenheit", "fahrenheit": "fahrenheit", "\u00b0f": "fahrenheit", "farenheit": "fahrenheit", "kph": "km/h", "km/h": "km/h", "kmh": "km/h", "\u043a\u043c/\u0447": "km/h", "mph": "mph", "m/s": "m/s", "l": "l", "liter": "l", "liters": "l", "litre": "l", "\u043b": "l", "\u043b\u0438\u0442\u0440": "l", "\u043b\u0438\u0442\u0440\u043e\u0432": "l", "ml": "ml", "\u043c\u043b": "ml", "gal": "gal", "gallon": "gal", "gallons": "gal", "hour": "h", "hours": "h", "h": "h", "\u0447\u0430\u0441": "h", "\u0447\u0430\u0441\u043e\u0432": "h", "\u0447": "h", "minute": "min", "minutes": "min", "\u043c\u0438\u043d\u0443\u0442": "min", "\u043c\u0438\u043d": "min", "day": "day", "days": "day", "\u0434\u0435\u043d\u044c": "day", "\u0434\u043d\u0435\u0439": "day", } _TIMEZONE_ALIASES = { "utc": "UTC", "gmt": "UTC", "moscow": "Europe/Moscow", "msk": "Europe/Moscow", "moscow time": "Europe/Moscow", "\u043c\u043e\u0441\u043a\u0432\u0430": "Europe/Moscow", "saint petersburg": "Europe/Moscow", "\u043c\u0441\u043a": "Europe/Moscow", "berlin": "Europe/Berlin", "london": "Europe/London", "paris": "Europe/Paris", "new york": "America/New_York", "nyc": "America/New_York", "los angeles": "America/Los_Angeles", "tokyo": "Asia/Tokyo", "dubai": "Asia/Dubai", "almaty": "Asia/Almaty", "shanghai": "Asia/Shanghai", "sydney": "Australia/Sydney", "kyiv": "Europe/Kyiv", "kiev": "Europe/Kyiv", "kazan": "Europe/Moscow", "warsaw": "Europe/Warsaw", "istanbul": "Europe/Istanbul", "singapore": "Asia/Singapore", } _MATH_FUNCS: dict[str, Callable[..., float]] = { "sqrt": math.sqrt, "abs": abs, "round": round, "floor": math.floor, "ceil": math.ceil, "min": min, "max": max, "pow": pow, "sin": math.sin, "cos": math.cos, "tan": math.tan, "log": math.log, "log10": math.log10, "exp": math.exp, "pi": lambda: math.pi, "e": lambda: math.e, } def eval_expression(expression: Any) -> float | None: """Evaluate arithmetic safely. Returns None when the expression is not arithmetic.""" if isinstance(expression, bool): return None if isinstance(expression, (int, float)): return float(expression) text = _squash(expression).replace("\u00d7", "*").replace("\u00f7", "/").replace("\u0445", "*") text = text.replace("^", "**").replace(",", "").replace("%", "/100") text = re.sub(r"(?<=\d)\s+(\d)", r"*\1", text) if not text or not re.fullmatch(r"[0-9a-z_+\-*/().\s]*", text): return None try: tree = ast.parse(text, mode="eval") except SyntaxError: return None def walk(node: ast.AST) -> float: if isinstance(node, ast.Expression): return walk(node.body) if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)): return float(node.value) if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)): value = walk(node.operand) return value if isinstance(node.op, ast.UAdd) else -value if isinstance(node, ast.BinOp): left, right = walk(node.left), walk(node.right) ops: dict[type, Callable[[float, float], float]] = { ast.Add: lambda a, b: a + b, ast.Sub: lambda a, b: a - b, ast.Mult: lambda a, b: a * b, ast.Div: lambda a, b: a / b, ast.Pow: lambda a, b: a**b, ast.Mod: lambda a, b: a % b, ast.FloorDiv: lambda a, b: a // b, } for node_type, op in ops.items(): if isinstance(node.op, node_type): return op(left, right) raise ValueError("operator") if isinstance(node, ast.Call): if not isinstance(node.func, ast.Name): raise ValueError("call") func = _MATH_FUNCS.get(node.func.id) if func is None or node.keywords: raise ValueError("function") return float(func(*[walk(arg) for arg in node.args])) if isinstance(node, ast.Name): func = _MATH_FUNCS.get(node.id) if func is None: raise ValueError("name") return float(func()) raise ValueError("node") try: result = walk(tree) except Exception: return None if not math.isfinite(result): return None return result def norm_number(value: Any) -> float | None: if isinstance(value, bool): return None if isinstance(value, (int, float)): return float(value) text = _squash(value).replace(",", ".").replace(" ", "") text = re.sub(r"[^\d.\-e+]", "", text) if not text: return None try: return float(text) except ValueError: return None def norm_expression(value: Any) -> Any: evaluated = eval_expression(value) if evaluated is not None: return round(evaluated, 6) return _squash(value).replace(" ", "") def norm_from_aliases(aliases: Mapping[str, str], fallback: Callable[[str], str] | None = None) -> Callable[[Any], Any]: table = {_squash(key): _squash(value) for key, value in aliases.items()} tail: Callable[[str], str] = fallback or (lambda text: text) def normalizer(value: Any) -> Any: key = _squash(value) key = re.sub(r"^(в|to|from|into|in)\s+", "", key).strip() return table.get(key, tail(key)) return normalizer _norm_city = norm_from_aliases(_CITY_ALIASES, lambda t: t.rstrip(".,!?")) _norm_language = norm_from_aliases(_LANGUAGE_ALIASES) _norm_currency = norm_from_aliases(_CURRENCY_ALIASES) _norm_unit = norm_from_aliases(_UNIT_ALIASES) _norm_timezone = norm_from_aliases(_TIMEZONE_ALIASES) _norm_text = lambda value: re.sub(r"\s+", " ", _squash(value)).strip(" .,!?\"'") def norm_query(value: Any) -> Any: text = _norm_text(value) text = re.sub(r"[^\w\s\u0400-\u04ff]", " ", text) return re.sub(r"\s+", " ", text).strip() def norm_seconds(value: Any) -> Any: number = norm_number(value) if number is None: return _norm_text(value) return int(round(number)) REGISTRY: dict[str, ToolSpec] = { "calculator": ToolSpec( name="calculator", description="Evaluates a mathematical expression and returns the numeric result.", parameters={ "expression": "string: the arithmetic expression to evaluate, e.g. '(45 + 12) * 3'" }, required=("expression",), normalizers={"expression": norm_expression}, ), "get_weather": ToolSpec( name="get_weather", description="Returns the current weather for a city.", parameters={ "city": "string: city name", "unit": "string, optional: 'celsius' or 'fahrenheit'", }, required=("city",), optional=("unit",), normalizers={"city": _norm_city, "unit": _norm_unit}, ), "web_search": ToolSpec( name="web_search", description="Searches the web and returns ranked results for a query.", parameters={"query": "string: search query"}, required=("query",), normalizers={"query": norm_query}, ), "translate": ToolSpec( name="translate", description="Translates text into a target language.", parameters={ "text": "string: the text to translate", "target_language": "string: ISO 639-1 code or language name", }, required=("text", "target_language"), normalizers={"text": _norm_text, "target_language": _norm_language}, ), "convert_currency": ToolSpec( name="convert_currency", description="Converts an amount from one currency to another using current rates.", parameters={ "amount": "number: amount to convert", "from_currency": "string: ISO 4217 code or currency name", "to_currency": "string: ISO 4217 code or currency name", }, required=("amount", "from_currency", "to_currency"), normalizers={ "amount": norm_number, "from_currency": _norm_currency, "to_currency": _norm_currency, }, ), "convert_units": ToolSpec( name="convert_units", description="Converts a value between measurement units.", parameters={ "value": "number: value to convert", "from_unit": "string: source unit", "to_unit": "string: target unit", }, required=("value", "from_unit", "to_unit"), normalizers={"value": norm_number, "from_unit": _norm_unit, "to_unit": _norm_unit}, ), "set_timer": ToolSpec( name="set_timer", description="Starts a countdown timer for the given duration in seconds.", parameters={"seconds": "integer: duration of the timer in seconds"}, required=("seconds",), normalizers={"seconds": norm_seconds}, ), "save_note": ToolSpec( name="save_note", description="Saves a note with a title and body text.", parameters={"title": "string: short note title", "content": "string: note body"}, required=("title", "content"), normalizers={"title": _norm_text, "content": _norm_text}, ), "get_time": ToolSpec( name="get_time", description="Returns the current date and time in a given timezone.", parameters={"timezone": "string: IANA timezone name or city"}, required=("timezone",), normalizers={"timezone": _norm_timezone}, ), } TOOL_NAMES: tuple[str, ...] = tuple(REGISTRY) # Handles seen in the wild that mean the same tool. NAME_ALIASES: dict[str, str] = { "calc": "calculator", "calculate": "calculator", "math": "calculator", "evaluate_expression": "calculator", "weather": "get_weather", "weather_lookup": "get_weather", "get_current_weather": "get_weather", "search": "web_search", "search_web": "web_search", "google_search": "web_search", "currency_converter": "convert_currency", "convert": "convert_currency", "exchange_rate": "convert_currency", "unit_conversion": "convert_units", "convert_measurement": "convert_units", "timer": "set_timer", "create_timer": "set_timer", "start_timer": "set_timer", "note": "save_note", "add_note": "save_note", "create_note": "save_note", "time": "get_time", "current_time": "get_time", "get_current_time": "get_time", "translation": "translate", } def canonical_name(name: Any) -> str: key = _squash(name) return NAME_ALIASES.get(key, key) def tools_for(names: Sequence[str]) -> tuple[ToolSpec, ...]: return tuple(REGISTRY[name] for name in names if name in REGISTRY) def render_tools_json(specs: Sequence[ToolSpec]) -> str: payload = {"tools": [spec.schema() for spec in specs]} return json.dumps(payload, ensure_ascii=False, indent=2) def render_tools_xml(specs: Sequence[ToolSpec]) -> str: lines: list[str] = [] for spec in specs: lines.append(f"") lines.append(f" {spec.description}") lines.append(" ") for key, param_type in spec.parameters.items(): marker = " required" if key in spec.required else "" lines.append(f" ") lines.append(" ") lines.append("") return "\n".join(lines) def render_tools_plain(specs: Sequence[ToolSpec]) -> str: lines: list[str] = [] for spec in specs: params = ", ".join( f"{key}{'' if key in spec.required else ' (optional)'}" for key in spec.parameters ) lines.append(f"- {spec.name}({params}): {spec.description}") return "\n".join(lines) def render_tools(specs: Sequence[ToolSpec], protocol: Protocol) -> str: return { "json": render_tools_json, "xml": render_tools_xml, "plain": render_tools_plain, }[protocol](specs)