{"record":{"id":"8a78141760b835ce","repo":"hiyouga/LlamaFactory","slug":"failed-to-inject-generation-into-chat-templa","errorCode":null,"errorMessage":"Failed to inject {% generation %} into chat template.","messagePattern":"Failed to inject (.+?) into chat template\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/llamafactory/train/megatron_bridge/dataset_export.py","lineNumber":76,"sourceCode":"            \"Cannot inject {% generation %} into chat template: \"\n            \"no `{% elif message['role'] == 'assistant' %}` block found.\"\n        )\n\n    body = match.group(2)\n    if _END_GENERATION_REGEX.search(body):\n        return chat_template\n\n    patched = (\n        chat_template[: match.start()]\n        + match.group(1)\n        + \"{% generation %}\"\n        + body\n        + \"{% endgeneration %}\"\n        + match.group(3)\n        + chat_template[match.end() :]\n    )\n    if not _GENERATION_REGEX.search(patched):\n        raise ValueError(\"Failed to inject {% generation %} into chat template.\")\n    return patched\n\n\ndef build_chat_template_with_generation(\n    tokenizer_path: str | None,\n    trust_remote_code: bool = False,\n    template_name: str | None = None,\n) -> str | None:\n    r\"\"\"Build a chat template that supports assistant-only loss masks.\n\n    Prefers the LLaMA-Factory registered template (same formatting as HF Trainer),\n    then falls back to patching the tokenizer's native chat template.\n    \"\"\"\n    if not tokenizer_path:\n        return None\n\n    try:\n        from transformers import AutoTokenizer","sourceCodeStart":58,"sourceCodeEnd":94,"githubUrl":"https://github.com/hiyouga/LlamaFactory/blob/f28afaf6355af515454dfb16c97d728307c93897/src/llamafactory/train/megatron_bridge/dataset_export.py#L58-L94","documentation":"Error \"Failed to inject {% generation %} into chat template.\" thrown in hiyouga/LlamaFactory.","triggerScenarios":"Thrown at src/llamafactory/train/megatron_bridge/dataset_export.py:76 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":["Verify the chat template after injection contains matching {% generation %} and {% endgeneration %} tags; fix any custom template syntax so the injected block is valid Jinja."],"exampleFix":"# wrap assistant content explicitly\n{% generation %}...{% endgeneration %}","handlingStrategy":null,"validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"f28afaf6355af515454dfb16c97d728307c93897","analyzedAt":"2026-08-14T21:57:28.298Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}