Sub topic 4
Keeping format and wording consistent
This chapter assumes you know how a prompt produces a completion, can read short Python, and know the system, user, and assistant roles in chat prompts. It builds on the idea that a few-shot prompt is an instruction followed by input and output examples, and on how a single example is built from input, output, and delimiters.
Why consistency matters
A model reading a few-shot prompt predicts the most likely continuation of the text. It treats everything the examples share as part of the task. That includes the label names, the capitalization, the punctuation, the spacing, and the length of the answers.
The model can't tell which differences between examples you meant and which were accidents. If one example answers positive and another answers Positive., the model sees two valid patterns and may produce either. If every example ends with a single lowercase word, the model will very likely do the same. Consistency removes guesswork, so the model spends its attention on the real task.
Inconsistency has two costs:
- Unstable output. The same prompt returns different formats from one call to the next, which breaks any code that parses the answer.
- Wrong signals. A pattern you never intended, such as "long reviews are negative," can enter the prompt through an accidental difference.
What has to stay the same
Treat the examples as rows generated from one template. Everything outside the slots for the input and the output should be identical.
| Element | Keep identical | Typical slip |
|---|---|---|
| Field labels | `Review:` and `Sentiment:` in every example | `Review:` in one, `Text:` in another |
| Label vocabulary | The same fixed set of answers | `negative`, `Negative`, `bad` |
| Casing and punctuation | Same case, same ending | `positive` vs. `Positive.` |
| Whitespace | Same blank lines between examples, same space after the colon | A double blank line in one place |
| Field order | Input always before output | Output first in one example |
| Output shape | Same length and structure | One word in one example, a full sentence in another |
| Instruction wording | Names the same labels the examples use | Instruction says "positive/negative"; examples use "good/bad" |
A broken prompt and its repair
This prompt has five inconsistencies. Try to find them before reading on.
Classify the sentiment of each review as positive, negative, or neutral.
Review: The battery lasts all day and charging is fast.
Sentiment: Positive
Text: It stopped working after a week.
Label: negative.
Review: The package arrived on Tuesday.
Sentiment - neutral
Review: The screen is bright but the speakers are weak.
Sentiment:The problems are:
- The first answer is capitalized and the others are not.
- The second example uses
Text:andLabel:instead ofReview:andSentiment:. - The second answer ends with a period.
- The third example uses a dash instead of a colon.
- Two blank lines precede the last entry, while the others have one.
The repaired version uses one template everywhere:
Classify the sentiment of each review as positive, negative, or neutral.
Review: The battery lasts all day and charging is fast.
Sentiment: positive
Review: It stopped working after a week.
Sentiment: negative
Review: The package arrived on Tuesday.
Sentiment: neutral
Review: The screen is bright but the speakers are weak.
Sentiment:Generate examples from one template
Typing examples by hand invites small slips. A safer approach is to keep examples as data and render them with a single function. Every example then goes through the same code path, so the format cannot drift.
ALLOWED_LABELS = {"positive", "negative", "neutral"}
INSTRUCTION = "Classify the sentiment of each review as positive, negative, or neutral."
def render_example(text, label):
return f"Review: {text}\nSentiment: {label}"
def render_query(text):
return f"Review: {text}\nSentiment:"
def validate(examples):
problems = []
for i, (text, label) in enumerate(examples):
if label not in ALLOWED_LABELS:
problems.append(f"example {i}: label {label!r} is not in the allowed set")
if text != text.strip():
problems.append(f"example {i}: text has leading or trailing whitespace")
if "\n" in text:
problems.append(f"example {i}: text contains a newline")
if "Review:" in text or "Sentiment:" in text:
problems.append(f"example {i}: text contains a delimiter")
return problems
def build_prompt(examples, query):
problems = validate(examples)
if problems:
raise ValueError("; ".join(problems))
blocks = [INSTRUCTION]
blocks += [render_example(text, label) for text, label in examples]
blocks.append(render_query(query))
return "\n\n".join(blocks)
examples = [
("The battery lasts all day and charging is fast.", "positive"),
("It stopped working after a week.", "negative"),
("The package arrived on Tuesday.", "neutral"),
]
print(build_prompt(examples, "The screen is bright but the speakers are weak."))
bad = examples + [("Great value for the price.", "Positive")]
try:
build_prompt(bad, "Fine.")
except ValueError as error:
print("Rejected:", error)The script prints the repaired prompt, then rejects the extra example because Positive is not in the allowed set. The same idea works for any task. Define the allowed outputs in one place, render all examples through one function, and fail loudly when data breaks the rules.
The unfinished final entry
The last entry is the one the model completes, so it must match the examples exactly up to the point where the answer starts. Three details matter here.
- Stop at the same place. The final entry ends right after
Sentiment:. The examples have a space after the colon before the label. Leaving the space off the final entry is deliberate. Many tokenizers attach the leading space to the next word, so a prompt that ends in a space can push the model toward an unnatural token. Most APIs behave better when the prompt ends at the colon. - Expect the pattern to continue. A model completing a raw text prompt may keep going and invent a new
Review:entry after answering. Set a stop sequence such as a newline, or"\n\nReview:", or limit the maximum output tokens. You can also strip the output after the first line. - Normalize before you compare. Even with a consistent prompt, trim whitespace and lowercase the output before checking it against your label set.
Delimiters inside the data
Your template is only a reliable boundary if the data cannot imitate it. A review that contains the text Sentiment: positive makes the structure ambiguous, and the model may follow the text instead of the template. This is also a prompt-injection risk when the inputs come from users.
The validator above rejects examples that contain the delimiters. For the query, which you can't always control, you have three options:
- Choose delimiters that are unlikely to appear, such as
### REVIEWor XML-style tags like<review>...</review>. - Remove or escape the delimiter strings in the query before building the prompt.
- Wrap the text in a quoting convention, such as triple quotes, in every example and in the query.
Whichever you pick, apply it to every example and to the query.
Instruction and examples must agree
The instruction and the examples are two descriptions of the same task. When they disagree, the model has to choose, and it often follows the examples.
- If the instruction says "answer with one word" and one example gives a sentence, expect sentences.
- If the instruction lists
positive, negative, neutraland the examples usegood, bad, okay, you will see a mix of both. - If the instruction says to answer in JSON and the examples show plain text, the examples usually win.
After you edit one, re-read the other. When you rename a label, change it in the instruction, the examples, the validator, and the evaluation code at once. Keeping the label set in a single constant, as ALLOWED_LABELS does above, makes this easier.
Consistency in chat messages
In a chat prompt the roles carry some of the structure, but the same rules apply to the content. Every assistant turn in the examples should look exactly like the reply you want. The assistant turns should have the same casing, no extra punctuation, and no leading phrases such as "Sure!" or "The sentiment is". A user turn should contain only the input in the same shape as the real query. Don't add Review: to the examples and leave it off the query, or the reverse.
When to vary on purpose
Consistency applies to format, not to content. The inputs should differ in length, topic, and difficulty, and the examples should cover different labels. Deliberately varied inputs under a fixed format teach the model the task and not a surface trick. Later chapters on choosing examples, order, and label balance cover this variation.
One exception is a task whose output format depends on the input. For example, a refusal may be a fixed sentence while normal answers are labels. In that case each branch should have its own consistent pattern, and each pattern should appear in more than one example.
A checklist before you run the prompt
- Print the final prompt and read it as raw text, including blank lines.
- Confirm that every example uses the same field labels, in the same order.
- Confirm that every answer is drawn from one allowed set, with one casing and one ending.
- Confirm that the instruction names the same labels as the examples.
- Confirm that the final entry stops at the same point as the examples, without a trailing space.
- Set a stop sequence or output limit, and normalize the output before you compare it.
Exercise
A few-shot prompt for extracting a city from a sentence has four examples. Three answer with just the city name, for example Paris. The fourth answers The city is Paris. The instruction says "Reply with only the city name." In testing, about one reply in four comes back as a full sentence. What is the likely cause, and how would you fix it?
Show answer
The fourth example is inconsistent with both the other examples and the instruction. The model sees two output patterns and sometimes picks the sentence form. Change the fourth answer to just Paris, and render all examples through one template function. Then check that the output matches the allowed format after trimming whitespace. A validator that rejects answers containing more than one word would have caught the problem.
Exercise
Your final query in a raw-text prompt is Review: Great phone.\nSentiment: with a trailing space after the colon, while the examples show Sentiment: positive. Why might this cause trouble, and what should you change?
Show answer
Many tokenizers attach the leading space to the following word, so ending the prompt with a space can push the model toward an unnatural token or an unexpected format. End the final entry at Sentiment: with no trailing space so the model writes the space and the label itself. Also set a stop sequence so it doesn't continue with a new Review: entry.