Skip to content

unaiverse.uai.interpret

A form can be answered in many ways. The widget of the webapp sends a reply block. A person at a terminal types height: 180 or just 180 when the form has one field. A language model writes lines in the shape that the alt of the form asked for or a line of comma-separated values. Whoever wrote the text, interpret_reply reads it with the same code and returns one normalised ReplyEvent. It needs the pending forms of the conversation (the validated specs that this peer has received and not answered yet) ordered from the oldest to the newest. The narrative guide is Interactive messages.

The interpreter tries five readings in order and the first that matches wins. The contract calls them the rungs of the tolerance ladder.

Rung via Matches when Needs pending forms
1 block The message carries a valid reply block. No
2 labeled At least one key: value pair names a field of a pending form. Yes
3 bare The newest pending form has one interactive field and the whole text coerces to its type. Yes
4 csv One line of 2 or more comma-separated values coerces field by field to the newest pending form. Yes
5 freetext Nothing above matched. The text is never dropped. No

Callers import from unaiverse.uai. The package re-exports ReplyEvent, interpret_reply, parse_reply, check_reply, apply_canonical and scan_labeled. The two patterns NEXT_KEY_RE and TRAILING_RE are internal to the labeled rung.

Object Role
ReplyEvent The normalised answer: form, values, missing fields, issues, raw words, rung, duplicate flag.
interpret_reply Runs the ladder on one text.
parse_reply Reads only a reply block. A world that ignores free text uses it.
check_reply Re-checks the values of a reply against the form that asked for them.
apply_canonical Type-checks canonical values against a form.
scan_labeled Finds the key: value pairs of one form in a text.
from unaiverse.uai import build_form, interpret_reply

form = 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")

interpret_reply("height: 180 cm\ndiet: Vegetarian", pending=[form]).to_dict()
# {'kind': 'reply', 'to': 'p1', 'name': 'Profile', 'values': {'height': 180.0, 'diet': 'veg'},
#  'missing': [], 'issues': {}, 'raw': 'height: 180 cm\ndiet: Vegetarian', 'via': 'labeled', 'duplicate': False}

ReplyEvent dataclass

ReplyEvent(to: str | None = None, name: str | None = None, values: dict = dict(), missing: list = list(), issues: dict = dict(), raw: str = '', via: str = VIA_FREETEXT, duplicate: bool = False, kind: str = 'reply')

The answer event of the contract (section 5.3) as a frozen dataclass. A world reads it without modifying it, for example with event.values["height"] or "height" in event.missing. Because every field has a default, ReplyEvent() is an empty free-text event.

Field Type Default Meaning
to str or None None The id of the form that the text answers. None for a free text.
name str or None None The name of that form. None for a free text and for a block that answers a form missing from pending.
values dict {} The accepted canonical values by field name. A value read from text for a number or integer field is a float (42.0).
missing list[str] [] The required fields that the answer did not address. The list follows the order of the form. A field with an issue is never listed here.
issues dict[str, str] {} The fields whose value was rejected, each with its reason from the closed list (see coerce). These fields are absent from values.
raw str "" The words of the author. It is the last text of the raw list for a block that carries one and the whole incoming message in every other case.
via str "freetext" The rung that matched: one of VIA_BLOCK, VIA_LABELED, VIA_BARE, VIA_CSV and VIA_FREETEXT.
duplicate bool False True when to is in the answered ids given to the interpreter. A person who wants to change an answer answers the form again. The world decides what a duplicate means.
kind str "reply" Always "reply". It exists to make to_dict match the contract.

to_dict

to_dict() -> dict
Source code in unaiverse/uai/interpret.py
def to_dict(self) -> dict:
    """Returns the event as a plain dict, in the field order of the contract."""
    d = asdict(self)
    return {"kind": d.pop("kind"), **d}

Returns the event as a plain dict in the shape of the shared test vectors (kind first and the other fields in declaration order). The lists and dicts are copies.

