cd /news/large-language-models/schema-valid-isn-t-correct-parse-llm… · home › topics › large-language-models › article
[ARTICLE · art-177801] src=dev.to ↗ pub= topic=large-language-models verified=true sentiment=· neutral

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.

recommendation

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.

more in playbook: Verifying model output
by read10 min views40 publishedNov 28, 2026

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 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 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 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: 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.

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.

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.

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 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.

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 matches the match= argument with re.search, so a substring of the message is enough.

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.

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 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 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.

── more in #large-language-models 4 stories · sorted by recency
── more on @openai 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/schema-valid-isn-t-c…] indexed:0 read:10min 2026-11-28 · —