Sub topic 8
Chat Templates and Instruction-Tuned Models
Assume you know basic Python, JSON, and how prompts and completions work. You should also know that vLLM can run a model offline with LLM or expose it through an OpenAI-compatible API.
Why chat templates matter
An instruction-tuned model is a language model trained to follow requests written in a conversational format. It does not receive a Python list of messages directly. It receives tokens, including special markers that identify roles such as system, user, and assistant.
A chat template is a tokenizer rule that converts structured messages into that token sequence. Different model families use different markers. For example, one model may use <|user|>, while another uses [INST].
vLLM reads the template from the model's tokenizer configuration. The chat method applies it before generation:
from vllm import LLM, SamplingParams
llm = LLM(
model="Qwen/Qwen2.5-1.5B-Instruct",
max_model_len=4096,
)
messages = [
{"role": "system", "content": "Answer briefly and use plain language."},
{"role": "user", "content": "What does a chat template do?"},
]
params = SamplingParams(temperature=0.2, max_tokens=80)
outputs = llm.chat(messages, params)
print(outputs[0].outputs[0].text)The same message structure works with the OpenAI-compatible server. The server applies the selected model's template before sending tokens to the model.
flowchart LR
A[Messages with roles] --> B[Tokenizer chat template]
B --> C[Model input tokens]
C --> D[Generated assistant tokens]Common errors
Passing a plain prompt to an instruction-tuned model can reduce answer quality because the model may not recognize the expected conversation boundaries. Use llm.chat for messages, or use llm.generate only when you intentionally construct the model's prompt format.
The model must have a compatible chat template. If the tokenizer has no template, vLLM may report an error when you call chat. You can inspect the model files or provide a template explicitly with the server's template option.
The system role is not equally supported by every model. Some templates accept only user and assistant. Follow the model's documentation instead of assuming that every role is valid.
Do not add an assistant response to the message list unless you want the model to continue that response. The template normally adds a generation marker after the final user message.
| Input | Purpose |
|---|---|
| `system` message | Sets behavior or context |
| `user` message | Provides the current request |
| `assistant` message | Supplies prior conversation or a partial answer |
Exercise
Exercise
Why can the same messages produce different results with two instruction-tuned models?
Show answer
Each model may use a different chat template and was trained with different role markers, separators, and generation rules.