ReplyEvent().to_dict()
# {'kind': 'reply', 'to': None, 'name': None, 'values': {}, 'missing': [], 'issues': {}, 'raw': '',
#  'via': 'freetext', 'duplicate': False}

interpret_reply

interpret_reply(text, pending=None, answered=None, lang=None) -> ReplyEvent
Source code in unaiverse/uai/interpret.py
def interpret_reply(text, pending=None, answered=None, lang=None) -> ReplyEvent:
    """Interprets an incoming text as an answer to one of the pending forms.

    Args:
        text: The raw message, as it arrived.
        pending: Validated form specs, oldest first (the ones this peer has been asked).
        answered: Form ids already answered, used to flag a duplicate.
        lang: Fallback language, used when a spec declares none.

    Returns:
        A ReplyEvent. An unrecognisable text is never dropped: it comes back as a freetext event.
    """
    raw = text if isinstance(text, str) else ""
    pending = [s for s in (pending or []) if s]
    answered = set(answered or [])
    newest_first = list(reversed(pending))
    parts = parse_message(raw)
    prose = "\n".join(p["text"] for p in parts if p["type"] == "text").strip()

    # Rung 1: canonical block. When the block carries the words it was read from, the LAST of them is the
    # raw of the event (the author's most recent words), not the wire text around the block; a block
    # without them keeps the message text as before (validation only ever stores a non-empty list)
    reply = find_reply(parts)
    if reply is not None:
        event_raw = reply["raw"][-1] if "raw" in reply else raw
        spec = next((s for s in pending if s.get("id") == reply["to"]), None)
        if spec is None:
            return ReplyEvent(to=reply["to"], name=None, values=dict(reply["values"]), raw=event_raw,
                              via=VIA_BLOCK, duplicate=reply["to"] in answered)
        values, issues = apply_canonical(spec, reply["values"])
        return _finish(spec, values, issues, event_raw, VIA_BLOCK, answered)

    if len(newest_first) == 0 or prose == "":
        return _freetext(raw)

    # Rung 2: labeled lines, the pending spec with the most recognised keys wins
    best = None
    for spec in newest_first:
        found = scan_labeled(prose, spec)
        if len(found) == 0:
            continue
        if best is None or len(found) > len(best[1]):
            best = (spec, found)
    if best is not None:
        spec, found = best
        spec_lang = spec.get("lang") or lang
        values, issues = {}, {}
        for f in interactive_fields(spec):
            written = found.get(f["name"])
            if written is None or written == "":
                continue
            result = coerce_text(f, written, lang=spec_lang, allow_decimal_comma=True)
            if result.ok:
                values[f["name"]] = result.value
            else:
                issues[f["name"]] = result.reason
        return _finish(spec, values, issues, raw, VIA_LABELED, answered)

    # Rungs 3 and 4 only look at the newest pending form
    spec = newest_first[0]
    fields = interactive_fields(spec)
    spec_lang = spec.get("lang") or lang

    # Rung 3: single-field form, the whole text is the value. A type mismatch is not a match, because a line
    # of chat is not an answer to a number; a constraint failure is a match, and it is reported.
    if len(fields) == 1:
        f = fields[0]
        result = coerce_text(f, prose, lang=spec_lang, allow_decimal_comma=True)
        if result.ok:
            return _finish(spec, {f["name"]: result.value}, {}, raw, VIA_BARE, answered)
        if result.reason not in (ISSUE_TYPE, ISSUE_UNKNOWN_OPTION):
            return _finish(spec, {}, {f["name"]: result.reason}, raw, VIA_BARE, answered)

    # Rung 4: positional csv, at least two items, at most one per field, every item type-coercing
    if "\n" not in prose:
        items = [x.strip() for x in prose.split(",")]
        if 2 <= len(items) <= len(fields) and all(items):
            values, issues, typed = {}, {}, True
            for i, written in enumerate(items):
                f = fields[i]
                result = coerce_text(f, written, lang=spec_lang, allow_decimal_comma=False)
                if result.ok:
                    values[f["name"]] = result.value
                elif result.reason in (ISSUE_TYPE, ISSUE_UNKNOWN_OPTION):
                    typed = False
                else:
                    issues[f["name"]] = result.reason
            if typed:
                return _finish(spec, values, issues, raw, VIA_CSV, answered)

    # Rung 5
    return _freetext(raw)

