Spaces:
Sleeping
Sleeping
Download validation.py from andychoo98/WQF7002-Assignment1: direct link, hf CLI and curl.
- Browser
- Download file 1.59 kB
-
https://huggingface.co/spaces/andychoo98/WQF7002-Assignment1/resolve/main/validation.py
- Command line
-
hf download hf://spaces/andychoo98/WQF7002-Assignment1/validation.py
-
curl -L -o validation.py https://huggingface.co/spaces/andychoo98/WQF7002-Assignment1/resolve/main/validation.py
1.59 kB
| """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) | |