{% for message in messages -%}
    {%- if (loop.index % 2 == 1 and message['role'].lower() != 'user') or
            (loop.index % 2 == 0 and message['role'].lower() != 'assistant') -%}
        {{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}
    {%- endif -%}

    {{ message['role'].capitalize() + ': ' }}

    {%- 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']) }}
            {%- endif -%}
        {%- endfor -%}
    {%- endif -%}

    {%- if not loop.last -%}
        {{ ' ' }}
    {%- endif -%}
{%- endfor -%}
{%- if add_generation_prompt -%}
    {{ ' Assistant:' }}
{%- endif %}