Reads an incoming text as an answer to one of the pending forms and returns a ReplyEvent. It never raises and never returns None. A text that answers no form comes back as a freetext event.

Argument Type Default Meaning
text any required The message as it arrived. A value that is not a str is read as "".
pending list[dict] or None None Validated form specs ordered from the oldest. Empty entries (None, {}) are skipped.
answered iterable of str or None None Form ids already answered. They only affect duplicate.
lang str or None None Fallback language for a spec without lang. It selects the boolean words and the date shapes of rungs 2 to 4.

The interpreter first parses the message with parse_message. The prose that rungs 2 to 4 read is the text of every text part joined with newlines and stripped. A degraded block counts as text and a valid block does not.

Rung 1, block. The first valid reply block of the message wins over everything else in it. The prose around the block is ignored. The interpreter scans the pending specs from the oldest and looks for the one whose id equals to. When it finds one, the values go through apply_canonical: unknown keys are dropped, wrong types and violated constraints go to issues and missing required fields go to missing. When no pending spec has that id, the event carries to, name=None and the values exactly as received and unchecked. Such values are untrusted JSON and a world passes them through check_reply against its own copy of the form. raw is the last text of the raw list of the block when it has one and the whole message otherwise.

from unaiverse.uai import wrap_fence

reply = wrap_fence('{"v":1,"kind":"reply","to":"zz","values":{"evil":"<x>"}}')
interpret_reply(reply, pending=[form], answered=["zz"])
# ReplyEvent(to='zz', name=None, values={'evil': '<x>'}, missing=[], issues={}, raw=reply, via='block',
#            duplicate=True, kind='reply')

When pending is empty or the prose is empty, the ladder stops here with a freetext event. A message made only of a form block is therefore never an answer.

Rung 2, labeled. scan_labeled runs on the prose against every pending spec from the newest to the oldest. The spec with the most recognised keys wins and the newest one wins a tie. Each value found is read with coerce_text in the language of the spec (or lang) with the decimal comma allowed. An empty value counts as not written. The other pending forms are ignored.

city = build_form("City", [{"name": "city", "type": "text", "label": "City"}], form_id="c1")
interpret_reply("city: Pisa", pending=[form, city]).via        # 'labeled', to 'c1'
interpret_reply("Height: 999", pending=[form]).issues          # {'height': 'above_max'}, missing []
interpret_reply("height: 180,5", pending=[form]).values        # {'height': 180.5}

Rung 3, bare. This rung and the next look only at the newest pending form. When that form has exactly one interactive field, the whole prose is coerced as its value. A type failure (type, unknown_option) means that the text is not an answer and the interpreter moves to the next rung. A constraint failure (above_max, too_long, ...) means that the text is an answer with an issue. A one-field text form accepts any prose at this rung.

age = build_form("Age", [{"name": "age", "type": "integer", "min": 0, "max": 120, "required": True}], form_id="a1")
interpret_reply("42", pending=[age])      # via 'bare', values {'age': 42.0}
interpret_reply("200", pending=[age])     # via 'bare', issues {'age': 'above_max'}
interpret_reply("forty", pending=[age])   # via 'freetext'
interpret_reply("Pisa", pending=[city, form]).via   # 'freetext': the newest form has two fields

Rung 4, csv. The prose must be a single line. It is split on commas into items that are stripped. The rung applies when there are at least two items, no more items than interactive fields and no empty item. Item i is coerced as the value of field i with the decimal comma disabled. Every item must pass the type check. Constraint failures still match and go to issues. Fields after the last item are left out and appear in missing when required.

interpret_reply("180, omni", pending=[form]).values   # {'height': 180.0, 'diet': 'omni'}, via 'csv'

