skip to content

In Hugging Face Transformers, what do apply_chat_template's add_generation_prompt and continue_final_message do, and when do you set each?

level: middleimportance: must knowfreq 28%

answer

  1. where the rendered prompt stops
  2. the assistant-turn header
  3. False by default, True for inference
  4. prefill: leave the last message open
  5. both at once raises ValueError

basics

~20 s

add_generation_prompt=True appends the template's assistant-turn header so the model replies as the assistant; use it at inference, not for training data. continue_final_message=True leaves the last message open so the model continues a prefill. Combining them raises.

solid answer

~40 s

`apply_chat_template` renders a list of `{"role", "content"}` messages through the Jinja template stored with the tokenizer, so the model's own control tokens frame each turn. `add_generation_prompt` defaults to `False`: the prompt then ends after the last user turn, and the model may continue that turn instead of answering. Set it to `True` at inference to append the assistant header; leave it `False` when formatting training conversations. It only works if the template uses the flag. `continue_final_message=True` drops the end-of-turn tokens after the final message, so the model continues text you prefilled, such as an assistant reply started with an opening brace. The two contradict each other and together raise a `ValueError`. In Transformers v5 the default `tokenize=True, return_dict=True` returns a `BatchEncoding`, so call `model.generate(**inputs)`.

go deeper

for a junior

Recall that apply_chat_template turns a list of role and content messages into the model's own prompt format, and that add_generation_prompt=True is what makes the model answer as the assistant.

for a middle

Explain the defaults: add_generation_prompt False, tokenize True, and the v5 BatchEncoding return. Show when continue_final_message is the right flag and why combining the two raises.

for a senior

Diagnose wrong-prompt bugs from outputs: a model writing user turns, a closed prefill, duplicated special tokens after re-tokenizing. Know that the flag only works if the template reads it.

for a principal

Argue for rendering every prompt through the checkpoint's own template in shared code, never hand-built strings, so a model swap cannot silently change the format.

## What apply_chat_template does A chat model was trained on conversations written in one exact text format: particular **control tokens** mark where a system, user or assistant turn starts and ends. That format is stored with the tokenizer as a **chat template**, a Jinja template saved in the repo (a `chat_template.jinja` file, or a `chat_template` field in older tokenizer configs) and exposed as `tokenizer.chat_template`. `tokenizer.apply_chat_template(messages, ...)` takes a list of dictionaries with `"role"` and `"content"` keys, renders them through that template, and by default tokenizes the result. It is the generic mechanism; each model family's actual tokens are that family's business. If the tokenizer has no template and you pass none, the call raises a `ValueError`: there is no built-in fallback format to guess with. ## add_generation_prompt: ask for a reply Without help, the rendered text ends right after the last message's end-of-turn marker. A model given that has no signal that it should answer as the assistant; it may write another user turn, or continue in an odd voice. - **`add_generation_prompt=True`** passes a flag into the template, which appends the tokens that open an assistant turn. Generation then starts inside an assistant message. - It defaults to **`False`**. - It only has an effect if the template reads the flag. Some templates have no assistant header to add, and for those it changes nothing. - For **training data**, leave it `False`: the conversation already contains the assistant's reply, and a trailing header would add tokens that belong to no real turn. ## continue_final_message: prefill a reply **`continue_final_message=True`** renders the final message without its closing end-of-turn tokens, so the model keeps writing that same message. The usual use is a **prefill**: you write the first characters of the assistant's answer, for example an opening `{` to steer it toward JSON, and the model continues from there. A string value names a different field of the final message to continue, such as `"reasoning_content"`, if the template renders that field. The two flags ask for opposite things, a new turn against an unfinished one, so passing both raises a `ValueError`. | Goal | Last message | Flags | |---|---|---| | Get the assistant's next reply | user | `add_generation_prompt=True` | | Continue a reply you started | assistant (partial) | `continue_final_message=True` | | Format a finished conversation for training | assistant (complete) | neither | ## Tokenize now or later | `tokenize` | `return_dict` | Returns | |---|---|---| | `False` | ignored | the rendered string | | `True` (default) | `True` (default) | a `BatchEncoding` with `input_ids` and `attention_mask` | | `True` | `False` | the `input_ids` only | In **Transformers v5** the default return became a `BatchEncoding`, where v4 returned bare ids, so the idiomatic inference call is: ```python inputs = tokenizer.apply_chat_template( messages, add_generation_prompt=True, return_tensors="pt" ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=128) ``` When `tokenize=True`, the method tokenizes the rendered text with `add_special_tokens=False`, because the template already contains every special token it needs. If you render with `tokenize=False` and tokenize the string yourself later, pass `add_special_tokens=False` too, or the tokenizer may add its own start token on top of the template's. ## Masks a template can emit For training, `return_assistant_tokens_mask=True` adds an `assistant_masks` output: 1 on tokens the assistant wrote, 0 elsewhere. It needs `tokenize=True` and `return_dict=True`, it cannot be combined with `continue_final_message`, and it depends on the template marking assistant text with a `{% generation %}` block. A template without that block only logs a warning, and the mask comes back all zeros. ## Choosing or overriding the template The `chat_template` argument overrides the stored template for one call. It accepts either a Jinja template string or the **name** of one of several templates a repo may ship; extra templates are saved as separate `.jinja` files in a `chat_templates` folder beside the default one. If a tokenizer carries several named templates and none is the default, calling without `chat_template` raises a `ValueError` listing the available names. Assigning `tokenizer.chat_template` replaces the template on the object, and `save_pretrained` writes it out with the tokenizer, so a fine-tuned checkpoint ships with the format it was trained on. ## Typical failures 1. A chatbot that keeps writing "User:" lines because `add_generation_prompt` was left at `False`. 2. A prefilled reply that gets closed and restarted because the prefill was sent as a complete message. 3. v4-era code that treats the v5 return value as a tensor of ids. 4. A hand-written prompt string instead of the template, which silently drifts from the trained format.

  • How do you get a mask of only the assistant's tokens from apply_chat_template for training?
    Pass `return_assistant_tokens_mask=True` with `tokenize=True` and `return_dict=True`; the output gains `assistant_masks`, 1 on assistant-written tokens. It only works when the template wraps assistant text in a `{% generation %}` block; otherwise a warning is logged and the mask is all zeros. It cannot be combined with `continue_final_message`.
  • How do you check exactly which prompt text a chat model will receive from apply_chat_template?
    Call it with the same flags and `tokenize=False` to get the rendered string, and print it with its control tokens visible. Or decode the `input_ids` you actually send with `skip_special_tokens` left at `False`. Comparing that text against the model card's documented format catches a missing generation prompt or a wrong template at once.

  • add_generation_prompt defaults to True, so you never need to set it.
  • add_generation_prompt should be True when formatting training conversations.
  • Without a chat template, apply_chat_template falls back to a generic default format.
  • continue_final_message and add_generation_prompt can be combined to prefill a new turn.
  • Every template adds an assistant header when add_generation_prompt is set.

Assumes Transformers v5 (5.18): apply_chat_template defaults to return_dict=True and returns a BatchEncoding, where v4 returned bare input_ids.