Sub topic 8
Chat templates and instruction-tuned models
This chapter assumes you can run LLM offline and call vllm serve, as covered in the previous chapters. It also assumes you know the messages format of chat APIs. Here you will learn what a chat template is and where vLLM applies it. You will also see the errors that appear when the template is wrong or missing.
Base models and instruction-tuned models
A base model is trained only to continue text. An instruction-tuned model is trained further on conversations, so it answers a request instead of continuing it. During that training, every conversation is written in one fixed text format. The format uses special marker tokens that show where each message starts and ends and who wrote it.
The model learned that format, so it expects to see it at inference time. If you send plain text where the model expects markers, quality drops. You may see rambling, repeated user turns, or answers that never stop.
What a chat template is
A chat template is a Jinja program stored in the model's tokenizer_config.json under the chat_template key. It turns a list of role/content messages into the single prompt string the model was trained on. The Hugging Face tokenizer runs it. vLLM calls the tokenizer, so it uses the same template the model authors published.
For Qwen/Qwen2.5-1.5B-Instruct, the template produces the ChatML format. The <|im_start|> and <|im_end|> markers wrap each message. The last line of the prompt opens an assistant turn, and the model completes it.
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-1.5B-Instruct")
messages = [
{"role": "system", "content": "Answer in one sentence."},
{"role": "user", "content": "What is a KV cache?"},
]
prompt = tok.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
print(prompt)The output looks like this:
<|im_start|>system
Answer in one sentence.<|im_end|>
<|im_start|>user
What is a KV cache?<|im_end|>
<|im_start|>assistantTwo arguments matter here:
tokenize=Falsereturns the string, so you can read it. Leave it out to get token IDs.add_generation_prompt=Trueappends the opening of an assistant turn. Without it the prompt ends after the user message, and the model may write another user turn instead of an answer.
Where vLLM applies the template
The template runs only on the chat entry points. The plain completion entry points send your text to the model unchanged.
| Entry point | Template applied? | Input |
|---|---|---|
| `llm.chat(messages, params)` | Yes | List of messages |
| `llm.generate(prompt, params)` | No | Raw prompt string |
| `POST /v1/chat/completions` | Yes | List of messages |
| `POST /v1/completions` | No | Raw prompt string |
This is the most common source of confusion. If you call llm.generate("What is a KV cache?") on an instruction model, the model receives text with no markers. It still produces output, but the output is often worse and may look unrelated to the question.
flowchart LR
A["messages: role and content"] --> B["chat template (Jinja)"]
B --> C["prompt string with markers"]
C --> D["tokenizer"]
D --> E["token IDs"]
E --> F["vLLM scheduler and model"]
G["raw prompt string"] --> DRunning the diagram through the exact syntax above would fail, because the chapter format needs the diagram mermaid fence. The corrected version follows.
Comparing the two paths
The following script sends the same question through llm.chat and through llm.generate with a raw string. Run it and compare the replies.
from vllm import LLM, SamplingParams
llm = LLM(
model="Qwen/Qwen2.5-1.5B-Instruct",
max_model_len=4096,
gpu_memory_utilization=0.85,
)
params = SamplingParams(temperature=0.0, max_tokens=80)
question = "Explain the KV cache in two sentences."
templated = llm.chat([{"role": "user", "content": question}], params)
raw = llm.generate([question], params)
print("chat(): ", templated[0].outputs[0].text)
print("generate():", raw[0].outputs[0].text)Setting temperature=0.0 makes decoding greedy, so the difference you see comes from the prompt format and not from sampling noise.
You can also render the prompt yourself with apply_chat_template(..., tokenize=False, add_generation_prompt=True) and pass the string to llm.generate. The result should match llm.chat. Do this when you need to inspect or log the exact prompt.
The default system prompt
Some templates insert a system message when you provide none. The Qwen2.5 template adds "You are Qwen, created by Alibaba Cloud. You are a helpful assistant." in that case. This costs a few prompt tokens on every request. It can also change behavior if you assumed there was no system prompt. Always print the rendered prompt once for any model you deploy.
Special tokens and double markers
Tokenizers for some model families add a beginning-of-sequence (BOS) token automatically when they encode text. Llama-style templates already write the BOS token into the rendered string. If you render the template yourself and then pass the string to a path that tokenizes it again with special tokens enabled, the prompt starts with two BOS tokens. Quality usually degrades only slightly, so the bug is easy to miss. Using llm.chat or the chat endpoint avoids it, because vLLM handles tokenization after templating.
Missing templates and overrides
Base models usually have no chat_template. Recent versions of transformers no longer supply a fallback default. When you call the chat endpoint on such a model, vLLM returns an error saying the model's tokenizer does not define a chat template and that you must provide one. The right response depends on the model:
- If the model is a base model, use the completions endpoint with your own prompt format.
- If it is instruction-tuned but its repository lacks a template, supply one with
--chat-template.
A template file is plain Jinja. This one writes ChatML:
cat > chatml.jinja <<'EOF'
{% for message in messages %}{{ '<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>\n' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}
EOF
vllm serve Qwen/Qwen2.5-1.5B-Instruct \
--max-model-len 4096 \
--chat-template ./chatml.jinjaThe --chat-template option also overrides a template that the model already has. Use it only to match the format the model was trained on. A template cannot teach a model markers it has never seen. The model's own documentation is the source of truth for its format.
Common errors
- Using
generatefor chat. Replies are off-topic or ramble. Switch tollm.chator render the template first. - Forgetting
add_generation_prompt=True. When rendering by hand, the model continues the user turn. Add the flag. - Wrong template for the model. A template from a different family inserts markers the model does not know. Output degrades without any error.
- Replies that never end. The stop token was not recognized. Check that the model's
generation_config.jsonand tokenizer define the end-of-turn token, and do not overridestop_token_idswith a wrong value. - Roles the template rejects. Some templates raise an error if the conversation does not alternate user and assistant, or if a system role is not allowed. Fix the message list, not the server.
Exercise
You serve an instruction-tuned model with vllm serve. A colleague sends the question through POST /v1/completions with the prompt "Summarize the KV cache." and the answers are poor. The same question works well through POST /v1/chat/completions. What is the cause, and how can the colleague keep using /v1/completions?
Show answer
The completions endpoint does not apply the chat template, so the model receives text without its role markers. The chat endpoint applies the template, which is why it works. To keep using /v1/completions, render the prompt first with tokenizer.applychattemplate(messages, tokenize=False, addgenerationprompt=True) and send that string as the prompt.
Exercise
A model repository has no chat_template, and the chat endpoint returns an error about a missing template. Name two ways to resolve this and the condition each one needs.
Show answer
Either use the completions endpoint with a prompt in the format the model's documentation describes, or start the server with --chat-template pointing at a Jinja file. The second option only works if the file reproduces the format the model was trained on. If the model is a base model with no instruction tuning, the first option is the better choice.