Structured output forces a model's text to match a format. The format is compiled ahead of time into a deterministic automaton, and at each decode step the automaton's state determines which vocabulary tokens are legal. Implement the compiler for a small regex dialect and the per-state token masks.
Dialect. A pattern is one or more alternatives separated by |. Each alternative is a sequence of atoms: a literal character, an escaped character (\. means a literal dot), or a class [...] containing characters and ranges like a-z. An atom may be followed by one quantifier: *, + or ?. No groups, no ..
compile_regex(pattern)
{"n_states": int, "start": 0, "accepting": sorted list, "trans": {(state, char): state}}. States are numbered in order of discovery by a breadth-first walk from the start, trying characters in sorted order; only transitions to live states are stored (a missing entry means the input is rejected).token_masks(dfa, vocab)
vocab: a token is allowed if consuming all of its characters from that state stays within the automaton. Return the list of lists.advance(dfa, state, token)
None if any character is rejected.? and * and a self-loop for * and +; then convert with the subset construction over the set of characters that appear in the pattern.advance applied to every token; the masks are precomputed because the vocabulary is large and the step must be fast.