AI 320 — Applied AI, Retrieval and Reliable Automation · Weeks 3–5
Prompt contracts, structured outputs and validation
Full teaching sequence and cumulative subject work
Study the complete on-site source sections below, then work the original example, changed-condition problem and transfer laboratory. Review the assigned language and software-boundary material. Treat prompt examples as task specifications, not as guarantees of model compliance.
A schema is not an evidence test
Structured output constrains representation: fields, types, allowed values and sometimes relationships among fields. It does not prove that the cited passage supports the answer. Enforce an answer contract with distinct states such as answered, insufficient_evidence and conflict. A positive answer needs valid, authorized source identifiers and support for every material claim.
Reject unexpected fields when they could smuggle an action instruction through an otherwise valid object. Validate identifiers against the retrieved authorized corpus rather than accepting any well-formed string. Keep validation failures visible in evaluation.
Worked problem
Output is {status:answered,answer:All orders are refundable,sources:[P7]}. P7 says unused items may be refundable within 30 days. Evaluate syntax, source identity and entailment separately.
Trace the complete reasoning
The object might satisfy the declared schema if those fields and status are allowed. That is only structural validity.
Verify P7 exists, is the correct version and is accessible to the requester. An invented or unauthorized identifier fails provenance.
The unconditional all-orders claim exceeds P7’s restrictions. Correct it to the bounded conditions or mark unresolved exceptions.
If the workflow cannot establish applicability, return a distinct insufficient-evidence or conflict state rather than an unsupported positive answer.
Independent transfer problem
The source ID is genuine but refers to an expired policy. What should the validator or workflow establish before answering a current-policy question?
Compare the transfer solution
Check temporal applicability, superseding versions and the relevant transaction date. A genuine historical source can support a historical claim while failing a current-policy claim. Preserve the version and locator in provenance. Do not silently rewrite a historical transaction under a newer policy without a stated rule.
Learning objectives
- Explain and trace the mechanisms in prompt contracts, structured outputs and validation.
- Apply the method to the worked example and changed-condition exercise.
- Identify assumptions, failure cases and the evidence needed to justify a result.
Study the mechanism
A prompt should state the task, available evidence, constraints and required response structure. Delimit instructions from source material, but do not assume delimiters create a security boundary. A model can still misunderstand or follow hostile content. The application must enforce permissions, validate outputs and decide which actions are allowed.
Structured output makes some failures easier to detect. A JSON object with an answer and source identifiers is easier to validate than unrestricted prose. Parsing JSON checks syntax; validating fields checks shape; checking each citation against retrieved evidence checks grounding. These are separate layers. A valid object can still contain a false claim. Do not use eval to parse generated content or execute model-supplied code.
Keep privileged configuration outside untrusted input. A document may contain text telling the assistant to ignore its task or reveal secrets. That text is evidence to analyze, not an instruction with authority over the application. Reject unexpected fields and constrain allowed values where appropriate. If a model returns an unsupported action, the safe response is a controlled failure or clarification, not a permissive guess. Test empty outputs, extra fields, missing citations, malformed numbers and contradictory evidence.
Worked example
import json
def validate_answer(raw, allowed_ids):
data = json.loads(raw)
if type(data) is not dict or set(data) != {"answer", "sources"}:
raise ValueError("Unexpected answer shape")
if not isinstance(data["answer"], str) or type(data["sources"]) is not list:
raise ValueError("Invalid field types")
if not all(isinstance(s, str) and s in allowed_ids for s in data["sources"]):
raise ValueError("Unknown source")
return data
assert validate_answer('{"answer":"Review policy A","sources":["A"]}', {"A"})["sources"] == ["A"]The validator rejects an invented source ID and unexpected fields. It does not prove that policy A actually supports the answer; evidence review is still required. An empty sources list is syntactically permitted here so abstention can be represented, but a complete contract should distinguish an evidence-backed answer from an abstention and require sources for positive claims.
Check your understanding
What does valid JSON fail to establish?
- Truth, source support and authorization
- That the text follows JSON syntax
- That a parser can construct a data object
Answer and reasoning for every option
Correct: Truth, source support and authorization Syntax validation is weaker than semantic and permission checks.
Reconsider: That the text follows JSON syntax A successful parser does establish syntactic validity under its rules.
Reconsider: That a parser can construct a data object Parsing creates data, not evidence of its truth.
Transfer laboratory: A valid schema with an unsupported answer
A model returns valid JSON containing source ID A, but A does not entail the answer. Which checks passed and which failed?
Work through the full solution
Parsing and schema validation passed, and the ID may exist. Grounding failed because existence is weaker than entailment. Compare the exact claim with the cited passage, its conditions and version. A schema may require claim-to-passage mappings, but software cannot infer truth merely from their presence. Abstain or revise when evidence is insufficient.
Evidence of understanding
Separate syntax, field types, identifier existence and substantive support.
Complete on-site teaching readings
These are full attributed source sections, not previews. Read them alongside the original Academy explanation and code.
- 8.2. Feature extraction · The scikit-learn developers
- json — JSON encoder and decoder · Python Software Foundation and Python documentation contributors
- typing — Support for type hints · Python Software Foundation and Python documentation contributors
- Cross-site scripting (XSS) · Mozilla Contributors
- LLM01:2025 Prompt Injection · OWASP GenAI Security Project contributors
- LLM05:2025 Improper Output Handling · OWASP GenAI Security Project contributors
- LLM07:2025 System Prompt Leakage · OWASP GenAI Security Project contributors
Open the complete practice sequence and cumulative assessment →