File size: 1,931 Bytes
18b309b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
{%- 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 '</think>' in content %}
{%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
{%- set content = content.split('</think>')[-1].lstrip('\n') %}
{%- endif %}
{%- endif %}
{%- if reasoning_content %}
{{- '<|im_start|>assistant\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\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<|im_start|>assistant\n' }}
{%- endif %} |