From 01029165ccb32c90a3079947d76a1ff0d49febff Mon Sep 17 00:00:00 2001 From: Javier de Jesus Date: Mon, 22 Jun 2026 00:02:50 +0000 Subject: [PATCH] fix: avoid ENAMETOOLONG when chat_template is an inline jinja string A long literal chat_template made the .jinja resource lookup build a path whose final component exceeds NAME_MAX, so .is_file() raised OSError(ENAMETOOLONG) instead of returning False. Only attempt the template-name lookup when chat_template looks like a bare name, falling through to treat the value as an inline template otherwise. --- mergekit/merge.py | 13 +++++++++---- tests/test_chat_template.py | 24 ++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/mergekit/merge.py b/mergekit/merge.py index 5c3a7ea4..4f24caff 100644 --- a/mergekit/merge.py +++ b/mergekit/merge.py @@ -186,10 +186,15 @@ def _set_chat_template( LOG.info(f"Auto-selected chat template: {chat_template}") elif ( - t := importlib.resources.files(chat_templates).joinpath( - chat_template + ".jinja" - ) - ).is_file(): + len(chat_template) < 256 + and "\n" not in chat_template + and "{" not in chat_template + and ( + t := importlib.resources.files(chat_templates).joinpath( + chat_template + ".jinja" + ) + ).is_file() + ): chat_template = t.read_text() elif len(chat_template) < 20 or "{" not in chat_template: diff --git a/tests/test_chat_template.py b/tests/test_chat_template.py index a5e98d14..bdc1e083 100644 --- a/tests/test_chat_template.py +++ b/tests/test_chat_template.py @@ -62,3 +62,27 @@ def test_template_literal_jinja(self, model_base, model_b): config, validate=lambda p: check_chat_template(p, "{{messages[0]['content']}}"), ) + + def test_template_long_literal_jinja(self, model_base, model_b): + template = ( + "{% for message in messages %}" + + "{{ message['role'] }}: {{ message['content'] }}\n" + + "{% endfor %}" + + "{# " + + "x" * 300 + + " #}" + ) + config = MergeConfiguration( + merge_method="linear", + models=[ + InputModelDefinition(model=model_base, parameters={"weight": 0.5}), + InputModelDefinition(model=model_b, parameters={"weight": 0.5}), + ], + base_model=model_base, + dtype="bfloat16", + chat_template=template, + ) + run_and_check_merge( + config, + validate=lambda p: check_chat_template(p, "x" * 300), + )