Model Output Safety
🎯 Introduction
Model answers may contain harmful content, data that violates business rules, or HTML that causes XSS. Displaying or using them directly creates security risks. This article covers moderation of ordinary and streaming answers before delivery, structured data validation, and safe Markdown rendering in Vue.
🧱 Understand model output safety
Models can be influenced by user input and external sources, and can generate incorrect content on their own. Treat their output as untrusted data. OWASP calls the risk of using model output unsafely Improper Output Handling.
| Output use | Potential risks | Protection |
|---|---|---|
| Displaying answers | Harmful content, misinformation | Content moderation, fact-checking |
| Reading JSON | Invalid fields, business rule bypasses | Schema and business validation |
| Rendering pages | XSS, malicious links | Safe rendering, link restrictions |
| Executing operations | SQL injection, command injection | Parameterized queries, predefined operations, authorization |
🛠 Moderate output content
The previous article used the Moderation API to check user input. Here, we check model-generated answers to decide whether they can be delivered.
Moderate model answers
Use Node.js 22 and OpenAI SDK 5.12.2. Install dependencies in a separate directory:
npm install openai@5.12.2
After setting OPENAI_API_KEY, create moderation.mjs. First define a moderation function shared by ordinary and streaming answers:
import OpenAI from 'openai';
const openai = new OpenAI({ maxRetries: 0 });
async function moderateOutput(answer) {
const response = await openai.moderations.create({
model: 'omni-moderation-latest',
input: answer
}, { timeout: 5000 });
const result = response.results?.[0];
if (typeof result?.flagged !== 'boolean') {
throw new Error('INVALID_MODERATION_RESULT');
}
return !result.flagged;
}
Append the following code to pass generated output to the moderation function:
try {
const response = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Introduce Vue in one sentence' }]
});
const choice = response.choices[0];
const answer = choice?.message.content;
if (choice?.finish_reason !== 'stop' || typeof answer !== 'string' || !answer.trim()) {
throw new Error('INVALID_OUTPUT');
}
// Deliver only answers that pass moderation
if (await moderateOutput(answer)) {
console.log(answer);
} else {
console.log('The answer did not pass content moderation');
}
} catch {
console.log('An answer is temporarily unavailable');
}
Run node moderation.mjs. Possible results (illustrative, not measured API results):
| Situation | Content received by the user |
|---|---|
| Moderation passes | Vue is a JavaScript framework for building user interfaces. |
| Moderation rejects the answer | The answer did not pass content moderation |
| Generation or moderation fails | An answer is temporarily unavailable |
A finish_reason of stop indicates normal completion. This example rejects truncated or otherwise incomplete answers. Moderation can produce false positives and false negatives, and cannot verify factual accuracy.
🛠 Moderate streaming output
The key question for streaming responses is whether moderation happens before or after delivery: reviewing content afterward cannot retract what a user has already seen.
Full buffering
Generate → buffer → moderate → deliver
Reviews the entire answer before delivery, increasing time to first output.
Segment-based moderation
Buffer a segment → moderate with prior context → deliver
Displays content earlier, but may miss meaning that spans segments.
Moderation while sending
Send content while checking → stop on rejection
Cannot retract content the user has already seen.
Buffering the entire answer increases time to first output. Segment-based moderation can show content earlier but may miss meaning that spans segments. Moderating while sending can stop later output, but cannot prevent users from seeing content already displayed.
Moderate a streaming answer before sending it
If the application requires the entire answer to pass moderation first, replace the try...catch in moderation.mjs with the following, keeping the earlier moderation function:
try {
const stream = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Introduce Vue in one sentence' }],
stream: true,
max_completion_tokens: 300
});
let answer = '';
let finishReason = null;
for await (const chunk of stream) {
// Buffer on the server; do not send unmoderated chunks to the user
const choice = chunk.choices[0];
answer += choice?.delta.content ?? '';
if (choice?.finish_reason) {
finishReason = choice.finish_reason;
}
}
if (finishReason !== 'stop' || !answer.trim()) {
throw new Error('INVALID_OUTPUT');
}
if (await moderateOutput(answer)) {
console.log(answer);
} else {
console.log('The answer did not pass content moderation');
}
} catch {
console.log('An answer is temporarily unavailable');
}
Run node moderation.mjs again. The same three result branches apply, but nothing is printed during generation. An HTTP endpoint should likewise wait for moderation to pass before sending the response.
When segments must be displayed incrementally
Before sending each segment, moderate it together with previously sent text to preserve context. If moderation rejects it or fails, stop sending and cancel upstream generation. Do not moderate token by token: individual tokens usually lack complete meaning.
🛠 Schema and business validation
Suppose an AI Q&A application generates a document recommendation card containing a title, summary, and link. Valid JSON only means the data can be parsed; it does not guarantee valid fields or a trustworthy link.
The following examples test security logic with fixed simulated outputs, without depending on a model to generate specific content.
Validate the data structure
Use Node.js 22 and Zod 4.6.7. Install the dependency:
npm install zod@4.6.7
Create validate.mjs:
import { z } from 'zod';
const cardSchema = z.strictObject({
title: z.string().trim().min(1).max(60),
summary: z.string().max(300),
url: z.url()
});
function parseCard(raw) {
let data;
try {
data = JSON.parse(raw);
} catch {
return { ok: false, reason: 'INVALID_JSON' };
}
const result = cardSchema.safeParse(data);
if (!result.success) {
return { ok: false, reason: 'INVALID_SCHEMA' };
}
return { ok: true, card: result.data };
}
z.strictObject() rejects undeclared fields, preventing extra model-generated data from being passed directly to business code.
Validate business rules
z.url() checks URL syntax only. The application must also check whether the URL belongs to an allowed site.
Append this to validate.mjs:
const approvedOrigins = new Set(['https://docs.example.test']);
function validateCard(raw) {
const result = parseCard(raw);
if (!result.ok) {
return result;
}
const url = new URL(result.card.url);
// Allow only approved sites and reject credentials in URLs
if (url.protocol !== 'https:' || !approvedOrigins.has(url.origin)) {
return { ok: false, reason: 'UNTRUSTED_URL' };
}
if (url.username || url.password) {
return { ok: false, reason: 'UNTRUSTED_URL' };
}
return result;
}
Compare parsed URL values against the allowlist. Do not match domains with includes(), which could allow unrelated sites containing that domain in their address. If the application must control the final destination, prefer fixed links maintained by the application to avoid risks from redirects on allowed sites.
Verify validation results
Append this to the end of validate.mjs:
const card = {
title: 'Vue documentation',
summary: 'Learn the basics of Vue',
url: 'https://docs.example.test/vue/start'
};
const cases = [
['Valid data', JSON.stringify(card)],
['Invalid JSON', '{'],
['Invalid field', JSON.stringify({ ...card, title: 123 })],
['Extra field', JSON.stringify({ ...card, admin: true })],
['Unknown domain', JSON.stringify({ ...card, url: 'https://evil.test/vue' })],
['Unsafe scheme', JSON.stringify({ ...card, url: 'javascript:alert(1)' })]
];
for (const [name, raw] of cases) {
const result = validateCard(raw);
console.log(name, result.ok ? 'PASS' : result.reason);
}
Run node validate.mjs. Expected output:
Valid data PASS
Invalid JSON INVALID_JSON
Invalid field INVALID_SCHEMA
Extra field INVALID_SCHEMA
Unknown domain UNTRUSTED_URL
Unsafe scheme UNTRUSTED_URL
🛠 Render model output safely
When a browser interprets a model-generated string as HTML, event handler attributes and similar content may execute scripts, causing cross-site scripting (XSS).
Plain text versus HTML
| Vue syntax | How the browser handles model text |
|---|---|
{{ answer }} | Displays plain text without executing HTML tags |
v-html="answer" | Inserts HTML into the page, risking XSS without sanitization |
Render Markdown safely
If an AI chat interface needs headings, lists, and code blocks, text interpolation alone cannot render Markdown formatting. A Markdown parser converts syntax to HTML; DOMPurify sanitizes that HTML. These are separate responsibilities.
In an existing Vue 3 client application (Node.js 22), install markdown-it 15.0.3 and DOMPurify 3.5.0:
npm install markdown-it@15.0.3 dompurify@3.5.0
Create SafeMarkdown.vue. Configure the parser, sanitize the generated HTML, then pass it to v-html:
<template>
<div v-html="safeHtml"></div>
</template>
<script setup>
import { computed } from 'vue';
import MarkdownIt from 'markdown-it';
import DOMPurify from 'dompurify';
const props = defineProps({
answer: { type: String, required: true }
});
// Disable raw HTML in Markdown
const markdown = new MarkdownIt({ html: false, linkify: false });
// Allow only absolute HTTPS links while retaining the parser's safety checks
const defaultValidateLink = markdown.validateLink.bind(markdown);
markdown.validateLink = (url) => {
return defaultValidateLink(url) && /^https:\/\//i.test(url);
};
const safeHtml = computed(() => {
if (!DOMPurify.isSupported) {
return '';
}
const html = markdown.render(props.answer);
// Render only sanitized HTML
return DOMPurify.sanitize(html, {
USE_PROFILES: { html: true },
FORBID_TAGS: ['img', 'iframe', 'form', 'input', 'style'],
FORBID_ATTR: ['style']
});
});
</script>
This example disables images to prevent rendering from automatically requesting external resources supplied by the model.
Pass the following test content from a parent component in a standard Vue client application:
<template>
<SafeMarkdown :answer="answer" />
</template>
<script setup>
import SafeMarkdown from './SafeMarkdown.vue';
const answer = `## Getting started with Vue
**Components** are the building blocks of Vue.
<img src=x onerror=alert(1)>
[Unsafe link](javascript:alert(1))
[Official documentation](https://vuejs.org/)`;
</script>
The demo below renders with the same configuration in real time. Headings and bold text should render normally, raw HTML should appear as text, the unsafe link should not be clickable, and the official documentation link should work.
## Getting started with Vue __Components__ are the building blocks of Vue. <img src=x onerror=alert(1)> [Unsafe link](javascript:alert(1)) [Official documentation](https://vuejs.org/)
Do not append unsanitized HTML after sanitization, and keep security dependencies updated.
⚠️ Avoid executing model output directly
Do not pass model-generated strings directly to a database, shell, or eval(): unexpected instructions could abuse the application's own privileges.
| Unsafe practice | Recommended approach |
|---|---|
| Executing arbitrary model-generated SQL | Use predefined queries with parameter binding |
| Executing model-generated shell commands | Provide predefined operations with validated parameters |
| Executing model-generated JavaScript | Display code as text; use an isolated environment when execution is required |
❓ Questions and answers
Q1: Can the model regenerate an answer after its output is blocked?
Yes, but apply the same checks to the new answer and limit retries. If it still fails, return a clear failure message rather than weakening the safeguards.
🧪 Exercise
Edit the demo's Markdown to include lists, code blocks, raw HTML, unsafe URL schemes, and external images. Observe the rendering results.
Acceptance criteria: Lists and code blocks render normally; raw HTML does not execute; unsafe links are not clickable; external images produce no img elements; normal HTTPS documentation links remain clickable.
🎉 You can now choose moderation, validation, and safe handling based on how model output will be used.
Input Security and Content Moderation
Understand moderation classifications and use Express with the OpenAI Moderation API to block unacceptable input before calling a generative model.
Resource Consumption Protection
Limit AI request rates and concurrency, set timeouts, and cancel requests explicitly.
