{%- if not messages %}{{- raise_exception(‘No messages provided.’) }}{%- endif %}
{# 系统消息 #}
{%- if messages[0].role == ‘system’ %}{{- ‘<|im_start|>system\n’ + messages[0].content + ‘<|im_end|>\n’ }}{%- endif %}
{# 处理每条消息 #}
{%- for message in messages %}
{%- if message.role == ‘system’ and not loop.first %}{{- raise_exception(‘System message must be at the beginning.’) }}{%- endif %}
{%- if message.role == ‘user’ %}{{- ‘<|im_start|>user\n’ + message.content + ‘<|im_end|>\n’ }}
{%- elif message.role == ‘assistant’ %}
{{- ‘<|im_start|>assistant\n’ + message.content }}
{%- if message.tool_calls and message.tool_calls is iterable %}
{%- for tc in message.tool_calls %}
{%- set tc_func = tc.function if tc.function is defined else tc %}
{{- ‘
{%- if tc_func.arguments is mapping %}
{%- for key in tc_func.arguments %}
{{- ‘
{%- endfor %}
{%- elif tc_func.arguments is string %}
{{- tc_func.arguments }}
{%- endif %}
{{- ‘
{%- endfor %}
{%- endif %}
{{- ‘<|im_end|>\n’ }}
{%- elif message.role == ‘tool’ %}
{{- ‘<|im_start|>user\n
{%- endif %}
{%- endfor %}
{# 生成提示 #}
{%- if add_generation_prompt %}{{- ‘<|im_start|>assistant\n’ }}{%- endif %}