Kimi-K2-Instruct.jinja 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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=1) -%}
  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. {%- if tool_call['id'] is defined -%}
  36. {%- set formatted_id = tool_call['id'] -%}
  37. {%- else -%}
  38. {%- set formatted_id = 'functions.' + tool_call['function']['name'] + ':' + (tool_call_counter.value | string) -%}
  39. {%- set tool_call_counter.value = tool_call_counter.value + 1 -%}
  40. {%- endif -%}
  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 -%}