Render and Parse a Chat Template

easy
Unit 7 · Safety & Prompting0/3 to milestone

Chat models never see JSON messages. They see one string with special tokens marking each turn. The ChatML format looks like this:

<|im_start|>system
You are helpful.<|im_end|>
<|im_start|>user
Hi<|im_end|>

Each message renders as <|im_start|>{role}\n{content}<|im_end|>\n.

Implement:

  • render(messages, add_generation_prompt=False) for a list of {"role", "content"} dicts. Validate first, raising ValueError if:

    • a role isn't system, user or assistant
    • a system message appears anywhere but first
    • after the optional system message, the turns don't alternate user/assistant starting with user
    • any content contains <|im_start|> or <|im_end|> (users must not be able to inject fake turns)

    If add_generation_prompt is set, append <|im_start|>assistant\n so the model knows to reply.

  • parse(text): the inverse, returning the list of messages (ignore a trailing generation prompt)

#prompting#tokenizers#chat2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Render and Parse a Chat Template · TechGradify