Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 4: Structure, data, and templates

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

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.

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.

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.

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.

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.

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.