Skip to content

unaiverse.uai.fill

A language model never sees the JSON of a form. It reads the alt of the form (the instruction Reply with lines 'field: value'. Fields: ...) and answers in words. This module turns those words into the canonical reply block that the asker reads at the first rung of the ladder (see interpret_reply). Because a block is a message with a contract on its format, an answer that does not satisfy the form is not sent as it is. Instead the agent asks again. A model receives a corrective prompt within the same turn and a person at a terminal receives a line on the screen. Only an answer that satisfies the form is sent. When the agent stops asking, it sends the values it could read together with the words from which it read them.

The loop itself lives in the agent (uai_postprocess, uai_merge_reads and uai_answer_fell_short in unaiverse.agent_basics, driven by the module wrapper in unaiverse.modules.utils). The agent asks a model again at most UAI_MAX_RETRIES times (2 in the current version). This module holds the pieces of the loop: reading an answer, describing what is wrong, wording the second request and encoding the result. A world that wants its own policy overrides those agent methods in its role file and reuses these functions. The narrative guide is Interactive messages.

Callers import from unaiverse.uai because the package re-exports every public name of this module.

Object Role
read_answer Reads a text as the answer to one form and returns the values (when the form is satisfied) and the event.
fill_slots Returns only the values of read_answer.
describe_answer One line that names the missing and the rejected fields.
retry_prompt The corrective prompt for a model.
reprompt_person The corrective line for a person at a terminal.
encode_partial The reply block sent when the answer is still incomplete or invalid.
AnswerOutcome What the agent decided about one answer.
AnswerWithheld The exception that turns a processor step into a silent failure.

The corrective texts exist in Italian and English and follow the lang of the form. Every other language falls back to English.

from unaiverse.uai import build_form, read_answer, retry_prompt

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

values, event = read_answer("diet: omni", form)
# values is None, event.missing == ['height']
print(retry_prompt(form, "diet: omni", event))
Reply with lines 'field: value'. Fields: Height (number, in cm, between 50 and 250, required), Diet (one of: Vegetarian, Omnivore, optional).

Your answer was:
diet: omni

It does not satisfy the request yet: nothing was said about Height. What you already said stands (Diet: Omnivore): write ONLY the missing fields, one line per field in the form 'field: value', with no other text.

read_answer

read_answer(text, spec: dict, lang: str | None = None) -> tuple[dict | None, object]
Source code in unaiverse/uai/fill.py
def read_answer(text, spec: dict, lang: str | None = None) -> tuple[dict | None, object]:
    """Reads a text as the answer to one form, and says both what it gives and how it was understood.

    Args:
        text: What the processor produced.
        spec: The validated spec of the form that was asked.
        lang: Fallback language, used when the spec declares none.

    Returns:
        A tuple with the canonical values, when every required field was answered and nothing violates the
        spec, or None when they must not be encoded, and the event the text was read as, or None when there
        was nothing to read at all. The event is what tells an answer that fell short from a text that was
        never an answer, which is the difference between asking again and staying quiet.
    """
    if not isinstance(text, str) or not text.strip() or not spec:
        return None, None

    event = interpret_reply(text, pending=[spec], lang=lang)

    # Already canonical (the processor wrote the block itself), or not an answer at all, or an answer to
    # something else entirely
    if event.via in (VIA_BLOCK, VIA_FREETEXT) or event.to != spec.get("id"):
        return None, event

    # The form is not satisfied: this is what the asking-again loop is for
    if event.issues or event.missing or not event.values:
        return None, event
    return event.values, event

Reads a text as the answer to one form. It returns a tuple (values, event) with the values that the text gives and the event that describes how it was read.

Argument Type Default Meaning
text any required The text produced by the processor.
spec dict required The validated form that was asked.
lang str or None None Fallback language for a form without lang.

The function runs interpret_reply with spec as the only pending form and decides as follows.

Situation values event
text is not a string or is blank. spec is empty None None
The text carries a reply block (via == "block") None The event of the block
The text is free text (via == "freetext") or answers another form None The event
The text was read but leaves a required field missing, has an issue or gives no value None The event
Every required field is answered and nothing is rejected event.values The event

A None event means that there was nothing to read. A freetext event means that the text was not an answer. An event with values, missing fields or issues means an answer that is incomplete or has invalid values. The agent asks again only in the last case. A block written by the processor itself is sent unchanged and never re-encoded.

read_answer("height: 170\ndiet: omni", form)[0]   # {'height': 170.0, 'diet': 'omni'}
read_answer("", form)                              # (None, None)

