Rustem Feyzkhanov · Writing
Pydantic (and Monty) are all the semantic and ontology layers you need
Pydantic changed how we validate LLM output. Ask a model for structured output, through Instructor, PydanticAI or a provider SDK’s parse helper, and you hand it a Pydantic model as the contract. Responses are validated against that contract; integrations can retry failures within a configured budget. “Please answer in JSON” turned into a type system.
But shape validation answers only one question: is this well-formed? It can’t tell you whether the answer is true. RevenueChange(total_cents=6_200_000) is a perfectly valid instance and a perfectly wrong answer.
Monty changes what Pydantic can see. It’s the Pydantic team’s minimal, secure Python interpreter, written in Rust, for running code that LLMs write. Instead of a chain of tool calls, the agent writes a short Python program. Whenever that program calls an external function, execution pauses and control passes back to the host.
That pause is what matters. Suppose every function the agent can call takes a Pydantic model and returns Pydantic models. Then Pydantic validates more than the output. It validates the path: every request the agent makes, every row it gets back, and finally whether the answer agrees with what that path observed.
This post argues that once you validate the path, your Pydantic models stop being just schemas. They become your ontology and your semantic layer, and that’s what lets you scale agent policies from three to a hundred. Every example below comes from the runnable online-store example in ryfeus/agent-pathcheck, an open-source reference architecture built with Pydantic and Monty.
Meet the store
The example is a synthetic online store with the entities everyone already knows: customers, orders, order lines, products, categories, suppliers, shipments, returns, inventory snapshots and promotions. Internal users ask it ten kinds of question, grouped below by the validation work they require—from scoped reads to policy composition. These are qualitative tiers, not measured difficulty scores:
| Complexity | Question | What makes it hard | Checked answer |
|---|---|---|---|
| Scoped reads | What was net revenue for the production store in October? |
| $362,000 |
| Scoped reads | How many orders shipped in the week of October 19–25? |
| 2 |
| Complete evidence | How did net revenue by category change from September to October? |
| +$59,000, including Outdoor’s −$3,000 |
| Complete evidence | What’s the margin on P-120? |
| A checked refusal: its unit cost is missing |
| Related records | Is the $500 refund request on order 1042 within policy? |
| Eligible for automatic approval |
| Related records | Which 5 products should we restock? |
| P-101, P-102, P-107, P-108, P-109, totalling $13,100 |
| Shared and changing rules | Who becomes Gold this month? Who is at risk of churning? |
| Two lists that share one “active customer” definition |
| Shared and changing rules | ”Don’t restock anything selling under $50/month” |
| P-110 replaces P-109; total becomes $12,950 |
| Policy composition | Why did West-region revenue fall, and which promotion should we pause? |
| −$11,000; pause PROMO-app |
| Policy composition | Which suppliers had the most late deliveries to Gold customers last quarter? |
| S-1: 2, S-2: 1 |
Every row runs offline, with no API key:
python -m examples.online_store --demo --case category-comparison
python -m examples.online_store --all --replays
A valid schema, a wrong answer
RAG and tool use promise that the model saw the right data. A genuine retrieval trace can show that data was retrieved; a citation alone cannot. It doesn’t prove the answer follows from it.
Take the category-comparison question. The agent pulls September and October net revenue by category, and the citations look perfect. It reports +$62,000. The real change is +$59,000. Outdoor was discontinued in October (−$3,000), and the agent only looped over October’s categories. Every cited row is real. The answer isn’t, and it passes output validation without complaint.
The same failure shows up across the other use cases:
-
Wrong slice: the agent includes test-storefront orders, uses gross revenue instead of net revenue, or cuts “October” at midnight UTC instead of store time.
-
No evidence: a query fails, the agent catches the error, and returns a plausible count anyway.
-
Wrong relationship: it approves a refund using a different order’s delivery date.
-
Wrong eligibility: it recommends restocking a phone case by borrowing a sibling product’s sales history.
Each one produces a well-formed, cited, confident answer.
From output validation to path validation
With Monty, the agent’s answer is a program rather than a JSON blob. This is an illustrative, abbreviated version of the reference program for the category comparison; the ellipses stand for omitted arguments:
before = query(MeasureQuery(
storefront='prod', timezone='America/Los_Angeles', metric='net_revenue',
group_by='category', period='2026-09', region='all', channel='all',
customer_tier='all'))
after = query(MeasureQuery(..., period='2026-10', ...))
left = {r.key: r.value for r in before}
right = {r.key: r.value for r in after}
labels = {r.key: r.label for r in before + after}
keys = sorted(labels, key=lambda k: (
-(right.get(k, 0) - left.get(k, 0)), labels[k], k))
rows = [MeasureRow(key=k, label=labels[k],
value=right.get(k, 0) - left.get(k, 0),
before=left.get(k, 0), after=right.get(k, 0))
for k in keys]
MetricResult(rows=rows, total=sum(r.value for r in rows))
Every call out of the sandbox is a checkpoint, and Pydantic sits at each one:
-
The request. The host builds each request type for the task, and every field is a
Literal:model = create_model( name, __base__=PolicyModel, **{key: (Literal[values], ...) for key, values in choices.items()})For this task,
MeasureQuery(storefront="test", ...)ormetric="gross_revenue"fails in the constructor, before any SQL runs. Raw SQL, dictionaries and invented query classes never reach the database. -
The result. The host runs a fixed, parameterized query and validates the entire batch of rows. Timestamps must be canonical UTC, quantities positive, money integer cents. Only a fully valid batch is committed to a private evidence ledger, which starts fresh on every run. A rejected batch adds nothing.
-
The claim. The final model’s validator recomputes the answer from the ledger:
class MetricResult(PolicyModel):
rows: list[MeasureRow]
total: int
@model_validator(mode="after")
def matches_evidence(self):
expected = measure_result() # recomputed from the evidence ledger
if (self.rows != expected
or self.total != sum(row.value for row in expected)):
raise PolicyViolation(
"arithmetic", "store.metric_result",
"Return every required group in order and its exact total")
return self
For a comparison, measure_result() takes the union of categories from both months, counting a missing category as zero. So the +$62,000 answer fails, because Outdoor is in the September evidence and its −$3,000 has to appear. A breakdown that sums correctly but shuffles the numbers fails too.
Two more guards close the obvious shortcuts:
-
Re-running on changed data. The host re-runs the same submitted program after adding $1 to one Apparel order line. If the answer doesn’t move on this perturbation, publication is blocked. That catches stale or hardcoded output on this test; it does not prove derivation.
-
One claim per run. Decision policies allow one final claim construction per invocation, so the validator can’t be used as an oracle by trying answers until one passes.
Model prose is never the answer. Only the checked payload is published as the result; the narrative stays labeled unverified.
Why not just a workflow?
The first instinct is to take the decisions away from the model. Write a workflow: a fixed graph where the developer decides which queries run and in which order, and the model fills in slots or writes the summary.
For a fixed, known question, that’s the right call. “What was October’s net revenue?” needs one query and no judgment. Hardcode it and you’re done.
Maintaining question-specific graphs gets harder as the questions multiply:
-
Question-specific graphs multiply. Ten use cases, each with variants, can mean ten graphs and counting, unless workflows share reusable logic. The supplier-ranking question was never written as its own graph.
-
Rule changes don’t announce themselves. When “active customer” goes from 90 days to 60, a graph with a copied definition keeps answering under the old rule unless that definition is updated. Workflows can share policy code too. In the store, the policy is the input instead: last week’s restock selection is rejected under the corrected $50/month rule, and the acceptance check shows the changed answer.
-
Shape-only step checks don’t check joins. A schema used only for each step’s output shape can’t check that a refund used this order’s delivery date, or that a product’s sales history is its own. Custom validators can check those relationships in either a fixed workflow or an agent-written program.
-
The summary step is unchecked. If the last step is “the LLM writes the summary”, nothing compares its numbers to what the earlier steps returned.
What still differs is coverage. A fixed workflow answers the questions someone drew a graph for. The agent composes a path for the ones nobody did, and the host checks its final claim against the whole run, not one step at a time.
That’s also why “validate the path” doesn’t mean “fix the path”. A workflow fixes the path in advance. With Monty, the agent’s program is the workflow, written for this question, and the host checks whatever path it takes: each request against its scope, each result batch before it counts, and the final claim against everything the path observed.
The two compose. A workflow can keep the fixed parts of a process and make one of its steps a checked agent call.
Why not just a policy engine?
The next move is to let the model act, but write the rules down and enforce them outside it. Engines like Cedar are excellent at the first rules you need: read only production data, read only the period asked about, never write.
Cedar can check the answer as well. Model “publish” as an action and pass the agent’s claim in as context. A policy can then refuse an automatic refund over $500, or require the proposed restock IDs to be a subset of the eligible ones.
The catch is where those values come from. Cedar decides over the attributes it’s given; its bounded expression language does not run arbitrary loops or database aggregations. “Eligible IDs” or “within the refund window” have to be derived from what this run read:
-
the days between this order’s delivery and the request, in store time
-
the amount and quantity still refundable on this line after earlier returns
-
the top five restock candidates after every eligibility rule, ranked with tie-breaks
Whoever derives those attributes has done the verification; Cedar performs only the final comparison. So the real gap is between comparing against supplied facts and deriving the facts from what was observed.
Pydantic plus Monty does both in one place. Literal fields on request types are the permission check. Claim validators derive the expected values from the evidence ledger and compare against them, in the same Python, at the same boundary.
From three policies to a hundred
A store doesn’t stop at one question. Restocking, markdowns, refunds, loyalty tiers, churn alerts, win-back lists, fraud review, supplier scorecards and commissions all restate the same ideas:
-
only production orders count
-
what “net revenue” means, and in which month a refund lands
-
what an “active customer” is
-
that a return belongs to the customer who bought the line
-
that months are cut in store time
Written as a hundred independent policies, these drift apart. CRM shortens “active customer” from 90 days to 60. Loyalty gets the update; churn and win-back keep a stale copy. The two answers now disagree about the same customers, and nobody can say which past answers would have changed.
Pydantic models are the ontology
Rules repeat because they’re about the same things. In Pydantic, those things are already first-class:
-
Models are entities.
Orderdeclaresstorefront: Literal["prod", "test"], andOrderLinedeclaresquantity: int = Field(gt=0). A shared base class rejects any timestamp that isn’t canonical UTC. -
Typed fields are measures with units: money in integer cents, history in distinct selling days, delivery delay in local calendar days.
-
Relationships become rules. A refund decision must stay on one chain, Return → OrderLine → Order → Customer. This and the following decision snippets are illustrative excerpts; ellipses mark omitted code:
if row.order_id != request.order_id or row.customer_id != request.customer_id: return "rejected", "ownership" ... age = (local_date(request.requested_at, tz) - local_date(row.delivered_at, tz)).days if age > config.refund_days: return "rejected", "window"Tests pin the boundaries: day 30 passes and day 31 fails; $500 auto-approves and $500.01 goes to a human.
-
Decisions span relationships. Restock eligibility is plain Python over one observed row per product:
def restock_reason(row, config): if row.product_status != "active": return "product_inactive" if row.supplier_status != "active": return "supplier_inactive" if row.history_days < config.history_days: # this product's own selling days return "history" ...RestockProposalchecks a single candidate against the evidence, andRestockPlanrecomputes the whole ranking with the same rules:class RestockPlan(PolicyModel): proposals: list[RestockProposal] total_lost_revenue_cents: int outcome: Literal["recommendations", "no_eligible_products"] @model_validator(mode="after") def complete_ranking(self): # every rule, ranked by forecast, ties by product ID expected = eligible_stock() if ([p.product_id for p in self.proposals] != [r.product_id for r in expected] or self.total_lost_revenue_cents != sum(r.lost_revenue_cents for r in expected)): raise PolicyViolation("completeness", "store.restock_plan", ...) return selfThe fixture has a trap for every rule. The biggest forecast, P-104 Desk lamp, comes from an inactive supplier. P-103 Phone case has only 21 days of its own history; a sibling variant has 90. P-107 and P-108 tie at $2,100, so P-107 comes first by ID. The only answer that passes is P-101, P-102, P-107, P-108, P-109 for $13,100.
-
Concepts are defined once. “Active customer” and “Gold” are single functions shared by every policy that needs them:
Change the window once and both policies follow: with
--active-days 60, C-window drops out of the newly Gold list, and C-window and C-not-gold join the churn cohort.affected_policies("active_customer")lists loyalty, churn and composed Gold filters.Honest caveat: that dependency map is maintained by hand today. Deriving it from what each validator actually calls is the next step.
The cheap parts don’t all need writing. Field types, nullability and relationship metadata can come from the database schema; the cross-row checks here are explicit validators. Business rules are never inferred from tables, though. Thresholds, ranking and eligibility stay explicit, because they’re decisions with owners, not facts.
At that point your models have quietly become an ontology: a typed model of the domain with constraints attached. One difference from a classic ontology matters. It’s closed-world and scoped to the task: a missing fact means “not observed in this run”, which is exactly what verification needs.
A spectrum of enforcement, in plain Pydantic
You can’t write and test a hundred fully enforced policies on day one, and not every rule deserves to block an answer. So every rule in the store carries a level, an owner and a rationale (illustrative excerpt; the ellipsis omits other fields):
Rule("store.minimum_sales", "Require the corrected monthly-sales floor",
Level.TESTED if config.minimum_monthly_sales_cents else Level.DOCUMENTED,
"Merchandising", "correction:minimum-monthly-sales", ...)
| Level | Meaning | Rule in the store |
|---|---|---|
| Documented | Advice in prose | ”Prefer local suppliers” |
| Guided | Shown to the agent, not enforced | ”Mention new and discontinued categories” |
| Checked | A failing claim is rejected | ”Don’t restock under $50/month” in the corrected policy (also tested) |
| Tested | Checked, with boundary cases kept | Refund window: day 30 passes, day 31 fails |
These levels record rule maturity, rather than a general audit-only switch. Refusal is a claim like any other. Abstain is accepted only when a read the policy requires actually failed. The agent asked for P-120’s margin has to catch that exact failure in the same program (illustrative excerpt; ellipses omit request fields):
try:
row = query(ProductMarginQuery(..., product_id='P-120', ...))
except ValueError:
result = Abstain(kind="data_block", rule_id="store.cost_missing",
detail="The required product cost is unavailable.")
else:
result = ProductMargin(margin_cents=row.net_revenue_cents - row.cost_cents)
result
A failed optional read, such as another product’s margin, can’t justify a refusal. Neither can a truncated returns query for a different cohort.
Rules move up the levels as they prove their worth. The $50 correction is kept as a record with its owner, stages and boundary cases. The acceptance check re-runs last week’s selection under the new rule, confirms it’s now rejected, and shows the changed answer. The spectrum is how you get to a hundred policies incrementally instead of all at once.
Pydantic models are the semantic layer
Pydantic models already carry meaning: docstrings, field descriptions, JSON Schema and the validator source itself. The store generates semantic pages from the active policy for its entities, their relationships, rule owners, maturity and provenance, including the ten core entities shown above and a separate Forecast model. The agent reads them through a read_semantic tool next to run_workflow.
Because the pages are generated from the active policy, regeneration and freshness checks can expose stale generated content. When the agent asks what counts as eligible for restock, it gets the active rule declaration and validator source; authored descriptions and rationale still need review.
Two caveats, and a finding from the benchmark below:
-
Docs guide; they never certify. A lookup never commits evidence. Only a check against observed data can publish an answer.
-
Incomplete pages don’t help. In the store’s benchmark, pages that named the helper functions behind some rules without including them scored 39 of 54 tasks, no better than validation alone at 41. Regenerated with exact ordering, refund precedence and the helpers’ source, the same optional lookup reached 52 of 54.
-
Rejections drive lookups. Every lookup in that rerun came after a check rejected an answer, never before the first attempt. Validation tells the agent that it’s wrong; the generated pages tell it what the rule actually is.
Policies the planner composes
The supplier-ranking question has no question-specific hand-written policy; it composes host-defined measures, rules and validators. A planner LLM translates it into a PlanSpec, itself a Pydantic model, without touching any data:
class PlanSpec(PolicyModel):
measure: Literal["net_revenue", "shipped_orders", "late_deliveries"]
group_by: Literal["category", "customer", "supplier"]
periods: list[str] = Field(min_length=1, max_length=2)
shape: Literal["aggregate", "comparison", "top_k"] = "aggregate"
top: int | None = Field(default=None, ge=1, le=100)
region: Literal["all", "West", "East", "North", "South"] = "all"
channel: Literal["all", "web", "app", "marketplace"] = "all"
customer_tier: Literal["all", "gold"] = "all"
A deterministic compiler turns the plan into a policy from a small registry: three measures, their allowed groupings, three claim shapes and a few filters. It has no branch specific to this question. Requests for an unknown measure, raw SQL, a validator override or a change to inherited rules fail before any data access.
One constraint keeps this honest: the planner can add filters but never remove the rules it inherits. Production scope and store time come with every measure. The Gold filter brings the shared “active customer” definition, evaluated at each period’s end.
The answer comes back with the normalized plan and a plain-language summary. The engine verifies the answer under that plan; the person checks that the question was understood. The checked result, S-1 with two late orders and S-2 with one, is labeled an association with delays, not their cause.
What it doesn’t do
-
Authenticate data. The store’s data is trusted.
-
Enforce rules nobody wrote. Coverage is only as good as the encoded policy.
-
Prove how the answer was derived. A hardcoded right answer can still pass after the required reads. Re-running on changed data catches many such cases, but not all.
-
Verify prose, causes or intent. Explanations stay labeled unverified, and so does the planner’s reading of a natural-language question.
Does it hold up?
The store ships with a live benchmark: the real model (gpt-6-luna, low reasoning effort), the same MCP server and Monty sandbox, and 18 scenarios covering every case, each run three times. Expected answers and grades never enter the model’s context. Every mode keeps typed requests and per-call checks; only the final-claim check and the semantic pages vary. In the November 16, 2026 rerun:
- Typed tools, no final check: 33 of 54 correct, 17 wrong answers.
- Plus final-claim validation: 41 of 54 correct, zero wrong answers.
- Plus generated semantic pages: 52 of 54 correct, zero wrong answers: 11 paired wins and no losses against validation alone, for 2% more tokens per correct task.
Validation turns wrong answers into no answers, and the pages turn most of those into checked answers. They help during repair, not before it: both validated modes got 25 of 54 right on the first workflow, and all 15 lookups came after a rejection, after which all 15 tasks passed. The pages also had to be complete. In the first run they named helper functions without including them, and that mode scored 39 of 54.
The saved traces show the failure behind those numbers: the agent had the rule available and guessed instead of reading it. One comparison trial submitted four interpretations without a single lookup. A repaired trial read entities/metric_result.md after a rejection and passed. Without the final check, a near miss ships: an unchecked trial had the right totals with the rows in alphabetical order.
The refund traces add a second problem. The agent hardcoded its own reading of the $500 boundary as elif 50000 >= 50000:, and the rejection blamed the customer, line and delivery when only the reason code was wrong, so it had nowhere to look. One lookup of rules/store.refund fixed it.
A follow-up run attached the failing rule’s page to each rejection instead of waiting for a lookup. It scored 51 of 54 against 52 for lookup, with about 18% fewer tokens per correct task. Pushing the page works as well as letting the agent fetch it, and costs less. Rejections without a rule ID got no guidance at all, and those are the next gap to close.
Read these as descriptive results, not a reliability estimate. The scenarios are synthetic, the rerun followed a diagnosis of the first run on the same 18 scenarios, and unchanged modes drifted by up to three tasks between runs. The post’s running example stayed hard: category comparison scored 0 of 3 without the pages and 2 of 3 with them.
Related work
The core pattern, where the LLM proposes and deterministic code decides, isn’t new. In 2026 it’s converging from several directions, and it’s worth being precise about what this post adds.
Same architecture, different question: what the agent may do
-
TACIT (Odersky et al., EPFL; arXiv:2603.00991; best paper at CAIS ‘26) is the closest relative in spirit. Agents write code instead of calling tools directly. A typed API is the only way out to the world, and Scala 3 capture checking statically ensures the code can’t forge access rights or leak data out of pure sub-computations. “Types are the policy” is the same bet made here. The difference is that TACIT checks effects at compile time, while this post checks claims at run time against what was observed. The two compose: capability types decide what the agent may touch, and evidence-checked claim types decide what it may say.
-
CaMeL (Google DeepMind) runs agent-written Python in a custom interpreter that tracks provenance and enforces security policies before each tool call. It’s built to defeat prompt injection, not to check whether answers are true.
-
Invariant Guardrails writes deterministic rules over agent traces: tool-call sequences and data flows.
-
Cedar, discussed above, can gate an answer, but someone has to derive the facts it compares against.
-
Palantir’s Ontology and AIP are the commercial version of “an ontology for agents”: typed objects, links and actions, with functions expressing validation rules and derived values. Its permissioned action boundary governs changes to objects; that boundary alone does not establish whether an answer follows from a run’s evidence.
Same question: is the answer backed by evidence?
-
Evidence-Carrying Termination (Liu, UC San Diego, August 2026) is the closest match to the verification core. The agent proposes a certificate, and a deterministic verifier checks it against a trusted task contract and an immutable evidence ledger. Replay recomputes each claimed value through a closed transform language (sum, difference, top-k and so on). The differences from this post:
-
It uses tool calls rather than agent-written code.
-
It uses a closed transform language rather than Python validators: more analyzable, less expressive.
-
Replay recomputes from the ledger rather than re-running the program on perturbed data.
-
It doesn’t address policy reuse, ontologies or rule changes.
-
-
Tool receipts sign every tool execution and cross-reference the response’s claims against the receipts. It’s lighter-weight detection rather than a gate on publishing.
-
Structured validation of tool-agent traces checks whether answer values are supported by the correct observations. The revised paper also describes an online runtime monitor; it is not limited to offline evaluation.
Same building blocks, on the way in: ontology-backed knowledge graphs
-
Netflix’s ontology-driven observability describes typed facts from telemetry and incident discussions in a knowledge graph that root-cause agents query. Fareed Khan’s independent rebuild applies the public design to public data (code). The implementation details and experiments below belong to that rebuild, not Netflix. Many of its choices mirror this post:
-
SHACL shapes enforce explicit constraints on their targeted classes before the validated graph is stored. Inference is switched off, after it concluded that a misspelt host must be a real component.
-
Coverage records separate “nothing fired” from “nobody looked”.
-
Enrichers declare what they need, so one whose input neither the store nor another enricher provides is refused before it runs.
Its evidence verifier is deliberately mechanical. A hypothesis must cite IDs its own tools returned, name a component and a reason from closed lists, and fall inside the incident window, allowing five minutes before its start. That checks that the cited IDs were returned to the agent, not that it used them or that the conclusion follows from them. In the article’s worked example, verified hypotheses blamed disk reads; the answer key named packet loss.
Root causes can’t be fully recomputed, so a person still approves the fix. But two checks from this post would narrow the gap: cited evidence must be about the component being blamed, and the claimed reason must be backed by a signal of the matching kind on that component.
One result from the independent rebuild supports the typed approach. Graph facts in a single prompt named the right trigger 42% of the time, against 25% for raw text, and the raw-text single-prompt arm was the only tested setup that cited evidence it was never shown. That’s on 24 incidents in that experiment, so it’s suggestive rather than conclusive; it is not a Netflix benchmark.
The two layers compose. Graph validation rejects facts that violate its encoded constraints on the way in; checked claims reject answers that violate their evidence checks on the way out.
-
Same runtime: Monty
A prominent Monty use case is code mode, used for cost and latency. Silex Data runs it inside a gateway that checks and audits every tool call. Among the implementations compared here, this example specifically uses code mode’s function-call pauses to build an evidence ledger and check the final answer against it.
What’s new here, then, is the packaging and the scaling, not the core pattern:
-
The policy is plain Pydantic types, checked at run time inside a Monty session, with no separate certificate format or rule language.
-
Re-running the same program on changed data targets hardcoded answers.
-
Refusal is accepted only when a read the policy requires actually failed.
-
Entities serve as reusable components, rules carry an enforcement level, and the semantic layer is generated from the enforced policy. That’s how you get from three policies to a hundred.
The takeaway
Pydantic gave LLM outputs a shape. Monty gives Pydantic a view of the path. Put them together, and the same Python classes do three jobs from one source of truth:
-
Ontology: what exists in the store and how it relates.
-
Policy engine: what may be asked, and what may be claimed.
-
Semantic layer: what it all means, generated from the code that enforces it.
Retrieval shows the agent saw the data. Pydantic, watching the path, checks that the answer agrees with it.














