Skip to content

unaiverse.uai.compose

This module writes the blocks that a world or an agent puts in its messages. Its rule is "emit valid or emit nothing". A receiver draws an invalid block as its alt text with no widget. A content block without an alt reaches the chat bubble of a person as raw JSON. Every function here therefore validates what it builds with validate_block and raises UaiError instead of returning an invalid block. Import every name from unaiverse.uai. The module layout follows the JavaScript SDK and may change. The protocol itself is described in the package page and in Interactive messages.

Each block type has two functions. The build_ function returns the validated spec as a dict that the world keeps to check the answer later. The compose_ function returns the same spec as a fenced block that is ready to be concatenated with prose.

Object Returns
build_form, compose_form A form spec with its generated model instruction as a dict or as a fenced string.
build_media, compose_media A picture, video, audio or PDF block.
build_chart, compose_chart A data block with a bar, line or pie chart.
build_re_ask, re_ask A new form that asks again for only some fields of a form already sent.
gen_id A fresh form id.
guess_mime The MIME type of a URL from its extension.
truncate_outside_fences A message cut to a length without breaking a block.
UaiError The exception of every function above.

A world that asks a person for a rating writes the following code.

from unaiverse.uai import build_form, serialize_block

spec = build_form("Rating", [
    {"name": "stars", "type": "integer", "label": "Stars", "min": 1, "max": 5, "required": True},
    {"name": "note", "type": "textarea", "label": "Comment", "maxLength": 200},
], form_id="r1")
message = "How was the tour?\n\n" + serialize_block(spec)

The variable message then holds the following string.

How was the tour?

```uai
{"v":1,"type":"form","id":"r1","name":"Rating","fields":[{"name":"stars","type":"integer","label":"Stars","required":true,"min":1,"max":5},{"name":"note","type":"textarea","label":"Comment","maxLength":200}],"alt":"Reply with lines 'field: value'. Fields: Stars (integer, between 1 and 5, required), Comment (long text, at most 200 characters, optional)."}
```

UaiError

UaiError(message: str, element: int | None = None, reason: str | None = None)

Bases: Exception

Source code in unaiverse/uai/compose.py
def __init__(self, message: str, element: int | None = None, reason: str | None = None) -> None:
    super().__init__(message)
    self.element = element
    self.reason = reason

The exception raised when a block cannot be composed. It derives from Exception. Its message starts with uai: and names the failed block type and the reasons (for example uai: invalid form block (fields_invalid)).

Argument Type Default Meaning
message str required The text of the exception.
element int or None None The position of the element that failed. The Python composer never fills it and it is always None in the current version. The field exists for parity with the element compiler of the JavaScript SDK.
reason str or None None A machine-readable code of the failure.

The functions of this module raise it with these reasons.

reason Raised by When
The first error code of validate_block (for example fields_invalid, src_invalid, chart_invalid, name_duplicate:age) every build_ and compose_ function The spec breaks the protocol. The message lists every error code.
alt_too_long build_form, compose_form The generated instruction is longer than MAX_ALT_CHARS (2000) characters.
block_too_large every build_ and compose_ function The canonical JSON body exceeds MAX_BLOCK_BYTES (8192 bytes in UTF-8).
mime_unknown build_media, compose_media mime is missing and the extension of src names no known type.
no_fields build_re_ask, re_ask No field is left to ask.
from unaiverse.uai import UaiError, build_form

try:
    build_form("Empty", [])
except UaiError as e:
    print(e, e.reason)   # uai: invalid form block (fields_invalid) fields_invalid

element instance-attribute

element = element

The position of the failing element (int or None). It is always None when the error comes from this package.

reason instance-attribute

reason = reason

The code of the failure (str or None). Its values are those of the table above.

gen_id

gen_id(suffix: str | None = None) -> str
Source code in unaiverse/uai/compose.py
def gen_id(suffix: str | None = None) -> str:
    """Returns a fresh form id, optionally carrying a caller suffix (sanitised and truncated to fit)."""
    head = "".join(_RNG.choice(_ID_ALPHABET) for _ in range(6))
    if not suffix:
        return head
    tail = _ID_STRIP_RE.sub("", str(suffix))
    return f"{head}-{tail}"[:32] if tail else head

Returns a fresh form id made of six random characters from a to z and 0 to 9. The generator is a private random.Random instance of the module. Generating an id therefore never consumes the global random stream that a world may have seeded for its own logic.

Argument Type Default Meaning
suffix str or None None A readable suffix appended after a -. Every character outside [A-Za-z0-9_-] is removed and the result is cut to the 32 characters that a receiver accepts. An empty or fully removed suffix gives the bare six characters.

