Format a ChatML Prompt Template

Basics
BasicsPromptingChatMLOpenAIAnthropicGoogle

Problem

Implement format_chatml(system_prompt, user_message) that formats a system instruction and user turn into the standard ChatML prompt template ending with <|im_start|>assistant\n so an instruct LLM immediately begins generating the assistant reply.

Why It Matters: Open-weight instruct models (Qwen, OpenHermes, Mistral/ChatML fine-tunes) rely on exact special-token delimiters; a single missing newline or <|im_end|> tag causes degraded answers or runaway generation.

Function Signature

def format_chatml(system_prompt: str, user_message: str) -> str:
    """Format system and user text into a ChatML prompt string."""

Sample Input & Output

Example 1: Standard System + User Turn

Input:

system_prompt = "You are helpful.", user_message = "Hi!"

Expected Output:

"<|im_start|>system\nYou are helpful.<|im_end|>\n<|im_start|>user\nHi!<|im_end|>\n<|im_start|>assistant\n"

Explanation: Each role block is wrapped in <|im_start|>role\n...<|im_end|>\n, finishing with the open assistant header.

Example 2: Empty System Prompt

Input:

system_prompt = "", user_message = "2+2?"

Expected Output:

"<|im_start|>system\n<|im_end|>\n<|im_start|>user\n2+2?<|im_end|>\n<|im_start|>assistant\n"

Explanation: Even if system_prompt is empty, the exact ChatML role structure and trailing newline are preserved.

Constraints & Edge Cases

  • Match exact ChatML tags and newline separators.
  • Do not forget the trailing newline \n right after <|im_start|>assistant.
  • No extra spaces before <|im_end|>.

Constraints & Evaluation Criteria

  • Match exact ChatML tags and newline separators.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
'Be concise.', 'Hi'
Expected Output / Criteria
3-block ChatML string