{"slug": "schema-valid-isn-t-correct-parse-llm-output-with-pydantic-then-let-your-domain", "title": "Schema-Valid Isn't Correct: Parse LLM Output With Pydantic, Then Let Your Domain Refuse It", "summary": "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.", "body_md": "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\"}`.\n\nThe 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.\n\nNothing 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.\"\n\nOpenAI 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.\n\nRead the same page a little further and the edges show up:\n\n`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.\nSo 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.\n\n*Two gates: the first checks the shape, the second checks whether the business will honour it.*\n\nThere are two different questions here, and they belong in two different places.\n\n\"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.\n\n\"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.\n\nThis 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.\n\nYou 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.\n\nThe layout:\n\n```\nrefunds/\n  domain.py      # Order, Refund, typed refusals\n  ports.py       # RefundDraft, ReplyUnusable, Protocols\n  use_case.py    # ProposeRefund, HandoffToHuman\n  llm_claude.py  # Pydantic DTO, parse_reply, ClaudeSuggester\ntests/\n  test_propose_refund.py\n  test_parse_reply.py\n```\n\nThe 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.\n\n``` python\n# refunds/domain.py\nfrom dataclasses import dataclass\n\nclass RefundRefused(Exception):\n    \"\"\"A proposal the business will not honour.\"\"\"\n\nclass OrderNotFound(RefundRefused): ...\nclass WrongCustomer(RefundRefused): ...\nclass AmountNotPositive(RefundRefused): ...\nclass AmountExceedsRefundable(RefundRefused): ...\n\n@dataclass(frozen=True)\nclass Order:\n    order_id: str\n    customer_id: str\n    total_cents: int\n    refunded_cents: int = 0\n\n    @property\n    def refundable_cents(self) -> int:\n        return self.total_cents - self.refunded_cents\n\n@dataclass(frozen=True)\nclass Refund:\n    order_id: str\n    amount_cents: int\n    reason: str\n\n    @classmethod\n    def for_order(\n        cls, order: Order, customer_id: str,\n        amount_cents: int, reason: str,\n    ) -> \"Refund\":\n        if order.customer_id != customer_id:\n            raise WrongCustomer(order.order_id)\n        if amount_cents <= 0:\n            raise AmountNotPositive(str(amount_cents))\n        if amount_cents > order.refundable_cents:\n            raise AmountExceedsRefundable(\n                f\"{amount_cents} > {order.refundable_cents}\"\n            )\n        return cls(order.order_id, amount_cents, reason)\n```\n\nPython 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.\n\nThe ports module holds what the core needs from the outside: a plain `RefundDraft`, one error for \"the reply was unusable,\" and two `Protocol` s.\n\n``` python\n# refunds/ports.py\nfrom dataclasses import dataclass\nfrom typing import Protocol\n\nfrom refunds.domain import Order\n\n@dataclass(frozen=True)\nclass RefundDraft:\n    order_id: str\n    amount_cents: int\n    reason: str\n\nclass ReplyUnusable(Exception):\n    \"\"\"The model's reply could not become a RefundDraft.\"\"\"\n\nclass RefundSuggester(Protocol):\n    def suggest(\n        self, customer_id: str, message: str, hint: str | None\n    ) -> RefundDraft: ...\n\nclass OrderLookup(Protocol):\n    def get(self, order_id: str) -> Order | None: ...\n```\n\nThe 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.\n\n``` python\n# refunds/llm_claude.py\nimport anthropic\nfrom pydantic import BaseModel, ConfigDict, ValidationError\n\nfrom refunds.ports import RefundDraft, ReplyUnusable\n\nclass RefundReply(BaseModel):\n    model_config = ConfigDict(extra=\"forbid\", frozen=True)\n    order_id: str\n    amount_cents: int\n    reason: str\n\nSCHEMA = {\n    \"type\": \"object\",\n    \"properties\": {\n        \"order_id\": {\"type\": \"string\"},\n        \"amount_cents\": {\"type\": \"integer\"},\n        \"reason\": {\"type\": \"string\"},\n    },\n    \"required\": [\"order_id\", \"amount_cents\", \"reason\"],\n    \"additionalProperties\": False,\n}\n\ndef parse_reply(raw: str) -> RefundDraft:\n    try:\n        dto = RefundReply.model_validate_json(raw)\n    except ValidationError as exc:\n        raise ReplyUnusable(str(exc)) from exc\n    return RefundDraft(dto.order_id, dto.amount_cents, dto.reason)\n\nclass ClaudeSuggester:\n    def __init__(\n        self, client: anthropic.Anthropic,\n        model: str = \"claude-sonnet-5-5\",\n    ):\n        self._client = client\n        self._model = model\n\n    def suggest(\n        self, customer_id: str, message: str, hint: str | None\n    ) -> RefundDraft:\n        prompt = (\n            f\"Customer {customer_id} wrote:\\n{message}\\n\\n\"\n            \"Propose one refund as JSON with order_id, \"\n            \"amount_cents and reason.\"\n        )\n        if hint:\n            prompt += f\"\\nYour last proposal was refused: {hint}\"\n        resp = self._client.messages.create(\n            model=self._model,\n            max_tokens=512,\n            messages=[{\"role\": \"user\", \"content\": prompt}],\n            output_config={\n                \"format\": {\"type\": \"json_schema\", \"schema\": SCHEMA}\n            },\n        )\n        if resp.stop_reason != \"end_turn\":\n            raise ReplyUnusable(f\"stop_reason={resp.stop_reason}\")\n        return parse_reply(resp.content[0].text)\n```\n\n[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.\n\nNotice 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.\n\n*The model sits outside the hexagon. The adapter checks the shape; the core decides.*\n\nTyped errors pay off here. Each kind of refusal gets its own policy.\n\n```\n# refunds/use_case.py\nfrom refunds.domain import (\n    AmountExceedsRefundable, AmountNotPositive,\n    OrderNotFound, Refund, WrongCustomer,\n)\nfrom refunds.ports import OrderLookup, RefundSuggester, ReplyUnusable\n\nRETRYABLE = (\n    ReplyUnusable, AmountNotPositive, AmountExceedsRefundable,\n)\n\nclass HandoffToHuman(Exception):\n    \"\"\"Stop automating; a person should look at this.\"\"\"\n\nclass ProposeRefund:\n    def __init__(\n        self, llm: RefundSuggester, orders: OrderLookup,\n        attempts: int = 2,\n    ):\n        self._llm = llm\n        self._orders = orders\n        self._attempts = attempts\n\n    def __call__(self, customer_id: str, message: str) -> Refund:\n        hint: str | None = None\n        for _ in range(self._attempts):\n            try:\n                return self._try_once(customer_id, message, hint)\n            except RETRYABLE as exc:\n                hint = f\"{type(exc).__name__}: {exc}\"\n            except (OrderNotFound, WrongCustomer) as exc:\n                raise HandoffToHuman(\n                    f\"{type(exc).__name__}: {exc}\"\n                ) from exc\n        raise HandoffToHuman(f\"gave up after retries; {hint}\")\n\n    def _try_once(\n        self, customer_id: str, message: str, hint: str | None\n    ) -> Refund:\n        draft = self._llm.suggest(customer_id, message, hint)\n        order = self._orders.get(draft.order_id)\n        if order is None:\n            raise OrderNotFound(draft.order_id)\n        return Refund.for_order(\n            order, customer_id, draft.amount_cents, draft.reason\n        )\n```\n\nA 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.\n\nThe 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.\n\nThe 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.\n\n``` python\n# tests/test_propose_refund.py\nimport pytest\n\nfrom refunds.domain import Order, Refund\nfrom refunds.ports import RefundDraft, ReplyUnusable\nfrom refunds.use_case import HandoffToHuman, ProposeRefund\n\nclass ScriptedLLM:\n    def __init__(self, *replies):\n        self.replies = list(replies)\n        self.hints = []\n\n    def suggest(self, customer_id, message, hint):\n        self.hints.append(hint)\n        reply = self.replies.pop(0)\n        if isinstance(reply, Exception):\n            raise reply\n        return reply\n\nclass InMemoryOrders:\n    def __init__(self, *orders):\n        self._by_id = {o.order_id: o for o in orders}\n\n    def get(self, order_id):\n        return self._by_id.get(order_id)\n\nMINE = Order(\"A-100\", \"cust-1\", total_cents=4000,\n             refunded_cents=1000)\nTHEIRS = Order(\"B-200\", \"cust-2\", total_cents=9000)\n\ndef draft(order_id=\"A-100\", amount=2500):\n    return RefundDraft(order_id, amount, \"arrived broken\")\n\ndef test_valid_draft_becomes_refund():\n    use_case = ProposeRefund(ScriptedLLM(draft()),\n                             InMemoryOrders(MINE))\n    refund = use_case(\"cust-1\", \"my mug arrived broken\")\n    assert refund == Refund(\"A-100\", 2500, \"arrived broken\")\n\ndef test_over_refundable_retries_with_hint():\n    llm = ScriptedLLM(draft(amount=4000), draft(amount=3000))\n    use_case = ProposeRefund(llm, InMemoryOrders(MINE))\n    refund = use_case(\"cust-1\", \"refund all of it\")\n    assert refund.amount_cents == 3000\n    assert llm.hints[0] is None\n    assert \"AmountExceedsRefundable\" in llm.hints[1]\n\ndef test_someone_elses_order_goes_to_a_human():\n    llm = ScriptedLLM(draft(order_id=\"B-200\"), draft())\n    use_case = ProposeRefund(llm, InMemoryOrders(MINE, THEIRS))\n    with pytest.raises(HandoffToHuman, match=\"WrongCustomer\"):\n        use_case(\"cust-1\", \"please refund order B-200\")\n    assert len(llm.replies) == 1  # no second attempt\n\ndef test_two_bad_replies_give_up():\n    llm = ScriptedLLM(draft(amount=0), ReplyUnusable(\"refusal\"))\n    use_case = ProposeRefund(llm, InMemoryOrders(MINE))\n    with pytest.raises(HandoffToHuman, match=\"gave up\"):\n        use_case(\"cust-1\", \"hello\")\n```\n\nThe 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.\n\nThe 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.\n\n``` python\n# tests/test_parse_reply.py\nimport pytest\n\nfrom refunds.llm_claude import parse_reply\nfrom refunds.ports import ReplyUnusable\n\n@pytest.mark.parametrize(\"raw\", [\n    '{\"order_id\": \"A-100\", \"amount_cents\": \"lots\",'\n    ' \"reason\": \"x\"}',\n    '{\"order_id\": \"A-100\", \"reason\": \"x\"}',\n    \"I can't help with that.\",\n])\ndef test_bad_shape_is_unusable(raw):\n    with pytest.raises(ReplyUnusable):\n        parse_reply(raw)\n\ndef test_wrong_but_well_formed_passes_the_adapter():\n    raw = ('{\"order_id\": \"B-200\", \"amount_cents\": -500,'\n           ' \"reason\": \"x\"}')\n    assert parse_reply(raw).amount_cents == -500\n```\n\nRun 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.\n\nThat 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.\n\nThe 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).", "url": "https://wpnews.pro/news/schema-valid-isn-t-correct-parse-llm-output-with-pydantic-then-let-your-domain", "canonical_source": "https://dev.to/gabrielanhaia/schema-valid-isnt-correct-parse-llm-output-with-pydantic-then-let-your-domain-refuse-it-i1c", "published_at": "2026-11-28 16:01:24+00:00", "updated_at": "2026-11-28 16:14:24.505009+00:00", "lang": "en", "topics": ["large-language-models", "ai-agents", "ai-tools", "developer-tools"], "entities": ["OpenAI", "Anthropic", "Pydantic", "Alistair Cockburn"], "also_reported_by": [], "takeaway": "Schema-constrained decoding only guarantees shape, so parse LLM output with Pydantic in the provider adapter and enforce business rules like order ownership and refund balance in a domain factory that every caller must pass through.", "recommendation": {"advice": "Keep Pydantic parsing in the provider adapter for shape, and put business rules in a domain factory that raises typed refusals so every caller is checked.", "playbook": "output-verification", "playbook_url": "https://wpnews.pro/playbooks/output-verification"}, "alternates": {"html": "https://wpnews.pro/news/schema-valid-isn-t-correct-parse-llm-output-with-pydantic-then-let-your-domain", "markdown": "https://wpnews.pro/news/schema-valid-isn-t-correct-parse-llm-output-with-pydantic-then-let-your-domain.md", "text": "https://wpnews.pro/news/schema-valid-isn-t-correct-parse-llm-output-with-pydantic-then-let-your-domain.txt", "jsonld": "https://wpnews.pro/news/schema-valid-isn-t-correct-parse-llm-output-with-pydantic-then-let-your-domain.jsonld"}}