Schema-Valid Isn't Correct: Parse LLM Output With Pydantic, Then Let Your Domain Refuse It A developer describes a two-gate pattern for handling LLM-generated refund proposals: parse the model's JSON with Pydantic's model_validate_json inside the provider adapter to enforce shape, then pass the result to a domain factory that rejects proposals violating business rules (such as order ownership or remaining refundable balance) with typed errors. The approach follows Hexagonal Architecture, treating the model as one more external device, and keeps business rules in the domain so every caller — admin screens, bulk imports, payment webhooks — goes through the same checks rather than duplicating them in per-request schemas. A customer writes to your support bot: "My mug arrived broken. Please refund order B-200, all of it." Your refund agent asks the model for a proposal and gets back {"order id": "B-200", "amount cents": 9000, "reason": "arrived broken"} . The JSON parses. Every required field is there. Every type is right. Your schema validator is happy. Order B-200 belongs to a different customer, and the order this customer actually placed was $40, with $10 already refunded. Nothing in that reply broke the schema, because the schema never knew about either rule. OpenAI's Structured Outputs guide https://developers.openai.com/api/docs/guides/structured-outputs says it plainly: the feature constrains completed, non-refusal output to your JSON Schema, and your application still has to "validate any business rules that the schema does not express." OpenAI and Anthropic both constrain output to your schema now. Anthropic's structured outputs docs https://platform.claude.com/docs/en/build-with-claude/structured-outputs describe the feature as "constrained decoding" with "guaranteed field types and required fields," requested through output config.format . That is a real improvement over the days of regex-scraping JSON out of prose. Read the same page a little further and the edges show up: minimum and maximum , or string length limits. When you pass a Pydantic model through the SDK's helpers, a minimum: 100 is moved into the field's description and checked after the reply comes back. stop reason: "refusal" and a 200 status, and the docs warn the output "might not match your schema." max tokens "might be incomplete and not match your schema." enum values can come back with different capitalization than the schema lists. So the shape guarantee has holes, and you need a parse step anyway. The bigger point is the one from the opening: even a perfectly shaped reply knows nothing about which orders this customer owns or how much is left to refund. That information lives in your database, per request. You could rebuild the schema on every request with this customer's order IDs as an enum, but then your business rules live in a provider adapter, and the next caller that builds refunds never passes through it. Two gates: the first checks the shape, the second checks whether the business will honour it. There are two different questions here, and they belong in two different places. "Is this reply shaped like a refund proposal?" is a question about one provider's output format. It belongs in the adapter that talks to that provider. Pydantic https://pydantic.dev/docs/validation/latest/concepts/models/ is the right tool: model validate json takes a JSON string and raises a ValidationError when the data doesn't fit. "Will the business honour this refund?" is a question about your rules. It belongs in the core, in a factory that refuses to build a Refund that breaks them, and raises a typed error saying why. This is the split Alistair Cockburn described in the original Hexagonal Architecture article https://alistair.cockburn.us/hexagonal-architecture/ : an application that can be driven by users, programs or automated tests, and developed and tested in isolation from its eventual runtime devices and databases. The model is one more device outside the hexagon. It is also the device most likely to be persuaded by whatever the customer typed. You could push the rules into Pydantic with validators and a validation context. It works, until the second caller arrives: an admin screen, a bulk import, a webhook from your payment provider. Each one builds refunds, and each one would need the same rules copied into its own input model. Put the rule in the domain and every caller goes through it. The layout: refunds/ domain.py Order, Refund, typed refusals ports.py RefundDraft, ReplyUnusable, Protocols use case.py ProposeRefund, HandoffToHuman llm claude.py Pydantic DTO, parse reply, ClaudeSuggester tests/ test propose refund.py test parse reply.py The domain has no imports from Pydantic, the SDK or anything else. Errors are a small hierarchy, so the use case can catch them by kind. python refunds/domain.py from dataclasses import dataclass class RefundRefused Exception : """A proposal the business will not honour.""" class OrderNotFound RefundRefused : ... class WrongCustomer RefundRefused : ... class AmountNotPositive RefundRefused : ... class AmountExceedsRefundable RefundRefused : ... @dataclass frozen=True class Order: order id: str customer id: str total cents: int refunded cents: int = 0 @property def refundable cents self - int: return self.total cents - self.refunded cents @dataclass frozen=True class Refund: order id: str amount cents: int reason: str @classmethod def for order cls, order: Order, customer id: str, amount cents: int, reason: str, - "Refund": if order.customer id = customer id: raise WrongCustomer order.order id if amount cents <= 0: raise AmountNotPositive str amount cents if amount cents order.refundable cents: raise AmountExceedsRefundable f"{amount cents} {order.refundable cents}" return cls order.order id, amount cents, reason Python can't make a dataclass constructor private, so Refund ... is still callable directly. Treat for order as the only way in and keep direct construction to tests. A grep in code review catches the rest. The ports module holds what the core needs from the outside: a plain RefundDraft , one error for "the reply was unusable," and two Protocol s. python refunds/ports.py from dataclasses import dataclass from typing import Protocol from refunds.domain import Order @dataclass frozen=True class RefundDraft: order id: str amount cents: int reason: str class ReplyUnusable Exception : """The model's reply could not become a RefundDraft.""" class RefundSuggester Protocol : def suggest self, customer id: str, message: str, hint: str | None - RefundDraft: ... class OrderLookup Protocol : def get self, order id: str - Order | None: ... The adapter owns everything provider-shaped: the prompt, the request, the stop reason, the Pydantic DTO. parse reply is a pure function, so you can test it without a network. python refunds/llm claude.py import anthropic from pydantic import BaseModel, ConfigDict, ValidationError from refunds.ports import RefundDraft, ReplyUnusable class RefundReply BaseModel : model config = ConfigDict extra="forbid", frozen=True order id: str amount cents: int reason: str SCHEMA = { "type": "object", "properties": { "order id": {"type": "string"}, "amount cents": {"type": "integer"}, "reason": {"type": "string"}, }, "required": "order id", "amount cents", "reason" , "additionalProperties": False, } def parse reply raw: str - RefundDraft: try: dto = RefundReply.model validate json raw except ValidationError as exc: raise ReplyUnusable str exc from exc return RefundDraft dto.order id, dto.amount cents, dto.reason class ClaudeSuggester: def init self, client: anthropic.Anthropic, model: str = "claude-sonnet-5-5", : self. client = client self. model = model def suggest self, customer id: str, message: str, hint: str | None - RefundDraft: prompt = f"Customer {customer id} wrote:\n{message}\n\n" "Propose one refund as JSON with order id, " "amount cents and reason." if hint: prompt += f"\nYour last proposal was refused: {hint}" resp = self. client.messages.create model=self. model, max tokens=512, messages= {"role": "user", "content": prompt} , output config={ "format": {"type": "json schema", "schema": SCHEMA} }, if resp.stop reason = "end turn": raise ReplyUnusable f"stop reason={resp.stop reason}" return parse reply resp.content 0 .text Anthropic's Python SDK https://github.com/anthropics/anthropic-sdk-python also has client.messages.parse , which takes the Pydantic class as output format , sends the schema and validates the reply in one call. The steps are written out here so you can see which half is which. extra="forbid" makes Pydantic reject keys you didn't ask for, which matches "additionalProperties": False on the wire. Notice what the DTO doesn't do. It doesn't check that the amount is positive, and it doesn't look up the order. It turns text into a RefundDraft or raises ReplyUnusable . That's the whole job. The model sits outside the hexagon. The adapter checks the shape; the core decides. Typed errors pay off here. Each kind of refusal gets its own policy. refunds/use case.py from refunds.domain import AmountExceedsRefundable, AmountNotPositive, OrderNotFound, Refund, WrongCustomer, from refunds.ports import OrderLookup, RefundSuggester, ReplyUnusable RETRYABLE = ReplyUnusable, AmountNotPositive, AmountExceedsRefundable, class HandoffToHuman Exception : """Stop automating; a person should look at this.""" class ProposeRefund: def init self, llm: RefundSuggester, orders: OrderLookup, attempts: int = 2, : self. llm = llm self. orders = orders self. attempts = attempts def call self, customer id: str, message: str - Refund: hint: str | None = None for in range self. attempts : try: return self. try once customer id, message, hint except RETRYABLE as exc: hint = f"{type exc . name }: {exc}" except OrderNotFound, WrongCustomer as exc: raise HandoffToHuman f"{type exc . name }: {exc}" from exc raise HandoffToHuman f"gave up after retries; {hint}" def try once self, customer id: str, message: str, hint: str | None - Refund: draft = self. llm.suggest customer id, message, hint order = self. orders.get draft.order id if order is None: raise OrderNotFound draft.order id return Refund.for order order, customer id, draft.amount cents, draft.reason A wrong amount is the kind of mistake a model fixes when you tell it what went wrong, so it gets one more attempt with the refusal as a hint. A broken or refused reply gets the same treatment. An order ID that doesn't exist, or belongs to someone else, goes straight to a person. That ID came from text the customer typed, and you don't want the model taking guesses until it lands on an order that happens to pass. The hint for an amount error includes the refundable balance of the customer's own order. That's information the customer is allowed to see. If your rules involve anything they aren't, write the hint by hand instead of passing the exception text through. The fake implements the port and returns whatever you script: drafts that are perfectly shaped and wrong in a specific way. No network, no API key, no flaky sampling. pytest https://docs.pytest.org/en/stable/how-to/assert.html matches the match= argument with re.search , so a substring of the message is enough. python tests/test propose refund.py import pytest from refunds.domain import Order, Refund from refunds.ports import RefundDraft, ReplyUnusable from refunds.use case import HandoffToHuman, ProposeRefund class ScriptedLLM: def init self, replies : self.replies = list replies self.hints = def suggest self, customer id, message, hint : self.hints.append hint reply = self.replies.pop 0 if isinstance reply, Exception : raise reply return reply class InMemoryOrders: def init self, orders : self. by id = {o.order id: o for o in orders} def get self, order id : return self. by id.get order id MINE = Order "A-100", "cust-1", total cents=4000, refunded cents=1000 THEIRS = Order "B-200", "cust-2", total cents=9000 def draft order id="A-100", amount=2500 : return RefundDraft order id, amount, "arrived broken" def test valid draft becomes refund : use case = ProposeRefund ScriptedLLM draft , InMemoryOrders MINE refund = use case "cust-1", "my mug arrived broken" assert refund == Refund "A-100", 2500, "arrived broken" def test over refundable retries with hint : llm = ScriptedLLM draft amount=4000 , draft amount=3000 use case = ProposeRefund llm, InMemoryOrders MINE refund = use case "cust-1", "refund all of it" assert refund.amount cents == 3000 assert llm.hints 0 is None assert "AmountExceedsRefundable" in llm.hints 1 def test someone elses order goes to a human : llm = ScriptedLLM draft order id="B-200" , draft use case = ProposeRefund llm, InMemoryOrders MINE, THEIRS with pytest.raises HandoffToHuman, match="WrongCustomer" : use case "cust-1", "please refund order B-200" assert len llm.replies == 1 no second attempt def test two bad replies give up : llm = ScriptedLLM draft amount=0 , ReplyUnusable "refusal" use case = ProposeRefund llm, InMemoryOrders MINE with pytest.raises HandoffToHuman, match="gave up" : use case "cust-1", "hello" The third test is the opening scene. The second scripted reply is a valid refund for the customer's own order, and the test asserts it was never requested. The adapter gets its own tests, and one of them pins down the point of this whole post: a reply can sail through Pydantic and still be wrong. python tests/test parse reply.py import pytest from refunds.llm claude import parse reply from refunds.ports import ReplyUnusable @pytest.mark.parametrize "raw", '{"order id": "A-100", "amount cents": "lots",' ' "reason": "x"}', '{"order id": "A-100", "reason": "x"}', "I can't help with that.", def test bad shape is unusable raw : with pytest.raises ReplyUnusable : parse reply raw def test wrong but well formed passes the adapter : raw = '{"order id": "B-200", "amount cents": -500,' ' "reason": "x"}' assert parse reply raw .amount cents == -500 Run them from the project root with python -m pytest , which puts the current directory on the import path so refunds resolves. You need Python 3.10 or later for the str | None syntax, plus pydantic v2 and anthropic installed. That last test reads like a bug report, and it should. The adapter's contract is shape, and a negative refund for someone else's order has a fine shape. The refusal happens one layer in, in code the model never sees and can't argue with. Alexis King's Parse, don't validate https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/ makes the general case: the difference between validating and parsing is whether the information you checked gets kept. A Refund that exists is proof the rules passed. A dict that passed a schema proves only that it has the right keys. The move in this post is keeping the core apart from whatever sits outside it, so a model, a form or a webhook all hit the same rules. Hexagonal Architecture in Python https://www.amazon.com/dp/B0HQWDH23Q is about that boundary in ordinary Python services: it builds one async FastAPI and SQLAlchemy 2 service five ways Hexagonal, Clean, Onion, layered and vertical slice and then measures them. The book has no LLM chapters; it applies this post's design to a whole service, and every listing runs from the free companion repo https://github.com/gabrielanhaia/hexagonal-python-examples .