Skip to main content
This example demonstrates how to use constrained generation with ONNX Runtime GenAI to ensure outputs follow specific formats like JSON schemas.

Overview

The guidance example shows how to:
  • Define JSON schemas for output
  • Use Lark grammar for constrained generation
  • Ensure valid JSON output
  • Configure flexible whitespace handling
  • Measure generation performance

Complete Example

Key Concepts

JSON Schema Definition

Load or define a JSON schema to constrain the output:

Guidance Configuration

Configure schema guidance with formatting rules:

Validation

Verify the output is valid JSON:

Guidance Options

Whitespace Flexibility

  • whitespace_flexible: false: Strict whitespace control
  • whitespace_flexible: true: Allow flexible whitespace

Separators

  • key_separator: String between JSON keys and values (e.g., ": ")
  • item_separator: String between JSON items (e.g., ", ")

Feed-Forward Tokens

Enable fast-forward token generation for improved performance:

Usage Examples

Example Output

The example generates valid JSON matching the schema:
With performance metrics:

Lark Grammar Syntax

The example uses Lark grammar to define output structure:
  • start: %json {schema}: Define JSON output with schema
  • Custom grammar rules can be added for specific formats
  • Supports complex nested structures

Use Cases

  • API Response Generation: Ensure responses match OpenAPI schemas
  • Data Extraction: Extract structured data in specific formats
  • Code Generation: Generate code following syntax rules
  • Form Validation: Create outputs matching form schemas

Command-Line Arguments

Next Steps