Validating Model Output Before an Action

Validating Model Output Before an Action

user avatar

by me1afon

12 minutes ago


AI tools helped gather research and write the first draft of this article. I edited it and checked every quote and figure against the source page listed at the end, read on 2 December 2026. The cover illustration is AI-generated. Details at the end.

When a model's reply can trigger something, a database lookup, a file write, a message, a page shown to a customer, the reply stops being just text. It becomes the input of another program. The place to check it is the boundary between the model and that program, in ordinary code, written for what that program will do with it. Not in the prompt, not inside the model, and not once at the front of the system for every possible use.

This article explains why the boundary is the right place, what to check there for different destinations, and what a validator cannot catch. It walks a fictional order-status bot and a small test. It is not a security audit method and makes no claim about any real product. It sits between two other titles in this series: "When Retrieved Text Tries to Become an Instruction" (how untrusted text reaches a model) and "Giving an Agent Only the Access It Needs" (limiting what a tool can do at all).

Why the reply is untrusted input

The OWASP GenAI Security Project, in its 2025 list of risks for LLM applications, names this problem "Improper Output Handling". It defines it as "insufficient validation, sanitization, and handling of the outputs generated by large language models before they are passed downstream to other components and systems" [1]. It gives the reason in one sentence: "Since LLM-generated content can be controlled by prompt input, this behavior is similar to providing users indirect access to additional functionality" [1].

The model sits between a person (or a document, or a web page) and your code, and whatever steers the model also steers the reply. The page's prevention advice is blunt: "Treat the model as any other user, adopting a zero-trust approach, and apply proper input validation on responses coming from the model to backend functions" [1].

This does not mean the model is hostile or usually wrong. It means the check should not depend on whether the model is behaving: a reply from a good day and one from a manipulated prompt arrive at the same function.

OWASP separates this risk from a neighbouring one. Its page on "Excessive Agency" says it "differs from Insecure Output Handling which is concerned with insufficient scrutiny of LLM outputs" [2]. Excessive Agency is about what the system may do; output handling is about what it receives. You need both, and this article covers the second.

What goes wrong when nothing checks the reply

OWASP's output-handling page lists concrete ways the reply becomes a problem when it is passed on unchecked [1]:

  • model output entered into a system shell or a function such as exec or eval;
  • JavaScript or Markdown generated by the model and returned to a user, where the browser interprets it;
  • model-generated SQL executed without parameterization;
  • model output used to build file paths without sanitization;
  • model-generated content placed in email templates without escaping.

These are the old injection problems with a new kind of source. Each item is also a different destination, and each destination interprets text differently, which is why one generic check does not work.

Why a single check at the front is not enough

A common first design is one filter: scan the reply for bad words, then pass it on. Two things make it weak.

First, "bad" depends on the destination. A string that is harmless in a chat bubble can matter in a SQL statement or a web page. The OWASP page asks for "context-aware output encoding based on where the LLM output will be used" [1]. A filter that does not know the destination cannot pick the right rule.

Second, the filter and the executor drift apart. If the check lives in the chat layer and the executor is later called from a scheduled job, an admin tool or another agent, that path has no check. OWASP's guidance on agents states the fix as a principle: "Implement authorization in downstream systems rather than relying on an LLM to decide if an action is allowed or not" [2]. The same reasoning applies to validation: put it where every path to the action must pass.

So the practical rule has two halves. Put one validation step directly in front of each executor, so no route skips it. And write that step for that executor's inputs, not for "model output" in general.

A fictional example: an order-status bot

The following example is invented. Example Shop is a made-up store with a chat assistant, and Ana and Ben are made-up customers. Nothing here describes a real product.

The bot has one tool: look up the status of an order. The model replies with a small proposal naming a tool and its arguments, for example order_status with order_id set to A-1001. The signed-in customer is Ana, whose orders are A-1001 and A-1002. Ben's order is B-2001. The application knows who is signed in from its own session, not from the model.

The boundary sits between the proposal and the lookup. It does five things, in this order:

  1. Is the tool on the allowlist? Only order_status is. Anything else is rejected, including a tool the model was never offered.
  2. Are the argument names exactly the expected ones? No extras, none missing.
  3. Is each value the right type and shape? The order id must be a string matching one letter, a hyphen and four digits.
  4. Does the value pass the business rule? The order must exist and belong to the signed-in customer. The owner is read from the database, not from the proposal.
  5. Is the query built safely? The value reaches the database through a bound parameter, never by pasting it into the query text.

The test, run on 2 December 2026, fed the boundary six proposals as Ana (Python 3.10.6, standard library, in-memory SQLite, no real model; script and output in the article folder). The results:

Proposal Result
Tool order_status, id A-1001 Allowed, returns "shipped"
Same tool, id B-2001 (Ben's order) Rejected: order not found for this user
Same tool, id containing a quote and an OR clause Rejected: wrong format
Tool refund_order (never offered) Rejected: not on the allowlist
Right tool plus an extra argument named note Rejected: unexpected argument
Id given as the number 1001 Rejected: wrong format (not a string)

Two further runs isolate the database layer. A query built by pasting the id with the quote and the OR clause into the SQL text returned all three rows of the table. The same id passed as a bound parameter, with no validator, returned nothing. So the format check and the bound parameter each stopped this input on its own.

This is a toy: three rows, one tool, no model, one input shape picked to show a mechanism. It does not measure how often a real model produces such proposals and says nothing about any real system.

A fictional Example Shop order bot drawn as a path: the model's proposal enters a boundary box with five checks in a row, allowlist, argument names, type and shape, business rule, safe query, and only a passing proposal reaches the order database; rejected ones turn back with a reason.

What to check depends on the destination

The five checks above fit a database lookup. Other destinations need other checks. This table pairs each destination with what the sources say.

Where the reply goes What to do before it gets there Source
A database query Bind values through the database API. Map structural choices (table names, sort direction) to a fixed list [1][3][5]
A web page Treat the text as data, encode it for the context it lands in [1][4]
A file path Do not build a path from unsanitized model text (the author's proposal: let the model pick from known names and let code build the path) [1]
A shell or an interpreter Do not enter model text into it; prefer a narrow function that does one job in place of an open-ended one [1][2]
A person's email or message Escape the content for the template it lands in [1]
A tool that changes things Check authorization in the system that does the work; require approval for high-impact actions [2]

Queries. The Python sqlite3 documentation says: "Always use placeholders instead of string formatting to bind Python values to SQL statements, to avoid SQL injection attacks" [5]. OWASP's SQL injection cheat sheet says relying on "manually escaping dynamic inputs is error-prone and is strongly discouraged" [3]. For what a bound parameter cannot cover, "table names, column names, sort direction", it recommends mapping the choice "to a strict allow-list of fixed, application-owned values" [3]. If a model picks a sort order, the code should translate "newest" into the real clause itself.

Pages. The OWASP cross-site scripting cheat sheet says to "Prefer safe APIs that treat data as text" and to use context-specific output encoding where text lands in a context that interprets syntax [4]. In the test, a reply containing a script tag, passed through the standard library's HTML escaping, came out as inert text: the angle brackets became entities. That is a one-line case, not a full defence; the cheat sheet says HTML attributes and JavaScript contexts need other encodings [4]. It also warns: "Input validation can enforce expected formats, but it does not replace these protections" [4].

Actions. OWASP suggests: "Utilise human-in-the-loop control to require a human to approve high-impact actions before they are taken" [2]. This is a separate gate for actions you cannot take back, and it works best when the approval screen shows the resolved values in plain words, not the model's phrasing.

Where the checks live in the code

Placement matters as much as content. A design that holds up has these properties:

  • One chokepoint per executor. The validator runs inside the function that performs the action, or in a wrapper every caller must use. A check a caller can skip is a suggestion.
  • Identity from the session, never from the reply. In the test, the customer came from the application's state and the owner was read from the database. If the model is asked "which user is this for", that field is untrusted too.
  • Allowlists, not blocklists. The test accepts one tool, one argument name and one id shape. A list of known bad strings holds only the cases someone already thought of.
  • Reject with a reason, and keep the reason. Log the tool, the rule that failed and a request id. OWASP lists "Insufficient monitoring and logging of LLM outputs" among the conditions that raise the impact [1]. Do not log full private text.
  • Say what happens next. A rejection needs a defined outcome: ask the user, show a short message, or hand over to a person. A blind retry is not an outcome; see "Retries That Do Not Repeat the User's Action".

Schema validation and what vendors promise about structure are covered in "Structured Output Is Only Part of the Contract" and not repeated here. The boundary includes a schema check as one step and adds destination-specific rules and placement.

A fictional diagram of two routes to the same order lookup, the chat and a scheduled admin job, both passing through one boundary box placed directly in front of the executor; a dashed alternative with the check only in the chat layer shows the second route skipping it.

What a validator cannot catch

A boundary has limits, and it is better to name them.

  • Plausible, permitted and wrong. If the order id belongs to Ana and is real, but she meant the other one, every check passes. A validator checks that the action is allowed, not that it is what the user meant. Close that gap by showing the resolved values and asking for confirmation.
  • Safe for the executor, bad for the reader. A reply can be harmless to the database and still a misleading answer. That is answer-quality work, a separate job.
  • Gaps in the allowlist. If the allowlist contains a tool that does too much, the boundary approves it faithfully. Access limits and output checks work together, not in place of each other.
  • The sink you forgot. A new executor added later without a boundary is unprotected. Keep a short inventory of every place model output goes, and review it when a feature is added.

A checklist to adapt

This is the author's proposal, not an industry standard.

  • List the sinks: every place model output is shown, stored, run or sent.
  • One boundary per sink, inside or immediately in front of the executor.
  • Allowlist first: tools, argument names, formats, values from fixed lists.
  • Identity and permission from the session and the database, never from the reply.
  • Use the destination's safe API: bound parameters, text not markup, narrow functions instead of shells.
  • Gate the irreversible: a human approves the resolved values first.
  • Log rejections without private content, and define the next step.
  • Test the rejections: keep a small fixed set like the six above, and include legitimate-looking cases that must fail, such as another user's record.

What this article does not settle

It does not say how often real models produce output that should be rejected; no source read here reports a rate, and the test used no model. It does not claim the five checks suffice for a real system: the example is a toy with one tool and fictional data. It does not cover prompt-side defences, moderation or the input side, does not compare guardrail products and does not promise that a boundary prevents every attack. The table is a summary of the pages read, not a complete list. The design and the checklist are a proposal. Sources are as read on 2 December 2026 and may change.

How this article was made

Task What the AI did What a person did How it was checked
Research Gathered candidate sources and drafted notes Chose the question and which pages to rely on Every quote checked against the page named in the sources, downloaded as raw text on 2 December 2026
Test Wrote and ran a small Python script on fictional data Reviewed what the script does and what it does not show Script and its output saved in the article folder; run on Python 3.10.6 on 2 December 2026
Draft Wrote the first draft from the notes Edited the text, the example and the checklist An independent review compares claims with the sources before publication
Images Generated the cover illustration Chose and checked it Labelled as AI-generated in the disclosure line and alt text
Not done by AI — The decision to publish and responsibility for the text —

Conflicts of interest: none. The author has no commercial relationship with the organisations named here.

Responsible for this article: Dmitriy Lastovka, author. Corrections: contact form.

Sources

Labels: guidance (a published security guidance page), cheat sheet (a practitioner reference), documentation (a software project's documentation). Quotes are as on the pages read on 2 December 2026.

  1. OWASP GenAI Security Project, "LLM05:2025 Improper Output Handling". https://genai.owasp.org/llmrisk/llm052025-improper-output-handling/ Guidance.
  2. OWASP GenAI Security Project, "LLM06:2025 Excessive Agency". https://genai.owasp.org/llmrisk/llm062025-excessive-agency/ Guidance.
  3. OWASP Cheat Sheet Series, "SQL Injection Prevention Cheat Sheet". https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html Cheat sheet.
  4. OWASP Cheat Sheet Series, "Cross Site Scripting Prevention Cheat Sheet". https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html Cheat sheet.
  5. Python documentation, "sqlite3 — DB-API 2.0 interface for SQLite databases". https://docs.python.org/3/library/sqlite3.html Documentation.

Tier I

Sector: #18291

Sealed Hiding Place Room

Resource Cache

Resource Cache

Tier I

Requires 25% Tier Progress to Claim
Meme Cache

Meme Cache

Tier I

Requires 50% Tier Progress to Claim
Equipment Cache

Equipment Cache

Tier I

Requires 75% Tier Progress to Claim

After collecting, hiding places will be stored in your inventory and can be opened with Keys.

Other articles

Giving an Agent Only the Access It Needs

How to limit what an AI agent can do through its tools: fewer tools, narrower functions, scoped credentials, user context and approvals. A fictional example.

user avatarme1afon

When Retrieved Text Tries to Become an Instruction

Why text an AI agent reads from a document cannot be treated as a command, what OWASP and the research say, and a checkable rule for your own chat.

user avatarme1afon

Teaching a Chat to Say It Does Not Know

When a chat should decline to answer: four kinds of no-answer, what research says models do instead, a fictional help-chat example and a test plan.

user avatarme1afon

Handling Stale and Conflicting Sources

Two retrieved passages give different numbers. Name the kind of disagreement, apply a rule written in advance, and show the dates.

user avatarme1afon

A Citation Is Not the Same as Evidence

A link beside a sentence is a pointer; evidence is a passage that says the same thing. The "according to" test, audit figures, a fictional example, a check.

user avatarme1afon

What Reranking Adds to Retrieval

Why a second scoring pass over retrieved passages can help, what documentation and papers report, its cost and limits, and a fictional example.

user avatarme1afon

Important disclaimer: The information presented on the Dapp.Expert portal is intended solely for informational purposes and does not constitute an investment recommendation or a guide to action in the field of cryptocurrencies. The Dapp.Expert team is not responsible for any potential losses or missed profits associated with the use of materials published on the site. Before making investment decisions in cryptocurrencies, we recommend consulting a qualified financial advisor.