Sub topic 1
What a Prompt Is Made Of
Prerequisites
Assume you can call a large language model from Python, read basic YAML or JSON, and use Git. A prompt is the complete input sent to a model. It usually contains instructions, context, and a user request. Keeping these parts separate makes prompts easier to test and change.
Hard-coded prompt strings become difficult to maintain when several functions repeat the same instructions or embed changing data directly in long strings. A template keeps fixed text in one place and marks changing values with named variables.
From Strings to Templates with Variables
Python’s string.Template uses a dollar sign followed by a variable name:
from string import Template
template = Template(
"Summarize the following text in $style style:\n\n$text"
)
prompt = template.substitute(
style="concise",
text="Prompt templates separate fixed instructions from variable input."
)
print(prompt)The template is reusable. Each call supplies different values without rebuilding the instruction text. Named variables are clearer than positional values because their purpose is visible.
Rendering Templates and Validating Inputs
Rendering means replacing template variables with actual values. Validate the input names before rendering so spelling mistakes fail early.
from string import Template
REQUIRED = {"style", "text"}
def render(template_text, values):
missing = REQUIRED - values.keys()
extra = values.keys() - REQUIRED
if missing or extra:
raise ValueError(
f"missing={sorted(missing)} extra={sorted(extra)}"
)
return Template(template_text).substitute(values)Validation should also check value types, lengths, and allowed choices. For example, accept only known styles and limit the size of supplied text.
Handling Untrusted Input in Templates
User input is data, not an instruction from your application. Put it in a clearly marked section and state how the model should treat it. Do not let users submit a complete template unless that is an intentional feature. Escaping can prevent formatting problems, but it cannot reliably prevent prompt injection.
Exercise
Why should a renderer reject unexpected variable names?
Show answer
Unexpected names often indicate a typo, stale template, or attempt to change the prompt structure, so rejecting them makes the failure visible before the model call.