The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← Back to program

← AI 320 — Applied AI, Retrieval and Reliable Automation

Weeks 3–5

Prompt contracts, structured outputs and validation

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.

Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.

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 reasoning 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.

Extended teaching and laboratory

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.

Step-by-step reasoning 1. The object might satisfy the declared schema if those fields and status are allowed. That is only structural validity.

  1. Verify P7 exists, is the correct version and is accessible to the requester. An invented or unauthorized identifier fails provenance.
  1. The unconditional all-orders claim exceeds P7’s restrictions. Correct it to the bounded conditions or mark unresolved exceptions.
  1. If the workflow cannot establish applicability, return a distinct insufficient-evidence or conflict state rather than an unsupported positive answer.

Turn a generated object into a checked answer state

The earlier notation

{status:answered,answer:All orders are refundable,sources:[P7]}

is a schematic object, not literal JSON: keys and string values need double quotes. This distinction matters before discussing meaning. The literal JSON

{"status":"answered","answer":"All orders are refundable","sources":["P7"]}

can parse successfully and still make an unsupported claim. A parser constructs data; a schema checks a representation contract; neither establishes permission or entailment.

Define the result states before writing the prompt. In this teaching contract,

answered

has a nonempty answer and at least one source ID;

insufficient_evidence

has an empty answer and empty sources;

conflict

has an explanation and at least two source IDs. The conflict rule counts references, rather than proving that their contents disagree. A separate evidence review must establish the actual conflict and its applicability. The application should retain these states through the UI and action boundary instead of converting every result into an authoritative answer string.

Construct the allowed ID set from the exact source snapshot admitted to this request after authorization, effective-date and version checks. Do not use every syntactically valid ID in the database. A source becoming inaccessible between retrieval and release needs a stated revalidation policy; a cache is another copy subject to the same boundary. A model may propose references but cannot enlarge this set. Bind any claim-support review to the particular answer, source versions and locators: approval of an earlier draft does not approve a later changed claim.

import json

def reject_constant(value): raise ValueError("Nonstandard numeric constant")

def unique_object(pairs): result = {} for key, value in pairs: if key in result: raise ValueError("Duplicate object key") result[key] = value return result

def answer_contract(raw, allowed_ids): if type(raw) is not str or len(raw) > 10000: raise ValueError("Invalid or oversized response") obj = json.loads(raw, object_pairs_hook=unique_object, parse_constant=reject_constant) if type(obj) is not dict or set(obj) != {"status", "answer", "sources"}: raise ValueError("Unexpected fields") state, answer, sources = obj["status"], obj["answer"], obj["sources"] if type(state) is not str or type(answer) is not str or type(sources) is not list: raise ValueError("Invalid field types") if len(sources) > 20 or any(type(s) is not str or s not in allowed_ids for s in sources): raise ValueError("Invalid source reference") if len(set(sources)) != len(sources): raise ValueError("Duplicate source reference") if state == "answered": valid = bool(answer.strip()) and len(sources) >= 1 elif state == "insufficient_evidence": valid = answer == "" and sources == [] elif state == "conflict": valid = bool(answer.strip()) and len(sources) >= 2 else: valid = False if not valid: raise ValueError("State invariant failed") return obj

The length bound is one modest application constraint, not a complete parser resource defense. Transport byte limits, timeouts and concurrency budgets also belong at their own boundaries. This example rejects duplicate keys instead of silently allowing one value to replace another. Python type hints alone would not enforce these runtime conditions. Display answer text through the UI framework's text mechanism; do not treat it as executable HTML, SQL, a shell command or an authorized tool request. The returned object contains no action permission.

Trace a current-policy answer whose allowed set is {P7,P8}. An invented P9 fails identity validation. A genuine P7 with an answer omitting its unused-item and thirty-day conditions passes this representation check but fails substantive support. An empty

answered

result fails the state invariant; the declared empty insufficient-evidence object passes. A conflict citing only P7 fails even if its prose says that two documents disagree. Two IDs passing the check still require inspection of the actual contradictory propositions.

Optional changed contract: complete reasoning

Change the allowed set to {P8} after P7 access is withdrawn. The previously valid P7 representation now fails source validation; hiding its citation after releasing the same answer would not repair the boundary. Change a two-source conflict to [P8,P8]: duplicate rejection prevents manufacturing two distinct references. If P8 and P10 are both authorized but describe different transaction dates, their different deadlines do not establish a same-case conflict. Establish temporal applicability before choosing conflict or answered. A correct parser result does not resolve that interpretation. For the original unquoted schematic object, parsing fails first; replace it with actual JSON before reasoning about schema or support.

Optional criteria, one point each: distinguish schematic notation from literal parsing; enforce field/state invariants; bind source identity to current authorized provenance; assess claim support and action permission separately. Explain all four for four points.

Apply the idea

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.

The source ID is genuine but refers to an expired policy. What should the validator or workflow establish before answering a current-policy question?

Read the worked reasoning

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.

Check understanding

What does valid JSON fail to establish?

  1. Truth, source support and authorization
    Feedback

    Syntax validation is weaker than semantic and permission checks.

  2. That the text follows JSON syntax
    Feedback

    A successful parser does establish syntactic validity under its rules.

  3. That a parser can construct a data object
    Feedback

    Parsing creates data, not evidence of its truth.

Further reading

Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.

Use the preserved original investigation and connected Academy preparation/application below. Compare your reasoning with its optional complete model. Historical source directions remain in immutable edition4.

My learning →