Skip to content

unaiverse.uai.fence

A message carries a block as a fenced code block whose info string is uai. This module is the only one of the package that implements the grammar of that fence. It splits a message into prose segments and raw block bodies in their original order and it wraps a body into a fence. It parses no JSON. parse_message reads the bodies that this module extracts. Import the re-exported names from unaiverse.uai. The protocol is described in the package page.

The grammar follows CommonMark with one restriction on the tag.

  1. An opening fence is a line with at most three leading spaces, three or more backticks, optional spaces or tabs, the literal uai and optional trailing spaces or tabs. A line of tildes never opens a block.
  2. A closing fence is a line with at most three leading spaces, at least as many backticks as the opening fence and optional trailing spaces or tabs.
  3. The body is every line between the two fences joined with \n. One carriage return at the end of a fence line is ignored. The carriage returns of the body stay in it.
  4. An opening fence without a closing fence is prose.
  5. A body larger than MAX_BLOCK_BYTES (8192 bytes in UTF-8) is marked too_large and must never be parsed.
Object Re-exported by unaiverse.uai Role
has_fence yes A fast test for a candidate opening fence.
wrap_fence yes Puts a JSON body inside a fence.
extract_fences yes Splits a message into prose and raw blocks.
fence_spans yes The character spans of the blocks.
cut_to_bytes no Cuts a string to a byte budget on a character boundary.
OPEN_RE, HAS_FENCE_RE, CR_RE no The compiled regular expressions of the grammar.

OPEN_RE module-attribute

OPEN_RE = re.compile(' {0,3}(`{3,})[ \\t]*' + FENCE_TAG + '[ \\t]*')