It returns a str that always satisfies the id rule of the protocol (1 to 32 characters of [A-Za-z0-9_-]).

gen_id()                    # 'zf2q3n'
gen_id("Quiz #1 for Bob")   # 'syc9zj-Quiz1forBob'

A form that goes to several recipients needs one id per recipient. One answer would otherwise mark every copy as answered.

guess_mime

guess_mime(src: str) -> str | None
Source code in unaiverse/uai/compose.py
def guess_mime(src: str) -> str | None:
    """Guesses a MIME type from the extension of a URL, or None when the URL does not say.

    None rather than a generic binary type on purpose: a media block whose MIME says nothing is valid for
    the protocol and undrawable for a renderer, which is the one outcome composing here refuses to produce.
    """
    if not isinstance(src, str):
        return None
    ext = src.rsplit("?", 1)[0].rsplit("#", 1)[0].rsplit(".", 1)[-1].lower() if "." in src else ""
    return _MIME_BY_EXTENSION.get(ext)

Returns the MIME type that the extension of a URL names or None when the extension names no known type. The function drops the query (?...) and the fragment (#...) before reading the extension and compares it in lower case. It knows jpg, jpeg, png, gif, webp, svg, mp4, webm, mov, mp3, wav, ogg, m4a and pdf.

Argument Type Default Meaning
src str required The URL. Any other type returns None.
guess_mime("https://x.org/a/b.PNG?x=1")   # 'image/png'
guess_mime("https://x.org/video")         # None

The function returns None rather than a generic binary type on purpose. A media block with a generic MIME type is valid for the protocol but no renderer can draw it. build_media refuses to produce it.

build_form

build_form(name: str, fields: list, form_id: str | None = None, lang: str | None = None, alt: str | None = None, ai_hint: str | None = None, progress=None) -> dict
Source code in unaiverse/uai/compose.py
def build_form(name: str, fields: list, form_id: str | None = None, lang: str | None = None,
               alt: str | None = None, ai_hint: str | None = None, progress=None) -> dict:
    """Builds and validates a form spec, generating the model instruction when the author gives none.

    Args:
        name: The form name, shown to a human and used to refer to the form.
        fields: The field dicts, in the wire vocabulary (name, type, label, required, options, ...).
        form_id: The id an answer refers to. Generated when omitted; a form sent to several recipients must
            use a different id per recipient, or one answer marks every copy answered.
        lang: Language tag, which selects the wording of the generated instruction and of the parsing.
        alt: The model instruction. Generated from the spec when omitted, which is the normal case.
        ai_hint: Replaces the whole generated instruction, for a form that needs a bespoke one.
        progress: A pair (step, total), when the form is one page of a sequence.

    Returns:
        The normalised, validated spec, to be kept by the world so that it can check the answer later.

    Raises:
        UaiError: If the spec is not valid, if the generated instruction is too long, or if the block
            exceeds the size a receiver accepts.
    """
    spec = {"v": PROTOCOL_VERSION, "type": "form", "id": form_id or gen_id(), "name": name}
    if lang is not None:
        spec["lang"] = lang
    spec["fields"] = list(fields or [])
    if progress is not None:
        spec["progress"] = list(progress)
    if ai_hint is not None:
        spec["aiHint"] = ai_hint

    # Validation needs an alt to be there; the generated one is built from the validated spec and put in after,
    # exactly as the JavaScript mirror does.
    spec["alt"] = alt if alt is not None else "?"
    validated = _validated(spec, "form")
    if alt is None:
        generated = generate_form_alt(validated)
        if len(generated) > MAX_ALT_CHARS:
            raise UaiError(f"uai: the generated instruction of form '{validated['id']}' is "
                                f"{len(generated)} characters, the limit is {MAX_ALT_CHARS}; shorten the "
                                f"labels, split the form, or pass your own alt", reason="alt_too_long")
        validated["alt"] = generated
    _check_size(validated, "form")
    return validated

Builds and validates a form block and returns its normalized spec. The world keeps this dict and later passes it to check_reply, interpret_reply or encode_reply.

Argument Type Default Meaning
name str required The name of the form, shown to a person and used to refer to the form. Non-empty, at most 120 characters.
fields list[dict] required The ordered fields in the wire vocabulary of the protocol. Each field is a dict with name, type and the keys of its type (see the table below). A {"type": "section", "label": "..."} row is a heading between fields. The list holds from 1 to 40 items and from 1 to 20 interactive fields.
form_id str or None None The id that the answer refers to (1 to 32 characters of [A-Za-z0-9_-]). None generates one with gen_id.
lang str or None None A language tag such as "it", "en" or "it-IT". It selects the wording of the generated instruction and the words that the tolerant parser accepts (see templates). An unknown language falls back to English. None leaves the key out and English applies.
alt str or None None The text that a model and a terminal read in place of the form. In the normal case it is None and generate_form_alt generates it from the spec.
ai_hint str or None None A complete instruction that replaces the generated one. It travels as the key aiHint (at most 2000 characters). When alt is None, the generated alt is this text.
progress pair of int or None None (step, total) with 1 <= step <= total when the form is one page of a sequence. The generated instruction then starts with Step {step} of {total}..

The keys of a field are those of the protocol.

Key Types Meaning
name all The key of the value in the answer: [A-Za-z_][A-Za-z0-9_]*, at most 64 characters, unique in the form.
type all text, textarea, number, integer, bool, date or select (see FIELD_TYPES). An unknown type becomes text.
label all The text that a person reads (at most 120 characters). The name stands in for a missing label.
required all True when the answer is incomplete without this field. Default False.
help all One line under the field (at most 240 characters). The model instruction leaves it out.
default all The pre-filled canonical value of the widget. It must be valid for the type. It never fills a field that a model left out.
placeholder, maxLength text, textarea The placeholder (at most 240 characters) and the maximum length (integer, at least 1).
format text email, url or tel (see TEXT_FORMATS).
min, max, unit number, integer The bounds (integers for integer) and a unit of at most 16 characters.
min, max date The bounds as ISO dates YYYY-MM-DD.
options select From 1 to 50 {"value", "label", "help"?, "media"?} entries. A label holds no comma and labels are unique after normalization. media is an https URL.
max, min select The maximum and minimum number of options that a person picks. max defaults to 1 (a single choice) and min to 0.
ui all known types A presentation hint. "buttons" draws the options of a select as buttons. Unknown hints are sent unchanged and renderers ignore them.

The function fills the defaults and drops every key that the protocol does not know. A select field gains "max": 1 when it has no max. It returns the normalized spec, a dict with the keys v, type, id, name, lang (when given), fields, progress (when given), aiHint (when given) and alt.

It raises UaiError in three cases: (1) the spec is invalid, (2) the generated instruction is longer than 2000 characters (reason alt_too_long) and (3) the block exceeds 8192 bytes (reason block_too_large).

spec = 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")
spec["alt"]
# "Reply with lines 'field: value'. Fields: Height (number, in cm, between 50 and 250, required),
#  Diet (one of: Vegetarian, Omnivore, optional)."
spec["fields"][1]["max"]   # 1

With lang="it" the same form has the instruction Rispondi con righe 'campo: valore'. Campi: Height (numero, in cm, tra 50 e 250, obbligatorio), Diet (una tra: Vegetarian, Omnivore, facoltativo).

compose_form

compose_form(name: str, fields: list, **kwargs) -> str
Source code in unaiverse/uai/compose.py
def compose_form(name: str, fields: list, **kwargs) -> str:
    """Builds a form and returns it as a fenced block. See build_form for the arguments."""
    return serialize_block(build_form(name, fields, **kwargs))

Builds a form with build_form and returns it serialized by serialize_block. It accepts the same arguments (form_id, lang, alt, ai_hint and progress as keywords) and raises the same errors. Use it when the world does not need the spec afterwards (for example for a form whose answer the world never checks).

compose_form("Profile", fields, form_id="p1")
# ```uai
# {"v":1,"type":"form","id":"p1","name":"Profile","fields":[{"name":"height","type":"number",
#  "label":"Height","required":true,"min":50,"max":250,"unit":"cm"},{"name":"diet","type":"select",
#  "label":"Diet","max":1,"options":[{"value":"veg","label":"Vegetarian"},{"value":"omni",
#  "label":"Omnivore"}]}],"alt":"Reply with lines 'field: value'. Fields: ..."}
# ```

The real output is one line of JSON between the two fences. The comment wraps it for reading.

build_media

build_media(src: str, alt: str, mime: str | None = None, title: str | None = None, poster: str | None = None) -> dict
Source code in unaiverse/uai/compose.py
def build_media(src: str, alt: str, mime: str | None = None, title: str | None = None,
                poster: str | None = None) -> dict:
    """Builds and validates a media spec. The source must be an https URL, and alt is what a model reads."""
    guessed = mime or guess_mime(src)
    if guessed is None:
        raise UaiError(f"uai: cannot tell the MIME type of '{src}' from its URL; pass mime= "
                            f"(a media block that does not say what it carries cannot be drawn)",
                            reason="mime_unknown")
    spec = {"v": PROTOCOL_VERSION, "type": "media", "src": src, "mime": guessed}
    if title is not None:
        spec["title"] = title
    if poster is not None:
        spec["poster"] = poster
    spec["alt"] = alt
    validated = _validated(spec, "media")
    _check_size(validated, "media")
    return validated

Builds and validates a media block that shows a picture, a video, an audio file or a document.

Argument Type Default Meaning
src str required The address of the content. Only https URLs with a host are valid. http:, data: and javascript: URLs make the block invalid.
alt str required The text that a model, a terminal and a screen reader get in place of the media. Non-empty, at most 2000 characters.
mime str or None None The MIME type, for example image/png, video/mp4, audio/mpeg, application/pdf, video/youtube or video/vimeo. None guesses it from src with guess_mime. The spec stores it in lower case.
title str or None None A caption or the title of a click-to-load preview (at most 120 characters).
poster str or None None The https URL of a preview image.

It returns the spec with the keys v, type, src, mime, title and poster (when given) and alt. It raises UaiError with reason mime_unknown when no MIME type is given or guessed. A spec that breaks the protocol raises it with the first validation error (src_invalid, mime_invalid, title_invalid, poster_invalid, alt_missing or alt_too_long) and an oversized block with block_too_large.

build_media("https://example.org/cat.jpg", "A cat on a sofa.")
# {'v': 1, 'type': 'media', 'src': 'https://example.org/cat.jpg', 'mime': 'image/jpeg',
#  'alt': 'A cat on a sofa.'}

compose_media

compose_media(src: str, alt: str, **kwargs) -> str
Source code in unaiverse/uai/compose.py
def compose_media(src: str, alt: str, **kwargs) -> str:
    """Builds a media block and returns it as a fenced block. See build_media for the arguments."""
    return serialize_block(build_media(src, alt, **kwargs))

Builds a media block with build_media and returns it as a fenced block. The keywords mime, title and poster are passed on to build_media.

compose_media("https://example.org/cat.jpg", "A cat on a sofa.")
# ```uai
# {"v":1,"type":"media","src":"https://example.org/cat.jpg","mime":"image/jpeg","alt":"A cat on a sofa."}
# ```

build_chart

build_chart(chart: str, series: list, alt: str) -> dict
Source code in unaiverse/uai/compose.py
def build_chart(chart: str, series: list, alt: str) -> dict:
    """Builds and validates a chart spec. A caption belongs in the prose beside it: the block carries none."""
    spec = {"v": PROTOCOL_VERSION, "type": "data", "chart": chart, "series": list(series or []), "alt": alt}
    validated = _validated(spec, "data")
    _check_size(validated, "data")
    return validated

Builds and validates a data block that draws a chart. The block carries data only. Any caption belongs in the prose beside it.

Argument Type Default Meaning
chart str required The kind of chart: "bar", "line" or "pie" (see CHART_KINDS).
series list[dict] required From 1 to 10 series. Each one is {"label": str, "points": [[x, y], ...]} with at most 500 points. The x of a point is a string or a number and its y is a finite number. Other keys of a series are dropped.
alt str required The textual version of the chart for a model or a terminal. Non-empty, at most 2000 characters. A good alt lists the values.

It returns the spec {"v", "type": "data", "chart", "series", "alt"}. It raises UaiError with chart_invalid, series_invalid, series_item_invalid, point_invalid, alt_missing, alt_too_long or block_too_large.

compose_chart

compose_chart(chart: str, series: list, alt: str) -> str
Source code in unaiverse/uai/compose.py
def compose_chart(chart: str, series: list, alt: str) -> str:
    """Builds a chart and returns it as a fenced block. See build_chart for the arguments."""
    return serialize_block(build_chart(chart, series, alt))

Builds a chart with build_chart and returns it as a fenced block.

compose_chart("bar", [{"label": "Rain", "points": [["Mon", 3], ["Tue", 0.5]]}],
              "Rain in mm: Mon 3, Tue 0.5.")
# ```uai
# {"v":1,"type":"data","chart":"bar","series":[{"label":"Rain","points":[["Mon",3],["Tue",0.5]]}],"alt":"Rain in mm: Mon 3, Tue 0.5."}
# ```

build_re_ask

build_re_ask(spec: dict, only: list | None = None, form_id: str | None = None, lang: str | None = None, progress=None) -> dict
Source code in unaiverse/uai/compose.py
def build_re_ask(spec: dict, only: list | None = None, form_id: str | None = None, lang: str | None = None,
                 progress=None) -> dict:
    """Asks again for a form that was not satisfied, keeping only the fields still worth asking about.

    This is what a world does with what it learns from an answer: the fields nobody said anything about and
    the ones whose value it could not accept are exactly ``event.missing + list(event.issues)``. A form left
    with a single field is also the easiest one to answer, since a bare value is enough for it.

    Args:
        spec: The validated form that was asked the first time.
        only: The field names to ask again, or None for all of them. Section rows are not carried over.
        form_id: The id of the new question. Generated when omitted, and it must differ from the first, or
            an answer to one would look like an answer to the other.
        lang: Language of the new question, defaulting to the one of the original.
        progress: A pair (step, total), when the re-ask is one page of a sequence.

    Returns:
        The validated spec of the new form.

    Raises:
        UaiError: If nothing is left to ask.
    """
    fields = [dict(f) for f in interactive_fields(spec) if only is None or f["name"] in only]
    if len(fields) == 0:
        raise UaiError(f"uai: nothing left to ask of form '{spec.get('id')}'", reason="no_fields")
    return build_form(spec.get("name", "form"), fields, form_id=form_id or gen_id(),
                      lang=lang if lang is not None else spec.get("lang"), progress=progress)

Builds a new form that asks again for the fields of a form whose answer was incomplete or refused. A ReplyEvent names the fields to ask again. event.missing + list(event.issues) holds the required fields that nobody answered and the fields whose value was refused. A form left with one field is the easiest to answer because a bare value is enough for it (rung bare of interpret_reply).

Argument Type Default Meaning
spec dict required The validated spec of the form asked the first time.
only list[str] or None None The names of the fields to keep (their order does not matter). The new form lists them in the order of spec. None keeps every interactive field. Section rows are never carried over.
form_id str or None None The id of the new form. None generates one. With the same id as the first form an answer to one form would look like an answer to the other.
lang str or None None The language of the new form. None keeps the language of spec.
progress pair of int or None None (step, total) when the new form is one page of a sequence.

It returns the validated spec of the new form with the same name and a freshly generated alt. The aiHint and the custom alt of the original are not carried over. It raises UaiError with reason no_fields when no field is left. Any other failure raises the errors of build_form.

event = interpret_reply("diet: omni", [spec])    # height is required and missing
new_spec = build_re_ask(spec, only=event.missing + list(event.issues), form_id="p2")
new_spec["alt"]
# "Reply with lines 'field: value'. Fields: Height (number, in cm, between 50 and 250, required)."

re_ask

re_ask(spec: dict, only: list | None = None, **kwargs) -> str
Source code in unaiverse/uai/compose.py
def re_ask(spec: dict, only: list | None = None, **kwargs) -> str:
    """Asks again, as a fenced block ready to sit in a message. See build_re_ask for the arguments."""
    return serialize_block(build_re_ask(spec, only=only, **kwargs))

Builds the new form with build_re_ask and returns it as a fenced block. The keywords form_id, lang and progress are passed on to build_re_ask.

re_ask(spec, only=["height"], form_id="p2")
# ```uai
# {"v":1,"type":"form","id":"p2","name":"Profile","fields":[{"name":"height","type":"number","label":"Height","required":true,"min":50,"max":250,"unit":"cm"}],"alt":"Reply with lines 'field: value'. Fields: Height (number, in cm, between 50 and 250, required)."}
# ```

truncate_outside_fences

truncate_outside_fences(text, max_chars: int) -> str
Source code in unaiverse/uai/compose.py
def truncate_outside_fences(text, max_chars: int) -> str:
    """Shortens a message without ever cutting inside a fence.

    A partial fence is not a block any more: the receiver shows the leftover JSON as prose. So when the cut
    would fall inside a block, the whole block goes, together with what follows it.
    """
    if not isinstance(text, str) or max_chars is None or max_chars <= 0 or len(text) <= max_chars:
        return text
    cut = max_chars
    for start, end in fence_spans(text):
        if start < cut < end:
            cut = start
            break
    return text[:cut].rstrip()

Cuts a message to at most max_chars characters without cutting inside a block. A block cut in half is no longer a block and the receiver would show its leftover JSON as prose. When the cut falls inside a block, the function removes the whole block and everything after it. Trailing whitespace of the result is removed.

Argument Type Default Meaning
text str required The message. Any other type is returned unchanged.
max_chars int required The maximum length in characters. None, zero or a negative value returns text unchanged.

It returns the shortened str. A text that already fits comes back as it is.

msg = "Hi.\n\n" + compose_form("Profile", fields, form_id="p1") + "\n\nThanks."
truncate_outside_fences(msg, 10)   # 'Hi.'
truncate_outside_fences(msg, 0)    # msg, unchanged

A world calls it when a channel imposes a length limit on its messages. A limit of zero disables the cut and does not empty the message.