Skip to main content
Constrained decoding is useful when using function/tool calling as it helps ensure the output is in the correct format and guarantees structured outputs.

Overview

ONNX Runtime GenAI integrates LLGuidance for constrained decoding, enabling you to control the format and structure of model outputs.

Constraint Types

There are three types of constrained decoding available:

Lark Grammar

Recommended - Allows both regular output and function/tool output in JSON format

JSON Schema

Output will match JSON schema and be one of the provided functions/tools

Regex

Match a specific regular expression pattern

Configuration

Tokenizer Modification

To ensure function/tool calling works correctly with constrained decoding, you need to modify your tokenizer.json file. For each model that has its own tool calling token, set the token’s special attribute to true.
Example: Phi-4 mini uses <|tool_call|> and <|/tool_call|> tokens, so you should set the special attribute for them as true inside tokenizer.json.
Lark grammar provides the most flexibility, allowing both regular and structured outputs.

Example: JSON Schema with Lark Grammar

Using JSON Schema

JSON schema constraints ensure outputs conform to a specific structure.

Using Regex Constraints

Regex constraints allow you to match specific patterns.

Function/Tool Calling

Constrained decoding is particularly useful for function and tool calling scenarios.

Best Practices

Lark grammar is recommended because it supports both regular text output and structured function/tool calls. This gives you maximum flexibility in your applications.
Always verify that tool calling tokens are marked as special in your tokenizer.json. This is critical for proper parsing of structured outputs.
Before deploying, test your JSON schemas thoroughly to ensure they capture all valid outputs and properly constrain invalid ones.
Implement error handling for cases where the model cannot satisfy the constraints. Consider fallback strategies.

Performance Considerations

Constrained decoding adds computational overhead to token generation. The complexity increases with:
  • More complex grammars
  • Larger JSON schemas
  • More intricate regex patterns
For optimal performance:
  • Keep schemas as simple as possible
  • Use specific constraints rather than overly broad ones
  • Test with your expected load to measure impact

Next Steps

Runtime Options

Configure additional runtime settings

Model Builder

Prepare models for constrained decoding

API Reference

Explore the Generator API

Examples

View code examples on GitHub