Python Master Course V2 — 171. AI Task Design and Evaluation Contracts
Lesson 171: AI Task Design and Evaluation Contracts
An AI application begins with a decision about useful behavior. “Answer our questions” leaves unanswered which sources count, which questions are supported, what happens when evidence is missing, and who bears the cost of a mistake. This lesson turns that vague request into an executable contract for a fictional workshop knowledge assistant. The first implementation is deliberately deterministic: it lets you test the product boundary before adding a probabilistic component.
Learning objectives
- Translate a vague AI idea into inputs, outputs and acceptance criteria
- Choose between rules, retrieval, statistical models and generation
- Specify abstention and human-review boundaries
Prerequisites and setup
140, 150, 160 and 170: modeling capstones; 059: contracts
Use Python 3.11 or newer in a local project folder. This lesson uses only the standard library, works on a CPU, and needs no account, API key, network service, or downloaded model. Save the worked Python example as lesson171.py. Run the example before extending it; keep the original assertions as regression checks.
python lesson171.pyChoose the smallest mechanism that meets the need
A rule maps a well-defined condition to an action. Retrieval finds relevant existing information. A statistical predictor estimates an outcome from learned patterns. A generative model constructs new sequences. These mechanisms can be combined, but they have different failure modes. A fixed room-opening time stored in a small handbook usually needs lookup before it needs generation. A demand forecast needs historical outcomes, a validation strategy, and uncertainty rather than a handbook search.
Write the user decision first: a visitor wants to know when the workshop opens. Then define the authority: the included handbook, version one. Finally define success: return the exact approved answer and its source identifier, or explicitly abstain. A convincing sentence without evidence is not success under this contract. A deterministic baseline is valuable because added complexity must demonstrate a measurable improvement over something simple.
Inputs, outputs, and acceptance are separate contracts
Input validation specifies the allowed shape, size, and type of a request. Output validation specifies fields and relationships between fields. Acceptance criteria specify whether a validly shaped result actually helps. A result can pass its JSON schema yet answer the wrong question; treating these three layers as interchangeable hides defects.
Our input is a nonempty question of at most 200 characters. The output status is answered or abstain. Answered requires both text and a source; abstain requires neither. We reserve a future review status for cases where a person must make a consequential judgment. Versioning the contract is important: adding a required field or changing the meaning of abstention can break callers even when function names stay unchanged.
Make uncertainty actionable
Abstention is a product behavior, not an embarrassment to conceal. It communicates that the available system cannot support an answer under its rules. The message should explain the limit without pretending that no answer exists anywhere. “Not supported by this handbook” is more precise than “nobody knows.” Human review is a distinct route for sensitive or consequential decisions, conflicting sources, or unresolved ambiguity.
Before model selection, create positive cases, negative cases, malformed inputs, and boundary cases. Record which error matters most. If visitors are merely browsing, an unnecessary abstention may be tolerable. If a response changes a booking or affects access, the system must not infer permission from the fact that a question was asked.
Worked example: build, inspect, and test
Build the response type first, then the lookup, then acceptance checks. The frozen dataclass prevents accidental field reassignment; it does not validate itself, so validate_result performs explicit checks. Matching is intentionally narrow. These are reference rules, not semantic understanding or simulated model intelligence. A new paraphrase that abstains exposes baseline coverage honestly.
from dataclasses import dataclass
@dataclass(frozen=True)
class Result:
status: str
answer: str | None
source_id: str | None
FACTS = {
"when does the workshop open?":
("The workshop opens at 09:00 on weekdays.", "hours-v1"),
"are safety glasses required?":
("Safety glasses are required in the workshop.", "safety-v1"),
}
def validate_result(result):
if result.status not in {"answered", "abstain"}:
raise ValueError("unknown status")
if result.status == "answered":
if not result.answer or not result.source_id:
raise ValueError("answered requires evidence")
elif result.answer is not None or result.source_id is not None:
raise ValueError("abstention must not contain an answer")
return result
def answer(question):
if not isinstance(question, str):
raise ValueError("question must be text")
question = question.strip()
if not question or len(question) > 200:
raise ValueError("question length must be 1..200")
fact = FACTS.get(question.casefold())
result = Result("answered", *fact) if fact else Result("abstain", None, None)
return validate_result(result)
assert answer("When does the workshop open?").source_id == "hours-v1"
assert answer("Can I reserve a room?").status == "abstain"
assert answer(" ARE SAFETY GLASSES REQUIRED? ").status == "answered"
try:
answer(" ")
except ValueError:
print("Empty input rejected")
else:
raise AssertionError("empty input was accepted")
print(answer("When does the workshop open?"))
print(answer("Can I reserve a room?"))Expected output
Empty input rejected
Result(status='answered', answer='The workshop opens at 09:00 on weekdays.', source_id='hours-v1')
Result(status='abstain', answer=None, source_id=None)Failure modes worth testing
Do not equate a high number of answers with good quality. Answering every request can maximize coverage while producing unsupported claims. Conversely, always abstaining can appear safe while providing no utility. Measure the two behaviors separately. Avoid selecting a model before understanding data access, output constraints, and escalation needs. Also avoid putting source URLs, timestamps, or permissions into free-form text when callers need to validate those properties reliably.
Guided lab
Create a one-page contract for a fictional makerspace assistant with three supported intents and three excluded intents. For each supported intent, name the source, expected fields, acceptable variation, and consequence of a wrong response. Include one ambiguous question and one request for an external action. Build a local acceptance list before changing FACTS. Your deliverable is the contract, runnable reference implementation, and a short failure report. Do not hide uncovered paraphrases by deleting difficult cases; classify them as known baseline limitations.
Questions with explained answers
Why build rules before introducing a model?
The rules establish an inexpensive reference point and make the contract executable. They help isolate whether later errors come from retrieval, generation, validation, or an unclear requirement. Their purpose is not to prove that every application should use rules; it is to expose what additional complexity must improve.
Is valid output necessarily correct output?
No. A result can contain the right field names and types while quoting the wrong source or answering an unrelated question. Structural checks protect the interface. Source checks and task-specific acceptance cases evaluate meaning and usefulness. Both are necessary, and neither guarantees general reliability.
Should missing evidence produce a guessed answer?
Under this contract, no. Missing evidence produces abstention, even when a guess sounds plausible. A different product may permit clearly labeled estimates, but that requires an explicit requirement, suitable evidence, and evaluation of the estimate. It cannot be introduced silently as a fallback.
What does a review boundary change?
It changes who can make the final decision. The assistant may collect evidence and prepare a proposal, while a reviewer resolves conflicting or high-impact cases. The application must enforce that boundary in control flow; a sentence asking the model to be careful is not an approval mechanism.
When should the contract version change?
Change it when callers could reasonably interpret results differently: required fields, status meanings, source policies, length limits, or authorization semantics. Record the migration and retain regression cases. A wording change that preserves the contract may only need a content revision, depending on downstream dependencies.
Exercises and worked solutions
Exercise 1. Add a check that the upper input bound is enforced without assuming a particular question is answerable.
Worked answer 1
Test validation independently from knowledge coverage. A 200-character string is valid input and may abstain; 201 characters must fail. This separates interface behavior from the contents of FACTS.
assert answer("x" * 200).status == "abstain"
try:
answer("x" * 201)
except ValueError:
pass
else:
raise AssertionError("length limit missing")Exercise 2. A teammate wants to answer “Can you book it?” with “Booked.” What must change?
Worked answer 2
Booking is an external action outside this read-only contract. Define a booking tool, identify the user and requested reservation, verify permission, confirm required details, and represent success only after the booking system verifies it. Until that workflow exists, abstain or explain that booking is unsupported.
Recap and completion check
You now have an interface with defined inputs, explicit output invariants, traceable sources, and a tested unsupported path. Completion means another developer can describe what the assistant promises and what it refuses without inspecting hidden implementation assumptions. Keep this baseline and contract as later lessons add retrieval, structured proposals, review, and evaluation.
Official references
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.