Python Master Course V2 — 178. Human Review, Feedback and Escalation Workflows
Lesson 178: Human Review, Feedback and Escalation Workflows
Human review is useful only when uncertain work reaches the right person with enough evidence to decide and remains unresolved until that decision is recorded. A queue that automatically marks every item approved is not meaningful oversight. This lesson builds a small local queue for synthetic assistant requests, records explicit reviewer outcomes, and keeps feedback separate from production behavior. No personal data, external messages, or automatic model retraining is involved.
Learning objectives
- Route uncertain or high-impact outputs to human review
- Design feedback records without leaking unnecessary personal information
- Separate feedback collection from automatic model retraining
Prerequisites and setup
138: thresholds; 160: review queues; 176–177: evaluation and boundaries
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 lesson178.py. Run the example before extending it; keep the original assertions as regression checks.
python lesson178.pyRoute by consequence and evidence
A review rule can consider impact, missing evidence, conflicting sources, validation failures, and uncertainty. Do not use a model’s self-reported confidence as a calibrated probability without evidence. Even a well-calibrated prediction score is not a substitute for policy: some high-impact actions require review regardless of confidence. Conversely, sending every trivial question to a reviewer can overwhelm the queue and hide urgent cases.
Define what happens while a case waits. The user should receive a pending or abstention status rather than a fabricated final answer. The application should not execute the consequential action before review. Specify an owner, priority, expiry policy, and escalation route as the workflow matures. In this local exercise, unresolved cases remain visibly pending and no action executor exists.
Use explicit states and transitions
Our states are pending, approved, rejected, and needs_information. The first reviewer decision is permitted only for a pending item, preventing accidental double resolution. A real system may allow appeals or reopening, but those should be explicit transitions with history, not silent overwrites. Store the reviewer identity, decision reason code, and a reference to the evidence version considered.
An approval record is not automatically authorization for every downstream action. It applies to the specific reviewed proposal and scope. If the target, data, amount, or material circumstances change, the workflow needs a new decision. Keeping proposal identity separate from free-form conversation makes this boundary easier to enforce.
Collect useful feedback without creating a new data leak
A review record should include the minimum information necessary to understand the decision. Prefer request IDs, category codes, evidence references, and a short structured reason over full prompts containing personal details. Limit access, define retention, and redact unnecessary content before sharing reports. Our synthetic examples demonstrate minimization by storing no raw user message at all.
Feedback is an observation about a case, not an automatic training label. Reviewers can disagree, misunderstand the task, or see stale evidence. Aggregate feedback, investigate recurring patterns, revise data or policy deliberately, and evaluate changes before release. The example keeps a fixed production version to demonstrate that recording an approval does not silently change the assistant’s behavior.
Worked example: build, inspect, and test
The queue is an in-memory dictionary so the state machine is easy to inspect. route queues high-impact or unsupported requests and allows only supported low-impact responses to continue. decide accepts a known reviewer and reason code, then records a final or information-needed state. The example approves one item, leaves another pending, and confirms that the production version did not change.
from dataclasses import dataclass
@dataclass
class ReviewItem:
request_id: str
evidence_version: str
reason: str
state: str = "pending"
reviewer: str | None = None
decision_reason: str | None = None
QUEUE = {}
REVIEWERS = frozenset({"reviewer-demo"})
PRODUCTION_VERSION = "assistant-1.0"
def route(request_id, *, high_impact, supported, evidence_version):
if type(high_impact) is not bool or type(supported) is not bool:
raise ValueError("routing flags must be Boolean")
if not high_impact and supported:
return "answer"
if request_id in QUEUE:
raise ValueError("duplicate request")
reason = "high_impact" if high_impact else "missing_evidence"
QUEUE[request_id] = ReviewItem(request_id, evidence_version, reason)
return "pending_review"
def decide(request_id, reviewer, decision, reason):
if reviewer not in REVIEWERS:
raise ValueError("unknown reviewer")
if decision not in {"approved", "rejected", "needs_information"}:
raise ValueError("unknown decision")
if reason not in {"evidence_checked", "unsupported", "clarification_needed"}:
raise ValueError("unknown reason code")
item = QUEUE[request_id]
if item.state != "pending":
raise ValueError("case already reviewed")
item.state, item.reviewer, item.decision_reason = decision, reviewer, reason
return item
before = PRODUCTION_VERSION
print(route("request-a", high_impact=True, supported=True, evidence_version="kb-1"))
print(route("request-b", high_impact=False, supported=False, evidence_version="kb-1"))
decide("request-a", "reviewer-demo", "approved", "evidence_checked")
print("pending:", sum(item.state == "pending" for item in QUEUE.values()))
print("production:", PRODUCTION_VERSION)
assert PRODUCTION_VERSION == before
assert "raw_prompt" not in vars(QUEUE["request-a"])Expected output
pending_review
pending_review
pending: 1
production: assistant-1.0Failure modes worth testing
Do not interpret silence as approval or a cleared warning as a positive decision. Do not erase rejected cases merely to make approval rates look better. A high approval rate may reflect rubber-stamping, poor routing, or easy cases rather than quality. Avoid treating reviewer comments as trusted instructions to execute new actions; review scope must remain tied to the original proposal and applicable policy. REVIEWERS is a local identity fixture, not authentication: checking a supplied name against a set does not prove who is using the application. A real service must derive reviewer identity from a verified session and enforce its access rights.
Guided lab
Extend the queue with an explicit reopen operation that preserves the previous decision in an append-only history. Add a synthetic case whose evidence version changes while waiting and require a fresh review before approval. Define a small dashboard summary showing pending, needs-information, approved, and rejected counts. Your deliverable should explain who reviews each case, what evidence they see, and what happens when nobody responds. Keep the queue local and use invented IDs rather than real names or messages.
Questions with explained answers
Why review a high-impact case with strong evidence?
Evidence quality and action consequence are different dimensions. A source can be accurate while the resulting action still requires judgment or explicit authorization. The routing rule therefore checks impact independently of support, and the application withholds consequential execution until the required decision exists.
Does needs_information mean the case is finished?
It means a reviewer has identified a blocker, not that the user’s underlying task is complete. The item should remain visible in a separate unresolved category. A later response may trigger an explicit reopen or continuation path, preserving the earlier request for clarification.
Why avoid storing the full prompt in every review record?
Full prompts can contain unnecessary personal details, confidential documents, or credentials. Structured references often provide enough context for authorized reviewers while reducing duplication and exposure. When full evidence is genuinely needed, store it in an access-controlled location with a defined retention policy.
Should every approval become a training example?
No. Approval may concern policy, formatting, or a one-off exception rather than a generalizable correct answer. Review the label, evidence, consent, and intended use before adding data to training or evaluation. Feedback collection and model updates should be separate, auditable workflows.
What protects against two reviewers resolving the same case?
The example checks the state before updating, which is sufficient for its single-threaded demonstration. A concurrent system needs an atomic compare-and-update or transaction with a version field. Otherwise both reviewers may observe pending and overwrite each other’s decisions despite the check.
Exercises and worked solutions
Exercise 1. Try to review the approved case a second time and confirm rejection.
Worked answer 1
State transitions are part of the contract. A second decision must use a defined appeal or reopen path rather than overwriting history. The current simple queue has no such path.
try:
decide("request-a", "reviewer-demo", "rejected", "unsupported")
except ValueError as error:
assert str(error) == "case already reviewed"
else:
raise AssertionError("second decision overwrote the first")Exercise 2. Design a safe response when a reviewer is unavailable.
Worked answer 2
Return a pending-review or abstention status with an honest explanation of what remains unresolved. Apply a documented escalation or expiry policy if one exists; do not manufacture approval or execute the action. For this local lab, leave the item visible and report its unresolved state.
Recap and completion check
You have a review workflow with explicit routing, visible unresolved work, controlled state transitions, and minimized feedback records. Completion means an approval can be traced to a specific case and evidence version while production behavior remains unchanged. Useful human oversight is a process with ownership and boundaries, not a checkbox attached to an automated answer.
Official references
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.