Python Master Course V2 — 180. AI Application Capstone: A Cited Knowledge Assistant
Lesson 180: AI Application Capstone: A Cited Knowledge Assistant
This capstone combines the previous lessons into a local cited knowledge assistant that you can inspect end to end. The required backend is deterministic and extractive. It answers from two included fictional handbook passages, returns stable citations, abstains on unsupported or ambiguous queries, and routes high-impact requests to a review record. A built-in evaluation command checks behavior and produces real local timing observations without claiming to measure an LLM.
Learning objectives
- Integrate retrieval, validated outputs and bounded workflows
- Evaluate support, abstention, injection resistance and latency
- Deliver a local application with reviewable evidence and limitations
Prerequisites and setup
171–179: AI applications and evaluation; 120: tested packaging
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 lesson180.py. Run the example before extending it; keep the original assertions as regression checks.
python lesson180.pyDefine the release boundary
The application is a command-line program, not a public service. Its only data source is the included corpus, and its only tool is read-only search. It cannot send messages, reserve resources, execute shell commands, or fetch URLs. These constraints are enforced by its interface and registry rather than left to an instruction embedded in a prompt.
The output contract contains status, answer, citations, and a reason. An answered result must equal a cited passage. An abstention has no answer or citations. A review result records that a person must resolve the request; it does not imply approval or execution. Source IDs refer to local handbook records, so the deliverable must include those records and their version.
Integrate components without hiding their limits
The retriever uses conservative topic matching and requires exactly one candidate. This gives predictable behavior but poor linguistic coverage. A more capable retriever can be substituted later if it preserves source identity and access boundaries. Keep the answer constructor separate so changing retrieval does not accidentally change output validation.
The high-impact flag represents trusted application policy in this teaching program. It is not inferred from a document and should not be accepted as a permission-granting field from a model. In a real interface, define how impact is classified and who may override a decision. Our review queue records only an invented request ID and reason, minimizing unnecessary data.
A release needs evidence and limitations
The evaluation command should check positive answers, unsupported questions, ambiguity, review routing, citation integrity, and an invalid tool. Add a harmless injection document during testing and confirm that it cannot create a new capability. Record measured latency separately from pass/fail behavior. A single successful test run is evidence for the cases exercised, not proof of complete safety or generalization.
Package the source, a README, corpus snapshot, evaluation cases, environment information, and a failure analysis. Keep development examples separate from any newly reserved evaluation set. If you add an optional local generative model, label that backend and evaluate it separately with its model version and settings. Never report the deterministic baseline’s results as model accuracy.
Worked example: build, inspect, and test
Save the complete program as lesson180.py. Running it with no arguments executes the evaluation cases. Running it with a quoted question returns one JSON response. The evaluation prints stable behavior counts and a statement that timing samples were collected; it keeps the measured values in the local latencies list for inspection. The response for an opening-hours question includes a doc:// citation that resolves to DOCS.
import json
import re
import sys
from time import perf_counter_ns
DOCS = {
"hours-v1": {"text": "The workshop opens at 09:00 on weekdays.",
"topics": {"opening", "hours", "open", "workshop"}},
"safety-v1": {"text": "Safety glasses are required in the workshop.",
"topics": {"safety", "glasses", "required", "workshop"}},
}
STOP = {"the", "what", "when", "does", "are", "is"}
REVIEWS = []
def search(question):
words = set(re.findall(r"[a-z0-9]+", question.casefold())) - STOP
return sorted(id_ for id_, doc in DOCS.items() if words and words <= doc["topics"])
TOOLS = {"search": search}
def call_tool(name, question):
if name not in TOOLS:
raise ValueError("tool is not allowed")
return TOOLS[name](question)
def validate(result):
if set(result) != {"status", "answer", "citations", "reason"}:
raise ValueError("response fields")
if result["status"] == "answered":
if len(result["citations"]) != 1:
raise ValueError("exactly one citation required")
cite = result["citations"][0]
if cite["source_id"] not in DOCS:
raise ValueError("unknown source")
if result["answer"] != DOCS[cite["source_id"]]["text"]:
raise ValueError("unsupported answer")
if cite["uri"] != "doc://" + cite["source_id"]:
raise ValueError("incorrect source link")
elif result["status"] in {"abstain", "review"}:
if result["answer"] is not None or result["citations"]:
raise ValueError("non-answer contains evidence claim")
else:
raise ValueError("unknown status")
return result
def answer(question, *, high_impact=False):
if not isinstance(question, str) or not 1 <= len(question.strip()) <= 200:
raise ValueError("question must contain 1..200 characters")
if type(high_impact) is not bool:
raise ValueError("impact flag must be Boolean")
if high_impact:
REVIEWS.append({"id": f"review-{len(REVIEWS) + 1}", "reason": "high_impact"})
return validate({"status": "review", "answer": None,
"citations": [], "reason": "human decision required"})
matches = call_tool("search", question)
if len(matches) != 1:
return validate({"status": "abstain", "answer": None,
"citations": [], "reason": "missing or ambiguous evidence"})
id_ = matches[0]
return validate({"status": "answered", "answer": DOCS[id_]["text"],
"citations": [{"source_id": id_, "uri": "doc://" + id_}],
"reason": "exact source excerpt"})
def evaluate():
cases = [("opening hours", "answered"), ("safety glasses", "answered"),
("parking price", "abstain"), ("workshop", "abstain")]
latencies = []
for question, expected in cases:
start = perf_counter_ns()
result = answer(question)
latencies.append(perf_counter_ns() - start)
assert result["status"] == expected
assert answer("opening hours", high_impact=True)["status"] == "review"
try:
call_tool("send_email", "demo")
except ValueError:
pass
else:
raise AssertionError("unknown tool executed")
print("behavior cases passed:", len(cases))
print("review and tool-boundary checks passed")
print("latency samples collected:", len(latencies))
return latencies
if __name__ == "__main__":
if len(sys.argv) == 1:
latencies = evaluate()
else:
print(json.dumps(answer(" ".join(sys.argv[1:])), ensure_ascii=False))Expected output
behavior cases passed: 4
review and tool-boundary checks passed
latency samples collected: 4python lesson180.py "opening hours"Failure modes worth testing
Do not bury abstentions in logs while displaying a confident answer to the user. Do not call the four teaching cases a statistically meaningful benchmark. Avoid importing an untrusted serialized model merely to make the project seem more advanced. The strongest capstone is a small system with reproducible behavior, clear evidence, and honest limits; extra dependencies must earn their place through a measurable benefit.
Guided lab
Create a release folder containing the program, a versioned corpus, a contract document, and an evaluation report. Add at least eight new questions covering paraphrases, missing evidence, conflicting sources, and invalid input. Introduce a harmless document that claims permission to send a message and confirm that the application still has no such tool. Inspect every answered case manually for relevance. Finish by documenting three limitations and one justified improvement, then run the complete checks from a fresh local project directory.
Questions with explained answers
Why is the deterministic backend required?
It gives every learner a free, offline, inspectable baseline and separates application engineering from model availability. The important integration work still exists: retrieval, citations, validation, review routing, and evaluation. A real model can be added later without replacing these boundaries or inheriting their test results automatically.
What makes a citation valid in this application?
Its source ID exists in the included corpus, its local URI matches that ID, and the answer equals the stored passage. Those checks establish provenance for this extractive contract. A human still needs to assess relevance, completeness, and whether the source itself is authoritative and current.
Does review status mean an action was approved?
No. It means the application has created a record requiring a human decision and returned no substantive answer. There is no action executor in this capstone. A future executor would need to verify approval scope and current conditions before performing any consequential operation.
How should a generative extension be reported?
Name the actual model, version, runtime, settings, prompt version, and evaluation sample. Report generated-answer support and relevance separately from baseline results. Label any simulated outputs as fixtures. The presence of a model does not justify removing abstention, citation checks, or tool authorization.
What belongs in the release README?
Include installation and run commands, supported questions, source provenance, output status meanings, evaluation instructions, measured environment, known failures, and the absence of external-action capabilities. A new reader should be able to reproduce the local behavior and understand the limits without asking the author for hidden setup steps.
Exercises and worked solutions
Exercise 1. Verify that a cited answer can be resolved back to the included record.
Worked answer 1
Follow the returned source ID rather than guessing a document from answer text. This test protects the relationship between response construction and corpus identity.
result = answer("opening hours")
citation = result["citations"][0]
assert citation["uri"] == "doc://" + citation["source_id"]
assert DOCS[citation["source_id"]]["text"] == result["answer"]Exercise 2. The application abstains on a reasonable paraphrase. What is the next responsible change?
Worked answer 2
Add the paraphrase to development evidence, investigate whether retrieval or the contract is too restrictive, and make a targeted improvement. Preserve unsupported and ambiguous cases, then test on newly reserved questions. Do not simply weaken the system to return the first source for every query.
Recap and completion check
You have integrated a cited assistant whose capabilities and evidence are visible in a single local program. Completion requires a runnable release, a reproducible evaluation report, a review boundary, and documented limitations. This capstone is the bridge from experimenting with components to operating a service that can explain what it did and why.
Official references
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.