Render chat messages into a model prompt string

Why it matters A prompt rendered differently from training (a missing newline or header) is one of the most common reasons a fine-tuned chat model behaves badly.

Chat models are trained on one exact text layout. Fine-tuning data and inference prompts must be rendered the same way.

Write render_chat(messages, add_generation_prompt=True). messages is a list of dicts with "role" and "content". Allowed roles are "system", "user" and "assistant"; any other role raises ValueError, and so does a "system" message that is not the first message. Render each message as "<|" + role + "|>\n" + content + "<|end|>\n" and concatenate. If add_generation_prompt is True, append "<|assistant|>\n" so the model starts its reply.

Signaturedef render_chat(messages, add_generation_prompt=True)

Example

render_chat([{"role": "user", "content": "Hi"}]) is "<|user|>\nHi<|end|>\n<|assistant|>\n".

Understand the idea

A chat model never sees "messages"; it sees one long string. The chat template is the agreed layout that turns a list of turns into that string, like the fixed format of a railway ticket that the scanner expects.

Example: one user turn "Hi". The template writes the header <|user|>, a newline, the content, and an end marker: "<|user|>\nHi<|end|>\n". At inference we then add "<|assistant|>\n" so the next tokens the model writes are its reply. For a training example that already contains the assistant answer, we do not add an extra header.

Rule: text = concat("<|role|>\n" + content + "<|end|>\n" for each message) + ("<|assistant|>\n" if generating).

Real templates differ by model family, but every one has the same parts: role headers, end-of-turn markers and a generation prompt. Tokenizer libraries store the template with the model so training and serving render identically.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplerender_chat([{'role': 'user', 'content': 'Hi'}])
  • Sample 2: training samplerender_chat([{'role': 'system', 'content': 'Be brief.'}, {'role': 'user', 'content': '2+2?'}, {'role': 'ass...
  • Test 3: bad role_raises(lambda: render_chat([{'role': 'tool', 'content': 'x'}]))
  • Test 4: late system_raises(lambda: render_chat([{'role': 'user', 'content': 'a'}, {'role': 'system', 'content': 'b'}]))