Skip to content

unaiverse.uai.draft

This module is the answer side of a form. While a person fills a widget, the webapp keeps a draft with the values typed so far by field name. Two renderings of a draft exist. The readable projection is the text that a person reads. It is a line such as Height: 180 cm; Diet: Vegetarian that names fields and options by their labels. The reply block is the string sent over the network. It is one uai block with kind: "reply" that carries the id of the form, the canonical values and the projection as its alt. encode_reply produces exactly the string that the widget of the webapp produces. A Python agent that answers a form in code therefore sends the same bytes as a person who fills the widget. The narrative guide is Interactive messages.

The package unaiverse.uai re-exports the three functions of the module and callers import them from there.

Object Role
encode_reply Turns values into the fenced reply block that answers a form.
project_draft Turns values into the readable projection.
project_value Turns one value into its readable text.
from unaiverse.uai import build_form, encode_reply

form = build_form("Profile", [
    {"name": "height", "type": "number", "label": "Height", "unit": "cm", "min": 50, "max": 250, "required": True},
    {"name": "diet", "type": "select", "label": "Diet",
     "options": [{"value": "veg", "label": "Vegetarian"}, {"value": "omni", "label": "Omnivore"}]}],
    form_id="p1")

print(encode_reply(form, {"height": 180.0, "diet": "veg", "x": 1}, raw="height 180, veg"))
```uai
{"v":1,"kind":"reply","to":"p1","values":{"height":180,"diet":"veg"},"alt":"Height: 180 cm; Diet: Vegetarian","raw":["height 180, veg"]}
```

encode_reply

encode_reply(spec: dict, values: dict, raw: str | list | None = None) -> str
Source code in unaiverse/uai/draft.py
def encode_reply(spec: dict, values: dict, raw: str | list | None = None) -> str:
    """Turns some values into the message that answers a form.

    Only the fields the form declares travel, and a value that fails its own type or constraint check is left
    out, so that the receiver reports it as missing rather than acting on it. A partial answer encodes fine:
    skipping is the way out of a form, not an error.

    What comes out is the shape of the contract (section 7): one block, carrying its own readable projection
    as ``alt``, which is the human rendering of a reply. A projection over the alt cap is cut to it, with no
    marker, so that every implementation produces the same bytes. When ``raw`` is given, the block also
    carries the words the values were read from, verbatim, as a list of texts, oldest first: an answer can
    be built across corrective rounds, and the list is the provenance of the values. The field is
    transparent (every receiver ignores it unless it asks for it), and it is what lets an answer that fell
    short still travel as one block, values and words together, instead of words beside a block.

    Args:
        spec: The validated form being answered.
        values: What was filled in, by field name.
        raw: The words the values were read from: the list of the contributing texts, oldest first (a bare
            string counts as a one-text list).

    Returns:
        The message to send.
    """
    accepted = {}
    for f in interactive_fields(spec):
        v = (values or {}).get(f["name"])
        if not _is_filled(v):
            continue
        result = check_canonical(f, v)
        if result.ok:
            accepted[f["name"]] = result.value
    projection = project_draft(spec, accepted)[:MAX_ALT_CHARS]
    block = {"v": PROTOCOL_VERSION, "kind": "reply", "to": spec["id"], "values": accepted}
    if projection:
        block["alt"] = projection
    raw_texts = [raw] if isinstance(raw, str) else list(raw) if isinstance(raw, (list, tuple)) else []
    raw_texts = [t for t in raw_texts if non_empty(t)]
    if raw_texts:
        block["raw"] = raw_texts

        # The words must never cost the values: a raw that pushes the fenced body past the block cap every
        # receiver enforces is trimmed to fit, oldest texts first, then by cutting the last one (dropped
        # entirely when even a stub cannot fit). A block whose VALUES alone exceed the cap is past raw's
        # reach and degrades on arrival as it always did
        while "raw" in block and len(canonical_json(block).encode("utf-8")) > MAX_BLOCK_BYTES:
            texts = block["raw"]
            if len(texts) > 1:
                block["raw"] = texts[1:]
                continue
            budget = len(texts[0].encode("utf-8")) // 2
            if budget < 16:
                del block["raw"]
            else:
                block["raw"] = [cut_to_bytes(texts[0], budget)]
    return serialize_block(block)

Turns values into the message that answers a form and returns it as a str that holds one fenced reply block and nothing else. The agent calls it when the answer of its processor satisfies a form (uai_postprocess in agent_basics). encode_partial calls it when the corrective rounds are over and the answer still falls short.

