{"record":{"id":"5496fc932aeac7c1","repo":"BerriAI/litellm","slug":"error-rendering-template-e","errorCode":null,"errorMessage":"Error rendering template - {e}","messagePattern":"Error rendering template - (.+?)","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"litellm/litellm_core_utils/prompt_templates/factory.py","lineNumber":441,"sourceCode":"                    add_generation_prompt=True,\n                )\n            except Exception as e:\n                if \"Conversation roles must alternate user/assistant\" in str(e):\n                    # reformat messages to ensure user/assistant are alternating\n                    new_messages: Final = []\n                    for i in range(len(reformatted_messages) - 1):\n                        new_messages.append(reformatted_messages[i])\n                        if reformatted_messages[i][\"role\"] == reformatted_messages[i + 1][\"role\"]:\n                            if reformatted_messages[i][\"role\"] == \"user\":\n                                new_messages.append({\"role\": \"assistant\", \"content\": \"\"})\n                            else:\n                                new_messages.append({\"role\": \"user\", \"content\": \"\"})\n                    new_messages.append(reformatted_messages[-1])\n                    rendered_text = template.render(bos_token=bos_token, eos_token=eos_token, messages=new_messages)\n\n        return rendered_text\n    except Exception as e:\n        raise Exception(f\"Error rendering template - {e}\")  # don't use verbose_logger.exception, if exception is raised\n\n\nasync def _afetch_and_extract_template(\n    model: str, chat_template: Any | None, get_config_fn, get_template_fn\n) -> tuple[str, str, str]:\n    \"\"\"\n    Async version: Fetch template and tokens from HuggingFace.\n\n    Returns: (chat_template, bos_token, eos_token)\n    \"\"\"\n    from litellm.litellm_core_utils.prompt_templates.huggingface_template_handler import (\n        _extract_token_value,\n    )\n\n    bos_token = \"\"\n    eos_token = \"\"\n\n    if chat_template is None:","sourceCodeStart":423,"sourceCodeEnd":459,"githubUrl":"https://github.com/BerriAI/litellm/blob/77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8/litellm/litellm_core_utils/prompt_templates/factory.py#L423-L459","documentation":"litellm renders the HuggingFace chat template with Jinja2 and wraps any render failure in this generic message; the '{e}' suffix carries the actual Jinja2 error (undefined variable, syntax error, unknown filter, bad message shape). It deliberately avoids verbose logging so the exception propagates to the caller.","triggerScenarios":"Passing a custom chat_template with invalid Jinja2 syntax; a template referencing variables absent from the rendered context (e.g. expecting 'tools' when none are passed); message dicts whose keys the template accesses (message['content'] on None) are missing.","commonSituations":"Using community or hand-modified Jinja chat templates; template/tokenizer version drift after a model repo update; rendering a template designed for a different message schema.","solutions":["Read the wrapped exception text to find the concrete Jinja2 cause","Reproduce the render standalone with jinja2.Template(...).render(messages=sample, bos_token=..., eos_token=...) and fix the template","Guard template variables with Jinja defaults ({{ message['content'] or '' }})","Fall back to the model repo's stock template instead of a modified one"],"exampleFix":"# before: custom template referencing an undefined variable raises\nresp = litellm.completion(model=\"huggingface/org/model\", messages=messages,\n                         chat_template=\"{% for m in messages %}{{ m['undefined_key'] }}{% endfor %}\")\n\n# after: guard the variable\nresp = litellm.completion(model=\"huggingface/org/model\", messages=messages,\n                         chat_template=\"{% for m in messages %}{{ m['content'] or '' }}{% endfor %}\")","handlingStrategy":"try-catch","validationCode":"from jinja2 import Template\n\ndef template_renders(chat_template: str, sample_messages: list[dict]) -> tuple[bool, str]:\n    try:\n        Template(chat_template).render(\n            bos_token=\"<s>\", eos_token=\"</s>\", messages=sample_messages\n        )\n        return True, \"\"\n    except Exception as e:\n        return False, str(e)\n\n# check custom templates in CI with representative messages before deploying","typeGuard":null,"tryCatchPattern":"try:\n    resp = litellm.completion(model=model, messages=messages, chat_template=custom_template)\nexcept Exception as e:\n    if str(e).startswith(\"Error rendering template\"):\n        # the suffix carries the Jinja2 cause; fall back to the repo's stock template\n        resp = litellm.completion(model=model, messages=messages)\n    else:\n        raise","preventionTips":["Smoke-test custom Jinja templates with jinja2.Template against sample messages in CI","Guard message key access inside templates: {{ m['content'] or '' }}","Pin model repo revisions so templates do not drift under you","Keep the original exception text - it names the exact Jinja2 problem"],"tags":["jinja2","chat-template","huggingface","rendering"],"backgroundTag":"template-render-failed","analyzedSha":"77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8","analyzedAt":"2026-08-18T11:44:31.656Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}