Skip to content

unaiverse.uai.parse

This module turns a message into an ordered list of typed parts: prose, content blocks and replies. It implements the reading side of the protocol and draws nothing. Every failure degrades to text and no input makes it raise. One bad block becomes text and never affects the rest of the message. A world calls parse_message when it needs the structure of a message and the helpers below to pick a form or a reply out of the parts. The agent calls them on every message that carries a fence. Import every name from unaiverse.uai. The protocol is described in the package page.

Object Returns
parse_message The ordered parts of a message.
has_interactive_parts Whether the parts hold anything other than text.
find_form, newest_form The first or the last form spec of the parts.
find_reply The first reply spec of the parts.

parse_message

parse_message(text) -> list[dict]
Source code in unaiverse/uai/parse.py
def parse_message(text) -> list[dict]:
    """Parses a message into ordered parts.

    Args:
        text: The message, as it arrived on the wire.

    Returns:
        A list of parts. Prose is ``{"type": "text", "text"}``; a valid content block is
        ``{"type": "media" | "data" | "form" | "x", "spec", "alt"}``; a valid reply block is
        ``{"type": "reply", "spec": {"to", "values", ("raw")}}``; anything invalid degrades to
        ``{"type": "text", "text", "degraded": True, "errors": [...]}``.
    """
    parts = []
    for seg in extract_fences(text):
        if seg["kind"] == "prose":
            parts.append({"type": "text", "text": seg["text"]})
        else:
            parts.append(_block_to_part(seg))
    return parts

Parses a message into ordered parts. It extracts the fences with extract_fences, decodes each body with json.loads and validates the object with validate_block.

Argument Type Default Meaning
text str required The message as it arrived. A value that is not a str or an empty string gives [].

It returns a list[dict]. Each part has one of the shapes below.

Part Shape
Prose {"type": "text", "text": str}
Valid media, data or form block {"type", "spec": dict, "alt": str} with type equal to "media", "data" or "form" and spec equal to the normalized spec of validate_block
Valid experimental block (type starting with x-) {"type": "x", "spec": {"v", "type", "alt"}, "alt": str}
Valid reply block {"type": "reply", "spec": {"to", "values", "raw"?}, "alt": str}, where alt is the readable projection of the answer or "" when the block has none and raw is present only when the block carries usable texts
Degraded block {"type": "text", "text": str, "degraded": True, "errors": list[str]}

A degraded block keeps the order of the message. Its text depends on the failure.

Failure text of the part errors
Body over 8192 bytes The body cut to 8192 bytes. ["too_large"]
Body that is not JSON The raw body. ["json_invalid"]
Invalid block with a non-blank string alt The alt. The codes of validate_block, for example ["v_unsupported"].
Invalid block without a usable alt The raw body. The codes of validate_block, for example ["alt_missing"].
spec = build_form("Profile", fields, form_id="p1")
msg = "Hi.\n\n" + serialize_block(spec) + "\n\nThanks."
parse_message(msg)
# [{'type': 'text', 'text': 'Hi.'},
#  {'type': 'form', 'spec': {...the spec...}, 'alt': "Reply with lines 'field: value'. Fields: ..."},
#  {'type': 'text', 'text': 'Thanks.'}]

parse_message('```uai\n{"v":2,"type":"media","alt":"Future"}\n```')
# [{'type': 'text', 'text': 'Future', 'degraded': True, 'errors': ['v_unsupported']}]

parse_message('```uai\nnot json\n```')
# [{'type': 'text', 'text': 'not json', 'degraded': True, 'errors': ['json_invalid']}]

The protocol allows at most one form block per message. The parser does not enforce this limit and two valid forms give two form parts. newest_form then returns the second one and find_form the first.

has_interactive_parts

has_interactive_parts(parts: list[dict]) -> bool
Source code in unaiverse/uai/parse.py
def has_interactive_parts(parts: list[dict]) -> bool:
    """Tells whether a parsed message contains at least one non-text part."""
    return any(p["type"] != "text" for p in parts)

Returns True when a list of parts contains at least one part whose type is not "text". A degraded block counts as text.

Argument Type Default Meaning
parts list[dict] required The output of parse_message.
has_interactive_parts(parse_message("just words"))   # False
has_interactive_parts(parse_message(msg))            # True

find_form

find_form(parts: list[dict]) -> dict | None
Source code in unaiverse/uai/parse.py
def find_form(parts: list[dict]) -> dict | None:
    """Returns the first form spec of a parsed message, if any."""
    return next((p["spec"] for p in parts if p["type"] == "form"), None)

Returns the spec of the first form part or None when the parts hold no form.

Argument Type Default Meaning
parts list[dict] required The output of parse_message.

newest_form

newest_form(parts: list[dict]) -> dict | None
Source code in unaiverse/uai/parse.py
def newest_form(parts: list[dict]) -> dict | None:
    """Returns the last form spec of a parsed message, which is the one an answer refers to."""
    return next((p["spec"] for p in reversed(parts) if p["type"] == "form"), None)

Returns the spec of the last form part or None. The last form of a message is the one that an answer refers to. The agent calls it in uai_preprocess and uai_remember_form to find the form that its processor (or the person behind it) is answering.

Argument Type Default Meaning
parts list[dict] required The output of parse_message.

find_reply

find_reply(parts: list[dict]) -> dict | None
Source code in unaiverse/uai/parse.py
def find_reply(parts: list[dict]) -> dict | None:
    """Returns the first reply spec of a parsed message, if any."""
    return next((p["spec"] for p in parts if p["type"] == "reply"), None)

Returns the spec of the first reply part or None. The spec is {"to": str, "values": dict} with the key raw (a non-empty list[str]) when the block carries the words of the answer. The values are the ones received and have not been checked against any form. check_reply checks them.

Argument Type Default Meaning
parts list[dict] required The output of parse_message.
r = encode_reply(spec, {"height": 180, "diet": "veg"}, raw="height 180, veg")
find_reply(parse_message(r))
# {'to': 'p1', 'values': {'height': 180, 'diet': 'veg'}, 'raw': ['height 180, veg']}