A form with one text field accepts any text at the bare rung. For such a form every non-blank text is a complete answer.

fill_slots

fill_slots(text, spec: dict, lang: str | None = None) -> dict | None
Source code in unaiverse/uai/fill.py
def fill_slots(text, spec: dict, lang: str | None = None) -> dict | None:
    """The values of a clean, complete answer to one form, or None when the text does not satisfy it."""
    return read_answer(text, spec, lang=lang)[0]

Returns read_answer(text, spec, lang)[0]. The result holds the canonical values of a complete answer without issues and is None for any other text. It is the shortcut for a caller that does not need the event.

fill_slots("height: 170\ndiet: omni", form)   # {'height': 170.0, 'diet': 'omni'}
fill_slots("diet: omni", form)                # None

describe_answer

describe_answer(spec: dict, event, lang: str | None = None) -> str
Source code in unaiverse/uai/fill.py
def describe_answer(spec: dict, event, lang: str | None = None) -> str:
    """Says, in one line, what keeps an answer from satisfying its form, naming the fields as the author did.

    Args:
        spec: The validated form that was asked.
        event: The event the answer was read as.
        lang: Language of the sentence, defaulting to the one of the form.

    Returns:
        A readable summary, for whoever wrote the answer rather than for whoever asked.
    """
    words = _words(lang if lang is not None else spec.get("lang"))
    labels = {f["name"]: field_label(f) for f in interactive_fields(spec)}
    said = []
    if getattr(event, "missing", None):
        said.append(words["missing"].format(fields=", ".join(labels.get(n, n) for n in event.missing)))
    if getattr(event, "issues", None):
        said.append(words["issues"].format(
            fields=", ".join(f"{labels.get(n, n)} ({r})" for n, r in event.issues.items())))
    if not said:
        said.append(words["nothing"])
    return "; ".join(said)

Returns one line that says what keeps an answer from satisfying its form. It names the fields by the labels that the author of the form wrote. The line addresses the author of the answer and not the author of the form.

Argument Type Default Meaning
spec dict required The validated form.
event ReplyEvent or None required The event produced by reading the answer. Any object with missing and issues attributes works. None is accepted.
lang str or None None The language of the line. None takes the lang of the form.

The line joins up to two parts with ;: the missing fields (nothing was said about Height) and the rejected ones with their reasons (these values are not acceptable: Height (above_max)). When the event has neither, the line is no field of it could be read. In both languages the reasons are written as the codes of the contract.

describe_answer(form, read_answer("height: 999", form)[1])
# 'these values are not acceptable: Height (above_max)'

An event that has values and nothing wrong also produces no field of it could be read. The agent never describes such an event because it already satisfies the form.

retry_prompt

retry_prompt(spec: dict, text: str, event, model_view: str | None = None) -> str
Source code in unaiverse/uai/fill.py
def retry_prompt(spec: dict, text: str, event, model_view: str | None = None) -> str:
    """Words the second request to a model: the instruction it was given, its answer, and what is wrong.

    Args:
        spec: The validated form that was asked.
        text: What the model wrote.
        event: The event that answer was read as.
        model_view: The rendering of the message that carried the form, as the model read it the first time.
            When it is not known any more, the instruction of the form alone is repeated.

    Returns:
        The text to feed the model in place of the original message.
    """
    words = _words(spec.get("lang"))
    view = model_view if model_view else spec.get("alt", "")

    # When something was already read (this attempt or the merged rounds before it), the request narrows:
    # what stands is restated and only the missing fields are asked for, so an answer can be completed
    # across rounds instead of being rewritten from scratch every time (the policy merges the rounds,
    # which is what makes obeying the narrowed request safe)
    have = getattr(event, "values", None) or {}
    if have:
        again = words["again_partial"].format(answer=text.strip(), problem=describe_answer(spec, event),
                                              have=project_draft(spec, have))
    else:
        again = words["again"].format(answer=text.strip(), problem=describe_answer(spec, event))
    return f"{view.rstrip()}\n\n{again}" if view.strip() else again

Returns the text that the agent feeds to a model in place of the original message for the next corrective round. The agent calls it from uai_answer_fell_short while retries are left and the interaction is not about to expire.

Argument Type Default Meaning
spec dict required The validated form. Its lang selects the wording.
text str required What the model wrote. It is quoted after stripping.
event ReplyEvent or None required The event produced by reading text. After a corrective round the agent passes the merged reading of every attempt.
model_view str or None None The message as the model read it the first time (see to_model_text). When it is missing or empty the alt of the form is repeated instead.

