ai newsDi., 1. Dez.

Schema-valide LLM-Ausgaben sind noch lange korrekt: Domänenlogik als zweite Verteidigungslinie

Pydantic validiert die Struktur von LLM-Ausgaben, doch erst die eigene Domänenlogik kann inhaltlich unsinnige, aber schemakonforme Antworten zurückweisen.

dev.toSamstag 17:01 · 28.11.DE13 Min. Lesezeit
Bild: dev.to

Veröffentlicht am 28. Nov. • Bearbeitet am 28. Nov. • KI-gestützt

Ein Kunde schreibt an Ihren Support-Bot: "Meine Tasse ist kaputt angekommen. Bitte erstatten Sie Bestellung B-200, komplett." Ihr Erstattungs-Agent fragt das Modell nach einem Vorschlag und erhält {"order_id": "B-200", "amount_cents": 9000, "reason": "kaputt angekommen"}.

Das JSON ist parsbar. Jedes Pflichtfeld ist vorhanden. Jeder Typ stimmt. Ihr Schema-Validator ist zufrieden. Nur gehört Bestellung B-200 zu einem anderen Kunden, und die Bestellung, die dieser Kunde tatsächlich aufgegeben hat, belief sich auf 40 Dollar, wovon 10 Dollar bereits erstattet wurden.

Nichts in dieser Antwort hat das Schema verletzt, denn das Schema wusste von keiner der beiden Regeln. Der Leitfaden zu OpenAis Structured Outputs sagt es deutlich: Das Feature beschränkt vollständige, nicht abgelehnte Ausgaben auf Ihr JSON Schema, und Ihre Anwendung muss weiterhin alle Geschäftsregeln validieren, "die das Schema nicht ausdrückt".

OpenAI und Anthropic beschränken die Ausgabe inzwischen beide auf Ihr Schema. Die Dokumentation zu Anthropics structured outputs beschreibt das Feature als "constrained decoding" mit "garantierten Feldtypen und Pflichtfeldern", angefordert über output_config.format. Das ist ein echter Fortschritt gegenüber den Zeiten, in denen man JSON per Regex aus Fließtext herausgekratzt hat.

Liest man dieselbe Seite ein wenig weiter, zeigen sich die Ränder:

Die Garantie für die Form hat also Lücken, und ein Parse-Schritt ist ohnehin nötig. Der wichtigere Punkt ist der aus der Einleitung: Selbst eine perfekt geformte Antwort weiß nichts darüber, welche Bestellungen diesem Kunden gehören oder wie viel erstattungsfähig ist. Diese Information liegt pro Anfrage in Ihrer Datenbank. Man könnte das Schema bei jeder Anfrage neu aufbauen, mit den Bestell-IDs dieses Kunden als Enum, aber dann leben Ihre Geschäftsregeln in einem Provider-Adapter, und der nächste Aufrufer, der Erstattungen erstellt, läuft nie durch sie hindurch.

Zwei Tore: das erste prüft die Form, das zweite prüft, ob das Geschäft sie honoriert.

Hier liegen zwei verschiedene Fragen vor, und sie gehören an zwei verschiedene Orte.

"Ist diese Antwort wie ein Erstattungsvorschlag geformt?" ist eine Frage zum Ausgabeformat eines Providers. Sie gehört in den Adapter, der mit diesem Provider spricht. Pydantic ist das richtige Werkzeug: model_validate_json nimmt einen JSON-String und wirft eine ValidationError, wenn die Daten nicht passen.

"Wird das Geschäft diese Erstattung honorieren?" ist eine Frage zu Ihren Regeln. Sie gehört in den Kern, in eine Factory, die es ablehnt, ein Refund zu bauen, das sie bricht, und die einen typisierten Fehler mit Begründung auslöst.

Das ist genau die Aufteilung, die Alistair Cockburn in seinem ursprünglichen Artikel zur Hexagonal Architecture beschrieb: eine Anwendung, die von Benutzern, Programmen oder automatisierten Tests gesteuert werden kann und unabhängig von ihren späteren Laufzeitgeräten und Datenbanken entwickelt und getestet wird. Das Modell ist nur ein weiteres Gerät außerhalb des Hexagons. Es ist allerdings auch das Gerät, das sich am ehesten von allem überzeugen lässt, was der Kunde getippt hat.

Man könnte die Regeln mit Validatoren und einem Validierungskontext in Pydantic schieben. Das funktioniert, bis der zweite Aufrufer kommt: ein Admin-Screen, ein Bulk-Import, ein Webhook Ihres Zahlungsanbieters. Jeder davon erstellt Erstattungen, und jeder bräuchte dieselben Regeln kopiert in sein eigenes Eingabemodell. Legt man die Regel in die Domäne, geht jeder Aufrufer durch sie hindurch.

