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 yourtokenizer.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.Using Lark Grammar (Recommended)
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
Use Lark Grammar for Flexibility
Use Lark Grammar for Flexibility
Lark grammar is recommended because it supports both regular text output and structured function/tool calls. This gives you maximum flexibility in your applications.
Validate Tokenizer Configuration
Validate Tokenizer Configuration
Always verify that tool calling tokens are marked as special in your
tokenizer.json. This is critical for proper parsing of structured outputs.Test Schema Validity
Test Schema Validity
Before deploying, test your JSON schemas thoroughly to ensure they capture all valid outputs and properly constrain invalid ones.
Handle Generation Errors
Handle Generation Errors
Implement error handling for cases where the model cannot satisfy the constraints. Consider fallback strategies.
Performance Considerations
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