Objectives: LO-4.1, LO-4.2, LO-4.3
Prerequisites: the Module 4 reading and Lab 3
Time: about 2.5 hours
In this lab you build a tagged prompt with Python’s XML library, show a naive template breaking on customer text that contains its own markup, and fix it by escaping. Then you write a renderer that fills exactly a template’s declared fields, and compare two versions of the shop’s routing prompt with a diff.
The two prompt versions are files in data/prompts/: route-v1.txt and route-v2.xml. No
cell sends anything over the network or calls a model.
Use a fresh kernel and run the cells from top to bottom. Fill each answer cell, then run its
check, which prints passed or fails with a message that says what is wrong. The checks fail
on purpose until their exercises are complete.
Setup¶
import sys
from difflib import unified_diff
from string import Template
from xml.etree import ElementTree
from xml.sax.saxutils import escape
from promptlab import data_path, load_json
v1 = data_path("prompts/route-v1.txt").read_text(encoding="utf-8")
v2 = data_path("prompts/route-v2.xml").read_text(encoding="utf-8")
print("Python", sys.version.split()[0])Predict the parse¶
The customer’s text below contains & and <, which XML uses for markup. The cell wraps it in
a ticket element twice: once as it is, and once after escape has rewritten those
characters. Predict which of the two parses fails, then run the cell.
ticket = "Brake cable & housing < $20"
for serial in ("<ticket>" + ticket + "</ticket>", "<ticket>" + escape(ticket) + "</ticket>"):
try:
print(ElementTree.fromstring(serial).text)
except ElementTree.ParseError:
print("The XML parser rejected the text.")Exercise L4.1 (LO-4.1, ★★, about 25 minutes)¶
Build the document prompt. Write layout(document, instructions, question). Use one root
element named prompt. Give it the children documents, instructions, and question, in
that order. documents holds one doc element, whose text is document. Build the tree with
the XML library, and return the XML as a Unicode string, not bytes.
def layout(document, instructions, question):
raise NotImplementedError("L4.1")xml = layout("use a size < 18", "Quote the size", "Which size?")
assert isinstance(xml, str), f"Return the XML as a str, not {type(xml).__name__}."
root = ElementTree.fromstring(xml)
assert root.tag == "prompt", f"Name the root element prompt, not {root.tag!r}."
assert [child.tag for child in root] == ["documents", "instructions", "question"], \
f"Put the children in the order documents, instructions, question; got {[c.tag for c in root]}."
assert root.findtext("documents/doc") == "use a size < 18", \
"Put the document's exact text in documents/doc; the XML library escapes the < for you."
assert root.findtext("instructions") == "Quote the size", \
"Put the instructions' exact text in the instructions element."
assert root.findtext("question") == "Which size?", \
"Put the question's exact text in the question element."
print("passed")Exercise L4.2 (LO-4.2, ★★, about 25 minutes)¶
Recover literal closing tags. Write serialize_ticket(value), which returns a pair: the
naive interpolation and a safe version. Both wrap the value in a single outer ticket element.
Use a local XML parser to see what happens when the input contains the literal text
</ticket>. Explain in your notes what the parse result says about this representation.
def serialize_ticket(value):
raise NotImplementedError("L4.2")value = "The label on the sample says </ticket> and is damp."
bad, good = serialize_ticket(value)
try:
ElementTree.fromstring(bad)
except ElementTree.ParseError:
pass
else:
raise AssertionError("The naive version should fail to parse: the literal </ticket> ends the "
"element early.")
assert ElementTree.fromstring(good).text == value, \
"The safe version should parse back to the exact text."
tricky = "Parts & labor: <b>$40</b> </ticket>"
assert ElementTree.fromstring(serialize_ticket(tricky)[1]).text == tricky, \
"Escape &, <, and > in the safe version, so any text parses back unchanged."
print("passed")Exercise L4.3 (LO-4.2, LO-4.3, ★★, about 25 minutes)¶
Render exactly the declared fields. Write render(text, values) with string.Template.
Raise ValueError for an invalid template, a missing field, or an extra field. Escape every
supplied value once. Return the substituted string.
def render(text, values):
raise NotImplementedError("L4.3")final = ElementTree.fromstring(render(v2, {"ticket": "Pads & cables $20", "rules": "Route."}))
assert final.findtext("ticket") == "Pads & cables $20", \
f"Got {final.findtext('ticket')!r}: escape each value exactly once, and leave its $ alone."
assert final.findtext("instructions") == "Route.", \
"Fill the rules field into the instructions element."
for values in ({}, {"x": "1", "y": "2"}):
try:
render("<x>$x</x>", values)
except ValueError:
pass
else:
raise AssertionError(f"Require exactly x: {values!r} should raise ValueError.")
try:
render("<x>$</x>", {})
except ValueError:
pass
else:
raise AssertionError("A $ with no name is an invalid template: raise ValueError.")
print("passed")Exercise L4.4 (LO-4.3, ★★, about 25 minutes)¶
Review a version change. Write compare(first, second), which returns the unified diff of
the two texts’ lines, from first to second, as one string. Label its files v1 and v2.
Two identical texts give "". In your notes, explain the change you would expect to help with
ambiguous tickets.
def compare(first, second):
raise NotImplementedError("L4.4")delta = compare(v1, v2)
assert delta.startswith("--- v1\n+++ v2\n"), \
f"Start with the headers '--- v1' and '+++ v2', each on its own line; got {delta[:20]!r}."
assert "-Sort this ticket." in delta and "+ <ticket>$ticket</ticket>" in delta, \
"Show removed lines with - and added lines with +, keeping each line's indentation."
assert compare(v1, v1) == "", "Identical texts have no differences, so return ''."
print("passed")Summary¶
You kept the template’s structure intact, round-tripped customer text through it, rejected missing and extra fields, and read the changes between two versions of a prompt.