| {%- set image_count = namespace(value=0) %} |
| {%- set video_count = namespace(value=0) %} |
| {%- macro render_content(content, do_vision_count, is_system_content=false) %} |
| {%- if content is string %} |
| {{- content }} |
| {%- elif content is iterable and content is not mapping %} |
| {%- for item in content %} |
| {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} |
| {%- if is_system_content %} |
| {{- raise_exception('System message cannot contain images.') }} |
| {%- endif %} |
| {%- if do_vision_count %} |
| {%- set image_count.value = image_count.value + 1 %} |
| {%- endif %} |
| {%- if add_vision_id %} |
| {{- 'Picture ' ~ image_count.value ~ ': ' }} |
| {%- endif %} |
| {{- '<|vision_start|><|image_pad|><|vision_end|>' }} |
| {%- elif 'video' in item or item.type == 'video' %} |
| {%- if is_system_content %} |
| {{- raise_exception('System message cannot contain videos.') }} |
| {%- endif %} |
| {%- if do_vision_count %} |
| {%- set video_count.value = video_count.value + 1 %} |
| {%- endif %} |
| {%- if add_vision_id %} |
| {{- 'Video ' ~ video_count.value ~ ': ' }} |
| {%- endif %} |
| {{- '<|vision_start|><|video_pad|><|vision_end|>' }} |
| {%- elif 'text' in item %} |
| {{- item.text }} |
| {%- else %} |
| {{- raise_exception('Unexpected item type in content.') }} |
| {%- endif %} |
| {%- endfor %} |
| {%- elif content is none or content is undefined %} |
| {{- '' }} |
| {%- else %} |
| {{- raise_exception('Unexpected content type.') }} |
| {%- endif %} |
| {%- endmacro %} |
| {%- if not messages %} |
| {{- raise_exception('No messages provided.') }} |
| {%- endif %} |
| {%- if messages[0].role == 'system' %} |
| {%- set content = render_content(messages[0].content, false, true)|trim %} |
| {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} |
| {%- endif %} |
| {%- for message in messages %} |
| {%- set content = render_content(message.content, true)|trim %} |
| {%- if message.role == "system" %} |
| {%- if not loop.first %} |
| {{- raise_exception('System message must be at the beginning.') }} |
| {%- endif %} |
| {%- elif message.role == "user" %} |
| {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} |
| {%- elif message.role == "assistant" %} |
| {{- '<|im_start|>' + message.role + '\n' + content }} |
| {{- '<|im_end|>\n' }} |
| {%- else %} |
| {{- raise_exception('Unexpected message role.') }} |
| {%- endif %} |
| {%- endfor %} |
| {%- if add_generation_prompt %} |
| {{- '<|im_start|>assistant\n' }} |
| {%- endif %} |