How can a prompt builder detect a missing variable before sending a request?

Template.substitute replaces placeholders from a mapping and raises KeyError when a required key is missing.

Python example and interpretation

A template expecting label and text identifies the missing text field when supplied only a label. Having every field does not validate the field contents.

from string import Template
try: Template('$label = $text').substitute(label='topic')
except KeyError as exc: missing=exc.args[0]
missing

Result 'text'

中文

提示词模板漏传变量时,如何在发送前发现?

Template.substitute 对占位符进行映射替换,缺失的必要键会引发 KeyError。

Python 算例与适用条件

模板需要 label 和 text,只给 label 就能得到缺项名称。字段齐全仍不代表内容合法,还需遵守输入契约。

from string import Template
try: Template('$label = $text').substitute(label='topic')
except KeyError as exc: missing=exc.args[0]
missing

结果 'text'

References / 参考来源

Keep reading / 继续阅读