AI security and compliance
LLM security: why treat model output as untrusted input?
The model is one more client of your API. It does not get to skip validation.
Short answer
In LLM security, a model response is input your system did not write and cannot fully predict, and anyone who can influence the prompt can influence it. Treat it like a request from an unknown user: parse it into the same typed models that guard the rest of your API, validate it against your business rules, encode it for where it goes, and reject or retry anything that fails before it reaches users, databases or other systems.
On this page
01Why LLM security starts with untrusted output
Teams usually secure the input side of an LLM feature first: rate limits, prompt injection filters, content policies. The output side gets less attention, because the response comes from "our" model through "our" code. That is the mistake. This is part of our larger guide, AI security for SaaS: protect data and pass security reviews.

A model response is shaped by everything in its context window: the user's message, retrieved documents, tool results, earlier turns. Any of those can carry instructions the model follows. Even without an attacker, models produce malformed JSON, invent field values, return the right shape with the wrong meaning, or drift when the provider updates a model version.
OWASP names this risk Improper Output Handling and recommends exactly the stance we take: treat the model as any other user, apply zero-trust validation to its responses before they reach backend functions, and encode output for its destination. If a response can end up in HTML, a SQL query, a shell command, an email or another service's API, it can carry an attack into that place.
02Use the typed models you already have
If your backend is a typed API service, for example FastAPI with Pydantic, you already own the right tool. Every request body that comes from a browser or a partner system is parsed into a model with types, constraints and validators. Model responses deserve the same treatment.
The pattern is simple:
- 01
Define the shape you expect.
Write a typed model for the model's response, with the same care as a public request schema: required fields, enums instead of free strings, numeric ranges, string length limits.
- 02
Ask for that shape.
Use the provider's structured output or tool calling features so the model is steered toward the schema. This reduces failures; it does not remove the need to check.
- 03
Parse and validate on your side.
Run the raw response through your model. Type errors, missing fields and values outside allowed ranges fail here, not three services later.
- 04
Apply business rules.
Field validators and model validators can check what types cannot: that a referenced ID belongs to the current tenant, that a date is not in the past, that a status transition is allowed.
- 05
Decide what failure means.
Retry with the validation error, fall back to a safe default, or route to a person. Never pass a partially valid object downstream.
Pydantic supports this directly with field validators and model validators that raise validation errors, which is the same mechanism your request handling already uses. The benefit is consistency: one set of rules guards your data whether it came from a person, a partner or a model.
03Where validation is not enough
Typed validation catches malformed and out-of-range output. It does not catch output that is well formed and wrong. Several other controls matter.

