Community Python Snippet

A Prompt Template With Safe Interpolation

After a customer email leaked into a system prompt and changed the model's persona, I built a 30-line template that quotes user input, fences code, and refuses unknown placeholders. Use it before every LLM call.

A Prompt Template With Safe Interpolation

After a customer email leaked into a system prompt and changed the model's persona, I built a 30-line template that quotes user input, fences code, and refuses unknown placeholders. Use it before every LLM call.

Python
Compiler
3 snippets
openai
security
code-template
error-handling
elisehuang

By @elisehuang

February 4, 2026

·

Updated May 20, 2026

1,093 views

10

4.4 (15)

The two failure modes I have actually hit are typos like {custmer_name} (which .format happily turns into a KeyError at request time) and customer messages that try to override the system prompt. The allowlist catches the first; fencing every value with <<<USER_INPUT ... USER_INPUT>>> markers catches the second by giving the model an unambiguous boundary to ignore instructions inside. I picked string.Formatter over Jinja or str.format_map because subclassing it lets me intercept both the field lookup and the rendering in 20 lines without a dependency. The control-character strip stops a sneaky vector where a PDF paste smuggles \x1b escape sequences that some downstream tools interpret.