Rung 5, freetext. Any other text gives ReplyEvent(to=None, name=None, values={}, raw=text, via="freetext"). The world handles it as ordinary chat.

parse_reply

parse_reply(text, spec: dict | None = None) -> ReplyEvent | None
Source code in unaiverse/uai/interpret.py
def parse_reply(text, spec: dict | None = None) -> ReplyEvent | None:
    """Reads a canonical reply block out of a text, the answer a widget produces.

    Args:
        text: The raw message.
        spec: The form spec this text should answer, when the world still has it. Given one, values are
            type-checked and constraint-checked, and required fields that are absent are reported as missing.

    Returns:
        A ReplyEvent, or None when the text carries no reply block (a freetext answer, which the world handles
        with its own fallback).
    """
    if not isinstance(text, str) or find_reply(parse_message(text)) is None:
        return None
    return interpret_reply(text, pending=[spec] if spec else None)

Reads only the reply block of a text. It returns None when text is not a str or carries no valid reply block. Otherwise it returns the event of rung 1. A world calls it when it handles free text in its own way and only needs the answers sent by the widget.

Argument Type Default Meaning
text any required The raw message.
spec dict or None None The form that the text should answer. With it the values are type-checked, constraint-checked and completed with missing. Without it they pass through unchecked with name=None. A spec whose id differs from to behaves like no spec.
parse_reply("no block", form)   # None

check_reply

check_reply(spec: dict, values: dict) -> tuple[dict, list, dict]
Source code in unaiverse/uai/interpret.py
def check_reply(spec: dict, values: dict) -> tuple[dict, list, dict]:
    """Re-verifies the values of a reply against the form that asked for them.

    This is what a world calls on values that came from a peer: they are attacker-controlled JSON until they
    have been through here. Keys the form does not declare are dropped (contract, section 3.6).

    Returns:
        A tuple ``(values, missing, issues)``: the accepted canonical values, the required fields that were not
        answered, and the fields whose value violates the spec, by reason.
    """
    checked, issues = apply_canonical(spec, values if isinstance(values, dict) else {})
    missing = [f["name"] for f in interactive_fields(spec)
               if f.get("required") and f["name"] not in checked and f["name"] not in issues]
    return checked, missing, issues

Re-verifies reply values against the form that asked for them. Values that come from a peer are attacker-controlled JSON until they pass here. A world calls it on event.values when the event did not come from a known pending spec and on any values it receives through another path.

Argument Type Meaning
spec dict The validated form.
values any The values to check. Anything that is not a dict is treated as {}.

The return value is a tuple (values, missing, issues). values holds the accepted canonical values and drops the keys that the form does not declare. missing lists the required fields absent from both values and issues. issues maps each rejected field to its reason.

check_reply(form, {"height": "180", "diet": "zzz", "junk": 1})
# ({}, [], {'height': 'type', 'diet': 'unknown_option'})

apply_canonical

apply_canonical(spec: dict, incoming: dict) -> tuple[dict, dict]
Source code in unaiverse/uai/interpret.py
def apply_canonical(spec: dict, incoming: dict) -> tuple[dict, dict]:
    """Type-checks the canonical values of a reply block against a known spec, dropping the unknown keys."""
    values, issues = {}, {}
    for f in interactive_fields(spec):
        if f["name"] not in incoming:
            continue
        result = check_canonical(f, incoming[f["name"]])
        if result.ok:
            values[f["name"]] = result.value
        else:
            issues[f["name"]] = result.reason
    return values, issues

Type-checks canonical values against a form with check_canonical and returns the tuple (values, issues). Only the interactive fields of the spec are looked up in incoming. Every other key is dropped. A key that is present with a bad value goes to issues. It does not compute missing. check_reply adds that.

apply_canonical(form, {"height": 12, "diet": "no"})
# ({}, {'height': 'below_min', 'diet': 'unknown_option'})

scan_labeled

