TechByteByByte

Constraints

How limits like word counts, allowed values, and scope boundaries improve reliability — and the real, easy-to-miss trade-off between too few constraints and too many.

#Prompt Engineering#AI#Constraints#Fundamentals#Beginner

Start with the real problem

A constraint is a limit the answer must follow, such as “use no more than 100 words” or “choose only HIGH, MEDIUM, or LOW.”

Constraints reduce the space of acceptable answers, but every extra rule competes for attention. The goal is the smallest set of rules that protects the real requirement.

goal + essential limits + priorities → narrower acceptable output

What you will learn

  • Classify length, scope, value, and safety constraints.
  • Resolve contradictory constraints.
  • Separate preferences from hard rules.
  • Enforce consequential limits in code.

How this connects to current AI systems

Provider models follow explicit constraints increasingly well, but application code must enforce permissions, budgets, and safety-critical rules that must never change.

1. Why This Module Exists

Module 2 introduced constraints as one of the six building blocks — rules the output must respect. This module goes deeper: what kinds of constraints exist, why they really improve reliability, and the real, easy-to-underestimate trade-off between too few constraints and too many.


2. The Idea, in Plain Language

A constraint is a rule the AI’s response has to follow — a limit on length, content, scope, or allowed values.

"Under 100 words."
"Only use these categories: Urgent, Normal, Low."
"Don't mention pricing."
"Stay strictly focused on the technical details, not the business
case."

Constraints don’t tell the AI what to say — they narrow down the space of acceptable answers, ruling certain things in or out.


3. Common Types of Constraints

Length:         "under 100 words", "exactly 3 bullet points"
Allowed values:    "only respond with Yes, No, or Unclear"
Scope:                "focus only on X, ignore Y"
Tone:                    "formal", "no slang"
Language:                  "respond only in Spanish"
Required content:            "must include a call-to-action"
Forbidden content:              "never mention competitor names"

Each type resolves a different kind of ambiguity — length constraints resolve “how much,” allowed-value constraints resolve “which specific options,” scope constraints resolve “what to focus on and what to ignore.”


4. Why Constraints Really Help

Without constraints, the AI has to guess at boundaries you may care about but never stated.

Example — No constraints

"Write a product description for these wireless earbuds."

How long should it be? Could it mention the price? Could it exaggerate features? Nothing here rules any of that in or out.

Example — With constraints

"Write a product description for these wireless earbuds. Keep it
under 60 words. Do not mention price. Do not make any claims about
battery life beyond what's listed here: [specs]."

Now the response has clear, checkable boundaries — really useful both for consistency and, in this case, for avoiding unsupported claims (Module 22 covers this connection to hallucination directly).


5. The Real Trade-off — Too Few vs. Too Many

This is the part that’s easy to get wrong in both directions.

Too few constraints leave real ambiguity unresolved — exactly the problem Module 3 demonstrated directly with an unspecified output format producing a nearly flat, unconfident guess at structure.

Too many constraints can backfire in a different way:

"Write a birthday message. Must be under 15 words. Must mention her
age. Must include a joke. Must be heartfelt. Must reference her love
of hiking. Must not use the word 'happy.' Must end with an exclamation
point. Must rhyme."

Eight separate rules for a single short message — some of these are likely in tension with each other (a joke, heartfelt, no “happy,” and rhyming, all in under 15 words, is a really hard needle to thread). Piling on constraints doesn’t guarantee better results; past a certain point, it can make the task harder to satisfy at all, or push the AI to silently drop or bend the constraint that seems least important to it.

💡 The pattern to notice: the right number of constraints is “however many resolve genuine ambiguity that actually matters for this task” — not “as many as possible, just in case.”

Analogy: The Speed Limit vs. The 25 Driving Rules Think of adding constraints to a prompt like telling a teenager how to drive a car:

  • Under-constrained (High Risk): You hand them the keys and say: “Drive to the store.” They might drive at 90 MPH, take the scenic route, or return with dented bumpers. You left too many boundaries open.
  • Optimal Constraints (Clear Safety): You tell them: “Drive to the store. Do not exceed 45 MPH. Use the highway. Do not text.” The rules are clear, checkable, and easy to satisfy simultaneously.
  • Over-constrained (Failure): You tell them: “Drive to the store. Keep speed at exactly 32.5 MPH. Use hazards every 5 seconds. Keep hands at exactly 10-and-2. Never blink for more than 0.3 seconds. Keep AC at 71 degrees. Play only Mozart.”
    • The driver gets overwhelmed, panics, and crashes because the brain cannot process 25 simultaneous rules.
  • In prompting, every constraint takes up attention capacity in the model blocks. Keep rules focused only on critical boundaries.

📊 Visual Chart: Constraint Density & Success Probability

Here is the success rate pattern based on rule volume:

