| {%- macro safe_content(msg) -%} |
| {%- if msg.content is string -%} |
| {{ msg.content }} |
| {%- elif msg.content is iterable -%} |
| {%- for item in msg.content -%} |
| {%- if item.type == 'text' -%}{{ item.text }}{%- endif -%} |
| {%- endfor -%} |
| {%- endif -%} |
| {%- endmacro -%} |
| |
| {%- macro format_tool_call(tc) -%} |
| {%- set func = tc.function | default(tc) -%} |
| {%- set args = func.arguments | default('{}') -%} |
| <tool_call> |
| {"name": "{{ func.name | default('unknown') }}", "arguments": {{ args if args is string else (args | tojson) }}} |
| </tool_call> |
| {%- endmacro -%} |
| |
| {%- macro render_message(msg) -%} |
| {%- set content = safe_content(msg) -%} |
| {%- set reasoning = msg.reasoning_content | default('') | trim -%} |
| |
| {%- if msg.role == 'user' -%} |
| <|im_start|>user |
| {{ content }} |
| <|im_end|> |
| |
| {%- elif msg.role == 'assistant' -%} |
| <|im_start|>assistant |
| {%- if reasoning %} |
| <think> |
| {{ reasoning }} |
| </think> |
| |
| {%- elif '<think>' in content and '</think>' in content %} |
| {%- set parts = content.split('<think>', 1) -%} |
| {%- set think_parts = parts[1].split('</think>', 1) -%} |
| {%- set reasoning = think_parts[0] | trim -%} |
| {%- set content = (parts[0] + think_parts[1]) | trim -%} |
| <think> |
| {{ reasoning }} |
| </think> |
| |
| {%- endif -%} |
| {%- if content %} |
| {{ content }} |
| {%- endif -%} |
| {%- if msg.tool_calls -%} |
| {%- for tc in msg.tool_calls %} |
| {{ format_tool_call(tc) }} |
| {%- endfor -%} |
| {%- endif %} |
| <|im_end|> |
| |
| {%- elif msg.role == 'tool' -%} |
| <|im_start|>user |
| <tool_response> |
| {{ content }} |
| </tool_response> |
| <|im_end|> |
| |
| {%- elif msg.role == 'system' -%} |
| <|im_start|>system |
| {{ content }} |
| <|im_end|> |
| |
| {%- endif -%} |
| {%- endmacro -%} |
| |
| {%- if messages and messages[0].role == 'system' -%} |
| {%- if tools -%} |
| <|im_start|>system |
| {{ messages[0].content }} |
| |
| # Function Calling |
| |
| Available tools: |
| {%- for tool in tools %} |
| {{ tool | tojson }} |
| {%- endfor %} |
| |
| Usage: <tool_call>{"name": "func", "arguments": {...}}</tool_call> |
| <|im_end|> |
| {%- else -%} |
| {{ render_message(messages[0]) }} |
| {%- endif -%} |
| {%- set msg_start = 1 -%} |
| {%- else -%} |
| {%- set msg_start = 0 -%} |
| {%- if tools -%} |
| <|im_start|>system |
| # Function Calling |
| |
| Available tools: |
| {%- for tool in tools %} |
| {{ tool | tojson }} |
| {%- endfor %} |
| |
| Usage: <tool_call>{"name": "func", "arguments": {...}}</tool_call> |
| <|im_end|> |
| {%- endif -%} |
| {%- endif -%} |
| |
| {%- for msg in messages[msg_start:] -%} |
| {{ render_message(msg) }} |
| {%- endfor -%} |
| |
| {%- if add_generation_prompt -%} |
| <|im_start|>assistant |
| <think> |
| {%- endif -%} |
| |