{%- for message in messages -%}
    {%- if message['role'] == 'system' -%}
        {{- '<|im_start|>system\n' + message['content'] -}}
        {%- if tools is not none -%}
            {{- '<functions>' -}}{{- tools | tojson -}}{{- '</functions>' -}}
        {%- elif message.get('functions', none) is not none -%}
            {{- ' <functions>' + message['functions'] + '</functions>' -}}
        {%- endif -%}
        {{- '<|im_end|>\n' -}}
    {%- elif message['role'] == 'user' -%}
        {{- '<|im_start|>user\n' + message['content'] + '<|im_end|>\n' -}}
    {%- elif message['role'] == 'assistant' -%}
        {{- '<|im_start|>assistant\n' -}}
        {%- if message.get('content', none) is not none -%}
            {{- message['content'] -}}
        {%- endif -%}
        {%- if not loop.last -%}
            {{- '<|im_end|>\n' -}}
        {%- else -%}
            {{- eos_token -}}
        {%- endif -%}
    {%- endif -%}
    {%- if loop.last and add_generation_prompt -%}
        {{- '<|im_start|>assistant\n' -}}
    {%- endif -%}
{%- endfor -%}
