Why it matters

Treating LLM output as trusted is a common source of vulnerabilities: XSS via rendered HTML, code execution via LLM-generated scripts, SQL injection via LLM-generated queries. All are preventable with proper output handling.

Advertisement

The architecture

Rendering safely: escape HTML special characters. Use a markdown renderer with strict allow-list. Never inject LLM output as raw HTML.

Code execution: LLM-generated code must be sandboxed. Never eval() LLM output on the main process.

Output sanitization typesEscape for renderingHTML/JSSandbox for executionrestricted envValidate for structured useSQL/API paramsDifferent targets need different sanitization; assume LLM produces adversarial output
Three sanitization strategies.
Advertisement

How it works end to end

Structured output: when using LLM output as SQL, API parameters, or system commands, validate against a strict schema. Never concatenate directly.

Tool call validation: LLM-suggested tool calls should be authorized against a policy before executing.

Human review: for high-stakes actions (payments, deletions), require human confirmation of LLM-suggested actions.