{%- for message in messages -%}
{%- if message['role'] == 'system' -%}
{{- '<|im_start|>system\n' + message['content'] -}}
{%- if tools is not none -%}
{{- '' -}}{{- tools | tojson -}}{{- '' -}}
{%- elif message.get('functions', none) is not none -%}
{{- ' ' + message['functions'] + '' -}}
{%- endif -%}
{{- '<|im_end|>\n' -}}
{%- elif message['role'] == 'user' -%}
{{- '<|im_start|>user\n' + message['content'] + '<|im_end|>\n' -}}
{%- elif message['role'] == 'assistant' -%}
{{- '<|im_start|>assistant\n' -}}
{%- if message.get('content', none) is not none -%}
{{- message['content'] -}}
{%- endif -%}
{%- if not loop.last -%}
{{- '<|im_end|>\n' -}}
{%- else -%}
{{- eos_token -}}
{%- endif -%}
{%- endif -%}
{%- if loop.last and add_generation_prompt -%}
{{- '<|im_start|>assistant\n' -}}
{%- endif -%}
{%- endfor -%}