{%- set has_system = messages and messages[0].role == 'system' and messages[0].content is string %} {%- if has_system %} {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }} {%- endif %} {%- if messages and messages[-1].role == 'assistant' %} {# Find the user message immediately before the last assistant (scan backwards skipping last). #} {%- set ns = namespace(seen_last=false, user_before_last_asst=none) %} {%- for m in messages[::-1] %} {%- if not ns.seen_last %} {%- set ns.seen_last = true %} {%- elif ns.user_before_last_asst is none and m.role == 'user' and m.content is string %} {%- set ns.user_before_last_asst = m.content %} {%- endif %} {%- endfor %} {%- if ns.user_before_last_asst is not none %} {{- '<|im_start|>user\n' + ns.user_before_last_asst + '<|im_end|>\n' }} {%- endif %} {%- set content = '' %} {%- if messages[-1].content is string %} {%- set content = messages[-1].content %} {%- endif %} {%- set reasoning_content = '' %} {%- if messages[-1].reasoning_content is string %} {%- set reasoning_content = messages[-1].reasoning_content %} {%- else %} {%- if '' in content %} {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} {%- set content = content.split('')[-1].lstrip('\n') %} {%- endif %} {%- endif %} {%- if reasoning_content %} {{- '<|im_start|>assistant\n\n' + reasoning_content.strip('\n') + '\n\n\n' + content.lstrip('\n') + '<|im_end|>\n' }} {%- else %} {{- '<|im_start|>assistant\n' + content + '<|im_end|>\n' }} {%- endif %} {%- elif messages and messages[-1].role == 'user' and messages[-1].content is string %} {{- '<|im_start|>user\n' + messages[-1].content + '<|im_end|>\n' }} {%- endif %} {%- if add_generation_prompt %} {{- '<|im_start|>assistant\n' }} {%- endif %}