Sub topic 7
Using Enums and Constraints to Rule Out Bad Arguments
This chapter assumes you can read JSON Schema types (string, integer, object, array), have called an LLM API with tools before, and can read short Python examples. It covers how to use enums and constraints in a tool's input schema so the model has fewer ways to send a bad argument.
Why constraints matter
A model fills in arguments by predicting text. It sees your schema and descriptions, but nothing forces it to obey them. A free-text status field will receive "Shipped", "shipped", "in transit", or "on its way" depending on the prompt. Each of those is a different string, and only one may match what your backend expects.
Constraints shrink the space of valid answers. Two things happen when you add them:
- The model sees the allowed values in the schema, so it is more likely to pick one of them.
- Your server gets a precise rule to check, so a bad value can be rejected with a clear message.
Constraints guide the model. They do not guarantee compliant output. Some providers enforce schemas during generation in a strict mode, and others treat the schema as a strong hint. Chapter 15 covers those differences. Until then, assume any argument can still be wrong, and check it on the server.
Enums: a closed list of choices
An enum lists every allowed value for a field. Use one when the set of values is small, fixed, and known to you.
{
"status": {
"type": "string",
"enum": ["pending", "shipped", "delivered", "cancelled"],
"description": "Only return orders with this status. Omit to include all statuses."
}
}The model now sees four options and nothing else. If the user says "orders that are on their way", the model can map that phrase to shipped. You have moved the translation work from your backend into the model, where natural language is easy to handle.
Good candidates for enums
- Status or state fields, such as
pendingandshipped. - Sort orders, such as
newestandoldest. - Output formats, such as
summaryandfull. - Categories your system defines, such as
billing,technical, andother.
Poor candidates for enums
- Values with thousands of options, such as country codes or product SKUs. The list costs context tokens and still invites mistakes. Use a string with a format hint, or a lookup tool.
- Values that change often. A stale enum rejects valid input.
- Free text the user supplies, such as names or search queries.
Enum values should be self-explanatory
The model reads the enum values as words. Prefer "shipped" over "S" or "3". If a value is not obvious, explain it in the parameter description.
{
"priority": {
"type": "string",
"enum": ["low", "normal", "urgent"],
"description": "Ticket priority. Use 'urgent' only when the customer cannot use the product at all. Defaults to 'normal' if omitted."
}
}Keep casing consistent. If one tool uses "shipped", do not use "Shipped" in another. Mixed casing makes the model less sure which form is correct.
Numeric and string constraints
JSON Schema has several keywords that narrow a value without listing every option.
| Keyword | Applies to | Effect |
|---|---|---|
| `enum` | any type | Value must be one of the listed values |
| `minimum`, `maximum` | integer, number | Inclusive numeric bounds |
| `minLength`, `maxLength` | string | Bounds on string length |
| `pattern` | string | Value must match a regular expression |
| `minItems`, `maxItems` | array | Bounds on array length |
| `items` | array | Schema for each element |
| `default` | any type | Value used when the parameter is omitted |
The search_orders tool from the chapter plan uses bounds on limit:
{
"limit": {
"type": "integer",
"minimum": 1,
"maximum": 50,
"description": "Maximum number of orders to return. Defaults to 10 if omitted."
}
}Bounds do two jobs. They stop the model from asking for 10,000 rows, and they act as a cost control, because a capped limit caps the size of the result that returns to the context window.
Arrays and nested enums
An array of enum values lets the model select several options at once:
{
"include_fields": {
"type": "array",
"items": {
"type": "string",
"enum": ["id", "status", "total", "created_at", "items"]
},
"minItems": 1,
"maxItems": 5,
"uniqueItems": true,
"description": "Fields to include in each returned order. Omit to return id, status, and total."
}
}Be aware that uniqueItems and some other keywords are not supported by every provider's strict mode. Test them on the provider you use.
Patterns for formatted strings
Use pattern when a string must follow a shape, such as an ID:
{
"order_id": {
"type": "string",
"pattern": "^ord_[0-9]+$",
"description": "Order ID, for example 'ord_1001'."
}
}Patterns are useful, but they have limits. Regular expression support varies between providers, and a model can misread a complex pattern. Keep patterns short. Always repeat the format in the description in plain words and with an example, because the description is what the model reads most closely.
For dates, a format keyword such as "format": "date" exists in JSON Schema, but providers handle it unevenly. The safer approach used in the plan's search_orders example is a plain string, with the format stated in the description: "in YYYY-MM-DD format."
Constraints the schema cannot express
Some rules do not fit in a schema. Examples:
created_beforemust be later thancreated_after.- A customer ID must belong to the current user.
- An order must be in a state that allows cancellation.
- Exactly one of two parameters must be provided.
For these, state the rule in the description and enforce it in your code. Do not rely on advanced keywords such as oneOf, anyOf, or if/then at the top level of the input schema. Support is inconsistent, and a model tends to handle two simple tools better than one complicated conditional schema. If a tool has a parameter that is only meaningful when another has a certain value, consider splitting it into two tools.
Enforcing constraints on the server
A schema is a promise you make to the model, not a guarantee about what arrives. Validate every call. The server check should return a message that says what was wrong and what to do next, so the model can retry.
VALID_STATUSES = {"pending", "shipped", "delivered", "cancelled"}
def search_orders(customer_id: str, status: str | None = None, limit: int = 10) -> dict:
if status is not None and status not in VALID_STATUSES:
return {
"is_error": True,
"message": (
f"Invalid status {status!r}. "
f"Allowed values: {', '.join(sorted(VALID_STATUSES))}. "
"Omit status to include all orders."
),
}
if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= 50:
return {
"is_error": True,
"message": f"Invalid limit {limit!r}. Use an integer from 1 to 50.",
}
return {"is_error": False, "orders": []}Three details matter here:
- The message lists the allowed values. The model can correct itself on the next turn without asking the user.
- The check for
boolis deliberate. In Python,Trueis an instance ofint, so a plainisinstancecheck letsTruethrough as a limit of 1. - The server does not silently clamp a limit of 500 down to 50. Silent changes hide the problem, and the model may tell the user it returned 500 results. Rejecting with a message keeps the model's picture of reality accurate.
Defaults and optional enums
When a parameter is optional, say what happens if it is omitted. "Omit to include all statuses" is better than leaving the model to guess. If you declare a default in the schema, also state it in the description, since some providers drop unrecognized keywords before the model sees them.
Avoid adding an "all" or "any" value to an enum just to mean "no filter". An optional parameter that can be omitted is simpler, and it removes a value the model might mix up with a real status.
Common mistakes
- Using an enum and a loose description that contradict each other. If the description mentions
"in_transit"but the enum lists"shipped", the model has to pick one. - Listing enum values in the description only. The model may still send other values, and nothing enforces the list.
- Setting bounds so wide they do nothing, such as a maximum of 1,000,000.
- Making
patternstrict enough to reject legitimate values, such as IDs with uppercase letters that exist in production. - Trusting the schema and skipping server validation.
How constraints fit the loop
The diagram shows where each layer acts on a tool call.
Summary
- Use an enum for small, fixed sets of values, with names the model can read as plain words.
- Use
minimum,maximum,maxItems, andmaxLengthto cap both bad input and result size. - Keep patterns short, and repeat each format in the description with an example.
- Express cross-field rules in the description and enforce them in code.
- Validate on the server, and return errors that list the allowed values.
Exercise
A tool has a parameter sort that is a plain string, and its description says "Sort order: newest or oldest". The model sometimes sends "latest" or "Newest". Rewrite the parameter schema to prevent this, and say what your server should do if it still receives "latest".
Show answer
Use an enum: {"type": "string", "enum": ["newest", "oldest"], "description": "Sort order by creation date. Defaults to 'newest' if omitted."}. If the server still receives "latest", it should not guess. It should return an error such as: "Invalid sort 'latest'. Allowed values: newest, oldest." so the model can retry with a valid value.
Exercise
A tool takes country, and your business serves 190 countries. Should you use an enum? What would you do instead?
Show answer
An enum of 190 values costs context tokens on every request and still allows mistakes. Use a string parameter that expects ISO 3166-1 alpha-2 codes, such as 'DE', state the format with an example in the description, and validate the value on the server against your list of supported codes, returning an error that names the expected format.
Exercise
Why does the Python validation in this chapter reject limit=500 instead of silently changing it to 50?
Show answer
Silent clamping hides the problem. The model would believe it received up to 500 results and might report that to the user, when only 50 were returned. Rejecting with a message keeps the model's understanding accurate and lets it retry with a valid value.