graph TD
    classDef low fill:#f1c40f,stroke:#333,stroke-width:1px,color:#fff;
    classDef opt fill:#2ecc71,stroke:#333,stroke-width:1px,color:#fff;
    classDef high fill:#e74c3c,stroke:#333,stroke-width:1px,color:#fff;

    State1["1. Under-Constrained<br>(0-1 rules)"]:::low --> State1Out["Vague completions, high variance"]

    State2["2. Compute-Optimal Constraints<br>(2-4 rules)"]:::opt --> State2Out["Highly consistent, correct boundaries"]

    State3["3. Over-Constrained<br>(8+ rules)"]:::high --> State3Out["Rule conflicts, model ignores constraints, drop in accuracy"]

6. A Real Example From a Developer’s Perspective

Constraints are often what makes a prompt safe and reliable enough to actually ship in a product:

Before (too few constraints — real risk):
"Answer the customer's question about our refund policy."

After (constraints resolving real risk):
"Answer the customer's question using ONLY the refund policy text
provided below. Do not make up any details not present in the policy.
If the answer isn't in the policy, say so and offer to connect them
with a human agent. Keep the response under 100 words.

Refund policy:
[policy text]"

The “after” version adds constraints that directly prevent a real, costly failure mode: the AI confidently inventing refund policy details that don’t actually exist (Module 17 and Module 22 cover this kind of grounding constraint in much more depth).


7. A Simple Agentic AI Example

Constraints in agent instructions often double as genuine safety rails, not just style preferences:

"You are a billing agent. You may issue refunds up to $50 without
approval. For any refund above $50, do not process it — instead,
flag it for manager review. Never issue more than one refund per
customer per day without explicit manager approval."

These aren’t stylistic constraints — they’re operational boundaries that directly limit what actions the agent is allowed to take autonomously. This is exactly the kind of constraint that matters most in agentic systems, where “the AI just decided to do something” carries real consequences (Module 19 covers this in full).


8. How Is This Used in AI?

🤖 How Is This Used in AI?

Constraints are one of the most direct tools for making an AI feature production-safe — length limits control cost and UI fit, allowed-value constraints make output machine-parseable, and scope/content constraints prevent the AI from wandering into unsupported claims, off-topic responses, or unauthorized actions.


9. When Should You Use It?

  • There’s a real length, cost, or space limit the output must respect
  • The response needs to come from a specific, limited set of options (Module 8’s structured output often pairs with this)
  • There’s a genuine risk of the AI going off-topic, making unsupported claims, or (for agents) taking an action it shouldn’t

10. When Should You Be Careful?

  • Before adding a new constraint, ask whether it resolves real ambiguity, or is just a “might as well” addition
  • If you’re stacking many constraints, check whether any of them conflict (Module 6’s instruction-conflict lesson applies directly here)

11. Common Mistakes

Incorrect idea

Adding constraints “just in case,” without a real reason.

Why it is incorrect

Every added constraint adds length and a chance of conflict — Section 5 demonstrated directly how this can actively backfire.

Incorrect idea

Not noticing when constraints contradict each other.

Why it is incorrect

“Under 15 words” and “must rhyme, joke, and be heartfelt” is a real, genuine tension — exactly Module 6’s lesson about hidden conflicts, applied to constraints specifically.

Incorrect idea

Using vague constraints instead of precise ones.

Why it is incorrect

“Keep it short” is weaker than “under 50 words” — the second is checkable, the first is a matter of interpretation.

Incorrect idea

Forgetting that constraints can be safety-critical, not just stylistic

Why it is incorrect

, especially for agents — a missing constraint on agent actions (like the refund example) isn’t a minor quality issue, it’s a real operational risk.


12. Limitations

  • Constraints reduce ambiguity but don’t guarantee perfect compliance every time — an AI can still occasionally violate a stated limit, especially under a large pile of competing constraints
  • Constraints alone don’t resolve conflicts between themselves — you still have to notice and fix contradictions yourself (Module 6)
  • For really safety-critical boundaries (like the refund-approval example), a constraint stated in the prompt is a helpful first layer, but real production systems often add a second, code-level check behind it rather than relying on the prompt alone

13. Quick Reference — The Whole Idea in One Diagram

Too few constraints        -> real ambiguity left unresolved
                              (Module 3's flat-distribution problem)

Right amount                  -> genuine ambiguity resolved, task
                                still clearly achievable

Too many / conflicting            -> constraints compete with each
                                    other, task becomes hard or
                                    impossible to fully satisfy

14. Prompts in Code — Calling an LLM

Here’s how constraints actually look when calling an LLM through code — including a safety-critical example for an agent.

Example 1 — Simple

A single length constraint added directly to the prompt string.

import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=100,
    messages=[
        {"role": "user", "content": "Write a product description for "
                                     "wireless earbuds. Keep it under "
                                     "60 words."}
    ]
)
print(response.content[0].text)

Example 2 — Intermediate

