1{% macro render_content(msg) -%}
2 {%- set c = msg.get('content') -%}
3 {%- if c is string -%}
4 {{ c }}
5 {%- elif c is not none -%}
6 {% for content in c -%}
7 {% if content['type'] == 'image' or 'image' in content or 'image_url' in content -%}
8 <|media_start|>image<|media_content|><|media_pad|><|media_end|>
9 {% else -%}
10 {{ content['text'] }}
11 {%- endif -%}
12 {%- endfor -%}
13 {%- endif -%}
14{%- endmacro %}
15
16{%- set tool_response_queue = namespace(ids=[]) -%}
17{%- set tool_call_counter = namespace(value=0) -%}
18
19{%- if tools -%}
20 <|im_system|>tool_declare<|im_middle|>{{ tools | tojson }}<|im_end|>
21{%- endif -%}
22{% for message in messages %}
23 {%- if loop.first and messages[0]['role'] != 'system' -%}
24 <|im_system|>system<|im_middle|>You are Kimi, an AI assistant created by Moonshot AI.<|im_end|>
25 {% endif %}
26
27 {%- set role_name = message.get('name') or message['role'] -%}
28 {%- if message['role'] == 'user' -%}
29 <|im_user|>{{role_name}}<|im_middle|>
30 {%- elif message['role'] == 'assistant' -%}
31 <|im_assistant|>{{role_name}}<|im_middle|>
32 {%- else -%}
33 <|im_system|>{{role_name}}<|im_middle|>
34 {%- endif -%}
35
36 {%- if message['role'] == 'assistant' and message.get('tool_calls') -%}
37 {{render_content(message)}}<|tool_calls_section_begin|>
38 {%- for tool_call in message['tool_calls'] -%}
39 {%- set formatted_id = 'functions.' + tool_call['function']['name'] + ':' + (tool_call_counter.value | string) -%}
40 {%- set tool_call_counter.value = tool_call_counter.value + 1 -%}
41 {%- set _ = tool_response_queue.ids.append(formatted_id) -%}
42 <|tool_call_begin|>{{ formatted_id }}<|tool_call_argument_begin|>{% if tool_call['function']['arguments'] is string %}{{ tool_call['function']['arguments'] }}{% else %}{{ tool_call['function']['arguments'] | tojson }}{% endif %}<|tool_call_end|>
43 {%- endfor -%}
44 <|tool_calls_section_end|>
45 {%- elif message['role'] == 'tool' -%}
46 {%- if tool_response_queue.ids -%}
47 {%- set tool_call_id = tool_response_queue.ids.pop(0) -%}
48 {%- else -%}
49 {%- set tool_call_id = 'functions.' + message.get('name', 'unknown') + ':' + (tool_call_counter.value | string) -%}
50 {%- endif -%}
51 ## Return of {{ tool_call_id }}
52{{render_content(message)}}
53 {%- elif message['content'] is not none -%}
54 {{render_content(message)}}
55 {%- endif -%}
56 <|im_end|>
57{%- endfor -%}
58{%- if add_generation_prompt -%}
59 <|im_assistant|>assistant<|im_middle|>
60{%- endif -%}