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
¶
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
The position of the failing element (int or None). It is always None when the error comes from this package.
The code of the failure (str or None). Its values are those of the table above.
gen_id
¶
Source code in unaiverse/uai/compose.py
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_-]).
A form that goes to several recipients needs one id per recipient. One answer would otherwise mark every copy as answered.
guess_mime
¶
Source code in unaiverse/uai/compose.py
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. |
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
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
¶
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
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
¶
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
¶
Source code in unaiverse/uai/compose.py
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
¶
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
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
¶
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
¶
Source code in unaiverse/uai/compose.py
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.