LeyanW's picture
Add files using upload-large-folder tool
27e0680 verified
Raw History Blame Contribute Delete
2.4 kB
"""Typed tool schemas and effect declarations. No model or audio dependencies."""
from __future__ import annotations
from copy import deepcopy
from dataclasses import dataclass
import math
class ToolError(ValueError):
pass
def string(enum=None):
result = {"type": "string", "minLength": 1}
if enum is not None:
result["enum"] = list(enum)
return result
def integer(low, high):
return {"type": "integer", "minimum": low, "maximum": high}
def array(item, minimum=1):
return {"type": "array", "items": item, "minItems": minimum, "uniqueItems": True}
def validate(value, schema, path="arguments"):
kind = schema["type"]
valid = {"object": type(value) is dict, "string": type(value) is str,
"integer": type(value) is int, "number": type(value) in (int, float),
"boolean": type(value) is bool, "array": type(value) is list}[kind]
if not valid:
raise ToolError(f"{path}: expected {kind}")
if kind == "object":
props = schema["properties"]
missing = set(schema.get("required", [])) - value.keys()
extra = value.keys() - props.keys()
if missing or extra:
raise ToolError(f"{path}: missing={sorted(missing)}, unknown={sorted(extra)}")
for key, val in value.items():
validate(val, props[key], f"{path}.{key}")
if kind in ("integer", "number"):
if not math.isfinite(value) or not schema.get("minimum", -math.inf) <= value <= schema.get("maximum", math.inf):
raise ToolError(f"{path}: outside allowed range")
if "enum" in schema and value not in schema["enum"]:
raise ToolError(f"{path}: must be one of {schema['enum']}")
if kind == "string" and len(value) < schema.get("minLength", 0):
raise ToolError(f"{path}: empty string")
if kind == "array":
if len(value) < schema.get("minItems", 0) or len({str(v) for v in value}) != len(value):
raise ToolError(f"{path}: empty or duplicate entries")
for index, val in enumerate(value):
validate(val, schema["items"], f"{path}[{index}]")
@dataclass(frozen=True)
class ToolSpec:
name: str
description: str
parameters: dict
kind: str = "read"
def public(self):
return {"type": "function", "function": {"name": self.name, "description": self.description,
"parameters": deepcopy(self.parameters)}}