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
¶
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
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | |
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.
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
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. |
check_reply
¶
Source code in unaiverse/uai/interpret.py
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
¶
Source code in unaiverse/uai/interpret.py
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
¶
Source code in unaiverse/uai/interpret.py
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.
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.
The pattern of the trailing commas, semicolons and whitespace that scan_labeled removes from the end of each value.