Several constraints combined, including a grounding constraint that directly limits the AI to only the provided information — preventing the AI from inventing unsupported claims.

import anthropic

client = anthropic.Anthropic()

policy_text = "Refunds are available within 30 days of purchase with a receipt."

prompt = f"""Answer the customer's question using ONLY the refund
policy text below. Do not make up any details not present in the
policy. If the answer isn't in the policy, say so clearly. Keep the
response under 100 words.

Refund policy:
{policy_text}

Customer question: Can I get a refund after 45 days?"""

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=150,
    messages=[{"role": "user", "content": prompt}]
)
print(response.content[0].text)

Example 3 — Production Grade

A billing-agent function where the length/scope constraint lives in the prompt, but the safety-critical constraint (never auto-approve a refund over $50) is also enforced in code, not trusted to the prompt alone — exactly the Limitations point from Section 12.

import anthropic

client = anthropic.Anthropic()

AGENT_INSTRUCTIONS = (
    "You are a billing agent. You may recommend refunds up to $50. "
    "For any amount above $50, recommend flagging for manager review "
    "instead. Respond with a clear one-sentence recommendation."
)

def get_refund_recommendation(customer_request: str, amount: float) -> str:
    response = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=100,
        system=AGENT_INSTRUCTIONS,
        messages=[{"role": "user", "content":
                   f"Refund request: {customer_request} (Amount: ${amount})"}],
    )
    recommendation = response.content[0].text

    # SAFETY-CRITICAL CHECK -- enforced in code, not left to the prompt alone.
    if amount > 50:
        return f"[Requires manager approval] {recommendation}"
    return recommendation

result = get_refund_recommendation("Item arrived damaged", amount=75.00)
print(result)

Notice that even though the agent’s instructions already state the $50 rule, the code also checks amount > 50 independently — a real, defense-in-depth pattern for any constraint where getting it wrong has genuine consequences.


When to use it—and when not to

Use it when:

  • the output has clear boundaries.
  • business rules define allowed values.

Do not rely on it when:

  • constraints restate the same idea repeatedly.
  • money, access, or safety depends only on model obedience.

15. Interview Questions

Q: What is a constraint in the context of prompt design, and why does it help?

Ans: A constraint is a rule the AI’s response must follow — a limit on length, allowed values, scope, tone, or required/forbidden content. Constraints help by resolving specific kinds of ambiguity the instruction alone leaves open, giving the AI clear, checkable boundaries instead of leaving those decisions to guesswork.

Q: Why can adding too many constraints to a single prompt actually hurt output quality?

Ans: Constraints can conflict with each other, especially as more are piled on — for example, requiring a message to be simultaneously very short, funny, heartfelt, and rhyming creates real tension between those requirements. Past a certain point, additional constraints don’t resolve more ambiguity; they compete with each other, and the model has to implicitly decide which ones to prioritize, which can produce inconsistent or lower-quality results.

Q: Why might a production system enforce a critical constraint (like a refund approval limit) in code, in addition to stating it in the prompt?

Ans: Because a prompt constraint, however clearly stated, doesn’t guarantee the model will follow it with absolute certainty on every single request — for a constraint where a violation has real financial or operational consequences, relying on the prompt alone is a genuine risk. Enforcing the same rule independently in code provides a second, more reliable layer of protection — a defense-in-depth approach rather than trusting the prompt as the sole safeguard.

Q: How would you decide whether a given prompt needs more constraints, fewer constraints, or the right number as-is?

Ans: I’d check each existing or candidate constraint against a simple question: does this resolve genuine ambiguity that actually matters for this specific task? If a constraint doesn’t correspond to a real risk or real ambiguity, it’s likely unnecessary padding. I’d also check whether any of the constraints could conflict with each other — if satisfying one makes another harder or impossible to satisfy, that’s a sign there are too many, or that they need to be rephrased to resolve the tension explicitly (Module 6’s approach to conflicting instructions applies directly here).


16. What You Should Remember

  • Constraints — length, allowed values, scope, tone, required/forbidden content — narrow the space of acceptable answers, resolving specific kinds of ambiguity.
  • There’s a real trade-off: too few leaves ambiguity unresolved, too many can create conflicts and backfire — verified directly with an eight-constraint example that’s really hard to satisfy.
  • For safety-critical constraints (like agent action limits), a prompt constraint is a good first layer — but real systems often also enforce the same rule independently in code.

17. Quick Practice

Take this prompt: “Write a tweet about our new product launch.” Add 2-3 constraints that resolve genuine ambiguity (not just padding), and explain what specific ambiguity each one resolves.

18. Next Step

Next: Module 10 — Chain-of-Thought and Reasoning — how to help an AI handle multi-step problems more reliably, and what “reasoning” in an LLM actually means.

Author
TechByteByByte Editorial Team
Reviewed by
TechByteByByte Admin
Published
Last reviewed