| {%- if messages[0].role == 'system' %} |
| {{- '<|BOT|>system\n' + messages[0].content + '<|EOT|>\n' }} |
| {%- endif %} |
| {%- set ns = namespace(last_query_index=messages|length - 1) %} |
| {%- for message in messages[::-1] %} |
| {%- set index = (messages|length - 1) - loop.index0 %} |
| {%- if message.role == "user" %} |
| {%- set ns.last_query_index = index %} |
| {%- break %} |
| {%- endif %} |
| {%- endfor %} |
| {%- for message in messages %} |
| {%- if (message.role == "user") or (message.role == "system" and not loop.first) -%} |
| {{- '<|BOT|>' + message.role + '\n' }} |
| {%- for content in message.content | selectattr('type', 'equalto', 'image') %}{{ '<|image|>' }}{% endfor -%} |
| {%- for content in message.content | selectattr('type', 'equalto', 'video') %}{{ '<|video|>' }}{% endfor -%} |
| {% set has_media = (message.content | selectattr('type', 'in', ['image', 'video']) | list | length) > 0 %} |
| {%- for content in message.content | selectattr('type', 'equalto', 'text') -%} |
| {%- if has_media -%} |
| {{ '\n' + content.text }} |
| {%- else -%} |
| {{ content.text }} |
| {%- endif -%} |
| {%- endfor -%} |
| {{- '<|EOT|>\n' }} |
| {%- elif message.role == "assistant" %} |
| {%- set content_list = message.content | selectattr('type', 'equalto', 'text') | list %} |
| {%- set content = '' %} |
| {%- if content_list %} |
| {%- set content = content_list[0].text %} |
| {%- endif %} |
| {%- set reasoning_content = '' %} |
| {%- if message.reasoning_content is string %} |
| {%- set reasoning_content = message.reasoning_content %} |
| {%- else %} |
| {%- if '</think/>' in content %} |
| {% set parts = content.split('</think/>', 1) %} |
| {% set reasoning_content = parts[0].split('<think>', 1) | last | trim %} |
| {% set content = parts[1] | trim %} |
| {%- elif '</think>' in content %} |
| {% set parts = content.split('</think>', 1) %} |
| {% set reasoning_content = parts[0].split('<think>', 1) | last | trim %} |
| {% set content = parts[1] | trim %} |
| {%- endif %} |
| {%- endif %} |
| {%- if loop.index0 > ns.last_query_index %} |
| {%- if loop.last or (not loop.last and reasoning_content) %} |
| {{- '<|BOT|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n' + content.lstrip('\n') + '<|EOT|>\n' }} |
| {%- else %} |
| {{- '<|BOT|>' + message.role + '\n' + content + '<|EOT|>\n' }} |
| {%- endif %} |
| {%- else %} |
| {{- '<|BOT|>' + message.role + '\n' + content + '<|EOT|>\n' }} |
| {%- endif %} |
| {%- endif %} |
| {%- endfor %} |
| {%- if add_generation_prompt %} |
| {{- '<|BOT|>assistant\n' }} |
| {%- if enable_thinking is defined %} |
| {%- if not enable_thinking %} |
| {{- '<think>\n\n</think>\n' }} |
| {%- else %} |
| {{- '<think>\n' }} |
| {%- endif %} |
| {%- else %} |
| {{- '<think>\n\n</think>\n' }} |
| {%- endif %} |
| {%- endif %} |