The hype around structured outputs from LLMs like Claude has led many developers to believe that valid JSON is synonymous with safe execution. A recent article on DEV.to dismantles this dangerous assumption, illustrating a support tool where a perfectly parsed JSON response triggered an incorrect refund because the model hallucinated a different order ID. The core lesson is stark: your backend code must treat the model as an untrusted user, validating not just the shape of the data, but its business logic compliance before any action is taken.
The Illusion of Schema Safety
While features like constrained decoding help keep responses within a JSON schema, they do not enforce business rules. The article notes that API-level schema checks often ignore numeric limits or length constraints, leaving those to SDK helpers. More critically, a schema cannot know that a refund amount exceeds what a customer actually paid, or that an order ID belongs to the current conversation context. OWASP guidelines explicitly warn against improper output handling, urging developers to validate model responses before they reach backend functions, treating the model's output with the same skepticism as external user input.
Implementing Three-Tier Validation
To mitigate these risks, the article proposes a strict three-step validation pipeline. First, check the stop_reason to ensure the model didn't refuse or truncate the output. Second, verify the JSON shape and that the action exists in a known allowlist. Third, and most importantly, validate the content against trusted data from your database. For example, the model's proposed order_id must match the order already loaded for the session, and refund amounts must be checked against the order total using precise decimal arithmetic rather than floats to avoid rounding errors.
Handling Rejections and Edge Cases
When validation fails, the system should not silently fall back to executing the action. Instead, it should reject the request with a specific reason code, such as order_mismatch or amount_over_limit. This allows for observability and alerting without exposing raw customer data in logs. The article suggests retrying only on max_tokens errors and escalating other failures to human review. This approach ensures that a model's hallucination results in a controlled failure rather than an unintended financial transaction.
Key Takeaways
- Valid JSON does not imply valid business logic; always check against trusted database records.
- Use
Decimaltypes for monetary values to prevent floating-point drift during validation. - Implement an allowlist for actions to reject unexpected model outputs like
delete_account. - Treat
stop_reasonas the first line of defense against incomplete or refused responses.
The Bottom Line
Stop trusting schema compliance as a safety net. If your code acts on LLM output without cross-referencing trusted database state, you are one hallucinated order ID away from a financial disaster.