BerriAI/litellm · error · Exception

Error rendering template

Error message

Error rendering template - {e}

What it means

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.

Solutions

  1. Read the wrapped exception text to find the concrete Jinja2 cause
  2. Reproduce the render standalone with jinja2.Template(...).render(messages=sample, bos_token=..., eos_token=...) and fix the template
  3. Guard template variables with Jinja defaults ({{ message['content'] or '' }})
  4. Fall back to the model repo's stock template instead of a modified one

Example fix

# before: custom template referencing an undefined variable raises
resp = litellm.completion(model="huggingface/org/model", messages=messages,
                         chat_template="{% for m in messages %}{{ m['undefined_key'] }}{% endfor %}")

# after: guard the variable
resp = litellm.completion(model="huggingface/org/model", messages=messages,
                         chat_template="{% for m in messages %}{{ m['content'] or '' }}{% endfor %}")
Defensive patterns

Strategy: try-catch

Validate before calling

from jinja2 import Template

def template_renders(chat_template: str, sample_messages: list[dict]) -> tuple[bool, str]:
    try:
        Template(chat_template).render(
            bos_token="<s>", eos_token="</s>", messages=sample_messages
        )
        return True, ""
    except Exception as e:
        return False, str(e)

# check custom templates in CI with representative messages before deploying

Try / catch

try:
    resp = litellm.completion(model=model, messages=messages, chat_template=custom_template)
except Exception as e:
    if str(e).startswith("Error rendering template"):
        # the suffix carries the Jinja2 cause; fall back to the repo's stock template
        resp = litellm.completion(model=model, messages=messages)
    else:
        raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of BerriAI/litellm@77b7c6c40c (2026-08-18). Data as JSON: /api/errors/5496fc932aeac7c1. Report an issue: GitHub.

Appendix: source

Thrown at litellm/litellm_core_utils/prompt_templates/factory.py:441

                    add_generation_prompt=True,
                )
            except Exception as e:
                if "Conversation roles must alternate user/assistant" in str(e):
                    # reformat messages to ensure user/assistant are alternating
                    new_messages: Final = []
                    for i in range(len(reformatted_messages) - 1):
                        new_messages.append(reformatted_messages[i])
                        if reformatted_messages[i]["role"] == reformatted_messages[i + 1]["role"]:
                            if reformatted_messages[i]["role"] == "user":
                                new_messages.append({"role": "assistant", "content": ""})
                            else:
                                new_messages.append({"role": "user", "content": ""})
                    new_messages.append(reformatted_messages[-1])
                    rendered_text = template.render(bos_token=bos_token, eos_token=eos_token, messages=new_messages)

        return rendered_text
    except Exception as e:
        raise Exception(f"Error rendering template - {e}")  # don't use verbose_logger.exception, if exception is raised


async def _afetch_and_extract_template(
    model: str, chat_template: Any | None, get_config_fn, get_template_fn
) -> tuple[str, str, str]:
    """
    Async version: Fetch template and tokens from HuggingFace.

    Returns: (chat_template, bos_token, eos_token)
    """
    from litellm.litellm_core_utils.prompt_templates.huggingface_template_handler import (
        _extract_token_value,
    )

    bos_token = ""
    eos_token = ""

    if chat_template is None:

View on GitHub (pinned to 77b7c6c40c)