The prompt is the view, a blank line and one of two requests. When the event has no values the model is asked to answer again from scratch. When some values were already read, the request restates them through project_draft and asks only for the missing fields. Because the agent merges the rounds, answering only the missing fields is safe for the model.

retry_prompt(form, "boh", read_answer("boh", form)[1])
Reply with lines 'field: value'. Fields: Height (number, in cm, between 50 and 250, required), Diet (one of: Vegetarian, Omnivore, optional).

Your answer was:
boh

It does not satisfy the request: no field of it could be read. Answer again, one line per field in the form 'field: value', with no other text.

reprompt_person

reprompt_person(spec: dict, event) -> str
Source code in unaiverse/uai/fill.py
def reprompt_person(spec: dict, event) -> str:
    """Words the second request to a person at a keyboard: what was wrong, and that nothing was sent."""
    words = _words(spec.get("lang"))
    return words["person"].format(form=spec.get("name", spec.get("id")), problem=describe_answer(spec, event))

Returns the line that a person at a terminal reads when their answer does not satisfy the form. It names the form by name (or by id when the spec has no name) and says that nothing was sent. The agent prints it and withholds the answer. The next line that the person types is read against the same form. In the browser the agent has no terminal to print to and does not use this function.

Argument Type Meaning
spec dict The validated form. Its lang selects the wording.
event ReplyEvent or None The event produced by reading the answer.
reprompt_person(form, read_answer("diet: omni", form)[1])
# "The answer to 'Profile' does not satisfy the request (nothing was said about Height): it was not sent. Write it again."

encode_partial

encode_partial(spec: dict, text, event) -> str | None
Source code in unaiverse/uai/fill.py
def encode_partial(spec: dict, text, event) -> str | None:
    """What travels when the asking is over and the answer still falls short: one block, values and words.

    The values that could be read are encoded so that whoever asked reads them at the first rung and learns
    the rest is missing; the ones that violate the form are left out, as the contract wants. The words
    themselves travel inside the block, verbatim, as its ``raw``: one text, or the list of the attempts the
    (possibly merged) values were read from, oldest first. The answer stays one block whether it filled
    everything, something, or nothing readable at all. Only an empty answer with nothing readable has
    nothing to send, and None says so (the policy withholds that case before ever coming here).
    """
    values = getattr(event, "values", None) or {}
    texts = list(text) if isinstance(text, (list, tuple)) else [text]
    if not values and not any(non_empty(t) for t in texts):
        return None
    return encode_reply(spec, values, raw=texts)

Returns the message that the agent sends when the corrective rounds are over and the answer is still incomplete or invalid. The block carries the values that could be read and the original words in raw. The asker therefore reads the values at the first rung, learns from missing what is absent and can still read how the answer was phrased. It returns None only when there are no values and no non-blank text.

Argument Type Meaning
spec dict The validated form.
text str, list or tuple One text or the list of the texts of every attempt from the oldest to the newest.
event ReplyEvent or None The event whose values are encoded. A value that violates the form is left out by encode_reply.
city = build_form("City", [{"name": "city", "type": "text", "label": "City"}], form_id="c1")
encode_partial(city, ["first try", "second try"], interpret_reply("x", [city]))
# '```uai\n{"v":1,"kind":"reply","to":"c1","values":{"city":"x"},"alt":"City: x","raw":["first try","second try"]}\n```'

AnswerOutcome dataclass

AnswerOutcome(text: str | None = None, retry: str | None = None, withhold: bool = False)

The decision of the agent about the text that a processor produced in answer to a form. It is a frozen dataclass and uai_postprocess returns it. Exactly one of the three outcomes below applies.

Field Type Default Meaning
text str or None None The text sent in place of the output of the processor. None sends the output unchanged.
retry str or None None The corrective prompt to feed the processor again. When it is not None the module wrapper runs the processor once more.
withhold bool False True when nothing must be sent. The module wrapper then raises AnswerWithheld.

AnswerOutcome() means that the output is sent unchanged. AnswerOutcome(retry="...") asks again. AnswerOutcome(withhold=True) drops the answer and keeps the form pending.

AnswerWithheld

Bases: Exception

An Exception subclass with no extra attributes. The module wrapper (unaiverse.modules.utils) raises it from the processor call when the outcome has withhold=True. The agent catches it in its process step (unaiverse.agent), logs it at debug level and ends the step with False. Nothing reaches the output stream, the interaction that asked stays open and the person at the keyboard has already been told to answer again. Code outside the SDK never needs to raise it.