JsonSchemaConstraint
Helpers & Utilities ยท AiDotNet.Serving.StructuredOutput
Compiles a (subset of) JSON Schema to a regular expression and builds a RegexTokenConstraint
from it, so a model can be forced to emit JSON conforming to the schema. This is the mechanism behind the
OpenAI-compatible response_format: { type: "json_schema" } guided-decoding mode.
For Beginners
hand it a schema describing the JSON you want (which fields, what types) and it forces the model to fill in exactly that shape โ no missing fields, no wrong types, always parseable.
How It Works
The output is compact JSON (no insignificant whitespace) so the constraint is tight and
deterministic. Supported schema constructs: object with ordered properties (all treated as
required, emitted in declared order), scalar types string / integer / number /
boolean, string with enum or pattern, and array of a scalar
items type. A top-level enum restricts to a fixed set of JSON literals.
Methods
| Method | Summary |
|---|---|
RegexTokenConstraint AnyJsonObject(IReadOnlyList<string> tokenText, int eosTokenId, int maxDepth) |
Builds a token constraint that forces output to be any valid compact JSON value up to maxDepth nesting (the OpenAI json_object mode). |
RegexTokenConstraint FromSchema(string schemaJson, IReadOnlyList<string> tokenText, int eosTokenId) |
Builds a token constraint that forces output to match the given JSON Schema. |
string CompileToRegex(JToken schema) |
Compiles a JSON Schema token to a regex matching its compact JSON serialization. |