PythiloLesson 6 of 12 · progress kept in this browser

Guided generation

Foundation Models can do better than asking for JSON and hoping. In Swift you mark a struct @Generable, and describe its properties with @Guide: a description, and constraints such as a range of numbers or a fixed set of choices. The framework then guides the model as it writes, so the reply always decodes into that struct.

The same idea works anywhere: describe the type once, and derive both the instructions for the model and the validation of its reply from that one description. In Python a dataclass can carry the description in its fields' metadata.

from dataclasses import dataclass, field
from dataclasses import fields

@dataclass
class Tag:
    name: str = field(metadata={
        "description": "one word"})

for f in fields(Tag):
    print(f.name, f.type.__name__,
          f.metadata["description"])

A cloud model without guided output still needs the validation half.

Your task

Write schema(cls) returning, for each dataclass field, name -> {"type": the type's __name__, "description": metadata description or ""} plus "choices" and "range" when the metadata has them. Write validate(cls, data) returning cls(...) built from the fields (extra keys ignored), or raising ValueError naming every field that is missing, of the wrong type (type(value) is the field type), outside choices, or outside the inclusive range.