Skip to content

unaiverse.uai.alt

A model cannot fill a widget. It reads the alt of a form, a deterministic instruction that names each field with its type and constraints and asks for one field: value line per field. The reply interpreter then reads those lines back (rung labeled of interpret_reply). The instruction lists the options of a select by their label because a model writes words far more readily than identifiers. The interpreter maps each label back to its value. When the author of the form gives an aiHint, the hint replaces the whole instruction. build_form calls generate_form_alt whenever its alt argument is None. Import both functions from unaiverse.uai. The protocol is described in the package page and the wording comes from templates.

The instruction has this shape in English and in every unknown language:

[Step {step} of {total}. ]Reply with lines 'field: value'. Fields: {field}[, {field}]*.

The Italian shape is [Passo {step} di {total}. ]Rispondi con righe 'campo: valore'. Campi: {field}[, {field}]*. The strings are part of the contract. The shared test vectors pin them and the JavaScript SDK produces the same bytes.

describe_field

describe_field(f: dict, t: dict) -> str
Source code in unaiverse/uai/alt.py
def describe_field(f: dict, t: dict) -> str:
    """Describes one field for the instruction, in the descriptor order fixed by the contract."""
    d = []
    if f["type"] == "select":
        labels = [o["label"] for o in f["options"]]
        if f["max"] == 1:
            d.append(t["select_one"](labels))
        elif f.get("min") is not None and f["min"] > 0:
            d.append(t["select_many"](f["min"], f["max"], labels))
        elif f["max"] < len(f["options"]):
            d.append(t["select_many"](f.get("min", 0), f["max"], labels))
        else:
            d.append(t["select_some"](labels))
    else:
        d.append(t["types"][f["type"]])
    if f.get("unit"):
        d.append(t["unit"](f["unit"]))
    if f["type"] in ("number", "integer", "date"):
        if "min" in f and "max" in f:
            d.append(t["between"](f["min"], f["max"]))
        elif "min" in f:
            d.append(t["at_least"](f["min"]))
        elif "max" in f:
            d.append(t["at_most"](f["max"]))
    if "maxLength" in f:
        d.append(t["max_length"](f["maxLength"]))
    if f.get("format"):
        d.append(t["format"][f["format"]])
    d.append(t["required"] if f.get("required") else t["optional"])
    return f"{field_label(f)} ({', '.join(d)})"

Describes one interactive field as {label} ({descriptors}). The descriptors are joined with , in the order fixed by the protocol.

  1. The type word. A select with max 1 gives one of: L1, L2. A select with max greater than 1 gives {min} to {max} of: L1, L2 when min is above 0 or max is smaller than the number of options (with min defaulting to 0) and one or more of: L1, L2 otherwise. Every other type gives its word: text, long text, number, integer, yes or no or date YYYY-MM-DD.
  2. The unit: in {unit}.
  3. The range of a number, integer or date field: between {min} and {max}, at least {min} or at most {max}.
  4. The length: at most {maxLength} characters.
  5. The format: format email, format url or format phone.
  6. required when required is True and optional otherwise.

The help of the field is never part of the description.

Argument Type Default Meaning
f dict required One interactive field of a validated spec. A section row has no name and raises KeyError.
t dict required A language table of TEMPLATES, usually the second item returned by template_for.

It returns a str. The label falls back to the field name through field_label.

_, t = template_for("en")
describe_field({"name": "kids", "type": "integer", "label": "Children", "max": 4}, t)
# 'Children (integer, at most 4, optional)'
describe_field({"name": "extras", "type": "select", "label": "Extras", "max": 2, "options": [
    {"value": "b", "label": "Bike"}, {"value": "k", "label": "Kayak"}, {"value": "g", "label": "Guide"}]}, t)
# 'Extras (0 to 2 of: Bike, Kayak, Guide, optional)'

_, t = template_for("it")
describe_field({"name": "email", "type": "text", "label": "Email", "format": "email",
                "maxLength": 80, "required": True}, t)
# 'Email (testo, massimo 80 caratteri, formato email, obbligatorio)'

generate_form_alt

generate_form_alt(spec: dict) -> str
Source code in unaiverse/uai/alt.py
def generate_form_alt(spec: dict) -> str:
    """Returns the generated instruction for a validated form spec, honouring aiHint."""
    hint = spec.get("aiHint")
    if isinstance(hint, str) and hint.strip():
        return hint
    _, t = template_for(spec.get("lang"))
    head = t["progress"](spec["progress"][0], spec["progress"][1]) if "progress" in spec else ""
    fields = [describe_field(f, t) for f in interactive_fields(spec)]
    return f"{head}{t['intro']}{', '.join(fields)}."

Returns the instruction of a validated form. A non-blank aiHint is returned unchanged. Otherwise the function picks the language table from lang with template_for, writes the progress prefix when the spec has progress and lists every interactive field with describe_field. Section rows are left out.

Argument Type Default Meaning
spec dict required A validated form spec.

It returns a str. The function does not check the length. build_form raises UaiError with reason alt_too_long when the result exceeds 2000 characters.

spec = build_form("Trip", [
    {"type": "section", "label": "Who"},
    {"name": "email", "type": "text", "label": "Email", "format": "email", "maxLength": 80,
     "required": True, "help": "We never share it"},
    {"name": "day", "type": "date", "label": "Day", "min": "2026-01-01"},
    {"name": "meals", "type": "select", "label": "Meals", "max": 2,
     "options": [{"value": "l", "label": "Lunch"}, {"value": "d", "label": "Dinner"}]},
    {"name": "ok", "type": "bool", "label": "Insurance"},
], form_id="t", progress=(2, 3))
generate_form_alt(spec)
# "Step 2 of 3. Reply with lines 'field: value'. Fields: Email (text, at most 80 characters,
#  format email, required), Day (date YYYY-MM-DD, at least 2026-01-01, optional), Meals (one or
#  more of: Lunch, Dinner, optional), Insurance (yes or no, optional)."

The real result is one line. The comment wraps it for reading.