| Risk | Example | Control |
|---|---|---|
| Malformed output | Broken JSON, missing fields | Schema parsing, retry with the error |
| Invalid values | A status your workflow does not have | Enums and validators |
| Cross-tenant references | An ID from another customer's data | Ownership check in a validator or the service layer |
| Injection into another system | Generated text placed in HTML or SQL | Context-aware encoding, parameterized queries |
| Leaked internals | Tool names, internal IDs or field names in a reply | Output filters before display |
| Silent rewriting | A model "improving" a name or number | Constrain edits to spans, protect approved terms |
| Unauthorized action | A response that triggers a payment or deletion | Authorization in the API, human approval |
The last row is the important one. If a model response can cause an action, the action must still pass your normal authorization checks under the end user's identity. Validation proves the response is well formed. Authorization proves the action is allowed. You need both.
04Design responses so they are easy to check
The easiest output to validate is output with little freedom. A few habits help:
- Prefer structured flags to prose for decisions. A risk check that returns a list of named flags, each tied to its input, is testable. A paragraph of reasoning is not.
- Separate the decision from the explanation. Let the model write an explanation for the user, but drive the workflow from the structured fields.
- Ask for edits, not rewrites. When the model corrects text, have it return the spans it would change, and apply them in code. Whole-text regeneration hides changes to names, dates and figures.
- Keep identifiers out of the model's hands where you can. Resolve which record a user means in code, and give the model the resolved record rather than letting it pick an ID.
These choices also make evaluation easier, because each field can be compared with an expected value. For the wider picture of why AI features fail on the product around the model rather than the model itself, see why AI agents fail in production.
05What we see in production
One of our engineers worked inside a U.S. AI software company's own engineering team on the backend of its LLM application, a service built on FastAPI, Pydantic, Postgres and GPT-4. That stack is a common one for LLM features in established products, and it puts typed request and response models right next to every model call, which is where this validation belongs.
In products where we built the AI ourselves, the same rule shows up in different forms. For a regulated private investment platform, risk outputs are structured flags only, traceable to their inputs and stored for audit, and AI never approves a deal, a KYC check or a tokenization step.
In a short-term rental operations assistant, guards stop tool names, IDs and internal fields from appearing in replies, and block edit, delete and post actions where no tool exists. In a self-hosted document workspace for government archives, the writing tools let a rules engine detect errors and the model resolve only ambiguous spans; edits are applied as spans and never as regenerated text, and an approved term registry keeps entity names from being changed.
None of these controls trusts the model to behave. Each one checks what the model produced before it matters.
06A checklist for your next LLM endpoint
Before an LLM-backed endpoint goes live, confirm:
- 01
Every model response is parsed into a typed model, and parsing failures are handled explicitly.
- 02
Validators check tenant ownership, allowed values and allowed state changes.
- 03
Output placed in HTML, SQL, email or another API is encoded or parameterized for that destination.
- 04
Replies are filtered for internal names, IDs and secrets before display.
- 05
Any action triggered by model output passes normal authorization under the user's identity.
- 06
High-impact actions need human approval.
- 07
Validation failures are logged and counted, so a provider model update that changes behavior shows up as a metric, not a support ticket.
Frequently asked questions
Is the provider's structured output feature enough?
No. Structured output and tool calling steer the model toward your schema and reduce failures, but they do not remove the need to check. Parse and validate every response on your side with your own typed model, so type errors, missing fields and out-of-range values fail before they travel further.
What does typed validation not catch?
Output that is well formed and wrong. Validation proves a response has the right shape. Authorization proves an action is allowed, and encoding stops generated text from carrying an attack into HTML, SQL or another API. Any action from model output must still pass normal authorization under the end user's identity.
What should happen when a response fails validation?
Decide in advance: retry with the validation error, fall back to a safe default, or route to a person. Never pass a partially valid object downstream. Log and count validation failures too, so a provider model update that changes behavior shows up as a metric, not a support ticket.
How Datics helps
Datics specializes in brownfield AI: bringing production AI into the product you already operate, without forcing a rebuild.
Related work
Case studies from our projects on the same subject.
Transcripts U.S.
Government, Legal & Defense · Legal transcript marketplace
Court reporting agencies publish transcript metadata without the file ever leaving their browser
Agencies once uploaded full transcripts to the marketplace; now title page details are read in their own browser, and they confirm what is published.
Regulated investment platform
Financial Services · Private investment marketplace
Pitch decks become drafted deals, and issuers approve each field before publishing
Issuers retyped decks and financials into long deal forms. Now AI suggests each field, and the issuer applies, edits or rejects it.
TrailBlaze Innovations
Healthcare & Wellness · AI meal planning chat
Dieters get meal plans with every calorie computed from food data, not guessed
Chat assistants make up nutrition numbers. Here code computes every calorie from food data, and the model only phrases the plan.
More on AI security and compliance
AI security and compliance
AI security for SaaS: protect data and pass security reviews
A practical map of AI security for established SaaS: threats, data governance, permissions, audit trails and how to answer enterprise security reviews.
AI security and compliance
How do you stop AI data leakage through search metadata?
Stop AI data leakage in search by treating metadata as sensitive: classify records, automate high stakes rules, keep people on unclear cases, and audit.
AI security and compliance
Which AI disclaimers does a product need?
An AI disclaimer works when it is designed into the feature: say it is AI, that it can be wrong, what happens to data, and where its numbers come from.
AI security and compliance
What enterprise AI security questions do buyers ask?
Enterprise AI security reviews ask where data and models run, who reaches production, what the AI may do alone and how it is logged. Here is how to prepare.
AI security and compliance
How do you enforce tenant isolation beyond database rows?
Tenant isolation beyond database rows means boundaries per field and per role, in caches, files, payments and jobs, so no tenant sees what another owns.
AI security and compliance
What does HIPAA AI compliance mean for software vendors?
HIPAA AI for software vendors: what the product company owns, what the engineering team builds, and how to keep patient identifiers away from models.
Your customers already expect AI from your product.
Let us make it real without rebuilding what already works.
