Spaces:
Sleeping
Sleeping
File size: 1,592 Bytes
1435f2c | 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 | """Only these five tools and their validated arguments can be executed."""
from typing import Annotated, Literal
from pydantic import BaseModel, BeforeValidator, ConfigDict, Field, StringConstraints, ValidationError
Text = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=100)]
def number(value):
if isinstance(value, bool):
raise ValueError("amount must be a number, not a boolean")
return value
Amount = Annotated[float, BeforeValidator(number), Field(gt=0, le=100000, allow_inf_nan=False)]
Unit = Annotated[Literal["mg", "g", "mcg", "µg", "ug"],
BeforeValidator(lambda v: v.strip().lower() if isinstance(v, str) else v)]
class Arguments(BaseModel):
model_config = ConfigDict(extra="forbid")
class Lookup(Arguments):
name: Text
class Dose(Arguments):
ingredient: Text
amount: Amount
unit: Unit
class Order(Arguments):
items: Annotated[list[Dose], Field(min_length=1, max_length=30)]
class Diagnosis(Arguments):
diagnosis: Text
class Alternatives(Arguments):
ingredient: Text
diagnosis: Text | None = None
MODELS = {"lookup_ingredient": Lookup, "check_dose": Dose, "check_order": Order,
"find_ingredients_for_diagnosis": Diagnosis, "suggest_alternatives": Alternatives}
def validate_call(name, arguments):
if name not in MODELS:
return None, "Tool is not on the allowlist"
try:
return MODELS[name].model_validate(arguments).model_dump(), None
except (ValidationError, TypeError, ValueError) as exc:
return None, str(exc)
|