Skip to content

unaiverse.uai.serialize

A block is written in canonical form: keys in a fixed order for each block type, no whitespace outside strings, non-ASCII characters written without escapes and no trailing newline inside the fence. The Python package and the JavaScript SDK therefore produce the same bytes for the same spec. This property lets the shared test vectors compare outputs as strings and lets two implementations agree on the size limit of a block. Import canonical_json, serialize_block and num_to_text from unaiverse.uai. The key-order tables are module constants that only this module reads. The protocol is described in the package page.

The order of the keys of a block follows its table. Keys outside the table come after them in alphabetical order. Because the validator drops unknown keys, a validated spec holds only keys of the table.

serialize_block({"v": 1, "type": "media", "alt": "A cat.", "mime": "image/jpeg",
                 "src": "https://example.org/cat.jpg"})
# '```uai\n{"v":1,"type":"media","src":"https://example.org/cat.jpg","mime":"image/jpeg","alt":"A cat."}\n```'

BLOCK_ORDER module-attribute

BLOCK_ORDER = {'media': ('v', 'type', 'src', 'mime', 'title', 'poster', 'alt'), 'data': ('v', 'type', 'chart', 'series', 'alt'), 'form': ('v', 'type', 'id', 'name', 'lang', 'fields', 'progress', 'aiHint', 'alt'), 'reply': ('v', 'kind', 'to', 'values', 'alt', 'raw'), 'x': ('v', 'type', 'alt')}

A dict that maps each kind of block to the tuple of its keys in order.

Kind Order
media v, type, src, mime, title, poster, alt
data v, type, chart, series, alt
form v, type, id, name, lang, fields, progress, aiHint, alt
reply v, kind, to, values, alt, raw
x (any type starting with x-) v, type, alt

FIELD_ORDER module-attribute

FIELD_ORDER = ('name', 'type', 'label', 'required', 'help', 'default', 'placeholder', 'maxLength', 'format', 'min', 'max', 'unit', 'options', 'ui')

The key order of an interactive field of a form: name, type, label, required, help, default, placeholder, maxLength, format, min, max, unit, options, ui. A section row is always written as {"type": "section", "label": ...} with no other key. In a select field max and min therefore come before options.

OPTION_ORDER module-attribute

OPTION_ORDER = ('value', 'label', 'help', 'media')

The key order of a select option: value, label, help, media.

SERIES_ORDER module-attribute

SERIES_ORDER = ('label', 'points')

The key order of a chart series: label, points.

num_to_text

num_to_text(x) -> str
Source code in unaiverse/uai/serialize.py
def num_to_text(x) -> str:
    """Renders a number as JavaScript does, so that generated text matches byte for byte.

    The difference that matters is the integral float: JavaScript prints 180, Python would print 180.0.
    """
    if isinstance(x, bool):
        return "true" if x else "false"
    if isinstance(x, int):
        return str(x)
    if isinstance(x, float):
        return str(int(x)) if math.isfinite(x) and x.is_integer() else repr(x)
    return str(x)

Writes a number as JavaScript writes it. Generated text such as the model instruction or the projection of an answer must match the JavaScript SDK byte for byte. The difference that matters is the integral float: JavaScript prints 180 where Python prints 180.0.

Argument Type Default Meaning
x any required The value to write.
Input Output
True, False "true", "false"
int str(x) (42 gives "42")
finite float with no fractional part the integer (180.0 gives "180")
other float repr(x) (0.1 gives "0.1")
anything else str(x)

A non-finite float follows repr and gives "nan", "inf" or "-inf". JavaScript, on the other hand, writes NaN and Infinity. Validated blocks never hold such values because the validator accepts only finite numbers.

canonical_json

canonical_json(spec: dict) -> str
Source code in unaiverse/uai/serialize.py
def canonical_json(spec: dict) -> str:
    """Returns the canonical JSON body (no fence) of a validated spec."""
    if spec.get("kind") == "reply":
        kind = "reply"
    elif isinstance(spec.get("type"), str) and spec["type"].startswith("x-"):
        kind = "x"
    else:
        kind = spec.get("type")
    order = BLOCK_ORDER.get(kind)
    if order is None:
        raise ValueError(f"Interact: cannot serialize block of type {spec.get('type', spec.get('kind'))}")

    out = _ordered(spec, order)
    if kind == "form":
        fields = []
        for f in spec["fields"]:
            if f.get("type") == "section":
                fields.append({"type": "section", "label": f["label"]})
                continue
            field = _ordered(f, FIELD_ORDER)
            if "options" in field:
                field["options"] = [_ordered(op, OPTION_ORDER) for op in field["options"]]
            fields.append(field)
        out["fields"] = fields
    if kind == "data":
        out["series"] = [_ordered(s, SERIES_ORDER) for s in spec["series"]]
    if kind == "reply":

        # The caller's insertion order is the contract for reply values
        out["values"] = dict(spec["values"])
    return json.dumps(_json_ready(out), ensure_ascii=False, separators=(",", ":"))

Returns the canonical JSON body of a validated spec without the fence.

Argument Type Default Meaning
spec dict required A spec that has passed validate_block. The function does not validate it.

The function picks the order from kind ("reply") or from type (x- prefix or a block type). It orders the fields and options of a form and the series of a chart with their own tables. The order of the values of a reply is part of the contract and the function keeps the order of the caller. Every integral float becomes an integer at any depth ({"b": 2.0} becomes {"b":2}). It writes non-ASCII characters as they are (ensure_ascii=False) with the separators , and :.

It returns a str. It raises ValueError with the message Interact: cannot serialize block of type ... when the spec has neither kind: "reply" nor a known or experimental type.

canonical_json({"v": 1, "kind": "reply", "to": "a", "values": {"b": 2.0, "a": 1}})
# '{"v":1,"kind":"reply","to":"a","values":{"b":2,"a":1}}'

encode_reply measures the size of a block on this string and the composer checks it against MAX_BLOCK_BYTES.

serialize_block

serialize_block(spec: dict) -> str
Source code in unaiverse/uai/serialize.py
def serialize_block(spec: dict) -> str:
    """Returns a validated spec as a fenced block, ready to sit inside a message."""
    return wrap_fence(canonical_json(spec))

Returns a validated spec as a fenced block ready to sit inside a message. It calls canonical_json and then wrap_fence and raises the same ValueError.

Argument Type Default Meaning
spec dict required A validated spec, for example the output of build_form.
serialize_block(build_chart("pie", [{"label": "Votes", "points": [["Yes", 12], ["No", 5]]}],
                            "Votes: Yes 12, No 5."))
# '```uai\n{"v":1,"type":"data","chart":"pie","series":[{"label":"Votes","points":[["Yes",12],["No",5]]}],"alt":"Votes: Yes 12, No 5."}\n```'

A world that keeps the spec of a form calls serialize_block on it to put the form in a message. This is the same string that compose_form returns.