{{- if or .System (eq $firstMsg.Role "system") (eq $firstMsg.Role "developer") }}
{{- "<|im_start|>system\n" }}
{{- if .System }}{{ .System }}
{{- else if eq $firstMsg.Role "developer" }}{{ $firstMsg.Content }}
{{- else if eq $firstMsg.Role "system" }}{{ $firstMsg.Content }}
{{- end }}
{{- if .Tools }}
{{- "\n\n# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
{{- range .Tools }}{{ "\n" }}{{ . }}{{- end }}
{{- "\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n</function>\n</tool_call>" }}
{{- end }}
{{- "<|im_end|>\n" }}
{{- end }}
{{- range $i, $m := .Messages }}
{{- $content := .Content }}
{{- $role := .Role }}
{{- /* Apply Role Mapping Fix */ -}}
{{- if eq $role "developer" }}
{{- if eq $i 0 }}{{ $role = "system" }}{{ else }}{{ $role = "user" }}{{ end }}
{{- end }}
{{- /* Fallback for unexpected roles to prevent 500s */ -}}
{{- if and (ne $role "system") (ne $role "user") (ne $role "assistant") (ne $role "tool") }}