{"record":{"id":"fe3595200b53d72d","repo":"microsoft/graphrag","slug":"missing-key-in-context-for-template-template-nam","errorCode":null,"errorMessage":"Missing key in context for template '{template_name}': {e.message}","messagePattern":"Missing key in context for template '(.+?)': (.+?)","errorType":"exception","errorClass":"KeyError","httpStatus":null,"severity":"error","filePath":"packages/graphrag-llm/graphrag_llm/templating/jinja_template_engine.py","lineNumber":47,"sourceCode":"        \"\"\"\n        self._templates = {}\n        self._template_manager = template_manager\n\n    def render(self, template_name: str, context: dict[str, Any]) -> str:\n        \"\"\"Render a template with the given context.\"\"\"\n        jinja_template = self._templates.get(template_name)\n        if jinja_template is None:\n            template_contents = self._template_manager.get(template_name)\n            if template_contents is None:\n                msg = f\"Template '{template_name}' not found.\"\n                raise KeyError(msg)\n            jinja_template = Template(template_contents, undefined=StrictUndefined)\n            self._templates[template_name] = jinja_template\n        try:\n            return jinja_template.render(**context)\n        except UndefinedError as e:\n            msg = f\"Missing key in context for template '{template_name}': {e.message}\"\n            raise KeyError(msg) from e\n        except Exception as e:\n            msg = f\"Error rendering template '{template_name}': {e!s}\"\n            raise RuntimeError(msg) from e\n\n    @property\n    def template_manager(self) -> \"TemplateManager\":\n        \"\"\"Template manager associated with this engine.\"\"\"\n        return self._template_manager\n","sourceCodeStart":29,"sourceCodeEnd":56,"githubUrl":"https://github.com/microsoft/graphrag/blob/f40e9a26ce62ba0b3fef8837d24aafdcc6e6c704/packages/graphrag-llm/graphrag_llm/templating/jinja_template_engine.py#L29-L56","documentation":"JinjaTemplateEngine.render raises this KeyError when the template compiles fine but references a variable that is not supplied in the render context. Templates are compiled with StrictUndefined, so any missing key aborts rendering instead of silently rendering an empty string.","triggerScenarios":"Calling render(template_name, context) where the template references a variable (e.g. {{ document }}) that is absent from the context dict/kwargs. Adding new variables to a template without updating all callers triggers it.","commonSituations":"Template updated to require a new field but caller code not updated; optional context keys not defaulted; refactors renaming context keys.","solutions":["Read e.message to identify the missing variable name and add it to the context","Keep template variable contract in sync with callers; update both together","Default optional variables in the caller (ctx.setdefault(...)) or make the template use {{ var | default(...) }} instead of bare references","Add a render smoke-test per template with the full expected context"],"exampleFix":"# before\nengine.render(\"summarize\", {\"text\": doc})  # template uses {{ document }}\n\n# after\nengine.render(\"summarize\", {\"document\": doc})","handlingStrategy":"try-catch","validationCode":"from jinja2 import Environment\nfrom jinja2.meta import find_undeclared_variables\nimport ast\n\n# Inspect template source for required vars before render\nsrc = engine.template_manager.get(name)\nast.parse(\"\", mode=\"eval\") if False else None\nrequired = find_undeclared_variables(Environment().parse(src))\nmissing = required - set(context)\nif missing:\n    raise KeyError(f\"Missing context keys: {missing}\")","typeGuard":"def has_all_context_keys(src: str, context: dict) -> bool:\n    from jinja2 import Environment\n    from jinja2.meta import find_undeclared_variables\n    return not (find_undeclared_variables(Environment().parse(src)) - set(context))","tryCatchPattern":"try:\n    out = engine.render(name, ctx)\nexcept KeyError as e:\n    if \"Missing key in context\" in str(e):\n        ctx.setdefault(str(e).split(\": \")[-1], \"\")  # or fix caller data\n        out = engine.render(name, ctx)\n    else:\n        raise","preventionTips":["Keep template variable contracts in sync with callers via tests","Use setdefault/frozen defaults for optional context keys","Prefer {% if var %} or |default() in templates for optional fields"],"tags":["graphrag-llm","templating","jinja2","missing-variable"],"backgroundTag":"jinja-undefined-variable","analyzedSha":"f40e9a26ce62ba0b3fef8837d24aafdcc6e6c704","analyzedAt":"2026-08-27T11:16:29.677Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}