{%- for m in messages -%}{%- if m['role'] == 'user' -%}{{ '<|user|>' + m['content'] + '<|end|>' }}{%- elif m['role'] == 'assistant' -%}{%- if loop.index0 == 0 or messages[loop.index0 - 1]['role'] != 'tool' -%}{{ '<|assistant|>' }}{%- endif -%}{%- for tc in m.get('tool_calls', []) -%}{%- set f = tc['function'] if 'function' in tc else tc -%}{%- set a = f['arguments'] -%}{%- if a is mapping -%}{%- set a = a.get('query', a.get('title', '')) -%}{%- endif -%}{{ '<|call|>' + f['name'] + ': ' + a + '<|/call|>' }}{%- endfor -%}{%- if m.get('content') -%}{{ m['content'] + '<|end|>' }}{%- endif -%}{%- elif m['role'] == 'tool' -%}{{ '<|result|>' + m['content'] + '<|/result|>' }}{%- endif -%}{%- endfor -%}{%- if add_generation_prompt and messages[-1]['role'] == 'user' -%}{{ '<|assistant|>' }}{%- endif -%}