Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Escape caller template text spliced into Jinja string literals (#7731)
Vineeth Sai Varikuntla90f5170d0aa2
diff --git a/tests/python/test_construct_chat_template_validation.py b/tests/python/test_construct_chat_template_validation.pyindex 1f73b6edf29..0202d99430b 100644--- a/tests/python/test_construct_chat_template_validation.py+++ b/tests/python/test_construct_chat_template_validation.py@@ -113,16 +113,21 @@ _SYSTEM_CHAT_TEMPLATE = ()-def _render(jinja_template, messages):+def _render(+ jinja_template,+ messages,+ add_generation_prompt = False,+ bos_token = "<s>",+):from jinja2.sandbox import ImmutableSandboxedEnvironmentenv = ImmutableSandboxedEnvironment()env.globals["raise_exception"] = lambda message: (_ for _ in ()).throw(RuntimeError(message))return env.from_string(jinja_template).render(messages = messages,- bos_token = "<s>",+ bos_token = bos_token,eos_token = "</s>",- add_generation_prompt = False,+ add_generation_prompt = add_generation_prompt,)@@ -238,3 +243,77 @@ def test_input_boundary_prefers_the_longest_eos_token():rendered_user_turn = _render(jinja_template, [{"role": "user", "content": "Hi"}])assert rendered_user_turn == "### User: Hi</s>extra"+++_APOSTROPHE_CHAT_TEMPLATE = (+ "{SYSTEM}\n"+ "### User's turn: {INPUT}\n### Bot's reply: {OUTPUT}</s>"+ "### User's turn: {INPUT}\n### Bot's reply: {OUTPUT}</s>"+)+++ "default_system_message",+ [+ "Answer the user's question.",+ r"Put the answer in \boxed{}.",+ r"Files live in C:\Users\me",+ # Windows CRLF: Jinja rewrites a raw \r to \n.+ "Answer briefly.\r\nBe polite.",+ ],+)+def test_quotes_and_backslashes_survive_into_the_jinja_template(default_system_message):+ """Template text is concatenated into Jinja `'...'` literals, so it has to be+ escaped on the way in. An apostrophe used to close the literal early+ (TemplateSyntaxError: expected token 'end of print statement'), and a backslash was+ read as a Jinja escape, so `\\boxed` silently became a backspace character and+ `C:\\Users` raised `truncated \\UXXXXXXXX escape`. Covers the system message and+ the instruction/response sections, which are spliced by three separate call sites."""+ _, jinja_template, _, _ = construct_chat_template(+ tokenizer = _SuccessFakeTokenizer(),+ chat_template = _APOSTROPHE_CHAT_TEMPLATE,+ default_system_message = default_system_message,+ extra_eos_tokens = ["</s>"],+ )++ rendered = _render(jinja_template, [{"role": "user", "content": "Hi"}])+ assert default_system_message in rendered+ assert "### User's turn: Hi" in rendered++ # The generation prompt uses its own literal, not process().+ prompted = _render(+ jinja_template,+ [{"role": "user", "content": "Hi"}],+ add_generation_prompt = True,+ )+ assert prompted.endswith("### Bot's reply: ")+++class _BosFakeTokenizer(_SuccessFakeTokenizer):+ """A bos_token carrying characters the Jinja escaper rewrites."""++ bos_token = "<s'\\a>"++ def __call__(self, text):+ # input_ids[0] == bos_token_id takes the BOS-handling branch.+ return SimpleNamespace(input_ids = [1])+++def test_bos_token_with_quote_or_backslash_is_not_emitted_twice():+ """The BOS is stripped from the system section so it is only rendered once, via+ `{{ bos_token }}`. Stripping it after process() had escaped the section left it+ unmatched, and the caller-system branch then emitted it a second time."""+ bos = _BosFakeTokenizer.bos_token+ _, jinja_template, _, _ = construct_chat_template(+ tokenizer = _BosFakeTokenizer(),+ chat_template = bos + _APOSTROPHE_CHAT_TEMPLATE,+ default_system_message = "Be helpful.",+ extra_eos_tokens = ["</s>"],+ )++ for messages in (+ [{"role": "user", "content": "Hi"}],+ [{"role": "system", "content": "Sysmsg"}, {"role": "user", "content": "Hi"}],+ ):+ rendered = _render(jinja_template, messages, bos_token = bos)+ assert rendered.count(bos) == 1, rendereddiff --git a/unsloth/chat_templates.py b/unsloth/chat_templates.pyindex 0c49b870334..c4c559a4139 100644--- a/unsloth/chat_templates.py+++ b/unsloth/chat_templates.py@@ -2617,7 +2617,15 @@ extra_eos_tokens = None,part + '\n\n' + ollama_eos# HF Jinja Chat template+ # Caller text is spliced into Jinja '...' literals, where a bare quote closes+ # the literal and a backslash is read as an escape, and \r is normalised to \n+ # before unescaping. Backslash first, else it re-escapes the ones added after.+ def escape_jinja_literal(text):+ return text.replace("\\", "\\\\").replace("'", "\\'").replace("\r", "\\r")+def process(part, which, content = "message['content']"):+ # Escape the literal pieces only; the placeholder becomes Jinja syntax below.+ part = which.join(escape_jinja_literal(piece) for piece in part.split(which))if part.endswith(which):part = "'" + part[:part.find(which)] + f"' + {content}"elif part.startswith(which):@@ -2640,11 +2648,14 @@ extra_eos_tokens = None,"{% endif %}"\"{% endfor %}"\"{% if add_generation_prompt %}"\- "{{ '" + output_part[:output_part.find("{OUTPUT}")] + "' }}"\+ "{{ '" + escape_jinja_literal(output_part[:output_part.find("{OUTPUT}")]) + "' }}"\"{% endif %}"# Now add system prompt to jinjaif len(system_part) != 0:+ # Strip the BOS while raw: an escaped bos_token no longer matches.+ if has_bos_token:+ system_part = system_part.replace(tokenizer.bos_token, "", 1)partial_system = process(system_part, "{SYSTEM}", "messages[0]['content']")partial_system = partial_system.replace("{SYSTEM}", "")@@ -2652,17 +2663,12 @@ extra_eos_tokens = None,if default_system_message is None:raise RuntimeError("Unsloth: Please specify a default system message!")- # Separate the BOS- if has_bos_token:- partial_system = partial_system.replace(tokenizer.bos_token, "", 1)- system_part = system_part .replace(tokenizer.bos_token, "", 1)-partial_system = \"{% if messages[0]['role'] == 'system' %}"\"{{ " + partial_system + " }}"\"{% set loop_messages = messages[1:] %}"if default_system_message is not None:- full_system = system_part.replace("{SYSTEM}", default_system_message)+ full_system = escape_jinja_literal(system_part.replace("{SYSTEM}", default_system_message))if "{SYSTEM}" in system_part:modelfile += '\nSYSTEM "' + default_system_message + '"'partial_system += "{% else %}"\