AIEP
Security & TrustEmergingUpdated 2026-11

Closed-Vocabulary Output

Let the model pick from a fixed list of allowed values and drop anything outside it, so it cannot invent a category, a field or a number your system never defined.

Runnable example, tested in CISourceTestsJump to code
$cd examples && pytest security_and_trust/test_closed_vocabulary_output.py
structured-outputvalidationhallucinationschemasafety

What It Is

The model's output is limited to values you defined in advance: a set of allowed strings for each field, a numeric range for each number, and nothing else. Your code checks every field after the model answers. A value outside the set is dropped, not corrected. The name is ours; the building blocks (JSON Schema enums, structured-output modes) are standard.

The Problem It Solves

Free-form model output looks valid and isn't. Ask for a "month" and you can get "febuary", "late winter" or "any time". Ask for a category and you get one that your code has never heard of, which then falls through a switch, gets stored, and shows up in a filter menu. Asking the model to "only use these values" in the prompt works most of the time, which is the worst reliability level because it hides the failures until production.

How It Works

flowchart LR
    S["Spec: allowed values
and ranges per field"] --> P["Prompt lists the vocabulary"] S --> V P --> M["Model returns JSON"] M --> V{"Each field: exactly in
the set / in range?"} V -->|"yes"| K["Keep value"] V -->|"no"| D["Drop and record why
(never repair)"] M -->|"unknown key / not JSON"| D K & D --> R["Parsed values + dropped list"]
  1. Write the vocabulary down as data. For each field, list the allowed values (or a range). The same spec builds the prompt and does the validation, so they cannot drift apart.
  2. Ask once. Send the vocabulary in the prompt. If your provider supports schema-constrained decoding, turn it on too, but don't rely on it alone: not every provider enforces every schema feature, and a model swap can change what is enforced.
  3. Validate every field in code. Keep a value only if it is exactly in the set (or in range). Ignore keys that aren't in the spec.
  4. Drop, don't repair. "February" is close to "feb", and mapping it silently is how a typo becomes a wrong answer. If you want fuzzy matching, make it a separate, logged step with its own tests.
  5. Report what was dropped. An empty field is a normal result. Log the refusals: a rising drop rate for one field means the prompt or the vocabulary needs work.

When to Use It

  • The output feeds code: filters, routing, database fields, API parameters.
  • A wrong category is worse than a missing one.
  • The set of valid values is small enough to list, or can be listed from your data.

When NOT to Use It

  • The output is prose for a person. Use a Grounding Verifier or a Guardrail for that.
  • The vocabulary is open-ended and large. If you can't list the values, you can't close the set. Validate against a lookup (an ID that must exist) instead.
  • You need the model to surface new categories. Then you want discovery, not control. Collect what the model says separately and review it before it joins the vocabulary.

Trade-offs

  • Recall for safety. Dropping an unrecognised value loses information the model may have got right. That is the intended trade, but measure how often it happens.
  • The spec is now a thing you maintain. When the data adds a new category, the vocabulary has to change with it. Build the spec from the data where you can.
  • It constrains values, not truth. A model can pick a valid but wrong month. Validation proves membership, not correctness.

Failure Modes

The prompt and the validator disagree. The prompt lists one set and the code checks another, so valid answers are silently dropped. Generate both from one spec.

"Helpful" repair creeps back in. Someone adds a fuzzy match to reduce the drop rate, and a mis-mapped value now looks legitimate. Keep any repair separate, logged and tested against labelled examples.

Everything is optional, so everything is empty. If every field may be omitted and the model learns to omit them, you get a valid result that means nothing. Treat "no usable fields" as its own outcome and handle it explicitly (see Intent-Only Retrieval).

Implementation Example

A small spec language (one choice, several choices, a bounded number), one validation function, and one model call with no retry loop. The tests cover near-miss values that must be refused, booleans passed as numbers, unknown keys and non-JSON replies.

cd examples && pytest security_and_trust/test_closed_vocabulary_output.py
"""Closed-Vocabulary Output.
 
Let the model choose from a fixed set of values; never let it invent them. The
model's JSON is checked field by field against a spec of allowed values. A value
outside the spec is dropped (never "repaired" into something close), unknown
keys are ignored, and the result says what was dropped so callers can log it.
"""
 
from __future__ import annotations
 
import json
from collections.abc import Callable
from dataclasses import dataclass, field
 
 
@dataclass(frozen=True)
class Choice:
    """One value from a closed set."""
    allowed: frozenset[str]
 
 
@dataclass(frozen=True)
class Choices:
    """Zero or more values, each from a closed set."""
    allowed: frozenset[str]
    max_items: int = 5
 
 
@dataclass(frozen=True)
class Number:
    low: float
    high: float
 
 
Spec = dict[str, Choice | Choices | Number]
 
 
@dataclass
class Parsed:
    values: dict[str, object] = field(default_factory=dict)
    dropped: list[str] = field(default_factory=list)  # what we refused, and why
 
 
def parse(raw: str, spec: Spec) -> Parsed:
    out = Parsed()
    try:
        data = json.loads(raw)
    except (json.JSONDecodeError, TypeError):
        out.dropped.append("response is not valid JSON")
        return out
    if not isinstance(data, dict):
        out.dropped.append("response is not a JSON object")
        return out
 
    for key in data:
        if key not in spec:
            out.dropped.append(f"{key}: not in the spec")
 
    for key, rule in spec.items():
        if key not in data or data[key] is None:
            continue
        value = data[key]
        if isinstance(rule, Choice):
            if isinstance(value, str) and value in rule.allowed:
                out.values[key] = value
            else:
                out.dropped.append(f"{key}: {value!r} is not an allowed value")
        elif isinstance(rule, Choices):
            items = value if isinstance(value, list) else [value]
            kept = [v for v in items if isinstance(v, str) and v in rule.allowed]
            out.dropped += [f"{key}: {v!r} is not an allowed value" for v in items if v not in kept]
            if kept:
                out.values[key] = list(dict.fromkeys(kept))[: rule.max_items]
        elif isinstance(rule, Number):
            # bool is an int in Python; "true" is not a number of days.
            if isinstance(value, (int, float)) and not isinstance(value, bool) and rule.low <= value <= rule.high:
                out.values[key] = value
            else:
                out.dropped.append(f"{key}: {value!r} is outside {rule.low}..{rule.high}")
    return out
 
 
def ask(question: str, llm: Callable[[str], str], spec: Spec) -> Parsed:
    """One model call, one validation. No retry loop: a dropped field is a normal outcome."""
    vocabulary = "\n".join(
        f"- {k}: one of {sorted(r.allowed)}" if isinstance(r, Choice)
        else f"- {k}: any of {sorted(r.allowed)}" if isinstance(r, Choices)
        else f"- {k}: a number from {r.low} to {r.high}"
        for k, r in spec.items()
    )
    prompt = (
        "Answer with a JSON object using only these fields and values. Omit a field if the "
        f"question does not say.\n{vocabulary}\n\nQuestion: {question}"
    )
    return parse(llm(prompt), spec)

Tool Landscape

ToolNotes
Provider structured-output modes (OpenAI, Gemini, Anthropic)Constrain decoding to a JSON Schema; check which keywords each one enforces
JSON Schema validatorsValidate after the fact, whatever produced the output
Pydantic, ZodTyped models that double as the spec and the validator
Outlines, GuidanceGrammar-constrained generation for self-hosted models

Further Reading

Spotted something wrong or have a production story? Edit this page on GitHub.