Skip to content

unaiverse.uai.model

A language model never reads the JSON of a block. It reads the model view of the message. This view keeps the prose untouched and in its order and replaces every content block by its alt. A reply block has no instruction to show. A model reads it as one name: value line per value (the shape that the model itself is asked to write) followed by the latest words of the answer when the block carries them. The agent builds this view in uai_preprocess before its processor runs and the logger uses it to print a message on a terminal that cannot draw blocks. Import both functions from unaiverse.uai. The protocol is described in the package page.

The view has two caps that the protocol does not define. The contract bounds the size of one block but not of a whole message and the network accepts very large messages. MAX_BLOCKS_MODEL_VIEW (16) limits the number of rendered blocks and MAX_MODEL_VIEW_BYTES (65536) limits the size of the result. A peer therefore cannot make a model read an unbounded prompt.

to_model_text

to_model_text(text, max_blocks: int = MAX_BLOCKS_MODEL_VIEW, max_bytes: int = MAX_MODEL_VIEW_BYTES) -> str
Source code in unaiverse/uai/model.py
def to_model_text(text, max_blocks: int = MAX_BLOCKS_MODEL_VIEW, max_bytes: int = MAX_MODEL_VIEW_BYTES) -> str:
    """Returns what a model should read in place of a message that may carry protocol blocks.

    Args:
        text: The raw message.
        max_blocks: How many blocks are rendered before the rest is summarised in one line.
        max_bytes: Upper bound, in UTF-8 bytes, of the returned text.

    Returns:
        The message with every block replaced by its model rendering, prose and order untouched.
    """
    return parts_to_model_text(parse_message(text), max_blocks=max_blocks, max_bytes=max_bytes)

Returns the model view of a message (the text that a model reads in its place). It parses the message with parse_message and renders the parts with parts_to_model_text.

Argument Type Default Meaning
text str required The raw message. A message without blocks comes back as its prose.
max_blocks int 16 The maximum number of rendered blocks. The remaining ones are counted and summarized in one line [... N more blocks omitted]. Degraded blocks are text and do not count.
max_bytes int 65536 The size in UTF-8 bytes above which the rendering is cut on a character boundary. The line [... truncated] is then appended.

It returns a str. The parts are joined with one \n. A prose segment loses the blank lines that separated it from a fence. The function never raises on its input.

msg = "Hi.\n\n" + compose_form("Profile", fields, form_id="p1") + "\n\nThanks."
to_model_text(msg)
# "Hi.\nReply with lines 'field: value'. Fields: Height (number, in cm, between 50 and 250, required),
#  Diet (one of: Vegetarian, Omnivore, optional).\nThanks."

to_model_text(encode_reply(spec, {"height": 180, "diet": "veg"}, raw="height 180, veg"))
# 'height: 180\ndiet: veg\nheight 180, veg'

to_model_text('a\n```uai\n{"v":1,"type":"x-poll","alt":"A poll"}\n```\nb', max_blocks=0)
# 'a\nb\n[... 1 more blocks omitted]'

to_model_text("x" * 100, max_bytes=10)
# 'xxxxxxxxxx\n[... truncated]'

The cut applies to the rendering before the marker line is appended. The returned text can therefore exceed max_bytes by the 16 bytes of \n[... truncated].

parts_to_model_text

parts_to_model_text(parts: list, max_blocks: int = MAX_BLOCKS_MODEL_VIEW, max_bytes: int = MAX_MODEL_VIEW_BYTES) -> str
Source code in unaiverse/uai/model.py
def parts_to_model_text(parts: list, max_blocks: int = MAX_BLOCKS_MODEL_VIEW,
                        max_bytes: int = MAX_MODEL_VIEW_BYTES) -> str:
    """Same as to_model_text, for a caller that has already parsed the message."""
    out = []
    blocks = 0
    omitted = 0
    for p in parts:
        if p["type"] == "text":
            out.append(p["text"])
            continue
        blocks += 1
        if blocks > max_blocks:
            omitted += 1
            continue
        if p["type"] == "reply":

            # A reply reads as its values and, when the block carries them, as the latest words they were
            # read from: a partial answer keeps the phrasing (and whatever the values missed) visible,
            # and a failed one reads as its words alone, never as an empty line
            lines = "\n".join(f"{k}: {_value_to_text(v)}" for k, v in p["spec"]["values"].items())
            raw_texts = p["spec"].get("raw")
            raw = raw_texts[-1] if raw_texts else ""
            out.append(f"{lines}\n{raw}" if lines and raw else (lines or raw))
        else:
            out.append(p["alt"])
    if omitted > 0:
        out.append(f"[... {omitted} more blocks omitted]")

    rendered = "\n".join(out)
    if len(rendered.encode("utf-8")) > max_bytes:
        rendered = cut_to_bytes(rendered, max_bytes) + "\n[... truncated]"
    return rendered

Renders parts that the caller has already parsed. It returns the same text as to_model_text and avoids a second parse when the caller needs the parts too. The agent calls it because it also passes the same parts to newest_form to find the form.

Argument Type Default Meaning
parts list[dict] required The output of parse_message.
max_blocks int 16 As in to_model_text.
max_bytes int 65536 As in to_model_text.

Each part becomes text according to its type.

Part Rendering
text (prose or degraded block) Its text.
media, data, form, x Its alt.
reply One line name: value per entry of values in the order of the block, followed by the last text of raw on its own line when the block carries raw. A reply with no values renders as that text alone and a reply with neither renders as an empty line.

A reply value is written as the JavaScript SDK writes it: a list as its items joined with ,, None as an empty string, a bool as true or false, a dict as compact JSON and a float through num_to_text (180.0 becomes 180).

parts = parse_message(msg)
parts_to_model_text(parts) == to_model_text(msg)   # True