{%- set vars = namespace(next_image_id=1) -%}
{%- for message in messages -%}
    {{ '<|' + message['role'] + '|>' + '\n' }}

    {%- if message['content'] is string -%}
        {{ message['content'] }}
    {%- elif message['content'] is iterable -%}
        {%- for item in message['content'] -%}
            {%- if item['type'] == 'text' -%}
                {{ item['text'] if 'text' in item else item['content'] }}
            {%- elif item['type'].startswith('image') -%}
                {{ '<|image_{i:d}|>'.format(i=vars.next_image_id) }}
                {%- set vars.next_image_id = vars.next_image_id + 1 -%}
            {%- endif -%}
        {%- endfor -%}
    {%- endif -%}

    {{ '<|end|>\n' }}
{%- endfor -%}

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