Here's an illustrative support tool. A model reads a customer message and returns a small JSON object: which order it's about, what to do (refund, replace or escalate) and, for refunds, how much. The backend parses the JSON and calls the payments service.
It works for weeks. Then a message that says "I was charged twice, refund the other order too" comes back with a different order ID, and a refund for more than the item cost. The JSON was perfectly valid. That was the problem: the code treated "it parsed" as "it's safe to do."
Valid isn't the same as allowed
Schema features help with shape. Claude's structured outputs docs describe constrained decoding that keeps responses to your JSON schema, and they also list the exceptions. A response that stops with stop_reason of refusal or max_tokens may not match the schema at all. Numeric and length limits like minimum and maxLength aren't enforced by the API itself; the SDK helpers check them in your code. And enum capitalization isn't guaranteed, so compare case-insensitively.
Even a perfect schema can't know your business rules. It can't tell that the order belongs to this customer or that a refund can't exceed what they paid. OWASP's entry on improper output handling puts it plainly: treat the model like any other user and validate its responses before they reach backend functions.
So split the work into three checks:
model response
|
v
1. did it finish? stop_reason == end_turn
|
v
2. is it the right shape? JSON object, known action
|
v
3. is it allowed? checked against data you trust
|
v
act, or reject with a reason code
The code
import json
from decimal import Decimal, InvalidOperation
ACTIONS = {"refund", "replace", "escalate"}
MAX_REFUND = Decimal("200.00") # illustrative policy limit
class Rejected(Exception):
def __init__(self, code):
super().__init__(code)
self.code = code
def check_triage(stop_reason, text, order):
"""Turn model text into a decision we're willing to act on.
order comes from your database, never from the model."""
if stop_reason != "end_turn":
raise Rejected(f"stop_reason:{stop_reason}")
try:
data = json.loads(text)
except json.JSONDecodeError:
raise Rejected("not_json")
if not isinstance(data, dict):
raise Rejected("not_object")
action = str(data.get("action", "")).strip().lower()
if action not in ACTIONS:
raise Rejected("unknown_action")
if data.get("order_id") != order["id"]:
raise Rejected("order_mismatch")
if action != "refund":
return {"action": action, "order_id": order["id"]}
try:
amount = Decimal(str(data.get("amount")))
except InvalidOperation:
raise Rejected("amount_not_number")
if not amount.is_finite() or amount <= 0:
raise Rejected("amount_out_of_range")
if amount > min(MAX_REFUND, order["total"]):
raise Rejected("amount_over_limit")
return {"action": "refund", "order_id": order["id"],
"amount": amount.quantize(Decimal("0.01"))}
A few choices worth calling out:
-
The order comes from your database. The model's
order_idhas to match the order you already loaded for this conversation. It can't point the action somewhere else. -
Decimal, not float. Money comparisons with floats drift.
Decimal("NaN")and negatives are rejected explicitly. -
Reason codes, not raw text.
Rejectedcarries a short code you can count and alert on without copying customer messages into logs. -
An allowlist of actions. Anything outside
ACTIONSfails, even if it looks reasonable.
Tests
import json
from decimal import Decimal
import pytest
from check import Rejected, check_triage
ORDER = {"id": "ord_123", "total": Decimal("80.00")}
def ok(**fields):
return json.dumps({"order_id": "ord_123", **fields})
def code_for(stop_reason, text):
with pytest.raises(Rejected) as err:
check_triage(stop_reason, text, ORDER)
return err.value.code
def test_valid_refund_passes_with_exact_amount():
out = check_triage("end_turn", ok(action="refund", amount=19.99),
ORDER)
assert out["amount"] == Decimal("19.99")
def test_enum_casing_is_normalized():
out = check_triage("end_turn", ok(action="Escalate"), ORDER)
assert out["action"] == "escalate"
def test_truncated_or_refused_output_is_never_parsed():
assert code_for("max_tokens", '{"action": "ref') == \
"stop_reason:max_tokens"
assert code_for("refusal", "Sorry") == "stop_reason:refusal"
def test_well_formed_but_unsafe_values_are_rejected():
assert code_for("end_turn", ok(action="refund", amount=-5)) == \
"amount_out_of_range"
nan = ok(action="refund", amount="NaN")
assert code_for("end_turn", nan) == "amount_out_of_range"
assert code_for("end_turn", ok(action="refund", amount=95)) == \
"amount_over_limit"
def test_model_cannot_pick_a_different_order():
text = json.dumps({"order_id": "ord_999", "action": "refund",
"amount": 10})
assert code_for("end_turn", text) == "order_mismatch"
def test_unknown_action_is_rejected():
assert code_for("end_turn", ok(action="delete_account")) == \
"unknown_action"
The tests don't call a model. They feed in the outputs you're worried about, which is easier to keep stable than a live call.
What to do when a check fails
Don't silently fall back to "do it anyway." Common options:
- Send the case to a person, with the reason code.
- Retry once if the failure was
max_tokens, with a larger limit. - Count rejections by code. A jump in
order_mismatchafter a prompt change tells you something.
Limits
- This checks one structured decision. Free text shown to users still needs output encoding for the place it's rendered.
- Your limits are only as good as the data behind them. If
order["total"]is wrong, the check passes wrong refunds. - Validation doesn't make the model's judgment right. A refund can pass every rule and still be the wrong call, which is why people review edge cases.
Where this fits
We work on Obligra Verify, which is designed to retain the evidence your application selects. Our server-side capture pattern makes a related point about trust: records are submitted from your backend after the workflow produces an output, and frontend or mobile clients don't call Verify directly.
This article was generated by an AI agent (Claude) for the Obligra Verify team and checked against the linked sources.
Top comments (0)