scan_labeled(text: str, spec: dict) -> dict
Source code in unaiverse/uai/interpret.py
def scan_labeled(text: str, spec: dict) -> dict:
    """Finds the "key: value" pairs of one spec in a text.

    A key (field name or label, whitespace-insensitive and case-insensitive) separates only at the start of the
    text, after a newline, or after a comma or semicolon, and only when followed by a colon.

    Returns:
        A dict mapping field name to the raw value string that was written for it.
    """
    fields = interactive_fields(spec)
    keys = []
    for f in fields:
        keys.append((f["name"], f))
        label = field_label(f)
        if normalize_label(label) != normalize_label(f["name"]):
            keys.append((label, f))

    # Longer keys first, so that "Nome completo" beats "Nome" at the same position
    keys.sort(key=lambda item: len(item[0]), reverse=True)

    matches = []
    for key, f in keys:
        pattern = r"\s+".join(re.escape(word) for word in key.strip().split())
        if not pattern:
            continue
        key_re = re.compile(r"(^|\n|[,;])[ \t]*(" + pattern + r")[ \t]*:", re.IGNORECASE)
        for m in key_re.finditer(text):
            matches.append({"start": m.start() + len(m.group(1)), "end": m.end(), "field": f, "len": len(key)})

    matches.sort(key=lambda m: (m["start"], -m["len"]))
    chosen = []
    last_end = -1
    for m in matches:
        if m["start"] < last_end:
            continue
        chosen.append(m)
        last_end = m["end"]

    found = {}
    for i, m in enumerate(chosen):
        stop = chosen[i + 1]["start"] if i + 1 < len(chosen) else len(text)
        value = text[m["end"]:stop]
        next_key = NEXT_KEY_RE.search(value)
        if next_key is not None:
            value = value[:next_key.start()]
        value = TRAILING_RE.sub("", value.strip())
        if m["field"]["name"] not in found:
            found[m["field"]["name"]] = value
    return found

Finds the key: value pairs of one form in a text and returns a dict from field name to the value string as written. Rung 2 of interpret_reply calls it on every pending form.

Argument Type Meaning
text str The prose of the message.
spec dict One validated form.

Every field has its name as a key. Its label is a second key when the label differs from the name after normalisation. A key matches without regard to case and with any run of whitespace between its words. A key matches only at the start of the text or after a newline, a , or a ; and only when optional spaces and : follow it. Longer keys are tried first. Nome completo: is therefore never read as Nome:. Of two overlapping matches the earlier one is kept.

The value of a key runs to the start of the next recognised key. It stops earlier at a line that starts with an unknown key shaped like word: (see NEXT_KEY_RE) because the contract forbids a value to absorb an unknown key and the text after it. The value is then stripped and loses its trailing commas, semicolons and whitespace. When a field appears twice the first value is kept.

nm = build_form("Name", [{"name": "nome", "type": "text", "label": "Nome"},
                         {"name": "full", "type": "text", "label": "Nome completo", "required": True}],
                form_id="n1", lang="it")
scan_labeled("Nome completo: Ada Lovelace\nnome: Ada", nm)   # {'full': 'Ada Lovelace', 'nome': 'Ada'}
scan_labeled("Note: hi\nNome: Ada\nother: x\nmore", nm)      # {'nome': 'Ada'}
scan_labeled("Height: 12, diet: veg; other: x", form)        # {'height': '12', 'diet': 'veg; other: x'}

The last example shows a limit of the current version. An unknown key cuts a value only when it opens a new line. After a comma or a semicolon it stays inside the value. In the example diet reads veg; other: x and then fails as an unknown_option.

NEXT_KEY_RE module-attribute

NEXT_KEY_RE = re.compile('\\n[ \\t]*[^\\n:]{1,64}:')

The pattern of an unknown key at the start of a line: a newline, optional spaces and 1 to 64 characters other than newline and colon, followed by :. scan_labeled cuts a value at its first match.

TRAILING_RE module-attribute

TRAILING_RE = re.compile('[,;\\s]+\\Z')

The pattern of the trailing commas, semicolons and whitespace that scan_labeled removes from the end of each value.