refunds/ domain.py # Order, Refund, typisierte Ablehnungen ports.py # RefundDraft, ReplyUnusable, Protokolle use_case.py # ProposeRefund, HandoffToHuman llm_claude.py # Pydantic DTO, parse_reply, ClaudeSuggester tests/ test_propose_refund.py test_parse_reply.py Vollbildmodus öffnen Vollbildmodus verlassen Der Kern: eine Erstattung, die sich weigert zu existieren Die Domäne hat keine Importe aus Pydantic, dem SDK oder irgendetwas sonst. Fehler bilden eine kleine Hierarchie, sodass der Use Case sie nach Art abfangen kann.

# 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 ) Vollbildmodus öffnen Vollbildmodus verlassen Python kann den Konstruktor eines Dataclass nicht privat machen, Refund ist also weiterhin direkt aufrufbar. Betrachten Sie for_order als einzigen Einstieg und halten Sie die direkte Konstruktion für Tests. Ein grep im Code Review fängt den Rest.

Das Ports-Modul enthält das, was der Kern von außen braucht: ein schlichtes RefundDraft, einen Fehler für "die Antwort war unbrauchbar" und zwei Protocol s.

# 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:... Vollbildmodus öffnen Vollbildmodus verlassen Der Adapter: Pydantic am Rand Der Adapter besitzt alles, was providerförmig ist: den Prompt, die Anfrage, den Stop-Grund, das Pydantic-DTO. parse_reply ist eine reine Funktion, man kann sie also ohne Netzwerk testen.

# 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 ) Vollbildmodus öffnen Vollbildmodus verlassen Anthropics Python-SDK bietet außerdem client.messages.parse(), das die Pydantic-Klasse als output_format entgegennimmt, das Schema sendet und die Antwort in einem Aufruf validiert. Die Schritte sind hier ausgeschrieben, damit man sieht, welche Hälfte welche ist. extra="forbid" lässt Pydantic Schlüssel ablehnen, nach denen man nicht gefragt hat, was "additionalProperties": False auf der Leitung entspricht.

Achten Sie darauf, was das DTO nicht tut. Es prüft nicht, ob der Betrag positiv ist, und es schlägt die Bestellung nicht nach. Es verwandelt Text in ein RefundDraft oder wirft ReplyUnusable. Das ist die ganze Aufgabe.

Das Modell sitzt außerhalb des Hexagons. Der Adapter prüft die Form; der Kern entscheidet.

Typisierte Fehler zahlen sich hier aus. Jede Art von Ablehnung bekommt ihre eigene Politik.

# 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 ) Enter fullscreen mode Exit fullscreen mode Ein falscher Betrag ist die Art von Fehler, die ein Modell behebt, wenn man ihm sagt, was schiefgelaufen ist, also bekommt es einen weiteren Versuch mit der Ablehnung als Hinweis. Eine fehlerhafte oder verweigerte Antwort wird gleichbehandelt. Eine Bestell-ID, die nicht existiert oder jemand anderem gehört, geht direkt an einen Menschen.

Diese ID stammt aus Text, den der Kunde eingegeben hat, und man möchte nicht, dass das Modell so lange rät, bis es zufällig auf eine Bestellung stößt, die gerade besteht.

Der Hinweis auf einen Betragsfehler enthält den erstattungsfähigen Saldo der eigenen Bestellung des Kunden. Das sind Informationen, die der Kunde sehen darf. Wenn Ihre Regeln irgendetwas umfassen, das er nicht sehen darf, formulieren Sie den Hinweis von Hand, statt den Ausnahmetext einfach durchzureichen.

Das Fake implementiert den Port und liefert zurück, was man ihm vorgibt: Entwürfe, die perfekt geformt sind und auf eine bestimmte Weise falsch. Kein Netzwerk, kein API-Schlüssel, kein instabiles Sampling. pytest vergleicht das match=-Argument mit re.search, daher genügt ein Teilstring der Nachricht.

# 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" ) Enter fullscreen mode Exit fullscreen mode Der dritte Test ist die Eröffnungsszene. Die zweite programmierte Antwort wäre eine gültige Rückerstattung für die eigene Bestellung des Kunden, und der Test stellt sicher, dass sie nie angefordert wurde.

Der Adapter erhält eigene Tests, und einer davon hält den Kernpunkt dieses gesamten Beitrags fest: Eine Antwort kann Pydantic problemlos passieren und trotzdem falsch sein.

# 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 Enter fullscreen mode Exit fullscreen mode Führen Sie sie vom Projektstammverzeichnis aus mit python -m pytest aus, wodurch das aktuelle Verzeichnis in den Importpfad aufgenommen wird, sodass refunds aufgelöst wird. Sie brauchen Python 3.10 oder höher für die Syntax str | None sowie installiertes pydantic v2 und anthropic.

Der letzte Test liest sich wie ein Fehlerbericht, und das soll er auch. Der Vertrag des Adapters ist die Form, und eine negative Rückerstattung für die Bestellung eines anderen hat eine tadellose Form. Die Verweigerung geschieht eine Ebene tiefer, in Code, den das Modell nie sieht und mit dem es nicht diskutieren kann. Alexis Kings „Parse, don't validate“ macht den allgemeinen Fall deutlich: Der Unterschied zwischen Validieren und Parsen liegt darin, ob die geprüften Informationen erhalten bleiben. Ein Refund, das existiert, ist der Beweis, dass die Regeln bestanden wurden. Ein dict, das ein Schema bestanden hat, beweist nur, dass es die richtigen Schlüssel hat.

