Kimi-K2-Instruct.jinja 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. {%- set tool_response_queue = namespace(ids=[]) -%}
  16. {%- set tool_call_counter = namespace(value=0) -%}
  17. {%- if tools -%}
  18. <|im_system|>tool_declare<|im_middle|>{{ tools | tojson }}<|im_end|>
  19. {%- endif -%}
  20. {% for message in messages %}
  21. {%- if loop.first and messages[0]['role'] != 'system' -%}
  22. <|im_system|>system<|im_middle|>You are Kimi, an AI assistant created by Moonshot AI.<|im_end|>
  23. {% endif %}
  24. {%- set role_name = message.get('name') or message['role'] -%}
  25. {%- if message['role'] == 'user' -%}
  26. <|im_user|>{{role_name}}<|im_middle|>
  27. {%- elif message['role'] == 'assistant' -%}
  28. <|im_assistant|>{{role_name}}<|im_middle|>
  29. {%- else -%}
  30. <|im_system|>{{role_name}}<|im_middle|>
  31. {%- endif -%}
  32. {%- if message['role'] == 'assistant' and message.get('tool_calls') -%}
  33. {{render_content(message)}}<|tool_calls_section_begin|>
  34. {%- for tool_call in message['tool_calls'] -%}
  35. {%- set formatted_id = 'functions.' + tool_call['function']['name'] + ':' + (tool_call_counter.value | string) -%}
  36. {%- set tool_call_counter.value = tool_call_counter.value + 1 -%}
  37. {%- set _ = tool_response_queue.ids.append(formatted_id) -%}
  38. <|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|>
  39. {%- endfor -%}
  40. <|tool_calls_section_end|>
  41. {%- elif message['role'] == 'tool' -%}
  42. {%- if tool_response_queue.ids -%}
  43. {%- set tool_call_id = tool_response_queue.ids.pop(0) -%}
  44. {%- else -%}
  45. {%- set tool_call_id = 'functions.' + message.get('name', 'unknown') + ':' + (tool_call_counter.value | string) -%}
  46. {%- endif -%}
  47. ## Return of {{ tool_call_id }}
  48. {{render_content(message)}}
  49. {%- elif message['content'] is not none -%}
  50. {{render_content(message)}}
  51. {%- endif -%}
  52. <|im_end|>
  53. {%- endfor -%}
  54. {%- if add_generation_prompt -%}
  55. <|im_assistant|>assistant<|im_middle|>
  56. {%- endif -%}