{%- for message in messages -%}
    {{- '<|im_start|>' + message['role'] + '\n' + message['content'] -}}
    {%- if (loop.last and add_generation_prompt) or not loop.last -%}
        {{- '<|im_end|>' + '\n' -}}
    {%- endif -%}
{%- endfor -%}

{%- if add_generation_prompt and messages[-1]['role'] != 'assistant' -%}
    {{- '<|im_start|>assistant\n' -}}
{%- endif -%}