Der Kerngedanke dieses Beitrags ist, den Kern von allem getrennt zu halten, was außerhalb liegt, sodass ein Modell, ein Formular oder ein Webhook alle auf dieselben Regeln treffen. Hexagonal Architecture in Python handelt von genau dieser Grenze in gewöhnlichen Python-Diensten: Es baut einen async-FastAPI- und SQLAlchemy-2-Dienst auf fünf Arten (Hexagonal, Clean, Onion, geschichtet und Vertical Slice) und vermisst diese dann. Das Buch hat keine LLM-Kapitel; es wendet das Design dieses Beitrags auf einen kompletten Dienst an, und jedes Listing läuft aus dem kostenlosen Begleit-Repository.

Expand Abdullah Naseer Abdullah Naseer Abdullah Naseer Follow Need to know about me? I Can Be Your Manager Or a Worker Here's My Insta ID 👉: wogfl Come if you need Anything 🤞 Joined Oct 26, 2026 • Nov 28 Dropdown menu Copy link Hide Das ist die klarste Formulierung des Problems, die ich gesehen habe: „Ein Refund, das existiert, ist der Beweis, dass die Regeln bestanden wurden“ ist ein deutlich besseres mentales Modell als „das JSON wurde validiert“. Auch das Bild der zwei Tore ist mir im Kopf geblieben: die Form am Rand, die Geschäftsregeln im Kern, und niemals dürfen die beiden ihre Rollen tauschen.

Das Detail, das mich am meisten überrascht hat, war das Minimum: 100 wandert lautlos in die Feldbeschreibung, statt von der Grammatik durchgesetzt zu werden. Das bedeutet, dass ein Entwickler etwas schreiben kann, das wie eine harte Einschränkung aussieht, es ausliefern kann und erst in Produktion merkt, dass das Modell nie tatsächlich daran gebunden war. Genauso bei der Groß-/Kleinschreibung von enum-Werten: schemavalide, semantisch falsch, und genau die Art von Fehler, die einen Test passiert, der nur den Parse-Erfolg prüft.

Eines interessiert mich noch: Der Retry-Hinweis enthält den erstattungsfähigen Saldo des Kunden, damit das Modell einen falschen Betrag korrigieren kann. Wie denken Sie darüber, dass dieser Hinweis Informationen zurück in den Prompt leitet? Und praktischer gefragt: Wie machen Sie den Retry idempotent, sodass ein „korrigierter“ zweiter Versuch nicht versehentlich eine zweite Rückerstattung anlegen kann, falls die erste tatsächlich durchgegangen ist? Hält der Use Case eine Reservierung vor, oder verweigert die Domäne ein zweites Refund für dieselbe Bestellung grundsätzlich?

Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.

Original (Englisch) anzeigen

Posted on Nov 28 • Edited on Nov 28 • AI-assisted

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:

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.

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 Enter fullscreen mode Exit fullscreen mode The core: a refund that refuses to exist 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.

# 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 ) Enter fullscreen mode Exit fullscreen mode 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.

# 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:... Enter fullscreen mode Exit fullscreen mode The adapter: Pydantic at the edge 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.

# 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 ) Enter fullscreen mode Exit fullscreen mode 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.

# 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 ) Enter fullscreen mode Exit fullscreen mode 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.

# 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" ) Enter fullscreen mode Exit fullscreen mode 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.

# 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 Enter fullscreen mode Exit fullscreen mode 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.

Expand Abdullah Naseer Abdullah Naseer Abdullah Naseer Follow Need to know about me? I Can Be Your Manager Or a Worker Here's My Insta ID 👉: wogfl Come if you need Anything 🤞 Joined Oct 26, 2026 • Nov 28 Dropdown menu Copy link Hide This is the clearest framing of the problem I've seen: "a Refund that exists is proof the rules passed" is a much better mental model than "the JSON validated." The two-gates image stuck with me too — shape at the edge, business rules in the core, and never letting the two trade jobs.

The detail that surprised me most was the minimum: 100 silently moving into the field description instead of being enforced by the grammar. That means a developer can write what looks like a hard constraint, ship it, and only discover in production that the model was never actually bound by it. Same with enum capitalization — schema-valid, semantically wrong, and exactly the kind of failure that slips past a test that only checks parse success.

One thing I'm curious about: the retry hint includes the customer's refundable balance so the model can correct a wrong amount. How do you think about that hint leaking information back into the prompt — and, more practically, how do you make the retry idempotent so a "corrected" second attempt can't accidentally create a second refund if the first one actually went through? Is the use case holding a reservation, or does the domain refuse a second Refund for the same order outright?

Originaltitel: Schema-Valid Isn't Correct: Parse LLM Output With Pydantic, Then Let Your Domain Refuse ItQuelle: dev.to (dev.to). Original öffnen