The chat API is a convenient lie
The chat completions API presents a conversation as an ordered list of messages, each labelled system, user or assistant. That structure feels fundamental, as though the model has three separate input channels. It does not. A transformer sees one flat sequence of token ids. There is no system register, no user register, no privileged memory region. The roles exist because something wrote words like system and user into the sequence before the model read it, and the model learned during training to condition on those words.
That something is the chat template: a small program, almost always written in Jinja, stored alongside the tokenizer. It receives the message list and emits a string containing role headers, separators, your content, and end-of-turn markers. The serving stack tokenizes that string and appends the assistant header so the model knows where to start writing. Everything you think of as chat behaviour is downstream of that one function.
The practical consequence is that the same message list can produce radically different token sequences depending on which template renders it, and the model only behaves well on the sequence it was trained on. A system message that carries real weight under one template may be silently folded into the first user turn under another. A prompt that works perfectly through one inference server can degrade through a different one that ships a stale copy of the template. None of this raises an exception. You get fluent, confident output that quietly ignores half your instructions.
Treat a rendering mismatch as the first hypothesis when a self-hosted model underperforms its published numbers. It is a five-minute check that eliminates a whole class of phantom bugs.
What a chat template is, mechanically
In the Hugging Face ecosystem the template lives in tokenizer_config.json under the chat_template key, or in a separate chat_template.jinja file in newer releases. You can read it directly, and you should. It is usually thirty to eighty lines of Jinja with loops over messages, conditionals on role, and calls to raise_exception for malformed input. It is code, written by a human, with version history and occasional bugs.
Rendering it is a one-liner in transformers: tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True). With tokenize=True you get ids in one step, which is what you want in production because the template and the tokenizer then cannot drift apart. The add_generation_prompt flag appends the assistant header, the cue that says the next tokens belong to the model. Forget that flag and you are asking the model to continue a document that ends with a user turn and no reply marker, which is a different and much weaker conditioning signal.
vLLM accepts --chat-template at server start and renders it for every chat completion request. Ollama stores one in the Modelfile. llama.cpp reads it from GGUF metadata or a flag. Each is a place where a different copy can enter your stack; through a gateway there may be three copies in play.
The template also decides things the API does not fix: whether a system message is allowed, whether two consecutive user messages are legal, whether an empty assistant message is dropped, whether a trailing newline follows the header, and whether the end-of-turn token is emitted or left for the model to generate.
One conversation, four templates
Take a minimal conversation: a system message saying you are a terse assistant, a user message asking for the capital of France, and an assistant reply of Paris. Rendered by four common families, it becomes four different documents.
ChatML, used by Qwen and many others, writes an im_start token, the literal word system, a newline, the content, an im_end token, then repeats for user and assistant. All three roles exist natively, multiple system messages are legal, and the role names appear as plain text inside the envelope.
Llama 3 uses a begin_of_text token, a start_header_id block containing the role name, an end_header_id, two newlines, the content, and an eot_id. The role name sits inside its own special-token envelope rather than being plain text, so the model has never seen the string system as ordinary text in that position.
Llama 2, still common in older deployments, wraps a system block inside the first instruction block and has no separate system turn at all, which makes a multi-turn system message structurally impossible.
Mistral's template has no system role in the serialized output. Pass a system message and the template concatenates it with the first user message inside one instruction block. The content survives; the role does not, so the model receives your policy as though the user had typed it.
Gemma is stricter: user and model turns alternate with start_of_turn and end_of_turn markers, there is no system role, and consecutive messages from the same role raise a template error. A correct integration fails loudly rather than guessing.
Now consider a prompt that assumes the system role is authoritative. Under ChatML it sits in its own turn, structurally separated from user content. Under Mistral it is glued to the user's question with a newline between them. Under a template that silently drops unknown roles, it disappears. The instruction did not become less important because you meant it more; the serializer changed the evidence the model has about who said what.
Special tokens are not text
A special token is an entry in the vocabulary that the tokenizer recognises as a unit and that ordinary text cannot produce by accident. The im_start marker in ChatML is one token with one id, not a run of ordinary characters. This distinction drives most of the subtle bugs in prompt construction.
When you build a prompt by string concatenation and then call the tokenizer, the tokenizer scans your text for known special-token strings and, by default, converts them to their ids. That is convenient for templates and dangerous for user input. If a user types the exact characters of an end-of-turn marker into a chat box, a naive pipeline will encode them as the real token, and the model will see a turn boundary in the middle of user content. Everything after that boundary reads as a new turn, possibly with a role the user chose.
The mitigation is not clever prompting. Strip or escape known special-token strings from untrusted content before rendering, or tokenize untrusted spans with special-token splitting disabled so the characters stay literal. Then test it: send a message containing every delimiter your model knows and confirm the rendered prompt treats it as one user turn. This is a two-minute test that most deployments never run.
The mirror-image bug is writing a template by hand with the right characters but the wrong ids. If your tokenizer has im_start in its vocabulary but you produce the string through a code path that disables special-token matching, you get several ordinary tokens where the model expects one. The text looks identical when printed. The model sees a sequence it has never seen in training, and quality drops without any error. Always render through the tokenizer's own template function rather than assembling markers yourself.
What a system prompt does, and what it cannot do
Given that the system role is a convention, what is it actually good for? Three things, all real. First, it is a stable place for instructions that apply to the whole conversation: persona, tone, output format, tool-use policy, refusal rules. Because it precedes the user turn, it conditions every later token. Second, it is cacheable: a fixed prefix can be reused across requests, which matters for latency and cost at scale. Third, it is a clean seam: you can swap a system prompt per product surface without touching user content.
What it is not is a security boundary. The model has no mechanism that makes system text physically unoverrideable. It has a learned preference, reinforced by training data and sometimes by explicit instruction-hierarchy training, to follow earlier and more privileged instructions. That preference is statistical. A determined user message, an injected document, or a tool output that says to ignore previous instructions can move the model. Work such as OpenAI's 2024 instruction-hierarchy paper improves robustness but does not turn the boundary into an access control.
Treat the system prompt as public. Assume a user can extract it, and never put API keys, internal URLs or personal data in it. Treat its instructions as strong defaults, not enforcement. If a rule must hold, enforce it in code: validate the output, restrict the tools, check authorization server-side. A prompt that says never reveal the customer's email is a suggestion; a filter that redacts email addresses is a control.
The same logic applies to injection through retrieved documents. Wrapping untrusted text in delimiters and labelling it as data helps the model separate instructions from content, and is worth doing, but it is a mitigation rather than a fix. The honest framing for a design review: the system prompt shapes behaviour, the application enforces it.
Prompts that survive any template
Write for the weakest template you might encounter, then verify against the strongest. A few rules cover most of the ground.
- Send exactly one system message, as the first element. Multiple system messages are legal in ChatML and rejected or merged elsewhere; one is portable.
- Never put role headers inside message content. A user message that begins with the word system and a colon is, at best, confusing and, at worst, a delimiter injection attempt you are authoring yourself.
- Put hard requirements in the user turn as well as the system turn. Under templates that merge the system message into the first user message, this costs nothing and reads naturally; under templates that keep them separate, repetition is a mild and usually helpful emphasis.
- State the output contract explicitly and repeat it at the end of the user message. Models attend more strongly to recent tokens, and the end of the prompt is the most recent thing they see.
- Use plain, unambiguous delimiters for data: triple quotes, XML-style tags with simple names, or fenced blocks. Avoid delimiters that collide with the model's special tokens.
- Keep the system prompt static per surface. Anything dynamic, such as a user name or a timestamp, belongs at the end of the user turn, where it cannot poison prefix caching.
- Test with the actual tokenizer and template you deploy, not with a string you pasted into a playground.
Debugging a template mismatch
The symptom is always the same shape: fluent but disobedient, answering a slightly different question than the one asked, or leaking reasoning into the final answer. The cause is usually a serialization difference you cannot see in the API response.
Start by rendering one representative request to text and reading it end to end, including whitespace. Check that the role headers match the ones in the model card, that the assistant header is present at the end, and that there is no duplicated bos token. A doubled begin-of-sequence token is a classic: transformers adds one by default and some servers add another, so the model sees a document that starts twice.
Then compare token counts. If your rendered prompt is a few tokens longer than expected, you are probably emitting literal marker text instead of special ids. If it is shorter, a role may have been dropped. Token counts are a cheap fingerprint for a structural problem.
Finally, check the server's template version against the model repository's. Templates get patched: a missing newline after a header, a changed end-of-turn token, a fixed condition for empty system messages. Log the template hash at startup next to the model hash, and treat a change in either as a change in the system.
Caching, ordering, and the cost of a moving prefix
Prefix caching, whether vLLM's automatic prefix cache or a provider's prompt caching, hashes the token prefix and reuses the key-value tensors computed for it. The reuse is exact-prefix only: one changed token at position ten invalidates everything after it.
That makes prompt layout an economic decision. Static instructions go first, in the system message. Retrieved documents come next. The user's actual question goes last. Interpolate a timestamp or a user name into the top of the system prompt and no two requests share a prefix, so you pay full prefill cost every time.
The same layout helps the model. Instructions that never change sit at the start, where they act as a constant frame; the specific task sits at the end, close to where generation begins. This is not a mysterious prompt-engineering trick, it is just putting stable context before variable context, which is also how you would lay out a function's arguments.
One caveat: some templates do not preserve the system message as a separate prefix when they merge it into the first user turn. Under Mistral's template, changing the user question changes the tokens immediately after the merged system text, so the cache breaks at that point rather than at the end. You still get reuse of the system portion only if the template emits it as a distinct block. Measure cache hit rate rather than assuming it.
Checklist before you ship
The whole topic reduces to a short list you can run against any deployment.
- Render one real request with the deployed tokenizer and template, print it with visible whitespace, and read it.
- Confirm the system message appears as its own turn, or know exactly where it went if the template merges it.
- Confirm the assistant generation prompt is present and correct.
- Confirm no duplicate bos or eos tokens at the boundaries.
- Send a message containing every special-token string the model knows and verify it stays inside one user turn.
- Log the template hash and the tokenizer revision next to the model revision.
- Keep the system prompt free of secrets and free of per-request variables.
- Enforce every hard rule in code, not only in the prompt.
- Re-run the check whenever the server image, tokenizer or weights change.