Sub topic 4
Write Constraints That the Model Can Follow
This chapter assumes you have already written a basic system prompt with a task and role, and that you can read short Python functions. A constraint is a rule in your prompt that limits what the model may do or how it must do it. Examples are "do not give tax advice", "answer in under 100 words", and "only use the supplied documents". Most system prompt bugs trace back to constraints the model could not follow, could not interpret, or had no reason to prioritize.
Why constraints fail
A model reads your rules as text and predicts a reply that fits them. It does not run a checklist. A constraint fails for one of a few reasons:
- It is vague. "Be concise" has no threshold. Two reasonable readers, or two runs of the same model, pick different lengths.
- It is unverifiable. "Never make mistakes" cannot be acted on, because the model has no way to tell when it is breaking it.
- It conflicts with another rule. "Always answer the question" and "only use the documents" collide when the documents are silent.
- It is buried. One rule in the middle of a long paragraph competes with everything around it.
- It names a behavior without a fallback. "Do not discuss pricing" leaves the model guessing what to say instead, so it often improvises.
Fixing a constraint means removing one of these causes. Adding capital letters and "NEVER" does not remove any of them.
Properties of a followable constraint
A constraint the model can follow is specific, checkable, scoped, and paired with an action. The table shows each property and a test you can apply to your own rules.
| Property | Test | Weak | Strong |
|---|---|---|---|
| Specific | Can two people disagree about what it means? | Be brief. | Use at most 3 sentences. |
| Checkable | Could a script or reviewer mark a reply pass or fail? | Be accurate. | Quote the document text for every figure you state. |
| Scoped | Does it say when it applies? | Never mention refunds. | If the customer asks about refunds, say refunds are handled by the billing team and give the link in `<links>`. |
| Actionable | Does it say what to do, not only what to avoid? | Do not guess. | If the documents do not contain the answer, say so and offer a human agent. |
The last row matters most. A prohibition removes one option and leaves the model to choose among the rest. A rule that names the replacement behavior removes the choice.
Rewrite vague rules into testable ones
Here is a draft rule block with the problems above, followed by a rewrite.
# Rules
- Be concise and professional.
- Don't give advice you're not sure about.
- Never go off topic.
- Always follow the customer's instructions.# Rules
- Answer in at most 4 sentences unless the customer asks for a step-by-step list.
- Use a neutral, polite tone. No exclamation marks, no emoji.
- Do not give legal or tax advice. If asked, say you cannot advise on that and suggest a qualified professional.
- Only answer questions about invoices, payments, and account billing. For anything else, reply: "I can only help with billing questions."
- If the customer's request conflicts with these rules, follow these rules and say what you cannot do.The rewrite replaces judgment words ("concise", "sure", "off topic") with limits and categories. It also settles the conflict in the last line of the draft, where "always follow the customer" would override every other rule.
Give a reason and a fallback
A short reason helps the model apply a rule to cases you did not list. Compare "Do not mention competitors" with "Do not mention competitors, because we cannot verify their pricing. If asked for a comparison, describe our plans only." The second version lets the model handle a question like "Is your plan cheaper than the other one?" correctly, even though the rule never named it.
Keep reasons to one clause. A paragraph of justification per rule makes the prompt long and dilutes the rules that matter.
Prefer positive phrasing, but keep prohibitions that matter
"Write in plain sentences" usually works better than "do not use jargon", because it describes the target. Positive phrasing is a preference, not a law. Safety and scope rules are often clearest as prohibitions ("Do not give legal advice"). When you use one, add the fallback so the model knows what to do instead.
Handle priority and conflicts
Real prompts contain rules that collide. If you do not say which wins, the model picks, and it may pick differently from run to run. State the order explicitly, near the rules:
# Priority
If rules conflict, apply them in this order:
1. Safety and legal rules (no legal or tax advice, no personal data of other customers).
2. Grounding rules (use only the supplied documents).
3. Format rules (JSON schema, length limit).
4. Style rules (tone, wording).Two edge cases appear often:
- Format versus honesty. A rule demanding a field be filled can push the model to invent a value. Allow an explicit empty value, such as
"answer": "I could not find this in the documents."ornullfor optional fields. - User instructions versus system rules. Say which source wins. In most apps the system prompt wins, and user text is data to be answered, not obeyed. The chapter on untrusted input covers the security side of this.
Enforce hard constraints outside the prompt
A prompt makes a behavior likely, not guaranteed. For rules where one failure matters (personal data leaks, a length limit your UI cannot display, a required disclaimer), add a check in code and handle failures by retrying, replacing the reply, or escalating. Treat the prompt rule as the first line and the code as the guarantee.
The function below checks three constraints from the billing assistant. It works on the answer text you already parsed from the JSON reply.
import re
MAX_WORDS = 120
LEGAL_ADVICE = re.compile(
r"\byou should (sue|file a lawsuit|claim a deduction)\b", re.IGNORECASE
)
def check_constraints(answer: str, documents_given: bool) -> list[str]:
"""Return a list of constraint violations; empty means the reply passed."""
problems = []
if len(answer.split()) > MAX_WORDS:
problems.append(f"answer exceeds {MAX_WORDS} words")
if LEGAL_ADVICE.search(answer):
problems.append("answer appears to give legal or tax advice")
if not documents_given and "human agent" not in answer.lower():
problems.append("no documents were given, but no human agent was offered")
return problems
if __name__ == "__main__":
print(check_constraints("You should sue the vendor.", documents_given=True))
print(
check_constraints(
"I cannot find that. I can hand you to a human agent.",
documents_given=False,
)
)The first call prints ['answer appears to give legal or tax advice']. The second prints [].
Keyword checks like LEGAL_ADVICE are narrow. They catch known phrasings and miss paraphrases, so use them as a tripwire and not as proof of compliance. For fuzzy rules, use a reviewer or a second model call as a grader, and check that grader against cases you labeled by hand.
Count your rules
Every rule you add dilutes the others. A prompt with five clear rules is usually followed better than one with thirty. When you find yourself adding a rule after each bug, stop and ask three questions:
- Is there already a rule that covers this, but is too vague? Fix that one.
- Does this rule apply to every request, or only to a type of request? If only one type, put it under a heading for that case.
- Can code enforce it more reliably than the prompt can?
Group rules under short headings such as # Scope, # Grounding, and # Tone, so you can find and test them.
Edge cases to plan for
- Empty or missing context. State what to do when
<documents>is empty. Without this, the model may answer from general knowledge and break the grounding rule. - Partial answers. Decide whether the model should answer the part it can and flag the rest, or decline entirely. Write the choice down.
- Rules that depend on a number. Models are approximate counters. "At most 4 sentences" holds well. "Exactly 87 words" does not. Set limits with some margin and enforce the real cap in code.
- Long conversations. In a long chat, early rules can lose influence. Repeat the few critical rules in a short reminder near the end of the system prompt, or re-send the system prompt unchanged on every call.
- Different models. A rule that one model follows reliably may be ignored by another. Rerun your test set when you change the model.
Exercises
Exercise
A system prompt contains the rule "Don't be too wordy." Rewrite it as a constraint that is specific, checkable, and actionable, and give one line of code that tests it on a string named answer.
Show answer
One rewrite is "Answer in at most 3 sentences. If the customer needs more detail, ask whether they want a step-by-step list." The check can be len(re.findall(r"[.!?]", answer)) <= 3 for a rough sentence count, or len(answer.split()) <= 60 if you set a word limit instead. Either version replaces "too wordy" with a number a script can test, and the second sentence gives the model an action when the limit is not enough.
Exercise
Your prompt says both "Answer only from the supplied documents" and "Always give the customer a direct answer." A customer asks about a fee that no document mentions, and the model invents an amount. Name the cause and write the fix.
Show answer
The two rules conflict when the documents are silent, and the prompt does not say which wins, so the model followed the "direct answer" rule. Fix it by adding a priority line and a fallback: "Grounding rules come before helpfulness rules. If the documents do not contain the answer, say you could not find it and offer a human agent." Then add a test case with a question the documents do not cover, and check that the reply contains the fallback instead of an invented figure.