Argument Type Default Meaning
spec dict required The validated form being answered. Its id becomes to and its lang selects the words of the projection.
values dict or None required The canonical values by field name. None counts as {}.
raw str, list, tuple or None None The words from which the values were read. A string counts as a list of one text. A list holds the texts of the corrective rounds from the oldest to the newest. Blank entries and entries that are not strings are dropped.

The encoding follows these steps.

  1. Only the interactive fields of the form are looked up. Keys that the form does not declare are never sent.
  2. A value that is None, "" or [] counts as not filled and is left out.
  3. Each other value goes through check_canonical. A value that fails its type or a constraint is dropped without any error. The receiver then reports the field as missing instead of acting on a bad value.
  4. The projection of the accepted values becomes alt. A projection longer than 2000 characters is cut to that length with no marker. An empty projection leaves alt out of the block.
  5. The non-blank texts of raw, when any, become the raw key of the block.
  6. When raw pushes the canonical body past MAX_BLOCK_BYTES (8192 UTF-8 bytes), the oldest texts are dropped one at a time. When one text is left and still too long, it is cut repeatedly to half its UTF-8 length on a character boundary. When this halved budget falls under 16 bytes the raw key is removed. The values are never trimmed. A block whose values alone exceed the limit is emitted as it is and degrades on arrival.

The values keep the order of the fields in the form. Integral floats are written as integers (180.0 becomes 180). A partial answer encodes without any error because a person may leave fields empty.

age = build_form("Age", [{"name": "age", "type": "integer", "min": 0, "max": 120, "required": True}], form_id="a1")
encode_reply(age, {})
# '```uai\n{"v":1,"kind":"reply","to":"a1","values":{}}\n```'
encode_reply(age, {}, raw="I don't know")
# '```uai\n{"v":1,"kind":"reply","to":"a1","values":{},"raw":["I don\'t know"]}\n```'
encode_reply(age, {"age": 300})
# '```uai\n{"v":1,"kind":"reply","to":"a1","values":{}}\n```'   (300 is above max and is dropped)

With raw=["a" * 3000, "b" * 3000, "c" * 9000] the two oldest texts are dropped and the last one is cut to 4500 characters. The resulting message is 4590 characters long and still carries "values":{"age":42}.

project_draft

project_draft(spec: dict, values: dict) -> str
Source code in unaiverse/uai/draft.py
def project_draft(spec: dict, values: dict) -> str:
    """Returns the label-only line that shows what has been filled: form order, filled fields only."""
    _, t = template_for(spec.get("lang"))
    out = []
    for f in interactive_fields(spec):
        v = (values or {}).get(f["name"])
        if not _is_filled(v):
            continue
        out.append(f"{field_label(f)}: {project_value(f, v, t)}")
    return "; ".join(out)

Returns the readable projection of some values as a str. The fields follow the order of the form and only filled ones appear. Each one is written as label: value through field_label and project_value. The separator between two fields is ;. Values are not checked here and keys that the form does not declare are ignored.

Argument Type Meaning
spec dict The validated form. Its lang selects the words for booleans and the order of dates.
values dict or None The values by field name.
project_draft(form, {"height": 180, "diet": "veg"})
# 'Height: 180 cm; Diet: Vegetarian'

The corrective prompt of retry_prompt uses the same projection to restate what an answer already gave.

project_value

project_value(f: dict, v, t: dict) -> str
Source code in unaiverse/uai/draft.py
def project_value(f: dict, v, t: dict) -> str:
    """Renders one canonical value the way a human reads it."""
    if f["type"] == "select":
        labels = {o["value"]: o["label"] for o in f["options"]}
        if isinstance(v, list):
            return ", ".join(labels.get(x, str(x)) for x in v)
        return labels.get(v, str(v))
    if f["type"] == "bool":
        return t["yes"] if v else t["no"]
    if f["type"] in ("number", "integer"):
        return f"{num_to_text(v)} {f['unit']}" if f.get("unit") else num_to_text(v)
    if f["type"] == "date":
        year, month, day = str(v).split("-")
        return t["date"](year, month, day)
    return str(v)

Returns the readable text of one canonical value as a str.

Argument Type Meaning
f dict The validated field.
v any The canonical value.
t dict One of the tables of TEMPLATES.
Field type Rendering it en
select The label of the option. A list gives the labels joined by ,. A value without an option is written as it is. Red, x Red, x
bool The word of the language. Sì / No Yes / No
number, integer The number as JavaScript writes it, then a space and the unit when declared. 180 cm 180 cm
date Day first in Italian and month first in English. 03/04/2024 04/03/2024
text, textarea The string as typed.

The date row shows the ISO value 2024-04-03. A date value must be an ISO string because the function splits it on -. A value of another shape raises ValueError. Callers in the package pass only values that are already valid.