The compiled pattern of an opening fence: {0,3}(`{3,})[ \t]*uai[ \t]* (it starts with a space). extract_fences matches it against a whole line with fullmatch. Group 1 captures the backticks and its length gives the minimum number of backticks of the closing fence.

HAS_FENCE_RE module-attribute

HAS_FENCE_RE = re.compile('```[ \\t]*' + FENCE_TAG + '[ \\t]*(\\r?\\n|$)')

The compiled pattern behind has_fence: three backticks, optional spaces or tabs, uai, optional spaces or tabs and then a line end or the end of the text. The pattern is searched anywhere in the text and is not anchored to the start of a line.

CR_RE module-attribute

CR_RE = re.compile('\\r\\Z')

The compiled pattern \r\Z that removes one trailing carriage return from a line before the fence patterns are tested. A message with CRLF line ends therefore splits like the same message with LF line ends.

has_fence

has_fence(text) -> bool
Source code in unaiverse/uai/fence.py
def has_fence(text) -> bool:
    """Tells whether a text contains at least one candidate opening fence."""
    return isinstance(text, str) and HAS_FENCE_RE.search(text) is not None

Returns True when a text contains at least one candidate opening fence. The node, the agent, the logger and the processor wrapper call it on every incoming or outgoing text as a fast path before any parsing.

Argument Type Default Meaning
text any required The text to test. A value that is not a str gives False.

It returns a bool. The test is cheap and permissive and matches ```uai even after other characters on the same line. A True result means only that the message may hold a block. parse_message gives the final answer.

has_fence("Hi\n```uai\n{}\n```")   # True
has_fence("see ```uai\n")          # True (a candidate that extract_fences does not open)
has_fence("```uaix\n")             # False
has_fence(None)                    # False

wrap_fence

wrap_fence(body: str) -> str
Source code in unaiverse/uai/fence.py
def wrap_fence(body: str) -> str:
    """Wraps a canonical JSON body in a uai fence."""
    return "```" + FENCE_TAG + "\n" + body + "\n```"

Wraps a JSON body in a uai fence. It adds no trailing newline after the closing fence.

Argument Type Default Meaning
body str required The canonical JSON body. The function does not check it.
wrap_fence('{"v":1}')   # '```uai\n{"v":1}\n```'

serialize_block calls it on the output of canonical_json.

cut_to_bytes

cut_to_bytes(s: str, max_bytes: int) -> str
Source code in unaiverse/uai/fence.py
def cut_to_bytes(s: str, max_bytes: int) -> str:
    """Cuts a string so that its UTF-8 encoding fits in max_bytes, on a character boundary."""
    out = []
    used = 0
    for ch in s:
        n = len(ch.encode("utf-8"))
        if used + n > max_bytes:
            break
        out.append(ch)
        used += n
    return "".join(out)

Cuts a string to the longest prefix whose UTF-8 encoding fits in max_bytes. The cut never splits a character.

Argument Type Default Meaning
s str required The string to cut.
max_bytes int required The byte budget.
cut_to_bytes("caffè", 5)   # 'caff' (the è takes two bytes and would make six)

The package uses it for the body of an oversized block, for the model view of to_model_text and for the raw texts that encode_reply trims.

extract_fences

extract_fences(text) -> list[dict]
Source code in unaiverse/uai/fence.py
def extract_fences(text) -> list[dict]:
    """Splits a message into an ordered list of prose and raw block segments.

    Args:
        text: The message to split.

    Returns:
        A list of dicts. Prose segments are ``{"kind": "prose", "text", "start", "end"}`` and are never empty;
        block segments are ``{"kind": "block", "raw", "bytes", "too_large", "start", "end"}``, where "start" and
        "end" are character offsets of the whole fence in the original text. A block whose raw body exceeds the
        byte limit comes back with ``too_large`` and its "raw" already cut: it must never be parsed.
    """
    segments: list[dict] = []
    if not isinstance(text, str) or len(text) == 0:
        return segments

    lines = text.split("\n")

    # Character offset of the beginning of each line, plus one past the end of the text
    offsets = []
    pos = 0
    for line in lines:
        offsets.append(pos)
        pos += len(line) + 1
    offsets.append(pos)

    prose: list[str] = []
    prose_start = 0
    i = 0

    def flush_prose(end_offset: int) -> None:
        if len(prose) == 0:
            return
        # Blank lines that only separate prose from a fence are not content
        joined = re.sub(r"\A\n+|\n+\Z", "", "\n".join(prose))
        if joined.strip() != "":
            segments.append({"kind": "prose", "text": joined, "start": prose_start, "end": end_offset})
        prose.clear()

    while i < len(lines):
        open_match = OPEN_RE.fullmatch(CR_RE.sub("", lines[i]))
        if open_match is None:
            if len(prose) == 0:
                prose_start = offsets[i]
            prose.append(lines[i])
            i += 1
            continue

        # Find the closing fence: at least as many backticks, nothing else
        ticks = len(open_match.group(1))
        close_re = re.compile(r" {0,3}`{" + str(ticks) + r",}[ \t]*")
        j = i + 1
        while j < len(lines) and close_re.fullmatch(CR_RE.sub("", lines[j])) is None:
            j += 1
        if j >= len(lines):
            # Unterminated: the fence is prose, as the contract prescribes
            if len(prose) == 0:
                prose_start = offsets[i]
            prose.append(lines[i])
            i += 1
            continue

        flush_prose(offsets[i])
        raw_full = "\n".join(lines[i + 1:j])
        n_bytes = len(raw_full.encode("utf-8"))
        too_large = n_bytes > MAX_BLOCK_BYTES
        segments.append({"kind": "block",
                         "raw": cut_to_bytes(raw_full, MAX_BLOCK_BYTES) if too_large else raw_full,
                         "bytes": n_bytes, "too_large": too_large,
                         "start": offsets[i], "end": min(offsets[j] + len(lines[j]), len(text))})
        i = j + 1

    flush_prose(len(text))
    return segments

Splits a message into an ordered list of prose and block segments.

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

It returns a list[dict] with two shapes of segment.

Key Prose segment Block segment
kind "prose" "block"
text The prose without the blank lines that only separate it from a fence. A prose segment is never empty or blank. absent
raw absent The body between the fences, cut to 8192 bytes when too_large is True.
bytes absent The size of the full body in UTF-8 bytes.
too_large absent True when the body exceeds MAX_BLOCK_BYTES.
start, end Character offsets of the segment in text (end is exclusive and the range includes the separating blank lines). Character offsets of the whole fence from the start of the opening line to one past the last character of the closing line.

The function never raises. A body over the limit comes back cut. Its caller must not parse it.

m = 'Intro\n\n```uai\n{"v":1,"type":"x-a","alt":"z"}\n```\nOutro\n```uai\nnot closed'
extract_fences(m)
# [{'kind': 'prose', 'text': 'Intro', 'start': 0, 'end': 7},
#  {'kind': 'block', 'raw': '{"v":1,"type":"x-a","alt":"z"}', 'bytes': 30, 'too_large': False,
#   'start': 7, 'end': 48},
#  {'kind': 'prose', 'text': 'Outro\n```uai\nnot closed', 'start': 49, 'end': 72}]

The second opening fence has no closing fence and stays prose. A block opened by four backticks needs at least four backticks to close. A line of three backticks inside it belongs to the body.

fence_spans

fence_spans(text) -> list[tuple[int, int]]
Source code in unaiverse/uai/fence.py
def fence_spans(text) -> list[tuple[int, int]]:
    """Returns the character spans of the fenced blocks of a message, in order."""
    return [(s["start"], s["end"]) for s in extract_fences(text) if s["kind"] == "block"]

Returns the (start, end) character spans of the blocks of a message in order. It runs extract_fences and keeps the block segments. Blocks marked too_large are included.

Argument Type Default Meaning
text str required The message.
fence_spans(m)   # [(7, 48)] for the message of the previous example

truncate_outside_fences uses these spans to avoid cutting inside a block.