All insights

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.

Co-founder and CTO, Datics AI6 min read

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
  1. 01Why LLM security starts with untrusted output
  2. 02Use the typed models you already have
  3. 03Where validation is not enough
  4. 04Design responses so they are easy to check
  5. 05What we see in production
  6. 06A checklist for your next LLM endpoint
  7. Frequently asked questions

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.

What shapes a model response: user message, retrieved documents, tool results and earlier turns, any of which can steer it
Any text in the context window can carry instructions the model follows.

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:

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

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

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

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

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

Table of seven risks from LLM output, an example of each and the control that handles it
Validation catches shape; authorization and encoding catch the rest.
RiskExampleControl
Malformed outputBroken JSON, missing fieldsSchema parsing, retry with the error
Invalid valuesA status your workflow does not haveEnums and validators
Cross-tenant referencesAn ID from another customer's dataOwnership check in a validator or the service layer
Injection into another systemGenerated text placed in HTML or SQLContext-aware encoding, parameterized queries
Leaked internalsTool names, internal IDs or field names in a replyOutput filters before display
Silent rewritingA model "improving" a name or numberConstrain edits to spans, protect approved terms
Unauthorized actionA response that triggers a payment or deletionAuthorization 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:

  1. 01

    Every model response is parsed into a typed model, and parsing failures are handled explicitly.

  2. 02

    Validators check tenant ownership, allowed values and allowed state changes.

  3. 03

    Output placed in HTML, SQL, email or another API is encoded or parameterized for that destination.

  4. 04

    Replies are filtered for internal names, IDs and secrets before display.

  5. 05

    Any action triggered by model output passes normal authorization under the user's identity.

  6. 06

    High-impact actions need human approval.

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

›References (2)
  1. OWASP Top 10 for LLM Applications: LLM05 Improper Output Handling
  2. Pydantic documentation: Validators

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.

Brownfield AIInside a live productDocument intelligence
Read case study

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.

Brownfield AIAgentic workflowsInside a live product
Read case study

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.

AI-native productAgentic workflowsRuns in client cloud
Read case study

More on AI security and compliance

Your customers already expect AI from your product.

Let us make it real without rebuilding what already works.