File size: 2,403 Bytes
27e0680
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""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)}}