
Lesson 4: Enums and Constraints
Master the boundaries of data. Learn how to use 'enum', 'min/max', and 'pattern' constraints in JSON Schema to ensure Claude produces mathematically Precise outputs that never deviate from your business logic.
Module 8: Structured Output and Schema Design
Lesson 4: Enums and Constraints
The ultimate defense against hallucination is the Constraint. If you give Claude a blank text box, it will fill it with poetry. If you give Claude a drop-down menu, it will pick an option.
In this lesson, we master the enum and constraint keywords that turn "Probabilistic Words" into "Deterministic Tokens."
1. The Power of Enums
An enum provides a fixed list of valid strings.
"sentiment": {
"type": "string",
"enum": ["Positive", "Negative", "Neutral"]
}
Why Enums are "Magic":
When Claude generates tokens for an enum property, the model's internal probability for those specific words (Positive, Negative, Neutral) spikes to nearly 100%. Claude cannot output "Happy" or "Sad" if the enum is strictly defined.
Architect's Move: Use Enums for any categorical data (e.g., Status codes, Departments, priority levels).
2. Numeric Constraints: minimum and maximum
Don't just trust Claude to provide a "Realistic" number. Force it.
- Example:
"rating": { "type": "integer", "minimum": 1, "maximum": 5 }
3. String Constraints: minLength and maxLength
If you need a "Brief Summary," don't just say "Briefly."
- Action:
"summary": { "type": "string", "maxLength": 100 }
4. Pattern Recognition (RegEx)
The pattern keyword allows you to use Regular Expressions to validate strings. This is perfect for dates, IDs, or phone numbers.
"phone": {
"type": "string",
"pattern": "^\\d{3}-\\d{3}-\\d{4}$"
}
5. Visualizing the Constraint Engine
graph TD
A[Model Intelligence] --> B{Schema Filter}
B -->|Enum| C[Fixed Choice]
B -->|Range| D[Bounded Number]
B -->|Pattern| E[RegEx Format]
C --> F[100% Reliable Output]
D --> F
E --> F
6. Summary
- Enums are your strongest weapon against hallucination.
- Ranges prevent mathematical absurdities.
- Patterns (RegEx) enforce technical formats.
In the final lesson of this module, we look at how to verify these outputs: Validation Strategies.
Interactive Quiz
- Explain why an
enumreduces model hallucination. - What is the difference between
minimumandexclusiveMinimum? - How can you use the
patternkeyword to suggest a specific date format? - Setup an Enum for "Traffic_Light_State" with 3 valid options.
Reference Video: