Semantic validation and refusal
Validate meaning after validating structure
The previous lesson checked field presence, types and allowed values. A well-formed record can still name an item that does not exist, report an incorrect quantity, or use a unit incompatible with a catalog. Semantic validation checks relationships and evidence that shape alone cannot establish. Treat a generated record as a proposal; the stockroom application is responsible for validation, authorization and any side effect. This lesson uses synthetic item IDs and no inventory changes or financial actions.
Use an independent source of truth
Our catalog maps P1 to its permitted unit, box. The evidence dictionary represents facts independently extracted or reviewed from the original note; it is not another copy of the model answer. If the note is ambiguous, a reviewer must mark the field missing instead of guessing. The function below assumes the shape check has succeeded. It checks missing values, catalog membership, unit consistency and agreement with independent evidence, in that order. A correct record is accepted only for draft review, never for a real operation. The second call changes quantity from 2 to 3; it passes shape but fails evidence. A valid known ID alone cannot establish that the source named that ID.
def semantic_status(record, catalog, evidence): # Precondition: record passed the application's shape check. if any(record[key] is None for key in ("item", "quantity", "unit")): return "review_missing" item = record["item"] if item not in catalog: return "review_unknown_item" if record["unit"] != catalog[item]: return "review_unit" if any(evidence.get(key) != record[key] for key in record): return "review_evidence" return "accepted_for_review"
catalog = {"P1": "box"}evidence = {"item":"P1", "quantity":2, "unit":"box"}print(semantic_status(evidence, catalog, evidence))print(semantic_status(dict(evidence, quantity=3), catalog, evidence))Handle refusals, incomplete responses and invalid output separately
In a real integration inspect the response status, refusal representation and completeness indicators defined by the exact provider before extracting fields. An incomplete response may end mid-object, but even a parseable prefix is not a complete response. A refusal is a distinct outcome, not a quantity of zero. Unknown status and transport errors must be handled without presuming success. The next local routing function uses invented adapter statuses; it is not an API schema. It gives failure statuses precedence over parsed output and only shows a draft when both validation layers pass. The printed routes are stop_refusal, show_draft and review_incomplete. A refusal must not be bypassed by repeatedly rephrasing a request. A transient transport failure may warrant a bounded retry under a separate policy; semantic or schema failures can go to review, not unlimited repair loops.
def route_response(status, valid_shape, semantic_result): # Local adapter statuses, not a provider API contract. if status == "refused": return "stop_refusal" if status == "incomplete": return "review_incomplete" if status != "complete": return "review_transport" if not valid_shape: return "review_shape" if semantic_result != "accepted_for_review": return "review_semantics" return "show_draft"
print(route_response("refused", True, "accepted_for_review"))print(route_response("complete", True, "accepted_for_review"))print(route_response("incomplete", True, "accepted_for_review"))Design a safe fallback
If the chosen provider does not support a required schema feature, use a verified simpler supported contract, a deterministic parser where possible, or manual entry with review. Do not quietly remove critical constraints. Keep raw and normalized representations separate; record schema version, status and error codes, but avoid logging sensitive source text. For an extraction service, measure complete response rate, schema pass rate, field-level accuracy on labeled examples, abstention coverage and error rates among accepted records. Report denominators: 90 correct out of 100 accepted is not the same as 90 correct out of 1,000 submitted. Track review load and critical errors rather than optimizing only JSON validity.
Practice and next step
Try a valid-shape response with item P9, a missing quantity, and an incorrect but permitted unit. Verify that every case routes to review. Try an incomplete status with a valid record; it still cannot be shown. Write a deterministic fixture table with source, expected draft and expected error route. If a real provider returns unsupported or unknown status, stop or review until the adapter has been verified. In the next chapter, map these local ideas to a versioned API interface without exposing credentials.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Semantic validation and refusal quiz
Apply the validation contract to synthetic stockroom records.
A record passes shape checks but names an unknown item. What should happen?
What should be done if an incomplete response contains parseable JSON?
Which input is suitable as independent evidence?
Which action is appropriate after a refusal?
A service accepts 100 of 1,000 responses and 90 accepted records are correct. What must be reported?